blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
dfc81a68ef4381eeb2025904b710803be0bc30c3
93176e72508a8b04769ee55bece71095d814ec38
/Utilities/otbliblas/include/liblas/external/property_tree/ini_parser.hpp
e5c210caafdba9882a0007c695855c4cfcde4532
[ "MIT", "BSL-1.0" ]
permissive
inglada/OTB
a0171a19be1428c0f3654c48fe5c35442934cf13
8b6d8a7df9d54c2b13189e00ba8fcb070e78e916
refs/heads/master
2021-01-19T09:23:47.919676
2011-06-29T17:29:21
2011-06-29T17:29:21
1,982,100
4
5
null
null
null
null
UTF-8
C++
false
false
12,328
hpp
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // Copyright (C) 2009 Sebastian Redl // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_INI_PARSER_HPP_INCLUDED #define BOOST_PROPERTY_TREE_INI_PARSER_HPP_INCLUDED #include <liblas/external/property_tree/ptree.hpp> #include <liblas/external/property_tree/detail/ptree_utils.hpp> #include <liblas/external/property_tree/detail/file_parser_error.hpp> #include <fstream> #include <string> #include <sstream> #include <stdexcept> #include <locale> namespace liblas { namespace property_tree { namespace ini_parser { /** * Determines whether the @c flags are valid for use with the ini_parser. * @param flags value to check for validity as flags to ini_parser. * @return true if the flags are valid, false otherwise. */ inline bool validate_flags(int flags) { return flags == 0; } /** Indicates an error parsing INI formatted data. */ class ini_parser_error: public file_parser_error { public: /** * Construct an @c ini_parser_error * @param message Message describing the parser error. * @param filename The name of the file being parsed containing the * error. * @param line The line in the given file where an error was * encountered. */ ini_parser_error(const std::string &message, const std::string &filename, unsigned long line) : file_parser_error(message, filename, line) { } }; /** * Read INI from a the given stream and translate it to a property tree. * @note Clears existing contents of property tree. In case of error * the property tree is not modified. * @throw ini_parser_error If a format violation is found. * @param stream Stream from which to read in the property tree. * @param[out] pt The property tree to populate. */ template<class Ptree> void read_ini(std::basic_istream< typename Ptree::key_type::value_type> &stream, Ptree &pt) { typedef typename Ptree::key_type::value_type Ch; typedef std::basic_string<Ch> Str; const Ch semicolon = stream.widen(';'); const Ch lbracket = stream.widen('['); const Ch rbracket = stream.widen(']'); Ptree local; unsigned long line_no = 0; Ptree *section = 0; Str line; // For all lines while (stream.good()) { // Get line from stream ++line_no; std::getline(stream, line); if (!stream.good() && !stream.eof()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "read error", "", line_no)); // If line is non-empty line = property_tree::detail::trim(line, stream.getloc()); if (!line.empty()) { // Comment, section or key? if (line[0] == semicolon) { // Ignore comments } else if (line[0] == lbracket) { // If the previous section was empty, drop it again. if (section && section->empty()) local.pop_back(); typename Str::size_type end = line.find(rbracket); if (end == Str::npos) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "unmatched '['", "", line_no)); Str key = property_tree::detail::trim( line.substr(1, end - 1), stream.getloc()); if (local.find(key) != local.not_found()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate section name", "", line_no)); section = &local.push_back( std::make_pair(key, Ptree()))->second; } else { Ptree &container = section ? *section : local; typename Str::size_type eqpos = line.find(Ch('=')); if (eqpos == Str::npos) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "'=' character not found in line", "", line_no)); if (eqpos == 0) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "key expected", "", line_no)); Str key = property_tree::detail::trim( line.substr(0, eqpos), stream.getloc()); Str data = property_tree::detail::trim( line.substr(eqpos + 1, Str::npos), stream.getloc()); if (container.find(key) != container.not_found()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate key name", "", line_no)); container.push_back(std::make_pair(key, Ptree(data))); } } } // If the last section was empty, drop it again. if (section && section->empty()) local.pop_back(); // Swap local ptree with result ptree pt.swap(local); } /** * Read INI from a the given file and translate it to a property tree. * @note Clears existing contents of property tree. In case of error the * property tree unmodified. * @throw ini_parser_error In case of error deserializing the property tree. * @param filename Name of file from which to read in the property tree. * @param[out] pt The property tree to populate. * @param loc The locale to use when reading in the file contents. */ template<class Ptree> void read_ini(const std::string &filename, Ptree &pt, const std::locale &loc = std::locale()) { std::basic_ifstream<typename Ptree::key_type::value_type> stream(filename.c_str()); if (!stream) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "cannot open file", filename, 0)); stream.imbue(loc); try { read_ini(stream, pt); } catch (ini_parser_error &e) { BOOST_PROPERTY_TREE_THROW(ini_parser_error( e.message(), filename, e.line())); } } namespace detail { template<class Ptree> void check_dupes(const Ptree &pt) { if(pt.size() <= 1) return; const typename Ptree::key_type *lastkey = 0; typename Ptree::const_assoc_iterator it = pt.ordered_begin(), end = pt.not_found(); lastkey = &it->first; for(++it; it != end; ++it) { if(*lastkey == it->first) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate key", "", 0)); lastkey = &it->first; } } } /** * Translates the property tree to INI and writes it the given output * stream. * @pre @e pt cannot have data in its root. * @pre @e pt cannot have keys both data and children. * @pre @e pt cannot be deeper than two levels. * @pre There cannot be duplicate keys on any given level of @e pt. * @throw ini_parser_error In case of error translating the property tree to * INI or writing to the output stream. * @param stream The stream to which to write the INI representation of the * property tree. * @param pt The property tree to tranlsate to INI and output. * @param flags The flags to use when writing the INI file. * No flags are currently supported. */ template<class Ptree> void write_ini(std::basic_ostream< typename Ptree::key_type::value_type > &stream, const Ptree &pt, int flags = 0) { using detail::check_dupes; typedef typename Ptree::key_type::value_type Ch; typedef std::basic_string<Ch> Str; BOOST_ASSERT(validate_flags(flags)); (void)flags; if (!pt.data().empty()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "ptree has data on root", "", 0)); check_dupes(pt); for (typename Ptree::const_iterator it = pt.begin(), end = pt.end(); it != end; ++it) { check_dupes(it->second); if (it->second.empty()) { stream << it->first << Ch('=') << it->second.template get_value< std::basic_string<Ch> >() << Ch('\n'); } else { if (!it->second.data().empty()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "mixed data and children", "", 0)); stream << Ch('[') << it->first << Ch(']') << Ch('\n'); for (typename Ptree::const_iterator it2 = it->second.begin(), end2 = it->second.end(); it2 != end2; ++it2) { if (!it2->second.empty()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "ptree is too deep", "", 0)); stream << it2->first << Ch('=') << it2->second.template get_value< std::basic_string<Ch> >() << Ch('\n'); } } } } /** * Translates the property tree to INI and writes it the given file. * @pre @e pt cannot have data in its root. * @pre @e pt cannot have keys both data and children. * @pre @e pt cannot be deeper than two levels. * @pre There cannot be duplicate keys on any given level of @e pt. * @throw info_parser_error In case of error translating the property tree * to INI or writing to the file. * @param filename The name of the file to which to write the INI * representation of the property tree. * @param pt The property tree to tranlsate to INI and output. * @param flags The flags to use when writing the INI file. * The following flags are supported: * @li @c skip_ini_validity_check -- Skip check if ptree is a valid ini. The * validity check covers the preconditions but takes <tt>O(n log n)</tt> * time. * @param loc The locale to use when writing the file. */ template<class Ptree> void write_ini(const std::string &filename, const Ptree &pt, int flags = 0, const std::locale &loc = std::locale()) { std::basic_ofstream<typename Ptree::key_type::value_type> stream(filename.c_str()); if (!stream) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "cannot open file", filename, 0)); stream.imbue(loc); try { write_ini(stream, pt, flags); } catch (ini_parser_error &e) { BOOST_PROPERTY_TREE_THROW(ini_parser_error( e.message(), filename, e.line())); } } } } } namespace liblas { namespace property_tree { using ini_parser::ini_parser_error; using ini_parser::read_ini; using ini_parser::write_ini; } } #endif
[ [ [ 1, 309 ] ] ]
31aa996e3be9093e47eba9c961d48166b3066bd3
6ad58793dd1f859c10d18356c731b54f935c5e9e
/MYUltilityClass/TextViewPad.h
4063ee550d075d4ce8852b5fdbc67305e73027d9
[]
no_license
ntchris/kittybookportable
83f2cf2fbc2cd1243b585f85fb6bc5dd285aa227
933a5b096524c24390c32c654ce8624ee35d3835
refs/heads/master
2021-01-10T05:49:32.035999
2009-06-12T08:50:21
2009-06-12T08:50:21
45,051,534
0
0
null
null
null
null
GB18030
C++
false
false
7,019
h
#ifndef __TextViewPad__ #define __TextViewPad__ //#include <stdio.h> #include <CommonString.h> #include <PSP_Window.h> #include <WinComponent.h> #include <ConfigWindow.h> #include <stdio.h> //Store the lineHead char index for each line ( lines in PSP screen) class LineHeadStore { const static unsigned long maxSize = 1024*1024*1; unsigned long size; unsigned long *lineHead_ap; public: bool add( unsigned long lineHeadPosition ); void clear( void ); //get position from line number unsigned long get( unsigned long index); //get position of the last line number unsigned long get( void ); unsigned long LineHeadStore::getLineNumber( unsigned long position ) ; inline unsigned long getSize( void ) { return size; }; LineHeadStore(); ~LineHeadStore(); }; //==================================================================================================== class BookMarkStruct { public: bool hasData; unsigned long position; //including path char filename[ pathMaxLen ]; BookMarkStruct () { hasData = false; memset( filename, 0, pathMaxLen ); position = 0; } } ; //==================================================================================================== // BookMarkHandler class handler 10 bookmark for different books; // a bookmark means : a book file name + position. class BookMarkHandler { public: static const unsigned short maxBookMarkCount = 5 ; private: static BookMarkStruct allBookMark[ maxBookMarkCount ]; static const char bookMarkFileName[]; BookMarkHandler( ); ~BookMarkHandler( ); static bool sanityCheckingAndCreateNewBookMarkFile ( void ) ; public: static BookMarkStruct currentBookMark; // index means the position of the bm file, total is 5 static bool save ( int index ); static bool load ( int index ); static bool load ( void ); //static BookMarkStruct * getBookMarkInfo ( void ); static bool getBookMarkValid( int index ); }; //==================================================================================================== class BookMarkWindow : public PSP_Window { ushortBitMap wholeScreenBMP; Button *btn_save_a [ BookMarkHandler::maxBookMarkCount ]; Button *btn_load_a [ BookMarkHandler::maxBookMarkCount ]; // Label * label_save, *label_load ; void addComopnents ( void ); BookMarkWindow ( ); ~BookMarkWindow ( ); void drawAllItems( void ); void restoreWindow( void ); public: const static int doneReturn = 0, saveActionDone = 1, loadActionDone = 2; //return the index static int show( void ); }; //========================================================================= // to do : support unicode text file class TextViewPad :public PSP_Window { enum TextFileType { normalText, unicodeText, unicodeBigEndText } ; //read 512 KB one time. // 4MB 可以 6MB 可以. //这是unicode 的size, 就是说, asc text最大只有一般 即3MB. static const unsigned long maxFileLoadLengthOneTime = 1024 * 1024 * 6 ; //static const unsigned long maxFileBufferUnicodeLength = maxFileLoadLengthOneTime; static unsigned long bookMarkLine; unsigned short *unicodeBuffer;//[ maxFileLoadLengthOneTime ]; unsigned long loadedBufferSize ; unsigned long fileSize; unsigned char ascFontSize ; unsigned short fontSize ; // unsigned char onePressLineMoveStep ; //bool inited ; char filename[ pathMaxLen]; void showFile ( unsigned long lineNumber = 0 ); // next page bool addLineHeadIndex ( unsigned long headIndex ); //PSPArray lineHeadIndex_array ; LineHeadStore *lineHeadStorep; unsigned long totalPagesCount ; void showAllLineHead ( void ); void initTextViewPad( void ); void printOneLineTTFString( const char * ); bool loadTextFile( const char *filename , unsigned long fromPosition = 0 ); void getAllLineHead( void ); static const int quitTextView = 0, loadBookMark = 1; int readFileFromBuffer ( void ); void countTotalPages( void ); TextFileType getTextFileUnicodeType( const unsigned char * textBuffer ); void convertUnicodeToBigEnd ( const unsigned char *unicode, const unsigned char *unicodeBigEnd ); /* unsigned long printTTFHanZiUnicodeString ( unsigned short winx, unsigned short winy, unsigned short color, const unsigned short *unicodeStr, unsigned long size ) ; */ void loadFontFile( void ); void applyBookMarkLine( void ); unsigned long countOneLineHanZiUnicodeString ( const unsigned short *unicodeStr, unsigned long size ) ; unsigned long printTTFHanZiUnicodeString ( unsigned short winx, unsigned short winy, unsigned short color, const unsigned short *unicodeStr, unsigned long size ) ; unsigned long printUnicodeAscHanZi16String ( unsigned short winx, unsigned short winy, unsigned short color, const unsigned short *unicodeString , unsigned long bufferSize ) ; //const static int cancel = 0; int handleBookMarkWin( void ) ; ScrollBar *textViewScrollBar; //unsigned long onePageLinesCount; void showInfo( void ); unsigned long countLinesDown( unsigned long currentLineNumber,unsigned long step, unsigned long totalLine ); unsigned long countLinesUp( unsigned long currentLineNumber, unsigned long step ); unsigned short countEnglishWordWidth( const unsigned short *uniStr, unsigned short wordAscCount ); static const unsigned short TextViewPadWinYStart = 0; unsigned short maxLineOnePage ; unsigned short stepPage ; public: //How about super big file ?? static TextViewPadConfig config; //simplely read one and ONLY one file, not bookmark static void readOneFile ( const char *fileName ); static void readMoreFileFromFileMgr ( const char *fileName ); static void readMoreFileFromBookMark ( void ) ; void loadConfig( void ); void applyConfig( void ); TextViewPad (); TextViewPad ( const Rectangle &rec ); ~TextViewPad (); static void selfTestLineHead( void ); static void selfTestPrintTextFileTextMode ( void ); static void selfTestConfig ( void ); static void selfTestBookMark( void ); }; #endif //__TextViewPad__
[ "ntchris0623@05aa5984-5704-11de-9010-b74abb91d602" ]
[ [ [ 1, 252 ] ] ]
a8ca1f48b802d57ccd00dfd6c56b677c9ab19eaa
4506e6ceb97714292c3250023b634c3a07b73d5b
/rpg2kdevSDK/SDK/CRpgLsd.h
9296dcf37982cd00fc058671132593728ea34d98
[]
no_license
take-cheeze/rpgtukuru-iphone
76f23ddfe015018c9ae44b5e887cf837eb061bdf
3447dbfab84ed1f17e46e9d6936c28b766dadd36
refs/heads/master
2016-09-05T10:47:30.461471
2011-11-01T09:45:19
2011-11-01T09:45:19
1,151,984
2
1
null
null
null
null
UTF-8
C++
false
false
2,139
h
/** @file @brief Save??.lsd(LcfSaveData)を管理するクラス @author sue445 */ #ifndef _INC_CRPGLSD #define _INC_CRPGLSD #include <string> #include <vector> // #include <kuto/kuto_types.h> #include "CRpgIOBase.h" /// Save??.lsd(LcfSaveData)を管理するクラス class CRpgLsd : public CRpgIOBase { public: enum { MAX_SAVEDATA = 15, ///< セーブデータの最大番号 }; struct DataSelectInfo { uint64_t time; ///< 0x01 タイムスタンプ std::string leaderName; ///< 0x0B 先頭のキャラの名前 int leaderLevel; ///< 0x0C 先頭のキャラのLv int leaderHP; ///< 0x0D 先頭のキャラのHP std::string partyImage[4]; ///< 0x15 1人目顔絵ファイル int partyImageNo[4]; ///< 0x16 1人目顔絵番号 }; struct SystemInfo { std::string systemTexture; ///< 0x15 システムグラフィック std::vector<bool> switches; ///< 0x20 スイッチ std::vector<int> vars; ///< 0x22 変数 bool enableTeleport; ///< 0x51 テレポート可能か bool enableEscape; ///< 0x52 エスケープ可能か bool enableSave; ///< 0x53 セーブ可能か bool enableMenu; ///< 0x54 メニューの呼び出し可能か std::string battleMap; ///< 0x55 戦闘背景 int saveNum; ///< 0x59 セーブ回数 }; struct Location { int mapId; ///< 0x0B マップ番号 int x; ///< 0x0C X座標 int y; ///< 0x0D Y座標 }; private: const char* GetHeader(){ return "LcfSaveData"; } ///< ファイルごとの固有ヘッダ(CRpgIOBaseからオーバーライドして使います) void analyzeDataSelectInfo(sueLib::smart_buffer& buf); void analyzeSystemInfo(sueLib::smart_buffer& buf); void analyzeLocation(sueLib::smart_buffer& buf); public: DataSelectInfo dataSelectInfo_; SystemInfo systemInfo_; Location location_; public: CRpgLsd(){} ///< コンストラクタ ~CRpgLsd(){} ///< デストラクタ bool Init(int nSaveNum, const char* szDir=""); ///< 初期化 void Save(int nSaveNum, const char* szDir=""); ///< Save to file }; #endif
[ "project.kuto@07b74652-1305-11df-902e-ef6c94960d2c", "takechi101010@07b74652-1305-11df-902e-ef6c94960d2c" ]
[ [ [ 1, 10 ], [ 12, 24 ], [ 26, 70 ] ], [ [ 11, 11 ], [ 25, 25 ] ] ]
c19350f3d271c159c9eb23bc900ed5be542fd6e5
9e79b20463b122df1d83a1e394f54689a949fb4e
/examples/DACI2C/MultiDAC.cpp
ede4ad5eef3ad15b03b2989a482283ebcb4b9961
[]
no_license
michaelvandam/mojoduino
4870c522b7be77a33cb19d1a6448dbee9ca9c148
57233cadde626b5b9a7accf941d78470ebe17000
refs/heads/master
2021-01-02T22:51:23.392713
2010-10-23T01:45:30
2010-10-23T01:45:30
32,952,233
0
0
null
null
null
null
UTF-8
C++
false
false
966
cpp
#include "wiring.h" #include "MultiDAC.h" #include "Wire.h" MultiDAC::MultiDAC(){ MultiDAC::setAddress(0); init(); } MultiDAC::MultiDAC(char addr){ MultiDAC::setAddress(addr); init(); } void MultiDAC::setAddress(char addr){ address = addr; } char MultiDAC::getAddress(){ return address; } void MultiDAC::init(){ for(char x=0;x<MAX_OUT;x++){ outputs[x]= Output(x,address); } } Output::Output(){ } Output::Output(char addr, char dacaddress){ setPinAddress(addr); DACaddress = dacaddress; } void Output::setPinAddress(char addr){ pinaddress = addr; } char Output::getAddress(){ return pinaddress; } void Output::setValue(unsigned int value){ int highbyte = value>>8; int lowbyte = value; Wire.beginTransmission(DACaddress); Wire.send((WRITE_PWR<<4) | (pinaddress)); //00020000 Wire.send(highbyte); Wire.send(lowbyte); Wire.endTransmission(); }
[ "inomod@2cfd8b6e-c46e-11de-b12b-e93134c88cf6" ]
[ [ [ 1, 57 ] ] ]
b32b2ae4ec1821928af7c6942bbc19e6a2f7db18
b369aabb8792359175aedfa50e949848ece03180
/src/wblib/wblib/FreeFlightCamera.cpp
aa5ed0b249dca216433f72e99440d975ea2dda14
[]
no_license
LibreGamesArchive/magiccarpet
6d49246817ab913f693f172fcfc53bf4cc153842
39210d57096d5c412de0f33289fbd4d08c20899b
refs/heads/master
2021-05-08T02:00:46.182694
2009-01-06T20:25:36
2009-01-06T20:25:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
#include "FreeFlightCamera.h" wbLib::FreeFlightCamera::FreeFlightCamera(float _x, float _y, float _z) : Camera(_x, _y, _z) { } /** * Moves the camera forward * * FreeFlight means, the camera moves along it's view direction */ void wbLib::FreeFlightCamera::MoveForward() { wbLib::Vector3f temp = this->view; temp.Normalize(); temp.ScalarMult(this->moveSpeed); // By moving in the view direction, this camera // behaves like free flight this->pos += temp; } /** * Moves the camera back * * FreeFlight means, the camera moves along it�s view direction */ void wbLib::FreeFlightCamera::MoveBackward() { wbLib::Vector3f temp = this->view; temp.Normalize(); temp.ScalarMult(this->moveSpeed); // By moving in the view direction, this camera // behaves like free flight this->pos -= temp; }
[ [ [ 1, 32 ] ] ]
e9359c944802e0eb9928513ffd6f713f32babf0d
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/math/random/sobol.hpp
5a48d619ccf82f85c137ab6e635b8c4c6cd090f7
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,973
hpp
/******************************************************************************** * qmlib/math/rndgen.hpp * * Copyright (C) 2007-2008 Luca Sbardella <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * 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. * * Suggestions: [email protected] * Bugs: [email protected] * * For more information, please see the quantmind Home Page: * http://www.quantmind.com * *******************************************************************************/ /// \file /// \ingroup random /// /// \brief SOBOL Low-Discrepancy sequence generator /// /// - A Gray code counter and bitwise operations are used for very /// fast sequence generation. /// /// - The implementation relies on primitive polynomials modulo two /// from the book "Monte Carlo Methods in Finance" by Peter Jackel. /// /// - 21,200 primitive polynomials modulo two are provided by /// default in qmlib. Jackel has calculated 8,129,334 /// polynomials, also available in a different file that can be /// downloaded from http://quantlib.org. If you need that many /// dimensions you must replace the default version of the /// primitivepolynomials.c file with the extended one. /// /// - The choice of initialization numbers (also know as free direction /// integers) is crucial for the homogeneity properties of the sequence. /// Sobol defines two homogeneity properties: Property A and Property A'. /// /// The unit initialization numbers suggested in "Numerical /// Recipes in C", 2nd edition, by Press, Teukolsky, Vetterling, /// and Flannery (section 7.7) fail the test for Property A even /// for low dimensions. /// /// Bratley and Fox published coefficients of the free direction /// integers up to dimension 40, crediting unpublished work of /// Sobol' and Levitan. See Bratley, P., Fox, B.L. (1988) /// "Algorithm 659: Implementing Sobol's quasirandom sequence /// generator," ACM Transactions on Mathematical Software /// 14:88-100. These values satisfy Property A for d<=20 and d = /// 23, 31, 33, 34, 37; Property A' holds for d<=6. /// /// Jackel provides in his book (section 8.3) initialization /// numbers up to dimension 32. Coefficients for d<=8 are the same /// as in Bradley-Fox, so Property A' holds for d<=6 but Property /// A holds for d<=32. /// /// The implementation of Lemieux, Cieslak, and Luttmer includes /// coefficients of the free direction integers up to dimension /// 360. Coefficients for d<=40 are the same as in Bradley-Fox. /// For dimension 40<d<=360 the coefficients have /// been calculated as optimal values based on the "resolution" /// criterion. See "RandQMC user's guide - A package for /// randomized quasi-Monte Carlo methods in C," by C. Lemieux, /// M. Cieslak, and K. Luttmer, version January 13 2004, and /// references cited there /// (http://www.math.ucalgary.ca/~lemieux/randqmc.html). /// The values up to d<=360 has been provided to the QuantLib team by /// Christiane Lemieux, private communication, September 2004. /// /// For more info on Sobol' sequences see also "Monte Carlo /// Methods in Financial Engineering," by P. Glasserman, 2004, /// Springer, section 5.2.3 /// /// \test /// - the correctness of the returned values is tested by /// reproducing known good values. /// - the correctness of the returned values is tested by checking /// their discrepancy against known good values. #ifndef __SOBOL_QM_HPP__ #define __SOBOL_QM_HPP__ #include <qmlib/math/random/rndgen.hpp> QM_NAMESPACE2(math) /// \brief The Heston Low-discrepancy Number generator /// \ingroup random /// \note /// Adapted form the book "Monte Carlo Methods in Finance" by Peter Jackel. class HaltonGenerator : public lowDiscrepacySequenceGenerator { public: HaltonGenerator(qm_Size dim, qm_Size seed); protected: void nextSequence() const; }; //static const qm_int SOBOL_BITS = 8*sizeof(qm_uns_long); //static const qm_real SOBOL_NFACT = 0.5/(1UL<<(SOBOL_BITS-1)); /// \brief The Sobol Low-discrepancy Number generator /// \ingroup random /// \note /// Adapted form the book "Monte Carlo Methods in Finance" by Peter Jackel. /// /// The template argument defined the free direction of integers. /// - D = 0 Unit initialization ("Numerical Recipes in C", 2nd edition) /// - D = 1 Jaeckel /// - D = 2 SobolLevitan /// - D = 3 SobolLevitanLemieux template<int D = 1> class SobolGenerator : public lowDiscrepacySequenceGenerator { public: typedef std::vector<qm_uns_long> integers; typedef std::vector<integers> vector_integers; // pre dimensionality must be <= PPMT_MAX_DIM SobolGenerator(qm_Size dim, qm_Size seed); protected: void nextSequence() const; qm_real uniform(qm_uns_long n) const {return n * c_normalizationFactor;} private: static const qm_int c_bits; //static const qm_int SOBOL_BITS = 8*sizeof(qm_uns_long); static const qm_real c_normalizationFactor; //static const qm_real SOBOL_NFACT = 0.5/(1UL<<(SOBOL_BITS-1)); // vector_integers m_directionIntegers; mutable integers m_lastsequence; }; QM_NAMESPACE_END2 #endif // __SOBOL_QM_HPP__
[ [ [ 1, 156 ] ] ]
be22731e7e19a016f6444d391b51e551bb5e971e
978a06157ab6a5edebab278eb0e58c942d145e75
/libzpaqo.cpp
18ecf58b4dab3c6981f89cda3de23d5849cac8bd
[]
no_license
windreamer/zpaq
8a32f9ae0190b308060a9685dd8bf1cc556f6316
4ccd4a75c4892c14694448a973f298dcd37ea490
refs/heads/master
2016-08-03T14:39:51.951949
2011-01-26T09:19:14
2011-01-26T09:19:14
1,297,712
1
0
null
null
null
null
UTF-8
C++
false
false
25,589
cpp
/* libzpaqo.cpp Part of LIBZPAQ Version 2.02 See accompanying libzpaq.txt for documentation. Written by Matt Mahoney, Nov. 13, 2010 The LIBZPAQ software is placed in the public domain. It may be used without restriction. LIBZPAQ is provided "as is" with no warranty. This file contains optimized versions of models[], ZPAQL::run(), Predictor::predict() and Predictor::update() for fast.cfg, mid.cfg, and max.cfg. It was generated using zpaq 2.02 as follows: zpaq cfast x nul: zpaq amid x nul: zpaq amax x nul: zpaq kox x rename zpaqopt.cpp libzpaqo.cpp followed by inserting this comment and removing the declaration for zpaqdir at the end. */ #include "libzpaq.h" namespace libzpaq { const char models[]={ // Model 1 26,0,1,2,0,0,2,3,16,8,19,0,0,96,4,28, 59,10,59,112,25,10,59,10,59,112,56,0, // Model 2 69,0,3,3,0,0,8,3,5,8,13,0,8,17,1,8, 18,2,8,18,3,8,19,4,4,22,24,7,16,0,7,24, -1,0,17,104,74,4,95,1,59,112,10,25,59,112,10,25, 59,112,10,25,59,112,10,25,59,112,10,25,59,10,59,112, 25,69,-49,8,112,56,0, // Model 3 -60,0,5,9,0,0,22,1,-96,3,5,8,13,1,8,16, 2,8,18,3,8,19,4,8,19,5,8,20,6,4,22,24, 3,17,8,19,9,3,13,3,13,3,13,3,14,7,16,0, 15,24,-1,7,8,0,16,10,-1,6,0,15,16,24,0,9, 8,17,32,-1,6,8,17,18,16,-1,9,16,19,32,-1,6, 0,19,20,16,0,0,17,104,74,4,95,2,59,112,10,25, 59,112,10,25,59,112,10,25,59,112,10,25,59,112,10,25, 59,10,59,112,10,25,59,112,10,25,69,-73,32,-17,64,47, 14,-25,91,47,10,25,60,26,48,-122,-105,20,112,63,9,70, -33,0,39,3,25,112,26,52,25,25,74,10,4,59,112,25, 10,4,59,112,25,10,4,59,112,25,65,-113,-44,72,4,59, 112,8,-113,-40,8,68,-81,60,60,25,69,-49,9,112,25,25, 25,25,25,112,56,0, 0,0}; int Predictor::predict() { switch(z.select) { case 1: { // 2 components // 0 ICM 16 if (c8==1 || (c8&0xf0)==16) comp[0].c=find(comp[0].ht, 16+2, z.H(0)+16*c8); comp[0].cxt=comp[0].ht[comp[0].c+(hmap4&15)]; p[0]=stretch(comp[0].cm(comp[0].cxt)>>8); // 1 ISSE 19 0 { if (c8==1 || (c8&0xf0)==16) comp[1].c=find(comp[1].ht, 21, z.H(1)+16*c8); comp[1].cxt=comp[1].ht[comp[1].c+(hmap4&15)]; int *wt=(int*)&comp[1].cm[comp[1].cxt*2]; p[1]=clamp2k((wt[0]*p[0]+wt[1]*64)>>16); } return squash(p[1]); } case 2: { // 8 components // 0 ICM 5 if (c8==1 || (c8&0xf0)==16) comp[0].c=find(comp[0].ht, 5+2, z.H(0)+16*c8); comp[0].cxt=comp[0].ht[comp[0].c+(hmap4&15)]; p[0]=stretch(comp[0].cm(comp[0].cxt)>>8); // 1 ISSE 13 0 { if (c8==1 || (c8&0xf0)==16) comp[1].c=find(comp[1].ht, 15, z.H(1)+16*c8); comp[1].cxt=comp[1].ht[comp[1].c+(hmap4&15)]; int *wt=(int*)&comp[1].cm[comp[1].cxt*2]; p[1]=clamp2k((wt[0]*p[0]+wt[1]*64)>>16); } // 2 ISSE 17 1 { if (c8==1 || (c8&0xf0)==16) comp[2].c=find(comp[2].ht, 19, z.H(2)+16*c8); comp[2].cxt=comp[2].ht[comp[2].c+(hmap4&15)]; int *wt=(int*)&comp[2].cm[comp[2].cxt*2]; p[2]=clamp2k((wt[0]*p[1]+wt[1]*64)>>16); } // 3 ISSE 18 2 { if (c8==1 || (c8&0xf0)==16) comp[3].c=find(comp[3].ht, 20, z.H(3)+16*c8); comp[3].cxt=comp[3].ht[comp[3].c+(hmap4&15)]; int *wt=(int*)&comp[3].cm[comp[3].cxt*2]; p[3]=clamp2k((wt[0]*p[2]+wt[1]*64)>>16); } // 4 ISSE 18 3 { if (c8==1 || (c8&0xf0)==16) comp[4].c=find(comp[4].ht, 20, z.H(4)+16*c8); comp[4].cxt=comp[4].ht[comp[4].c+(hmap4&15)]; int *wt=(int*)&comp[4].cm[comp[4].cxt*2]; p[4]=clamp2k((wt[0]*p[3]+wt[1]*64)>>16); } // 5 ISSE 19 4 { if (c8==1 || (c8&0xf0)==16) comp[5].c=find(comp[5].ht, 21, z.H(5)+16*c8); comp[5].cxt=comp[5].ht[comp[5].c+(hmap4&15)]; int *wt=(int*)&comp[5].cm[comp[5].cxt*2]; p[5]=clamp2k((wt[0]*p[4]+wt[1]*64)>>16); } // 6 MATCH 22 24 if (comp[6].a==0) p[6]=0; else { comp[6].c=comp[6].ht((comp[6].limit>>3) -comp[6].b)>>(7-(comp[6].limit&7))&1; p[6]=stretch(comp[6].cxt*(comp[6].c*-2+1)&32767); } // 7 MIX 16 0 7 24 255 { comp[7].cxt=z.H(7)+(c8&255); comp[7].cxt=(comp[7].cxt&(comp[7].c-1))*7; int* wt=(int*)&comp[7].cm[comp[7].cxt]; p[7]=(wt[0]>>8)*p[0]; p[7]+=(wt[1]>>8)*p[1]; p[7]+=(wt[2]>>8)*p[2]; p[7]+=(wt[3]>>8)*p[3]; p[7]+=(wt[4]>>8)*p[4]; p[7]+=(wt[5]>>8)*p[5]; p[7]+=(wt[6]>>8)*p[6]; p[7]=clamp2k(p[7]>>8); } return squash(p[7]); } case 3: { // 22 components // 0 CONST 160 // 1 ICM 5 if (c8==1 || (c8&0xf0)==16) comp[1].c=find(comp[1].ht, 5+2, z.H(1)+16*c8); comp[1].cxt=comp[1].ht[comp[1].c+(hmap4&15)]; p[1]=stretch(comp[1].cm(comp[1].cxt)>>8); // 2 ISSE 13 1 { if (c8==1 || (c8&0xf0)==16) comp[2].c=find(comp[2].ht, 15, z.H(2)+16*c8); comp[2].cxt=comp[2].ht[comp[2].c+(hmap4&15)]; int *wt=(int*)&comp[2].cm[comp[2].cxt*2]; p[2]=clamp2k((wt[0]*p[1]+wt[1]*64)>>16); } // 3 ISSE 16 2 { if (c8==1 || (c8&0xf0)==16) comp[3].c=find(comp[3].ht, 18, z.H(3)+16*c8); comp[3].cxt=comp[3].ht[comp[3].c+(hmap4&15)]; int *wt=(int*)&comp[3].cm[comp[3].cxt*2]; p[3]=clamp2k((wt[0]*p[2]+wt[1]*64)>>16); } // 4 ISSE 18 3 { if (c8==1 || (c8&0xf0)==16) comp[4].c=find(comp[4].ht, 20, z.H(4)+16*c8); comp[4].cxt=comp[4].ht[comp[4].c+(hmap4&15)]; int *wt=(int*)&comp[4].cm[comp[4].cxt*2]; p[4]=clamp2k((wt[0]*p[3]+wt[1]*64)>>16); } // 5 ISSE 19 4 { if (c8==1 || (c8&0xf0)==16) comp[5].c=find(comp[5].ht, 21, z.H(5)+16*c8); comp[5].cxt=comp[5].ht[comp[5].c+(hmap4&15)]; int *wt=(int*)&comp[5].cm[comp[5].cxt*2]; p[5]=clamp2k((wt[0]*p[4]+wt[1]*64)>>16); } // 6 ISSE 19 5 { if (c8==1 || (c8&0xf0)==16) comp[6].c=find(comp[6].ht, 21, z.H(6)+16*c8); comp[6].cxt=comp[6].ht[comp[6].c+(hmap4&15)]; int *wt=(int*)&comp[6].cm[comp[6].cxt*2]; p[6]=clamp2k((wt[0]*p[5]+wt[1]*64)>>16); } // 7 ISSE 20 6 { if (c8==1 || (c8&0xf0)==16) comp[7].c=find(comp[7].ht, 22, z.H(7)+16*c8); comp[7].cxt=comp[7].ht[comp[7].c+(hmap4&15)]; int *wt=(int*)&comp[7].cm[comp[7].cxt*2]; p[7]=clamp2k((wt[0]*p[6]+wt[1]*64)>>16); } // 8 MATCH 22 24 if (comp[8].a==0) p[8]=0; else { comp[8].c=comp[8].ht((comp[8].limit>>3) -comp[8].b)>>(7-(comp[8].limit&7))&1; p[8]=stretch(comp[8].cxt*(comp[8].c*-2+1)&32767); } // 9 ICM 17 if (c8==1 || (c8&0xf0)==16) comp[9].c=find(comp[9].ht, 17+2, z.H(9)+16*c8); comp[9].cxt=comp[9].ht[comp[9].c+(hmap4&15)]; p[9]=stretch(comp[9].cm(comp[9].cxt)>>8); // 10 ISSE 19 9 { if (c8==1 || (c8&0xf0)==16) comp[10].c=find(comp[10].ht, 21, z.H(10)+16*c8); comp[10].cxt=comp[10].ht[comp[10].c+(hmap4&15)]; int *wt=(int*)&comp[10].cm[comp[10].cxt*2]; p[10]=clamp2k((wt[0]*p[9]+wt[1]*64)>>16); } // 11 ICM 13 if (c8==1 || (c8&0xf0)==16) comp[11].c=find(comp[11].ht, 13+2, z.H(11)+16*c8); comp[11].cxt=comp[11].ht[comp[11].c+(hmap4&15)]; p[11]=stretch(comp[11].cm(comp[11].cxt)>>8); // 12 ICM 13 if (c8==1 || (c8&0xf0)==16) comp[12].c=find(comp[12].ht, 13+2, z.H(12)+16*c8); comp[12].cxt=comp[12].ht[comp[12].c+(hmap4&15)]; p[12]=stretch(comp[12].cm(comp[12].cxt)>>8); // 13 ICM 13 if (c8==1 || (c8&0xf0)==16) comp[13].c=find(comp[13].ht, 13+2, z.H(13)+16*c8); comp[13].cxt=comp[13].ht[comp[13].c+(hmap4&15)]; p[13]=stretch(comp[13].cm(comp[13].cxt)>>8); // 14 ICM 14 if (c8==1 || (c8&0xf0)==16) comp[14].c=find(comp[14].ht, 14+2, z.H(14)+16*c8); comp[14].cxt=comp[14].ht[comp[14].c+(hmap4&15)]; p[14]=stretch(comp[14].cm(comp[14].cxt)>>8); // 15 MIX 16 0 15 24 255 { comp[15].cxt=z.H(15)+(c8&255); comp[15].cxt=(comp[15].cxt&(comp[15].c-1))*15; int* wt=(int*)&comp[15].cm[comp[15].cxt]; p[15]=(wt[0]>>8)*p[0]; p[15]+=(wt[1]>>8)*p[1]; p[15]+=(wt[2]>>8)*p[2]; p[15]+=(wt[3]>>8)*p[3]; p[15]+=(wt[4]>>8)*p[4]; p[15]+=(wt[5]>>8)*p[5]; p[15]+=(wt[6]>>8)*p[6]; p[15]+=(wt[7]>>8)*p[7]; p[15]+=(wt[8]>>8)*p[8]; p[15]+=(wt[9]>>8)*p[9]; p[15]+=(wt[10]>>8)*p[10]; p[15]+=(wt[11]>>8)*p[11]; p[15]+=(wt[12]>>8)*p[12]; p[15]+=(wt[13]>>8)*p[13]; p[15]+=(wt[14]>>8)*p[14]; p[15]=clamp2k(p[15]>>8); } // 16 MIX 8 0 16 10 255 { comp[16].cxt=z.H(16)+(c8&255); comp[16].cxt=(comp[16].cxt&(comp[16].c-1))*16; int* wt=(int*)&comp[16].cm[comp[16].cxt]; p[16]=(wt[0]>>8)*p[0]; p[16]+=(wt[1]>>8)*p[1]; p[16]+=(wt[2]>>8)*p[2]; p[16]+=(wt[3]>>8)*p[3]; p[16]+=(wt[4]>>8)*p[4]; p[16]+=(wt[5]>>8)*p[5]; p[16]+=(wt[6]>>8)*p[6]; p[16]+=(wt[7]>>8)*p[7]; p[16]+=(wt[8]>>8)*p[8]; p[16]+=(wt[9]>>8)*p[9]; p[16]+=(wt[10]>>8)*p[10]; p[16]+=(wt[11]>>8)*p[11]; p[16]+=(wt[12]>>8)*p[12]; p[16]+=(wt[13]>>8)*p[13]; p[16]+=(wt[14]>>8)*p[14]; p[16]+=(wt[15]>>8)*p[15]; p[16]=clamp2k(p[16]>>8); } // 17 MIX2 0 15 16 24 0 { comp[17].cxt=((z.H(17)+(c8&0))&(comp[17].c-1)); int w=comp[17].a16[comp[17].cxt]; p[17]=(w*p[15]+(65536-w)*p[16])>>16; } // 18 SSE 8 17 32 255 { comp[18].cxt=(z.H(18)+c8)*32; int pq=p[17]+992; if (pq<0) pq=0; if (pq>1983) pq=1983; int wt=pq&63; pq>>=6; comp[18].cxt+=pq; p[18]=stretch(((comp[18].cm(comp[18].cxt)>>10)*(64-wt) +(comp[18].cm(comp[18].cxt+1)>>10)*wt)>>13); comp[18].cxt+=wt>>5; } // 19 MIX2 8 17 18 16 255 { comp[19].cxt=((z.H(19)+(c8&255))&(comp[19].c-1)); int w=comp[19].a16[comp[19].cxt]; p[19]=(w*p[17]+(65536-w)*p[18])>>16; } // 20 SSE 16 19 32 255 { comp[20].cxt=(z.H(20)+c8)*32; int pq=p[19]+992; if (pq<0) pq=0; if (pq>1983) pq=1983; int wt=pq&63; pq>>=6; comp[20].cxt+=pq; p[20]=stretch(((comp[20].cm(comp[20].cxt)>>10)*(64-wt) +(comp[20].cm(comp[20].cxt+1)>>10)*wt)>>13); comp[20].cxt+=wt>>5; } // 21 MIX2 0 19 20 16 0 { comp[21].cxt=((z.H(21)+(c8&0))&(comp[21].c-1)); int w=comp[21].a16[comp[21].cxt]; p[21]=(w*p[19]+(65536-w)*p[20])>>16; } return squash(p[21]); } default: return predict0(); } } void Predictor::update(int y) { switch(z.select) { case 1: { // 2 components // 0 ICM 16 { comp[0].ht[comp[0].c+(hmap4&15)]= st.next(comp[0].ht[comp[0].c+(hmap4&15)], y); U32& pn=comp[0].cm(comp[0].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 1 ISSE 19 0 { int err=y*32767-squash(p[1]); int *wt=(int*)&comp[1].cm[comp[1].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[0]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[1].ht[comp[1].c+(hmap4&15)]=st.next(comp[1].cxt, y); } break; } case 2: { // 8 components // 0 ICM 5 { comp[0].ht[comp[0].c+(hmap4&15)]= st.next(comp[0].ht[comp[0].c+(hmap4&15)], y); U32& pn=comp[0].cm(comp[0].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 1 ISSE 13 0 { int err=y*32767-squash(p[1]); int *wt=(int*)&comp[1].cm[comp[1].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[0]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[1].ht[comp[1].c+(hmap4&15)]=st.next(comp[1].cxt, y); } // 2 ISSE 17 1 { int err=y*32767-squash(p[2]); int *wt=(int*)&comp[2].cm[comp[2].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[1]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[2].ht[comp[2].c+(hmap4&15)]=st.next(comp[2].cxt, y); } // 3 ISSE 18 2 { int err=y*32767-squash(p[3]); int *wt=(int*)&comp[3].cm[comp[3].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[2]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[3].ht[comp[3].c+(hmap4&15)]=st.next(comp[3].cxt, y); } // 4 ISSE 18 3 { int err=y*32767-squash(p[4]); int *wt=(int*)&comp[4].cm[comp[4].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[3]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[4].ht[comp[4].c+(hmap4&15)]=st.next(comp[4].cxt, y); } // 5 ISSE 19 4 { int err=y*32767-squash(p[5]); int *wt=(int*)&comp[5].cm[comp[5].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[4]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[5].ht[comp[5].c+(hmap4&15)]=st.next(comp[5].cxt, y); } // 6 MATCH 22 24 { if (comp[6].c!=y) comp[6].a=0; comp[6].ht(comp[6].limit>>3)+=comp[6].ht(comp[6].limit>>3)+y; if ((++comp[6].limit&7)==0) { int pos=comp[6].limit>>3; if (comp[6].a==0) { comp[6].b=pos-comp[6].cm(z.H(6)); if (comp[6].b&(comp[6].ht.size()-1)) while (comp[6].a<255 && comp[6].ht(pos-comp[6].a-1) ==comp[6].ht(pos-comp[6].a-comp[6].b-1)) ++comp[6].a; } else comp[6].a+=comp[6].a<255; comp[6].cm(z.H(6))=pos; if (comp[6].a>0) comp[6].cxt=2048/comp[6].a; } } // 7 MIX 16 0 7 24 255 { int err=(y*32767-squash(p[7]))*24>>4; int* wt=(int*)&comp[7].cm[comp[7].cxt]; wt[0]=clamp512k(wt[0]+((err*p[0]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err*p[1]+(1<<12))>>13)); wt[2]=clamp512k(wt[2]+((err*p[2]+(1<<12))>>13)); wt[3]=clamp512k(wt[3]+((err*p[3]+(1<<12))>>13)); wt[4]=clamp512k(wt[4]+((err*p[4]+(1<<12))>>13)); wt[5]=clamp512k(wt[5]+((err*p[5]+(1<<12))>>13)); wt[6]=clamp512k(wt[6]+((err*p[6]+(1<<12))>>13)); } break; } case 3: { // 22 components // 0 CONST 160 // 1 ICM 5 { comp[1].ht[comp[1].c+(hmap4&15)]= st.next(comp[1].ht[comp[1].c+(hmap4&15)], y); U32& pn=comp[1].cm(comp[1].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 2 ISSE 13 1 { int err=y*32767-squash(p[2]); int *wt=(int*)&comp[2].cm[comp[2].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[1]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[2].ht[comp[2].c+(hmap4&15)]=st.next(comp[2].cxt, y); } // 3 ISSE 16 2 { int err=y*32767-squash(p[3]); int *wt=(int*)&comp[3].cm[comp[3].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[2]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[3].ht[comp[3].c+(hmap4&15)]=st.next(comp[3].cxt, y); } // 4 ISSE 18 3 { int err=y*32767-squash(p[4]); int *wt=(int*)&comp[4].cm[comp[4].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[3]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[4].ht[comp[4].c+(hmap4&15)]=st.next(comp[4].cxt, y); } // 5 ISSE 19 4 { int err=y*32767-squash(p[5]); int *wt=(int*)&comp[5].cm[comp[5].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[4]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[5].ht[comp[5].c+(hmap4&15)]=st.next(comp[5].cxt, y); } // 6 ISSE 19 5 { int err=y*32767-squash(p[6]); int *wt=(int*)&comp[6].cm[comp[6].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[5]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[6].ht[comp[6].c+(hmap4&15)]=st.next(comp[6].cxt, y); } // 7 ISSE 20 6 { int err=y*32767-squash(p[7]); int *wt=(int*)&comp[7].cm[comp[7].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[6]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[7].ht[comp[7].c+(hmap4&15)]=st.next(comp[7].cxt, y); } // 8 MATCH 22 24 { if (comp[8].c!=y) comp[8].a=0; comp[8].ht(comp[8].limit>>3)+=comp[8].ht(comp[8].limit>>3)+y; if ((++comp[8].limit&7)==0) { int pos=comp[8].limit>>3; if (comp[8].a==0) { comp[8].b=pos-comp[8].cm(z.H(8)); if (comp[8].b&(comp[8].ht.size()-1)) while (comp[8].a<255 && comp[8].ht(pos-comp[8].a-1) ==comp[8].ht(pos-comp[8].a-comp[8].b-1)) ++comp[8].a; } else comp[8].a+=comp[8].a<255; comp[8].cm(z.H(8))=pos; if (comp[8].a>0) comp[8].cxt=2048/comp[8].a; } } // 9 ICM 17 { comp[9].ht[comp[9].c+(hmap4&15)]= st.next(comp[9].ht[comp[9].c+(hmap4&15)], y); U32& pn=comp[9].cm(comp[9].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 10 ISSE 19 9 { int err=y*32767-squash(p[10]); int *wt=(int*)&comp[10].cm[comp[10].cxt*2]; wt[0]=clamp512k(wt[0]+((err*p[9]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err+16)>>5)); comp[10].ht[comp[10].c+(hmap4&15)]=st.next(comp[10].cxt, y); } // 11 ICM 13 { comp[11].ht[comp[11].c+(hmap4&15)]= st.next(comp[11].ht[comp[11].c+(hmap4&15)], y); U32& pn=comp[11].cm(comp[11].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 12 ICM 13 { comp[12].ht[comp[12].c+(hmap4&15)]= st.next(comp[12].ht[comp[12].c+(hmap4&15)], y); U32& pn=comp[12].cm(comp[12].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 13 ICM 13 { comp[13].ht[comp[13].c+(hmap4&15)]= st.next(comp[13].ht[comp[13].c+(hmap4&15)], y); U32& pn=comp[13].cm(comp[13].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 14 ICM 14 { comp[14].ht[comp[14].c+(hmap4&15)]= st.next(comp[14].ht[comp[14].c+(hmap4&15)], y); U32& pn=comp[14].cm(comp[14].cxt); pn+=int(y*32767-(pn>>8))>>2; } // 15 MIX 16 0 15 24 255 { int err=(y*32767-squash(p[15]))*24>>4; int* wt=(int*)&comp[15].cm[comp[15].cxt]; wt[0]=clamp512k(wt[0]+((err*p[0]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err*p[1]+(1<<12))>>13)); wt[2]=clamp512k(wt[2]+((err*p[2]+(1<<12))>>13)); wt[3]=clamp512k(wt[3]+((err*p[3]+(1<<12))>>13)); wt[4]=clamp512k(wt[4]+((err*p[4]+(1<<12))>>13)); wt[5]=clamp512k(wt[5]+((err*p[5]+(1<<12))>>13)); wt[6]=clamp512k(wt[6]+((err*p[6]+(1<<12))>>13)); wt[7]=clamp512k(wt[7]+((err*p[7]+(1<<12))>>13)); wt[8]=clamp512k(wt[8]+((err*p[8]+(1<<12))>>13)); wt[9]=clamp512k(wt[9]+((err*p[9]+(1<<12))>>13)); wt[10]=clamp512k(wt[10]+((err*p[10]+(1<<12))>>13)); wt[11]=clamp512k(wt[11]+((err*p[11]+(1<<12))>>13)); wt[12]=clamp512k(wt[12]+((err*p[12]+(1<<12))>>13)); wt[13]=clamp512k(wt[13]+((err*p[13]+(1<<12))>>13)); wt[14]=clamp512k(wt[14]+((err*p[14]+(1<<12))>>13)); } // 16 MIX 8 0 16 10 255 { int err=(y*32767-squash(p[16]))*10>>4; int* wt=(int*)&comp[16].cm[comp[16].cxt]; wt[0]=clamp512k(wt[0]+((err*p[0]+(1<<12))>>13)); wt[1]=clamp512k(wt[1]+((err*p[1]+(1<<12))>>13)); wt[2]=clamp512k(wt[2]+((err*p[2]+(1<<12))>>13)); wt[3]=clamp512k(wt[3]+((err*p[3]+(1<<12))>>13)); wt[4]=clamp512k(wt[4]+((err*p[4]+(1<<12))>>13)); wt[5]=clamp512k(wt[5]+((err*p[5]+(1<<12))>>13)); wt[6]=clamp512k(wt[6]+((err*p[6]+(1<<12))>>13)); wt[7]=clamp512k(wt[7]+((err*p[7]+(1<<12))>>13)); wt[8]=clamp512k(wt[8]+((err*p[8]+(1<<12))>>13)); wt[9]=clamp512k(wt[9]+((err*p[9]+(1<<12))>>13)); wt[10]=clamp512k(wt[10]+((err*p[10]+(1<<12))>>13)); wt[11]=clamp512k(wt[11]+((err*p[11]+(1<<12))>>13)); wt[12]=clamp512k(wt[12]+((err*p[12]+(1<<12))>>13)); wt[13]=clamp512k(wt[13]+((err*p[13]+(1<<12))>>13)); wt[14]=clamp512k(wt[14]+((err*p[14]+(1<<12))>>13)); wt[15]=clamp512k(wt[15]+((err*p[15]+(1<<12))>>13)); } // 17 MIX2 0 15 16 24 0 { int err=(y*32767-squash(p[17]))*24>>5; int w=comp[17].a16[comp[17].cxt]; w+=(err*(p[15]-p[16])+(1<<12))>>13; if (w<0) w=0; if (w>65535) w=65535; comp[17].a16[comp[17].cxt]=w; } // 18 SSE 8 17 32 255 train(comp[18], y); // 19 MIX2 8 17 18 16 255 { int err=(y*32767-squash(p[19]))*16>>5; int w=comp[19].a16[comp[19].cxt]; w+=(err*(p[17]-p[18])+(1<<12))>>13; if (w<0) w=0; if (w>65535) w=65535; comp[19].a16[comp[19].cxt]=w; } // 20 SSE 16 19 32 255 train(comp[20], y); // 21 MIX2 0 19 20 16 0 { int err=(y*32767-squash(p[21]))*16>>5; int w=comp[21].a16[comp[21].cxt]; w+=(err*(p[19]-p[20])+(1<<12))>>13; if (w<0) w=0; if (w>65535) w=65535; comp[21].a16[comp[21].cxt]=w; } break; } default: return update0(y); } c8+=c8+y; if (c8>=256) { z.run(c8-256); hmap4=1; c8=1; } else if (c8>=16 && c8<32) hmap4=(hmap4&0xf)<<5|y<<4|1; else hmap4=(hmap4&0x1f0)|(((hmap4&0xf)*2+y)&0xf); } void ZPAQL::run(U32 input) { switch(select) { case 1: { a = input; m(b) = a; a = 0; d = 0; a = (a+m(b)+512)*773; --b; a = (a+m(b)+512)*773; h(d) = a; ++d; --b; a = (a+m(b)+512)*773; --b; a = (a+m(b)+512)*773; h(d) = a; return; break; } case 2: { a = input; ++c; m(c) = a; b = c; a = 0; d = 1; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; --b; a = (a+m(b)+512)*773; h(d) = a; ++d; a = m(c); a <<= (8&31); h(d) = a; return; break; } case 3: { a = input; ++c; m(c) = a; b = c; a = 0; d = 2; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; --b; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = (a+m(b)+512)*773; h(d) = a; --b; ++d; a = m(c); a &= ~ 32; f = (a > U32(64)); if (!f) goto L300057; f = (a < U32(91)); if (!f) goto L300057; ++d; h(d) = (h(d)+a+512)*773; --d; swap(h(d)); a += h(d); a *= 20; h(d) = a; goto L300066; L300057: a = h(d); f = (a == U32(0)); if (f) goto L300065; ++d; h(d) = a; --d; L300065: h(d) = 0; L300066: ++d; ++d; b = c; --b; a = 0; a = (a+m(b)+512)*773; h(d) = a; ++d; --b; a = 0; a = (a+m(b)+512)*773; h(d) = a; ++d; --b; a = 0; a = (a+m(b)+512)*773; h(d) = a; ++d; a = b; a -= 212; b = a; a = 0; a = (a+m(b)+512)*773; h(d) = a; swap(b); a -= 216; swap(b); a = m(b); a &= 60; h(d) = (h(d)+a+512)*773; ++d; a = m(c); a <<= (9&31); h(d) = a; ++d; ++d; ++d; ++d; ++d; h(d) = a; return; break; } default: run0(input); } } }
[ [ [ 1, 879 ] ] ]
4547b7b2c9ed138a5298e40fe3a4f8129e616514
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/FingerSuite/FingerMsgBox/MainFrm.h
2e1358cdef130d1b32e3338cdc04751b76608851
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
20,276
h
// MainFrm.h : interface of the CMainFrame class // ///////////////////////////////////////////////////////////////////////////// #pragma once #include "sharedmem.h" #include "InterceptEngine.h" #include "..\Common\Utils.h" #include "..\Common\log\logger.h" #include "..\Common\AboutView.h" #include "..\Common\fngrbtn.h" #include "..\FingerSuiteCPL\Commons.h" #include "MsgBoxWindow.h" #include "..\Common\fngrsplash.h" #define IDT_TMR_DISABLED 10012 #define MASK_EVENTMUTE 0x0004 typedef enum {QVGA = 320, WQVGA = 400, VGA = 640, WVGA = 800} RESOLUTION; static UINT UWM_INTERCEPT_MSGBOX = ::RegisterWindowMessage(UWM_INTERCEPT_MSGBOX_MSG); static UINT UWM_UPDATECONFIGURATION = ::RegisterWindowMessage(UWM_UPDATECONFIGURATION_MSG); class CMainFrame : public CFrameWindowImpl<CMainFrame>, public CUpdateUI<CMainFrame>, public CMessageFilter, public CIdleHandler { public: DECLARE_FRAME_WND_CLASS(L"FINGER_MSGBOX", IDR_MAINFRAME) CMsgBoxWindow m_msgBoxView; CAboutView m_aboutView; virtual BOOL PreTranslateMessage(MSG* pMsg) { if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg)) return TRUE; return m_msgBoxView.PreTranslateMessage(pMsg); } virtual BOOL OnIdle() { return FALSE; } void DoPaint(CDCHandle dc) { RECT rc; GetClientRect(&rc); if (m_bDisabledTransp) { dc.FillSolidRect(&rc, m_clNoTranspBackground); } else { if (!(m_imgBkg.IsValid())) CaptureScreen(dc); m_imgBkg.Draw(dc, rc); } } BEGIN_UPDATE_UI_MAP(CMainFrame) END_UPDATE_UI_MAP() BEGIN_MSG_MAP(CMainFrame) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_CLOSE, OnClose) MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(WM_ACTIVATE, OnActivate) MESSAGE_HANDLER(WM_WININICHANGE, OnWininichange) MESSAGE_HANDLER(UM_MINIMIZE, OnMinimize) MESSAGE_HANDLER(UWM_INTERCEPT_MSGBOX, OnInterceptMsgBox) MESSAGE_HANDLER(UWM_UPDATECONFIGURATION, OnUpdateConfiguration) COMMAND_ID_HANDLER(ID_MENU_CANCEL, OnCancel) COMMAND_ID_HANDLER(ID_MENU_EXIT, OnMenuExit) COMMAND_ID_HANDLER(ID_MENU_ABOUT, OnMenuAbout) COMMAND_ID_HANDLER(ID_MENU_SHOWORIGINAL, OnMenuShowOriginal) COMMAND_ID_HANDLER(ID_MENU_ADDTOEXCLUSIONLIST, OnMenuAddToExclusionList) COMMAND_ID_HANDLER(ID_MENU_ADDTOWNDEXCLUSIONLIST, OnMenuAddToWndExclusionList) CHAIN_MSG_MAP(CUpdateUI<CMainFrame>) CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>) END_MSG_MAP() LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CreateSimpleCEMenuBar(FM_IDW_MENU_BAR, SHCMBF_HIDESIPBUTTON); CSplashWindow* pSplash = new CSplashWindow(m_hWnd, IDR_MAINFRAME, L"FingerMsgbox"); LoadConfiguration(); // msgbox m_hWndClient = m_msgBoxView.Create(m_hWnd); // about CString strCredits = "\n\n" "\tFingerMsgBox v1.01\n\n" "\rProgrammed by:\n" "Francesco Carlucci\n" "<[email protected]>\n" "\n\n" "http://forum.xda-developers.com/\n" " showthread.php?t=459125\n"; m_aboutView.SetCredits(strCredits); m_aboutView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN); // // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); SetHWndServerMsgBox(m_hWnd); InstallHook(); SignalWaitEvent(EVT_FNGRMSGBOX); ModifyStyle(0, WS_NONAVDONEBUTTON, SWP_NOSIZE); m_bDisabled = FALSE; pSplash->Dismiss(); return 0; } LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return 0; } LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { if(wParam != SIZE_MINIMIZED) { } return 0; } LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { RemoveHook(); if (!(m_fText.IsNull())) { m_fText.DeleteObject(); m_fText = NULL; } if (!(m_fCaption.IsNull())) { m_fCaption.DeleteObject(); m_fCaption = NULL; } if (!(m_fBtn.IsNull())) { m_fBtn.DeleteObject(); m_fBtn = NULL; } bHandled = FALSE; return 0; } LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return 1; } LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if(wParam != NULL) { DoPaint((HDC)wParam); } else { CPaintDC dc(m_hWnd); DoPaint(dc.m_hDC); } return 0; } LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { int fActive = LOWORD(wParam); if ((fActive == WA_ACTIVE) || (fActive == WA_CLICKACTIVE)) { } else if (fActive == WA_INACTIVE) { if (IsWindowVisible()) { SetMsgBoxResult(IDCANCEL); Minimize(); } } return 0; } LRESULT OnWininichange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if (wParam == SETTINGCHANGE_RESET) { //SetMsgBoxResult(IDCANCEL); //Minimize(); m_msgBoxView.ModifyShape(); m_msgBoxView.ModifyButtons(); } return 0; } LRESULT OnMinimize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { Minimize(); return 0; } LRESULT OnCancel(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SetMsgBoxResult(IDCANCEL); Minimize(); return 0; } LRESULT OnInterceptMsgBox(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled) { LPMSGBOXINFO lpInfo = (LPMSGBOXINFO)lParam; HWND hDestWnd = lpInfo->hWnd; UINT uType = lpInfo->uType; LOG(L"Intercepting MessageBoxW...uType=%08x hWnd=%08X\n", uType, hDestWnd); if (m_bDisabled) return 1; if (IsDeviceLocked()) return 1; m_hForeWnd = ::GetForegroundWindow(); if (IsExcludedApp(hDestWnd)) return 1; if (IsExcludedWnd(hDestWnd)) return 1; if (!(m_msgBoxView.SetMsgBox(hDestWnd, uType, lpInfo->szCaption, lpInfo->szText))) return 1; Sleep(100); SwitchToMsgBoxView(); SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001)); ShowWindow(SW_SHOW); PlayMessageBoxSound(uType); bHandled = TRUE; return 0; } LRESULT OnMenuExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SetMsgBoxResult(IDCANCEL); Minimize(); PostMessage(WM_CLOSE); return 0; } LRESULT OnMenuAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SwitchToAboutView(); SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001)); ShowWindow(SW_SHOW); return 0; } LRESULT OnMenuShowOriginal(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SetMsgBoxResult(-1); Minimize(); return 0; } LRESULT OnMenuAddToExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { HWND hDestWnd = m_msgBoxView.GetOwnerWnd(); DWORD dwProcessId; GetWindowThreadProcessId(hDestWnd, &dwProcessId); HMODULE hProcess = (HMODULE)dwProcessId; WCHAR szName[MAX_PATH]; if (GetModuleFileName(hProcess, szName, MAX_PATH)) { CString szApp = (LPTSTR)szName; szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1); if (m_excludedApps.Find(szApp) == -1) m_excludedApps.Add(szApp); SaveExclusionList(m_excludedApps, L"Software\\FingerMsgbox"); } SetMsgBoxResult(-1); Minimize(); return 0; } LRESULT OnMenuAddToWndExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { HWND hDestWnd = m_msgBoxView.GetOwnerWnd(); WCHAR szTitle[MAX_PATH]; ::GetWindowText(hDestWnd, szTitle, MAX_PATH); WCHAR szClassName[MAX_PATH]; ::GetClassName(hDestWnd, szClassName, MAX_PATH); WCHAR szName[MAX_PATH]; wsprintf(szName, L"%s - %s", szTitle, szClassName); CString szWnd = (LPTSTR)szName; if (m_excludedWnds.Find(szWnd) == -1) m_excludedWnds.Add(szWnd); SaveWndExclusionList(m_excludedWnds, L"Software\\FingerMsgbox"); SetMsgBoxResult(-1); Minimize(); return 0; } LRESULT OnUpdateConfiguration(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { LoadConfiguration(); SetMsgBoxResult(FALSE); Minimize(); return 0; } private: void Minimize() { ShowWindow(SW_HIDE); SignalWaitEvent(EVT_FNGRMSGBOX); } HWND ManageDOTNETApp(HWND& hDestWnd) { HWND hDestCtrl = NULL; WCHAR szClass[50]; ::GetClassName(hDestWnd, szClass, 50); if (lstrcmpi(szClass, L"MS_SOFTKEY_CE_1.0") == 0) { DWORD dwProcessId; GetWindowThreadProcessId(hDestWnd, &dwProcessId); HWND hDotNETWnd = ::FindWindow(L"#NETCF_AGL_BASE_", NULL); if (hDotNETWnd != NULL) { DWORD dwProcess2Id; GetWindowThreadProcessId(hDotNETWnd, &dwProcess2Id); if (dwProcess2Id == dwProcessId) { hDestCtrl = hDestWnd; hDestWnd = hDotNETWnd; } } } return hDestCtrl; } BOOL IsExcludedApp(HWND hWnd) { DWORD dwProcessId; GetWindowThreadProcessId(hWnd, &dwProcessId); HMODULE hProcess = (HMODULE)dwProcessId; WCHAR szName[MAX_PATH]; if (GetModuleFileName(hProcess, szName, MAX_PATH)) { CString szApp = (LPTSTR)szName; szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1); for (int i = 0; i < m_excludedApps.GetSize(); i ++) { if (m_excludedApps[i].CompareNoCase( szApp ) == 0) return TRUE; } } return FALSE; } BOOL IsExcludedWnd(HWND hWnd) { WCHAR szTitle[MAX_PATH]; ::GetWindowText(hWnd, szTitle, MAX_PATH); WCHAR szClassName[MAX_PATH]; ::GetClassName(hWnd, szClassName, MAX_PATH); WCHAR szName[MAX_PATH]; wsprintf(szName, L"%s - %s", szTitle, szClassName); CString szWnd = (LPTSTR)szName; for (int i = 0; i < m_excludedWnds.GetSize(); i ++) { if (m_excludedWnds[i].CompareNoCase( szWnd ) == 0) return TRUE; } return FALSE; } void CaptureScreen(CDCHandle dc) { RECT rc; GetClientRect(&rc); CDC dcTemp; dcTemp.CreateCompatibleDC(dc); CBitmap bmpBkg; bmpBkg.CreateCompatibleBitmap(dc, rc.right, rc.bottom); CBitmap bmpOld = dcTemp.SelectBitmap(bmpBkg); dcTemp.FillSolidRect(&rc, RGB(0,0,0)); dcTemp.SelectBitmap(bmpOld); m_imgBkg.CreateFromHBITMAP(bmpBkg); m_imgBkg.AlphaCreate(); m_imgBkg.AlphaSet((BYTE)m_iTransp); } void LoadConfiguration() { WCHAR keyName[] = L"Software\\FingerMsgBox"; // load transparency level m_iTransp = 128; if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_iTransp))) wprintf(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError())); m_msgBoxView.m_iTransp = m_iTransp; m_bDisabledTransp = FALSE; if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisabledTransp))) wprintf(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError())); m_msgBoxView.m_bDisabledTransp = m_bDisabledTransp; m_clNoTranspBackground = RGB(0,0,0); RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_clNoTranspBackground); m_msgBoxView.m_clNoTranspBackground = m_clNoTranspBackground; WCHAR szSkin[60] = L"default"; RegReadString(HKEY_LOCAL_MACHINE, keyName, L"Skin", szSkin); WCHAR szAppPath[MAX_PATH] = L""; CString strAppDirectory; GetModuleFileName(NULL, szAppPath, MAX_PATH); strAppDirectory = szAppPath; strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\')); CString skinBasePath; skinBasePath.Format(L"%s\\skins\\%s", strAppDirectory, szSkin); // detect resolution RESOLUTION resolution = QVGA; DEVMODE dm; ::ZeroMemory(&dm, sizeof(DEVMODE)); dm.dmSize = sizeof(DEVMODE); if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm)) { resolution = (RESOLUTION)dm.dmPelsHeight; } // load icon images switch (resolution) { case QVGA: case WQVGA: m_msgBoxView.SetScaleFactor(1); break; case VGA: case WVGA: m_msgBoxView.SetScaleFactor(2); break; } if ( (resolution == VGA) || (resolution == WVGA)) { m_msgBoxView.m_imgHeader.Load(skinBasePath + L"\\msgbox_header_vga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnInfo.Load(skinBasePath + L"\\msgbox_iconinfo_vga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnQuestion.Load(skinBasePath + L"\\msgbox_iconquestion_vga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnStop.Load(skinBasePath + L"\\msgbox_iconstop_vga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnWarning.Load(skinBasePath + L"\\msgbox_iconwarning_vga.png", CXIMAGE_FORMAT_PNG); // normal AddDynamicSet(m_msgBoxView.m_arrDynamicImages, NORMAL, skinBasePath + L"\\msgbox_button_normal_left_vga.png", skinBasePath + L"\\msgbox_button_normal_center_vga.png", skinBasePath + L"\\msgbox_button_normal_right_vga.png"); // pressed AddDynamicSet(m_msgBoxView.m_arrDynamicImages, PUSHED, skinBasePath + L"\\msgbox_button_pressed_left_vga.png", skinBasePath + L"\\msgbox_button_pressed_center_vga.png", skinBasePath + L"\\msgbox_button_pressed_right_vga.png"); } else { m_msgBoxView.m_imgHeader.Load(skinBasePath + L"\\msgbox_header_qvga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnInfo.Load(skinBasePath + L"\\msgbox_iconinfo_qvga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnQuestion.Load(skinBasePath + L"\\msgbox_iconquestion_qvga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnStop.Load(skinBasePath + L"\\msgbox_iconstop_qvga.png", CXIMAGE_FORMAT_PNG); m_msgBoxView.m_icnWarning.Load(skinBasePath + L"\\msgbox_iconwarning_qvga.png", CXIMAGE_FORMAT_PNG); // normal AddDynamicSet(m_msgBoxView.m_arrDynamicImages, NORMAL, skinBasePath + L"\\msgbox_button_normal_left_qvga.png", skinBasePath + L"\\msgbox_button_normal_center_qvga.png", skinBasePath + L"\\msgbox_button_normal_right_qvga.png"); // pressed AddDynamicSet(m_msgBoxView.m_arrDynamicImages, PUSHED, skinBasePath + L"\\msgbox_button_pressed_left_qvga.png", skinBasePath + L"\\msgbox_button_pressed_center_qvga.png", skinBasePath + L"\\msgbox_button_pressed_right_qvga.png"); } // load skin settings CSimpleIniW ini(TRUE, TRUE, TRUE); SI_Error rc = ini.LoadFile(skinBasePath + L"\\settings_fingermsgbox.ini"); // load background and selected color COLORREF clValue = 0; m_msgBoxView.m_clBkg = (StringRGBToColor(ini.GetValue(L"colors", L"BkgColor"), clValue)) ? clValue : RGB(255,255,255); m_msgBoxView.m_clCaptionText = (StringRGBToColor(ini.GetValue(L"colors", L"CaptionTextColor"), clValue)) ? clValue : RGB(255,255,255); m_msgBoxView.m_clText = (StringRGBToColor(ini.GetValue(L"colors", L"TextColor"), clValue)) ? clValue : RGB(0,0,0); m_msgBoxView.m_clBtnText = (StringRGBToColor(ini.GetValue(L"colors", L"ButtonTextColor"), clValue)) ? clValue : RGB(0,0,0); m_msgBoxView.m_clBtnSelText = (StringRGBToColor(ini.GetValue(L"colors", L"SelButtonTextColor"), clValue)) ? clValue : RGB(255,255,255); m_msgBoxView.m_clLine = (StringRGBToColor(ini.GetValue(L"colors", L"LineColor"), clValue)) ? clValue : RGB(160,160,160); if (!(m_fText.IsNull())) m_fText.DeleteObject(); if (!(m_fCaption.IsNull())) m_fCaption.DeleteObject(); if (!(m_fBtn.IsNull())) m_fBtn.DeleteObject(); LOGFONT lf; if (StringToLogFont(ini.GetValue(L"fonts", L"TextFont"), lf)) { m_fText.CreateFontIndirect(&lf); } if (StringToLogFont(ini.GetValue(L"fonts", L"CaptionFont"), lf)) { m_fCaption.CreateFontIndirect(&lf); } if (StringToLogFont(ini.GetValue(L"fonts", L"ButtonFont"), lf)) { m_fBtn.CreateFontIndirect(&lf); } m_msgBoxView.m_fText = m_fText; m_msgBoxView.m_fCaption = m_fCaption; m_msgBoxView.m_fBtn = m_fBtn; //sounds m_szDefaultSound = ini.GetValue(L"sounds", L"DefaultSound" ); m_szErrorSound = ini.GetValue(L"sounds", L"ErrorSound" ); m_szWarningSound = ini.GetValue(L"sounds", L"WarningSound" ); m_szInfoSound = ini.GetValue(L"sounds", L"InfoSound" ); m_szQuestionSound = ini.GetValue(L"sounds", L"QuestionSound" ); //general options LPCWSTR lpwszCenterCaption = ini.GetValue(L"general", L"CenterCaption"); if (lstrcmpi(lpwszCenterCaption, L"true") == 0) m_msgBoxView.m_bCenterCaption = TRUE; else m_msgBoxView.m_bCenterCaption = FALSE; // list of excluded apps LoadExclusionList(m_excludedApps, L"Software\\FingerMsgbox"); LoadWndExclusionList(m_excludedWnds, L"Software\\FingerMsgbox"); } public: static HRESULT ActivatePreviousInstance(HINSTANCE hInstance) { const TCHAR* pszMutex = L"FINGERMSGBOXMUTEX"; const TCHAR* pszClass = L"FINGER_MSGBOX"; const DWORD dRetryInterval = 100; const int iMaxRetries = 25; for(int i = 0; i < iMaxRetries; ++i) { HANDLE hMutex = CreateMutex(NULL, FALSE, pszMutex); DWORD dw = GetLastError(); if(hMutex == NULL) { HRESULT hr = (dw == ERROR_INVALID_HANDLE) ? E_INVALIDARG : E_FAIL; return hr; } if(dw == ERROR_ALREADY_EXISTS) { CloseHandle(hMutex); HWND hwnd = FindWindow(pszClass, NULL); if(hwnd == NULL) { Sleep(dRetryInterval); continue; } else { if(SetForegroundWindow(reinterpret_cast<HWND>(reinterpret_cast<ULONG>(hwnd) | 0x1)) != 0) { return S_FALSE; } } } else { return S_OK; } } return S_OK; } void SwitchToMsgBoxView() { m_hWndClient = m_msgBoxView; m_aboutView.ShowWindow(SW_HIDE); m_aboutView.SetWindowLongPtr(GWL_ID, 0); m_msgBoxView.ShowWindow(SW_SHOW); m_msgBoxView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST); m_msgBoxView.SetFocus(); } void SwitchToAboutView() { m_hWndClient = m_aboutView; m_msgBoxView.ShowWindow(SW_HIDE); m_msgBoxView.SetWindowLongPtr(GWL_ID, 0); m_aboutView.ShowWindow(SW_SHOW); m_aboutView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST); m_aboutView.SetFocus(); UpdateLayout(); } void PlayMessageBoxSound(int uType) { if (!(IsEvtSoundActive())) return; CString fileName; if ((uType & MB_ICONEXCLAMATION) || (uType & MB_ICONWARNING)) { fileName = m_szWarningSound; goto soundend; } if ((uType & MB_ICONINFORMATION) || (uType & MB_ICONASTERISK)) { fileName = m_szInfoSound; goto soundend; } if (uType & MB_ICONQUESTION) { fileName = m_szQuestionSound; goto soundend; } if ((uType & MB_ICONSTOP) || (uType & MB_ICONERROR) || (uType & MB_ICONHAND)) { fileName = m_szErrorSound; goto soundend; } soundend: if (fileName.IsEmpty()) fileName = m_szDefaultSound; PlaySound(fileName, NULL, SND_ASYNC | SND_FILENAME | SND_NODEFAULT); } protected: HWND m_hForeWnd; CxImage m_imgBkg; BOOL m_bDisabledTransp; COLORREF m_clNoTranspBackground; DWORD m_iTransp; CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedApps; CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedWnds; BOOL m_bDisabled; CMenu m_menuConfig; CFontHandle m_fText; CFontHandle m_fCaption; CFontHandle m_fBtn; CString m_szDefaultSound; CString m_szErrorSound; CString m_szWarningSound; CString m_szInfoSound; CString m_szQuestionSound; private: BOOL IsEvtSoundActive() { BOOL bRes = TRUE; DWORD dwMute = 0; HRESULT hr = RegistryGetDWORD(HKEY_CURRENT_USER, L"ControlPanel\\Volume", L"Mute", &dwMute); if (SUCCEEDED(hr)) { if ( ! (dwMute & MASK_EVENTMUTE) ) bRes = FALSE; } return bRes; } };
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 751 ] ] ]
ae84e924a0b368cea1cbf54efd5d1f588875865e
06965c8bfe9274f24b961eaad95062051aaec1b2
/GUI/StatusFrame.h
30ce85ae2473953e54fc4549ae4283f5b8148199
[]
no_license
vinaybalhara/BaczekKPAI
902f2a27c1f565e9bae11ace82125052a3364306
9550e0c5abc260efc47355031aebd7d1831dfb0c
refs/heads/master
2021-01-16T19:14:52.776176
2010-12-07T15:43:48
2010-12-07T15:43:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,318
h
#ifndef STATUSFRAME_H #define STATUSFRAME_H #ifdef USE_STATUS_WINDOW // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/colordlg.h" #include "wx/image.h" #include "wx/artprov.h" #define wxTEST_GRAPHICS 1 #if wxTEST_GRAPHICS #include "wx/graphics.h" #if wxUSE_GRAPHICS_CONTEXT == 0 #undef wxTEST_GRAPHICS #define wxTEST_GRAPHICS 0 #endif #else #undef wxUSE_GRAPHICS_CONTEXT #define wxUSE_GRAPHICS_CONTEXT 0 #endif // what do we show on screen (there are too many shapes to put them all on // screen simultaneously) enum ScreenToShow { Show_Default, Show_Text, Show_Lines, Show_Brushes, Show_Polygons, Show_Mask, Show_Ops, Show_Regions, Show_Circles, Show_Splines, #if wxUSE_GRAPHICS_CONTEXT Show_Alpha, #endif Show_Gradient, Show_Max }; class MyCanvas; // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); // event handlers (these functions should _not_ be virtual) void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnClip(wxCommandEvent& event); #if wxUSE_GRAPHICS_CONTEXT void OnGraphicContext(wxCommandEvent& event); #endif void OnShow(wxCommandEvent &event); void OnOption(wxCommandEvent &event); #if wxUSE_COLOURDLG wxColour SelectColour(); #endif // wxUSE_COLOURDLG void PrepareDC(wxDC& dc); int m_backgroundMode; int m_textureBackground; int m_mapMode; double m_xUserScale; double m_yUserScale; int m_xLogicalOrigin; int m_yLogicalOrigin; bool m_xAxisReversed, m_yAxisReversed; wxColour m_colourForeground, // these are _text_ colours m_colourBackground; wxBrush m_backgroundBrush; MyCanvas *m_canvas; private: // any class wishing to process wxWidgets events must use this macro DECLARE_EVENT_TABLE() }; // define a scrollable canvas for drawing onto class MyCanvas: public wxScrolledWindow { public: MyCanvas( MyFrame *parent ); void OnPaint(wxPaintEvent &event); void OnMouseMove(wxMouseEvent &event); void ToShow(ScreenToShow show) { m_show = show; Refresh(); } // set or remove the clipping region void Clip(bool clip) { m_clip = clip; Refresh(); } #if wxUSE_GRAPHICS_CONTEXT void UseGraphicContext(bool use) { m_useContext = use; Refresh(); } #endif protected: void DrawTestLines( int x, int y, int width, wxDC &dc ); void DrawTestPoly(wxDC& dc); void DrawTestBrushes(wxDC& dc); void DrawText(wxDC& dc); void DrawImages(wxDC& dc); void DrawWithLogicalOps(wxDC& dc); #if wxUSE_GRAPHICS_CONTEXT void DrawAlpha(wxDC& dc); #endif void DrawRegions(wxDC& dc); void DrawCircles(wxDC& dc); void DrawSplines(wxDC& dc); void DrawDefault(wxDC& dc); void DrawGradients(wxDC& dc); void DrawRegionsHelper(wxDC& dc, wxCoord x, bool firstTime); private: MyFrame *m_owner; ScreenToShow m_show; wxBitmap m_smile_bmp; wxIcon m_std_icon; bool m_clip; #if wxUSE_GRAPHICS_CONTEXT bool m_useContext ; #endif DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items File_Quit = wxID_EXIT, File_About = wxID_ABOUT, MenuShow_First = wxID_HIGHEST, File_ShowDefault = MenuShow_First, File_ShowText, File_ShowLines, File_ShowBrushes, File_ShowPolygons, File_ShowMask, File_ShowOps, File_ShowRegions, File_ShowCircles, File_ShowSplines, #if wxUSE_GRAPHICS_CONTEXT File_ShowAlpha, #endif File_ShowGradients, MenuShow_Last = File_ShowGradients, File_Clip, #if wxUSE_GRAPHICS_CONTEXT File_GraphicContext, #endif MenuOption_First, MapMode_Text = MenuOption_First, MapMode_Lometric, MapMode_Twips, MapMode_Points, MapMode_Metric, UserScale_StretchHoriz, UserScale_ShrinkHoriz, UserScale_StretchVertic, UserScale_ShrinkVertic, UserScale_Restore, AxisMirror_Horiz, AxisMirror_Vertic, LogicalOrigin_MoveDown, LogicalOrigin_MoveUp, LogicalOrigin_MoveLeft, LogicalOrigin_MoveRight, LogicalOrigin_Set, LogicalOrigin_Restore, #if wxUSE_COLOURDLG Colour_TextForeground, Colour_TextBackground, Colour_Background, #endif // wxUSE_COLOURDLG Colour_BackgroundMode, Colour_TextureBackgound, MenuOption_Last = Colour_TextureBackgound }; #endif // USE_STATUS_WINDOW #endif
[ [ [ 1, 221 ] ], [ [ 222, 222 ] ] ]
c2db8e423cab6580bf85ce5be6444bfb86f9e493
374f53386d36e3aadf0ed88e006394220f732f30
/win/DirectShow/SkeltonMFC/DirectShowSkeltonMFCView.cpp
5ae7d471c9e804d891a878cb502728fcc53fefad
[ "MIT" ]
permissive
yatjf/sonson-code
e7edbc613f8c97be5f7c7367be2660b3cb75a61b
fbb564af37adb2305fe7d2148f8d4f5a3450f72b
refs/heads/master
2020-06-13T08:02:38.469864
2010-07-01T14:20:40
2010-07-01T14:20:40
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
12,560
cpp
// // SkeltonMFC // DirectShowSkeltonMFCView.cpp // // The MIT License // // Copyright (c) 2009 sonson, sonson@Picture&Software // // 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. //// DirectShowSkeltonMFCView.cpp : CDirectShowSkeltonMFCView クラスの動作の定義を行います。 // #include "stdafx.h" #include "DirectShowSkeltonMFC.h" #include "DirectShowSkeltonMFCDoc.h" #include "DirectShowSkeltonMFCView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #pragma comment( lib, "strmBasd.lib" ) // DirectShow #pragma comment( lib, "Quartz.lib" ) // AMGetErrorText()のために必要 ///////////////////////////////////////////////////////////////////////////// // CDirectShowSkeltonMFCView IMPLEMENT_DYNCREATE(CDirectShowSkeltonMFCView, CView) BEGIN_MESSAGE_MAP(CDirectShowSkeltonMFCView, CView) //{{AFX_MSG_MAP(CDirectShowSkeltonMFCView) ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDirectShowSkeltonMFCView クラスの構築/消滅 CDirectShowSkeltonMFCView::CDirectShowSkeltonMFCView() { // TODO: この場所に構築用のコードを追加してください。 m_pGraph = NULL; // グラフ ビルダ m_pMediaCtrl = NULL; // メディア コントロール m_pVideoWindow=NULL; // 描画用のウィンドウ m_pBuilder = NULL; // キャプチャビルダー m_pMediaEvent = NULL; // メディアイベント m_pSrc = NULL; // ソース m_pVideoRenderer = NULL; // レンダラ m_pThrough = NULL; // このプログラムでつかうフィルタ } CDirectShowSkeltonMFCView::~CDirectShowSkeltonMFCView() { ReleaseAll(); CoUninitialize(); // COMの終了 } BOOL CDirectShowSkeltonMFCView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: この位置で CREATESTRUCT cs を修正して Window クラスまたはスタイルを // 修正してください。 cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL); return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CDirectShowSkeltonMFCView クラスの描画 void CDirectShowSkeltonMFCView::OnDraw(CDC* pDC) { CDirectShowSkeltonMFCDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); RECT rect; this->GetWindowRect(&rect); // TODO: この場所にネイティブ データ用の描画コードを追加します。 } ///////////////////////////////////////////////////////////////////////////// // CDirectShowSkeltonMFCView クラスの診断 #ifdef _DEBUG void CDirectShowSkeltonMFCView::AssertValid() const { CView::AssertValid(); } void CDirectShowSkeltonMFCView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CDirectShowSkeltonMFCDoc* CDirectShowSkeltonMFCView::GetDocument() // 非デバッグ バージョンはインラインです。 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDirectShowSkeltonMFCDoc))); return (CDirectShowSkeltonMFCDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CDirectShowSkeltonMFCView クラスのメッセージ ハンドラ ///////////////////////////////////////////////////////////////////////////////////////// // 初期化時のメッセージハンドラ void CDirectShowSkeltonMFCView::OnInitialUpdate() { CView::OnInitialUpdate(); // DirectShowの初期化 if( !InitializeDirectShow()){ // 初期化失敗 ReleaseAll(); CoUninitialize(); // COMの終 this->MessageBox("DirectShowの初期化に失敗しました.\n強制終了します.","",MB_OK); ::PostMessage(this->GetParent()->m_hWnd, WM_CLOSE, 0, 0); // アプリケーション終了 } } ///////////////////////////////////////////////////////////////////////////////////////// // リサイズのメッセージハンドラ void CDirectShowSkeltonMFCView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); // DirectShowのウィンドウが有効化を調べる if( !m_pVideoWindow )return; HRESULT hResult; // ウィンドウを不可視状態にする hResult = m_pVideoWindow->put_Visible(OAFALSE); if (hResult != S_OK)return; // ウィンドウの場所と大きさをセット hResult = m_pVideoWindow->SetWindowPosition(0, 0, cx, cy); if (hResult != S_OK)return; // ウィンドウを可視状態にする hResult = m_pVideoWindow->put_Visible(OATRUE); if (hResult != S_OK)return; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShowフィルタの作成 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::CreateFilters(void){ HRESULT hResult; // Throughフィルタのインスタンスを作成 hResult = CoCreateInstance(CLSID_Through, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void **)&m_pThrough); if (hResult != S_OK)return FALSE; // グラフビルダに追加する hResult = m_pGraph->AddFilter(m_pThrough, L"Through"); if (hResult != S_OK)return FALSE; // VideoRendererのインスタンスを作成 hResult = CoCreateInstance(CLSID_VideoRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void **)&m_pVideoRenderer); if (hResult != S_OK)return FALSE; // グラフビルダに追加する hResult = m_pGraph->AddFilter(m_pVideoRenderer, L"Video Renderer"); if (hResult != S_OK)return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShowフィルタの接続 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::ConectFilters(void){ HRESULT hResult; // ソースのフィルタをThroughフィルタに接続 hResult = m_pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,m_pSrc,0,m_pThrough); if (hResult != S_OK)return FALSE; // ThroughフィルタをVideoRendererに接続 hResult = m_pBuilder->RenderStream( 0, &MEDIATYPE_Video, m_pThrough, NULL, m_pVideoRenderer ); if (hResult != S_OK)return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShow描画領域の設定 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::SetWindow(void){ HRESULT hResult; // グラフビルダからウィンドウを取得する hResult = m_pGraph->QueryInterface(IID_IVideoWindow, (void **) &m_pVideoWindow); if (hResult != S_OK)return FALSE; // ウィンドウのオーナーとなるウィンドウのハンドルを指定する hResult = m_pVideoWindow->put_Owner( (OAHWND)this->m_hWnd ); if (hResult != S_OK)return FALSE; // ウィンドウのスタイルを指定する hResult = m_pVideoWindow->put_WindowStyle(WS_CHILD); if (hResult != S_OK)return FALSE; // ウィンドウの領域サイズを取得し,書き込む範囲を設定する RECT rect; this->GetWindowRect(&rect); hResult = m_pVideoWindow->SetWindowPosition(0, 0, rect.right-rect.left,rect.bottom-rect.top); if (hResult != S_OK)return FALSE; // ウィンドウを可視状態にする hResult = m_pVideoWindow->put_Visible(OATRUE); if (hResult != S_OK)return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShowフィルタの解放 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::ReleaseAll(void){ if(m_pMediaCtrl)m_pMediaCtrl->Stop(); if(m_pGraph)m_pGraph->Release(); if(m_pMediaCtrl)m_pMediaCtrl->Release(); if(m_pSrc)m_pSrc->Release(); if(m_pThrough)m_pThrough->Release(); if(m_pVideoRenderer)m_pVideoRenderer->Release(); if(m_pBuilder)m_pBuilder->Release(); if(m_pVideoWindow)m_pVideoWindow->Release(); if(m_pMediaEvent)m_pMediaEvent->Release(); m_pGraph = NULL; // グラフ ビルダ m_pMediaCtrl = NULL; // メディア コントロール m_pVideoWindow=NULL; // 描画用のウィンドウ m_pBuilder = NULL; // キャプチャビルダー m_pMediaEvent = NULL; // メディアイベント m_pSrc = NULL; // ソース m_pVideoRenderer = NULL; // レンダラ m_pThrough = NULL; // このプログラムでつかうフィルタ return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShowキャプチャデバイスの取得と列挙 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::GetCaptureDevice(IBaseFilter **ppSrcFilter) { HRESULT hResult; // デバイスを列挙する ICreateDevEnum *pDevEnum = NULL; hResult = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC, IID_ICreateDevEnum, (void **)&pDevEnum); if (hResult != S_OK)return FALSE; // 列挙したデバイスの一番目をデバイスとして取得する IEnumMoniker *pClassEnum = NULL; hResult = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pClassEnum, 0); if (hResult != S_OK)return FALSE; // デバイスをフィルタに接続する ULONG cFetched; IMoniker *pMoniker = NULL; if (pClassEnum->Next(1, &pMoniker, &cFetched) == S_OK){ // 最初のモニカをフィルタオブジェクトにバインドする pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void **)ppSrcFilter); pMoniker->Release(); }else return FALSE; // グラフビルダに追加する hResult = m_pGraph->AddFilter(m_pSrc, L"Video Capture"); if (hResult != S_OK)return FALSE; // オブジェクトの片づけ pClassEnum->Release(); pDevEnum->Release(); return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // DirectShowの初期化 ///////////////////////////////////////////////////////////////////////////////////////// BOOL CDirectShowSkeltonMFCView::InitializeDirectShow(void){ HRESULT hResult; hResult = CoInitialize( NULL ); // フィルタグラフ作成 hResult = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, IID_IGraphBuilder, (void **)&m_pGraph); if (hResult != S_OK)return FALSE; // キャプチャデバイス取得 hResult = GetCaptureDevice(&m_pSrc); if (hResult != TRUE)return FALSE; // キャプチャビルダの作成 hResult = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC, IID_ICaptureGraphBuilder2, (void **)&m_pBuilder); if (hResult != S_OK)return FALSE; // グラフにキャプチャビルダをセット hResult = m_pBuilder->SetFiltergraph(m_pGraph); if (hResult != S_OK)return FALSE; // メディアコントロールを取得 m_pGraph->QueryInterface(IID_IMediaControl, (void **)&m_pMediaCtrl); // フィルタの作成 if( !CreateFilters() )return FALSE; // フィルタの接続 if( !ConectFilters() )return FALSE; // ウィンドウのセット if( !SetWindow() )return FALSE; // 処理開始 hResult = m_pMediaCtrl->Run(); return TRUE; }
[ "yoshida.yuichi@0d0a6a56-2bd1-11de-9cad-a3574e5575ef" ]
[ [ [ 1, 341 ] ] ]
716d81546ed725aded6f9a64f1e21db653944a32
852e51ea29da0d06dc0d55c43529d5d976117156
/src/plinks.cpp
40815db88e89a415b6262735d13d5901697c78ed
[]
no_license
hustshego/gt
aaf4b4323ba73a2e89a52068d895aedcc8acc1d1
629681b5605b0af4d46aa865a67416f64fd2e64c
refs/heads/master
2020-12-11T09:05:07.641267
2011-01-10T21:27:08
2011-01-10T21:27:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,729
cpp
#include "plinks.h" using namespace cyclone; Ogre::Real ParticleLink::currentLength() const { Ogre::Vector3 relativePos = particle[0]->getPosition() - particle[1]->getPosition(); return relativePos.length(); } unsigned ParticleCable::addContact(ParticleContact *contact, unsigned limit) const { // Find the length of the cable Ogre::Real length = currentLength(); // Check if we're over-extended if (length < maxLength) { return 0; } // Otherwise return the contact contact->particle[0] = particle[0]; contact->particle[1] = particle[1]; // Calculate the normal Ogre::Vector3 normal = particle[1]->getPosition() - particle[0]->getPosition(); normal.normalise(); contact->contactNormal = normal; contact->penetration = length-maxLength; contact->restitution = restitution; return 1; } unsigned ParticleRod::addContact(ParticleContact *contact, unsigned limit) const { // Find the length of the rod Ogre::Real currentLen = currentLength(); // Check if we're over-extended if (currentLen == length) { return 0; } // Otherwise return the contact contact->particle[0] = particle[0]; contact->particle[1] = particle[1]; // Calculate the normal Ogre::Vector3 normal = particle[1]->getPosition() - particle[0]->getPosition(); normal.normalise(); // The contact normal depends on whether we're extending or compressing if (currentLen > length) { contact->contactNormal = normal; contact->penetration = currentLen - length; } else { contact->contactNormal = normal * -1; contact->penetration = length - currentLen; } // Always use zero restitution (no bounciness) contact->restitution = 0; return 1; } Ogre::Real ParticleConstraint::currentLength() const { Ogre::Vector3 relativePos = particle->getPosition() - anchor; return relativePos.length(); } unsigned ParticleCableConstraint::addContact(ParticleContact *contact, unsigned limit) const { // Find the length of the cable Ogre::Real length = currentLength(); // Check if we're over-extended if (length < maxLength) { return 0; } // Otherwise return the contact contact->particle[0] = particle; contact->particle[1] = 0; // Calculate the normal Ogre::Vector3 normal = anchor - particle->getPosition(); normal.normalise(); contact->contactNormal = normal; contact->penetration = length-maxLength; contact->restitution = restitution; return 1; } unsigned ParticleRodConstraint::addContact(ParticleContact *contact, unsigned limit) const { // Find the length of the rod Ogre::Real currentLen = currentLength(); // Check if we're over-extended if (currentLen == length) { return 0; } // Otherwise return the contact contact->particle[0] = particle; contact->particle[1] = 0; // Calculate the normal Ogre::Vector3 normal = anchor - particle->getPosition(); normal.normalise(); // The contact normal depends on whether we're extending or compressing if (currentLen > length) { contact->contactNormal = normal; contact->penetration = currentLen - length; } else { contact->contactNormal = normal * -1; contact->penetration = length - currentLen; } // Always use zero restitution (no bounciness) contact->restitution = 0; return 1; } //-------------------------------------------------------------- unsigned ParticleSeperation::addContact(ParticleContact *contact, unsigned limit) const { // Find the length of the rod Ogre::Real currentLen = currentLength(); // Check if we're over-extended if (currentLen >= length) { return 0; } // Otherwise return the contact contact->particle[0] = particle[0]; contact->particle[1] = particle[1]; // Calculate the normal Ogre::Vector3 normal = particle[1]->getPosition() - particle[0]->getPosition(); normal.normalise(); // The contact normal depends on whether we're extending or compressing if (currentLen < length) { contact->contactNormal = normal * -1; contact->penetration = length - currentLen; } // Always use zero restitution (no bounciness) contact->restitution = 0; return 1; }
[ [ [ 1, 176 ] ] ]
1e2c8ef07d1f53d68b63cf5339cad8bc4f6389eb
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/read_bidir_filter_test.hpp
631d25a93b8511117f41e6ac0d6575651fa67102
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
4,886
hpp
// (C) Copyright Jonathan Turkanis 2004 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_FILTER_HPP_INCLUDED #define BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_FILTER_HPP_INCLUDED #include <fstream> #include <boost/iostreams/combine.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/test/test_tools.hpp> #include "detail/filters.hpp" #include "detail/sequence.hpp" #include "detail/temp_file.hpp" #include "detail/verification.hpp" void read_bidirectional_filter_test() { using namespace std; using namespace boost; using namespace boost::iostreams; using namespace boost::iostreams::test; uppercase_file upper; //{ // test_file src; // temp_file dest; // Dummy. // filtering_stream<bidirectional> first; // first.push(combine(toupper_filter(), tolower_filter())); // first.push( // combine(file_source(src.name()), file_sink(dest.name())) // ); // ifstream second(upper.name().c_str()); // BOOST_CHECK_MESSAGE( // compare_streams_in_chars(first, second), // "failed reading from filtering_stream<bidirectional> in chars with an " // "input filter" // ); //} { test_file src; temp_file dest; // Dummy. filtering_stream<bidirectional> first; first.push(combine(toupper_filter(), tolower_filter())); first.push( combine(file_source(src.name()), file_sink(dest.name())) ); ifstream second(upper.name().c_str()); BOOST_CHECK_MESSAGE( compare_streams_in_chunks(first, second), "failed reading from filtering_stream<bidirectional> in chunks with an " "input filter" ); } //{ // test_file src; // temp_file dest; // Dummy. // filtering_stream<bidirectional> first( // combine(toupper_multichar_filter(), tolower_filter()), 0 // ); // first.push( // combine(file_source(src.name()), file_sink(dest.name())) // ); // ifstream second(upper.name().c_str()); // BOOST_CHECK_MESSAGE( // compare_streams_in_chars(first, second), // "failed reading from filtering_stream<bidirectional> in chars with " // "a multichar input filter with no buffer" // ); //} //{ // test_file src; // temp_file dest; // Dummy. // filtering_stream<bidirectional> first( // combine(toupper_multichar_filter(), tolower_filter()), 0 // ); // first.push( // combine(file_source(src.name()), file_sink(dest.name())) // ); // ifstream second(upper.name().c_str()); // BOOST_CHECK_MESSAGE( // compare_streams_in_chunks(first, second), // "failed reading from filtering_stream<bidirectional> in chunks " // "with a multichar input filter with no buffer" // ); //} //{ // test_file src; // temp_file dest; // Dummy. // filtering_stream<bidirectional> first( // combine(toupper_multichar_filter(), tolower_filter()) // ); // first.push( // combine(file_source(src.name()), file_sink(dest.name())) // ); // ifstream second(upper.name().c_str()); // BOOST_CHECK_MESSAGE( // compare_streams_in_chars(first, second), // "failed reading from filtering_stream<bidirectional> in chars with a " // "multichar input filter" // ); //} //{ // test_file src; // temp_file dest; // Dummy. // filtering_stream<bidirectional> first( // combine(toupper_multichar_filter(), tolower_filter()) // ); // first.push( // combine(file_source(src.name()), file_sink(dest.name())) // ); // ifstream second(upper.name().c_str()); // BOOST_CHECK_MESSAGE( // compare_streams_in_chunks(first, second), // "failed reading from filtering_stream<bidirectional> in chunks " // "with a multichar input filter" // ); //} } #endif // #ifndef BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_FILTER_HPP_INCLUDED
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 130 ] ] ]
fb78de118de1de3b8b2b09dfbdc07ebd3ce8cd8a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/regex/v4/regex_workaround.hpp
d69f4433b6481dca1a741743d6ca71dd438cf8eb
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
4,972
hpp
/* * * Copyright (c) 1998-2005 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE regex_workarounds.cpp * VERSION see <boost/version.hpp> * DESCRIPTION: Declares Misc workarounds. */ #ifndef BOOST_REGEX_WORKAROUND_HPP #define BOOST_REGEX_WORKAROUND_HPP #include <new> #include <cstring> #include <cstdlib> #include <cstddef> #include <cassert> #include <cstdio> #include <string> #include <stdexcept> #include <iterator> #include <algorithm> #include <iosfwd> #include <vector> #include <map> #include <boost/limits.hpp> #include <boost/assert.hpp> #include <boost/cstdint.hpp> #include <boost/throw_exception.hpp> #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> #include <boost/shared_ptr.hpp> #include <boost/mpl/bool_fwd.hpp> #ifndef BOOST_NO_STD_LOCALE # include <locale> #endif #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::sprintf; using ::strcpy; using ::strcat; using ::strlen; } #endif namespace boost{ namespace re_detail{ #ifdef BOOST_NO_STD_DISTANCE template <class T> std::ptrdiff_t distance(const T& x, const T& y) { return y - x; } #else using std::distance; #endif }} #ifdef BOOST_REGEX_NO_BOOL # define BOOST_REGEX_MAKE_BOOL(x) static_cast<bool>((x) ? true : false) #else # ifdef BOOST_MSVC // warning suppression with VC6: # pragma warning(disable: 4800) # pragma warning(disable: 4786) # endif # define BOOST_REGEX_MAKE_BOOL(x) static_cast<bool>(x) #endif /***************************************************************************** * * Fix broken broken namespace support: * ****************************************************************************/ #if defined(BOOST_NO_STDC_NAMESPACE) && defined(__cplusplus) namespace std{ using ::ptrdiff_t; using ::size_t; using ::abs; using ::memset; using ::memcpy; } #endif /***************************************************************************** * * helper functions pointer_construct/pointer_destroy: * ****************************************************************************/ #ifdef __cplusplus namespace boost{ namespace re_detail{ #ifdef BOOST_MSVC #pragma warning (push) #pragma warning (disable : 4100) #endif template <class T> inline void pointer_destroy(T* p) { p->~T(); (void)p; } #ifdef BOOST_MSVC #pragma warning (pop) #endif template <class T> inline void pointer_construct(T* p, const T& t) { new (p) T(t); } }} // namespaces #endif /***************************************************************************** * * helper function copy: * ****************************************************************************/ #ifdef __cplusplus namespace boost{ namespace re_detail{ #if BOOST_WORKAROUND(BOOST_MSVC,>=1400) && defined(_CPPLIB_VER) && !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) // // MSVC 8 will either emit warnings or else refuse to compile // code that makes perfectly legitimate use of std::copy, when // the OutputIterator type is a user-defined class (apparently all user // defined iterators are "unsafe"). This code works around that: // template<class InputIterator, class OutputIterator> inline OutputIterator copy( InputIterator first, InputIterator last, OutputIterator dest ) { return stdext::unchecked_copy(first, last, dest); } template<class InputIterator1, class InputIterator2> inline bool equal( InputIterator1 first, InputIterator1 last, InputIterator2 with ) { return stdext::unchecked_equal(first, last, with); } // use safe versions of strcpy etc: using ::strcpy_s; using ::strcat_s; #else using std::copy; using std::equal; inline std::size_t strcpy_s( char *strDestination, std::size_t sizeInBytes, const char *strSource ) { if(std::strlen(strSource)+1 > sizeInBytes) return 1; std::strcpy(strDestination, strSource); return 0; } inline std::size_t strcat_s( char *strDestination, std::size_t sizeInBytes, const char *strSource ) { if(std::strlen(strSource) + std::strlen(strDestination) + 1 > sizeInBytes) return 1; std::strcat(strDestination, strSource); return 0; } #endif inline void overflow_error_if_not_zero(std::size_t i) { if(i) { std::overflow_error e("String buffer too small"); boost::throw_exception(e); } } }} // namespaces #endif #endif // include guard
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 202 ] ] ]
8ea7b5acc7929fdca4af2b03bb7f3edca7c2d8b2
80716d408715377e88de1fc736c9204b87a12376
/TspLib3/Src/spdll_notrace.cpp
c80855d69942c4341d0216ea85c29c72aaa095b9
[]
no_license
junction/jn-tapi
b5cf4b1bb010d696473cabcc3d5950b756ef37e9
a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4
refs/heads/master
2021-03-12T23:38:01.037779
2011-03-10T01:08:40
2011-03-10T01:08:40
199,317
2
2
null
null
null
null
UTF-8
C++
false
false
67,620
cpp
/******************************************************************************/ // // SPDLL_NOTRACE.CPP - Service Provider DLL shell. // // Copyright (C) 1994-2000 JulMar Entertainment Technology, Inc. // All rights reserved // // This module disables the JTTSPTRC.DLL tracing support. // // This source code is intended only as a supplement to the // TSP++ Class Library product documentation. This source code cannot // be used in part or whole in any form outside the TSP++ library. // /******************************************************************************/ /*---------------------------------------------------------------------------*/ // INCLUDE FILES /*---------------------------------------------------------------------------*/ #include "stdafx.h" #include "tsplayer.h" #pragma warning(disable:4100) // Unreferenced formal parameter warning /*---------------------------------------------------------------------------*/ // CONSTANTS /*---------------------------------------------------------------------------*/ #undef DLLEXPORT #define DLLEXPORT extern "C" /******************************************************************************/ // // TSPIAPI TSPI_line functions // /******************************************************************************/ /////////////////////////////////////////////////////////////////////////// // TSPI_lineAccept // // This function accepts the specified offering call. It may optionally // send the specified User->User information to the calling party. // DLLEXPORT LONG TSPIAPI TSPI_lineAccept (DRV_REQUESTID dwRequestId, HDRVCALL hdCall, LPCSTR lpsUserUserInfo, DWORD dwSize) { return tsplib_lineAccept(dwRequestId, hdCall, lpsUserUserInfo, dwSize); }// TSPI_lineAccept /////////////////////////////////////////////////////////////////////////// // TSPI_lineAddToConference // // This function adds the specified call (hdConsultCall) to the // conference (hdConfCall). // DLLEXPORT LONG TSPIAPI TSPI_lineAddToConference (DRV_REQUESTID dwRequestId, HDRVCALL hdConfCall, HDRVCALL hdConsultCall) { return tsplib_lineAddToConference(dwRequestId, hdConfCall,hdConsultCall); }// TSPI_lineAddToConference /////////////////////////////////////////////////////////////////////////// // TSPI_lineAnswer // // This function answers the specified offering call. // DLLEXPORT LONG TSPIAPI TSPI_lineAnswer (DRV_REQUESTID dwRequestId, HDRVCALL hdCall, LPCSTR lpsUserUserInfo, DWORD dwSize) { return tsplib_lineAnswer(dwRequestId, hdCall, lpsUserUserInfo, dwSize); }// TSPI_lineAnswer /////////////////////////////////////////////////////////////////////////// // TSPI_lineBlindTransfer // // This function performs a blind or single-step transfer of the // specified call to the specified destination address. // DLLEXPORT LONG TSPIAPI TSPI_lineBlindTransfer (DRV_REQUESTID dwRequestId, HDRVCALL hdCall, LPCWSTR lpszDestAddr, DWORD dwCountryCode) { return tsplib_lineBlindTransfer(dwRequestId, hdCall, lpszDestAddr, dwCountryCode); }// TSPI_lineBlindTransfer //////////////////////////////////////////////////////////////////////////// // TSPI_lineClose // // This function closes the specified open line after stopping all // asynchronous requests on the line. // DLLEXPORT LONG TSPIAPI TSPI_lineClose (HDRVLINE hdLine) { return tsplib_lineClose(hdLine); }// TSPI_lineClose //////////////////////////////////////////////////////////////////////////// // TSPI_lineCloseCall // // This function closes the specified call. The HDRVCALL handle will // no longer be valid after this call. // DLLEXPORT LONG TSPIAPI TSPI_lineCloseCall (HDRVCALL hdCall) { return tsplib_lineCloseCall(hdCall); }// TSPI_lineCloseCall #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineCloseMSPInstance // // This function closes an MSP call instance. This function // requires TAPI 3.0 negotiation. // DLLEXPORT LONG TSPIAPI TSPI_lineCloseMSPInstance(HDRVMSPLINE hdMSPLine) { return tsplib_lineCloseMSPInstance(hdMSPLine); }// TSPI_lineCloseMSPInstance #endif /////////////////////////////////////////////////////////////////////////// // TSPI_lineCompleteCall // // This function is used to specify how a call that could not be // connected normally should be completed instead. The network or // switch may not be able to complete a call because the network // resources are busy, or the remote station is busy or doesn't answer. // DLLEXPORT LONG TSPIAPI TSPI_lineCompleteCall (DRV_REQUESTID dwRequestId, HDRVCALL hdCall, LPDWORD lpdwCompletionID, DWORD dwCompletionMode, DWORD dwMessageID) { return tsplib_lineCompleteCall(dwRequestId, hdCall, lpdwCompletionID, dwCompletionMode, dwMessageID); }// TSPI_lineCompleteCall /////////////////////////////////////////////////////////////////////////// // TSPI_lineCompleteTransfer // // This function completes the transfer of the specified call to the // party connected in the consultation call. If 'dwTransferMode' is // LINETRANSFERMODE_CONFERENCE, the original call handle is changed // to a conference call. Otherwise, the service provider should send // callstate messages change all the calls to idle. // DLLEXPORT LONG TSPIAPI TSPI_lineCompleteTransfer (DRV_REQUESTID dwRequestId, HDRVCALL hdCall, HDRVCALL hdConsultCall, HTAPICALL htConfCall, LPHDRVCALL lphdConfCall, DWORD dwTransferMode) { return tsplib_lineCompleteTransfer(dwRequestId, hdCall, hdConsultCall, htConfCall, lphdConfCall, dwTransferMode); }// TSPI_lineCompleteTransfer //////////////////////////////////////////////////////////////////////////// // TSPI_lineConditionalMediaDetection // // This function is invoked by TAPI.DLL when the application requests a // line open using the LINEMAPPER. This function will check the // requested media modes and return an acknowledgement based on whether // we can monitor all the requested modes. // DLLEXPORT LONG TSPIAPI TSPI_lineConditionalMediaDetection (HDRVLINE hdLine, DWORD dwMediaModes, LPLINECALLPARAMS const lpCallParams) { return tsplib_lineConditionalMediaDetection(hdLine, dwMediaModes, lpCallParams); }// TSPI_lineConditionalMediaDetection #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineCreateMSPInstance // // This function creates a media service provider instance for a specific // line device. This function returns a TSP handle for the MSP call. It // requires TAPI 3.0 negotiation. // DLLEXPORT LONG TSPIAPI TSPI_lineCreateMSPInstance(HDRVLINE hdLine, DWORD dwAddressID, HTAPIMSPLINE htMSPLine, LPHDRVMSPLINE lphdMSPLine) { return tsplib_lineCreateMSPInstance(hdLine, dwAddressID, htMSPLine, lphdMSPLine); }// TSPI_lineCreateMSPInstance #endif /////////////////////////////////////////////////////////////////////////// // TSPI_lineDevSpecific // // This function is used as a general extension mechanims to allow // service providers to provide access to features not described in // other operations. // DLLEXPORT LONG TSPIAPI TSPI_lineDevSpecific(DRV_REQUESTID dwRequestId, HDRVLINE hdLine, DWORD dwAddressId, HDRVCALL hdCall, LPVOID lpParams, DWORD dwSize) { return tsplib_lineDevSpecific(dwRequestId, hdLine, dwAddressId, hdCall, lpParams, dwSize); }// TSPI_lineDevSpecific /////////////////////////////////////////////////////////////////////////// // TSPI_lineDevSpecificFeature // // This function is used as an extension mechanism to enable service // providers to provide access to features not described in other // operations. // DLLEXPORT LONG TSPIAPI TSPI_lineDevSpecificFeature (DRV_REQUESTID dwRequestId, HDRVLINE hdLine, DWORD dwFeature, LPVOID lpParams, DWORD dwSize) { return tsplib_lineDevSpecificFeature(dwRequestId, hdLine, dwFeature, lpParams, dwSize); }// TSPI_lineDevSpecificFeature /////////////////////////////////////////////////////////////////////////// // TSPI_lineDial // // This function dials the specified dialable number on the specified // call device. // DLLEXPORT LONG TSPIAPI TSPI_lineDial (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPCWSTR lpszDestAddress, DWORD dwCountryCode) { return tsplib_lineDial(dwRequestID, hdCall, lpszDestAddress, dwCountryCode); }// TSPI_lineDial //////////////////////////////////////////////////////////////////////////// // TSPI_lineDrop // // This function disconnects the specified call. The call is still // valid and should be closed by the application following this API. // DLLEXPORT LONG TSPIAPI TSPI_lineDrop (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPCSTR lpsUserUserInfo, DWORD dwSize) { return tsplib_lineDrop(dwRequestID, hdCall, lpsUserUserInfo, dwSize); }// TSPI_lineDrop /////////////////////////////////////////////////////////////////////////// // TSPI_lineForward // // This function forwards calls destined for the specified address on // the specified line, according to the specified forwarding instructions. // When an origination address is forwarded, the incoming calls for that // address are deflected to the other number by the switch. This function // provides a combination of forward and do-not-disturb features. This // function can also cancel specific forwarding currently in effect. // DLLEXPORT LONG TSPIAPI TSPI_lineForward (DRV_REQUESTID dwRequestId, HDRVLINE hdLine, DWORD bAllAddresses, DWORD dwAddressId, LPLINEFORWARDLIST const lpForwardList, DWORD dwNumRingsAnswer, HTAPICALL htConsultCall, LPHDRVCALL lphdConsultCall, LPLINECALLPARAMS const lpCallParams) { return tsplib_lineForward(dwRequestId, hdLine, bAllAddresses, dwAddressId, lpForwardList, dwNumRingsAnswer, htConsultCall, lphdConsultCall, lpCallParams); }// TSPI_lineForward /////////////////////////////////////////////////////////////////////////// // TSPI_lineGatherDigits // // This function initiates the buffered gathering of digits on the // specified call. TAPI.DLL specifies a buffer in which to place the digits, // and the maximum number of digits to be collected. // // Digit collection may be terminated in the following ways: // // (1) The requested number of digits is collected. // // (2) One of the digits detected matches a digit in 'szTerminationDigits' // before the specified number of digits is collected. The detected // termination digit is added to the buffer and the buffer is returned. // // (3) One of the timeouts expires. The 'dwFirstDigitTimeout' expires if // the first digit is not received in this time period. The // 'dwInterDigitTimeout' expires if the second, third (and so on) digit // is not received within that time period, and a partial buffer is // returned. // // (4) Calling this function again while digit gathering is in process. // The old collection session is terminated, and the contents is // undefined. The mechanism for canceling without restarting this // event is to invoke this function with 'lpszDigits' equal to NULL. // DLLEXPORT LONG TSPIAPI TSPI_lineGatherDigits (HDRVCALL hdCall, DWORD dwEndToEnd, DWORD dwDigitModes, LPWSTR lpszDigits, DWORD dwNumDigits, LPCWSTR lpszTerminationDigits, DWORD dwFirstDigitTimeout, DWORD dwInterDigitTimeout) { return tsplib_lineGatherDigits(hdCall, dwEndToEnd, dwDigitModes, lpszDigits, dwNumDigits, lpszTerminationDigits, dwFirstDigitTimeout, dwInterDigitTimeout); }// TSPI_lineGatherDigits /////////////////////////////////////////////////////////////////////////// // TSPI_lineGenerateDigits // // This function initiates the generation of the specified digits // using the specified signal mode. // DLLEXPORT LONG TSPIAPI TSPI_lineGenerateDigits (HDRVCALL hdCall, DWORD dwEndToEndID, DWORD dwDigitMode, LPCWSTR lpszDigits, DWORD dwDuration) { return tsplib_lineGenerateDigits(hdCall, dwEndToEndID, dwDigitMode, lpszDigits, dwDuration); }// TSPI_lineGenerateDigits /////////////////////////////////////////////////////////////////////////// // TSPI_lineGenerateTone // // This function generates the specified tone inband over the specified // call. Invoking this function with a zero for 'dwToneMode' aborts any // tone generation currently in progress on the specified call. // Invoking 'lineGenerateTone' or 'lineGenerateDigit' also aborts the // current tone generation and initiates the generation of the newly // specified tone or digits. // DLLEXPORT LONG TSPIAPI TSPI_lineGenerateTone (HDRVCALL hdCall, DWORD dwEndToEnd, DWORD dwToneMode, DWORD dwDuration, DWORD dwNumTones, LPLINEGENERATETONE const lpTones) { return tsplib_lineGenerateTone(hdCall, dwEndToEnd, dwToneMode, dwDuration, dwNumTones, lpTones); }// TSPI_lineGenerateTone /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAddressCaps // // This function queries the specified address on the specified // line device to determine its telephony capabilities. // DLLEXPORT LONG TSPIAPI TSPI_lineGetAddressCaps (DWORD dwDeviceID, DWORD dwAddressID, DWORD dwTSPIVersion, DWORD dwExtVersion, LPLINEADDRESSCAPS lpAddressCaps) { return tsplib_lineGetAddressCaps(dwDeviceID, dwAddressID, dwTSPIVersion, dwExtVersion, lpAddressCaps); }// TSPI_lineGetAddressCaps /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAddressID // // This function returns the specified address associated with the // specified line in a specified format. // DLLEXPORT LONG TSPIAPI TSPI_lineGetAddressID (HDRVLINE hdLine, LPDWORD lpdwAddressID, DWORD dwAddressMode, LPCWSTR lpszAddress, DWORD dwSize) { return tsplib_lineGetAddressID(hdLine, lpdwAddressID, dwAddressMode, lpszAddress, dwSize); }// TSPI_lineGetAddressID /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetCallIDs // // This function retrieves call-id information for this call. It is used // by TAPI as a quick way to retrieve call-id information rather than // using the full lineGetCallInfo function. // // TAPI 2.2 and 3.0 // DLLEXPORT LONG TSPIAPI TSPI_lineGetCallIDs(HDRVCALL hdCall, LPDWORD lpdwAddressID, LPDWORD lpdwCallID, LPDWORD lpdwRelatedCallID) { return tsplib_lineGetCallIDs(hdCall, lpdwAddressID, lpdwCallID, lpdwRelatedCallID); }// TSPI_lineGetCallIDs /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAddressStatus // // This function queries the specified address for its current status. // DLLEXPORT LONG TSPIAPI TSPI_lineGetAddressStatus (HDRVLINE hdLine, DWORD dwAddressID, LPLINEADDRESSSTATUS lpAddressStatus) { return tsplib_lineGetAddressStatus(hdLine, dwAddressID, lpAddressStatus); }// TSPI_lineGetAddressStatus /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetCallAddressID // // This function retrieves the address for the specified call. // DLLEXPORT LONG TSPIAPI TSPI_lineGetCallAddressID (HDRVCALL hdCall, LPDWORD lpdwAddressID) { return tsplib_lineGetCallAddressID(hdCall, lpdwAddressID); }// TSPI_lineGetCallAddressID #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetCallHubTracking // // This function retrieves the call hub tracking support structure (TAPI 3.0) // DLLEXPORT LONG TSPIAPI TSPI_lineGetCallHubTracking(HDRVLINE hdLine, LPLINECALLHUBTRACKINGINFO lpTrackingInfo) { return tsplib_lineGetCallHubTracking(hdLine, lpTrackingInfo); }// TSPI_lineGetCallHubTracking #endif /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetCallInfo // // This function retrieves the telephony information for the specified // call handle. // DLLEXPORT LONG TSPIAPI TSPI_lineGetCallInfo (HDRVCALL hdCall, LPLINECALLINFO lpCallInfo) { return tsplib_lineGetCallInfo(hdCall, lpCallInfo); }// TSPI_lineGetCallInfo /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetCallStatus // // This function retrieves the status for the specified call. // DLLEXPORT LONG TSPIAPI TSPI_lineGetCallStatus (HDRVCALL hdCall, LPLINECALLSTATUS lpCallStatus) { return tsplib_lineGetCallStatus(hdCall, lpCallStatus); }// TSPI_lineGetCallStatus /////////////////////////////////////////////////////////////////////////// // TSPI_lineGetDevCaps // // This function retrieves the telephony device capabilties for the // specified line. This information is valid for all addresses on // the line. // DLLEXPORT LONG TSPIAPI TSPI_lineGetDevCaps (DWORD dwDeviceID, DWORD dwTSPIVersion, DWORD dwExtVersion, LPLINEDEVCAPS lpLineDevCaps) { return tsplib_lineGetDevCaps(dwDeviceID, dwTSPIVersion, dwExtVersion, lpLineDevCaps); }// TSPI_lineGetDevCaps ////////////////////////////////////////////////////////////////////////// // TSPI_lineGetDevConfig // // This function returns a data structure object, the contents of which // are specific to the line (SP) and device class, giving the current // configuration of a device associated one-to-one with the line device. // DLLEXPORT LONG TSPIAPI TSPI_lineGetDevConfig (DWORD dwDeviceID, LPVARSTRING lpDeviceConfig, LPCWSTR lpszDeviceClass) { return tsplib_lineGetDevConfig(dwDeviceID, lpDeviceConfig, lpszDeviceClass); }// TSPI_lineGetDevConfig ////////////////////////////////////////////////////////////////////////// // TSPI_lineGetExtensionID // // This function returns the extension ID that the service provider // supports for the indicated line device. // DLLEXPORT LONG TSPIAPI TSPI_lineGetExtensionID (DWORD dwDeviceID, DWORD dwTSPIVersion, LPLINEEXTENSIONID lpExtensionID) { return tsplib_lineGetExtensionID(dwDeviceID, dwTSPIVersion, lpExtensionID); }// TSPI_lineGetExtensionID ////////////////////////////////////////////////////////////////////////// // TSPI_lineGetIcon // // This function retreives a service line device-specific icon for // display to the user // DLLEXPORT LONG TSPIAPI TSPI_lineGetIcon (DWORD dwDeviceID, LPCWSTR lpszDeviceClass, LPHICON lphIcon) { return tsplib_lineGetIcon(dwDeviceID, lpszDeviceClass, lphIcon); }// TSPI_lineGetIcon ////////////////////////////////////////////////////////////////////////// // TSPI_lineGetID // // This function returns a device id for the specified // device class associated with the specified line, address, or call // handle. // DLLEXPORT LONG TSPIAPI TSPI_lineGetID (HDRVLINE hdLine, DWORD dwAddressID, HDRVCALL hdCall, DWORD dwSelect, LPVARSTRING lpVarString, LPCWSTR lpszDeviceClass, HANDLE hTargetProcess) { return tsplib_lineGetID(hdLine, dwAddressID, hdCall, dwSelect, lpVarString, lpszDeviceClass, hTargetProcess); }// TSPI_lineGetID //////////////////////////////////////////////////////////////////////////// // TSPI_lineGetLineDevStatus // // This function queries the specified open line for its status. The // information is valid for all addresses on the line. // DLLEXPORT LONG TSPIAPI TSPI_lineGetLineDevStatus (HDRVLINE hdLine, LPLINEDEVSTATUS lpLineDevStatus) { return tsplib_lineGetLineDevStatus(hdLine, lpLineDevStatus); }// TSPI_lineGetLineDevStatus //////////////////////////////////////////////////////////////////////////// // TSPI_lineGetNumAddressIDs // // This function returns the number of addresses availble on a line. // DLLEXPORT LONG TSPIAPI TSPI_lineGetNumAddressIDs (HDRVLINE hdLine, LPDWORD lpNumAddressIDs) { return tsplib_lineGetNumAddressIDs(hdLine, lpNumAddressIDs); }// TSPI_lineGetNumAddressIDs //////////////////////////////////////////////////////////////////////////// // TSPI_lineHold // // This function places the specified call appearance on hold. // DLLEXPORT LONG TSPIAPI TSPI_lineHold (DRV_REQUESTID dwRequestID, HDRVCALL hdCall) { return tsplib_lineHold(dwRequestID, hdCall); }// TSPI_lineHold //////////////////////////////////////////////////////////////////////////// // TSPI_lineMakeCall // // This function places a call on the specified line to the specified // address. // DLLEXPORT LONG TSPIAPI TSPI_lineMakeCall (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, HTAPICALL htCall, LPHDRVCALL lphdCall, LPCWSTR lpszDestAddress, DWORD dwCountryCode, LPLINECALLPARAMS const lpCallParams) { return tsplib_lineMakeCall(dwRequestID, hdLine, htCall, lphdCall, lpszDestAddress, dwCountryCode, lpCallParams); }// TSPI_lineMakeCall /////////////////////////////////////////////////////////////////////////// // TSPI_lineMonitorDigits // // This function enables and disables the unbuffered detection of digits // received on the call. Each time a digit of the specified digit mode(s) // is detected, a LINE_MONITORDIGITS message is sent to the application by // TAPI.DLL, indicating which digit was detected. // DLLEXPORT LONG TSPIAPI TSPI_lineMonitorDigits (HDRVCALL hdCall, DWORD dwDigitModes) { return tsplib_lineMonitorDigits(hdCall, dwDigitModes); }// TSPI_lineMonitorDigits /////////////////////////////////////////////////////////////////////////// // TSPI_lineMonitorMedia // // This function enables and disables the detection of media modes on // the specified call. When a media mode is detected, a LINE_MONITORMEDIA // message is sent to TAPI.DLL. // DLLEXPORT LONG TSPIAPI TSPI_lineMonitorMedia (HDRVCALL hdCall, DWORD dwMediaModes) { return tsplib_lineMonitorMedia(hdCall, dwMediaModes); }// TSPI_lineMonitorMedia /////////////////////////////////////////////////////////////////////////// // TSPI_lineMonitorTones // // This function enables and disables the detection of inband tones on // the call. Each time a specified tone is detected, a message is sent // to the client application through TAPI.DLL // DLLEXPORT LONG TSPIAPI TSPI_lineMonitorTones (HDRVCALL hdCall, DWORD dwToneListID, LPLINEMONITORTONE const lpToneList, DWORD dwNumEntries) { return tsplib_lineMonitorTones(hdCall, dwToneListID, lpToneList, dwNumEntries); }// TSPI_lineMonitorTones #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineMSPIdentify // // This function determines the associated MSP CLSID for each line // device. This function requires TAPI 3.0 negotiation. // DLLEXPORT LONG TSPIAPI TSPI_lineMSPIdentify(DWORD dwDeviceID, GUID* pCLSID) { return tsplib_lineMSPIdentify(dwDeviceID, pCLSID); } #endif /////////////////////////////////////////////////////////////////////////// // TSPI_lineNegotiateExtVersion // // This function returns the highest extension version number the SP is // willing to operate under for the device given the range of possible // extension versions. // DLLEXPORT LONG TSPIAPI TSPI_lineNegotiateExtVersion (DWORD dwDeviceID, DWORD dwTSPIVersion, DWORD dwLowVersion, DWORD dwHiVersion, LPDWORD lpdwExtVersion) { return tsplib_lineNegotiateExtVersion(dwDeviceID, dwTSPIVersion, dwLowVersion, dwHiVersion, lpdwExtVersion); }// TSPI_lineNegotiateExtVersion /////////////////////////////////////////////////////////////////////////// // TSPI_lineNegotiateTSPIVersion // // This function is called to negotiate line versions for the TSP // driver. // DLLEXPORT LONG TSPIAPI TSPI_lineNegotiateTSPIVersion (DWORD dwDeviceID, DWORD dwLowVersion, DWORD dwHighVersion, LPDWORD lpdwTSPIVersion) { return tsplib_lineNegotiateTSPIVersion(dwDeviceID, dwLowVersion, dwHighVersion, lpdwTSPIVersion); }// TSPI_lineNegotiateTSPIVersion //////////////////////////////////////////////////////////////////////////// // TSPI_lineOpen // // This function opens the specified line device based on the device // id passed and returns a handle for the line. The TAPI.DLL line // handle must also be retained for further interaction with this // device. // DLLEXPORT LONG TSPIAPI TSPI_lineOpen (DWORD dwDeviceID, HTAPILINE htLine, LPHDRVLINE lphdLine, DWORD dwTSPIVersion, LINEEVENT lpfnEventProc) { return tsplib_lineOpen(dwDeviceID, htLine, lphdLine, dwTSPIVersion, lpfnEventProc); }// TSPI_lineOpen ////////////////////////////////////////////////////////////////////////////// // TSPI_linePark // // This function parks the specified call according to the specified // park mode. // DLLEXPORT LONG TSPIAPI TSPI_linePark (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, DWORD dwParkMode, LPCWSTR lpszDirAddr, LPVARSTRING lpNonDirAddress) { return tsplib_linePark(dwRequestID, hdCall, dwParkMode, lpszDirAddr, lpNonDirAddress); }// TSPI_linePark /////////////////////////////////////////////////////////////////////////////// // TSPI_linePickup // // This function picks up a call alerting at the specified destination // address and returns a call handle for the picked up call. If invoked // with a NULL for the 'lpszDestAddr' parameter, a group pickup is performed. // If required by the device capabilities, 'lpszGroupID' specifies the // group ID to which the alerting station belongs. // DLLEXPORT LONG TSPIAPI TSPI_linePickup (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, DWORD dwAddressID, HTAPICALL htCall, LPHDRVCALL lphdCall, LPCWSTR lpszDestAddr, LPCWSTR lpszGroupID) { return tsplib_linePickup(dwRequestID, hdLine, dwAddressID, htCall, lphdCall, lpszDestAddr, lpszGroupID); }// TSPI_linePickup //////////////////////////////////////////////////////////////////////////////// // TSPI_linePrepareAddToConference // // This function prepares an existing conference call for the addition of // another party. It creates a new temporary consultation call. The new // consultation call can subsequently be added to the conference call. // DLLEXPORT LONG TSPIAPI TSPI_linePrepareAddToConference (DRV_REQUESTID dwRequestID, HDRVCALL hdConfCall, HTAPICALL htConsultCall, LPHDRVCALL lphdConsultCall, LPLINECALLPARAMS const lpCallParams) { return tsplib_linePrepareAddToConference(dwRequestID, hdConfCall, htConsultCall, lphdConsultCall, lpCallParams); }// TSPI_linePrepareAddToConference #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineReceiveMSPData // // This function receives data sent by a media service provider (MSP). // It requires TAPI 3.0 negotiation. // DLLEXPORT LONG TSPIAPI TSPI_lineReceiveMSPData(HDRVLINE hdLine, HDRVCALL hdCall, HDRVMSPLINE hdMSPLine, LPVOID pBuffer, DWORD dwSize) { return tsplib_lineReceiveMSPData(hdLine, hdCall, hdMSPLine, LPVOID pBuffer, dwSize); }// TSPI_lineReceiveMSPData #endif ///////////////////////////////////////////////////////////////////////////////// // TSPI_lineRedirect // // This function redirects the specified offering call to the specified // destination address. // DLLEXPORT LONG TSPIAPI TSPI_lineRedirect (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPCWSTR lpszDestAddr, DWORD dwCountryCode) { return tsplib_lineRedirect(dwRequestID, hdCall, lpszDestAddr, dwCountryCode); }// TSPI_lineRedirect ///////////////////////////////////////////////////////////////////////////////// // TSPI_lineReleaseUserUserInfo // // This function releases a block of User->User information which is stored // in the CALLINFO record. // DLLEXPORT LONG TSPIAPI TSPI_lineReleaseUserUserInfo (DRV_REQUESTID dwRequestID, HDRVCALL hdCall) { return tsplib_lineReleaseUserUserInfo(dwRequestID, hdCall); }// TSPI_lineReleaseUserUserInfo ///////////////////////////////////////////////////////////////////////////////// // TSPI_lineRemoveFromConference // // This function removes the specified call from the conference call to // which it currently belongs. The remaining calls in the conference call // are unaffected. // DLLEXPORT LONG TSPIAPI TSPI_lineRemoveFromConference (DRV_REQUESTID dwRequestID, HDRVCALL hdCall) { return tsplib_lineRemoveFromConference(dwRequestID, hdCall); }// TSPI_lineRemoveFromConference /////////////////////////////////////////////////////////////////////////////////// // TSPI_lineSecureCall // // This function secures the call from any interruptions or interference // that may affect the call's media stream. // DLLEXPORT LONG TSPIAPI TSPI_lineSecureCall (DRV_REQUESTID dwRequestID, HDRVCALL hdCall) { return tsplib_lineSecureCall(dwRequestID, hdCall); }// TSPI_lineSecureCall /////////////////////////////////////////////////////////////////////////////// // TSPI_lineSelectExtVersion // // This function selects the indicated extension version for the indicated // line device. Subsequent requests operate according to that extension // version. // DLLEXPORT LONG TSPIAPI TSPI_lineSelectExtVersion (HDRVLINE hdLine, DWORD dwExtVersion) { return tsplib_lineSelectExtVersion(hdLine, dwExtVersion); }// TSPI_lineSelectExtVersion ////////////////////////////////////////////////////////////////////////////// // TSPI_lineSendUserUserInfo // // This function sends user-to-user information to the remote party on the // specified call. // DLLEXPORT LONG TSPIAPI TSPI_lineSendUserUserInfo (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPCSTR lpsUserUserInfo, DWORD dwSize) { return tsplib_lineSendUserUserInfo(dwRequestID, hdCall, lpsUserUserInfo, dwSize); }// TSPI_lineSendUserUserInfo ////////////////////////////////////////////////////////////////////////////// // TSPI_lineSetAppSpecific // // This function sets the application specific portion of the // LINECALLINFO structure. This is returned by the TSPI_lineGetCallInfo // function. // DLLEXPORT LONG TSPIAPI TSPI_lineSetAppSpecific (HDRVCALL hdCall, DWORD dwAppSpecific) { return tsplib_lineSetAppSpecific(hdCall, dwAppSpecific); }// TSPI_lineSetAppSpecific ///////////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCallData // // This function sets CALLDATA into a calls CALLINFO record. // // Added for v2.0 // DLLEXPORT LONG TSPIAPI TSPI_lineSetCallData (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPVOID lpCallData, DWORD dwSize) { return tsplib_lineSetCallData(dwRequestID, hdCall, lpCallData, dwSize); }// TSPI_lineSetCallData #if (TAPI_CURRENT_VERSION >= 0x00030000) /////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCallHubTracking // // This function sets the call hub tracking support structure (TAPI 3.0) // DLLEXPORT LONG TSPIAPI TSPI_lineSetCallHubTracking(HDRVLINE hdLine, LPLINECALLHUBTRACKINGINFO lpTrackingInfo) { return tsplib_lineSetCallHubTracking(hdLine, lpTrackingInfo); }// TSPI_lineGetCallHubTracking #endif ///////////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCallParams // // This function sets certain parameters for an existing call. // DLLEXPORT LONG TSPIAPI TSPI_lineSetCallParams (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, DWORD dwBearerMode, DWORD dwMinRate, DWORD dwMaxRate, LPLINEDIALPARAMS const lpDialParams) { return tsplib_lineSetCallParams(dwRequestID, hdCall, dwBearerMode, dwMinRate, dwMaxRate, lpDialParams); }// TSPI_lineSetCallParams /////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCallTreatment // // Sets the call treatment for the specified call. If the call // treatment can go into effect then it happens immediately, // otherwise it is set into place the next time the call enters // a state where the call treatment is valid. // DLLEXPORT LONG TSPIAPI TSPI_lineSetCallTreatment (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, DWORD dwCallTreatment) { return tsplib_lineSetCallTreatment(dwRequestID, hdCall, dwCallTreatment); }// TSPI_lineSetCallTreatment //////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCurrentLocation // // This function is called by TAPI whenever the address translation location // is changed by the user (in the Dial Helper dialog or // 'lineSetCurrentLocation' function. SPs which store parameters specific // to a location (e.g. touch-tone sequences specific to invoke a particular // PBX function) would use the location to select the set of parameters // applicable to the new location. // DLLEXPORT LONG TSPIAPI TSPI_lineSetCurrentLocation (DWORD dwLocation) { return tsplib_lineSetCurrentLocation(dwLocation); }// TSPI_lineSetCurrentLocation //////////////////////////////////////////////////////////////////////////// // TSPI_lineSetDefaultMediaDetection // // This function tells us the new set of media modes to watch for on // this line (inbound or outbound). // DLLEXPORT LONG TSPIAPI TSPI_lineSetDefaultMediaDetection (HDRVLINE hdLine, DWORD dwMediaModes) { return tsplib_lineSetDefaultMediaDetection(hdLine, dwMediaModes); }// TSPI_lineSetDefaultMediaDetection ///////////////////////////////////////////////////////////////////////////// // TSPI_lineSetDevConfig // // This function restores the configuration of a device associated one-to-one // with the line device from a data structure obtained through TSPI_lineGetDevConfig. // The contents of the data structure are specific to the service provider. // DLLEXPORT LONG TSPIAPI TSPI_lineSetDevConfig (DWORD dwDeviceID, LPVOID const lpDevConfig, DWORD dwSize, LPCWSTR lpszDeviceClass) { return tsplib_lineSetDevConfig(dwDeviceID, lpDevConfig, dwSize, lpszDeviceClass); }// TSPI_lineSetDevConfig //////////////////////////////////////////////////////////////////////////////// // TSPI_lineSetMediaControl // // This function enables and disables control actions on the media stream // associated with the specified line, address, or call. Media control actions // can be triggered by the detection of specified digits, media modes, // custom tones, and call states. The new specified media controls replace all // the ones that were in effect for this line, address, or call prior to this // request. // DLLEXPORT LONG TSPIAPI TSPI_lineSetMediaControl (HDRVLINE hdLine, DWORD dwAddressID, HDRVCALL hdCall, DWORD dwSelect, LPLINEMEDIACONTROLDIGIT const lpDigitList, DWORD dwNumDigitEntries, LPLINEMEDIACONTROLMEDIA const lpMediaList, DWORD dwNumMediaEntries, LPLINEMEDIACONTROLTONE const lpToneList, DWORD dwNumToneEntries, LPLINEMEDIACONTROLCALLSTATE const lpCallStateList, DWORD dwNumCallStateEntries) { return tsplib_lineSetMediaControl(hdLine, dwAddressID, hdCall, dwSelect, lpDigitList, dwNumDigitEntries, lpMediaList, dwNumMediaEntries, lpToneList, dwNumToneEntries, lpCallStateList, dwNumCallStateEntries); }// TSPI_lineSetMediaControl //////////////////////////////////////////////////////////////////////////// // TSPI_lineSetMediaMode // // This function changes the provided calls media in the LINECALLSTATE // structure. // DLLEXPORT LONG TSPIAPI TSPI_lineSetMediaMode (HDRVCALL hdCall, DWORD dwMediaMode) { return tsplib_lineSetMediaMode(hdCall, dwMediaMode); }// TSPI_lineSetMediaMode /////////////////////////////////////////////////////////////////////////// // TSPI_lineSetCallQualityOfService // // This function attempts to nogotiate a level of QOS on the call with // the switch. If the desired QOS is not available, then it returns an // error and remains at the current level of QOS. // DLLEXPORT LONG TSPIAPI TSPI_lineSetCallQualityOfService (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, LPVOID lpSendingFlowSpec, DWORD dwSendingFlowSpecSize, LPVOID lpReceivingFlowSpec, DWORD dwReceivingFlowSpecSize) { return tsplib_lineSetQualityOfService(dwRequestID, hdCall, lpSendingFlowSpec, dwSendingFlowSpecSize, lpReceivingFlowSpec, dwReceivingFlowSpecSize); }// TSPI_lineSetCallQualityOfService /////////////////////////////////////////////////////////////////////////// // TSPI_lineSetStatusMessages // // This function tells us which events to notify TAPI about when // address or status changes about the specified line. // DLLEXPORT LONG TSPIAPI TSPI_lineSetStatusMessages (HDRVLINE hdLine, DWORD dwLineStates, DWORD dwAddressStates) { return tsplib_lineSetStatusMessages(hdLine, dwLineStates, dwAddressStates); }// TSPI_lineSetStatusMessages ///////////////////////////////////////////////////////////////////////////// // TSPI_lineSetTerminal // // This operation enables TAPI.DLL to specify to which terminal information // related to a specified line, address, or call is to be routed. This // can be used while calls are in progress on the line, to allow events // to be routed to different devices as required. // DLLEXPORT LONG TSPIAPI TSPI_lineSetTerminal (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, DWORD dwAddressID, HDRVCALL hdCall, DWORD dwSelect, DWORD dwTerminalModes, DWORD dwTerminalID, DWORD bEnable) { return tsplib_lineSetTerminal(dwRequestID, hdLine, dwAddressID, hdCall, dwSelect, dwTerminalModes, dwTerminalID, bEnable); }// TSPI_lineSetTerminal //////////////////////////////////////////////////////////////////////////// // TSPI_lineSetupConference // // This function sets up a conference call for the addition of a third // party. // DLLEXPORT LONG TSPIAPI TSPI_lineSetupConference (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, HDRVLINE hdLine, HTAPICALL htConfCall, LPHDRVCALL lphdConfCall, HTAPICALL htConsultCall, LPHDRVCALL lphdConsultCall, DWORD dwNumParties, LPLINECALLPARAMS const lpLineCallParams) { return tsplib_lineSetupConference(dwRequestID, hdCall, hdLine, htConfCall, lphdConfCall, htConsultCall, lphdConsultCall, dwNumParties, lpLineCallParams); }// TSPI_lineSetupConference //////////////////////////////////////////////////////////////////////////// // TSPI_lineSetupTransfer // // This function sets up a call for transfer to a destination address. // A new call handle is created which represents the destination // address. // DLLEXPORT LONG TSPIAPI TSPI_lineSetupTransfer (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, HTAPICALL htConsultCall, LPHDRVCALL lphdConsultCall, LPLINECALLPARAMS const lpCallParams) { return tsplib_lineSetupTransfer(dwRequestID, hdCall, htConsultCall, lphdConsultCall, lpCallParams); }// TSPI_lineSetupTransfer ////////////////////////////////////////////////////////////////////////////// // TSPI_lineSetLineDevStatus // // The service provider sets the device status as indicated, // sending the appropriate LINEDEVSTATE messages to indicate the // new status. // DLLEXPORT LONG TSPIAPI TSPI_lineSetLineDevStatus (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, DWORD dwStatusToChange, DWORD fStatus) { return tsplib_lineSetLineDevStatus(dwRequestID, hdLine, dwStatusToChange, fStatus); }// TSPI_lineSetLineDevStatus ////////////////////////////////////////////////////////////////////////////// // TSPI_lineSwapHold // // This function swaps the specified active call with the specified // call on hold. // DLLEXPORT LONG TSPIAPI TSPI_lineSwapHold (DRV_REQUESTID dwRequestID, HDRVCALL hdCall, HDRVCALL hdHeldCall) { return tsplib_lineSwapHold(dwRequestID, hdCall, hdHeldCall); }// TSPI_lineSwapHold //////////////////////////////////////////////////////////////////////////// // TSPI_lineUncompleteCall // // This function is used to cancel the specified call completion request // on the specified line. // DLLEXPORT LONG TSPIAPI TSPI_lineUncompleteCall (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, DWORD dwCompletionID) { return tsplib_lineUncompleteCall(dwRequestID, hdLine, dwCompletionID); }// TSPI_lineUncompleteCall //////////////////////////////////////////////////////////////////////////// // TSPI_lineUnhold // // This function retrieves the specified held call // DLLEXPORT LONG TSPIAPI TSPI_lineUnhold (DRV_REQUESTID dwRequestId, HDRVCALL hdCall) { return tsplib_lineUnhold(dwRequestId, hdCall); }// TSPI_lineUnhold ///////////////////////////////////////////////////////////////////////////// // TSPI_lineUnpark // // This function retrieves the call parked at the specified // address and returns a call handle for it. // DLLEXPORT LONG TSPIAPI TSPI_lineUnpark (DRV_REQUESTID dwRequestID, HDRVLINE hdLine, DWORD dwAddressID, HTAPICALL htCall, LPHDRVCALL lphdCall, LPCWSTR lpszDestAddr) { return tsplib_lineUnpark(dwRequestID, hdLine, dwAddressID, htCall, lphdCall, lpszDestAddr); }// TSPI_lineUnpark /******************************************************************************/ // // TSPI_phone functions // /******************************************************************************/ ////////////////////////////////////////////////////////////////////////// // TSPI_phoneClose // // This function closes the specified open phone device after completing // or aborting all outstanding asynchronous requests on the device. // DLLEXPORT LONG TSPIAPI TSPI_phoneClose (HDRVPHONE hdPhone) { return tsplib_phoneClose(hdPhone); }// TSPI_phoneClose /////////////////////////////////////////////////////////////////////////// // TSPI_phoneDevSpecific // // This function is used as a general extension mechanism to enable // a TAPI implementation to provide features not generally available // to the specification. // DLLEXPORT LONG TSPIAPI TSPI_phoneDevSpecific (DRV_REQUESTID dwRequestID, HDRVPHONE hdPhone, LPVOID lpParams, DWORD dwSize) { return tsplib_phoneDevSpecific(dwRequestID, hdPhone, lpParams, dwSize); }// TSPI_phoneDevSpecific /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetButtonInfo // // This function returns information about the specified phone // button. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetButtonInfo (HDRVPHONE hdPhone, DWORD dwButtonId, LPPHONEBUTTONINFO lpButtonInfo) { return tsplib_phoneGetButtonInfo(hdPhone, dwButtonId, lpButtonInfo); }// TSPI_phoneGetButtonInfo //////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetData // // This function uploads the information from the specified location // in the open phone device to the specified buffer. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetData (HDRVPHONE hdPhone, DWORD dwDataId, LPVOID lpData, DWORD dwSize) { return tsplib_phoneGetData(hdPhone, dwDataId, lpData, dwSize); }// TSPI_phoneGetData /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetDevCaps // // This function queries a specified phone device to determine its // telephony capabilities // DLLEXPORT LONG TSPIAPI TSPI_phoneGetDevCaps (DWORD dwDeviceId, DWORD dwTSPIVersion, DWORD dwExtVersion, LPPHONECAPS lpPhoneCaps) { return tsplib_phoneGetDevCaps(dwDeviceId, dwTSPIVersion, dwExtVersion, lpPhoneCaps); }// TSPI_phoneGetDevCaps /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetDisplay // // This function returns the current contents of the specified phone // display. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetDisplay (HDRVPHONE hdPhone, LPVARSTRING lpString) { return tsplib_phoneGetDisplay(hdPhone, lpString); }// TSPI_phoneGetDisplay ////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetExtensionID // // This function retrieves the extension ID that the service provider // supports for the indicated device. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetExtensionID (DWORD dwDeviceId, DWORD dwTSPIVersion, LPPHONEEXTENSIONID lpExtensionId) { return tsplib_phoneGetExtensionID(dwDeviceId, dwTSPIVersion, lpExtensionId); }// TSPI_phoneGetExtensionID /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetGain // // This function returns the gain setting of the microphone of the // specified phone's hookswitch device. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetGain (HDRVPHONE hdPhone, DWORD dwHookSwitchDev, LPDWORD lpdwGain) { return tsplib_phoneGetGain(hdPhone, dwHookSwitchDev, lpdwGain); }// TSPI_phoneGetGain /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetHookSwitch // // This function retrieves the current hook switch setting of the // specified open phone device // DLLEXPORT LONG TSPIAPI TSPI_phoneGetHookSwitch (HDRVPHONE hdPhone, LPDWORD lpdwHookSwitchDevs) { return tsplib_phoneGetHookSwitch(hdPhone, lpdwHookSwitchDevs); }// TSPI_phoneGetHookSwitch /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetIcon // // This function retrieves a specific icon for display from an // application. This icon will represent the phone device. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetIcon (DWORD dwDeviceId, LPCWSTR lpszDeviceClass, LPHICON lphIcon) { return tsplib_phoneGetIcon(dwDeviceId, lpszDeviceClass, lphIcon); }// TSPI_phoneGetIcon /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetID // // This function retrieves the device id of the specified open phone // handle (or some other media handle if available). // DLLEXPORT LONG TSPIAPI TSPI_phoneGetID (HDRVPHONE hdPhone, LPVARSTRING lpDeviceId, LPCWSTR lpszDeviceClass, HANDLE hTargetProcess) { return tsplib_phoneGetID(hdPhone, lpDeviceId, lpszDeviceClass, hTargetProcess); }// TSPI_phoneGetID /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetLamp // // This function returns the current lamp mode of the specified // lamp. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetLamp (HDRVPHONE hdPhone, DWORD dwButtonLampId, LPDWORD lpdwLampMode) { return tsplib_phoneGetLamp(hdPhone, dwButtonLampId, lpdwLampMode); }// TSPI_phoneGetLamp /////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetRing // // This function enables an application to query the specified open // phone device as to its current ring mode. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetRing (HDRVPHONE hdPhone, LPDWORD lpdwRingMode, LPDWORD lpdwVolume) { return tsplib_phoneGetRing(hdPhone, lpdwRingMode, lpdwVolume); }// TSPI_phoneGetRing ////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetStatus // // This function queries the specified open phone device for its // overall status. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetStatus (HDRVPHONE hdPhone, LPPHONESTATUS lpPhoneStatus) { return tsplib_phoneGetStatus(hdPhone, lpPhoneStatus); }// TSPI_phoneGetStatus //////////////////////////////////////////////////////////////////////////// // TSPI_phoneGetVolume // // This function returns the volume setting of the phone device. // DLLEXPORT LONG TSPIAPI TSPI_phoneGetVolume (HDRVPHONE hdPhone, DWORD dwHookSwitchDev, LPDWORD lpdwVolume) { return tsplib_phoneGetVolume(hdPhone, dwHookSwitchDev, lpdwVolume); }// TSPI_phoneGetVolume /////////////////////////////////////////////////////////////////////////// // TSPI_phoneNegotiateTSPIVersion // // This function returns the highest SP version number the // service provider is willing to operate under for this device, // given the range of possible values. // DLLEXPORT LONG TSPIAPI TSPI_phoneNegotiateTSPIVersion (DWORD dwDeviceID, DWORD dwLowVersion, DWORD dwHighVersion, LPDWORD lpdwVersion) { return tsplib_phoneNegotiateTSPIVersion(dwDeviceID, dwLowVersion, dwHighVersion, lpdwVersion); }// TSPI_phoneNegotiateTSPIVersion /////////////////////////////////////////////////////////////////////////// // TSPI_phoneNegotiateExtVersion // // This function returns the highest extension version number the // service provider is willing to operate under for this device, // given the range of possible extension values. // DLLEXPORT LONG TSPIAPI TSPI_phoneNegotiateExtVersion (DWORD dwDeviceID, DWORD dwTSPIVersion, DWORD dwLowVersion, DWORD dwHighVersion, LPDWORD lpdwExtVersion) { return tsplib_phoneNegotiateExtVersion(dwDeviceID, dwTSPIVersion, dwLowVersion, dwHighVersion, lpdwExtVersion); }// TSPI_phoneNegotiateExtVersion //////////////////////////////////////////////////////////////////////////// // TSPI_phoneOpen // // This function opens the phone device whose device ID is given, // returning the service provider's opaque handle for the device and // retaining the TAPI opaque handle. // DLLEXPORT LONG TSPIAPI TSPI_phoneOpen (DWORD dwDeviceId, HTAPIPHONE htPhone, LPHDRVPHONE lphdPhone, DWORD dwTSPIVersion, PHONEEVENT lpfnEventProc) { return tsplib_phoneOpen(dwDeviceId, htPhone, lphdPhone, dwTSPIVersion, lpfnEventProc); }// TSPI_phoneOpen /////////////////////////////////////////////////////////////////////////// // TSPI_phoneSelectExtVersion // // This function selects the indicated extension version for the // indicated phone device. Subsequent requests operate according to // that extension version. // DLLEXPORT LONG TSPIAPI TSPI_phoneSelectExtVersion (HDRVPHONE hdPhone, DWORD dwExtVersion) { return tsplib_phoneSelectExtVersion(hdPhone, dwExtVersion); }// TSPI_phoneSelectExtVersion ////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetButtonInfo // // This function sets information about the specified button on the // phone device. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetButtonInfo (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwButtonId, LPPHONEBUTTONINFO const lpButtonInfo) { return tsplib_phoneSetButtonInfo(dwRequestId, hdPhone, dwButtonId, lpButtonInfo); }// TSPI_phoneSetButtonInfo ////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetData // // This function downloads the information in the specified buffer // to the opened phone device at the selected data id. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetData (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwDataId, LPVOID const lpData, DWORD dwSize) { return tsplib_phoneSetData(dwRequestId, hdPhone, dwDataId, lpData, dwSize); }// TSPI_phoneSetData ////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetDisplay // // This function causes the specified string to be displayed on the // phone device. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetDisplay (DRV_REQUESTID dwRequestID, HDRVPHONE hdPhone, DWORD dwRow, DWORD dwCol, LPCWSTR lpszDisplay, DWORD dwSize) { return tsplib_phoneSetDisplay(dwRequestID, hdPhone, dwRow, dwCol, lpszDisplay, dwSize) ; }// TSPI_phoneSetDisplay /////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetGain // // This function sets the gain of the microphone of the specified hook // switch device. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetGain (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwHookSwitchDev, DWORD dwGain) { return tsplib_phoneSetGain(dwRequestId, hdPhone, dwHookSwitchDev, dwGain); }// TSPI_phoneSetGain /////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetHookSwitch // // This function sets the hook state of the specified open phone's // hookswitch device to the specified mode. Only the hookswitch // state of the hookswitch devices listed is affected. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetHookSwitch (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwHookSwitchDevs, DWORD dwHookSwitchMode) { return tsplib_phoneSetHookSwitch(dwRequestId, hdPhone, dwHookSwitchDevs, dwHookSwitchMode); }// TSPI_phoneSetHookSwitch /////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetLamp // // This function causes the specified lamp to be set on the phone // device to the specified mode. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetLamp (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwButtonLampId, DWORD dwLampMode) { return tsplib_phoneSetLamp(dwRequestId, hdPhone, dwButtonLampId, dwLampMode); }// TSPI_phoneSetLamp /////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetRing // // This function rings the specified open phone device using the // specified ring mode and volume. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetRing (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwRingMode, DWORD dwVolume) { return tsplib_phoneSetRing(dwRequestId, hdPhone, dwRingMode, dwVolume); }// TSPI_phoneSetRing ////////////////////////////////////////////////////////////////////////// // TSPI_phoneSetStatusMessages // // This function causes the service provider to filter status messages // which are not currently of interest to any application. // DLLEXPORT LONG TSPIAPI TSPI_phoneSetStatusMessages (HDRVPHONE hdPhone, DWORD dwPhoneStates, DWORD dwButtonModes, DWORD dwButtonStates) { return tsplib_phoneSetStatusMessages(hdPhone, dwPhoneStates, dwButtonModes, dwButtonStates); }// TSPI_phoneSetStatusMessages ///////////////////////////////////////////////////////////////////////// // TSPI_phoneSetVolume // // This function either sets the volume of the speaker or the // specified hookswitch device on the phone // DLLEXPORT LONG TSPIAPI TSPI_phoneSetVolume (DRV_REQUESTID dwRequestId, HDRVPHONE hdPhone, DWORD dwHookSwitchDev, DWORD dwVolume) { return tsplib_phoneSetVolume(dwRequestId, hdPhone, dwHookSwitchDev, dwVolume); }// TSPI_phoneSetVolume /******************************************************************************/ // // TSPI_provider functions // /******************************************************************************/ /////////////////////////////////////////////////////////////////////////// // TSPI_providerInit // // This function is called when TAPI.DLL wants to initialize // our service provider. // DLLEXPORT LONG TSPIAPI TSPI_providerInit (DWORD dwTSPIVersion, DWORD dwPermanentProviderID, DWORD dwLineDeviceIDBase, DWORD dwPhoneDeviceIDBase, DWORD dwNumLines, DWORD dwNumPhones, ASYNC_COMPLETION lpfnCompletionProc, LPDWORD lpdwTSPIOptions) { return tsplib_providerInit(dwTSPIVersion, dwPermanentProviderID, dwLineDeviceIDBase, dwPhoneDeviceIDBase, dwNumLines, dwNumPhones, lpfnCompletionProc, lpdwTSPIOptions); }// TSPI_providerInit /////////////////////////////////////////////////////////////////////////// // TSPI_providerShutdown // // This function is called when the TAPI.DLL is shutting down our // service provider. // DLLEXPORT LONG TSPIAPI TSPI_providerShutdown (DWORD dwTSPIVersion, DWORD dwProviderID) { return tsplib_providerShutdown(dwTSPIVersion, dwProviderID); }// TSPI_providerShutdown //////////////////////////////////////////////////////////////////////////// // TSPI_providerEnumDevices (Win95) // // This function is called before the TSPI_providerInit to determine // the number of line and phone devices supported by the service provider. // If the function is not available, then TAPI will read the information // out of the TELEPHON.INI file per TAPI 1.0. // DLLEXPORT LONG TSPIAPI TSPI_providerEnumDevices (DWORD dwPermanentProviderID, LPDWORD lpdwNumLines, LPDWORD lpdwNumPhones, HPROVIDER hProvider, LINEEVENT lpfnLineCreateProc, PHONEEVENT lpfnPhoneCreateProc) { return tsplib_providerEnumDevices(dwPermanentProviderID, lpdwNumLines, lpdwNumPhones, hProvider, lpfnLineCreateProc, lpfnPhoneCreateProc); }// TSPI_providerEnumDevices ///////////////////////////////////////////////////////////////////////////// // TSPI_providerCreateLineDevice (Win95) // // This function is called by TAPI in response to the receipt of a // LINE_CREATE message from the service provider which allows the dynamic // creation of a new line device. The passed deviceId identifies this // line from TAPIs perspective. // DLLEXPORT LONG TSPIAPI TSPI_providerCreateLineDevice (DWORD dwTempID, DWORD dwDeviceID) { return tsplib_providerCreateLineDevice(dwTempID, dwDeviceID); }// TSPI_providerCreateLineDevice ///////////////////////////////////////////////////////////////////////////// // TSPI_providerCreatePhoneDevice (Win95) // // This function is called by TAPI in response to the receipt of a // PHONE_CREATE message from the service provider which allows the dynamic // creation of a new phone device. The passed deviceId identifies this // phone from TAPIs perspective. // DLLEXPORT LONG TSPIAPI TSPI_providerCreatePhoneDevice (DWORD dwTempID, DWORD dwDeviceID) { return tsplib_providerCreatePhoneDevice(dwTempID, dwDeviceID); }// TSPI_providerCreatePhoneDevice ///////////////////////////////////////////////////////////////////////////// // TSPI_providerFreeDialogInstance (Tapi 2.0) // // This function is called to inform the service provider that // the dialog associated with the "hdDlgInstance" has exited. // After this function is called, the service provider should no // longer send data to the dialog using the LINE_SENDDIALOGINSTANCEDATA // message. // DLLEXPORT LONG TSPIAPI TSPI_providerFreeDialogInstance (HDRVDIALOGINSTANCE hdDlgInstance) { return tsplib_providerFreeDialogInstance(hdDlgInstance); }// TSPI_providerFreeDialogInstance ///////////////////////////////////////////////////////////////////////////// // TSPI_providerGenericDialogData (Tapi 2.0) // // This function delivers to the service provider data that was // sent from the UI DLL running in an application context via // the TSISPIDLLCALLBACK function. The contents of the memory // block pointed to be lpParams is defined by the service provider // and UI DLL. The service provider can modify the contents of the // memory block; when this function returns, TAPI will copy the // new modified data back to the original UI DLL parameter block. // DLLEXPORT LONG TSPIAPI TSPI_providerGenericDialogData (DWORD dwObjectID, DWORD dwObjectType, LPVOID lpParams, DWORD dwSize) { return tsplib_providerGenericDialogData(dwObjectID, dwObjectType, lpParams, dwSize); }// TSPI_providerGenericDialogData ///////////////////////////////////////////////////////////////////////////// // TSPI_providerUIIdentify (Tapi 2.0) // // This function returns the name of the UI DLL for this // service provider. // DLLEXPORT LONG TSPIAPI TSPI_providerUIIdentify (LPWSTR lpszUIDLLName) { return tsplib_providerUIIdentify(lpszUIDLLName); }// TSPI_providerUIIdentify /******************************************************************************/ // // AGENT SUPPORT FUNCTIONS called by DEVICE.CPP when proxy requests are // recieved // /******************************************************************************/ ///////////////////////////////////////////////////////////////////////////// // TSPI_lineSetAgentGroup // // Called by the agent proxy to set the agent group for a particular line // and address. // DLLEXPORT LONG TSPIAPI TSPI_lineSetAgentGroup(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTGROUPLIST const lpGroupList) { return tsplib_lineSetAgentGroup(dwRequestID, dwDeviceID, dwAddressID, lpGroupList); }// TSPI_lineSetAgentGroup ///////////////////////////////////////////////////////////////////////////// // TSPI_lineSetAgentState // // Called by the agent proxy to set the current agent state // DLLEXPORT LONG TSPIAPI TSPI_lineSetAgentState(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwAgentState, DWORD dwNextAgentState) { return tsplib_lineSetAgentState(dwRequestID, dwDeviceID, dwAddressID, dwAgentState, dwNextAgentState); }// TSPI_lineSetAgentState ///////////////////////////////////////////////////////////////////////////// // TSPI_lineSetAgentActivity // // Called by the agent proxy to set the current agent activity // DLLEXPORT LONG TSPIAPI TSPI_lineSetAgentActivity(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwActivityID) { return tsplib_lineSetAgentActivity(dwRequestID, dwDeviceID, dwAddressID, dwActivityID); }// TSPI_lineSetAgentActivity ///////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAgentStatus // // Called by the agent proxy to query the current agent state // DLLEXPORT LONG TSPIAPI TSPI_lineGetAgentStatus(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTSTATUS lpStatus) { return tsplib_lineGetAgentStatus(dwDeviceID, dwAddressID, lpStatus); }// TSPI_lineGetAgentStatus ///////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAgentCaps // // Called by the agent proxy to query the capabilities of the address // DLLEXPORT LONG TSPIAPI TSPI_lineGetAgentCaps(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTCAPS lpCapabilities) { return tsplib_lineGetAgentCaps(dwDeviceID, dwAddressID, lpCapabilities); }// TSPI_lineGetAgentCaps ///////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAgentActivityList // // Called by the agent proxy to get the list of available agent activities // DLLEXPORT LONG TSPIAPI TSPI_lineGetAgentActivityList(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTACTIVITYLIST lpList) { return tsplib_lineGetAgentActivityList(dwDeviceID, dwAddressID, lpList); }// TSPI_lineGetAgentActivityList ///////////////////////////////////////////////////////////////////////////// // TSPI_lineGetAgentGroupList // // Called by the agent proxy to query the available groups // DLLEXPORT LONG TSPIAPI TSPI_lineGetAgentGroupList(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTGROUPLIST lpList) { return tsplib_lineGetAgentGroupList(dwDeviceID, dwAddressID, lpList); }// TSPI_lineGetAgentGroupList ///////////////////////////////////////////////////////////////////////////// // TSPI_lineAgentSpecific // // Called by the agent proxy to manage device-specific agent requests // DLLEXPORT LONG TSPIAPI TSPI_lineAgentSpecific(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwAgentExtensionID, LPVOID lpvParams, DWORD dwSize) { return tsplib_lineAgentSpecific(dwRequestID, dwDeviceID, dwAddressID, dwAgentExtensionID, lpvParams, dwSize); }// TSPI_lineGetAgentGroupList /******************************************************************************/ // // OBSOLETE FUNCTIONS - Required only for export // /******************************************************************************/ //////////////////////////////////////////////////////////////////////////// // TSPI_lineConfigDialog // // This function is called to display the line configuration dialog // when the user requests it through either the TAPI api or the control // panel applet. // extern "C" LONG TSPIAPI TSPI_lineConfigDialog (DWORD /*dwDeviceID*/, HWND /*hwndOwner*/, LPCSTR /*lpszDeviceClass*/) { return LINEERR_OPERATIONUNAVAIL; }// TSPI_lineConfigDialog /////////////////////////////////////////////////////////////////////////// // TSPI_lineConfigDialogEdit (Win95) // // This function causes the provider of the specified line device to // display a modal dialog to allow the user to configure parameters // related to the line device. The parameters editted are NOT the // current device parameters, rather the set retrieved from the // 'TSPI_lineGetDevConfig' function (lpDeviceConfigIn), and are returned // in the lpDeviceConfigOut parameter. // extern "C" LONG TSPIAPI TSPI_lineConfigDialogEdit (DWORD /*dwDeviceID*/, HWND /*hwndOwner*/, LPCSTR /*lpszDeviceClass*/, LPVOID const /*lpDeviceConfigIn*/, DWORD /*dwSize*/, LPVARSTRING /*lpDeviceConfigOut*/) { return LINEERR_OPERATIONUNAVAIL; }// TSPI_lineConfigDialogEdit /////////////////////////////////////////////////////////////////////////// // TSPI_phoneConfigDialog // // This function invokes the parameter configuration dialog for the // phone device. // extern "C" LONG TSPIAPI TSPI_phoneConfigDialog (DWORD /*dwDeviceId*/, HWND /*hwndOwner*/, LPCSTR /*lpszDeviceClass*/) { return PHONEERR_OPERATIONUNAVAIL; }// TSPI_phoneConfigDialog //////////////////////////////////////////////////////////////////////////// // TSPI_providerConfig // // This function is invoked from the control panel and allows the user // to configure our service provider. // extern "C" LONG TSPIAPI TSPI_providerConfig (HWND, DWORD) { return LINEERR_OPERATIONUNAVAIL; }// TSPI_providerConfig //////////////////////////////////////////////////////////////////////////// // TSPI_providerInstall // // This function is invoked to install the service provider onto // the system. // extern "C" LONG TSPIAPI TSPI_providerInstall (HWND, DWORD) { return LINEERR_OPERATIONUNAVAIL; }// TSPI_providerInstall //////////////////////////////////////////////////////////////////////////// // TSPI_providerRemove // // This function removes the service provider // extern "C" LONG TSPIAPI TSPI_providerRemove (HWND, DWORD) { return LINEERR_OPERATIONUNAVAIL; }// TSPI_providerRemove
[ "Owner@.(none)" ]
[ [ [ 1, 1914 ] ] ]
2965b691b94e6ee7bba7e689f938a8463244e4a1
bd37f7b494990542d0d9d772368239a2d44e3b2d
/client/src/Personaje.cpp
74fbd4670f58cd440a42e158db0af059c04eb0fd
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,380
cpp
/////////////////////////////////////////////////////////// // Personaje.cpp // Implementation of the Class Personaje // Created on: 21-Nov-2007 23:40:21 /////////////////////////////////////////////////////////// #include "Personaje.h" Personaje::Personaje(){ } Personaje::Personaje(Posicion& posicion){ this->posicion=posicion; } Personaje::~Personaje() { } /** * Posicion del personaje en el mapa */ Posicion* Personaje::GetPosicion() { return &posicion; } /** * Velocidad del personaje */ int Personaje::GetVelocidad(){ return velocidad; } /** * Retorna el Identificador de personaje */ int Personaje::GetId()const { return idPersonaje; } /** * Identificador de personaje */ void Personaje::SetId(int id){ idPersonaje = id; } /** * Posicion del personaje en el mapa */ void Personaje::SetPosicion(Posicion pos){ posicion.setArista( pos.getArista() ); posicion.setPosicionArista( pos.getPosicionArista() ); posicion.setDireccion( pos.getDireccion() ); } /** * Velocidad del personaje */ void Personaje::SetVelocidad(int newVal){ velocidad = newVal; } void Personaje::SetModel(Model* model){ this->model=model; } void Personaje::SetRotacion(Coordenada rotacion) { this->rotacion = rotacion; } void Personaje::SetCoord(Coordenada coord) { this->coord= coord; } void Personaje::renderizar() { glPushMatrix(); glTranslatef(coord.x, coord.y, coord.z);//(0,0,0) para el escenario glRotatef(rotacion.x, 1.0f, 0.0f, 0.0f); glRotatef(rotacion.y, 0.0f, 1.0f, 0.0f); glRotatef(rotacion.z, 0.0f, 0.0f, 1.0f); if (GetRol()==0) glScalef(P_ESCALAX, P_ESCALAY, P_ESCALAZ); else glScalef(F_ESCALAX, F_ESCALAY, F_ESCALAZ); if (model != NULL) { if (model->tex != NULL) { glEnable(GL_TEXTURE_2D); glBindTexture (GL_TEXTURE_2D, model->tex->id); } else { glDisable(GL_TEXTURE_2D); } if (model->mat != NULL) { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glMaterialfv(GL_FRONT, GL_AMBIENT, model->mat->amb); glMaterialfv(GL_FRONT, GL_DIFFUSE, model->mat->dif); glMaterialfv(GL_FRONT, GL_SPECULAR, model->mat->spe); glMaterialf(GL_FRONT, GL_SHININESS, model->mat->shininess); } else { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } for (unsigned int i = 0; i < model->triSize; i++) { Coordenada p, n; glBegin(GL_TRIANGLES); UV uv; p = model->Points[model->Tris[i].p0-1]; n = model->Normals[model->Tris[i].n0-1]; uv = model->UVs[model->Tris[i].uv0-1]; glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glNormal3f(n.x, n.y, n.z); glTexCoord2f(uv.u, uv.v); glVertex3f(p.x, p.y, p.z); p = model->Points[model->Tris[i].p1-1]; n = model->Normals[model->Tris[i].n1-1]; uv = model->UVs[model->Tris[i].uv1-1]; glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glNormal3f(n.x, n.y, n.z); glTexCoord2f(uv.u, uv.v); glVertex3f(p.x, p.y, p.z); p = model->Points[model->Tris[i].p2-1]; n = model->Normals[model->Tris[i].n2-1]; uv = model->UVs[model->Tris[i].uv2-1]; glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glNormal3f(n.x, n.y, n.z); glTexCoord2f(uv.u, uv.v); glVertex3f(p.x, p.y, p.z); glEnd(); } } glPopMatrix(); }
[ "nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8", "scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8", "rencat@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 12 ], [ 15, 16 ], [ 19, 21 ], [ 23, 25 ], [ 27, 51 ], [ 53, 53 ], [ 55, 60 ], [ 62, 62 ], [ 66, 75 ] ], [ [ 13, 14 ], [ 52, 52 ], [ 54, 54 ], [ 61, 61 ], [ 63, 65 ] ], [ [ 17, 18 ], [ 22, 22 ], [ 26, 26 ], [ 76, 160 ] ] ]
4964a18dadc7e8109ebf9d3b44e72ec17f4d1ef0
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_Utility/Modules/ConfigDB/Cx_CfgRecordset.cpp
e9e4c273ec0e85b23e08bc2068a0f4e89d2b0662
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
UTF-8
C++
false
false
7,665
cpp
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // 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. #include "StdAfx.h" #include "Cx_CfgRecordset.h" #include "Cx_CfgDatabase.h" #include "DbFunc.h" Cx_CfgRecordset::Cx_CfgRecordset() : m_bNeedExecuteSQL(true), m_lRecIndex(0), m_lRecordCount(-1) { } Cx_CfgRecordset::~Cx_CfgRecordset() { } void Cx_CfgRecordset::InitializeBySQL(Cx_CfgDatabase* pDB, const std::wstring& wstrSQL) { ASSERT(NULL == m_pDB && pDB != NULL); m_pDB = pDB; m_wstrSQL = wstrSQL; } std::wstring Cx_CfgRecordset::GetTableName() const { LPCWSTR pszFrom = StrStrIW(m_wstrSQL.c_str(), L"FROM "); if (pszFrom != NULL) { return DbFunc::GetLevel1Name(pszFrom + 5); } return L""; } std::wstring Cx_CfgRecordset::GetSQLCommand() const { return m_wstrSQL; } long Cx_CfgRecordset::GetCurIndex() const { return m_lRecIndex; } _RecordsetPtr Cx_CfgRecordset::GetCurRecord() { if (m_bNeedExecuteSQL && IsValid()) { m_bNeedExecuteSQL = false; try { m_pRs = m_pDB->ExecuteSQL(m_wstrSQL.c_str(), __FILE__, __LINE__); m_lRecIndex = 0; } CATCH_DB_STR_ERROR; } return m_pRs; } long Cx_CfgRecordset::GetRecordCount() { if (m_lRecordCount < 0) { m_pDB->GetRecordCount(m_lRecordCount, m_wstrSQL.c_str()); } return m_lRecordCount; } bool Cx_CfgRecordset::SetCurIndex(long nIndex) { ASSERT(nIndex >= 0); _RecordsetPtr pRs = GetCurRecord(); if (NULL == pRs) { return false; } try { if (nIndex == m_lRecIndex + 1) { pRs->MoveNext(); } else if (nIndex < m_lRecIndex && 0 == nIndex) { pRs->MoveFirst(); } else if (nIndex != m_lRecIndex) { return false; } m_lRecIndex = nIndex; return true; } CATCH_DB_STR_ERROR; return false; } bool Cx_CfgRecordset::IsValid() const { return m_pDB && !m_wstrSQL.empty(); } std::wstring Cx_CfgRecordset::GetString(LPCWSTR, LPCWSTR) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return L""; } bool Cx_CfgRecordset::SetString(LPCWSTR, LPCWSTR) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } int Cx_CfgRecordset::GetInt(LPCWSTR, int) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetInt(LPCWSTR, int) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } long Cx_CfgRecordset::GetInt32(LPCWSTR, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetInt32(LPCWSTR, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } ULONG Cx_CfgRecordset::GetUInt32(LPCWSTR, ULONG) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetUInt32(LPCWSTR, ULONG) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } short Cx_CfgRecordset::GetInt16(LPCWSTR, short) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetInt16(LPCWSTR, short) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } WORD Cx_CfgRecordset::GetUInt16(LPCWSTR, WORD) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetUInt16(LPCWSTR, WORD) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::GetBool(LPCWSTR, BOOL) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetBool(LPCWSTR, BOOL) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } double Cx_CfgRecordset::GetDouble(LPCWSTR, double) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetDouble(LPCWSTR, double) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } float Cx_CfgRecordset::GetFloat(LPCWSTR, float) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetFloat(LPCWSTR, float) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } COLORREF Cx_CfgRecordset::GetRGB(LPCWSTR, COLORREF) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return 0; } bool Cx_CfgRecordset::SetRGB(LPCWSTR, COLORREF) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::GetCMYK(LPCWSTR, WORD&, WORD&, WORD&, WORD&) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetCMYK(LPCWSTR, WORD, WORD, WORD, WORD) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::GetDate(LPCWSTR, int&, int&, int&) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetDate(LPCWSTR, int, int, int) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::GetDateTime(LPCWSTR, int&, int&, int&, int&, int&, int&) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } bool Cx_CfgRecordset::SetDateTime(LPCWSTR, int, int, int, int, int, int) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } long Cx_CfgRecordset::GetDoubleArray(LPCWSTR, double*, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return 0; } bool Cx_CfgRecordset::SetDoubleArray(LPCWSTR, const double*, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } long Cx_CfgRecordset::GetIntArray(LPCWSTR, long*, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return 0; } bool Cx_CfgRecordset::SetIntArray(LPCWSTR, const long*, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; } long Cx_CfgRecordset::GetBinary(LPCWSTR, LPVOID, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return 0; } bool Cx_CfgRecordset::SetBinary(LPCWSTR, LPCVOID, long) { ASSERT_MESSAGE(0, "The function is not supportable. [Recordset::GetXXX/SetXXX]"); return false; }
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 315 ] ] ]
4579946128ca21ff6ddb2ce08fe23d0ef56fd2fb
6327ac79f3294817895d5ef859509145bc0c28a9
/win/gfx.cpp
bcd3c4cb34c70f420592fccf214b85125f3e9494
[]
no_license
corpsofengineers/ffed3d
c8da1cb6e58f8b37b138d6f7d7ac0faa585e961b
8b6df7c081fd9ec4cf86220e8561439a8340d59b
refs/heads/master
2021-01-10T13:17:57.882726
2011-12-05T22:24:07
2011-12-05T22:24:07
49,797,267
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
165,484
cpp
#include <windows.h> #include <stdio.h> #include <math.h> #include <direct.h> #include <d3dx9.h> #include "../ffeapi.h" #include "../ffecfg.h" #include "win32api.h" #include "ffe3d.h" #include "Xfile/XFileEntity.h" #include "Render/RenderSystem.h" #include <GL/glu.h> #define N_0 0.0f #define N_1 1.0f #define WIDTH 640 #define HEIGHT 400 #define DIVIDER 10000 const bool callAsm=true; const bool splineExport=false; bool skipCurrentModel=false; bool subObject=false; float GetPlanetRadius (void *planet); extern "C" ffeVertex *DATA_009200; // Vertex buffer? extern "C" char *DATA_007892_Icosahedron; extern "C" ModelInstance_t** DATA_008861; extern "C" char *DATA_006821; extern "C" unsigned char *DATA_008874; extern "C" PANELCLICKAREA *DATA_007684; extern "C" int *DATA_008804; // game time extern "C" InstanseList_t *instanceList; // 0x006ab9c0 extern "C" ffeVertex* FUNC_001470_getVertex(void *a, int num); extern "C" ffeVertex* FUNC_001471(void *a, int num); extern "C" ffeVertex* FUNC_001472(void *a, int num); extern "C" int FUNC_001473_getVar(void *a, int cmd); extern "C" void* FUNC_001758_doMath(void *a, void *b, short cmd); extern "C" unsigned short* FUNC_001756_SkipIfBitClear(void *a, void *b, short cmd); extern "C" unsigned short* FUNC_001757_SkipIfBitSet(void *a, void *b, short cmd); extern "C" unsigned short* FUNC_001752_SkipIfNotVisible(void *a, void *b, short cmd); extern "C" unsigned short* C_FUNC_001752_SkipIfNotVisible(DrawMdl_t *gptr, unsigned short *var2, unsigned short var1); extern "C" unsigned short* FUNC_001755_SkipIfVisible(void *a, void *b, short cmd); extern "C" unsigned short* C_FUNC_001755_SkipIfVisible(DrawMdl_t *gptr, unsigned short *var2, unsigned short var1); extern "C" unsigned short* FUNC_GraphNull(void *a, void *b, short cmd); extern "C" unsigned short FUNC_001474_getRadius(void *a, int cmd); //extern "C" unsigned char * FUNC_001532_GetModelInstancePtr(unsigned char, void *); //extern "C" Model_t * FUNC_001538_GetModelPtr(int); //extern "C" char *FUNC_001344_StringExpandFFCode(char *dest, int ffcode, StrVars *vars); //extern "C" char *FUNC_001345_StringExpandFF40Code(char *dest, int stridx); extern int C_FUNC_001874_DrawPlanet(DrawMdl_t *DrawMdl, char *cmd); #define _GLUfuncptr void(__stdcall*)(void) #define MIN(X,Y) (((X) < (Y)) ? (X) : (Y)) #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) extern int aspectfix; unsigned char Ambient2[7][8][3] = { 0,0,0, 0,0,0, 0,0,0, 0,0,0, 0,0,0, 0,0,0, 0,0,0, 0,0,0, // none 7,7,7, 7,7,7, 7,7,7, 6,6,6, 5,5,5, 4,4,4, 3,3,3, 2,2,2, // default 7,6,3, 7,5,2, 7,4,2, 6,3,1, 5,2,0, 4,1,0, 3,0,0, 2,0,0, // Red 7,7,5, 7,6,4, 7,5,2, 6,4,0, 5,3,0, 4,2,0, 3,2,0, 2,1,0, // Orange 7,7,7, 7,7,7, 6,6,6, 5,5,5, 4,4,4, 3,3,3, 2,2,2, 1,1,1, // White 7,7,7, 7,7,7, 6,7,7, 6,6,7, 5,5,7, 4,4,7, 3,3,6, 2,2,4, // Cyan 0,6,7, 0,5,7, 0,4,7, 0,3,7, 0,2,6, 0,1,5, 0,0,4, 0,0,2 // Blue }; unsigned char Ambient[7][3] = { 0,0,0, // none 7,7,7, // 6,3,1, // Red 6,4,0, // Orange 5,5,5, // White 6,6,7, // Cyan 0,3,7 // Blue }; unsigned char starColors[11][3] = { 15,6,4, // Type 'M' red star 15,6,4, // Giant red star 15,9,5, // Type 'K' orange star 15,15,6, // Type 'G' yellow star 15,15,15, // Type 'F' white star 13,15,15, // Type 'A' hot white star 7,15,15, // Type 'B' hot blue star 15,11,6, // Bright giant star 14,9,2, // Supergiant star 7,15,15, // Blue supergiant star 8,13,15 // White dwarf star }; //extern LPDIRECT3DDEVICE9 renderSystem->GetDevice(); std::vector<Sprite> sprites; //extern LPDIRECT3DVERTEXBUFFER9 d3d_vb; extern sVertexBuffer vertexBuffer; CUSTOMVERTEX *Vertices; extern VERTEXTYPE vertexType[MAXVERT]; extern int vertexNum; extern MODEL modelList[6000]; extern int modelNum; int mainModelNum=0; int parentModelNum=0; extern FFTEXT ffText[2000]; extern int textNum; extern ULONG pWinPal32[256]; extern FFEsprite spriteList[400]; extern int maxsprite; D3DXVECTOR3 mainModelCoord; extern D3DXVECTOR3 playerLightPos; extern xModel* objectList[500]; extern "C" unsigned int **textColor; extern "C" unsigned char **ambColor; extern "C" Model_t **ffeModelList; extern "C" void **textPool; extern "C" unsigned int **DATA_007824; unsigned int t_DATA_007824; //extern "C" void C_PlaceStation (int *starport, int lat, int lon, int *objectList); // Используются для перехвата в 2D extern "C" void C_DrawScannerMarker(int x1, int y1, int x2, int y2, int col); extern "C" void C_DrawHLine(int x, int y, int len, int color); extern "C" void C_DrawCircle (u16 *center, int radius, int color); extern "C" void C_DrawLine(u16 *point1, u16 *point2, int col); extern "C" void C_DrawTriangle(u16 *point1, u16 *point2, u16 *point3, int color); extern "C" void C_DrawQuad(u16 *point1, u16 *point2, u16 *point3, u16 *point4, int color); void DrawTriangle(u16 *point1, u16 *point2, u16 *point3, u16 *t1, u16 *t2, u16 *t3, int color, int text, int z, bool intern); void mMatrix(unsigned char* inst); Vect3f getNormal(unsigned char num); Vect3f getReNormal(unsigned char num); Vect3f GetTriangeNormal(Vect3f* vVertex1, Vect3f* vVertex2, Vect3f* vVertex3); int textStartX=-1; char *C_DrawText (char *pStr, int xpos, int ypos, int col, bool shadow, int ymin, int ymax, int height); extern void RenderDirect3D(void); extern bool awaitingRender; struct Model_t *mod; DrawMdl_t* gptr; ModelInstance_t* iptr; unsigned short *gcmd; float expVert[3]; float expVertOrigin[3]; float prevPoint[3]; D3DXMATRIX camRot, camPos; D3DXVECTOR3 camForward, camUp; extern int range; bool draw2D; extern int curwidth; extern int curheight; unsigned char localColor[3]; Color4c currentColor(0,0,0,0); int currentR=0; int currentG=0; int currentB=0; int currentTex; bool doLight=true; bool useLocalColor=false; short *globalvar; short globalvar0; int currentModel; int t_localvar[7]; int p_localvar[7]; int *localvar; D3DXMATRIX posMatrix, mainRotMatrix, mainRotMatrixO, currentMatrix, matWorld; D3DXMATRIX lightRotMatrix; int currentScale; int currentScale2; int currentNormal; unsigned char currentAmbientR=15; unsigned char currentAmbientG=15; unsigned char currentAmbientB=15; DWORD fullAmbientColor; D3DXVECTOR3 curLightPos; D3DXVECTOR3 sunLightPos; bool transparent; int mxVertices; D3DXVECTOR3 mVertices[MAXVERT]; int mxIndexes; int mIndexes[MAXVERT]; bool exportb[500]; bool billboardMatrix; float lastPlanetRadius; int incabin; extern bool panellight[20]; bool clearBeforeRender=false; extern "C" void C_clearAll() { clearBeforeRender=true; } #define COUNTER_CLOCKWISE 0 #define CLOCKWISE 1 /* * orientation * * Return either clockwise or counter_clockwise for the orientation * of the polygon. */ static double ver[2000][3]; static double ver2[2000][3]; float vertbuf[256][4]; int vcount=0; bool ExportMesh(int exp) { if (mxIndexes==0) return false; ID3DXMesh* pMesh = NULL; D3DXCreateMeshFVF( mxIndexes / 3, mxVertices, D3DXMESH_MANAGED, D3DFVF_MESH, renderSystem->GetDevice(), &pMesh ); BYTE *pVertex=NULL; pMesh->LockVertexBuffer( 0, (void**)&pVertex ); DWORD vertSize=D3DXGetFVFVertexSize(D3DFVF_MESH); for(int i=0;i<mxVertices;i++) { D3DXVECTOR3 *vPtr=(D3DXVECTOR3 *) pVertex; vPtr->x=mVertices[i].x; vPtr->y=mVertices[i].y; vPtr->z=mVertices[i].z; pVertex+=vertSize; } pMesh->UnlockVertexBuffer(); BYTE *pIndex=NULL; pMesh->LockIndexBuffer( 0, (void**)&pIndex ); DWORD indSize=sizeof(USHORT); for(int j=0;j<mxIndexes;j++) { USHORT *iPtr=(USHORT *) pIndex; *iPtr=mIndexes[j]; pIndex+=indSize; } pMesh->UnlockIndexBuffer(); D3DXComputeNormals(pMesh, NULL); char buf[200]; sprintf(buf,"models\\_export"); _mkdir(buf); sprintf(buf,"models\\_export\\%i",exp); _mkdir(buf); sprintf(buf,"models\\_export\\%i\\export.x",exp); D3DXSaveMeshToX(buf, pMesh, NULL, NULL, NULL, 0, D3DXF_FILEFORMAT_TEXT); sprintf(buf,"models\\%i\\exportflag",exp); remove(buf); return true; } int findVertex(Vect3f *curpoint) { for(int i=0;i<mxVertices;i++) { if (mVertices[i].x==curpoint->x && mVertices[i].y==curpoint->y && mVertices[i].z==curpoint->z) { return i; } } return -1; } void newIndex(Vect3f *curpoint) { //int f=findVertex(curpoint); //if (f>-1) { // mIndexes[mxIndexes]=f; // mxIndexes++; //} else { mVertices[mxVertices].x=curpoint->x; mVertices[mxVertices].y=curpoint->y; mVertices[mxVertices].z=curpoint->z; mIndexes[mxIndexes]=mxVertices; mxVertices++; mxIndexes++; //} } bool checkOrientation(float *p1, float *p2, float *p3) { /* float x1=p2[0]-p1[0]; float y1=p2[1]-p1[1]; float z1=p2[2]-p1[2]; float x2=p3[0]-p1[0]; float y2=p3[1]-p1[1]; float z2=p3[2]-p1[2]; float cf = (x1*x2 + y1*y2 + z1*z2) / sqrtf ((x1*x1 + y1*y1 + z1*z1) * (x2*x2 + y2*y2 + z2*z2)); float ccf = acos(cf); if (cvf<0) return false; */ Vect3f vNormal, oldNormal; float checkx, checky, checkz; vNormal = GetTriangeNormal(&Vect3f(p1[0], p1[1], p1[2]), &Vect3f(p2[0], p2[1], p2[2]), &Vect3f(p3[0], p3[1], p3[2])); oldNormal=getNormal(currentNormal); checkx = (oldNormal.x*vNormal.x)==-0 ? 0 : (oldNormal.x*vNormal.x); checky = (oldNormal.y*vNormal.y)==-0 ? 0 : (oldNormal.y*vNormal.y); checkz = (oldNormal.z*vNormal.z)==-0 ? 0 : (oldNormal.z*vNormal.z); if (checkx<0 || checky<0 || checkz<0) return false; return true; } // Попытки расчета ориентации полигона int orientation(int s, int n) { double area; int i; /* Do the wrap-around first */ area = ver[n-1][2] * ver[s][1] - ver[s][2] * ver[n-1][1]; /* Compute the area (times 2) of the polygon */ for (i = s; i < n-2; i++) { area += ver[i][2] * ver[i+1][1] - ver[i+1][2] * ver[i][1]; } if (area >= 0.0) return COUNTER_CLOCKWISE; else return CLOCKWISE; } /* End of orientation */ int orientation2(int s, int n) { double area; int i; /* Do the wrap-around first */ //area = ver[n-1][0] * ver[s][1] - ver[s][0] * ver[n-1][1]; //area = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1); area = 0; /* Compute the area (times 2) of the polygon */ for (i = s; i < n-3; i++) area += (ver[i+1][0] - ver[i][0]) * (ver[i+2][1] - ver[i][1]) - (ver[i+2][0] - ver[i][0]) * (ver[i+1][1] - ver[i][1]); //area += ver[i][0] * ver[i+1][1] - ver[i+1][0] * ver[i][1]; if (area >= 0.0) return COUNTER_CLOCKWISE; else return CLOCKWISE; } /* End of orientation */ void copyMatrix(D3DXMATRIX *dst, D3DXMATRIX *src) { memcpy(dst, src, sizeof(D3DXMATRIX)); } #define INTERPOLATE(a,b,t) ((1.0f-t)*(a) + t*(b)) // Два варианта расчета кривой Безье // Первый... void eval_bezier2( float *out, float t, float ctrlpoints[4][3]) { float left, right, mid, left_mid, mid_right; // x left = INTERPOLATE(ctrlpoints[0][0], ctrlpoints[1][0], t); mid = INTERPOLATE(ctrlpoints[1][0], ctrlpoints[2][0], t); right = INTERPOLATE(ctrlpoints[2][0], ctrlpoints[3][0], t); left_mid = INTERPOLATE(left, mid, t); mid_right = INTERPOLATE(mid, right, t); out[0]=INTERPOLATE(left_mid, mid_right, t); // y left = INTERPOLATE(ctrlpoints[0][1], ctrlpoints[1][1], t); mid = INTERPOLATE(ctrlpoints[1][1], ctrlpoints[2][1], t); right = INTERPOLATE(ctrlpoints[2][1], ctrlpoints[3][1], t); left_mid = INTERPOLATE(left, mid, t); mid_right = INTERPOLATE(mid, right, t); out[1]=INTERPOLATE(left_mid, mid_right, t); // z left = INTERPOLATE(ctrlpoints[0][2], ctrlpoints[1][2], t); mid = INTERPOLATE(ctrlpoints[1][2], ctrlpoints[2][2], t); right = INTERPOLATE(ctrlpoints[2][2], ctrlpoints[3][2], t); left_mid = INTERPOLATE(left, mid, t); mid_right = INTERPOLATE(mid, right, t); out[2]=INTERPOLATE(left_mid, mid_right, t); } // И второй. // P(t)=P_0*(1-t)^3+P_1*3(1-t)^2*t+P_2*3(1-t)*t2+P_3*t3 void eval_bezier(float *out, float t, float ctrlpoints[4][3]) { float m,a1,a2,a3,a4,t2,t3; t2 = t*t; t3 = t*t*t; m = 1.0f-t; a1 = m*m*m; a2 = 3.0f*(m*m)*t; a3 = 3.0f*m*t2; a4 = t3; out[0]=ctrlpoints[0][0]*a1+ ctrlpoints[1][0]*a2+ ctrlpoints[2][0]*a3+ ctrlpoints[3][0]*a4; out[1]=ctrlpoints[0][1]*a1+ ctrlpoints[1][1]*a2+ ctrlpoints[2][1]*a3+ ctrlpoints[3][1]*a4; out[2]=ctrlpoints[0][2]*a1+ ctrlpoints[1][2]*a2+ ctrlpoints[2][2]*a3+ ctrlpoints[3][2]*a4; } Vect3f GetVertexNormal(Vect3f* vVertex) { //D3DXVECTOR3 vNormal; //D3DXVECTOR3 n = D3DXVECTOR3(0, 0, 0); //D3DXVec3Subtract(&vNormal, &n, vVertex); //vNormal.x = vVertex->x; //vNormal.y = vVertex->y; //vNormal.z = vVertex->z; //D3DXVec3Normalize(&vNormal, &vNormal); Vect3f normal(*vVertex); return normal.normalize(); } Vect3f GetTriangeNormal(Vect3f* vVertex1, Vect3f* vVertex2, Vect3f* vVertex3) { Vect3f vNormal; Vect3f v1; Vect3f v2; //D3DXVec3Subtract(&v1, vVertex1, vVertex3); //D3DXVec3Subtract(&v2, vVertex2, vVertex3); //D3DXVec3Cross(&vNormal, &v1, &v2); //D3DXVec3Normalize(&vNormal, &vNormal); v1 = *vVertex1 - *vVertex3; v2 = *vVertex2 - *vVertex3; vNormal.cross(v1,v2); return vNormal; } void cp(float *v,float *v1,float *v2) { v[0] = v1[1]*v2[2] - v2[1]*v1[2]; v[1] = v1[2]*v2[0] - v2[2]*v1[0]; v[2] = v1[0]*v2[1] - v2[0]*v1[1]; v[0] = v[0] == -0 ? 0 : v[0]; v[1] = v[1] == -0 ? 0 : v[1]; v[2] = v[2] == -0 ? 0 : v[2]; return; } void norm(float *v) { float c; c = 1/sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0] *= c; v[1] *= c; v[2] *= c; v[0] = v[0] == -0 ? 0 : v[0]; v[1] = v[1] == -0 ? 0 : v[1]; v[2] = v[2] == -0 ? 0 : v[2]; return; } D3DVECTOR GetPTriangeNormal(float *v1, float *v2, float *v3) { D3DXVECTOR3 vNormal; float n[3]; v1[0] = v1[0] == -0 ? 0 : v1[0]; v1[1] = v1[1] == -0 ? 0 : v1[1]; v1[2] = v1[2] == -0 ? 0 : v1[2]; v2[0] = v2[0] == -0 ? 0 : v2[0]; v2[1] = v2[1] == -0 ? 0 : v2[1]; v2[2] = v2[2] == -0 ? 0 : v2[2]; v3[0] = v3[0] == -0 ? 0 : v3[0]; v3[1] = v3[1] == -0 ? 0 : v3[1]; v3[2] = v3[2] == -0 ? 0 : v3[2]; float edge1[3],edge2[3]; int j; for (j=0;j<3;j++) { edge1[j] = v1[j] - v2[j]; edge2[j] = v3[j] - v2[j]; } cp(n,edge1,edge2); norm(n); vNormal.x=n[0]; vNormal.y=n[1]; vNormal.z=n[2]; return vNormal; } #define RAD_2_DEG 57.295779513082323f void DrawRealCircle(float *p1, float radius1, Vect3f normal, int m_nSegments) { int nCurrentSegment; D3DXMATRIX trans, trans2; D3DXMatrixIdentity(&trans); D3DXMatrixIdentity(&trans2); VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,(m_nSegments*2+10)*vertexBuffer.vertexSize); Color4c color = currentColor; int curver=vertexNum; int amount=0; float rDeltaSegAngle = (2.0f * D3DX_PI / m_nSegments); float rSegmentLength = 1.0f / (float)m_nSegments; //Create the triangle fan: Center Vertices->pos.set(0.0f+p1[0],0.0f - (radius1 / 2.0f)+p1[1],0.0f+p1[2]); Vertices->difuse = color; Vertices->u1() = 0.5f; Vertices->v1() = 0.5f; Vertices->n.set(0.0f,-1.0f,0.0f); Vertices++; vertexNum++; amount++; //Create the triangle fan: Edges for(nCurrentSegment = m_nSegments; nCurrentSegment >= 0; nCurrentSegment--) { float x0 = radius1 * sinf(nCurrentSegment * rDeltaSegAngle); float z0 = radius1 * cosf(nCurrentSegment * rDeltaSegAngle); Vertices->pos.set(x0+p1[0],0.0f - (radius1 / 2.0f)+p1[1],z0+p1[2]); Vertices->difuse = color; Vertices->u1() =(0.5f * sinf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->v1() = (0.5f * cosf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->n.set(0.0f,-1.0f,0.0f); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_FAN; vertexType[curver].amount = amount; vertexType[curver].textNum = currentTex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; renderSystem->UnlockVertexBuffer(vertexBuffer); } void DrawRealCylinder(float *p1, float *p2, float radius1, float radius2, bool s1, bool s2, bool s3) { int nCurrentSegment; int m_nSegments=20; Vect3f diff; double h; float x0, z0; D3DXVECTOR3 v; D3DXMATRIX trans1, trans2, trans3; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,(200)*vertexBuffer.vertexSize); diff.x = p2[0] - p1[0]; diff.y = p2[1] - p1[1]; diff.z = p2[2] - p1[2]; h = sqrt (diff.x*diff.x + diff.y*diff.y + diff.z*diff.z); //glTranslatef (v1[0], v1[1], v1[2]); //glRotatef (-RAD_2_DEG * (atan2 (vdiff[2], vdiff[0]) - M_PI/2), 0.0f, 1.0f, 0.0f); //glRotatef (-RAD_2_DEG * asin (vdiff[1]/h), 1.0f, 0.0f, 0.0f); D3DXMatrixIdentity(&trans1); D3DXMatrixIdentity(&trans2); D3DXMatrixIdentity(&trans3); D3DXMatrixTranslation(&trans1, (p1[0]+p2[0])/2, (p1[1]+p2[1])/2,(p1[2]+p2[2])/2); float a1=-(atan2 (diff.z, diff.x) - M_PI/2); float a2=-asin (diff.y/h); D3DXMatrixRotationY(&trans2, a1); D3DXMatrixRotationX(&trans3, a2); //D3DXMatrixMultiply(&trans2, &trans3, &trans2); D3DXMatrixMultiply(&trans1, &trans2, &trans1); D3DXMatrixMultiply(&trans1, &trans3, &trans1); Color4c color = currentColor; int curver=vertexNum; int amount=0; float rDeltaSegAngle = (2.0f * D3DX_PI / m_nSegments); float rSegmentLength = 1.0f / (float)m_nSegments; if (s1) { //Create the sides triangle strip for(nCurrentSegment = 0; nCurrentSegment <= m_nSegments; nCurrentSegment++) { x0 = radius1 * sinf(nCurrentSegment * rDeltaSegAngle); z0 = radius1 * cosf(nCurrentSegment * rDeltaSegAngle); v.x=x0; v.z=0.0f+(h/2.0f); v.y=z0; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() = 1.0f - (rSegmentLength * (float)nCurrentSegment); Vertices->v1() = 0.0; Vertices->n.set(x0,0.0f,z0); Vertices++; vertexNum++; amount++; x0 = radius2 * sinf(nCurrentSegment * rDeltaSegAngle); z0 = radius2 * cosf(nCurrentSegment * rDeltaSegAngle); v.x=x0; v.z=0.0f-(h/2.0f); v.y=z0; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() = 1.0f - (rSegmentLength * (float)nCurrentSegment); Vertices->v1() = 1.0f; Vertices->n.set(x0,0.0f,z0); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_STRIP; vertexType[curver].amount = amount; vertexType[curver].textNum = currentTex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; curver=vertexNum; amount=0; } if (s2) { //Create the top triangle fan: Center v.x=0.0f; v.z=0.0f+(h/2.0f); v.y=0.0f; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() = 0.5f; Vertices->v1() = 0.5f; Vertices->n.set(0.0f,1.0f,0.0f); Vertices++; vertexNum++; amount++; //Create the top triangle fan: Edges for(nCurrentSegment = 0; nCurrentSegment <= m_nSegments; nCurrentSegment++) { x0 = radius1 * sinf(nCurrentSegment * rDeltaSegAngle); z0 = radius1 * cosf(nCurrentSegment * rDeltaSegAngle); v.x=x0; v.z=0.0f+(h/2.0f); v.y=z0; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() =(0.5f * sinf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->v1() = (0.5f * cosf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->n.set(0.0f,1.0f,0.0f); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_FAN; vertexType[curver].amount = amount; vertexType[curver].textNum = currentTex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; curver=vertexNum; amount=0; } if (s3) { //Create the bottom triangle fan: Center Vertices->pos.set(0.0f+p1[0],0.0f - (radius1 / 2.0f)+p1[1],0.0f+p1[2]); v.x=0.0f; v.z=0.0f-(h/2.0f); v.y=0.0f; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() = 0.5f; Vertices->v1() = 0.5f; Vertices->n.set(0.0f,-1.0f,0.0f); Vertices++; vertexNum++; amount++; //Create the bottom triangle fan: Edges for(nCurrentSegment = m_nSegments; nCurrentSegment >= 0; nCurrentSegment--) { x0 = radius2 * sinf(nCurrentSegment * rDeltaSegAngle); z0 = radius2 * cosf(nCurrentSegment * rDeltaSegAngle); v.x=x0; v.z=0.0f-(h/2.0f); v.y=z0; D3DXVec3TransformCoord(&v,&v,&trans1); Vertices->pos.set(v.x, v.y, v.z); Vertices->difuse = color; Vertices->u1() =(0.5f * sinf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->v1() = (0.5f * cosf(nCurrentSegment * rDeltaSegAngle)) + 0.5f; Vertices->n.set(0.0f,-1.0f,0.0f); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_FAN; vertexType[curver].amount = amount; vertexType[curver].textNum = currentTex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; } renderSystem->UnlockVertexBuffer(vertexBuffer); } _inline float Noise(int x, int y) { int n = x + y * 57; n = (n<<13) ^ n; float ret = ( 1.0f - ( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f); if (ret < 0) ret = 0; return ret; } void DrawPlanetSphere(float *p1, float radius, int tex, int n) { D3DXVECTOR3 vNormal; Color4c color; int i, j; double theta1,theta2,theta3; if (exportb[currentModel]==true && splineExport==true) return; int amount=0; float cx=(float)*p1; float cy=(float)*(p1+1); float cz=(float)*(p1+2); int l=n/2*n*2+2; //Lock the vertex buffer //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,l,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,l*vertexBuffer.vertexSize); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); int curver=vertexNum; float TWOPI = 6.28318530717958f; float PIDIV2 = 1.57079632679489f; float ex = 0.0f; float ey = 0.0f; float ez = 0.0f; float px = 0.0f; float py = 0.0f; float pz = 0.0f; // Disallow a negative number for radius. //if( r < 0 ) // r = -r; // Disallow a negative number for precision. //if( p < 0 ) // p = -p; // If the sphere is too small, just render a OpenGL point instead. /* if( p < 4 || r <= 0 ) { glBegin( GL_POINTS ); glVertex3f( cx, cy, cz ); glEnd(); return; } */ float snt1, cnt1, snt2, cnt2, snt3, cnt3; float radius2; if (n<60) j = 1; else j = 0; for(;j < n/2; j++ ) { theta1 = j * TWOPI / n - PIDIV2; theta2 = (j + 1) * TWOPI / n - PIDIV2; snt1 = sin(theta1); snt2 = sin(theta2); cnt1 = cos(theta1); cnt2 = cos(theta2); amount=0; curver=vertexNum; for( int i = 0; i <= n; i++ ) { theta3 = i * (TWOPI) / n; snt3 = sin(theta3); cnt3 = cos(theta3); radius2 = radius;// + Noise(i/(double)n*100, 2*j/(double)n*100)*1000; ex = cnt1 * cnt3; ey = snt1; ez = cnt1 * snt3; px = cx + radius2 * ex; py = cy + radius2 * ey; pz = cz + radius2 * ez; Vertices->pos.set(px,py,pz); Vertices->difuse = color; Vertices->u1() = i/(double)n; Vertices->v1() = 2*j/(double)n; Vertices->n.set(ex,ey,ez); Vertices++; vertexNum++; amount++; radius2 = radius;// + Noise(i/(double)n*100, 2*(j+1)/(double)n*100)*1000; ex = cnt2 * cnt3; ey = snt2; ez = cnt2 * snt3; px = cx + radius2 * ex; py = cy + radius2 * ey; pz = cz + radius2 * ez; Vertices->pos.set(px,py,pz); Vertices->difuse = color; Vertices->u1() = i/(double)n; Vertices->v1() = 2*(j+1)/(double)n; Vertices->n.set(ex,ey,ez); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_STRIP; vertexType[curver].amount = amount; vertexType[curver].textNum = tex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; } renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } // Кривовато void DrawRealSphere(float *p1, float radius, int tex, int n) { D3DXVECTOR3 vNormal; Color4c color; int i, j; double theta1,theta2,theta3; if (exportb[currentModel]==true && splineExport==true) return; int amount=0; float cx=(float)*p1; float cy=(float)*(p1+1); float cz=(float)*(p1+2); int l=n/2*n*2+2; //Lock the vertex buffer //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,l,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,l*vertexBuffer.vertexSize); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); int curver=vertexNum; float TWOPI = 6.28318530717958f; float PIDIV2 = 1.57079632679489f; float ex = 0.0f; float ey = 0.0f; float ez = 0.0f; float px = 0.0f; float py = 0.0f; float pz = 0.0f; // Disallow a negative number for radius. //if( r < 0 ) // r = -r; // Disallow a negative number for precision. //if( p < 0 ) // p = -p; // If the sphere is too small, just render a OpenGL point instead. /* if( p < 4 || r <= 0 ) { glBegin( GL_POINTS ); glVertex3f( cx, cy, cz ); glEnd(); return; } */ float snt1, cnt1, snt2, cnt2, snt3, cnt3; if (n<60) j = 1; else j = 0; for(;j < n/2; j++ ) { theta1 = j * TWOPI / n - PIDIV2; theta2 = (j + 1) * TWOPI / n - PIDIV2; snt1 = sin(theta1); snt2 = sin(theta2); cnt1 = cos(theta1); cnt2 = cos(theta2); amount=0; curver=vertexNum; for( int i = 0; i <= n; i++ ) { theta3 = i * (TWOPI) / n; snt3 = sin(theta3); cnt3 = cos(theta3); ex = cnt1 * cnt3; ey = snt1; ez = cnt1 * snt3; px = cx + radius * ex; py = cy + radius * ey; pz = cz + radius * ez; Vertices->pos.set(px,py,pz); Vertices->difuse = color; Vertices->u1() = i/(double)n; Vertices->v1() = 2*j/(double)n; Vertices->n.set(ex,ey,ez); Vertices++; vertexNum++; amount++; ex = cnt2 * cnt3; ey = snt2; ez = cnt2 * snt3; px = cx + radius * ex; py = cy + radius * ey; pz = cz + radius * ez; Vertices->pos.set(px,py,pz); Vertices->difuse = color; Vertices->u1() = i/(double)n; Vertices->v1() = 2*(j+1)/(double)n; Vertices->n.set(ex,ey,ez); Vertices++; vertexNum++; amount++; } vertexType[curver].type = GL_TRIANGLE_STRIP; vertexType[curver].amount = amount; vertexType[curver].textNum = tex; vertexType[curver].doLight=doLight; vertexType[curver].transparent=transparent; } renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } void DrawRealLine(float *p1, float *p2) { Color4c color; D3DXVECTOR3 vNormal; if (vertexNum>MAXVERT-100) return; //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*2,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,2*vertexBuffer.vertexSize); color = currentColor; Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = GL_LINES; vertexType[vertexNum].amount = 2; vertexType[vertexNum].textNum = -1; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=false; //vNormal = GetVertexNormal(&(Vertices->pos)); Vertices->n = GetVertexNormal(&(Vertices->pos)); Vertices++; vertexNum++; Vertices->pos.x = (float)*p2; Vertices->pos.y = (float)*(p2+1); Vertices->pos.z = (float)*(p2+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)1; //vNormal = GetVertexNormal(&D3DXVECTOR3(Vertices->pos.x, Vertices->pos.y, Vertices->pos.z)); Vertices->n = GetVertexNormal(&(Vertices->pos)); Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } int tc=0; // Используется для возвратных вершин тесселятора void addVertex(double *p1, int type) { Vect3f vNormal; Color4c color; Vect3f curPoint; curPoint=Vect3f((float)p1[0], (float)p1[1], (float)p1[2]); newIndex(&curPoint); if (vertexNum>MAXVERT-100) return; //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*1,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,1*vertexBuffer.vertexSize); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); Vertices->pos.x = (float)p1[0]; Vertices->pos.y = (float)p1[1]; Vertices->pos.z = (float)p1[2]; Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; if (currentNormal!=0) { //vNormal = getReNormal(currentNormal); //vNormal = getNormal(currentNormal); Vertices->n = getNormal(currentNormal); } else { Vertices->n.set(0,0,0); } Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } void DrawRealSquare(float *p1, float *p2, float *p3, float *p4, int normal) { Color4c color; Vect3f vNormal; float corrector; if (exportb[currentModel]==true && splineExport==true) return; if (vertexNum>MAXVERT-100) return; //vNormal = GetTriangeNormal(&D3DXVECTOR3((float)*p1, (float)*(p1+1), (float)*(p1+2)) // ,&D3DXVECTOR3((float)*p2, (float)*(p2+1), (float)*(p2+2)) // ,&D3DXVECTOR3((float)*p3, (float)*(p3+1), (float)*(p3+2))); Vect3f curPoint; curPoint=Vect3f((float)*p1, (float)*(p1+1), (float)*(p1+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p4, (float)*(p4+1), (float)*(p4+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p4, (float)*(p4+1), (float)*(p4+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p2, (float)*(p2+1), (float)*(p2+2)); newIndex(&curPoint); //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*4,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,4*vertexBuffer.vertexSize); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); vertexType[vertexNum].vertCount=4; vertexType[vertexNum].type = GL_TRIANGLE_STRIP; vertexType[vertexNum].amount = 4; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)1; if (normal!=0) { //vNormal = getNormal(normal); Vertices->n = getNormal(normal); } else { Vertices->n.set(0,0,0); } Vertices++; vertexNum++; Vertices->pos.x = (float)*p4; Vertices->pos.y = (float)*(p4+1); Vertices->pos.z = (float)*(p4+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; if (normal!=0) { //vNormal = getNormal(normal); Vertices->n = getNormal(normal); } else { Vertices->n.set(0,0,0); } Vertices++; vertexNum++; Vertices->pos.x = (float)*p3; Vertices->pos.y = (float)*(p3+1); Vertices->pos.z = (float)*(p3+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)1; if (normal!=0) { //vNormal = getNormal(normal); Vertices->n = getNormal(normal); } else { Vertices->n.set(0,0,0); } Vertices++; vertexNum++; Vertices->pos.x = (float)*p2; Vertices->pos.y = (float)*(p2+1); Vertices->pos.z = (float)*(p2+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)0; if (normal!=0) { //vNormal = getNormal(normal); Vertices->n = getNormal(normal); } else { Vertices->n.set(0,0,0); } Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } #define absd(a) ((a)>=0?(float)(a):(float)-(a)) void DrawRealTriangle(float *p1, float *p2, float *p3, int type, int normal); void DrawRealSquare2(float *p1, float *p2, float *p3, float *p4, int normal) { Color4c color; Vect3f vNormal; double ax, ay, az; double bx, by, bz; double cx, cy, cz; if (exportb[currentModel]==true && splineExport==true) return; if (vertexNum>MAXVERT-100) return; //p1[1]-=0.002f; //p2[1]-=0.002f; //p3[1]-=0.002f; //p4[1]-=0.002f; //p1[2]+=0.02f; //p2[2]+=0.02f; //p3[2]+=0.02f; //p4[2]+=0.02f; Vect3f curPoint; curPoint=Vect3f((float)*p1, (float)*(p1+1), (float)*(p1+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p4, (float)*(p4+1), (float)*(p4+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p4, (float)*(p4+1), (float)*(p4+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p2, (float)*(p2+1), (float)*(p2+2)); newIndex(&curPoint); ax=*p1/2+*p2/2; ay=*(p1+1)/2+*(p2+1)/2; az=*(p1+2)/2+*(p2+2)/2; bx=*p3/2+*p4/2; by=*(p3+1)/2+*(p4+1)/2; bz=*(p3+2)/2+*(p4+2)/2; cx=ax/2+bx/2; cy=ay/2+by/2; cz=az/2+bz/2; vNormal = getNormal(normal); color = currentColor; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,6*vertexBuffer.vertexSize); Vertices->pos.x = (float)cx; Vertices->pos.y = (float)cy; Vertices->pos.z = (float)cz; Vertices->difuse = color; Vertices->u1() = 0.5f; Vertices->v1() = 0.5f; vertexType[vertexNum].type = GL_TRIANGLE_FAN; vertexType[vertexNum].amount = 6; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)1; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p2; Vertices->pos.y = (float)*(p2+1); Vertices->pos.z = (float)*(p2+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p3; Vertices->pos.y = (float)*(p3+1); Vertices->pos.z = (float)*(p3+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)0; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p4; Vertices->pos.y = (float)*(p4+1); Vertices->pos.z = (float)*(p4+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)1; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)1; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); // d3d_vb->Unlock(); } void DrawRealTriangle(float *p1, float *p2, float *p3, int type, int normal) { Color4c color; Vect3f vNormal; if (exportb[currentModel]==true && splineExport==true) return; if (vertexNum>MAXVERT-100) return; /* int zzz=0; D3DXVECTOR3 oldNormal; float pp1[3],pp2[3],pp3[3]; vNormal = GetTriangeNormal(&Vect3f((float)*p1, (float)*(p1+1), (float)*(p1+2)) ,&Vect3f((float)*p2, (float)*(p2+1), (float)*(p2+2)) ,&Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2))); oldNormal=getNormal(currentNormal); if (currentNormal>0 && (oldNormal.x*vNormal.x<0 || oldNormal.y*vNormal.y<0 || oldNormal.z*vNormal.z<0)) zzz=1; */ /* if ((oldNormal.x>0 && vNormal.x<0) || (oldNormal.x<0 && vNormal.x>0)) zzz=1; if ((oldNormal.y>0 && vNormal.y<0) || (oldNormal.y<0 && vNormal.y>0)) zzz=1; if ((oldNormal.z>0 && vNormal.z<0) || (oldNormal.z<0 && vNormal.z>0)) zzz=1; */ /* if (zzz) { pp1[0]=p3[0]; pp1[1]=p3[1]; pp1[2]=p3[2]; pp3[0]=p1[0]; pp3[1]=p1[1]; pp3[2]=p1[2]; p1[0]=pp1[0]; p1[1]=pp1[1]; p1[2]=pp1[2]; p3[0]=pp3[0]; p3[1]=pp3[1]; p3[2]=pp3[2]; } */ Vect3f curPoint; curPoint=Vect3f((float)*p1, (float)*(p1+1), (float)*(p1+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p2, (float)*(p2+1), (float)*(p2+2)); newIndex(&curPoint); curPoint=Vect3f((float)*p3, (float)*(p3+1), (float)*(p3+2)); newIndex(&curPoint); //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*3,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,3*vertexBuffer.vertexSize); vNormal = getNormal(normal); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)1; vertexType[vertexNum].type = GL_TRIANGLES; vertexType[vertexNum].amount = 3; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p2; Vertices->pos.y = (float)*(p2+1); Vertices->pos.z = (float)*(p2+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; Vertices->pos.x = (float)*p3; Vertices->pos.y = (float)*(p3+1); Vertices->pos.z = (float)*(p3+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)1; Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } void DrawCustomTriangle(Vect3f *p1, Vect3f *p2, Vect3f *p3, Vect3f *n1, Vect3f *n2, Vect3f *n3, int color1, int color2, int color3) { Color4c color; Vect3f vNormal; short r, g, b; if (vertexNum>MAXVERT-100) return; Vect3f curPoint; curPoint.x=p1->x; curPoint.y=p1->y; curPoint.z=p1->z; newIndex(&curPoint); curPoint.x=p2->x; curPoint.y=p2->y; curPoint.z=p2->z; newIndex(&curPoint); curPoint.x=p3->x; curPoint.y=p3->y; curPoint.z=p3->z; newIndex(&curPoint); VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,3*vertexBuffer.vertexSize); r=(color1&0x00FF0000)>>16; g=(color1&0x0000FF00)>>8; b=(color1&0x000000FF); color.set(b*31, g*31, r*31); Vertices->pos.x = p1->x; Vertices->pos.y = p1->y; Vertices->pos.z = p1->z; Vertices->difuse = color; Vertices->u1() = (float)1; Vertices->v1() = (float)1; vertexType[vertexNum].type = GL_TRIANGLES; vertexType[vertexNum].amount = 3; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; if (n1->x==0) { vNormal = GetTriangeNormal(p1,p2,p3); Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; } else { Vertices->n.x = n1->x; Vertices->n.y = n1->y; Vertices->n.z = n1->z; } Vertices->n.normalize(); Vertices++; vertexNum++; r=(color2&0x00FF0000)>>16; g=(color2&0x0000FF00)>>8; b=(color2&0x000000FF); color.set(b*31, g*31, r*31); Vertices->pos.x = p2->x; Vertices->pos.y = p2->y; Vertices->pos.z = p2->z; Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=true; if (n1->x==0) { Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; } else { Vertices->n.x = n2->x; Vertices->n.y = n2->y; Vertices->n.z = n2->z; } Vertices->n.normalize(); Vertices++; vertexNum++; r=(color3&0x00FF0000)>>16; g=(color3&0x0000FF00)>>8; b=(color3&0x000000FF); color.set(b*31, g*31, r*31); Vertices->pos.x = p3->x; Vertices->pos.y = p3->y; Vertices->pos.z = p3->z; Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)1; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = currentTex; vertexType[vertexNum].doLight=true; if (n1->x==0) { Vertices->n.x = vNormal.x; Vertices->n.y = vNormal.y; Vertices->n.z = vNormal.z; } else { Vertices->n.x = n3->x; Vertices->n.y = n3->y; Vertices->n.z = n3->z; } Vertices->n.normalize(); Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } // Лампочки void DrawRealPoint(float *p1, unsigned int radius) { Color4c color; if (vertexNum>MAXVERT-100) return; //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*1,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,1*vertexBuffer.vertexSize); //if (currentTex==0 || useLocalColor) color = currentColor; //else // color.set(255,255,255); Vertices->pos.x = (float)*p1; Vertices->pos.y = (float)*(p1+1); Vertices->pos.z = (float)*(p1+2); Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = GL_POINTS; vertexType[vertexNum].radius = (float)(radius<<currentScale)/DIVIDER/DIVIDER; //vertexType[vertexNum].radius = (float)radius/DIVIDER/50; vertexType[vertexNum].textNum = 602; vertexType[vertexNum].doLight=doLight; vertexType[vertexNum].transparent=transparent; Vertices->n.x = 0; Vertices->n.y = 0; Vertices->n.z = 0; Vertices++; vertexNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } // Кривовато void DrawBillboard(float *p1, float width) { float bp1[3], bp2[3], bp3[3], bp4[3]; if (exportb[currentModel]==true && splineExport==true) return; D3DXMATRIX billMatrix; D3DXVECTOR3 v1, v2, v3, vt; D3DXMatrixInverse(&billMatrix,NULL, &mainRotMatrix); D3DXMatrixMultiply(&billMatrix, &posMatrix, &billMatrix); v1.x = billMatrix[12]; v1.y = billMatrix[13]; v1.z = billMatrix[14]; D3DXVec3Normalize(&v1, &v1); vt.x = 0.0f; vt.y = 1.0f; vt.z = 0.0f; D3DXVec3Cross(&v2, &v1, &vt); D3DXVec3Normalize(&v2, &v2); D3DXVec3Cross(&v3, &v1, &v2); D3DXVec3Normalize(&v3, &v3); v2*=width/2; v3*=width/2; bp1[0]=p1[0]-v2.x-v3.x; bp1[1]=p1[1]-v2.y-v3.y; bp1[2]=p1[2]-v2.z-v3.z; bp2[0]=p1[0]-v2.x+v3.x; bp2[1]=p1[1]-v2.y+v3.y; bp2[2]=p1[2]-v2.z+v3.z; bp3[0]=p1[0]+v2.x-v3.x; bp3[1]=p1[1]+v2.y-v3.y; bp3[2]=p1[2]+v2.z-v3.z; bp4[0]=p1[0]+v2.x+v3.x; bp4[1]=p1[1]+v2.y+v3.y; bp4[2]=p1[2]+v2.z+v3.z; DrawRealSquare(bp1, bp4, bp3, bp2, 0); } void drawBillLine(float *p1, float *p2, float width) { float bp1[3], bp2[3], bp3[3], bp4[3]; D3DXVECTOR4 out; D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); p1[0] = out.x; p1[1] = out.y; p1[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(p2[0],p2[1],p2[2]), &mainRotMatrix); p2[0] = out.x; p2[1] = out.y; p2[2] = out.z; //D3DXMATRIX billMatrix; //D3DXMatrixInverse(&billMatrix,NULL, &mainRotMatrix); //D3DXMatrixMultiply(&billMatrix, &posMatrix, &billMatrix); D3DXVECTOR3 v1, v2, v3; v1.x=p1[0]+posMatrix[12]; v1.y=p1[1]+posMatrix[13]; v1.z=p1[2]+posMatrix[14]; D3DXVec3Normalize(&v1, &v1); v2.x=p2[0]+posMatrix[12]; v2.y=p2[1]+posMatrix[13]; v2.z=p2[2]+posMatrix[14]; D3DXVec3Normalize(&v2, &v2); D3DXVec3Cross(&v3, &v1, &v2); D3DXVec3Normalize(&v3, &v3); width/=2; bp1[0]=v3.x*width+p1[0]; bp1[1]=v3.y*width+p1[1]; bp1[2]=v3.z*width+p1[2]; bp2[0]=(-v3.x)*width+p1[0]; bp2[1]=(-v3.y)*width+p1[1]; bp2[2]=(-v3.z)*width+p1[2]; bp3[0]=bp1[0]+(p2[0]-p1[0]); bp3[1]=bp1[1]+(p2[1]-p1[1]); bp3[2]=bp1[2]+(p2[2]-p1[2]); bp4[0]=bp2[0]+(p2[0]-p1[0]); bp4[1]=bp2[1]+(p2[1]-p1[1]); bp4[2]=bp2[2]+(p2[2]-p1[2]); D3DXMATRIX invMatrix; D3DXMatrixInverse(&invMatrix,NULL, &mainRotMatrix); D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &invMatrix); p1[0] = out.x; p1[1] = out.y; p1[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(p2[0],p2[1],p2[2]), &invMatrix); p2[0] = out.x; p2[1] = out.y; p2[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(bp1[0],bp1[1],bp1[2]), &invMatrix); bp1[0] = out.x; bp1[1] = out.y; bp1[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(bp2[0],bp2[1],bp2[2]), &invMatrix); bp2[0] = out.x; bp2[1] = out.y; bp2[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(bp3[0],bp3[1],bp3[2]), &invMatrix); bp3[0] = out.x; bp3[1] = out.y; bp3[2] = out.z; D3DXVec3Transform(&out,&D3DXVECTOR3(bp4[0],bp4[1],bp4[2]), &invMatrix); bp4[0] = out.x; bp4[1] = out.y; bp4[2] = out.z; //DrawRealLine(p1, bp1); //DrawRealLine(p1, bp2); //DrawRealLine(p2, bp3); //DrawRealLine(p2, bp4); DrawRealSquare(bp2, bp3, bp4, bp1, 0); } void copyVertex(float *p1, float *p2) { p1[0]=p2[0]; p1[1]=p2[1]; p1[2]=p2[2]; } void plusVertex(double *mass, float *p) { mass[0]=p[0]; mass[1]=p[1]; mass[2]=p[2]; } // Получить глобальную или локальную переменную модели int getVar(unsigned short cmd) { int t, result; if (callAsm) { return FUNC_001473_getVar(gptr, (int)cmd); } else { if ((unsigned char)(cmd&0xC0)==0xC0) { t=cmd&0x3F; return localvar[t]; //return FUNC_001473_getVar(gptr, (int)cmd); } else if ((unsigned char)(cmd&0xC0)==0x80) { t=cmd&0x3F; result=globalvar[t]; return result; //return FUNC_001473_getVar(gptr, (int)cmd); } else if ((unsigned char)(cmd&0xC0)==0x40) { //t=cmd&0x3F; //t=t<<10; //t=cmd<<10; //cmd=cmd&0x3F; t=((cmd & 0x7f)<<9)+((cmd >> 7) & 0x1ff); //t/=25; return t; } else if ((unsigned char)(cmd&0xC0)==0x00) { t=((cmd & 0x7f)<<9)+((cmd >> 7) & 0x1ff); //t/=25; return t; } else { return 0; } } } inline signed char getByte(void *offs, int num) { if (num%2>0) return *(((char *)offs+2)+num-1); else return *(((char *)offs+2)+num+1); } signed char getByte2(void *offs, int num) { return *(((char *)offs)+num); } Vect3f getNormal(unsigned char num) { Vect3f normal; if (mod!=NULL && mod->Normals_ptr!=NULL && num>0) { char *normalPtr = mod->Normals_ptr+(num/2-1)*6; normal.x=(float)*(normalPtr+2); normal.y=(float)*(normalPtr+3); normal.z=(float)*(normalPtr+4); if (num%2>0) normal.x*=-1; /* D3DXMATRIX tmpMatrix; D3DXMatrixIdentity(&tmpMatrix); tmpMatrix[12]=normal.x; tmpMatrix[13]=normal.y; tmpMatrix[14]=normal.z; D3DXMatrixMultiply(&tmpMatrix, &mainRotMatrix, &tmpMatrix); normal.x=tmpMatrix[12]; normal.y=tmpMatrix[13]; normal.z=tmpMatrix[14]; */ //D3DXVec3Normalize(&normal, &normal); normal.normalize(); } else { normal.x=0; normal.y=0; normal.z=0; } return normal; } Vect3f getReNormal(unsigned char num) { Vect3f vNormal1, vNormal2, normal; if (mod->Normals_ptr!=NULL && num>0) { vNormal1 = GetVertexNormal(&Vect3f(Vertices->p.x, Vertices->p.y, Vertices->p.z)); char *normalPtr = mod->Normals_ptr+(num/2-1)*6; vNormal2.x=(float)*(normalPtr+2); vNormal2.y=(float)*(normalPtr+3); vNormal2.z=(float)*(normalPtr+4); if (num%2>0) vNormal2.x*=-1; /* D3DXMATRIX tmpMatrix; D3DXMatrixIdentity(&tmpMatrix); tmpMatrix[12]=vNormal2.x; tmpMatrix[13]=vNormal2.y; tmpMatrix[14]=vNormal2.z; D3DXMatrixMultiply(&tmpMatrix, &mainRotMatrix, &tmpMatrix); vNormal2.x=tmpMatrix[12]; vNormal2.y=tmpMatrix[13]; vNormal2.z=tmpMatrix[14]; */ //D3DXVec3Normalize(&vNormal2, &vNormal2); vNormal2.normalize(); normal.x = (float)(vNormal1.x/2+vNormal2.x/6); normal.y = (float)(vNormal1.y/2+vNormal2.y/6); normal.z = (float)(vNormal1.z/2+vNormal2.z/6); //D3DXVec3Normalize(&normal, &normal); normal.normalize(); } else { normal.x=0; normal.y=0; normal.z=0; } //return vNormal1; return normal; } char * getVertexPtr(unsigned char num) { return mod->Vertices_ptr+num/2*6; } // Получить вершину, переданную субобъекту предыдущим объектом. Не уверен, что правильно. // Используется, например, для совмещения внутреннего помещения станции со входом. void getExpVertex(float *p, int vertNum) { int num; num=vertNum-251; expVert[0]=(float)*(int*)(*(unsigned int*)(gptr+0x80-num*4)+4)/DIVIDER; expVert[1]=(float)*(int*)(*(unsigned int*)(gptr+0x80-num*4)+8)/DIVIDER; expVert[2]=(float)*(int*)(*(unsigned int*)(gptr+0x80-num*4)+12)/DIVIDER; expVertOrigin[0]=(float)*(int*)(*(unsigned int*)(gptr+0x70)+4)/DIVIDER; expVertOrigin[1]=(float)*(int*)(*(unsigned int*)(gptr+0x70)+8)/DIVIDER; expVertOrigin[2]=(float)*(int*)(*(unsigned int*)(gptr+0x70)+12)/DIVIDER; p[0]=expVert[0]-expVertOrigin[0]; p[1]=expVert[1]-expVertOrigin[1]; p[2]=expVert[2]-expVertOrigin[2]; if (num==0) { prevPoint[0]=(float)((long)(p[0]*100*DIVIDER)>>currentScale); prevPoint[1]=(float)((long)(p[1]*100*DIVIDER)>>currentScale); prevPoint[2]=(float)((long)(p[2]*100*DIVIDER)>>currentScale); prevPoint[0]/=100; prevPoint[1]/=100; prevPoint[2]/=100; } D3DXMATRIX tmpMatrix, oneMatrix; D3DXMatrixIdentity(&tmpMatrix); D3DXMatrixIdentity(&oneMatrix); tmpMatrix[12]=p[0]; tmpMatrix[13]=p[1]; tmpMatrix[14]=p[2]; D3DXMatrixInverse(&oneMatrix,NULL, &mainRotMatrix); D3DXMatrixMultiply(&tmpMatrix, &tmpMatrix, &oneMatrix); p[0]=tmpMatrix[12]; p[1]=tmpMatrix[13]; p[2]=tmpMatrix[14]; } // Вершины имеют типы. См. доки от Jongware. void getTransVertex(float *p, int vertNum) { int rnd; float pta[3], ptb[3], ptc[3]; char *vertOffs; vertOffs = getVertexPtr(vertNum); if (vertNum<=250) { p[0]=(float)*(vertOffs+2); p[1]=(float)*(vertOffs+3); p[2]=(float)*(vertOffs+4); if (*(vertOffs)==5) { // Обычная вершина getTransVertex(pta, (unsigned char)p[2]); p[0]=pta[0]*-1; p[1]=pta[1]*-1; p[2]=pta[2]*-1; } else if (*(vertOffs)==7) { // Со случайной величиной getTransVertex(pta, (unsigned char)p[2]); rnd=(int)p[2]/10; p[0]=pta[0]+ (rnd > 0 ? (rand()%rnd-rnd/2) : 0.0f); p[1]=pta[1]+ (rnd > 0 ? (rand()%rnd-rnd/2) : 0.0f); p[2]=pta[2]+ (rnd > 0 ? (rand()%rnd-rnd/2) : 0.0f); } else if (*(vertOffs)==11) { // Среднее между getTransVertex(pta, (unsigned char)p[2]); getTransVertex(ptb, (unsigned char)p[1]); p[0]=pta[0]/2+ptb[0]/2; p[1]=pta[1]/2+ptb[1]/2; p[2]=pta[2]/2+ptb[2]/2; } else if (*(vertOffs)==15) { // Комбинация из вершин getTransVertex(pta, (unsigned char)p[0]); getTransVertex(ptb, (unsigned char)p[1]); getTransVertex(ptc, (unsigned char)p[2]); p[0]=ptb[0]+pta[0]-ptc[0]; p[1]=ptb[1]+pta[1]-ptc[1]; p[2]=ptb[2]+pta[2]-ptc[2]; } else if (*(vertOffs)==17) { // Неизвестный тип. Экспериментирую. getTransVertex(pta, (unsigned char)p[0]); pta[2]+=p[1]; pta[0]+=p[1]; p[0]=pta[0]; p[1]=pta[1]; p[2]=pta[2]; //p[0]=prevPoint[0]; //p[1]=prevPoint[1]; //p[2]=prevPoint[2]-4; } else if (*(vertOffs)==19) { // Интерполяция // Частично работает (шасси, опускающиеся крылья) // Не совпадает с оригиналом (туба на skeet cruiser) // Частично глючит (хвост у turner class). Хотя у него // может быть проблема с глоб. или лок. переменными. unsigned short var=getVar((unsigned char)p[0]); getTransVertex(pta, (unsigned char)p[2]); getTransVertex(ptb, (unsigned char)p[1]); p[0]=ptb[0]+(pta[0]-ptb[0])/0xFFFF*var; p[1]=ptb[1]+(pta[1]-ptb[1])/0xFFFF*var; p[2]=ptb[2]+(pta[2]-ptb[2])/0xFFFF*var; } else if (*(vertOffs)==23) { // Неизвестный тип. Экспериментирую getTransVertex(pta, (unsigned char)p[1]); getTransVertex(ptb, (unsigned char)p[2]); p[1]=pta[1]; p[2]=ptb[2]; } if (vertNum%2>0) { p[0]*=-1; } } else { getExpVertex(p, vertNum); } } unsigned char rotate=0; bool rotateNext=false; // Для получения нужной вершины текущей модели inline void getVertex(float *p, unsigned char num, float *origin, unsigned char scale, unsigned char orient) { int sFactor=1; ffeVertex* vertex; D3DXMATRIX tmpMatrix, oneMatrix, twoMatrix; D3DXVECTOR3 v; D3DXMatrixIdentity(&tmpMatrix); D3DXMatrixIdentity(&oneMatrix); D3DXMatrixIdentity(&twoMatrix); if (num==255) { p[0]=0; p[1]=0; p[2]=0; return; } if (true) { //if (DATA_009200[num].unknown6 != 0) { // vertex = &DATA_009200[num]; //} else { vertex = FUNC_001470_getVertex(gptr, num); //} v.x=(float)vertex->x/DIVIDER; v.y=(float)vertex->y/DIVIDER; v.z=(float)vertex->z/DIVIDER; D3DXMatrixInverse(&oneMatrix,NULL, &mainRotMatrixO); D3DXVec3TransformCoord(&v,&v,&oneMatrix); D3DXVec3TransformCoord(&v,&v,&currentMatrix); if (billboardMatrix) { D3DXVec3TransformCoord(&v,&v,&oneMatrix); } p[0]=v.x; p[1]=v.y; p[2]=v.z; } else { if (num<=250) { //getTransVertex(p, num); p[0]=vertbuf[num][0]; p[1]=vertbuf[num][1]; p[2]=vertbuf[num][2]; } else { getExpVertex(p, num); } v.x = p[0]; v.y = p[1]; v.z = p[2]; D3DXVec3TransformCoord(&v,&v,&currentMatrix); if (billboardMatrix) { D3DXMatrixInverse(&oneMatrix,NULL, &mainRotMatrix); D3DXVec3TransformCoord(&v,&v,&oneMatrix); } p[0]=v.x; p[1]=v.y; p[2]=v.z; } if (currentModel<3) { p[0]+=0.01f; p[1]+=0.01f; p[2]+=0.01f; } if ((!currentTex && (currentColor.r==0 && currentColor.g==0 && currentColor.b==0)) || //currentTex==72 || //(currentTex>=90 && currentTex<=93) || //currentTex==93 || //currentTex==441 || (currentTex>=460 && currentTex<=462)) { //int scaleFactor = abs(10-mod->Scale); //float r=(float)((short)mod->Radius>>scaleFactor)*2/DIVIDER; p[0]*=1.015; p[1]*=1.015; p[2]*=1.015; } if (currentColor.r==0 && currentColor.g==238 && currentColor.b==238 && currentTex==0) { if (currentModel==27) { p[0]*=1.08; p[1]*=1.08; p[2]*=1.08; } else { p[0]*=1.02; p[1]*=1.02; p[2]*=1.02; } } } #ifndef CALLBACK # ifdef WIN32 # define CALLBACK __attribute__ ((__stdcall__)) # else # define CALLBACK # endif #endif /* CALLBACK */ int ucount; int curVer; int addit; short currWhich; static D3DXVECTOR3 pNormals[2000]; static D3DXVECTOR3 pNormals2[2000]; static D3DXVECTOR3 pVertices[2000]; static D3DXVECTOR3 pcenter; // Тесселяция стартанула void CALLBACK beginCallback(GLenum which) { curVer=vertexNum; currWhich=which; ucount=0; addit=0; } void CALLBACK errorCallback(GLenum errorCode) { const GLubyte *estring; estring = gluErrorString(errorCode); fprintf(stderr, "Tessellation Error: %s\n", estring); } // Тесселяция закончена. Пересчитаем нормали (глючно) void CALLBACK endCallback(void) { if (ucount == 0) return; vertexType[curVer].type=currWhich; vertexType[curVer].amount = ucount; vertexType[curVer].textNum = currentTex; vertexType[curVer].doLight = doLight; Vect3f vNormal,oldNormal; oldNormal = getNormal(currentNormal); oldNormal.normalize(); vNormal = GetTriangeNormal(&Vect3f(pVertices[1].x, pVertices[1].y, pVertices[1].z), &Vect3f(pVertices[2].x, pVertices[2].y, pVertices[2].z), &Vect3f(pVertices[3].x, pVertices[3].y, pVertices[3].z)); /* for(int i=0;i<ucount;i+=3) { vNormal = GetTriangeNormal(&Vect3f(pVertices[i].x, pVertices[i].y, pVertices[i].z), &Vect3f(pVertices[i+1].x, pVertices[i+1].y, pVertices[i+1].z), &Vect3f(pVertices[i+2].x, pVertices[i+2].y, pVertices[i+2].z)); if ((oldNormal.x>0 && vNormal.x<0) || (oldNormal.x<0 && vNormal.x>0)) vNormal.x*=-1; if ((oldNormal.y>0 && vNormal.y<0) || (oldNormal.y<0 && vNormal.y>0)) vNormal.y*=-1; if ((oldNormal.z>0 && vNormal.z<0) || (oldNormal.z<0 && vNormal.z>0)) vNormal.z*=-1; pNormals[i].x=vNormal.x; pNormals[i].y=vNormal.y; pNormals[i].z=vNormal.z; pNormals[i+1].x=vNormal.x; pNormals[i+1].y=vNormal.y; pNormals[i+1].z=vNormal.z; pNormals[i+2].x=vNormal.x; pNormals[i+2].y=vNormal.y; pNormals[i+2].z=vNormal.z; pNormals2[i].x=vNormal.x; pNormals2[i].y=vNormal.y; pNormals2[i].z=vNormal.z; pNormals2[i+1].x=vNormal.x; pNormals2[i+1].y=vNormal.y; pNormals2[i+1].z=vNormal.z; pNormals2[i+2].x=vNormal.x; pNormals2[i+2].y=vNormal.y; pNormals2[i+2].z=vNormal.z; } Vect3f n; int a; for(int i=0;i<ucount;i++) { n.x=0; n.y=0; n.z=0; a=0; for(int k=0;k<ucount;k++) { if (pVertices[i].x==pVertices[k].x && pVertices[i].y==pVertices[k].y && pVertices[i].z==pVertices[k].z) { n.x+=pNormals2[k].x; n.y+=pNormals2[k].y; n.z+=pNormals2[k].z; a++; } } n.x/=a; n.y/=a; n.z/=a; // Из-за кривой тесселяции приходится извращаться с нормалями // Добавим среднее от вершины n.x=n.x/2+(pVertices[i].x-pcenter.x)/2; n.y=n.y/2+(pVertices[i].y-pcenter.y)/2; n.z=n.z/2+(pVertices[i].z-pcenter.z)/2; // Добавим среднее от оригинальной нормали FFE n.x=n.x/2+oldNormal.x/2; n.y=n.y/2+oldNormal.y/2; n.z=n.z/2+oldNormal.z/2; n.x=oldNormal.x; n.y=oldNormal.y; n.z=oldNormal.z; n.normalize(); //D3DXVec3Normalize(&n, &n); pNormals[i].x=n.x; pNormals[i].y=n.y; pNormals[i].z=n.z; } */ //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*curVer,sizeof(CUSTOMVERTEX)*ucount,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,curVer,ucount*vertexBuffer.vertexSize); for(int i=0;i<ucount;i++) { (Vertices+i)->n.x = oldNormal.x;//pNormals[i].x; (Vertices+i)->n.y = oldNormal.y;//pNormals[i].y; (Vertices+i)->n.z = oldNormal.z;//pNormals[i].z; } renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); // Можно посмотреть на нормали /* float p1[3],p2[3]; for(int i=0;i<ucount;i++) { p1[0]=pVertices[i].x; p1[1]=pVertices[i].y; p1[2]=pVertices[i].z; p2[0]=pVertices[i].x+pNormals[i].x; p2[1]=pVertices[i].y+pNormals[i].y; p2[2]=pVertices[i].z+pNormals[i].z; DrawRealLine(p1,p2); } */ } // Получаем вершину из тесселятора void CALLBACK vertexCallback(double *vertex) { double p[3]; p[0]=vertex[0]; p[1]=vertex[1]; p[2]=vertex[2]; //p[0]-=1000; //p[1]-=1000; //p[2]-=1000; if (!skipCurrentModel) addVertex(p,0); else return; pVertices[ucount].x=(float)p[0]; pVertices[ucount].y=(float)p[1]; pVertices[ucount].z=(float)p[2]; ucount++; } void CALLBACK edgeFlag(GLboolean flag) { // empty } /* combineCallback is used to create a new vertex when edges * intersect. coordinate location is trivial to calculate, * but weight[4] may be used to average color, normal, or texture * coordinate data. */ GLUtesselator *tobj = NULL; GLdouble vertex[1000][3]; void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut ) { // В туториалах используют malloc, но это была бы явная // утечка памяти. Лучше через доп. буфер. vertex[addit][0] = coords[0]; vertex[addit][1] = coords[1]; vertex[addit][2] = coords[2]; *dataOut = &vertex[addit][0]; addit++; } // Скрипт задает цвет и текстуру void setMaterial(short cmd) { useLocalColor=false; currentTex=-1; if (currentModel==166) { int a=0; } if ((short)(cmd & 0x2000)==0x2000) { doLight=false; } else { doLight=true; } if ((short)(cmd & 0x1000)==0x1000) { currentR=localColor[0]; currentG=localColor[1]; currentB=localColor[2]; currentColor.set(currentR, currentG, currentB); useLocalColor=true; } if ((short)(cmd & 0x4000)==0x4000) { currentTex=400+(cmd & 0x0FFF); if (currentColor.r==0 && currentColor.g==0 && currentColor.b==0) { currentColor.set(255,255,255); } } else if (!useLocalColor) { currentTex=-1; short rgb=(cmd & 0x0FFF); short r=(rgb&0x0F00)>>8; short g=(rgb&0x00F0)>>4; short b=(rgb&0x000F); currentR=r * 12 + 63; currentG=g * 12 + 63; currentB=b * 12 + 63; currentColor.set(currentR,currentG,currentB); } } // Математика скрипта. Возможно, не совсем корректно работает. // Смотри доки от Jongware. void doMath(unsigned short *command) { int t; int result; unsigned char dest=(*command&0xFF00)>>8; int operand = (*command&0xF0)>>4; int source1 = getVar(*(command+1)&0xFF); int source2 = getVar((*(command+1)&0xFF00)>>8); switch (operand) { case 0: result=source1+source2; break; case 1: result=source1-source2; break; case 2: result=source1*source2; break; case 3: result=source1/source2; break; case 4: result=source1>>source2; break; case 5: result=source1<<source2; break; case 6: result=max(source1,source2); break; case 7: result=min(source1,source2); break; case 8: result=source1 * 0x10000 / source2; break; case 9: result=source1>>source2; case 10: result=source1<<source2; case 11: result=(source1<source2) ? 0 : source1-source2; break; case 12: result=(source1>source2) ? source2 : source1; break; case 13: result=0;//(int)(source1 * sin(source2)); break; case 14: result=0;//(int)(source1 * cos(source2)); break; case 15: result=source1&source2; break; default: result=0; break; } if ((unsigned char)(dest&0xC0)==0xC0) { t=dest&0x3F; localvar[t]=result; } else if ((unsigned char)(dest&0x80)==0x80) { t=dest&0x3F; globalvar[t]=(short)result; } } // Нифига не понял, как правильно обрабатывать флаги void setMatrix(unsigned char orient) { D3DXVECTOR3 v1,v2; /* #166 starmap grid 0100 009C 0000 ; Rotate -- default 0000 C01E ; Cmd 1Eh (parm. 0600h) FFE6 ; Cmd 6 [7]: 2047 #170 purple circle 1001 8019 ; Cmd 19, no-op C01E ; Cmd 1Eh (parm. 0600h) 013C 0000 ; Rotate -- default 0000 C01E ; Cmd 1Eh (parm. 0600h) #173 starmap nebula 1100 019C 0000 ; Rotate -- default 0000 C01E ; Cmd 1Eh (parm. 0600h) FFC6 ; Cmd 6 [7]: 2046 FROM JONGWARE: No surprise ... bits 0..2 mirror, 3..5 rotate around one of the axes (and special value 6 uses a pre-set rotation matrix). In my wireframe mesh viewer you can see some correct rotations, some bad... and the latest version draws some of the Radiation warning signs on the Panther upside down -- again! AND 38h negates rows per bit, AND 07h gives 5 additional rotations. Bits 20h negates the top row of your matrix, 10h the second row, and 08h the third row. 01h to 05h rotate 90deg along the x, y, and z axes. I had some problems interpreting this until I found you have to do the negate first (if necessary), then the rotation. Value 06h is a special (arbitrary) rotation angle, and 07h seems unused (though I'm getting increasingly careful stating something is "unused" :) I still have problems with this rotation, though -- I'll try to update galaxy7.html a.s.a. I have a fully working wireframe ... At the mo' I don't even dare to *think* of planet code... */ if (currentModel==166) D3DXMatrixRotationZ(&currentMatrix, 3.14f/2); if (currentModel==170) D3DXMatrixRotationX(&currentMatrix, 3.14f/2); if (currentModel==173) D3DXMatrixRotationY(&currentMatrix, 3.14f/2); } float nullOrigin[3]={0.0f, 0.0f, 0.0f}; float dist, radius; // Смотри "The Frontier Galaxy VII.htm" от Jongware extern void sendToRender(int num, float *origin, unsigned char orient, int scale) { int i,numpoly, n, m, startpoly; float p1[3], p2[3], p3[3], p4[3]; D3DXMATRIX tmpMatrix, oneMatrix; ffeVertex* vertex; unsigned short *command; int cn=0; numpoly=0; if (num!=-1) { //mod = (Model_t *)*((unsigned int *)model+num); mod = (Model_t *)*(unsigned int *)gptr; currentModel=num; command=gcmd; } /* for(int i=0;i<mod->NumVertices;i++) { //if (DATA_009200[num].unknown6 != 0) { // vertex = &DATA_009200[num]; //} else { vertex = FUNC_001472(gptr, i); //} vertbuf[i][0]=(float)vertex->x/DIVIDER; vertbuf[i][1]=(float)vertex->y/DIVIDER; vertbuf[i][2]=(float)vertex->z/DIVIDER; tmpMatrix[12]=vertbuf[i][0]; tmpMatrix[13]=vertbuf[i][1]; tmpMatrix[14]=vertbuf[i][2]; D3DXMatrixInverse(&oneMatrix,NULL, &mainRotMatrixO); D3DXMatrixMultiply(&tmpMatrix, &tmpMatrix, &oneMatrix); vertbuf[i][0]=tmpMatrix[12]; vertbuf[i][1]=tmpMatrix[13]; vertbuf[i][2]=tmpMatrix[14]; */ /* getTransVertex(vertbuf[i], i); // Нужно, для не потерять десятые доли от деления. Если убрать, потеряем плавность. if (currentScale<10) { vertbuf[i][0]*=10; vertbuf[i][1]*=10; vertbuf[i][2]*=10; } vertbuf[i][0]=(float)((long)vertbuf[i][0]<<(currentScale))/DIVIDER; vertbuf[i][1]=(float)((long)vertbuf[i][1]<<(currentScale))/DIVIDER; vertbuf[i][2]=(float)((long)vertbuf[i][2]<<(currentScale))/DIVIDER; if (currentScale<10) { vertbuf[i][0]/=10; vertbuf[i][1]/=10; vertbuf[i][2]/=10; } */ //} /* if (mod!=NULL) command = mod->Mesh_ptr; else return; */ //localColor[0]=mod->DefaultColorR*17; //localColor[1]=mod->DefaultColorG*17; //localColor[2]=mod->DefaultColorB*17; //localColor[0]=gptr->localColor.r; //localColor[1]=gptr->localColor.g; //localColor[2]=gptr->localColor.b; if (localColor[0]==localColor[1]==localColor[2]) { localColor[0]=mod->DefaultColorR * 12 + 63; localColor[1]=mod->DefaultColorG * 12 + 63; localColor[2]=mod->DefaultColorB * 12 + 63; } //currentColor.set(localColor[0],localColor[1],localColor[2]); currentColor.set(255,255,255); currentTex=-1; int vert=vertexNum; // Этот кусочек использовался для забивания на далекие мелкие объекты. // Например, куски города на марсе. //if (currentModel>=81 && currentModel<=102) { /* D3DXMATRIX tmpMatrix; D3DXMatrixIdentity(&tmpMatrix); tmpMatrix[12]=(float)origin[0]; tmpMatrix[13]=(float)origin[1]; tmpMatrix[14]=(float)origin[2]; D3DXMatrixMultiply(&tmpMatrix, &mainRotMatrix, &tmpMatrix); D3DXMatrixMultiply(&tmpMatrix, &posMatrix, &tmpMatrix); */ //double dist=sqrt(posMatrix[12]*posMatrix[12]+posMatrix[13]*posMatrix[13]+posMatrix[14]*posMatrix[14]); //if (currentMatrix>0 && dist>10000) // return; //if (currentMatrix>1 && dist>1500) // return; //if (posMatrix[13]<2000 && dist>800) // return; // } while(1) { if (mod==NULL) { return; } if (*(command)==0x0000) return; if (*(unsigned int*)DATA_007824==0) return; if (currentModel==2) transparent=true; else transparent=false; doLight=true; currentTex=false; cn++; if (*command==0x0001) { // Ball // Есть проблемы с радиусом setMaterial(*(command+1)); getVertex(p1, getByte(command, 4), origin, scale, orient); float r; //int scaleFactor = currentScale + currentScale2 - 8; /* if (scaleFactor < 0) { radius -= (dist << -scaleFactor); } else if (scaleFactor < 0x10) { radius = (radius << scaleFactor) - dist; scaleFactor = 0; } else { scaleFactor -= 0x10; radius = (radius << 0x10) - (dist >> scaleFactor); } */ if (*(command+2) >> 8 == 0) r=(float)getVar(*(command+2))/DIVIDER; else { int scaleFactor = abs(10-currentScale); r=(float)((short)*(command+2)>>scaleFactor)*2/DIVIDER; } if (getByte(command, 5)&0x80) { // Лампочка transparent=true; /* D3DXVECTOR4 out; D3DXMATRIX invMatrix; D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); out.z-=0.01f; D3DXMatrixInverse(&invMatrix, NULL, &mainRotMatrix); D3DXVec3Transform(&out,&D3DXVECTOR3(out.x,out.y,out.z), &invMatrix); p1[0]=out.x; p1[1]=out.y; p1[2]=out.z; */ DrawRealPoint(p1, *(command+2)); for(int ii=0;ii<10;ii++) { if (modelList[mainModelNum].light[ii].enable) continue; D3DXVECTOR4 out; D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); out.x+=posMatrix[12]; out.y+=posMatrix[13]; out.z+=posMatrix[14]; modelList[mainModelNum].light[ii].enable=true; modelList[mainModelNum].light[ii].r=1.0f/255*currentR; modelList[mainModelNum].light[ii].g=1.0f/255*currentG; modelList[mainModelNum].light[ii].b=1.0f/255*currentB; modelList[mainModelNum].light[ii].pos.x=out.x; modelList[mainModelNum].light[ii].pos.y=out.y; modelList[mainModelNum].light[ii].pos.z=out.z; modelList[mainModelNum].light[ii].dist=3.0f; break; } } else { // Шарик if (!skipCurrentModel) DrawRealSphere(p1, r, currentTex, 40); } command+=4; continue; } if (*command==0x0002) { // Line setMaterial(*(command+1)); getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 3), origin, scale, orient); if (currentModel==156 || // Laser currentModel==319 || // Hyperspace warp (currentModel>353 && currentModel<361)) { // Laser intro float width; if (posMatrix[14]<1 && posMatrix[14]>-1) p1[1]-=0.4; if (currentModel!=319) { width=0.125f; /* for(int ii=0;ii<10;ii++) { if (modelList[mainModelNum].light[ii].enable) continue; D3DXVECTOR4 out; D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); out.x+=posMatrix[12]; out.y+=posMatrix[13]; out.z+=posMatrix[14]; modelList[mainModelNum].light[ii].enable=true; modelList[mainModelNum].light[ii].r=1.0f/255*currentR; modelList[mainModelNum].light[ii].g=1.0f/255*currentG; modelList[mainModelNum].light[ii].b=1.0f/255*currentB; modelList[mainModelNum].light[ii].pos.x=out.x; modelList[mainModelNum].light[ii].pos.y=out.y; modelList[mainModelNum].light[ii].pos.z=out.z; modelList[mainModelNum].light[ii].dist=10.0f; break; } */ } else { width=0.025f; } currentTex=705; doLight=false; transparent=true; if (!skipCurrentModel) { drawBillLine(p1, p2, width); //currentTex=0; DrawRealLine(p1, p2); } if (currentModel!=319) { currentTex=706; //getVertex(p1, getByte(command, 2), origin, scale, orient); if (!skipCurrentModel) DrawBillboard(p1, width*4); } } else { currentTex=-1; if (!skipCurrentModel) DrawRealLine(p1, p2); } command+=3; continue; } if (*command==0x0003) { // Triangle setMaterial(*(command+1)); getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 3), origin, scale, orient); getVertex(p3, getByte(command, 4), origin, scale, orient); currentNormal=getByte(command, 5); //if (checkOrientation(p1,p2,p3)==true) { if (!skipCurrentModel) DrawRealTriangle(p1, p2, p3, 2, getByte(command, 5)); //} else { // if (!skipCurrentModel) // DrawRealTriangle(p3, p2, p1, 2, getByte(command, 5)); //} command+=4; continue; } if (*command==0x0004) { // Square setMaterial(*(command+1)); getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 5), origin, scale, orient); getVertex(p3, getByte(command, 3), origin, scale, orient); getVertex(p4, getByte(command, 4), origin, scale, orient); currentNormal=getByte(command, 7); if (currentModel==336) { // smoke transparent=true; } if (currentModel==169 || currentModel==170) { // cross doLight=false; currentColor.set(200,200,200); transparent=true; } if (currentTex>=464 && currentTex<=493) { // explode currentTex=464+(localvar[1]/1536); if (currentTex>493) currentTex=493; useLocalColor=false; transparent=true; } //if (checkOrientation(p1,p2,p3)==true) { if (!skipCurrentModel) DrawRealSquare2(p1, p2, p3, p4, getByte(command, 7)); //} else { // if (!skipCurrentModel) // DrawRealSquare2(p4, p3, p2, p1, getByte(command, 7)); //} command+=5; continue; } // Используется GluTess. Смотри "ProgZ_ru - gluTessVertex.htm" if (*command==0x0005) { // Polygon int pcc=0; int spl=16; int firstVertex=-1; int lastVertex=0; vcount=0; startpoly=0; setMaterial(*(command+1)); command+=1; int c=getByte(command, 0); currentNormal=getByte(command, 1); numpoly++; if (tobj == NULL) { tobj = gluNewTess (); //gluTessNormal (tobj, 0, 0, 1); //gluTessProperty(tobj, GLU_TESS_BOUNDARY_ONLY, GL_TRUE); gluTessCallback(tobj, GLU_TESS_VERTEX, (_GLUfuncptr) vertexCallback); gluTessCallback(tobj, GLU_TESS_BEGIN, (_GLUfuncptr) beginCallback); gluTessCallback(tobj, GLU_TESS_END, (_GLUfuncptr) endCallback); gluTessCallback(tobj, GLU_TESS_ERROR, (_GLUfuncptr) errorCallback); gluTessCallback(tobj, GLU_TESS_COMBINE, (_GLUfuncptr) combineCallback); gluTessCallback(tobj, GLU_TESS_EDGE_FLAG, (_GLUfuncptr) edgeFlag); } Vect3f oldNormal; oldNormal = getNormal(currentNormal); //gluTessNormal (tobj, oldNormal.x, oldNormal.y, oldNormal.z); gluTessProperty(tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD); gluTessBeginPolygon (tobj, NULL); for(i=2;i<=c;i++) { if (getByte(command, i)==0x04) { // start line getVertex(p1, getByte(command, i+1), origin, scale, orient); if (firstVertex==-1) firstVertex=getByte(command, i+1); ver[vcount][0]=p1[0]; ver[vcount][1]=p1[1]; ver[vcount][2]=p1[2]; vcount++; getVertex(p1, getByte(command, i+3), origin, scale, orient); lastVertex=getByte(command, i+3); ver[vcount][0]=p1[0]; ver[vcount][1]=p1[1]; ver[vcount][2]=p1[2]; vcount++; i+=3; continue; } if (getByte(command, i)==0x06) { // continue line getVertex(p1, getByte(command, i+1), origin, scale, orient); lastVertex=getByte(command, i+1); ver[vcount][0]=p1[0]; ver[vcount][1]=p1[1]; ver[vcount][2]=p1[2]; vcount++; i+=1; continue; } if (getByte(command, i)==0x02) { // start curve float out[3]; float ctrlpoints[4][3]; getVertex(ctrlpoints[0], getByte(command, i+2), origin, scale, orient); getVertex(ctrlpoints[1], getByte(command, i+3), origin, scale, orient); getVertex(ctrlpoints[2], getByte(command, i+4), origin, scale, orient); getVertex(ctrlpoints[3], getByte(command, i+5), origin, scale, orient); /* int oldColor = currentColor; currentColor = D3DCOLOR_XRGB(255,255,0); DrawRealLine(ctrlpoints[0], ctrlpoints[1]); DrawRealLine(ctrlpoints[1], ctrlpoints[2]); DrawRealLine(ctrlpoints[2], ctrlpoints[3]); currentColor = oldColor; */ if (firstVertex==-1) firstVertex=getByte(command, i+2); lastVertex=getByte(command, i+5); for (m=0; m<=spl; m++) { eval_bezier (out, (float)m/(float)spl, ctrlpoints); ver[vcount][0]=out[0]; ver[vcount][1]=out[1]; ver[vcount][2]=out[2]; vcount++; } i+=5; continue; } if (getByte(command, i)==0x08) { // continue curve float out[3]; float ctrlpoints[4][3]; getVertex(ctrlpoints[0], lastVertex, origin, scale, orient); getVertex(ctrlpoints[1], getByte(command, i+1), origin, scale, orient); getVertex(ctrlpoints[2], getByte(command, i+2), origin, scale, orient); getVertex(ctrlpoints[3], getByte(command, i+3), origin, scale, orient); lastVertex=getByte(command, i+3); for (m=1; m<=spl; m++) { eval_bezier (out, (float)m/(float)spl, ctrlpoints); ver[vcount][0]=out[0]; ver[vcount][1]=out[1]; ver[vcount][2]=out[2]; vcount++; } i+=3; continue; } if (getByte(command, i)==0x0A && // End inner contour getByte(command, i+1)==0x00) { int zzz; zzz=0; if (lastVertex!=firstVertex) { getVertex(p1, firstVertex, origin, scale, orient); ver[vcount][0]=p1[0]; ver[vcount][1]=p1[1]; ver[vcount][2]=p1[2]; vcount++; } //if (lastVertex==firstVertex) // vcount--; /* // Центр полигона по Y. Небольшой патч для пересчета нормалей. p1[0]=0; p1[1]=0; p1[2]=0; for(n=startpoly;n<vcount;n++) { p1[0]=MIN(p1[0],(float)ver[n][0]); p1[1]=MIN(p1[1],(float)ver[n][1]); p1[2]=MIN(p1[2],(float)ver[n][2]); } p2[0]=0; p2[1]=0; p2[2]=0; for(n=startpoly;n<vcount;n++) { p2[0]=MAX(p2[0],(float)ver[n][0]); p2[1]=MAX(p2[1],(float)ver[n][1]); p2[2]=MAX(p2[2],(float)ver[n][2]); } pcenter.x=(p1[0]+p2[0])/2; pcenter.y=(p1[1]+p2[1])/2; pcenter.z=(p1[2]+p2[2])/2; p1[0]=pcenter.x; p1[1]=pcenter.y; p1[2]=pcenter.z; //DrawRealPoint(p1, 10); */ // Тут я пытался определить направление обхода вершин полигона. // Не сработало, так что не используется // D3DXVECTOR3 vNormal, oldNormal; // vNormal = GetTriangeNormal(&D3DXVECTOR3((float)ver[vcount-2][0], (float)ver[vcount-2][1], (float)ver[vcount-2][2]), // &D3DXVECTOR3((float)pcenter.x, (float)pcenter.y, (float)pcenter.z), // &D3DXVECTOR3((float)ver[startpoly][0], (float)ver[startpoly][1], (float)ver[startpoly][2])); // vNormal = GetTriangeNormal(&D3DXVECTOR3((float)ver[startpoly][0], (float)ver[startpoly][1], (float)ver[startpoly][2]), // &D3DXVECTOR3((float)pcenter.x, (float)pcenter.y, (float)pcenter.z), // &D3DXVECTOR3((float)ver[vcount-2][0], (float)ver[vcount-2][1], (float)ver[vcount-2][2])); //p2[0]=vNormal.x; //p2[1]=vNormal.y; //p2[2]=vNormal.z; //currentColor=D3DCOLOR_XRGB(255,0,0); //DrawRealLine(p1,p2); // oldNormal=getNormal(currentNormal); //p2[0]=oldNormal.x; //p2[1]=oldNormal.y; //p2[2]=oldNormal.z; //currentColor=D3DCOLOR_XRGB(255,255,0); //DrawRealLine(p1,p2); // // if ((oldNormal.x>0 && vNormal.x<0) || (oldNormal.x<0 && vNormal.x>0)) // zzz=1; // if ((oldNormal.y>0 && vNormal.y<0) || (oldNormal.y<0 && vNormal.y>0)) // zzz=1; // if ((oldNormal.z>0 && vNormal.z<0) || (oldNormal.z<0 && vNormal.z>0)) // zzz=1; p1[0]=0; p1[2]=0; // Обход бага тесселятора. Пусьть все вершины будут положительными. // После выборки из тесселятора уменьшим на ту же величину. //for(n=startpoly;n<vcount;n++) { //ver[n][0]+=1000; //ver[n][1]+=1000; //ver[n][2]+=1000; //} /* for(n=startpoly;n<vcount;n++) { ver[n][0]+=0.00001f; ver[n][1]+=0.00001f; ver[n][2]+=0.00001f; } */ gluTessBeginContour (tobj); if (!zzz) { for(n=startpoly;n<vcount;n++) { gluTessVertex (tobj, &ver[n][0], &ver[n][0]); } } else { for(n=vcount-1;n!=startpoly;n--) { gluTessVertex (tobj, &ver[n][0], &ver[n][0]); } } gluTessEndContour (tobj); startpoly=vcount; firstVertex=-1; i+=1; continue; } if (getByte(command, i)==0x0C) { // Circle getVertex(p1, getByte(command, i+1), origin, scale, orient); int scaleFactor = abs(10-currentScale); radius=(float)((short)getByte(command, i+2)>>scaleFactor)*2/DIVIDER; //DrawRealCircle(p1, 100, getNormal(getByte(command, i+3)), 12); i+=3; continue; } if (getByte(command, i)==0x00) { // End poly int zzz; zzz=0; if (lastVertex!=firstVertex) { getVertex(p1, firstVertex, origin, scale, orient); ver[vcount][0]=p1[0]; ver[vcount][1]=p1[1]; ver[vcount][2]=p1[2]; vcount++; } //if (lastVertex==firstVertex) // vcount--; // Центр полигона по Y. Небольшой патч для пересчета нормалей. p1[0]=0; p1[1]=0; p1[2]=0; for(n=startpoly;n<vcount;n++) { p1[0]=MIN(p1[0],(float)ver[n][0]); p1[1]=MIN(p1[1],(float)ver[n][1]); p1[2]=MIN(p1[2],(float)ver[n][2]); } p2[0]=0; p2[1]=0; p2[2]=0; for(n=startpoly;n<vcount;n++) { p2[0]=MAX(p2[0],(float)ver[n][0]); p2[1]=MAX(p2[1],(float)ver[n][1]); p2[2]=MAX(p2[2],(float)ver[n][2]); } pcenter.x=(p1[0]+p2[0])/2; pcenter.y=(p1[1]+p2[1])/2; pcenter.z=(p1[2]+p2[2])/2; p1[0]=pcenter.x; p1[1]=pcenter.y; p1[2]=pcenter.z; //DrawRealPoint(p1, 10); // Тут я пытался определить направление обхода вершин полигона. // Не сработало, так что не используется // D3DXVECTOR3 vNormal, oldNormal; // vNormal = GetTriangeNormal(&D3DXVECTOR3((float)ver[vcount-2][0], (float)ver[vcount-2][1], (float)ver[vcount-2][2]), // &D3DXVECTOR3((float)pcenter.x, (float)pcenter.y, (float)pcenter.z), // &D3DXVECTOR3((float)ver[startpoly][0], (float)ver[startpoly][1], (float)ver[startpoly][2])); // vNormal = GetTriangeNormal(&D3DXVECTOR3((float)ver[startpoly][0], (float)ver[startpoly][1], (float)ver[startpoly][2]), // &D3DXVECTOR3((float)pcenter.x, (float)pcenter.y, (float)pcenter.z), // &D3DXVECTOR3((float)ver[vcount-2][0], (float)ver[vcount-2][1], (float)ver[vcount-2][2])); //p2[0]=vNormal.x; //p2[1]=vNormal.y; //p2[2]=vNormal.z; //currentColor=D3DCOLOR_XRGB(255,0,0); //DrawRealLine(p1,p2); // oldNormal=getNormal(currentNormal); //p2[0]=oldNormal.x; //p2[1]=oldNormal.y; //p2[2]=oldNormal.z; //currentColor=D3DCOLOR_XRGB(255,255,0); //DrawRealLine(p1,p2); // if ((oldNormal.x>0 && vNormal.x<0) || (oldNormal.x<0 && vNormal.x>0)) // zzz=1; // if ((oldNormal.y>0 && vNormal.y<0) || (oldNormal.y<0 && vNormal.y>0)) // zzz=1; // if ((oldNormal.z>0 && vNormal.z<0) || (oldNormal.z<0 && vNormal.z>0)) // zzz=1; p1[0]=0; p1[2]=0; // Обход бага тесселятора. Пусьть все вершины будут положительными. // После выборки из тесселятора уменьшим на ту же величину. //for(n=startpoly;n<vcount;n++) { //ver[n][0]+=1000; //ver[n][1]+=1000; //ver[n][2]+=1000; //} /* for(n=startpoly;n<vcount;n++) { ver[n][0]+=0.00001f; ver[n][1]+=0.00001f; ver[n][2]+=0.00001f; } */ // Тесселируем gluTessBeginContour (tobj); if (!zzz) { for(n=startpoly;n<vcount;n++) { gluTessVertex (tobj, &ver[n][0], &ver[n][0]); } } else { for(n=vcount-1;n!=startpoly;n--) { gluTessVertex (tobj, &ver[n][0], &ver[n][0]); } } gluTessEndContour (tobj); /* D3DXVECTOR3 oldNormal; oldNormal = getNormal(currentNormal); float p1[3], p2[3], p3[3], p0[3]; for(n=startpoly;n<vcount-1;n++) { p1[0]=ver[n][0]; p1[1]=ver[n][1]; p1[2]=ver[n][2]; p2[0]=ver[n+1][0]; p2[1]=ver[n+1][1]; p2[2]=ver[n+1][2]; DrawRealLine(p1,p2); } p0[0]=0; p0[1]=0; p0[2]=0; p3[0]=0; p3[1]=0; p3[2]=0; for(n=startpoly;n<vcount;n++) { p3[0]+=ver[n][0]; p3[1]+=ver[n][1]; p3[2]+=ver[n][2]; } p3[0]/=vcount-1-startpoly; p3[1]/=vcount-1-startpoly; p3[2]/=vcount-1-startpoly; //DrawRealLine(p0,p3); for(n=startpoly;n<vcount-1;n++) { p1[0]=(ver[n][0]-p3[0])/2+(p3[0]); p1[1]=(ver[n][1]-p3[1])/2+(p3[1]); p1[2]=(ver[n][2]-p3[2])/2+(p3[2]); p2[0]=(ver[n+1][0]-p3[0])/2+(p3[0]); p2[1]=(ver[n+1][1]-p3[1])/2+(p3[1]); p2[2]=(ver[n+1][2]-p3[2])/2+(p3[2]); DrawRealLine(p1,p2); } */ i+=2; command +=i/2; break; } } gluTessEndPolygon (tobj); command++; continue; } if (*command==0x0007) { // Mirror triangle setMaterial(*(command+1)); getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 3), origin, scale, orient); getVertex(p3, getByte(command, 4), origin, scale, orient); currentNormal=getByte(command, 5); //if (checkOrientation(p1,p2,p3)==true) { if (!skipCurrentModel) DrawRealTriangle(p1, p2, p3, 2, getByte(command, 5)); //} else { // if (!skipCurrentModel) // DrawRealTriangle(p3, p2, p1, 2, getByte(command, 5)); //} getVertex(p1, getByte(command, 2)^1, origin, scale, orient); getVertex(p2, getByte(command, 3)^1, origin, scale, orient); getVertex(p3, getByte(command, 4)^1, origin, scale, orient); currentNormal=getByte(command, 5)^1; //if (checkOrientation(p1,p2,p3)==true) { if (!skipCurrentModel) DrawRealTriangle(p3, p2, p1, 2, getByte(command, 5)^1); //} else { // if (!skipCurrentModel) // DrawRealTriangle(p3, p2, p1, 2, getByte(command, 5)^1); //} command+=4; continue; } if (*command==0x0008) { // Mirror square setMaterial(*(command+1)); if (currentModel==156) { command+=5; continue; } getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 5), origin, scale, orient); getVertex(p3, getByte(command, 3), origin, scale, orient); getVertex(p4, getByte(command, 4), origin, scale, orient); currentNormal=getByte(command, 7); //if (checkOrientation(p2,p3,p4)==true) { if (!skipCurrentModel) DrawRealSquare2(p1, p2, p3, p4, getByte(command, 7)); //} else { // if (!skipCurrentModel) // DrawRealSquare2(p4, p3, p2, p1, getByte(command, 7)); //} getVertex(p1, getByte(command, 2)^1, origin, scale, orient); getVertex(p2, getByte(command, 5)^1, origin, scale, orient); getVertex(p3, getByte(command, 3)^1, origin, scale, orient); getVertex(p4, getByte(command, 4)^1, origin, scale, orient); currentNormal=getByte(command, 7)^1; //if (checkOrientation(p2,p3,p4)==true) { if (!skipCurrentModel) DrawRealSquare2(p1, p2, p3, p4, getByte(command, 7)^1); //} else { // if (!skipCurrentModel) // DrawRealSquare2(p4, p3, p2, p1, getByte(command, 7)^1); //} command+=5; continue; } if (*command==0x0009) { // Thruster (pine) // Не совсем корректно работает. Плюс надо добавить круг билбордом, // как в оригинале. Он нужен в случаях, когда смотришь на выхлопы прямо сзади. D3DXVECTOR4 out; setMaterial(*(command+1)); getVertex(p2, getByte(command, 2), origin, scale, orient); getVertex(p1, getByte(command, 3), origin, scale, orient); out.x=p2[0]-p1[0]; out.y=p2[1]-p1[1]; out.z=p2[2]-p1[2]; float dist = sqrtf(out.x*out.x+out.y*out.y+out.z*out.z); for(int ii=0;ii<10;ii++) { if (modelList[mainModelNum].light[ii].enable) continue; D3DXVec3Transform(&out,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); out.x+=posMatrix[12]; out.y+=posMatrix[13]; out.z+=posMatrix[14]; modelList[mainModelNum].light[ii].enable=true; modelList[mainModelNum].light[ii].pos.x=out.x; modelList[mainModelNum].light[ii].pos.y=out.y; modelList[mainModelNum].light[ii].pos.z=out.z; out.x=p2[0]-p1[0]; out.y=p2[1]-p1[1]; out.z=p2[2]-p1[2]; modelList[mainModelNum].light[ii].dist=dist; modelList[mainModelNum].light[ii].r=1.0f/255*currentR/3.0f*modelList[mainModelNum].light[ii].dist; modelList[mainModelNum].light[ii].g=1.0f/255*currentG/3.0f*modelList[mainModelNum].light[ii].dist; modelList[mainModelNum].light[ii].b=1.0f/255*currentB/3.0f*modelList[mainModelNum].light[ii].dist; break; } float width; /* if (getByte(command, 5)==0) { width=(float)(getByte(command, 4))/4; } else { width=(float)(getByte(command, 5)<<currentScale)/DIVIDER/10; } */ width=dist/5; p4[0]=p1[0]; p4[1]=p1[1]; p4[2]=p1[2]; doLight=false; transparent=true; useLocalColor=true; if (currentModel==335) { p2[0]*=1000; p2[1]*=1000; p2[2]*=1000; if (posMatrix[14]<1 && posMatrix[14]>-1) p1[1]-=0.2; currentTex=705; doLight=false; drawBillLine(p1, p2, width/2); } currentTex=101; drawBillLine(p1, p2, width); D3DXVECTOR4 pos1, pos2; D3DXVec3Transform(&pos1,&D3DXVECTOR3(p1[0],p1[1],p1[2]), &mainRotMatrix); D3DXVec3Transform(&pos2,&D3DXVECTOR3(p2[0],p2[1],p2[2]), &mainRotMatrix); /* out.x=pos2.x-pos1.x; out.y=pos2.y-pos1.y; out.z=0; float dist2d = sqrtf(out.x*out.x+out.y*out.y); */ width=dist/5; //if (dist2d<width) { //useLocalColor=true; currentTex=291; //currentColor.r=currentR; //currentColor.g=currentG; //currentColor.b=currentB; float wp=(float)(rand()%10000)/95000; DrawBillboard(p4, width*2*0.9f-wp); //} command+=4; continue; } if (*command==0x000A) { // Text rotateNext=false; command+=5; continue; } if (*command==0x0011) { // Cone float radius2; getVertex(p1, getByte(command, 2), origin, scale, orient); getVertex(p2, getByte(command, 3), origin, scale, orient); int scaleFactor = gptr->actualScale;//(8-currentScale); int r1 = (unsigned char)getByte(command, 5); int r2 = (unsigned char)getByte(command, 7); radius = (float)(r1 << (scaleFactor/2))/DIVIDER; radius2 = (float)(r2 << (scaleFactor/2))/DIVIDER; if (r1==2 && r2!=0) { radius=(float)((mod->Radius*2)<<(scaleFactor/2))/DIVIDER; radius2=radius/2; } if (r2==0) radius2=radius; if (r1==138) { radius/=1.5; } if (r2==138) { radius2/=1.5; } if (r1>=140 && r1!=154) { radius/=5; } if (r2>=140 && r2!=154) { radius2/=5; } if (r1==5) { radius*=5; } if (r2==5) { radius2*=5; } if (r1==6) { radius*=6; } if (r2==6) { radius2*=6; } setMaterial(*(command+1)); if (!skipCurrentModel) DrawRealCylinder(p1, p2, radius, radius2, 0, 1, 0); setMaterial(*(command+5)); if (!skipCurrentModel) DrawRealCylinder(p1, p2, radius, radius2, 1, 0, 0); setMaterial(*(command+6)); if (!skipCurrentModel) DrawRealCylinder(p1, p2, radius, radius2, 0, 0, 1); //DrawRealLine(p1, p2); command+=7; continue; } if (*command==0x0016) { // Curve int spl=16; float ctrlpoints[4][3]; setMaterial(*(command+1)); getVertex(ctrlpoints[0], getByte(command, 2), origin, scale, orient); getVertex(ctrlpoints[2], getByte(command, 3), origin, scale, orient); getVertex(ctrlpoints[1], getByte(command, 4), origin, scale, orient); getVertex(ctrlpoints[3], getByte(command, 5), origin, scale, orient); //DrawRealPoint(ctrlpoints[0], 10); //DrawRealPoint(ctrlpoints[1], 10); //DrawRealPoint(ctrlpoints[2], 10); //DrawRealPoint(ctrlpoints[3], 10); //DrawRealLine(ctrlpoints[0], ctrlpoints[1]); //DrawRealLine(ctrlpoints[3], ctrlpoints[1]); //DrawRealLine(ctrlpoints[1], ctrlpoints[0]); if (!skipCurrentModel) for (m=0; m<spl && currentModel!=354; m++) { eval_bezier (p1, (float)m/(float)spl, ctrlpoints); eval_bezier (p2, (float)(m+1)/(float)spl, ctrlpoints); DrawRealLine(p1, p2); } command+=5; continue; } if (*command==0x0018) { // Ball array setMaterial(*(command+1)); //float radius=(float)(getVar(*(command+2)))/DIVIDER/50; /* int rad=FUNC_001474_getRadius(gptr,*(command+2)); float radius=(float)rad/DIVIDER; */ if (num==154) { localvar[1] -= localvar[2]; } if (*(command+2) >> 8 == 0) radius=(float)getVar(*(command+2))/DIVIDER; else { int scaleFactor = abs(10-currentScale); radius=(float)((short)*(command+2)>>scaleFactor)*2/DIVIDER; } command+=3; useLocalColor=true; transparent=true; if (num==316) { //radius /= 400; currentTex=707; } else if (num==109) { if (radius<0.03) radius=0.03; currentTex=704; } else if (num==154) { currentTex=721; D3DXMatrixRotationZ(&tmpMatrix, (float)*DATA_008804/60000.0f * (globalvar[0] == 0 ? 1 : -1)); D3DXMatrixMultiply(&mainRotMatrix, &mainRotMatrix, &tmpMatrix); } else { currentTex=704; } if (!skipCurrentModel) while(1) { if ((char)(*command>>8)==0x7f) { break; } getVertex(p1, *command>>8, origin, scale, orient); //if (num!=154) DrawBillboard(p1, radius); //DrawRealPoint(p1,radius); if ((char)(*command&0xFF)==0x7f) { //DrawRealSphere(p1, radius, currentTex, 40); break; } getVertex(p1, *command&0xFF, origin, scale, orient); //if (num!=154) DrawBillboard(p1, radius); //DrawRealPoint(p1,radius); command++; } command++; continue; } if (*command==0x001A) { // Set Color if (getByte(command, 3) == 0 && getByte(command, 2)!=0) { //int var=FUNC_001473_getVar(gptr, command+1)&0x7; int var=getVar(getByte(command, 2))&0x7; if (var==0) { short rgb=(*(command+1)&0x0FFF); short r=(rgb&0x0F00)>>8; short g=(rgb&0x00F0)>>4; short b=(rgb&0x000F); //currentColor=D3DCOLOR_XRGB(r*16,g*16,b*16); localColor[0]=(char)r * 12 + 63; localColor[1]=(char)g * 12 + 63; localColor[2]=(char)b * 12 + 63; } else { short rgb=(*(command+2+var)&0x0FFF); short r=(rgb&0x0F00)>>8; short g=(rgb&0x00F0)>>4; short b=(rgb&0x000F); //currentColor=D3DCOLOR_XRGB(r*16,g*16,b*16); localColor[0]=(char)r * 12 + 63; localColor[1]=(char)g * 12 + 63; localColor[2]=(char)b * 12 + 63; } command+=10; } else { short rgb=(*(command+1)&0x0FFF); short r=(rgb&0x0F00)>>8; short g=(rgb&0x00F0)>>4; short b=(rgb&0x000F); localColor[0]=(char)r * 12 + 63; localColor[1]=(char)g * 12 + 63; localColor[2]=(char)b * 12 + 63; command+=3; } continue; } if (*command==0x001F) { // Planet? // Тут еще работать и работать if (currentModel>=138 && currentModel<=148) { // Звезда setMaterial(*(command+1)); getTransVertex(p1, 6); dist=sqrtf(posMatrix[12]*posMatrix[12]+posMatrix[13]*posMatrix[13]+posMatrix[14]*posMatrix[14]); radius=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; //DrawRealSphere(p1, radius, 0, 60); doLight=false; useLocalColor=false; currentTex=701; transparent=false; DrawBillboard(p1, radius*8); } else { if (currentModel==445 || currentModel==134) { int a=0; } int a=timeGetTime(); // Планета setMaterial(*(command+1)); C_FUNC_001874_DrawPlanet(gptr,(char *)(command+1)); //useLocalColor=true; getTransVertex(p1, 6); /* // Большая Проблема с Радиусом (БПР) // Радиус беру по одной из вершин планеты dist=sqrtf(posMatrix[12]*posMatrix[12]+posMatrix[13]*posMatrix[13]+posMatrix[14]*posMatrix[14]); doLight=true; if (dist>radius*2) { modelList[modelNum].zwrite=true; } */ //currentColor=D3DCOLOR_XRGB(255,255,255); //DrawRealSphere(p1, radius, 0, 60); currentTex=704; useLocalColor=false; transparent=false; float radius=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; p1[0]=posMatrix[12]; p1[1]=posMatrix[13]; p1[2]=posMatrix[14]; D3DXVECTOR3 v; v.x = p1[0]; v.y = p1[1]; v.z = p1[2]; //D3DXVec3TransformCoord(&v,&v,&mainRotMatrixO); p1[0]=v.x; p1[1]=v.y; p1[2]=v.z; //DrawBillboard(p1, radius*2.5f); //modelList[currentModel].zclear=true; } command+=7; while(1) { if (*(command)==0x0000) { command++; break; } command+=8; } continue; } if (*command==0x0000 || *command==0x0720) { break; } if ((short)(*command & 0x001D)==0x001D) { // Math if (callAsm) FUNC_001758_doMath(gptr, command+1, *command); else doMath(command); //command=FUNC_GraphNull(gptr, command+1, *command); command+=2; continue; } if ((short)(*command & 0x001E)==0x001E) { // unknown! command+=1; continue; } if ((short)(*command & 0x001C)==0x001C) { // Rotate // фикс ми unsigned char orient=*command>>5; if (*(command+1)==0) setMatrix(orient); //rotateNext=true; if (*command==0xC01C) command++; command+=2; continue; } if ((short)(*command & 0x001B)==0x001B) { // Scaled sub-object // Так как я теперь перехватываю не только целые объекты, а еще и // субобъекты, эта команда не нужна. if ((unsigned char)(getByte(command, 0)&0x80) == 0x80) { command+=6; } else { command+=4; } continue; } if ((short)(*command & 0x0019)==0x0019) { // Indentity matrix billboardMatrix=true; //D3DXMATRIX one; //D3DXMatrixInverse(&one,NULL, &mainRotMatrix); //D3DXMatrixMultiply(&currentMatrix,&currentMatrix,&one); command+=1; continue; } if ((short)(*command & 0x0015)==0x0015) { // Process Vertex? command+=1; continue; } if ((short)(*command & 0x0014)==0x0014) { // Skip If Bit Set /* unsigned char bit=getByte(command, 0); unsigned short var=getVar(getByte(command, 1)); unsigned short tst=var; if (bit==0) { tst=var|-1; } else { tst=var&(short)(1 << (bit-1)); } //if (tst!=0) { // var=0; //} //var&=1; if (var==0) { if (*command>>5==0) return; command+=*command>>5; } */ /* if ((bit==0 && var!=0) || (bit>0 && (var&(short)(1 << (bit-1)))==0)) { if (*command>>5==0) return; command+=*command>>5; } */ command=FUNC_001757_SkipIfBitSet(gptr, command+1, *command); //command+=2; continue; } if ((short)(*command & 0x0013)==0x0013) { // Skip If Bit Clear /* unsigned char bit=getByte(command, 0); unsigned short var=getVar(getByte(command, 1)); unsigned short tst=var; if (bit!=0) { tst=var&(short)(1 << (bit-1)); } if (tst==0) { var=0; } var&=1; if (var==0) { if (*command>>5==0) return; command+=*command>>5; } */ /* if ((bit==0 && var==0) || (bit>0 && (var&(short)(1 << (bit-1)))==0)) { if (*command>>5==0) return; command+=*command>>5; } */ command=FUNC_001756_SkipIfBitClear(gptr, command+1, *command); //command+=2; continue; } if ((short)(*command & 0x0012)==0x0012) { command+=2; continue; } if ((short)(*command & 0x000F)==0x000F) { command+=1; continue; } if ((short)(*command & 0x000E)==0x000E) { // Sub-object // Так как я теперь перехватываю не только целые объекты, а еще и // субобъекты, эта команда не нужна. if ((unsigned char)(getByte(command, 0)&0x80) == 0x80) { command+=4; } else { command+=2; } continue; } if ((short)(*command & 0x000D)==0x000D) { // Math if (callAsm) FUNC_001758_doMath(gptr, command+1, *command); else doMath(command); command+=2; continue; } if ((short)(*command & 0x000C)==0x000C) { // Skip If Visible/Skip If Closer Than //if ((*(command+1)&0x8000)==0) { /* D3DXMATRIX tmpMatrix; D3DXMatrixIdentity(&tmpMatrix); tmpMatrix[12]=(float)origin[0]; tmpMatrix[13]=(float)origin[1]; tmpMatrix[14]=(float)origin[2]; D3DXMatrixMultiply(&tmpMatrix, &mainRotMatrix, &tmpMatrix); D3DXMatrixMultiply(&tmpMatrix, &posMatrix, &tmpMatrix); double dist=sqrt(tmpMatrix[12]*tmpMatrix[12]+tmpMatrix[13]*tmpMatrix[13]+tmpMatrix[14]*tmpMatrix[14]); //dist /=152; if (dist/10<(double)(*(command+1)&0x7FFF)) */ //command+=*command>>5; //} else { //command+=*command>>5; //} //if (exportb[currentModel]==false) { //if ((*(command+1) & 0x8000) == 0) command=C_FUNC_001755_SkipIfVisible(gptr, command+1, *command); //else { // command+=*command>>5; // command+=2; //} //} else { // command+=*command>>5; // command+=2; //} //command+=2; continue; } if ((short)(*command & 0x000B)==0x000B) { // Skip If Not Visible/Skip If Further Than //if ((*(command+1)&0x8000)==0) { /* D3DXMATRIX tmpMatrix; D3DXMatrixIdentity(&tmpMatrix); tmpMatrix[12]=(float)origin[0]; tmpMatrix[13]=(float)origin[1]; tmpMatrix[14]=(float)origin[2]; D3DXMatrixMultiply(&tmpMatrix, &mainRotMatrix, &tmpMatrix); D3DXMatrixMultiply(&tmpMatrix, &posMatrix, &tmpMatrix); double dist=sqrt(tmpMatrix[12]*tmpMatrix[12]+tmpMatrix[13]*tmpMatrix[13]+tmpMatrix[14]*tmpMatrix[14]); if (dist/10>(double)(*(command+1)&0x7FFF)) command+=*command>>5; */ //if (currentModel<81 || currentModel>102) { // //command+=*command>>5; //} //} else { //command+=*command>>5; //} //if (exportb[currentModel]==false) { //if ((*(command+1) & 0x8000) == 0) // command=FUNC_001752_SkipIfNotVisible(gptr, command+1, *command); //else // command+=2; command=C_FUNC_001752_SkipIfNotVisible(gptr, command+1, *command); //} else { //command+=*command>>5; // command+=2; //} //command+=2; continue; } if ((short)(*command & 0x0006)==0x0006) { // TRANSFORMATION? // Полный скип switch (*command >> 13) { case 0: D3DXMatrixIdentity(&currentMatrix); break; case 1: case 3: if ((unsigned char)getByte(command,0)==0xff) { while(1) { for (i=0;(unsigned char)getByte(command,i)==0xff;i+=2) {} command+=i/2; break; } } command++; break; case 2: break; case 7: if (*command >> 5 == 2045) command +=1; else if (*command >> 5 == 2046) command +=0; else if (*command >> 5 == 2047) command +=0; else { command +=1; break; } default: break; } command++; continue; } return; } } D3DCOLOR getD3DColor(DWORD color) { unsigned char argb[4]; *(DWORD *)argb=color; //return D3DCOLOR_XRGB(255,255,255); return D3DCOLOR_XRGB(argb[2],argb[1],argb[0]); } void DrawClipSprite(int index, int x, int y, int z, int h, int w, float NPx1, float NPx2, float NPy1, float NPy2) { VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,4*vertexBuffer.vertexSize); modelList[modelNum].index=0; modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; modelList[modelNum].zwrite=false; modelList[modelNum].backsprite=false; Vertices->pos.x = (float)x; Vertices->pos.y = (float)y; Vertices->pos.z = (float)z; Vertices->u1() = NPx1; Vertices->v1() = NPy1; vertexType[vertexNum].type = GL_TRIANGLE_STRIP; vertexType[vertexNum].amount = 4; vertexType[vertexNum].textNum = index; Vertices->difuse.RGBA() = (DWORD)pWinPal32[15]; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)x; Vertices->pos.y = (float)h; Vertices->pos.z = (float)z; Vertices->u1() = NPx1; Vertices->v1() = NPy2; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = index; Vertices->difuse.RGBA() = (DWORD)pWinPal32[15]; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)w; Vertices->pos.y = (float)y; Vertices->pos.z = (float)z; Vertices->u1() = NPx2; Vertices->v1() = NPy1; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = index; Vertices->difuse.RGBA() = (DWORD)pWinPal32[15]; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)w; Vertices->pos.y = (float)h; Vertices->pos.z = (float)z; Vertices->u1() = NPx2; Vertices->v1() = NPy2; vertexType[vertexNum].type = 0; vertexType[vertexNum].textNum = index; Vertices->difuse.RGBA() = (DWORD)pWinPal32[15]; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } extern int panelnum; // Осталась используемой для рисования спрайтов extern "C" void C_BlitClipInternal (int index, int xpos, int ypos, char *ptr, int xmin, int ymin, int xmax, int ymax) { short x, y, width, height, w, h; float z; float NPx1, NPx2; float NPy1, NPy2; int aspectfactor=(curheight-curwidth/1.6f); vertexType[vertexNum].transparent=true; if (vertexNum>MAXVERT-100) return; if (index==162 || index==177) panelnum=0; if (index==111 || index==188) panelnum=1; if (index==197 || index==208) panelnum=2; if (index==140 || index==151) panelnum=3; switch(index) { // F1 case 167: panellight[1]=true; break; case 178: panellight[5]=true; break; case 177: panellight[6]=true; break; case 176: panellight[7]=true; break; case 175: panellight[8]=true; break; case 174: panellight[9]=true; break; case 173: panellight[10]=true; break; case 172: panellight[11]=true; break; case 170: panellight[13]=true; break; case 169: panellight[14]=true; break; // F2 case 166: panellight[2]=true; break; case 189: panellight[5]=true; break; case 188: panellight[6]=true; break; case 187: panellight[7]=true; break; case 186: panellight[8]=true; break; case 185: panellight[9]=true; break; case 184: panellight[10]=true; break; case 183: panellight[11]=true; break; case 182: panellight[12]=true; break; // F3 case 165: panellight[3]=true; break; case 211: panellight[5]=true; break; case 210: panellight[6]=true; break; case 209: panellight[7]=true; break; case 208: panellight[8]=true; break; case 207: panellight[9]=true; break; case 206: panellight[10]=true; break; case 205: panellight[11]=true; break; case 204: panellight[12]=true; break; case 203: panellight[13]=true; break; // F4 case 164: panellight[4]=true; break; case 152: panellight[5]=true; break; case 151: panellight[6]=true; break; case 150: panellight[7]=true; break; case 149: panellight[8]=true; break; case 148: panellight[9]=true; break; default: break; } if (index >=102 && index <=211) // Основные кнопки панели return; if (index ==268) return; NPx1 = N_0; NPx2 = N_1; NPy1 = N_0; NPy2 = N_1; x = xpos; y = ypos; xmax = xmax == -1 ? 320 : xmax; ymax = ymax == -1 ? 200 : ymax; if (index==273) { x-=8; y-=1; if (xmin>0) xmin-=8; if (xmax>0) xmax-=8; if (ymin>0) ymin-=1; if (ymax>0) ymax-=1; } if (index==274) { x-=3; //y-=1; if (xmin>0) xmin-=3; if (xmax>0) xmax-=3; //if (ymin>0) ymin-=1; //if (ymax>0) ymax-=1; } if (index>0) { width = *((unsigned short *)ptr+1); height = *(ptr+1); } else { width = 13; height = 8; } width+=x; height+=y; z = 0; if (index == 0) { // pointer z = 0; } if (index==96) { // cabin vertexType[vertexNum].transparent=false; modelList[modelNum].backsprite=true; //width=320; height=158; z=1; incabin++; } if (index==66) { // "First Encounters" x=0; width=320; } if (index==47 || index==48) { z = 1; } if (index==97 || index==98) { z = 0; vertexType[vertexNum].transparent=true; } if (y>=158) { z=0; } if (index>=254 && index<=261) { z = 1; vertexType[vertexNum].transparent=false; } if (index==96) { xmin-=3; ymin-=2; xmax+=3; ymax+=2; x-=3; y-=2; width+=3; height+=2; } if (xmin < x) {xmin=x;} if (ymin < y) {ymin=y;} if (xmax > width) {xmax=width;} if (ymax > height) {ymax=height;} NPx1 = 1.0f/(width-x)*(xmin-x); NPx2 = 1.0f/(width-x)*(xmax-x); NPy1 = 1.0f/(height-y)*(ymin-y); NPy2 = 1.0f/(height-y)*(ymax-y); x = xmin < x ? x : xmin; y = ymin < y ? y : ymin; width = xmax > width ? width : xmax; height = ymax > height ? height : ymax; if (index==96) { D3DRECT rect; if (aspectfix) { rect.x1=(int)((float)curwidth/320*x); rect.y1=(int)((float)(curheight-aspectfactor)/200*y)+aspectfactor/2+2; rect.x2=(int)((float)curwidth/320*width); rect.y2=(int)((float)(curheight-aspectfactor)/200*height)+aspectfactor/2; } else { rect.x1=(int)((float)curwidth/320*x); rect.y1=(int)((float)curheight/200*y); rect.x2=(int)((float)curwidth/320*width); rect.y2=(int)((float)curheight/200*height); } if (renderSystem->GetDevice()!=NULL) renderSystem->GetDevice()->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,D3DCOLOR_XRGB(0,0,0),1.0f,0); } if (false) { spriteList[maxsprite].pos.x=x; spriteList[maxsprite].pos.y=y; // spriteList[maxsprite].pos.z=z; spriteList[maxsprite].rect.left=x/320*curwidth; spriteList[maxsprite].rect.top=y/200*curheight; spriteList[maxsprite].rect.right=width/320*curwidth; spriteList[maxsprite].rect.bottom=height/200*curheight; spriteList[maxsprite].tex=index; maxsprite++; } else { x = x*curwidth/320 - curwidth / 2; y = ~(y*curheight/200 - curheight / 2); w = width*curwidth/320 - curwidth / 2; h = ~(height*curheight/200 - curheight / 2); //sprites.push_back(Sprite(x,y,w,h,index)); } DrawClipSprite(index, x, y, z, h, w, NPx1, NPx2, NPy1, NPy2); } // Уже не используется extern "C" void C_DrawQuadVClip(u16 *p1, u16 *p2, u16 *p3, u16 *p4, int color) { unsigned short point1[2], point2[2], point3[2], point4[2]; point1[0]=*p1; point1[1]=*(p1+1); point2[0]=*p2; point2[1]=*(p2+1); point3[0]=*p3; point3[1]=*(p3+1); point4[0]=*p4; point4[1]=*(p4+1); C_DrawTriangle(point1, point2, point3, color); C_DrawTriangle(point1, point3, point4, color); } // Уже не используется extern "C" void C_DrawQuad(u16 *p1, u16 *p2, u16 *p3, u16 *p4, int color) { unsigned short point1[2], point2[2], point3[2], point4[2]; point1[0]=*p1; point1[1]=*(p1+1); point2[0]=*p2; point2[1]=*(p2+1); point3[0]=*p3; point3[1]=*(p3+1); point4[0]=*p4; point4[1]=*(p4+1); C_DrawTriangle(point1, point2, point3, color); C_DrawTriangle(point1, point3, point4, color); } // Уже не используется extern "C" void C_DrawTexTriangleDet(u16 *p1, u16 *p2, u16 *p3, u16 *t1, u16 *t2, u16 *t3, int text) { unsigned short point1[2], point2[2], point3[2]; point1[0]=*p1*2; point1[1]=*(p1+1)*2; point3[0]=*p2*2; point3[1]=*(p2+1)*2; point2[0]=*p3*2; point2[1]=*(p3+1)*2; DrawTriangle(point1, point2, point3, t1, t2, t3, 15, text, 1, false); } // Уже не используется extern "C" void C_DrawTexQuadDet(u16 *p1, u16 *p2, u16 *p3, u16 *p4, u16 *t1, u16 *t2, u16 *t3, u16 *t4, int text) { return; unsigned short point1[2], point2[2], point3[2], point4[2]; point1[0]=*p1*2; point1[1]=*(p1+1)*2; point2[0]=*p2*2; point2[1]=*(p2+1)*2; point3[0]=*p3*2; point3[1]=*(p3+1)*2; point4[0]=*p4*2; point4[1]=*(p4+1)*2; DrawTriangle(point1, point2, point3, t1, t2, t3, 15, text, 1, false); DrawTriangle(point1, point3, point4, t1, t3, t4, 15, text, 1, false); } // Уже не используется extern "C" void C_DrawTriangle(u16 *p1, u16 *p2, u16 *p3, int color) { return; unsigned short point1[2], point2[2], point3[2]; unsigned short t1[2], t2[2], t3[2]; point1[0]=*p1*2; point1[1]=*(p1+1)*2; point2[0]=*p2*2; point2[1]=*(p2+1)*2; point3[0]=*p3*2; point3[1]=*(p3+1)*2; t1[0]=0; t1[1]=0; t2[0]=1; t2[1]=0; t3[0]=1; t3[1]=1; DrawTriangle(point1, point2, point3, t1, t2, t3, color, 0, 1, false); } extern "C" void C_DrawTexTriangleInternal (long* texels, SHORT p1[2], SHORT p2[2], SHORT p3[2], SHORT t1[2], SHORT t2[2], SHORT t3[2], long text) { int v1_x=0, v1_y=0, v2_x=0, v2_y=0, v3_x=0, v3_y=0; int texture, color; int z=1; int sizey = *( ((UCHAR*)texels) - 7 ); int sizex = *( (USHORT*) (((UCHAR*)texels)-6) ); if(sizey==0) { sizey = 512; } t1[0] = max(1,min(sizex-1,t1[0])); t2[0] = max(1,min(sizex-1,t2[0])); t3[0] = max(1,min(sizex-1,t3[0])); t1[1] = max(1,min(sizey-1,t1[1])); t2[1] = max(1,min(sizey-1,t2[1])); t3[1] = max(1,min(sizey-1,t3[1])); if (vertexNum>MAXVERT-100) return; v1_x = *p1; v1_y = *(p1+1); v2_x = *p2; v2_y = *(p2+1); v3_x = *p3; v3_y = *(p3+1); texture = (unsigned short)text; color = pWinPal32[max(*(unsigned char *)(ambColor),15)]; if (v1_x>=30000) v1_x=(65535-v1_x)*-1; if (v2_x>=30000) v2_x=(65535-v2_x)*-1; if (v3_x>=30000) v3_x=(65535-v3_x)*-1; if (v1_y>=30000) v1_y=(65535-v1_y)*-1; if (v2_y>=30000) v2_y=(65535-v2_y)*-1; if (v3_y>=30000) v3_y=(65535-v3_y)*-1; v1_x = (v1_x*curwidth/320-curwidth/2); v1_y = ~(v1_y*curheight/200-curheight/2); v2_x = (v2_x*curwidth/320-curwidth/2); v2_y = ~(v2_y*curheight/200-curheight/2); v3_x = (v3_x*curwidth/320-curwidth/2); v3_y = ~(v3_y*curheight/200-curheight/2); VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,3*vertexBuffer.vertexSize); modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; modelList[modelNum].zwrite=false; modelList[modelNum].cull=CULL_NONE; modelList[modelNum].material=0; Vertices->pos.x = (float)v1_x; Vertices->pos.y = (float)v1_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = color; Vertices->u1() = ((float)t1[0]) / (float)sizex; Vertices->v1() = ((float)t1[1]) / (float)sizey; vertexType[vertexNum].type = GL_TRIANGLES; vertexType[vertexNum].amount = 3; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; vertexType[vertexNum].transparent=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)v2_x; Vertices->pos.y = (float)v2_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = color; Vertices->u1() = ((float)t2[0]) / (float)sizex; Vertices->v1() = ((float)t2[1]) / (float)sizey; vertexType[vertexNum].type = 2; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)v3_x; Vertices->pos.y = (float)v3_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = color; Vertices->u1() = ((float)t3[0]) / (float)sizex; Vertices->v1() = ((float)t3[1]) / (float)sizey; vertexType[vertexNum].type = 2; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } // void DrawTriangle(u16 *p1, u16 *p2, u16 *p3, u16 *t1, u16 *t2, u16 *t3, int color, int text, int z, bool intern) { int v1_x=0, v1_y=0, v2_x=0, v2_y=0, v3_x=0, v3_y=0; int texture; //int p1_x, p1_y, p2_x, p2_y, p3_x, p3_y; //int o1, o2, o3; //if (!intern) // return; if (vertexNum>MAXVERT-100) return; v1_x = *p1; v1_y = *(p1+1); v2_x = *p2; v2_y = *(p2+1); v3_x = *p3; v3_y = *(p3+1); texture = (unsigned short)text; if (texture>500) texture=(unsigned char)text; if (texture>0) { color = pWinPal32[*(unsigned char *)(ambColor)]; } else { color = pWinPal32[(unsigned char)color]; } //texture = 88; //color = pWinPal32[*(unsigned char *)(ambColor)]; /* if (texture>0 && color==15) { color = pWinPal32[max(*(unsigned char *)(ambColor),15)]; } else { color = pWinPal32[(unsigned char)color]; } switch(texture) { case 53: case 54: case 55: case 56: case 57: case 58: case 101: case 291: color = pWinPal32[15]; default: break; } */ if (v1_x>=30000) v1_x=(65535-v1_x)*-1; if (v2_x>=30000) v2_x=(65535-v2_x)*-1; if (v3_x>=30000) v3_x=(65535-v3_x)*-1; if (v1_y>=30000) v1_y=(65535-v1_y)*-1; if (v2_y>=30000) v2_y=(65535-v2_y)*-1; if (v3_y>=30000) v3_y=(65535-v3_y)*-1; /* v1_x = v1_x - WIDTH / 2; v1_y = ~(v1_y - HEIGHT / 2); v2_x = v2_x - WIDTH / 2; v2_y = ~(v2_y - HEIGHT / 2); v3_x = v3_x - WIDTH / 2; v3_y = ~(v3_y - HEIGHT / 2); */ v1_x = (v1_x*curwidth/640-curwidth/2); v1_y = ~(v1_y*curheight/400-curheight/2); v2_x = (v2_x*curwidth/640-curwidth/2); v2_y = ~(v2_y*curheight/400-curheight/2); v3_x = (v3_x*curwidth/640-curwidth/2); v3_y = ~(v3_y*curheight/400-curheight/2); //if(FAILED(d3d_vb->Lock(sizeof(CUSTOMVERTEX)*vertexNum,sizeof(CUSTOMVERTEX)*3,(BYTE**)&Vertices,0))) return; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,3*vertexBuffer.vertexSize); modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; modelList[modelNum].zwrite=false; modelList[modelNum].cull=CULL_NONE; modelList[modelNum].material=GALAXY; modelList[modelNum].backsprite=false; Vertices->pos.x = (float)v1_x; Vertices->pos.y = (float)v1_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = (DWORD)color; Vertices->u1() = (float)(*t1 > 0 ? 1 : 0); Vertices->v1() = (float)(*(t1+1) > 0 ? 1 : 0); vertexType[vertexNum].type = GL_TRIANGLES; vertexType[vertexNum].amount = 3; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; vertexType[vertexNum].transparent=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)v2_x; Vertices->pos.y = (float)v2_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = (DWORD)color; Vertices->u1() = (float)(*t2 > 0 ? 1 : 0); Vertices->v1() = (float)(*(t2+1) > 0 ? 1 : 0); vertexType[vertexNum].type = 2; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)v3_x; Vertices->pos.y = (float)v3_y; Vertices->pos.z = (float)z; Vertices->difuse.RGBA() = (DWORD)color; Vertices->u1() = (float)(*t3 > 0 ? 1 : 0); Vertices->v1() = (float)(*(t3+1) > 0 ? 1 : 0); vertexType[vertexNum].type = 2; vertexType[vertexNum].textNum = texture; vertexType[vertexNum].doLight=false; Vertices->n.x = 0.0f; Vertices->n.y = 0.0f; Vertices->n.z = 0.0f; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } // Уже не используется extern "C" void C_DrawCircle (u16 *center, int radius, int color) { return; int xc = *center; int yc = *center+1; int r = radius; int x=r,y=0,d=3-2*r,da=6,db=10-4*r; while (x>y) { C_DrawHLine(xc+x, yc+y, 1, color); C_DrawHLine(xc+y, yc+x, 1, color); C_DrawHLine(xc-x, yc+y, 1, color); C_DrawHLine(xc-y, yc+x, 1, color); C_DrawHLine(xc+x, yc-y, 1, color); C_DrawHLine(xc+y, yc-x, 1, color); C_DrawHLine(xc-x, yc-y, 1, color); C_DrawHLine(xc-y, yc-x, 1, color); if(d<0) { d+=da; db+=4; } else { d+=db; db+=8; x--; } da+=4; y++; } } extern "C" void C_DrawScannerMarkerUp(int x1, int y1, int x2, int y2, int col) { unsigned short point1[2], point2[2], point3[2], point4[2]; unsigned short t1[2], t2[2], t3[2]; int t; x1*=2; y1*=2; x2*=2; y2*=2; point1[0]=x1; point1[1]=y1; point2[0]=x2; point2[1]=y1; point3[0]=x1; point3[1]=y2; point4[0]=x2; point4[1]=y2; t1[0]=0; t1[1]=0; t2[0]=1; t2[1]=0; t3[0]=1; t3[1]=1; DrawTriangle(point1, point2, point3, t1, t2, t3, col, 0, 0, 1); DrawTriangle(point2, point3, point4, t1, t2, t3, col, 0, 0, 1); int size=x2-x1; point1[0]=x2; point1[1]=y1; point2[0]=x2+size*2; point2[1]=y1; point3[0]=x2; point3[1]=y1+size; point4[0]=x2+size*2; point4[1]=y1+size; DrawTriangle(point1, point2, point3, t1, t2, t3, col, 0, 0, 1); DrawTriangle(point2, point3, point4, t1, t2, t3, col, 0, 0, 1); } extern "C" void C_DrawScannerMarkerDown(int x1, int y1, int x2, int y2, int col) { unsigned short point1[2], point2[2], point3[2], point4[2]; unsigned short t1[2], t2[2], t3[2]; int t; x1*=2; y1*=2; x2*=2; y2*=2; point1[0]=x1; point1[1]=y1; point2[0]=x2; point2[1]=y1; point3[0]=x1; point3[1]=y2; point4[0]=x2; point4[1]=y2; t1[0]=0; t1[1]=0; t2[0]=1; t2[1]=0; t3[0]=1; t3[1]=1; DrawTriangle(point1, point2, point3, t1, t2, t3, col, 0, 0, 1); DrawTriangle(point2, point3, point4, t1, t2, t3, col, 0, 0, 1); int size=x2-x1; point1[0]=x2; point1[1]=y2; point2[0]=x2+size*2; point2[1]=y2; point3[0]=x2; point3[1]=y2-size; point4[0]=x2+size*2; point4[1]=y2-size; DrawTriangle(point1, point2, point3, t1, t2, t3, col, 0, 0, 1); DrawTriangle(point2, point3, point4, t1, t2, t3, col, 0, 0, 1); } // Еще используется extern "C" void C_DrawLine(u16 *p1, u16 *p2, int col) { int start_x, end_x, start_y, end_y; if (vertexNum>MAXVERT-100) return; start_x = *p1*2; start_y = *(p1+1)*2; end_x = *p2*2; end_y = *(p2+1)*2; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,2*vertexBuffer.vertexSize); Color4c color; color.RGBA() = (DWORD)pWinPal32[col]; modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; modelList[modelNum].backsprite=false; modelList[modelNum].zwrite=false; Vertices->pos.x = (float)(start_x*curwidth/640-curwidth/2); Vertices->pos.y = (float)~(start_y*curheight/400-curheight/2); Vertices->pos.z = 0.0f; Vertices->difuse = color; vertexType[vertexNum].type = GL_LINES; vertexType[vertexNum].amount = 2; vertexType[vertexNum].textNum = 0; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)(end_x*curwidth/640-curwidth/2); Vertices->pos.y = (float)~(end_y*curheight/400-curheight/2); Vertices->pos.z = 0.0f; Vertices->difuse = color; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } extern "C" void C_DrawBoxToBuf(int x1, int y1, int x2, int y2, int col) { //renderSystem->GetDevice()->Clear(0,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,D3DCOLOR_XRGB(0,0,0),1.0f,0); D3DRECT rect; int afk=curwidth/1.6f; if (aspectfix) { rect.x1=(int)((float)curwidth/320*x1)-2; rect.y1=(int)((float)afk/200*y1)+(long)(curheight-curwidth/1.6f)/2-2; rect.x2=(int)((float)curwidth/320*x2)+2; rect.y2=(int)((float)afk/200*y2)+(long)(curheight-curwidth/1.6f)/2+2; } else { rect.x1=(int)((float)curwidth/320*x1)-2; rect.y1=(int)((float)curheight/200*y1)-2; rect.x2=(int)((float)curwidth/320*x2)+2; rect.y2=(int)((float)curheight/200*y2)+2; } Color4c color; color.RGBA() = (DWORD)pWinPal32[col]; if (renderSystem->GetDevice()!=NULL) renderSystem->GetDevice()->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,D3DCOLOR_XRGB(color.r,color.g,color.b),1.0f,0); } extern "C" void C_DrawBoxToBufNew(int x1, int y1, int x2, int y2, int col) { //renderSystem->GetDevice()->Clear(0,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,D3DCOLOR_XRGB(0,0,0),1.0f,0); D3DRECT rect; if (aspectfix) { rect.x1=x1; rect.y1=y1+(curheight-curwidth/1.6f)/2; rect.x2=x2; rect.y2=y2+(curheight-curwidth/1.6f)/2; } else { rect.x1=x1; rect.y1=y1; rect.x2=x2; rect.y2=y2; } D3DCOLOR rgb = D3DCOLOR_XRGB(col,col,col); if (renderSystem->GetDevice()!=NULL) renderSystem->GetDevice()->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,rgb,1.0f,0); } void C_Galaxy(int a, int b, int c, int size) { int edi = a * size / ((float)curwidth/320); int edx = b >> 16; int eax = c >> 16; int color; int esi, ebx, local_1, local_2, xcof, ycof; edi = edi > 0 ? edi : 1; xcof=edi; if (aspectfix) ycof=edi; else ycof=edi * (curwidth/1.6f)/curheight; ycof = ycof > 0 ? ycof : 1; int width = curwidth; int height; if (aspectfix) height = curwidth/1.6f*0.80f; else height = curheight*0.80f; edx = edx - (xcof>>1)+xcof; eax = eax - (ycof>>1)-ycof; b = edx + xcof * (width/2/size); local_1 = eax - ycof * (height/2/size-1); if (aspectfix) esi = curwidth/1.6f*0.78f; else esi = curheight*0.78f; do { local_2 = b; ebx = width; do { color = FUNC_000853_GetNumstars(local_2, local_1, xcof) >> 8; C_DrawBoxToBufNew(ebx, esi, ebx + size, esi + size, color); local_2 = local_2 - xcof; ebx = ebx - size; } while(ebx >= 0); local_1 = local_1 + ycof; esi = esi - size; } while(esi >= 0); } extern "C" unsigned short* C_FUNC_001752_SkipIfNotVisible(DrawMdl_t *gptr, unsigned short *var2, unsigned short var1) { if ((*var2 & 0x8000) == 0 || currentModel==235 || currentModel<3) { return FUNC_001752_SkipIfNotVisible(gptr, var2, var1); } else { return var2+1; } } extern "C" unsigned short* C_FUNC_001755_SkipIfVisible(DrawMdl_t *gptr, unsigned short *var2, unsigned short var1) { //if ((*var2 & 0x8000) == 0 || currentModel==235) { return FUNC_001755_SkipIfVisible(gptr, var2, var1); //} else { // return var2+1+(var1>>5); //} } extern "C" void C_FUNC_000847_Galaxy(int a, int b, int c) { C_Galaxy(a, b, c, curwidth/320); } extern "C" void C_FUNC_000848_Galaxy(int a, int b, int c) { C_Galaxy(a, b, c, curwidth/320*2); } extern "C" void C_FUNC_000849_Galaxy(int a, int b, int c) { C_Galaxy(a, b, c, curwidth/320*4); } extern "C" void C_DrawParticle(short *ptr, int size, int col); extern "C" void C_ConsoleSetButtonImage(int image, int value) { //if (image == 56 && value==1) { short coord[2]; coord[0] = 100; coord[1] = 170; //C_DrawParticle((unsigned short *)&coord[0], 10, 15); //} } extern "C" void C_DrawSprite(int xcent, int ycent, int num, int flag, int col) { float size; int aspectfactor=(curheight-curwidth/1.6f); if (vertexNum>MAXVERT-100) return; if (flag==0) { size = (num+2); Color4c color; color.RGBA() = (DWORD)pWinPal32[col]; modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; modelList[modelNum].backsprite=true; modelList[modelNum].zwrite=false; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,1*vertexBuffer.vertexSize); Vertices->pos.x = (float)(xcent*curwidth/320-curwidth/2); Vertices->pos.y = (float)~(ycent*(curheight)/200-(curheight)/2);//-size*2*curheight/200; if (aspectfix) { Vertices->pos.y = (float)~(ycent*(curheight)/200-(curheight)/2);//-size*2*curheight/200; } if (size!=0) { int b=0; } Vertices->pos.z = 0.0f; Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = GL_POINTS2; vertexType[vertexNum].radius = (float)0.1f*size; vertexType[vertexNum].textNum = 602; vertexType[vertexNum].doLight=false; vertexType[vertexNum].transparent=false; Vertices->n.x = 0; Vertices->n.y = 0; Vertices->n.z = 0; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } } extern "C" void C_DrawSprite2(short *ptr, int size, int col) { C_DrawSprite((int)ptr[0]-1, (int)ptr[1]-1, -20, 0, col); } extern "C" void C_DrawParticle(short *ptr, int size, int col) { int aspectfactor=(curheight-curwidth/1.6f); if (vertexNum>MAXVERT-100) return; size = size == 0 ? 1 : size; Color4c color; color.RGBA() = (DWORD)pWinPal32[col]; modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; ptr[1]+=size/2; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,1*vertexBuffer.vertexSize); Vertices->pos.x = (float)(ptr[0]*curwidth/320-curwidth/2); Vertices->pos.y = (float)~(ptr[1]*(curheight)/200-(curheight)/2);//-size*2*curheight/200; if (aspectfix) { Vertices->pos.y = (float)~(ptr[1]*(curheight)/200-(curheight)/2);//-size*2*curheight/200; } if (size!=0) { int b=0; } Vertices->pos.z = 0.0f; Vertices->difuse = color; Vertices->u1() = (float)0; Vertices->v1() = (float)0; vertexType[vertexNum].type = GL_POINTS; vertexType[vertexNum].radius = (float)0.1f*size; vertexType[vertexNum].textNum = 602; vertexType[vertexNum].doLight=false; vertexType[vertexNum].transparent=true; Vertices->n.x = 0; Vertices->n.y = 0; Vertices->n.z = 0; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } static int prevx=0, prevy=0, prevlen=0, prevcol=0, prevIndex=0; // Использовалась много где. Например, для закрашивания сплайновых // полигонов. Вряд ли еще будет нужна. extern "C" void C_DrawHLine(int x, int y, int len, int col) { int start_x, end_x, start_y, end_y; return; if (vertexNum>MAXVERT-100) return; start_x = x; start_y = y; end_x = x+len; end_y = y; VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,2*vertexBuffer.vertexSize); Color4c color; color.RGBA() = (DWORD)pWinPal32[col]; if (color.r!=color.b) int a=0; modelList[modelNum].doMatrix=2; modelList[modelNum].vertStart=vertexNum; Vertices->pos.x = (float)(start_x*curwidth/640-curwidth/2); Vertices->pos.y = (float)~(start_y*curheight/400-curheight/2); Vertices->pos.z = 1.0f; Vertices->difuse = color; vertexType[vertexNum].type = GL_LINES; vertexType[vertexNum].amount = 2; vertexType[vertexNum].textNum = -1; vertexType[vertexNum].doLight=false; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; Vertices->pos.x = (float)(end_x*curwidth/640-curwidth/2); Vertices->pos.y = (float)~(end_y*curheight/400-curheight/2); Vertices->pos.z = 1.0f; Vertices->difuse = color; Vertices->n.x = 1.0f; Vertices->n.y = 1.0f; Vertices->n.z = 1.0f; Vertices++; vertexNum++; modelList[modelNum].vertEnd=vertexNum; modelNum++; renderSystem->UnlockVertexBuffer(vertexBuffer); } // Для отображения текста. Есть некоторые мелкие проблемы. char *C_DrawText (char *pStr, int xpos, int ypos, int col, bool shadow, int ymin, int ymax, int height) { char *text; int color, num; FFTEXT *buf; bool stop=false; int newLine=10; if (textStartX==-1) { textStartX=xpos; } buf = ffText; num = textNum; if (num>1900) return pStr; if (ymax > 0 && ypos>ymax-10) { return pStr; } if (ypos>158) { newLine=8; } if (height>0) { newLine=height; } textNum++; text = pStr; if (!shadow) { color = col; } else { color = 0; } buf[num].x = xpos*2; buf[num].y = ypos*2; buf[num].color = getD3DColor(pWinPal32[color]); for(int i=0;stop==false;i++) { // 0x0 0x??: Write image (bitmap index) // 0x1 0x??: Set colour (pal colour) // 0xd: Newline // 0x1d 0x?? 0x??: Set position (xpos/2, ypos) // 0x1e 0x??: Set xpos (xpos/2) // 0xff: not sure... switch((unsigned char)*text) { case 1: // color if (!shadow) { buf[num].text[i]=0; return C_DrawText (text+2, xpos+i*4, ypos, *((unsigned int *)textColor+*(text+1)), false, ymin, ymax, height); } else { buf[num].text[i]=0; return C_DrawText (text+2, xpos+i*4, ypos, 0, true, ymin, ymax, height); } case 13: // new line buf[num].text[i]=0; return C_DrawText (text+1, textStartX, ypos+newLine, col, shadow, ymin, ymax, height); case 30: // set x pos buf[num].text[i]=0; return C_DrawText (text+2,(unsigned char)*(text+1)*2+shadow, ypos, col, shadow, ymin, ymax, height); case 31: // set xy pos textStartX=(unsigned char)*(text+1)*2+shadow; buf[num].text[i]=0; return C_DrawText (text+3,(unsigned char)*(text+1)*2+shadow, (unsigned char)*(text+2)+shadow, col, shadow, ymin, ymax, height); case 255: text++; i--; break; case 0: // image? buf[num].text[i]=0; textStartX=-1; stop=true; break; case '{': buf[num].text[i]='/'; buf[num].text[i+1]='h'; i++; text++; break; case '|': buf[num].text[i]='/'; buf[num].text[i+1]='s'; i++; text++; break; case 129: buf[num].text[i]='['; buf[num].text[i+1]=' '; buf[num].text[i+2]=' '; buf[num].text[i+3]=']'; i+=3; text++; break; default: if (ymin<0 || ypos>=ymin) { buf[num].text[i]=*text; } else { buf[num].text[i]=0; } text++; break; } } return text+1; } // Текст extern "C" char *C_PersistTextWrite (char *pStr, int xpos, int ypos, int col) { return NULL; } // Текст extern "C" char *C_WriteStringShadowed (char *pStr, int xpos, int ypos, int col) { C_DrawText (pStr, xpos+1, ypos+1, 0, true, -1, -1, -1); return C_DrawText (pStr, xpos, ypos, (unsigned char)col, false, -1, -1, -1); } // Текст extern "C" char *C_TextWriteInternal(char *pStr, int xpos, int ypos, int col, char *charfunc, int ymin, int ymax, int height) { return C_DrawText (pStr, xpos, ypos, (unsigned char)col, false, ymin, ymax, height); } void DrawClouds(float *p1, float radius, int tex, int n) { D3DXVECTOR3 vNormal; Color4c color; int i, j; double theta1,theta2,theta3; float pp[3]; if (exportb[currentModel]==true && splineExport==true) return; float cx=(float)*p1; float cy=(float)*(p1+1); float cz=(float)*(p1+2); int l=n/2*n*2+2; //VertexXYZNDT1* Vertices = (VertexXYZNDT1*)renderSystem->LockVertexBuffer(vertexBuffer,vertexNum,l*vertexBuffer.vertexSize); color.set(255,255,255); currentTex=704; doLight=0; transparent=0; float TWOPI = 6.28318530717958f; float PIDIV2 = 1.57079632679489f; float ex = 0.0f; float ey = 0.0f; float ez = 0.0f; float snt1, cnt1, snt2, cnt2, snt3, cnt3; if (n<60) j = 1; else j = 0; D3DXMatrixIdentity(&posMatrix); D3DXMatrixIdentity(&mainRotMatrix); D3DXMatrixMultiply(&mainRotMatrix, &mainRotMatrix, &mainRotMatrixO); for(;j < n/2; j++ ) { theta1 = j * TWOPI / n - PIDIV2; theta2 = (j + 1) * TWOPI / n - PIDIV2; snt1 = sin(theta1); snt2 = sin(theta2); cnt1 = cos(theta1); cnt2 = cos(theta2); for( int i = 0; i <= n; i++ ) { theta3 = i * (TWOPI) / n; snt3 = sin(theta3); cnt3 = cos(theta3); ex = cnt1 * cnt3; ey = snt1; ez = cnt1 * snt3; pp[0] = cx + radius * ex; pp[1] = cy + radius * ey; pp[2] = cz + radius * ez; posMatrix[12]=pp[0]; posMatrix[13]=pp[1]; posMatrix[14]=pp[2]; DrawBillboard(&pp[0], 1000); } } //renderSystem->UnlockVertexBuffer(vertexBuffer); //d3d_vb->Unlock(); } D3DXVECTOR3 a, b, c; D3DXVECTOR3 pos; D3DXMATRIX matScale; bool inAtmo; float atmoW; float atmoR; void DrawAtmosphere(float c=1.0f) { return; D3DXMATRIX atm, pposMatrix; float scal=1.0f; D3DXMatrixIdentity(&pposMatrix); D3DXMatrixIdentity(&matScale); pposMatrix[12]=pos.x; pposMatrix[13]=pos.y; pposMatrix[14]=pos.z; modelList[modelNum].index=445; modelList[modelNum].doMatrix=1; modelList[modelNum].subObject=false; transparent=false; doLight=true; modelList[modelNum].vertStart=vertexNum; float dist=sqrtf(pos.x*pos.x+pos.y*pos.y+pos.z*pos.z); float radius2=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; //radius2*=1.04f; modelList[modelNum].lightPos.x=-(float)gptr->lpos.x * 1500; modelList[modelNum].lightPos.y=-(float)gptr->lpos.y * 1500; modelList[modelNum].lightPos.z=-(float)gptr->lpos.z * 1500; currentTex=-1; currentColor.set(0,0,0); if (currentModel!=445 && currentModel!=447 && currentModel!=449) { if (dist>radius2*1.04f) { scal=0.01f * gptr->scale2; pposMatrix[12]*=scal; pposMatrix[13]*=scal; pposMatrix[14]*=scal; } } else { scal=0.03f; pposMatrix[12]*=scal; pposMatrix[13]*=scal; pposMatrix[14]*=scal; } scal*=45; pposMatrix[12]*=45; pposMatrix[13]*=45; pposMatrix[14]*=45; // Пусть облака движутся. D3DXMatrixRotationY(&atm, (float)*DATA_008804/1200000000.0f); D3DXMatrixMultiply(&atm, &atm, &mainRotMatrixO); D3DXMatrixMultiply(&modelList[modelNum].world, &atm, &pposMatrix); D3DXMatrixScaling(&matScale, scal, scal, scal); D3DXMatrixMultiply(&modelList[modelNum].world, &matScale, &modelList[modelNum].world); if (dist<radius2*c) { inAtmo=true; atmoW=(radius2*c)/dist; atmoR=(radius2*c); modelList[modelNum].cull=CULL_CW; modelList[modelNum].zwrite=false; modelList[modelNum].zenable=false; modelList[modelNum].material=ATMO2; DrawRealSphere(nullOrigin, radius2 * c, 699, 60); } else { modelList[modelNum].cull=CULL_CCW; modelList[modelNum].zwrite=true; modelList[modelNum].material=ATMO; DrawRealSphere(nullOrigin, radius2 * c, 700, 60); } modelList[modelNum].dist=dist; modelList[modelNum].vertEnd=vertexNum; modelNum++; } float mPosX=0; float mPosY=0; float mPosZ=0; extern void RenderDirect3D(void); bool Rings(int modelNum) { return (modelNum==314 || modelNum==319); } bool Planet(int modelNum) { return ((modelNum>=113 && modelNum<=136) || modelNum==445 || modelNum==447 || modelNum==449); } bool PlanetWithLife(int modelNum) { return ((modelNum>=121 && modelNum<=131) || modelNum==449); } s32 oldz=0; // Основная функция перехвата трехмерных объектов // Получает указатель на структуру DrawMdl_t. Смотри письмо от Jongware. extern "C" int C_Break(DrawMdl_t *drawModel, unsigned short *cmd) { FILE *pLog = NULL; int i=0; int curVer; float scale1=1.0f; float scale2=1.0f; float radius2; float dis; ModelInstance_t* inst; skipCurrentModel=false; // На всякий пожарный if (vertexNum>MAXVERT-3000) return 0; //if (subObject==false) { for (int ii=0;ii<10;ii++) modelList[modelNum].light[ii].enable=false; //} // указатель на структуру Model_t. Смотри письмо от Jongware. mod = drawModel->model3d; // указатель на структуру ModelInstance_t. Смотри письмо от Jongware. inst = drawModel->modelInstance; // Глобальные указатели gptr=drawModel; iptr=inst; gcmd=cmd; t_DATA_007824 = *(unsigned int*)DATA_007824; // Извращенский способ получить точный индекс модели for(i=0;i<=465;i++) { if (mod==*((Model_t**)ffeModelList+i)) { currentModel=i; break; } } modelList[modelNum].landingGear=inst->globalvars.landingState; mainModelNum=inst->model_num; if (mainModelNum==currentModel) { subObject=false; } else { subObject=true; } modelList[modelNum].instance = drawModel->modelInstance; // Локальный цвет модели localColor[0]=drawModel->localColor.r * 12 + 63; localColor[1]=drawModel->localColor.g * 12 + 63; localColor[2]=drawModel->localColor.b * 12 + 63; // Глобальные переменные модели globalvar = inst->globalvars.raw; // Локальные переменные модели localvar = drawModel->localvars; // Запоминаем состояние локальных переменных модели. // Потом надо будет их вернуть. if (!((currentModel>=113 && currentModel<=136) || currentModel==445 || currentModel==447 || currentModel==449)) { t_localvar[0]=localvar[0]; t_localvar[1]=localvar[1]; t_localvar[2]=localvar[2]; t_localvar[3]=localvar[3]; t_localvar[4]=localvar[4]; t_localvar[5]=localvar[5]; t_localvar[6]=localvar[6]; } if (subObject) { //localvar[0]++; /* localvar[0]=p_localvar[0]+1; localvar[1]=p_localvar[1]; localvar[2]=p_localvar[2]; //localvar[3]=0; //localvar[4]=0; //localvar[5]=0; //localvar[6]=0; */ } float origin[3]; origin[0]=0; origin[1]=0; origin[2]=0; // rotate // Получаем матрицу поворота модели unsigned int dd=0x80009fff; mainRotMatrix._11=mainRotMatrixO._11=(float)((double)drawModel->rotMatrix._11/dd); mainRotMatrix._12=mainRotMatrixO._12=(float)((double)drawModel->rotMatrix._12/dd); mainRotMatrix._13=mainRotMatrixO._13=(float)((double)drawModel->rotMatrix._13/dd); mainRotMatrix._21=mainRotMatrixO._21=(float)((double)drawModel->rotMatrix._21/dd); mainRotMatrix._22=mainRotMatrixO._22=(float)((double)drawModel->rotMatrix._22/dd); mainRotMatrix._23=mainRotMatrixO._23=(float)((double)drawModel->rotMatrix._23/dd); mainRotMatrix._31=mainRotMatrixO._31=(float)((double)drawModel->rotMatrix._31/dd); mainRotMatrix._32=mainRotMatrixO._32=(float)((double)drawModel->rotMatrix._32/dd); mainRotMatrix._33=mainRotMatrixO._33=(float)((double)drawModel->rotMatrix._33/dd); mainRotMatrix._41=mainRotMatrixO._41=0.0f; mainRotMatrix._42=mainRotMatrixO._42=0.0f; mainRotMatrix._43=mainRotMatrixO._43=0.0f; mainRotMatrix._14=mainRotMatrixO._14=0.0f; mainRotMatrix._24=mainRotMatrixO._24=0.0f; mainRotMatrix._34=mainRotMatrixO._34=0.0f; mainRotMatrix._44=mainRotMatrixO._44=1.0f; D3DXMatrixIdentity(&currentMatrix); billboardMatrix=false; pos.x=(float)drawModel->pos.x/DIVIDER; pos.y=(float)drawModel->pos.y/DIVIDER; pos.z=(float)drawModel->pos.z/DIVIDER; /* int x1=*(int*)(iPtr+0x3E); int x2=*(int*)(iPtr+0x3E+4); int y1=*(int*)(iPtr+0x3E+8); int y2=*(int*)(iPtr+0x3E+8+4); int z1=*(int*)(iPtr+0x3E+16); int z2=*(int*)(iPtr+0x3E+16+4); int x3 = *(int*)(iPtr+0x26); int y3 = *(int*)(iPtr+0x2E); int z3 = *(int*)(iPtr+0x36); pos.x = ((float)x3/100); pos.y = ((float)y3/100); pos.z = ((float)z3/100); */ //pos.x = (float)x1; //pos.y = (float)y1; //pos.z = (float)z1; //pos.x /= 100; //pos.y /= 100; //pos.z /= 100; if (Planet(currentModel) || currentModel==314) dis=sqrtf(pos.x*pos.x+pos.y*pos.y+pos.z*pos.z); else dis=pos.z; if (currentModel>=113 && currentModel<=136) { //scale1=32.0f; //scale2=32.0f; } /* if (objNum==86) { char buf[256]; sprintf(buf,"starport x = %f, y=%f, z=%f",pos.x,pos.y,pos.z); DrawText (buf, 10, 30, 7, false, -1, -1, -1); //sprintf(buf,"starport scale44 = %i",*(int*)(ptr+0x44)); //DrawText (buf, 10, 40, 7, false, -1, -1, -1); } */ // posMatrix[0]=1.0f; posMatrix[1]=0.0f; posMatrix[2]=0.0f; posMatrix[4]=0.0f; posMatrix[5]=1.0f; posMatrix[6]=0.0f; posMatrix[8]=0.0f; posMatrix[9]=0.0f; posMatrix[10]=1.0f; posMatrix[12]=mainModelCoord.x=pos.x; posMatrix[13]=mainModelCoord.y=pos.y; posMatrix[14]=mainModelCoord.z=pos.z; posMatrix[3]=0.0f; posMatrix[7]=0.0f; posMatrix[11]=0.0f; posMatrix[15]=1.0f; // if (modelconfig[mainObjectNum].skip) // return 0; // skip text on .x models if (subObject==true && currentModel <= 2 && mainModelNum >= 14 && mainModelNum <= 70 && objectList[mainModelNum]->Exist()) return 0; // skip text on .x models if (subObject==true && currentModel <= 2 && mainModelNum >= 14 && mainModelNum <= 70 && objectList[parentModelNum]->Exist()) return 0; if (subObject==true && currentModel >= 3 && objectList[mainModelNum]->config.notdrawsubmodels) skipCurrentModel=true; if (currentModel >= 233 && currentModel <= 235) clearBeforeRender=true; // for debug //if (1 && *DATA_008874!=0) { char txt[256]; //ModelInstance_t *zaza; //Model_t *zazamodel; //zaza=GetInstance(*DATA_008874, instanceList); //zazamodel=GetModel(zaza->model_num); //if (zaza==inst) if (0 && /*Planet(currentModel) && !*/PlanetWithLife(currentModel)) { sprintf(txt, "%f", dis); C_DrawText (&txt[0], 100, 100, 15, false, 0, 0, 20); sprintf(txt, "x: %i, y: %i, z: %i",drawModel->pos.x, drawModel->pos.y, drawModel->pos.z); C_DrawText (&txt[0], 100, 110, 15, false, 0, 0, 20); sprintf(txt, "%i, %i, %i",drawModel->scale, drawModel->scale2, drawModel->actualScale); C_DrawText (&txt[0], 100, 120, 15, false, 0, 0, 20); if (oldz > drawModel->pos.z) { int a=0; } oldz = drawModel->pos.z; } } //if (objNum>=113 && objNum<=148) // return 0; //if (objNum==173) // Galactic Nebula // return 0; //if (objNum==170) // // return 0; //if (objNum==315) // galaxy background // return 0; //if (objNum==444) // galaxy background (intro) // return 0; //if (objNum==158) // smoke // return 0; //if (objNum==334) // laser flash // return 0; //if (objNum==84) { // return 0; //} //if (objNum==109) // return 0; //if (objNum==59) // anaconda // return 0; //if (objNum==156) // laser beam // return 0; /* if (objNum==314) { posMatrix[12]*=10; posMatrix[13]*=10; posMatrix[14]*=10; scale2=10; } */ // Получаем коэффициент ресайза модели currentScale = drawModel->actualScale;// + drawModel->scale2; currentScale2 = 0; modelList[modelNum].scale = drawModel->scale2; radius2=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; // Это планета. Добавим атмосферу (если в радиусе, то до планеты). if (PlanetWithLife(currentModel)) { if (dis <= radius2*1.04f) { DrawAtmosphere(1.04f); if (dis <= radius2*1.02f) DrawAtmosphere(1.02f); } } if (mainModelNum >= 14 && mainModelNum <= 70 && currentModel > 13 && (currentModel < 195 || currentModel > 198)) modelList[modelNum].skinnum = iptr->globalvars.unique_Id & 255; //else if (currentModel > 13) // modelList[modelNum].skinnum = iptr->globalvars.unique_Id & 3; else modelList[modelNum].skinnum = 0; modelList[modelNum].subObject=subObject; // Материал modelList[modelNum].zwrite=true; modelList[modelNum].zenable=true; modelList[modelNum].zclear=false; modelList[modelNum].backsprite=false; modelList[modelNum].cull=CULL_NONE; if (currentModel==315 || currentModel==444) {// galaxy background modelList[modelNum].zwrite=false; modelList[modelNum].material=GALAXY; modelList[modelNum].cull=CULL_CCW; } else if (currentModel>=137 && currentModel<=148) { modelList[modelNum].material=SUN; modelList[modelNum].cull=CULL_CCW; modelList[modelNum].zwrite=false; } else if (Planet(currentModel)==true) { modelList[modelNum].material=PLANET; modelList[modelNum].cull=CULL_NONE; modelList[modelNum].zwrite=true; } else if (currentModel==314) { modelList[modelNum].material=-1; modelList[modelNum].cull=CULL_NONE; } else if (currentModel==169 || currentModel==170) { // cross modelList[modelNum].material=GALAXY; modelList[modelNum].zwrite=false; } else { modelList[modelNum].material=0; modelList[modelNum].cull=CULL_NONE; } if (currentModel==227) modelList[modelNum].cull=CULL_CCW; if (currentModel==156 || // Laser currentModel==319 || // Hyperspace warp (currentModel>353 && currentModel<361)) { // Laser intro modelList[modelNum].material=SUN; } modelList[modelNum].localR=drawModel->localColor.r * 12 + 63; modelList[modelNum].localG=drawModel->localColor.g * 12 + 63; modelList[modelNum].localB=drawModel->localColor.b * 12 + 63; // Получаем позицию источника света для текущей модели modelList[modelNum].lightPos.x=-(float)drawModel->lpos.x * 1500; modelList[modelNum].lightPos.y=-(float)drawModel->lpos.y * 1500; modelList[modelNum].lightPos.z=-(float)drawModel->lpos.z * 1500; //unsigned short mf; //int mn=0; //for (i=29;i<=33;i++) { // mf=globalvar[i]; // modelList[modelNum].missile[mn]=mf>>8; // mn++; // modelList[modelNum].missile[mn]=mf&0xFF; // mn++; //} // Текущая вершина curVer=vertexNum; mxVertices=0; mxIndexes=0; modelList[modelNum].index=currentModel; modelList[modelNum].vertStart=vertexNum; // Если существует внешняя модель, то пропускаем отрисовку из скрипта if (exportb[currentModel]==false && (objectList[currentModel]->Exist() || objectList[currentModel]->config.skip!=0)) { skipCurrentModel=true; } // } else { // skipCurrentModel=false; // } if ((currentModel==186 || currentModel==187) && objectList[mainModelNum]->Exist()) skipCurrentModel=true; if (currentModel==166) { // starmap grid //D3DXMatrixRotationX(&mainRotMatrix, 90*(3.14f/180)); //D3DXMatrixIdentity(&mainRotMatrix); int a=0; } if (Planet(currentModel) || Rings(currentModel)/* || currentModel==154*/) { //if (Planet(currentModel)) // D3DXMatrixIdentity(&mainRotMatrix); //D3DXMatrixIdentity(&posMatrix); if (currentModel!=445 && currentModel!=447 && currentModel!=449) { //scale2=drawModel->scale2; //posMatrix[12]*=scale2; //posMatrix[13]*=scale2; //posMatrix[14]*=scale2; //posMatrix[12]*=0.01f; //posMatrix[13]*=0.01f; //posMatrix[14]*=0.01f; //if (dis > radius2*1.04) { // if (pos.z<0) // return 0; // if ((currentModel<134 && currentModel>137) && currentModel!=148 && currentModel!=445) { // modelList[modelNum].zclear=true; // } //} else { //if (DATA_PlayerObject && DATA_PlayerObject->uchar_57 != 0) // modelList[modelNum].zclear=true; //} } else { //modelList[modelNum].zclear=true; //modelList[modelNum].zwrite=false; //scale2=0.03f; //posMatrix[12]*=scale2; //posMatrix[13]*=scale2; //posMatrix[14]*=scale2; } /* //if (!incabin) { scale2*=50; if (PlanetWithLife(currentModel)) { posMatrix[12]*=50.0001; posMatrix[13]*=50.0001; posMatrix[14]*=50.0001; } else { posMatrix[12]*=50.0025; posMatrix[13]*=50.0025; posMatrix[14]*=50.0025; } */ //} //if (incabin) //modelList[modelNum].zclear=true; } // if (mainObjectNum==154) { // // scale2=100;//*(int*)(ptr+0x148); // posMatrix[12]*=scale2; // posMatrix[13]*=scale2; // posMatrix[14]*=scale2; //} // if (currentModel==314) { // planet ring // scale2=0.01f*(*(int*)(ptr+0x130)); // posMatrix[12]*=scale2; // posMatrix[13]*=scale2; // posMatrix[14]*=scale2; // if (dis > lastPlanetRadius*2) { // //modelList[modelNum].zclear=true; // } // scale2*=50; // posMatrix[12]*=50; // posMatrix[13]*=50; // posMatrix[14]*=50; // //modelList[modelNum].zclear=true; //} // rotate patches D3DXMATRIX rot; D3DXMatrixIdentity(&rot); if (currentModel==166) { // starmap grid //D3DXMatrixRotationX(&mainRotMatrix, 90*(3.14f/180)); //D3DXMatrixIdentity(&mainRotMatrix); } if (currentModel==170) { // purple circle //D3DXMatrixRotationX(&rot, 3.14f/2.0f); } if (currentModel==173) { // nebula //D3DXMatrixRotationY(&rot, 3.14f/2.0f); } //if (currentModel<3 && (*(int *)(gptr+0xFC)==1902 || *(int *)(gptr+0xFC)==0xbe271aa0)) { // D3DXMatrixRotationY(&rot, 3.14f); //posMatrix[14]*=-1; //} //D3DXMatrixMultiply(&mainRotMatrix, &rot, &mainRotMatrix); // end rotate patches // effects rotation if (currentModel==329 || currentModel==330 || currentModel==331 || currentModel==332) { D3DXMatrixRotationZ(&rot, (float)(posMatrix[12] + posMatrix[13] + posMatrix[14])/50); } D3DXMatrixMultiply(&mainRotMatrix, &mainRotMatrix, &rot); // end effects rotation // position patches D3DXMATRIX posit; D3DXMatrixIdentity(&posit); D3DXMatrixMultiply(&posMatrix, &posit, &posMatrix); // end position patches if (currentModel>=117 && currentModel<=148) { lastPlanetRadius=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; } if (subObject==true && currentModel>=3) { Vect3f ncorr = getNormal(2); posMatrix[12]*=1.001; posMatrix[13]*=1.001; posMatrix[14]*=1.001; } if (currentModel==387 || currentModel==388) { posMatrix[13]-=0.01; } if (currentModel==371) { posMatrix[13]+=0.01; } D3DXMatrixMultiply(&modelList[modelNum].world, &mainRotMatrix, &posMatrix); //D3DXMatrixScaling(&matScale, scale2, scale2, scale2); //D3DXMatrixMultiply(&modelList[modelNum].world, &matScale, &modelList[modelNum].world); copyMatrix(&matWorld, &modelList[modelNum].world); copyMatrix(&modelList[modelNum].rotMat, &mainRotMatrix); if (DATA_PlayerObject && DATA_PlayerObject->uchar_57 == 0 && (Planet(currentModel)==true || Rings(currentModel)==true)) { doPerspectiveFar(); } else { doPerspectiveNear(); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!PARSING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //if (skipCurrentModel==false) { sendToRender(currentModel, origin, 0, 0); //} // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /* p_localvar[0]=localvar[0]; p_localvar[1]=localvar[1]; p_localvar[2]=localvar[2]; p_localvar[3]=localvar[3]; p_localvar[4]=localvar[4]; p_localvar[5]=localvar[5]; p_localvar[6]=localvar[6]; */ // Возвращаем локальные переменные модели на место. Их позже точно так-же // обработает оригинальный код на асме if (!((currentModel>=113 && currentModel<=136) || currentModel==445 || currentModel==447 || currentModel==449)) { localvar[0]=t_localvar[0]; localvar[1]=t_localvar[1]; localvar[2]=t_localvar[2]; localvar[3]=t_localvar[3]; localvar[4]=t_localvar[4]; localvar[5]=t_localvar[5]; localvar[6]=t_localvar[6]; } *(unsigned int*)DATA_007824 = t_DATA_007824; if (exportb[currentModel]==true) { if (ExportMesh(currentModel)) { exportb[currentModel]=false; } } modelList[modelNum].doMatrix=1; modelList[modelNum].vertEnd=vertexNum; modelList[modelNum].backsprite=false; modelList[modelNum].dist=dis; modelNum++; // Это планета. Добавим атмосферу (если в радиусе, то до планеты). if ((currentModel>=125 && currentModel<=132) || currentModel==449) { radius2=(float)(*(mod->Vertices_ptr+2)<<currentScale)/DIVIDER; if (dis > radius2*1.04f) { DrawAtmosphere(1.04f); } } parentModelNum = currentModel; D3DXMatrixIdentity(&currentMatrix); return 1; } extern "C" void C_Break2() { currentAmbientR=15; currentAmbientG=15; currentAmbientB=15; } D3DXMATRIX tempRotMatrix; void mMatrix(unsigned char* inst) { D3DXVECTOR3 a, b, c; a=D3DXVECTOR3((float)*(int*)(inst+0x0)/DIVIDER, (float)*(int*)(inst+0x4)/DIVIDER, (float)*(int*)(inst+0x8)/DIVIDER); b=D3DXVECTOR3((float)*(int*)(inst+0xc)/DIVIDER, (float)*(int*)(inst+0x10)/DIVIDER, (float)*(int*)(inst+0x14)/DIVIDER); c=D3DXVECTOR3((float)*(int*)(inst+0x18)/DIVIDER, (float)*(int*)(inst+0x1c)/DIVIDER, (float)*(int*)(inst+0x20)/DIVIDER); D3DXVec3Normalize(&a, &a); D3DXVec3Normalize(&b, &b); D3DXVec3Normalize(&c, &c); tempRotMatrix[0]=a.x; tempRotMatrix[1]=a.y; tempRotMatrix[2]=a.z; tempRotMatrix[4]=b.x; tempRotMatrix[5]=b.y; tempRotMatrix[6]=b.z; tempRotMatrix[8]=c.x; tempRotMatrix[9]=c.y; tempRotMatrix[10]=c.z; tempRotMatrix[12]=0.0f; tempRotMatrix[13]=0.0f; tempRotMatrix[14]=0.0f; tempRotMatrix[3]=0.0f; tempRotMatrix[7]=0.0f; tempRotMatrix[11]=0.0f; tempRotMatrix[15]=1.0f; D3DXMatrixMultiply(&lightRotMatrix, &lightRotMatrix, &tempRotMatrix); } extern "C" u32 DATA_NumObjects; D3DXVECTOR4 GetStarLightColor() { D3DXVECTOR4 lpos, color; u32 model; ModelInstance_t *plptr = DATA_PlayerObject; color = D3DXVECTOR4(1.0,1.0,1.0,1.0); if (DATA_PlayerObject == NULL) return color; // player obj not exist //for(int i = 114; i > 0; i--) { //model = instanceList->instances[i].index; //if (model >= 138 && model <= 148) // this is star? // break; // } model = instanceList->instances[114].index; playerLightPos.x=-(float)((double)(plptr->pos.x.full)/DIVIDER); playerLightPos.y=-(float)((double)(plptr->pos.y.full)/DIVIDER); playerLightPos.z=-(float)((double)(plptr->pos.z.full)/DIVIDER); D3DXVec3Normalize(&playerLightPos, &playerLightPos); playerLightPos.x*=1000000; playerLightPos.y*=1000000; playerLightPos.z*=1000000; D3DXMatrixIdentity(&lightRotMatrix); if (plptr->uchar_57 == 0) // not in relative pos mMatrix((u8*)plptr); else mMatrix((u8*)plptr+0x5a); D3DXVECTOR4 out; D3DXMatrixInverse(&lightRotMatrix, NULL, &lightRotMatrix); D3DXVec3Transform(&lpos, &playerLightPos, &lightRotMatrix); playerLightPos.x = lpos.x; playerLightPos.y = lpos.y; playerLightPos.z = lpos.z; if (model >= 138 && model <= 148) { // have star model // Нам бы цвет света звезды задать color.x = 1.0f / 255.0f * (starColors[model-138][0] * 17); color.y = 1.0f / 255.0f * (starColors[model-138][1] * 17); color.z = 1.0f / 255.0f * (starColors[model-138][2] * 17); color.w = 1.0f; color.x = color.x * 0.75 + 0.25; color.y = color.y * 0.75 + 0.25; color.z = color.z * 0.75 + 0.25; } return color; } extern "C" void C_Break3(unsigned char *ptr) { } extern "C" void C_Break4() { int a=0; }
[ "dreamonzzz@a43015ce-51b6-2c96-052f-f15b0ecaca65" ]
[ [ [ 1, 6159 ] ] ]
b429a94898f79c8732ae9bc28d22e606696715d2
110f8081090ba9591d295d617a55a674467d127e
/tests/listPrimes.cpp
0d46148456f38d66ec39b221c797f79e52aa544f
[]
no_license
rayfill/cpplib
617bcf04368a2db70aea8b9418a45d7fd187d8c2
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
refs/heads/master
2021-01-25T03:49:26.965162
2011-07-17T15:19:11
2011-07-17T15:19:11
783,979
1
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
#include <iostream> #include <math/MPI.hpp> class MPITest { public: static void run() { std::list<unsigned int> primes = MPInteger::getPrimeList(150*64*2); unsigned int count = 0; for (std::list<unsigned int>::iterator itor = primes.begin(); itor != primes.end(); ++itor) { std::cout << *itor << ", "; ++count ; if (count > 16) { count = 0; std::cout << std::endl; } } } }; int main() { MPITest().run(); return 0; }
[ "bpokazakijr@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 38 ] ] ]
d4186a49ba03ce32076158b1033dd27bf7d7c908
a1e9c29572b2404e4195c14a14dbf5f2d260d595
/src/ColorUtils.h
b67193c41786ae9ce6e1f9414f1e8500a0acac65
[]
no_license
morsela/texton-izer
87333d229a34bf885e00c77b672d671ff72941f3
8e9f96d4a00834087247d000ae4df5282cbbfc4e
refs/heads/master
2021-07-29T01:37:38.232643
2009-02-13T15:40:03
2009-02-13T15:40:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,505
h
#ifndef __H_COLOR_UTILS_H__ #define __H_COLOR_UTILS_H__ class ColorUtils { public: static void recolorPixel(uchar * pData, int y, int x, int step, CvScalar * pColor) { int pos = y*step+3*x; pData[pos+0] = (uchar)pColor->val[0]; pData[pos+1] = (uchar)pColor->val[1]; pData[pos+2] = (uchar)pColor->val[2]; } static void colorWindow(IplImage * pOutImg, IplImage * pImg, int x, int y, int sizeX, int sizeY) { uchar * pData = (uchar *)pOutImg->imageData; uchar * pData2 = (uchar *)pImg->imageData; CvScalar color; int step = pImg->widthStep; //copy the original image data to our buffer memcpy(pData, (uchar *)pImg->imageData, pImg->imageSize); color.val[0] = 200; color.val[1] = 0; color.val[2] = 0; for (int i=x; i<x+sizeX; i++) { recolorPixel(pData, y,i, step, &color); recolorPixel(pData, y+1,i, step, &color); recolorPixel(pData, y+sizeY,i, step, &color); if (y+sizeY+1 < pImg->height) recolorPixel(pData, y+sizeY+1,i, step, &color); } for (int j=y; j<y+sizeY; j++) { recolorPixel(pData, j,x, step, &color); recolorPixel(pData, j,x+1, step, &color); recolorPixel(pData, j,x+sizeX, step, &color); if (x+sizeX+1 < pImg->height) recolorPixel(pData, j,x+sizeX + 1, step, &color); } } static bool ColorUtils::compareColors(CvScalar& color1, CvScalar& color2) { return (color1.val[0] == color2.val[0] && color1.val[1] == color2.val[1] && color1.val[2] == color2.val[2]); } }; #endif //__H_COLOR_UTILS_H__
[ "morsela@7f168336-c49e-11dd-bdf1-993be837f8bb" ]
[ [ [ 1, 64 ] ] ]
9e755e970cf68f056911dec154aa330529f3777e
ea2786bfb29ab1522074aa865524600f719b5d60
/MultimodalSpaceShooter/src/input/GestureManager.h
d03606a3bf5635276905011a1b8527b0b897a83b
[]
no_license
jeremysingy/multimodal-space-shooter
90ffda254246d0e3a1e25558aae5a15fed39137f
ca6e28944cdda97285a2caf90e635a73c9e4e5cd
refs/heads/master
2021-01-19T08:52:52.393679
2011-04-12T08:37:03
2011-04-12T08:37:03
1,467,691
0
1
null
null
null
null
UTF-8
C++
false
false
2,445
h
#ifndef GESTUREMANAGER_H #define GESTUREMANAGER_H #include <XnCppWrapper.h> #include <string> #include <SFML/System/Vector2.hpp> #include <SFML/System.hpp> namespace Tracking { enum State { NotInitialized, // OpenNI not initialized Initialized, // Initialized but no user detected UserDetected, // A user is detected UserTracked // A user is tracked }; } ////////////////////////////////////////////////// /// Manage the gestural events of the game with a /// Kinect using OpenNI ////////////////////////////////////////////////// class GestureManager { public: GestureManager(); ~GestureManager(); bool initialize(); Tracking::State getState(); void startTracking(); void stopTracking(); const sf::Vector2f& getBodyPosition() const; const sf::Vector2f& getLeftHandPosition() const; const sf::Vector2f& getRightHandPosition() const; private: bool initOpenNI(); void processThread(); void update(); void setConvertedPos(sf::Vector2f& dest, const XnPoint3D& src); // Callbacks void onNewUser(xn::UserGenerator& generator, XnUserID nId); void onLostUser(xn::UserGenerator& generator, XnUserID nId); void onCalibrationStart(xn::SkeletonCapability& capability, XnUserID nId); void onCalibrationEnd(xn::SkeletonCapability& capability, XnUserID nId, XnBool bSuccess); void onPoseDetected(xn::PoseDetectionCapability& capability, const XnChar* strPose, XnUserID nId); friend class NiCallbacksWrapper; // Constants static const std::string CONFIG_PATH; static const float RESOLUTION_X; static const float RESOLUTION_Y; static const float FPS; // Attributes sf::Thread myThread; Tracking::State myCrtState; bool myIsTracking; sf::Vector2f myBodyPos; sf::Vector2f myLeftHandPos; sf::Vector2f myRightHandPos; // OpenNI variables xn::Context myNiContext; xn::DepthGenerator myNiDepthGenerator; xn::UserGenerator myNiUserGenerator; bool myNeedPose; XnChar myStrPose[20]; }; #endif // GESTUREMANAGER_H
[ [ [ 1, 76 ] ] ]
b8a0f3a446246eab330f4a7f4046e9bb35c7ec61
8b506bf34b36af04fa970f2749e0c8033f1a9d7a
/Code/Win32/di/diMouse.cpp
f333c26b85b3810f247aa3b34d394741e3053a4b
[]
no_license
gunstar/Prototype
a5155e25d7d54a1991425e7be85bfc7da42c634f
a4448b5f6d18048ecaedf26c71e2b107e021ea6e
refs/heads/master
2021-01-10T21:42:24.221750
2011-11-06T10:16:26
2011-11-06T10:16:26
2,708,481
0
0
null
null
null
null
UTF-8
C++
false
false
2,662
cpp
#include "diMouse.h" #include "diKeys.h" /*******************************************************************/ diMouse::diMouse(IDirectInput8* device) { Device = device; Handle = 0; SwapButtons = (GetSystemMetrics(SM_SWAPBUTTON) ? true : false); Visible = true; } diMouse::~diMouse() { close(); } void diMouse::close() { if(Handle) { Handle->Unacquire(); Handle->Release(); Handle = 0; } } bool diMouse::open(bool visible) { // Set: Visible = visible; // Open: if(Device->CreateDevice(GUID_SysMouse, &Handle, 0) == DI_OK) { if(Handle->SetDataFormat(&c_dfDIMouse) == DI_OK) { if(setBufferSize(100)) return true; } close(); } return false; } void diMouse::read(diCB* cb) { // Check: if(! Handle) return; // Read: HRESULT res; DWORD total = 100; res = Handle->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), Data, &total, 0); if(res != DI_OK && res != DI_BUFFEROVERFLOW) { /* switch(res) { case DIERR_INPUTLOST: total = total; break; case DIERR_INVALIDPARAM: total = total; break; case DIERR_NOTACQUIRED: total = total; break; case DIERR_NOTBUFFERED: total = total; break; case DIERR_NOTINITIALIZED: total = total; break; default: total = total; break; } */ res = Handle->Acquire(); if(res != DI_OK) return; res = Handle->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), Data, &total, 0); if(res != DI_OK && res != DI_BUFFEROVERFLOW) return; } enF2 xy; for(DIDEVICEOBJECTDATA* d = Data; d < Data + total; d++) { bool down = ((d->dwData & 0x80) != 0); switch(d->dwOfs) { case DIMOFS_BUTTON0 : cb->diCB_Key(SwapButtons ? diKeys::Mouse1 : diKeys::Mouse0, down); break; case DIMOFS_BUTTON1 : cb->diCB_Key(SwapButtons ? diKeys::Mouse0 : diKeys::Mouse1, down); break; case DIMOFS_BUTTON2 : cb->diCB_Key(SwapButtons ? diKeys::Mouse2 : diKeys::Mouse2, down); break; case DIMOFS_X : xy.X += (int) d->dwData; break; case DIMOFS_Y : xy.Y += (int) d->dwData; break; // case DIMOFS_Z : xy.Z += (int) d->dwData; break; } } if(! xy.is0()) cb->diCB_MouseMove(xy); } /*******************************************************************/ bool diMouse::setBufferSize(int bufferSize) { DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = bufferSize; HRESULT res = Handle->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph); return res == DI_OK || res == DI_PROPNOEFFECT; }
[ [ [ 1, 128 ] ] ]
7be4fb84643f72da362f9817f0c1f19389b9276e
ea4bdaf1f19d3a0890dd3ed7ef3219f58d1cd7b6
/generateIL.cpp
b062bbf429cdb6c43ba6f8915eac18bf42fe4f47
[]
no_license
hemogawa/IllustLogickGenerator
faffcb51f12105cbbc3a1e1b14a84ce5a99ef493
b43fced6de292778bb2488b1c740252b744687ea
refs/heads/master
2021-01-10T22:10:08.436332
2011-05-24T11:40:19
2011-05-24T11:40:19
1,793,060
0
0
null
null
null
null
UTF-8
C++
false
false
13,717
cpp
/********************************************** 北陸先端科学技術大学院大学 知識科学研究科 博士前期課程 1年 菊川真理子 ドット絵からイラストロジックを作成し,表示するプログラムです **********************************************/ #include<iostream> #include<cv.h> #include<stdio.h> #include<cxcore.h> #include<highgui.h> #include<math.h> #include<string.h> #include<sstream> using namespace std; /*色を取得する関数*/ uchar GetColorR(IplImage *srcImage, int x, int y){ return ((uchar*)(srcImage->imageData + srcImage->widthStep * y))[x * 3 + 2]; } uchar GetColorG(IplImage *srcImage, int x, int y){ return ((uchar*)(srcImage->imageData + srcImage->widthStep * y))[x * 3 + 1]; } uchar GetColorB(IplImage *srcImage, int x, int y){ return ((uchar*)(srcImage->imageData + srcImage->widthStep * y))[x * 3]; } /*次のマスの色を取得する関数nextColor(image,x座標,y座標,マス内のピクセル数,行=true:列=false)*/ int nextColor(IplImage * srcImage, int x, int y, int sizeNum,bool ver){ uchar r=0,g=0,b=0; int nc = 0; /*もし行のヒントだったら次のマスは下のマス*/ if (ver == true) { /*次のマスがある場合は色取得*/ if(srcImage->height - y > sizeNum){ r = GetColorR(srcImage, x, y+sizeNum); g = GetColorG(srcImage, x, y+sizeNum); b = GetColorB(srcImage, x, y+sizeNum); /*0だと桁上りしないため,一時的に1に変更*/ if(r==0) r=1; if(g==0) g=1; if(b==0) b=1; /*RGB3桁ずつ,計9桁の整数で色を保存しておく*/ nc = r*1000000+g*1000+b; } /*もし最後のマスだったら0にする*/ else { nc = 0; } } /*もし列のヒントだったら次のマスは右のマス*/ else{ if(srcImage->width - x > sizeNum){ r = GetColorR(srcImage, x+sizeNum, y); g = GetColorG(srcImage, x+sizeNum, y); b = GetColorB(srcImage, x+sizeNum, y); if(r==0) r=1; if(g==0) g=1; if(b==0) b=1; nc = r*1000000+g*1000+b; }else { nc = 0; } } return nc; } /*各行・列のヒントを取得*/ void getHints(int hints[30][30][2],IplImage *srcImage,int size,int sizeNum,bool ver){ uchar r=0,g=0,b=0; /********************* nowSets=現在の行or列 now=現在のマス lenSets=行or列の総数 len=捜索中の行or列内のマス数 cellSets=現在の行or列 cell=行or列中何番目のヒントであるか イメージとしてはnowSets番目の中のnow番目のマスという感じです *********************/ int x=0,y=0,nowSets=0,now=0,lenSets=0,len=0,cellSets=0,cell=0; /*初期値として本来当てはまらない値を設定*/ for (int i=0; i<30; i++) { for (int j=0; j<30; j++) { for (int k=0; k<2; k++) { hints[i][j][k] = size+1; } } } /*行の場合行数をlenSetsに,行中のマス数をlenに. 列の場合は列数をlenSetsに,列中のマス数をlenに*/ if(ver == true){ lenSets = srcImage->width; len = srcImage->height; }else { lenSets = srcImage->height; len = srcImage->width; } /*行の場合は現在の行のx座標をxに 列の場合は現在の列のy座標をyに代入*/ if(ver==true) x = nowSets; else y = nowSets; /*1行or列目からマスの色と数を取得.最後の列or行までループ*/ while (nowSets<lenSets) { /*新しい行or列では捜索するマス・ヒント番号を先頭に戻す*/ now=0;cell=0; /*行の場合は現在のマスのy座標をyに 列の場合は現在のマスのx座標をxに代入*/ if(ver==true) y = now; else x = now; /*行or列の末尾までマスを進めつつループ*/ while (now <len){ hints[cellSets][cell][0] = 1; //この時点でcellSet行or列目のcell番目のヒントは(不明)色が1マス /*色取得*/ r = GetColorR(srcImage, x, y); g = GetColorG(srcImage, x, y); b = GetColorB(srcImage, x, y); /*0だと桁上りしないため,一時的に1に変更*/ if(r==0) r=1; if(g==0) g=1; if(b==0) b=1; /*RGB3桁ずつ,計9桁の整数で色を保存しておく*/ hints[cellSets][cell][1] = r*1000000+g*1000+b; /*次のマスが同色である場合以下の処理.マスを進めていって違う色になるまでループ ここでのループによってcellSets行or列目のcell番目のヒントはhints[cellSets][cell][1]の色が hints[cellSets][cell][0]続いているという意味のものになる*/ while (hints[cellSets][cell][1] == nextColor(srcImage,x,y,sizeNum,ver)) { now+=sizeNum; //現在座標+マス目ピクセル数で次のマスの座標へと移る if(ver==true) y = now; else x = now; hints[cellSets][cell][0]++; //ヒントとして表示される数字を+1 } if (hints[cellSets][cell][1] != 255255255) { //白以外の場合次のヒントへ cell++; }else if(hints[cellSets][cell][0] == size){ hints[cellSets][cell][0] = 0; //白のみだったら0と表示 }else { hints[cellSets][cell][0] = size+1; //白マスは空にする(ヒントを進めずに上書き) } /*次のマス座標の取得,代入*/ now+=sizeNum; if(ver==true) y = now; else x = now; } /*次の行or列座標の取得,代入*/ cellSets++; nowSets+=sizeNum; if(ver==true) x = nowSets; else y = nowSets; } } /*列・行ごとの最大ヒント数を返す*/ int getMaxHint(int hints[30][30][2],int size){ int Max=0,tmp=0; for (int i=0; i<30; i++) { /*各行・列ごとのヒント数*/ for (int j=0; j<30; j++) { /*ヒントが空白になったら,そこまでのヒント数を保存*/ if(hints[i][j][0] == size+1){ tmp = j; break; } } /*最大ヒント数よりヒント数が大きければ,代入*/ if(tmp > Max) Max = tmp; } return Max; } /*ヒント表示のために数字を後ろに詰め,余った前の部分に空白を挿入する*/ void arrayPush(int hints[30][30][2],int max,int size){ for (int i=0; i<30; i++) { //行・列の移動 int numCell = 0; //数字を見つけたマス for (int j=max-1; j>=0; j--) { //下から数える if (hints[i][j][0] != 31) { //数字があったら numCell = j; //数字を見つけたマスを保存 for (int k=numCell; k>=0; k--) { hints[i][max-1-(numCell-k)][0] = hints[i][k][0]; //数字を下に詰める hints[i][max-1-(numCell-k)][1] = hints[i][k][1]; //色も入れ替え } break; } } /*余った部分を空白にする*/ for (int j=0; j<max-1-numCell; j++) { hints[i][j][0] = size+1; } } } int main(int argc, char **argv){ cout << "Content-type: text/html\n\n"; /*画像ロード*/ IplImage *srcImage = 0; srcImage = cvLoadImage("images/dstImage.png",CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); if(srcImage == 0) return -1; int size = 30; //マス数(今回は30で固定) int sizeNum = srcImage->height/size; //1マス数内のピクセル数 int hintsVer[30][30][2],hintsHol[30][30][2]; //行ヒントセットと,列ヒントセット[何行or列目][何番目の数字か][0:数字,1:色] int maxVer=0, maxHol=0; //行最大ヒント数と列最大ヒント数 getHints(hintsVer,srcImage,size,sizeNum,true);//縦ヒント取得 getHints(hintsHol,srcImage,size,sizeNum,false); //横ヒント取得 maxVer = getMaxHint(hintsVer,size); maxHol = getMaxHint(hintsHol,size); //行・列最大ヒント数取得 arrayPush(hintsVer,maxVer,size); arrayPush(hintsHol,maxHol,size); //ヒントを後ろに詰める int cellSize = 15; //出力結果におけるマスの大きさ /*ヒントを表示する部分の長さ.hintVerLen:行ヒント表示に必要な高さ hintHolLen列ヒント表示に必要な幅*/ int hintVerLen = maxVer* cellSize, hintHolLen= maxHol* cellSize; int borderWidth = 1; //通常の線の太さ int borderMWidth = 2; //5マス区切り線の太さ int markCnt = size/5 -1; //5マス区切り線の数 /*borderPlus:解答ゾーンにおける境界線の太さを全て足した値*/ int borderPlus = ((size-markCnt-1)*borderWidth)+(markCnt*borderMWidth); /*border(Ver|Hol)Plus:ヒント間の境界線の太さ.今回は0*/ int borderVerPlus = 0; int borderHolPlus = 0; /*********************************************** 問題の描画はdivタグを利用 Safariで印刷しようとすると綺麗に印刷用PDFが生成されます 5マスごとに目印として線を1px太くしています. ***********************************************/ printf("<div style=\"height:%dpx\">",hintVerLen+borderVerPlus); /*左上の何も無いスペース*/ printf("<div style=\"float:left;height:%dpx;width:%dpx;border-bottom:3px solid black; border-right:3px solid black;\"></div>",hintVerLen+borderVerPlus,hintHolLen+borderHolPlus); /*縦ヒント*/ printf("<div style=\"float:left; height:%dpx;width:%dpx; border-width:0px 3px 3px 0px; border-style:solid;\">",hintVerLen+borderVerPlus,size* cellSize+borderPlus); for (int i=0; i<maxVer; i++) { printf("<div style=\"float:left;height:%dpx; width:%dpx;\"",cellSize,size* cellSize+borderPlus); for (int j=0; j<size; j++) { int r = hintsVer[j][i][1]/1000000; int g = (hintsVer[j][i][1]-r*1000000)/1000; int b = hintsVer[j][i][1]-(r*1000000+g*1000); if(r==1) r=0; if(g==1) g=0; if(b==1) b=0; if(r==255 && g == 255 && b == 255){ r=0; g=0; b=0;} if (j== size-1) { borderWidth = 0; } else if (j %5 == 4){ borderWidth = 2; } else { borderWidth = 1; } if (hintsVer[j][i][0] == size+1) { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-right:%dpx dashed black;font-size:small;\"></div>",cellSize,cellSize,borderWidth); }else{ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-right:%dpx dashed black; color:rgb(%d,%d,%d);font-size:small;\">%d</div>",cellSize,cellSize,borderWidth,r,g,b,hintsVer[j][i][0]); } } printf("</div>"); } printf("</div>"); printf("</div>"); /*横ヒント*/ borderWidth = 1; printf("<div style=\"clear:both;float:left; height:%dpx;width:%dpx; border-width:0px 3px 3px 0px; border-style:solid;\">",size* cellSize+borderPlus,hintHolLen+borderHolPlus); for (int i=0; i<size; i++) { if (i== size-1) { borderWidth = 0; }else if (i% 5== 4) { borderWidth = 2; }else { borderWidth = 1; } printf("<div style=\"float:left;height:%dpx; width:%dpx;\"",cellSize+borderWidth,hintHolLen+borderHolPlus); for (int j=0; j<maxHol; j++) { int r = hintsHol[i][j][1]/1000000; int g = (hintsHol[i][j][1]-r*1000000)/1000; int b = hintsHol[i][j][1]-(r*1000000+g*1000); if(r==1) r=0; if(g==1) g=0; if(b==1) b=0; if(r==255 && g == 255 && b == 255){ r=0; g=0; b=0;} if (hintsHol[i][j][0] == size+1) { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-bottom:%dpx dashed black;font-size:small; \"></div>",cellSize,cellSize,borderWidth); }else{ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-bottom:%dpx dashed black; color:rgb(%d,%d,%d);font-size:small;\">%d</div>",cellSize,cellSize,borderWidth,r,g,b,hintsHol[i][j][0]); } } printf("</div>"); } printf("</div>"); /*解答ゾーン*/ borderWidth=1; printf("<div style=\"float:left; height:%dpx;width:%dpx; border-width:0px 3px 3px 0px; border-style:solid;\">",size* cellSize+borderPlus,size*cellSize+borderPlus); for (int i=0; i<size; i++) { if (i%5== 4) { printf("<div style=\"float:left;height:%dpx; width:%dpx;\"",cellSize+borderMWidth,size* cellSize+borderPlus); }else{ printf("<div style=\"float:left;height:%dpx; width:%dpx;\"",cellSize+borderWidth,size* cellSize+borderPlus); } for (int j=0; j<size; j++) { if( i==size-1 && j== size -1){ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px 0px 0px 0px;border-style:solid;\"></div>",cellSize,cellSize); }else if (i == size -1) { if (j%5== 4) { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx 0px 0px;border-style:solid;\"></div>",cellSize,cellSize,borderMWidth); }else { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx 0px 0px;border-style:solid;\"></div>",cellSize,cellSize,borderWidth); } }else if (j== size- 1) { if (i%5== 4) { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px 0px %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderMWidth); }else { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px 0px %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderWidth); } }else if (i%5==4 && j%5== 4) { printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderMWidth,borderMWidth); }else if(i%5==4){ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderWidth,borderMWidth); }else if(j%5==4){ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderMWidth,borderWidth); }else{ printf("<div style=\"float:left;height:%dpx; width:%dpx;border-width:0px %dpx %dpx 0px;border-style:solid;\"></div>",cellSize,cellSize,borderWidth,borderWidth); } } printf("</div>"); } printf("</div>"); return 0; }
[ [ [ 1, 311 ] ] ]
2a1f765bd5bf6934040c99d639b3751ab1229ee1
4ab40b7fa3d15e68457fd2b9100e0d331f013591
/mirrorworld/Scene/MWLaserModel.cpp
5aa775d95978f6b2ec597dc73036b60e0d1b2aa6
[]
no_license
yzhou61/mirrorworld
f5d2c221f3f8376cfb0bffd0a3accbe9bb1caa21
33653244e5599d7d04e8a9d8072d32ecc55355b3
refs/heads/master
2021-01-19T20:18:44.546599
2010-03-19T22:40:42
2010-03-19T22:40:42
32,120,779
0
0
null
null
null
null
UTF-8
C++
false
false
5,234
cpp
////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// #include "MWLaserModel.h" int MirrorWorld::LaserModel::m_nPlanes = 6; Ogre::Real MirrorWorld::LaserModel::m_Radius = 0.4f; const float laserRad = 0.01f; namespace MirrorWorld { void LaserBeam::init(Ogre::SceneManager* sceneMgr, Ogre::MaterialPtr material, int i) { m_pMaterial = material; m_pModel = sceneMgr->createManualObject("LaserBeam"+Ogre::StringConverter::toString(i)); m_pModel->setDynamic(true); material->getTechnique(0)->getPass(0)->setSelfIllumination(0, 0, 1); m_pSceneNode = sceneMgr->getRootSceneNode()->createChildSceneNode("LaserBeamNode"+Ogre::StringConverter::toString(i)); m_pSceneNode->attachObject(m_pModel); } void LaserBeam::destroy(Ogre::SceneManager* sceneMgr) { if (m_pModel) m_pSceneNode->detachObject(m_pModel); sceneMgr->destroyManualObject(m_pModel); sceneMgr->destroySceneNode(m_pSceneNode); } void LaserBeam::update(const Ogre::Vector3& sp, const Ogre::Vector3& ep) { Ogre::Vector3 dir = ep - sp; Ogre::Real length = dir.normalise(); Ogre::Vector3 radVec(0, LaserModel::m_Radius/2, 0); Ogre::Quaternion rot; rot.FromAngleAxis(Ogre::Degree(180.0f/LaserModel::m_nPlanes), Ogre::Vector3::UNIT_Z); if (!m_bCreated) { m_pModel->begin(m_pMaterial->getName(), Ogre::RenderOperation::OT_LINE_LIST); m_bCreated = true; } else m_pModel->beginUpdate(0); /* for (int i = 0;i < LaserModel::m_nPlanes; i++) { m_pModel->position(-radVec.x, -radVec.y, 1.0); m_pModel->textureCoord(0.0, 0.2); m_pModel->position(radVec.x, radVec.y, 1.0); m_pModel->textureCoord(1.0, 0.2); m_pModel->position(-radVec.x, -radVec.y, 0.0); m_pModel->textureCoord(0.0, 1.0); m_pModel->position(radVec.x, radVec.y, 0.0); m_pModel->textureCoord(1.0, 1.0); m_pModel->triangle(4*i, 4*i+3, 4*i+1); m_pModel->triangle(4*i, 4*i+2, 4*i+3); m_pModel->triangle(4*i+1, 4*i+3, 4*i+2); m_pModel->triangle(4*i, 4*i+1, 4*i+2); radVec = rot*radVec; } m_pModel->position(-LaserModel::m_Radius/2, -LaserModel::m_Radius/2, 0); m_pModel->textureCoord(0.0, 0.0); m_pModel->position(LaserModel::m_Radius/2, -LaserModel::m_Radius/2, 0); m_pModel->textureCoord(0.2, 0.0); m_pModel->position(LaserModel::m_Radius/2, LaserModel::m_Radius/2, 0); m_pModel->textureCoord(0.2, 0.2); m_pModel->position(-LaserModel::m_Radius/2, LaserModel::m_Radius/2, 0); m_pModel->textureCoord(0.2, 0.0); m_pModel->triangle(24, 25, 26); m_pModel->triangle(26, 27, 24); m_pModel->position(-LaserModel::m_Radius/2, -LaserModel::m_Radius/2, 1); m_pModel->textureCoord(0.0, 0.0); m_pModel->position(LaserModel::m_Radius/2, -LaserModel::m_Radius/2, 1); m_pModel->textureCoord(0.2, 0.0); m_pModel->position(LaserModel::m_Radius/2, LaserModel::m_Radius/2, 1); m_pModel->textureCoord(0.2, 0.2); m_pModel->position(-LaserModel::m_Radius/2, LaserModel::m_Radius/2, 1); m_pModel->textureCoord(0.2, 0.0); m_pModel->triangle(28, 29, 30); m_pModel->triangle(30, 31, 28);*/ for (int j = 0;j < 5; j++) { Ogre::Real rad = Ogre::Math::UnitRandom()*laserRad; for (int i = 0;i < 24; i++) { Ogre::Real val = Ogre::Math::UnitRandom()*360.0f; Ogre::Real x = Ogre::Math::Cos(val)*rad; Ogre::Real y = Ogre::Math::Sin(val)*rad; m_pModel->position(x, y, 0); m_pModel->position(x*10.0f, y*10.0f, 1); } } m_pModel->end(); Ogre::Quaternion rotDir = Ogre::Vector3::UNIT_Z.getRotationTo(dir); m_pSceneNode->resetToInitialState(); m_pSceneNode->scale(1.0, 1.0, length); m_pSceneNode->rotate(rotDir); m_pSceneNode->translate(sp); } void LaserBeam::active() { m_pSceneNode->setVisible(true); } void LaserBeam::deactive() { m_pSceneNode->setVisible(false); } LaserModel::LaserModel(Ogre::SceneManager *sceneMgr):m_nUseLaser(0) { m_pMaterial = Ogre::MaterialManager::getSingleton().getByName("Laserbeam"); Ogre::LogManager::getSingleton().logMessage("initializing lasermodel"); for (int i = 0;i < MAX_LASERBEAM; i++) m_LaserBeamList[i].init(sceneMgr, m_pMaterial, i); } void LaserModel::active() { for (int i = 0;i < m_nUseLaser; i++) m_LaserBeamList[i].active(); } void LaserModel::deactive() { for (int i = 0;i < MAX_LASERBEAM; i++) m_LaserBeamList[i].deactive(); } void LaserModel::update(const std::vector<Ogre::Vector3> &contactPointList) { deactive(); m_nUseLaser = (contactPointList.size() - 1) < MAX_LASERBEAM ? contactPointList.size() - 1 : MAX_LASERBEAM; for (int i = 0;i < m_nUseLaser; i++) m_LaserBeamList[i].update(contactPointList[i], contactPointList[i+1]); active(); } void LaserModel::destroy() { for (int i = 0;i < MAX_LASERBEAM; i++) m_LaserBeamList[i].destroy(m_pSceneMgr); } }
[ "cxyzs7@2e672104-186a-11df-85bb-b9a83fee2cb1" ]
[ [ [ 1, 147 ] ] ]
51ee9f38a7cd7aa5610dee2b3c6b0fefe3742c0a
2112057af069a78e75adfd244a3f5b224fbab321
/branches/ref1/src-root/include/ireon_editor/interface/editor_interface.h
22f0f7aae75db4cd1f8deec7fe671e00e3cec03b
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
h
/* Copyright (C) 2005 ireon.org developers council * $Id: interface.h 510 2006-02-26 21:09:40Z zak $ * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * 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. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * @file interface.h * Interface class */ #ifndef _EDITOR_I_INTERFACE_H #define _EDITOR_I_INTERFACE_H #include "interface/interface.h" class CEditorInterface : public CInterface { protected: CEditorInterface(); public: ~CEditorInterface(); static CEditorInterface* instance() {{if( !m_singleton ) m_singleton = new CEditorInterface; return m_singleton;}} bool init(RenderWindow* win); bool frameStarted(const FrameEvent &evt); void mouseMoved(MouseEvent *e); void mousePressedNoGUI(MouseEvent *e); void keyPressedNoGUI(KeyEvent *e); void pulseUpdate(Real time); protected: Real m_moveSpeed; Real m_moveScale; /// Detail solid/wireframe/points int m_sceneDetailIndex; private: static CEditorInterface* m_singleton; }; #endif
[ [ [ 1, 64 ] ] ]
b8e6d7a8daabc1a7c36cdaf4f6df8bd71d023f95
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonTangram/source/Controller/inc/LemonMenu.h
6c6ada21f8bde5dc2370c102a02e4f9786f75303
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
GB18030
C++
false
false
1,786
h
/* ============================================================================ Name : LemonMenu.h Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : CLemonMenu declaration ============================================================================ */ #ifndef LEMONMENU_H #define LEMONMENU_H // INCLUDES #include <e32std.h> #include <e32base.h> #include <COEDEF.H> #include <BITSTD.H> #include <W32STD.H> #include "MLemonMenuNotify.h" #include "DefaultDocHandler.h" #include "UIMgr.h" // CLASS DECLARATION class CLemonMenuBar; class CLemonMenuList; /** * CLemonMenu * */ class CLemonMenu : public CBase, public CDefaultDocHandler { public: // Constructors and destructor ~CLemonMenu(); static CLemonMenu* NewL(MLemonMenuNotify* aNotify); static CLemonMenu* NewLC(MLemonMenuNotify* aNotify); private: CLemonMenu(MLemonMenuNotify* aNotify); void ConstructL(); public: //CDefaultDocHandler virtual void StartElement(const TQualified& aName, const RArray<TAttribute>& aAttributes); virtual void EndElement(const TQualified& aName); void HideMenu(); void LoadMenuL(const TDesC& aFileName); void Draw(CFbsBitGc& gc); TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType); private: TInt ConvertNameToNumber(const TDesC& aName); void ParseMenu(const RArray<TAttribute>& aAttributes); void ParseItem(const RArray<TAttribute>& aAttributes); void EndParseMenu(); void FindListById(const TInt& aId); private: MLemonMenuNotify* iNotify; CLemonMenuBar* iMenuBar; CLemonMenuList* iMenuList; CLemonMenuList* iPtrList; //no own,用于添加数据用 TBool iMenuActive; MUIMgr* iUIMgr; }; #endif // LEMONMENU_H
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 75 ] ] ]
e254f63667c8775e8dcf269907ccbc423ca182cb
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Code/Flosti Engine/Graphics/ASEObject/ASETextureManager.h
e1a332b075fa09004a5cc6fa989507f5962d7c3d
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
h
//---------------------------------------------------------------------------------- // CObject3D class // Author: Enric Vergara // // Description: // //---------------------------------------------------------------------------------- #pragma once #ifndef INC_ASE_TEXTURE_MANAGER_H_ #define INC_ASE_TEXTURE_MANAGER_H_ #include <d3dx9.h> #include <map> #include <string> class CASETextureManager { public: CASETextureManager(); ~CASETextureManager() {/*Nothing todo*/;} static CASETextureManager * GetInstance (); void CleanUp (); LPDIRECT3DTEXTURE9 LoadTexture (const std::string& filename, LPDIRECT3DDEVICE9 Device); void SetTexturePath (const std::string& path) {m_TEXTURE_PATH = path;} private: void GetFilename (const char *path, std::string *filename); private: typedef std::map<std::string,LPDIRECT3DTEXTURE9>::iterator TTextureIterator; static CASETextureManager* m_TextureManager; std::map<std::string,LPDIRECT3DTEXTURE9> m_TextureMap; std::string m_TEXTURE_PATH; }; #endif //INC_ASE_TEXTURE_MANAGER_H_
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
4119b5f4d6e38dfaf75516c124bcda3be3e916da
50328883d48bc97b507aca76bab8630c30ee84f5
/src/Menu.cpp
813408fd6365d918f1b8e49a61891f41253f1c78
[ "MIT" ]
permissive
skeller1/datasynth
79efbba8ef494f8e92277499b283c4f03164f3e9
a84cc42e8678b7af054542c512124f4b07405f64
refs/heads/master
2021-01-23T23:56:20.440897
2011-12-18T20:32:55
2011-12-18T20:32:55
3,362,190
0
0
null
null
null
null
UTF-8
C++
false
false
5,593
cpp
#include "Menu.h" using namespace ds; Menu::Menu() { XMLObjects.loadFile("objects.xml"); XML.loadFile("menu.xml"); XML.pushTag("MENU", 0); bool bScan = true; int id = 0; vector <int> parents; int createId = 0; while(bScan) { if(XML.getNumTags("ENTRY") != 0) { id++; entry temp; temp.id = id; temp.name = XML.getAttribute("ENTRY","NAME", "", 0).c_str(); if(XML.getAttribute("ENTRY","TYPE", "", 0) != "") { temp.handler = XML.getAttribute("ENTRY","TYPE", "", 0).c_str(); } //get the entry id for creating objects if(temp.name == "Create") { createId = temp.id; } parents.push_back(id); temp.parent = parents[parents.size() - 2]; temp.level = XML.getPushLevel() - 1; temp.box.width = 100; temp.box.height = 15; temp.bIsVisible = false; //printf("%d - %d - %d - %s\n", temp.id, parents[parents.size() - 2], temp.level, temp.name.c_str()); entries.push_back(temp); XML.pushTag("ENTRY", 0); } else { XML.popTag(); parents.pop_back(); if (XML.tagExists("ENTRY", 0)) { XML.removeTag("ENTRY", 0); } else { bScan = false; } } } XMLObjects.pushTag("OBJECTS", 0); for(int i = 0; i < XMLObjects.getNumTags("OBJECT"); i++) { entry temp; temp.parent = createId; temp.name = XMLObjects.getAttribute("OBJECT","NAME", "", i).c_str(); temp.type = XMLObjects.getAttribute("OBJECT","TYPE", "", i).c_str(); temp.handler = "CreateNode"; temp.level = 1; temp.box.width = 100; temp.box.height = 15; temp.bIsVisible = false; entries.push_back(temp); } ofRegisterMouseEvents(this); bMouseIsOnNode = false; } Menu::~Menu() { ofUnregisterMouseEvents(this); XML.clear(); XMLObjects.clear(); } void Menu::draw() { int k = 0; for(unsigned int i = 0; i < entries.size(); i++) { if(entries[i].bIsVisible) { ofFill(); if(entries[i].box.inside(mouseX, mouseY)) { for(unsigned int j = 0; j < entries.size(); j++) { if(entries[j].parent == entries[i].id) { entries[j].box.x = entries[i].box.x + entries[i].box.width + 1; entries[j].box.y = entries[i].box.y + (k * (entries[i].box.height +1)); k++; entries[j].bIsVisible = true; } else { if(entries[j].level > entries[i].level) { entries[j].bIsVisible = false; } } } k = 0; ofSetColor(150,150,150,255); } else { ofSetColor(50,50,50,255); } ofRect(entries[i].box.x,entries[i].box.y,entries[i].box.width,entries[i].box.height); ofSetColor(255,255,255,255); ofDrawBitmapString(entries[i].name,entries[i].box.x + 3,entries[i].box.y + entries[i].box.height - 3); } } } void Menu::mouseMoved(ofMouseEventArgs & args) { mouseX = args.x; mouseY = args.y; } void Menu::mousePressed(ofMouseEventArgs & args) { //cout << "pressed (" << args.button << "," << x << "," << y << ")" << " bMouseIsOnNode: " << bMouseIsOnNode << endl; } void Menu::mouseDragged(ofMouseEventArgs & args) { } void Menu::mouseReleased(ofMouseEventArgs & args) { //cout << "released (" << args.button << "," << x << "," << y << ")" << " bMouseIsOnNode: " << bMouseIsOnNode << endl; if(args.button == 0) { for(unsigned int i = 0; i < entries.size(); i++) { if(entries[i].box.inside(mouseX, mouseY) && entries[i].bIsVisible) { menuEventType temp; temp.handler = entries[i].handler; temp.value = entries[i].name; temp.valueType = entries[i].type; ofNotifyEvent(menuEvent,temp,this); for(unsigned int i = 0; i < entries.size(); i++) { entries[i].bIsVisible = false; } } } } if(!bMouseIsOnNode) { //toggle if(args.button == 2) { x = args.x; y = args.y; int level = 0; for(unsigned int i = 0; i < entries.size(); i++) { //make all visible entries invisible first entries[i].bIsVisible = false; //move only the entries of the root level to the mouse pos and make them visible if(entries[i].parent == 0) { entries[i].box.x = x; entries[i].box.y = y + (level * (entries[i].box.height +1)); entries[i].bIsVisible = true; level++; } } } else { for(unsigned int i = 0; i < entries.size(); i++) { entries[i].bIsVisible = false; } } } }
[ [ [ 1, 189 ] ] ]
6de54f33d7d2155b6f84d1e9ce24a21adbf8bd99
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/core/icase.hpp
e1873701ccfc089aaa93bab73026f69c62d29769
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,220
hpp
/////////////////////////////////////////////////////////////////////////////// // icase.hpp // // Copyright 2004 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XPRESSIVE_DETAIL_CORE_ICASE_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_CORE_ICASE_HPP_EAN_10_04_2005 #include <boost/xpressive/detail/detail_fwd.hpp> #include <boost/xpressive/regex_constants.hpp> #include <boost/xpressive/detail/static/modifier.hpp> #include <boost/xpressive/detail/core/linker.hpp> namespace boost { namespace xpressive { namespace regex_constants { /////////////////////////////////////////////////////////////////////////////// /// \brief Makes a sub-expression case-insensitive. /// /// Use icase() to make a sub-expression case-insensitive. For instance, /// "foo" >> icase(set['b'] >> "ar") will match "foo" exactly followed by /// "bar" irrespective of case. detail::modifier_op<detail::icase_modifier> const icase = {{}, regex_constants::icase_}; } // namespace regex_constants using regex_constants::icase; }} // namespace boost::xpressive #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 33 ] ] ]
a9a355ac43214c4cbb0ee62fb85136164946aa7c
7d6597b8619a63f65b8a6cfcae721da7592b92aa
/spiral-core/include/spiral/internet/interfaces/IProducer.h
40c7bcdefad3869a7cbf7b6d7eafeb77a83835b9
[ "MIT" ]
permissive
RangelReale/spiral-io
51eb976a1def7959d364a57921cab527d30ea428
cf8dbdfcfbef5dc8092fd7ea0ce8d052edf2f35d
refs/heads/master
2023-07-06T22:39:19.708949
2009-12-10T21:00:22
2009-12-10T21:00:22
37,156,634
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
#ifndef _SPIRAL_INTERNET_INTERFACES_IPRODUCER_H__ #define _SPIRAL_INTERNET_INTERFACES_IPRODUCER_H__ namespace spiral { namespace internet { namespace interfaces { /** * A producer produces data for a consumer. * * Typically producing is done by calling the write method of an class * implementing L{IConsumer}. */ class IProducer { public: /** * Stop producing data. * * This tells a producer that its consumer has died, so it must stop * producing data for good. */ virtual void stopProducing() = 0; virtual ~IProducer() {} }; }}} // spiral::internet::interfaces #endif // _SPIRAL_INTERNET_INTERFACES_IPRODUCER_H__
[ "hitnrun@6cb40615-3296-4dc8-bcc4-269c24c2e8c1" ]
[ [ [ 1, 30 ] ] ]
003e14b62d7b0bba17a08e7c6f50adedfd4b567e
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/comsvcs.hpp
e01501df10f8cecd41b18a839d49e28306b74634
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
994
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'ComSvcs.pas' rev: 6.00 #ifndef ComSvcsHPP #define ComSvcsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <ActiveX.hpp> // Pascal unit #include <Mtx.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Comsvcs { //-- type declarations ------------------------------------------------------- //-- var, const, procedure --------------------------------------------------- } /* namespace Comsvcs */ using namespace Comsvcs; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // ComSvcs
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 33 ] ] ]
cda8c6155f3828993a2064f54d0ae6ccc2535989
3ea9ea4da0819d1cdf99cac9225c5b34e48430b1
/assign2-cpp/Program.cpp
8a870064774f9882257927a313a58bc6b5c13cb8
[]
no_license
keithfancher/Programming-Languages
b32697a233253dacd679cc120d698f552af02a93
f84ccf9beb4a56022c1ad0dae1400cab5b39fb5d
refs/heads/master
2016-09-10T08:05:41.992568
2011-07-23T23:16:34
2011-07-23T23:16:34
2,304,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
cpp
//**************************************************************************** // File : Program.cpp // Author: Keith T. Fancher // Date : 02/09/04 // Class : CS3490 // // Purpose: The implementation for the Program class, which is used to read // in the program, generate the binary, and other such useful thingies. //**************************************************************************** using namespace std; #include <iostream> #include <iomanip> #include <fstream> #include "Instruction.h" #include "Parse.h" #include "Program.h" Program::Program() { instructionCount = 0; } void Program::read(ifstream & in) { // infinite loops make things like this smoother, so there! while(42) { ins[instructionCount] = p.parse(in); if(!ins[instructionCount]) // if parse returns NULL we're done break; instructionCount++; } } void Program::generate(ofstream & of) { for(int i = 0; i < instructionCount; i++) { // output the 32-bit hex values to the output file of << setfill('0') << setw(8) << hex << ins[i]->encode() << endl; } } void Program::print() { cout << endl; // negative space! for(int i = 0; i < instructionCount; i++) ins[i]->print(); cout << endl; // a space between program and table for pretty-tude ins[0]->printSymbols(); }
[ [ [ 1, 57 ] ] ]
de07a4a4d13a490884b2418f7824ae9868f6248d
faaac39c2cc373003406ab2ac4f5363de07a6aae
/ zenithprime/src/controller/BattleBoard/BBSelectedState.cpp
64e17d5151ced8d4c5d83dc20e84bf5c13103e25
[]
no_license
mgq812/zenithprime
595625f2ec86879eb5d0df4613ba41a10e3158c0
3c8ff4a46fb8837e13773e45f23974943a467a6f
refs/heads/master
2021-01-20T06:57:05.754430
2011-02-05T17:20:19
2011-02-05T17:20:19
32,297,284
0
0
null
null
null
null
UTF-8
C++
false
false
2,184
cpp
#include "BBState.h" BBSelectedState* nullState = NULL; BBSelectedState* BBSelectedState::getState(){ if(nullState==NULL){ nullState = new BBSelectedState(); } return nullState; } void BBSelectedState::LeftMouseClick(NxRaycastHit& hit, BBControler* control){ if(hit.shape ==NULL){ control->getModel()->clearSelectedShips(); control->setState(BBNullState::getState()); } else if(hit.shape->isPlane()) { std::vector<BBShipModel*> list; control->getModel()->getSelectedShips(list); if(list.size() == 1) control->getModel()->getShipController()->MoveShip(list[0], hit.worldImpact.x, hit.worldImpact.z); for(int i = 0; i < list.size(); i++){ //list[i]->shipActor->moveGlobalPosition(hit.worldImpact); float dirx = hit.worldImpact.x - list[i]->getX(); float diry = hit.worldImpact.z - list[i]->getY(); list[i]->shipActor->addTorque(NxVec3(dirx,0.0f,diry)); } } else { if(!Keyboard::getCurrentKeyboard()->Keys[VK_SHIFT]){ control->getModel()->clearSelectedShips(); } control->getModel()->addSelectedShip((BBShipModel*)hit.shape->userData); } } void BBSelectedState::RightMouseClick(NxRaycastHit& hit, BBControler* control){ control->getModel()->clearSelectedShips(); control->setState(BBNullState::getState()); if(hit.shape ==NULL){ } else if(hit.shape->isPlane()) { } else { control->getModel(); } } void BBSelectedState::MouseHover(NxRaycastHit& hit, BBControler* control){ control->getModel()->clearHighlightedShips(); if(hit.shape ==NULL){ } else if(hit.shape->isPlane()) { std::vector<BBShipModel*> list; control->getModel()->getSelectedShips(list); if(list.size() == 1) control->getModel()->getShipController()->TryMoveShip(list[0], hit.worldImpact.x, hit.worldImpact.z); } else { control->getModel()->addHighlightedShip((BBShipModel*)hit.shape->userData); } } void BBSelectedState::LeftMouseDrag(NxRaycastHit& hit, BBControler* control){ if(hit.shape ==NULL){ //Do Nothing } else if(hit.shape->isPlane()) { } else { control->getModel(); } } BBSelectedState::BBSelectedState(){ }
[ "mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394" ]
[ [ [ 1, 89 ] ] ]
e1a46ba21bcffdb88d0f788424f2f7f2b7ebf021
7f30cb109e574560873a5eb8bb398c027f85eeee
/src/wxPacsPreferencesGui.cxx
7e37066ccdbcc90d3303aeeac864322fe2a322d8
[]
no_license
svn2github/MITO
e8fd0e0b6eebf26f2382f62660c06726419a9043
71d1269d7666151df52d6b5a98765676d992349a
refs/heads/master
2021-01-10T03:13:55.083371
2011-10-14T15:40:14
2011-10-14T15:40:14
47,415,786
1
0
null
null
null
null
UTF-8
C++
false
false
13,601
cxx
/** * \file wxPacsPreferencesGui.cxx * \brief File per la creazione del dialog per la scelta dei parametri di connessione al PACS * \author ICAR-CNR Napoli */ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "preferences.h" #endif #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wxPacsPreferencesGui.h" #include "pacsStoreSCP.h" #include "wxMainGui.h" #include <string> using namespace std; /* * wxPacsPreferencesGui type definition */ IMPLEMENT_DYNAMIC_CLASS( wxPacsPreferencesGui, wxDialog ) /* * wxPacsPreferencesGui event table definition */ BEGIN_EVENT_TABLE( wxPacsPreferencesGui, wxDialog ) //wxPacsPreferencesGui event table entries EVT_CLOSE( wxPacsPreferencesGui::OnCloseWindow ) EVT_BUTTON( cancel_button, wxPacsPreferencesGui::OnCancel ) EVT_BUTTON( ok_button, wxPacsPreferencesGui::OnAccept ) EVT_BUTTON( help_button1, wxPacsPreferencesGui::OnHelp1 ) EVT_BUTTON( help_button2, wxPacsPreferencesGui::OnHelp2 ) EVT_BUTTON( help_button3, wxPacsPreferencesGui::OnHelp3 ) EVT_BUTTON( browse_button, wxPacsPreferencesGui::OnBrowse ) //wxPacsPreferencesGui event table entries END_EVENT_TABLE() /* * wxPacsPreferencesGui constructors */ wxPacsPreferencesGui::wxPacsPreferencesGui() { } wxPacsPreferencesGui::wxPacsPreferencesGui(wxWindow* parent, pacsPreferences *_prefs, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style) { Create(parent, _prefs, id, caption, pos, size, style); } /* * wxPacsPreferencesGui distructor */ wxPacsPreferencesGui::~wxPacsPreferencesGui() { } /*! * wxPacsPreferencesGui creator */ bool wxPacsPreferencesGui::Create( wxWindow* parent, pacsPreferences *_prefs, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); prefs = _prefs; current = NULL; CreateControls(); GetSizer()->Fit(this); GetSizer()->SetSizeHints(this); Centre(); return true; } /* * Control creation for wxPacsPreferencesGui */ void wxPacsPreferencesGui::CreateControls() { preferencesDialog = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); preferencesDialog->SetSizer(itemBoxSizer2); wxNotebook* itemNotebook3 = new wxNotebook( preferencesDialog, notebook2, wxDefaultPosition, wxDefaultSize, wxNB_TOP ); wxPanel* itemPanel4 = new wxPanel( itemNotebook3, notebook2_panel1, wxDefaultPosition, wxSize(250, 280), wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL); itemPanel4->SetSizer(itemBoxSizer5); wxBoxSizer* itemBoxSizer6 = new wxBoxSizer(wxVERTICAL); itemBoxSizer5->Add(itemBoxSizer6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText7 = new wxStaticText( itemPanel4, wxID_STATIC, _("&Server Node"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer6->Add(itemStaticText7, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); serverInput = new wxTextCtrl( itemPanel4, panel1_textCtrl1, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer6->Add(serverInput, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText9 = new wxStaticText( itemPanel4, wxID_STATIC, _("&Server Port"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer6->Add(itemStaticText9, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); portInput = new wxTextCtrl( itemPanel4, panel1_textCtrl2, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer6->Add(portInput, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText11 = new wxStaticText( itemPanel4, wxID_STATIC, _("&Called AP Title"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer6->Add(itemStaticText11, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); calledAPInput = new wxTextCtrl( itemPanel4, panel1_textCtrl3, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer6->Add(calledAPInput, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText13 = new wxStaticText( itemPanel4, wxID_STATIC, _("&Calling AP Title"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer6->Add(itemStaticText13, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); callingAPInput = new wxTextCtrl( itemPanel4, panel1_textCtrl4, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer6->Add(callingAPInput, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText15 = new wxStaticText( itemPanel4, wxID_STATIC, _("&Storage AP Title"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer6->Add(itemStaticText15, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); storageAPInput = new wxTextCtrl( itemPanel4, panel1_textCtrl5, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer6->Add(storageAPInput, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); itemNotebook3->AddPage(itemPanel4, _("&Network")); wxPanel* itemPanel17 = new wxPanel( itemNotebook3, notebook2_panel2, wxDefaultPosition, wxSize(250, 280), wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer18 = new wxBoxSizer(wxHORIZONTAL); itemPanel17->SetSizer(itemBoxSizer18); wxBoxSizer* itemBoxSizer19 = new wxBoxSizer(wxVERTICAL); itemBoxSizer18->Add(itemBoxSizer19, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText20 = new wxStaticText( itemPanel17, wxID_STATIC, _("&Storage Server Port"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer19->Add(itemStaticText20, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); receiveStorageInput = new wxTextCtrl( itemPanel17, panel2_textCtrl1, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer19->Add(receiveStorageInput, 0, wxALIGN_LEFT|wxALL, 5); wxBoxSizer* itemBoxSizer22 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer19->Add(itemBoxSizer22, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); //receiveStorageExecButton = new wxCheckBox( itemPanel17, start_button, _("&Start/Stop automatically"), wxDefaultPosition, wxDefaultSize, 0 ); //receiveStorageExecButton->SetValue(false); //itemBoxSizer22->Add(receiveStorageExecButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton24 = new wxButton( itemPanel17, help_button1, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer22->Add(itemButton24, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText25 = new wxStaticText( itemPanel17, wxID_STATIC, _("&Receive/Local Files Directory"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer19->Add(itemStaticText25, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); receiveDirectoryInput = new wxTextCtrl( itemPanel17, panel2_textCtrl2, _T(""), wxDefaultPosition, wxSize(220, -1), wxTE_READONLY ); itemBoxSizer19->Add(receiveDirectoryInput, 0, wxALIGN_LEFT|wxALL, 5); wxBoxSizer* itemBoxSizer27 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer19->Add(itemBoxSizer27, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* itemButton28 = new wxButton( itemPanel17, help_button2, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer27->Add(itemButton28, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton29 = new wxButton( itemPanel17, browse_button, _("&Browse"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer27->Add(itemButton29, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText30 = new wxStaticText( itemPanel17, wxID_STATIC, _("&Max PDU"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer19->Add(itemStaticText30, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); maxPDU = new wxTextCtrl( itemPanel17, panel2_textCtrl3, _T(""), wxDefaultPosition, wxSize(220, -1), 0 ); itemBoxSizer19->Add(maxPDU, 0, wxALIGN_LEFT|wxALL, 5); wxButton* itemButton32 = new wxButton( itemPanel17, help_button3, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer19->Add(itemButton32, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); itemNotebook3->AddPage(itemPanel17, _("&Transfer/Receive")); itemBoxSizer2->Add(itemNotebook3, 0, wxALIGN_LEFT|wxALL, 5); wxBoxSizer* itemBoxSizer33 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer33, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* itemButton34 = new wxButton( preferencesDialog, ok_button, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer33->Add(itemButton34, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton35 = new wxButton( preferencesDialog, cancel_button, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer33->Add(itemButton35, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); } /* * Should we show tooltips? */ bool wxPacsPreferencesGui::ShowToolTips() { return true; } /* * Get bitmap resources */ wxBitmap wxPacsPreferencesGui::GetBitmapResource( const wxString& name ) { // Bitmap retrieval wxUnusedVar(name); return wxNullBitmap; } /* * Get icon resources */ wxIcon wxPacsPreferencesGui::GetIconResource( const wxString& name ) { // Icon retrieval wxUnusedVar(name); return wxNullIcon; } void wxPacsPreferencesGui::initSettings() { // initialize current settings if (current) { // items in the Network group serverInput->SetValue(current->server); calledAPInput->SetValue(current->calledAP); callingAPInput->SetValue(current->callingAP); storageAPInput->SetValue(current->storageAP); portInput->SetValue(current->serverPort); // items in the Receive group receiveStorageInput->SetValue(current->port); receiveDirectoryInput->SetValue(current->localDirectory); maxPDU->SetValue(current->maxPDU); } else { serverInput->SetValue(""); calledAPInput->SetValue(""); callingAPInput->SetValue(""); storageAPInput->SetValue(""); portInput->SetValue(""); // items in the Receive group receiveStorageInput->SetValue(""); receiveDirectoryInput->SetValue(""); maxPDU->SetValue(""); } } void wxPacsPreferencesGui::saveSettings() { // save fields to current // items in the Network group strcpy(current->server, serverInput->GetValue().c_str()); strcpy(current->calledAP, calledAPInput->GetValue().c_str()); strcpy(current->callingAP, callingAPInput->GetValue().c_str()); strcpy(current->storageAP, storageAPInput->GetValue().c_str()); strcpy(current->serverPort, portInput->GetValue().c_str()); // items in the Receive group strcpy(current->port, receiveStorageInput->GetValue().c_str()); //current->storageExec = receiveStorageExecButton->GetValue(); strcpy(current->localDirectory, receiveDirectoryInput->GetValue().c_str()); strcpy(current->maxPDU, maxPDU->GetValue().c_str()); strcpy(current->storageServer,""); strcpy(current->storeClient,"send_image -a "); strcat(current->storeClient,current->callingAP); strcat(current->storeClient," -c "); strcat(current->storeClient,current->calledAP); strcat(current->storeClient," -m "); strcat(current->storeClient,current->maxPDU); strcat(current->storeClient," "); strcat(current->storeClient,current->server); strcat(current->storeClient," "); strcat(current->storeClient,current->serverPort); //strcat(current->storeClient," > "); //strcat(current->storeClient,current->logFile); } void wxPacsPreferencesGui::show() { // create our working copy current = new pacsPreferences(prefs); // set up the data for editing initSettings(); // show the window preferencesDialog->Show(true); } void wxPacsPreferencesGui::quit(int _save) { // save indicates if current should replace prefs if (current != NULL) { if (_save == 1) { memcpy(prefs, current, sizeof(pacsPreferences)); delete current; current = NULL; // Alcune impostazioni richiedono il riavvio del server SCP pacsStoreSCP *pServer = ((wxMainGui*)GetParent())->getPacsStoreServer(); if(pServer) { // close the gui //preferencesDialog->Show(false); pServer->Stop(); pServer->Start(); } } else { delete current; current = NULL; } } // close the gui preferencesDialog->Show(false); } void wxPacsPreferencesGui::browse(wxTextCtrl* input) { string fileName="."; wxDirDialog *dlg = new wxDirDialog(this, "Select a directory", "."); if (dlg->ShowModal() == wxID_OK) fileName = dlg->GetPath().c_str(); dlg->Destroy(); input->SetValue(fileName.c_str()); } void wxPacsPreferencesGui::OnCancel( wxCommandEvent& event ) { quit(0); } void wxPacsPreferencesGui::OnAccept( wxCommandEvent& event ) { saveSettings(); quit(1); } void wxPacsPreferencesGui::OnHelp1( wxCommandEvent& event ) { wxMessageBox(_("Please enter the storage server port.")); } void wxPacsPreferencesGui::OnHelp2( wxCommandEvent& event ) { wxMessageBox(_("Enter the directory to be used by default for browsing local DICOM objects and storing images after transfer.")); } void wxPacsPreferencesGui::OnHelp3( wxCommandEvent& event ) { wxMessageBox(_("Please enter the Maximum PDU for find, move and store operations.")); } void wxPacsPreferencesGui::OnBrowse( wxCommandEvent& event ) { browse(receiveDirectoryInput); } void wxPacsPreferencesGui::OnCloseWindow( wxCloseEvent& event ) { quit(0); }
[ "kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de" ]
[ [ [ 1, 382 ] ] ]
4cd69388896e80fba9b03a9a81eac51399f0a6ae
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CX/11000.cpp
18a240b4ac9bd6ade536e5e5637c5cda47acf7f5
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
///////////////////////////////// // 11000 - Bee ///////////////////////////////// #include<cstdio> unsigned int f[45],i,m[45]; int k; int main(void){ m[0] = 0; f[0] = 1; for(i = 1; i < 45; i++) m[i] = f[i-1], f[i] = m[i-1]+f[i-1]+1; while(scanf("%d",&k) && k != -1) printf("%u %u\n",m[k],f[k]); return 0; }
[ [ [ 1, 15 ] ] ]
f0d4eab4765cd36125c89283b29bf06d99027811
23c0843109bcc469d7eaf369809a35e643491500
/Sound/SoundACM.cpp
a9687d074f1b5788ecb723c7918fb283f07f16b3
[]
no_license
takano32/d4r
eb2ab48b324c02634a25fc943e7a805fea8b93a9
0629af9d14035b2b768d21982789fc53747a1cdb
refs/heads/master
2021-01-19T00:46:58.672055
2009-01-07T01:28:38
2009-01-07T01:28:38
102,349
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,490
cpp
#include "SoundACM.h" #include <winbase.h> #include "../Log.h" using namespace base; SoundACM::SoundACM(void){ m_bOpen = false; } SoundACM::~SoundACM(){ Close(); } LRESULT SoundACM::Open(WAVEFORMATEX *pWFormat,LPVOID lpSrcBuf,DWORD dwSrcLength){ Close(); // 忘れんうちに引数をコピー:p m_lpSrcWFormat = pWFormat; m_lpSrcBuf = lpSrcBuf; m_dwSrcLength = dwSrcLength; // 構造体初期化 ::ZeroMemory(&m_destWFormat, sizeof(m_destWFormat)); ::ZeroMemory(&m_acmheader, sizeof(m_acmheader)); m_hAcm = NULL; m_dwDestLength = 0; m_destWFormat.wFormatTag = WAVE_FORMAT_PCM; // PCMになって欲しいねん! if (acmFormatSuggest(NULL,pWFormat,&m_destWFormat,sizeof(WAVEFORMATEX),ACM_FORMATSUGGESTF_WFORMATTAG)!=0){ return 1; // acm無いんとちゃう? } if (acmStreamOpen(&m_hAcm,NULL,pWFormat,&m_destWFormat,NULL,NULL,NULL,ACM_STREAMOPENF_NONREALTIME)!=0){ return 2; // acmおかしんとちゃう? } if (acmStreamSize(m_hAcm,dwSrcLength,&m_dwDestLength,ACM_STREAMSIZEF_SOURCE)!=0){ return 3; // なんでやねんと言いたい(笑) } if (m_dwDestLength == 0) return 4; // なぜじゃー m_bOpen = true; // Openに成功。これより任務に移る:p return 0; } LRESULT SoundACM::Open(LPBYTE src,DWORD size){ // 直接MP3のファイルとかをオープン:p LPBYTE src_begin = src; // フレームヘッダからWAVEFORMATEXのデータを用意する if (size <= 128) return 1; // そんな小さいわけあらへんがな:p // ID3v2タグがついているならば、読み飛ばす if ((src[0] == 'I') && (src[1] == 'D') && (src[2] == '3')) { DWORD dwID3Size = src[9] + (src[8]<<7) + (src[7]<<14) + (src[6]<<21); // バージョンチェック if(src[3]>=0x04) { // ID3v2.4.0以降 if(src[5]&0x10){ // フッタの有無 dwID3Size+=20; // フッタあり }else{ dwID3Size+=10; // フッタなし } }else{ // ID3v2.3.0以前 dwID3Size+=10; // フッタなし } if (size <= dwID3Size + 128) return 1; src += dwID3Size; size -= dwID3Size; } // MP3チェック if (src[0] !=0xff) return 1; if ((src[1]&0xf8)!=0xf8) return 1; int anBitrate[2][3][16] = { { // MPEG-1 { 0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0 }, // 32000Hz(layer1) { 0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,0 }, // 44100Hz(layer2) { 0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,0 }, // 48000Hz(layer3) }, { // MPEG-2 { 0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256,0 }, // 32000Hz(layer1) { 0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,0 }, // 44100Hz(layer2) { 0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,0 }, // 48000Hz(layer3) }, }; int anFreq[2][4] = { { 44100,48000,32000,0 }, { 22050,24000,16000,0 }, }; int nLayer = 4-((src[1] >> 1) & 3); if (nLayer == 4) { Log::Error( "SoundACM::Open MP3が無効なレイヤ" ); return 1; } int nMpeg = ((src[1] & 8) == 0) ? 1 : 0; int nBitrate = anBitrate[nMpeg][nLayer-1][ src[2]>>4 ]; int nFreq = anFreq[nMpeg][(src[2] >> 2) & 3]; int nChannel = ((src[3] >> 6) == 3) ? 1 : 2; int nFrameSize = 144000 * nBitrate / nFreq; // 無理矢理MP3のタグを用意する ::ZeroMemory(&m_WFormat, sizeof(m_WFormat)); m_WFormat.wfx.cbSize = MPEGLAYER3_WFX_EXTRA_BYTES; m_WFormat.wfx.wFormatTag = WAVE_FORMAT_MPEGLAYER3; m_WFormat.wfx.nChannels = nChannel; m_WFormat.wfx.nSamplesPerSec = nFreq; m_WFormat.wfx.nAvgBytesPerSec = nBitrate * 1000 / 8; m_WFormat.wfx.nBlockAlign = 1; m_WFormat.wfx.wBitsPerSample = 0; m_WFormat.wID = MPEGLAYER3_ID_MPEG; m_WFormat.fdwFlags = MPEGLAYER3_FLAG_PADDING_OFF; m_WFormat.nBlockSize = nFrameSize; m_WFormat.nFramesPerBlock = 1; m_WFormat.nCodecDelay = 0x0571; // 後ろにID3タグがついているならば、その分を除外する // size>128である事は保証されている if ((src_begin[size-128] == 'T') && (src_begin[size-127] == 'A') && (src_begin[size-126] == 'G')) { size -= 128; } return Open((WAVEFORMATEX*)&m_WFormat,(LPVOID)(src+4),size-4); }; WAVEFORMATEX* SoundACM::GetFormat(void) { if (m_bOpen) return &m_destWFormat; return NULL;// Openしてへんのに呼ぶな〜! } DWORD SoundACM::GetSize(void) const { if (m_bOpen) return m_dwDestLength; return 0; // Openしてへんのに呼ぶな〜! } LRESULT SoundACM::Convert(LPVOID lpDestBuf){ // ここでDirectSoundのLockしたメモリポインタを渡す if (!m_bOpen) { return 1; // Openできてへんのに呼ぶなっちゅーに! } m_acmheader.cbStruct = sizeof(m_acmheader); m_acmheader.pbSrc = (BYTE*)m_lpSrcBuf; m_acmheader.cbSrcLength = m_dwSrcLength; m_acmheader.pbDst = (BYTE*)lpDestBuf; // ここにコピーしたいねん! m_acmheader.cbDstLength = m_dwDestLength; if (acmStreamPrepareHeader(m_hAcm,&m_acmheader,NULL)!=0) { return 2; // 勘弁して〜(笑) } if (acmStreamConvert(m_hAcm,&m_acmheader,NULL)!=0){ return 3; // ダメじゃん(笑) } return 0; // 任務終了 } LRESULT SoundACM::Close(void) { if (m_bOpen) { m_bOpen = false; acmStreamUnprepareHeader(m_hAcm,&m_acmheader,NULL); return acmStreamClose(m_hAcm,NULL); } return 0; } bool SoundACM::IsOpen(void) const { return m_bOpen; }
[ [ [ 1, 181 ] ] ]
19c0a83f2f220206cdb49ec2aaa49c6d521541e9
42a799a12ffd61672ac432036b6fc8a8f3b36891
/cpp/IGC_Tron/IGC_Tron/OGLTexture.cpp
76bdd4eaf439644bc902b03b327ff05a7f59d2b8
[]
no_license
timotheehub/igctron
34c8aa111dbcc914183d5f6f405e7a07b819e12e
e608de209c5f5bd0d315a5f081bf0d1bb67fe097
refs/heads/master
2020-02-26T16:18:33.624955
2010-04-08T16:09:10
2010-04-08T16:09:10
71,101,932
0
0
null
null
null
null
UTF-8
C++
false
false
4,029
cpp
/**************************************************************************/ /* This file is part of IGC Tron */ /* (c) IGC Software 2009 - 2010 */ /* Author : Pierre-Yves GATOUILLAT */ /**************************************************************************/ /* 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 3 of the License, or */ /* (at your option) 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. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************/ /***********************************************************************************/ /** INCLUSIONS **/ /***********************************************************************************/ #include "Engine.h" #include "OGLTexture.h" /***********************************************************************************/ /** DEBUG **/ /***********************************************************************************/ #include "Debug.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /***********************************************************************************/ namespace IGC { /***********************************************************************************/ /** CONSTRUCTEURS / DESTRUCTEUR **/ /***********************************************************************************/ OGLTexture::OGLTexture( Engine* _engine ) : ITexture( _engine ) { glTexID = 0; } OGLTexture::~OGLTexture() { if ( glTexID != 0 ) glDeleteTextures( 1, &glTexID ); } /***********************************************************************************/ /** METHODES PUBLIQUES **/ /***********************************************************************************/ void OGLTexture::update() { glEnable( GL_TEXTURE_2D ); glGenTextures( 1, &glTexID ); glBindTexture( GL_TEXTURE_2D, glTexID ); if ( format == FORMAT_L8 ) glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE8, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data ); else if ( format == FORMAT_L8A8 ) glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE8_ALPHA8, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, data ); else if ( format == FORMAT_R8G8B8 ) glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); else if ( format == FORMAT_R8G8B8A8 ) glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); dirty = false; } void OGLTexture::bind() { if ( dirty ) update(); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, glTexID ); } void OGLTexture::unbind() { glDisable( GL_TEXTURE_2D ); } }
[ "raoul12@de5929ad-f5d8-47c6-8969-ac6c484ef978", "[email protected]" ]
[ [ [ 1, 93 ], [ 99, 99 ] ], [ [ 94, 98 ] ] ]
01443b9f68a00ead6104400838731f3519ef39e1
c3ae23286c2e8268355241f8f06cd1309922a8d6
/rateracerlib/mathlib/Matrix3.h
1d190a4fe13bcd938f6f206e9437fe04e15f9d2a
[]
no_license
BackupTheBerlios/rateracer-svn
2f43f020ecdd8a3528880d474bec1c0464879597
838ad3f326962028ce8d493d2c06f6af6ea4664c
refs/heads/master
2020-06-04T03:31:51.633612
2005-05-30T06:38:01
2005-05-30T06:38:01
40,800,078
0
0
null
null
null
null
UTF-8
C++
false
false
3,817
h
#pragma once #pragma warning( disable : 4514 ) // unreferenced inline function deleted #pragma warning( disable : 4710 ) // function not inlined #include <stdio.h> #include <assert.h> #include "MathUtils.h" class Vec3; class Matrix3 { protected: float m_[3][3]; // [col][row] public: Matrix3(); Matrix3(const Matrix3&); Matrix3(float, float, float, float, float, float, float, float, float); // array access float* operator [](int); const float* operator [](int) const; // assignment Matrix3& assign(float, float, float, float, float, float, float, float, float); void setZero(); void setIdentity(); void copyFrom(float [3][3]); void copyTo(float [3][3]) const; // math operators Matrix3& operator =(const Matrix3&); Matrix3& operator +=(const Matrix3&); Matrix3& operator -=(const Matrix3&); Matrix3& operator *=(const Matrix3&); Matrix3& operator *=(float); Matrix3& operator /=(float); Matrix3 operator +(const Matrix3&) const; Matrix3 operator -(const Matrix3&) const; Matrix3 operator -() const; Matrix3 operator *(const Matrix3&) const; Matrix3 operator *(float) const; Matrix3 operator /(float) const; friend Matrix3 operator *(float, const Matrix3&); bool operator ==(const Matrix3&) const; bool operator !=(const Matrix3&) const; Vec3 operator *(const Vec3&) const; friend Vec3 operator *(const Vec3&, const Matrix3&); // operations Matrix3 inverse() const; // FIXME Matrix3 inverseOrtho() const; Matrix3 transpose() const; Matrix3 adjoint() const; float determinant() const; bool isSingular() const; // transformation matrices static Matrix3 identity(); static Matrix3 rotate(float); static Matrix3 scale(float, float); static Matrix3 scaleUniform(float); static Matrix3 translate(float, float); void print( char *str ); }; // CONSTRUCTORS MATH_INLINE Matrix3::Matrix3() { //setZero(); } MATH_INLINE Matrix3::Matrix3(const Matrix3& M) { (*this) = M; } MATH_INLINE Matrix3::Matrix3(float e00, float e01, float e02, float e10, float e11, float e12, float e20, float e21, float e22) { assign(e00, e01, e02, e10, e11, e12, e20, e21, e22); } // ARRAY ACCESS MATH_INLINE float* Matrix3::operator [](int i) { assert(i == 0 || i == 1 || i == 2 || i == 3); return &m_[i][0]; } MATH_INLINE const float* Matrix3::operator [](int i) const { assert(i == 0 || i == 1 || i == 2 || i == 3); return &m_[i][0]; } // ASSIGNMENT MATH_INLINE Matrix3& Matrix3::assign(float e00, float e01, float e02, float e10, float e11, float e12, float e20, float e21, float e22) { m_[0][0] = e00; m_[1][0] = e01; m_[2][0] = e02; m_[0][1] = e10; m_[1][1] = e11; m_[2][1] = e12; m_[0][2] = e20; m_[1][2] = e21; m_[2][2] = e22; return *this; } MATH_INLINE void Matrix3::setZero() { assign(0,0,0, 0,0,0, 0,0,0); } MATH_INLINE void Matrix3::setIdentity() { assign(1,0,0, 0,1,0, 0,0,1); } MATH_INLINE Matrix3& Matrix3::operator =(const Matrix3& M) { assign(M[0][0], M[1][0], M[2][0], M[0][1], M[1][1], M[2][1], M[0][2], M[1][2], M[2][2]); return *this; } MATH_INLINE void Matrix3::copyFrom(float f[3][3]) { assign(f[0][0], f[1][0], f[2][0], f[0][1], f[1][1], f[2][1], f[0][2], f[1][2], f[2][2]); } MATH_INLINE void Matrix3::copyTo(float f[3][3]) const { f[0][0] = m_[0][0]; f[0][1] = m_[0][1]; f[0][2] = m_[0][2]; f[1][0] = m_[1][0]; f[1][1] = m_[1][1]; f[1][2] = m_[1][2]; f[2][0] = m_[2][0]; f[2][1] = m_[2][1]; f[2][2] = m_[2][2]; }
[ "gweronimo@afd64b18-8dda-0310-837d-b02fe5df315d" ]
[ [ [ 1, 170 ] ] ]
0fd8d3afbd7f3454144b0f3b4bd16bee69c69106
8342f87cc7e048aa812910975c68babc6fb6c5d8
/client/Game2/UpdateDownloader.cpp
44be94fd2832ecf774d1ea44011744c423c9afb5
[]
no_license
espes/hoverrace
1955c00961af4bb4f5c846f20e65ec9312719c08
7d5fd39ba688e2c537f35f7c723dedced983a98c
refs/heads/master
2021-01-23T13:23:03.710443
2010-12-19T22:26:12
2010-12-19T22:26:12
2,005,364
0
1
null
null
null
null
UTF-8
C++
false
false
5,550
cpp
// UpdateDownloader.cpp // Downloads and applies updates from the central update server. // // Copyright (c) 2009 Ryan Curtin // // Licensed under GrokkSoft HoverRace SourceCode License v1.0(the "License"); // you may not use this file except in compliance with the License. // // A copy of the license should have been attached to the package from which // you have taken this file. If you can not find the license you can not use // this file. // // // The author makes no representations about the suitability of // this software for any purpose. It is provided "as is" "AS IS", // 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. #include "StdAfx.h" #include "../../engine/Util/Config.h" #include "../../engine/Net/Agent.h" #include "../../engine/Net/NetExn.h" #include "../../engine/Util/OS.h" #include "UpdateDownloader.h" using namespace std; using namespace HoverRace; using namespace HoverRace::Client; using namespace HoverRace::Util; UpdateDownloader::UpdateDownloader() { // nothing to do } UpdateDownloader::~UpdateDownloader() { // nothing to do } /*** * Check the specified update server to see if HoverRace can be updated. * If we are a development build (cfg->IsPrerelease()) we will only attempt to update * to the newest development version, and stable versions (!cfg->IsPrerelease()) will * only attempt to update to the newest stable version. * * @param url Address of update server (stored in config) * @param cancelFlag Pointer to transfer cancel flag * * @return * true if an update is required * false if the current version is up to date * * @throws NetExn if transfer fails for some reason */ bool UpdateDownloader::CheckUrl(const std::string &url, Net::CancelFlagPtr cancelFlag) { Config *cfg = Config::GetInstance(); Net::Agent agent(url); //TODO: Set max size. stringstream io; agent.Get(io, cancelFlag); string in; getline(io, in); if(in != "VERSION LIST") throw Net::NetExn("Invalid format: Missing preamble"); io.exceptions(std::istream::badbit | std::istream::failbit); string stableVersion; string develVersion; string serverLocation; for( ; ; ) { string type; try { io >> type; } catch (istream::failure &) { break; // EOF } if(type == "stable") { io >> stableVersion; } else if(type == "devel") { io >> develVersion; } else if(type == "server") { io >> serverLocation; } } // verify information if(stableVersion == "") throw Net::NetExn("Cannot find newest stable version"); if(develVersion == "" && cfg->IsPrerelease()) throw Net::NetExn("Cannot find newest development version"); if(serverLocation == "") throw Net::NetExn("Cannot find update server"); currentVersion = Version(cfg->GetFullVersion()); updatedVersion = Version((cfg->IsPrerelease()) ? develVersion : stableVersion); if(updatedVersion > currentVersion) { // update is necessary // generate url char buffer[500]; #ifdef _DEBUG sprintf(buffer, "hoverrace-update-%ld.%ld.%ld.%ld-to-%ld.%ld.%ld.%ld.debug.zip", currentVersion.major, currentVersion.minor, currentVersion.patch, currentVersion.rev, updatedVersion.major, updatedVersion.minor, updatedVersion.patch, updatedVersion.rev); #else sprintf(buffer, "hoverrace-update-%ld.%ld.%ld.%ld-to-%ld.%ld.%ld.%ld.zip", currentVersion.major, currentVersion.minor, currentVersion.patch, currentVersion.rev, updatedVersion.major, updatedVersion.minor, updatedVersion.patch, updatedVersion.rev); #endif updateUrl = buffer; return true; } return false; } /*** * Default Version constructor. 0.0.0.0 default value. */ UpdateDownloader::Version::Version() { major = minor = patch = rev = 0; } /*** * Create a new Version object, using the input string which is delimited by * periods. i.e. "1.2.3.4" * * @param ver String version, delimited by periods */ UpdateDownloader::Version::Version(string ver) { sscanf(ver.c_str(), "%ld.%ld.%ld.%ld", &major, &minor, &patch, &rev); } /*** * Create a new Version object. */ UpdateDownloader::Version::Version(long major, long minor, long patch, long rev) { this->major = major; this->minor = minor; this->patch = patch; this->rev = rev; } string UpdateDownloader::Version::toString() { char buffer[500]; sprintf(buffer, "%ld.%ld.%ld.%ld", major, minor, patch, rev); string ret = buffer; return ret; } bool UpdateDownloader::Version::operator<(UpdateDownloader::Version &x) { if(major < x.major) return true; else if(major == x.major) { if(minor < x.minor) return true; else if(minor == x.minor) { if(patch < x.patch) return true; else if(patch == x.patch) { if(rev < x.rev) return true; } } } return false; } bool UpdateDownloader::Version::operator>(UpdateDownloader::Version &x) { if(major > x.major) return true; else if(major == x.major) { if(minor > x.minor) return true; else if(minor == x.minor) { if(patch > x.patch) return true; else if(patch == x.patch) { if(rev > x.rev) return true; } } } return false; } bool UpdateDownloader::Version::operator==(UpdateDownloader::Version &x) { return ((major == x.major) && (minor == x.minor) && (patch == x.patch) && (rev == x.rev)); }
[ "ryan@7d5085ce-8879-48fc-b0cc-67565f2357fd" ]
[ [ [ 1, 214 ] ] ]
acb002d63cdda4abee27244543fd8ec148da2274
c0bd82eb640d8594f2d2b76262566288676b8395
/src/shared/Database/dbcfile.h
bd7d746fff40ec80464ca1c3ed1fd4718c4a2f0c
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
2,727
h
#ifndef DBCFILE_H #define DBCFILE_H #include <cassert> #include <string> class DBCFile { public: DBCFile(); ~DBCFile(); // Open database. It must be openened before it can be used. bool open(const char*); // Database exceptions class Exception { public: Exception(const std::string &message): message(message) { } virtual ~Exception() { } const std::string &getMessage() {return message;} private: std::string message; }; class NotFound: public Exception { public: NotFound(): Exception("Key was not found") { } }; // Iteration over database class Iterator; class Record { public: float getFloat(size_t field) const { assert(field < file.fieldCount); return *reinterpret_cast<float*>(offset+field*4); } unsigned int getUInt(size_t field) const { assert(field < file.fieldCount); return *reinterpret_cast<unsigned int*>(offset+field*4); } int getInt(size_t field) const { assert(field < file.fieldCount); return *reinterpret_cast<int*>(offset+field*4); } const char *getString(size_t field) const { assert(field < file.fieldCount); size_t stringOffset = getUInt(field); assert(stringOffset < file.stringSize); return reinterpret_cast<char*>(file.stringTable + stringOffset); } private: Record(DBCFile &file, unsigned char *offset): file(file), offset(offset) {} DBCFile &file; unsigned char *offset; friend class DBCFile; friend class DBCFile::Iterator; }; /** Iterator that iterates over records */ class Iterator { public: Iterator(DBCFile &file, unsigned char *offset): record(file, offset) {} /// Advance (prefix only) Iterator & operator++() { record.offset += record.file.recordSize; return *this; } /// Return address of current instance Record const & operator*() const { return record; } const Record* operator->() const { return &record; } /// Comparison bool operator==(const Iterator &b) const { return record.offset == b.record.offset; } bool operator!=(const Iterator &b) const { return record.offset != b.record.offset; } private: Record record; }; // Get record by id Record getRecord(size_t id); /// Get begin iterator over records Iterator begin(); /// Get begin iterator over records Iterator end(); /// Trivial size_t getRecordCount() const { return recordCount;} size_t getFieldCount() const { return fieldCount; } private: std::string filename; unsigned int recordSize; unsigned int recordCount; unsigned int fieldCount; unsigned int stringSize; unsigned char *data; unsigned char *stringTable; }; #endif
[ [ [ 1, 117 ] ] ]
f8be908d82130588b3a61f1e6946c8f00c1c90c5
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/URLClient.cpp
590800735a47d90532d258a2c5274376aa2db5ae
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
15,706
cpp
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //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. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include <wininet.h> #include "UrlClient.h" #include "PartFile.h" #include "Packets.h" #include "ListenSocket.h" #include "HttpClientReqSocket.h" #include "Preferences.h" #include "OtherFunctions.h" #include "Statistics.h" #include "ClientCredits.h" //Xman #include "emule.h" #include "BandwidthControl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////////// // CUrlClient IMPLEMENT_DYNAMIC(CUrlClient, CUpDownClient) CUrlClient::CUrlClient() { m_iRedirected = 0; m_clientSoft = SO_URL; } void CUrlClient::SetRequestFile(CPartFile* pReqFile) { CUpDownClient::SetRequestFile(pReqFile); if (reqfile) { m_nPartCount = reqfile->GetPartCount(); m_abyPartStatus = new uint8[m_nPartCount]; memset(m_abyPartStatus, 1, m_nPartCount); m_bCompleteSource = true; } } bool CUrlClient::SetUrl(LPCTSTR pszUrl, uint32 nIP) { TCHAR szCanonUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwCanonUrlSize = ARRSIZE(szCanonUrl); if (!InternetCanonicalizeUrl(pszUrl, szCanonUrl, &dwCanonUrlSize, ICU_NO_ENCODE)) return false; TCHAR szUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwUrlSize = ARRSIZE(szUrl); if (!InternetCanonicalizeUrl(szCanonUrl, szUrl, &dwUrlSize, ICU_DECODE | ICU_NO_ENCODE | ICU_BROWSER_MODE)) return false; TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH]; TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH]; TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH]; TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH]; TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH]; TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH]; URL_COMPONENTS Url = {0}; Url.dwStructSize = sizeof(Url); Url.lpszScheme = szScheme; Url.dwSchemeLength = ARRSIZE(szScheme); Url.lpszHostName = szHostName; Url.dwHostNameLength = ARRSIZE(szHostName); Url.lpszUserName = szUserName; Url.dwUserNameLength = ARRSIZE(szUserName); Url.lpszPassword = szPassword; Url.dwPasswordLength = ARRSIZE(szPassword); Url.lpszUrlPath = szUrlPath; Url.dwUrlPathLength = ARRSIZE(szUrlPath); Url.lpszExtraInfo = szExtraInfo; Url.dwExtraInfoLength = ARRSIZE(szExtraInfo); if (!InternetCrackUrl(szUrl, 0, 0, &Url)) return false; if (Url.dwSchemeLength == 0 || Url.nScheme != INTERNET_SCHEME_HTTP) // we only support "http://" return false; if (Url.dwHostNameLength == 0) // we must know the hostname return false; if (Url.dwUserNameLength != 0) // no support for user/password return false; if (Url.dwPasswordLength != 0) // no support for user/password return false; if (Url.dwUrlPathLength == 0) // we must know the URL path on that host return false; m_strHostA = szHostName; TCHAR szEncodedUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwEncodedUrl = ARRSIZE(szEncodedUrl); if (!InternetCanonicalizeUrl(szUrl, szEncodedUrl, &dwEncodedUrl, ICU_ENCODE_PERCENT)) return false; m_strUrlPath = szEncodedUrl; m_nUrlStartPos = (uint64)-1; SetUserName(szUrl); //NOTE: be very careful with what is stored in the following IP/ID/Port members! if (nIP) m_nConnectIP = nIP; else m_nConnectIP = inet_addr(CT2A(szHostName)); ResetIP2Country(m_nConnectIP); //MORPH Added by SiRoB, IP to Country URLClient // if (m_nConnectIP == INADDR_NONE) // m_nConnectIP = 0; m_nUserIDHybrid = htonl(m_nConnectIP); ASSERT( m_nUserIDHybrid != 0 ); m_nUserPort = Url.nPort; return true; } CUrlClient::~CUrlClient() { } void CUrlClient::SendBlockRequests() { ASSERT(0); } bool CUrlClient::SendHttpBlockRequests() { m_dwLastBlockReceived = ::GetTickCount(); if (reqfile == NULL) throw CString(_T("Failed to send block requests - No 'reqfile' attached")); CreateBlockRequests(PARTSIZE / EMBLOCKSIZE); if (m_PendingBlocks_list.IsEmpty()){ // - Maella -Download Stop Reason- /* SetDownloadState(DS_NONEEDEDPARTS); SwapToAnotherFile(_T("A4AF for NNP file. UrlClient::SendHttpBlockRequests()"), true, false, false, NULL, true, true); */ SetDownloadState(DS_NONEEDEDPARTS, _T("No needed parts"), CUpDownClient::DSR_NONEEDEDPARTS); //Xman end return false; } POSITION pos = m_PendingBlocks_list.GetHeadPosition(); Pending_Block_Struct* pending = m_PendingBlocks_list.GetNext(pos); m_uReqStart = pending->block->StartOffset; m_uReqEnd = pending->block->EndOffset; bool bMergeBlocks = true; while (pos) { POSITION posLast = pos; pending = m_PendingBlocks_list.GetNext(pos); if (bMergeBlocks && pending->block->StartOffset == m_uReqEnd + 1) m_uReqEnd = pending->block->EndOffset; else { bMergeBlocks = false; reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset); delete pending->block; delete pending; m_PendingBlocks_list.RemoveAt(posLast); } } m_nUrlStartPos = m_uReqStart; CStringA strHttpRequest; strHttpRequest.AppendFormat("GET %s HTTP/1.0\r\n", m_strUrlPath); strHttpRequest.AppendFormat("Accept: */*\r\n"); strHttpRequest.AppendFormat("Range: bytes=%I64u-%I64u\r\n", m_uReqStart, m_uReqEnd); strHttpRequest.AppendFormat("Connection: Keep-Alive\r\n"); strHttpRequest.AppendFormat("Host: %s\r\n", m_strHostA); strHttpRequest.AppendFormat("\r\n"); if (thePrefs.GetDebugClientTCPLevel() > 0) Debug(_T("Sending HTTP request:\n%hs"), strHttpRequest); CRawPacket* pHttpPacket = new CRawPacket(strHttpRequest); theStats.AddUpDataOverheadFileRequest(pHttpPacket->size); socket->SendPacket(pHttpPacket); STATIC_DOWNCAST(CHttpClientDownSocket, socket)->SetHttpState(HttpStateRecvExpected); return true; } bool CUrlClient::TryToConnect(bool bIgnoreMaxCon, bool bNoCallbacks, CRuntimeClass* /*pClassSocket*/) { return CUpDownClient::TryToConnect(bIgnoreMaxCon, bNoCallbacks, RUNTIME_CLASS(CHttpClientDownSocket)); } void CUrlClient::Connect() { if (GetConnectIP() != 0 && GetConnectIP() != INADDR_NONE){ CUpDownClient::Connect(); return; } //Try to always tell the socket to WaitForOnConnect before you call Connect. socket->WaitForOnConnect(); socket->Connect(m_strHostA, m_nUserPort); return; } void CUrlClient::OnSocketConnected(int nErrorCode) { if (nErrorCode == 0) SendHttpBlockRequests(); } void CUrlClient::SendHelloPacket() { //SendHttpBlockRequests(); return; } void CUrlClient::SendFileRequest() { // This may be called in some rare situations depending on socket states. ; // just ignore it } bool CUrlClient::Disconnected(LPCTSTR pszReason, bool bFromSocket) { //Xman /* CHttpClientDownSocket* s = STATIC_DOWNCAST(CHttpClientDownSocket, socket); TRACE(_T("%hs: HttpState=%u, Reason=%s\n"), __FUNCTION__, s==NULL ? -1 : s->GetHttpState(), pszReason); // TODO: This is a mess.. if (s && (s->GetHttpState() == HttpStateRecvExpected || s->GetHttpState() == HttpStateRecvBody)) m_fileReaskTimes.RemoveKey(reqfile); // ZZ:DownloadManager (one resk timestamp for each file) */ //Xman end return CUpDownClient::Disconnected(CString(_T("CUrlClient::Disconnected")) + pszReason, bFromSocket); } bool CUrlClient::ProcessHttpDownResponse(const CStringAArray& astrHeaders) { if (reqfile == NULL) throw CString(_T("Failed to process received HTTP data block - No 'reqfile' attached")); if (astrHeaders.GetCount() == 0) throw CString(_T("Unexpected HTTP response - No headers available")); const CStringA& rstrHdr = astrHeaders.GetAt(0); UINT uHttpMajVer, uHttpMinVer, uHttpStatusCode; if (sscanf(rstrHdr, "HTTP/%u.%u %u", &uHttpMajVer, &uHttpMinVer, &uHttpStatusCode) != 3){ CString strError; strError.Format(_T("Unexpected HTTP response: \"%hs\""), rstrHdr); throw strError; } if (uHttpMajVer != 1 || (uHttpMinVer != 0 && uHttpMinVer != 1)){ CString strError; strError.Format(_T("Unexpected HTTP version: \"%hs\""), rstrHdr); throw strError; } bool bExpectData = uHttpStatusCode == HTTP_STATUS_OK || uHttpStatusCode == HTTP_STATUS_PARTIAL_CONTENT; bool bRedirection = uHttpStatusCode == HTTP_STATUS_MOVED || uHttpStatusCode == HTTP_STATUS_REDIRECT; if (!bExpectData && !bRedirection){ CString strError; strError.Format(_T("Unexpected HTTP status code \"%u\""), uHttpStatusCode); throw strError; } bool bNewLocation = false; bool bValidContentRange = false; for (int i = 1; i < astrHeaders.GetCount(); i++) { const CStringA& rstrHdr = astrHeaders.GetAt(i); if (bExpectData && _strnicmp(rstrHdr, "Content-Length:", 15) == 0) { uint64 uContentLength = _atoi64((LPCSTR)rstrHdr + 15); if (uContentLength != m_uReqEnd - m_uReqStart + 1){ if (uContentLength != reqfile->GetFileSize()){ // tolerate this case only CString strError; strError.Format(_T("Unexpected HTTP header field \"%hs\""), rstrHdr); throw strError; } TRACE("+++ Unexpected HTTP header field \"%s\"\n", rstrHdr); } } else if (bExpectData && _strnicmp(rstrHdr, "Content-Range:", 14) == 0) { uint64 ui64Start = 0, ui64End = 0, ui64Len = 0; if (sscanf((LPCSTR)rstrHdr + 14," bytes %I64u - %I64u / %I64u", &ui64Start, &ui64End, &ui64Len) != 3){ CString strError; strError.Format(_T("Unexpected HTTP header field \"%hs\""), rstrHdr); throw strError; } if (ui64Start != m_uReqStart || ui64End != m_uReqEnd || ui64Len != reqfile->GetFileSize()){ CString strError; strError.Format(_T("Unexpected HTTP header field \"%hs\""), rstrHdr); throw strError; } bValidContentRange = true; } else if (_strnicmp(rstrHdr, "Server:", 7) == 0) { if (m_strClientSoftware.IsEmpty()) m_strClientSoftware = rstrHdr.Mid(7).Trim(); } else if (bRedirection && _strnicmp(rstrHdr, "Location:", 9) == 0) { CString strLocation(rstrHdr.Mid(9).Trim()); if (!SetUrl(strLocation)){ CString strError; strError.Format(_T("Failed to process HTTP redirection URL \"%s\""), strLocation); throw strError; } bNewLocation = true; } } if (bNewLocation) { m_iRedirected++; if (m_iRedirected >= 3) throw CString(_T("Max. HTTP redirection count exceeded")); // the tricky part socket->Safe_Delete(); // mark our parent object for getting deleted! if (!TryToConnect(true)) // replace our parent object with a new one throw CString(_T("Failed to connect to redirected URL")); return false; // tell our old parent object (which was marked as to get deleted // and which is no longer attached to us) to disconnect. } if (!bValidContentRange){ if (thePrefs.GetDebugClientTCPLevel() <= 0) DebugHttpHeaders(astrHeaders); CString strError; strError.Format(_T("Unexpected HTTP response - No valid HTTP content range found")); throw strError; } SetDownloadState(DS_DOWNLOADING); return true; } bool CUpDownClient::ProcessHttpDownResponse(const CStringAArray& ) { ASSERT(0); return false; } bool CUpDownClient::ProcessHttpDownResponseBody(const BYTE* pucData, UINT uSize) { ProcessHttpBlockPacket(pucData, uSize); return true; } void CUpDownClient::ProcessHttpBlockPacket(const BYTE* pucData, UINT uSize) { if (reqfile == NULL) throw CString(_T("Failed to process HTTP data block - No 'reqfile' attached")); if (reqfile->IsStopped() || (reqfile->GetStatus() != PS_READY && reqfile->GetStatus() != PS_EMPTY)) throw CString(_T("Failed to process HTTP data block - File not ready for receiving data")); if (m_nUrlStartPos == (uint64)-1) throw CString(_T("Failed to process HTTP data block - Unexpected file data")); uint64 nStartPos = m_nUrlStartPos; uint64 nEndPos = m_nUrlStartPos + uSize; m_nUrlStartPos += uSize; // if (thePrefs.GetDebugClientTCPLevel() > 0) // Debug(" Start=%I64u End=%I64u Size=%u %s\n", nStartPos, nEndPos, size, DbgGetFileInfo(reqfile->GetFileHash())); if (!(GetDownloadState() == DS_DOWNLOADING || GetDownloadState() == DS_NONEEDEDPARTS)) throw CString(_T("Failed to process HTTP data block - Invalid download state")); m_dwLastBlockReceived = ::GetTickCount(); if (nEndPos == nStartPos || uSize != nEndPos - nStartPos) throw CString(_T("Failed to process HTTP data block - Invalid block start/end offsets")); thePrefs.Add2SessionTransferData(GetClientSoft(), (GetClientSoft()==SO_URL) ? (UINT)-2 : (UINT)-1, false, false, uSize); //Xman /* m_nDownDataRateMS += uSize; */ //Xman end if (credits) credits->AddDownloaded(uSize, GetIP()); nEndPos--; //Xman //remark: if the socket IsRawDataMode (means a httpsocket) we don't count the data at emsocket OnReceive, we have to do it at this point //remark: this isn't fully accurate because we don't remove the headers // - Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter- AddDownloadRate(uSize); theApp.pBandWidthControl->AddeMuleIn(uSize); //Xman end for (POSITION pos = m_PendingBlocks_list.GetHeadPosition(); pos != NULL; ) { POSITION posLast = pos; Pending_Block_Struct *cur_block = m_PendingBlocks_list.GetNext(pos); if (cur_block->block->StartOffset <= nStartPos && nStartPos <= cur_block->block->EndOffset) { if (thePrefs.GetDebugClientTCPLevel() > 0){ // NOTE: 'Left' is only accurate in case we have one(!) request block! void* p = m_pPCDownSocket ? (void*)m_pPCDownSocket : (void*)socket; Debug(_T("%08x Start=%I64u End=%I64u Size=%u Left=%I64u %s\n"), p, nStartPos, nEndPos, uSize, cur_block->block->EndOffset - (nStartPos + uSize) + 1, DbgGetFileInfo(reqfile->GetFileHash())); } m_nLastBlockOffset = nStartPos; uint32 lenWritten = reqfile->WriteToBuffer(uSize, pucData, nStartPos, nEndPos, cur_block->block, this); if (lenWritten > 0) { m_nTransferredDown += uSize; m_nCurSessionPayloadDown += lenWritten; SetTransferredDownMini(); if (nEndPos >= cur_block->block->EndOffset) { reqfile->RemoveBlockFromList(cur_block->block->StartOffset, cur_block->block->EndOffset); delete cur_block->block; delete cur_block; m_PendingBlocks_list.RemoveAt(posLast); if (m_PendingBlocks_list.IsEmpty()) { if (thePrefs.GetDebugClientTCPLevel() > 0) DebugSend("More block requests", this); m_nUrlStartPos = (uint64)-1; SendHttpBlockRequests(); } } // else // TRACE("%hs - %d bytes missing\n", __FUNCTION__, cur_block->block->EndOffset - nEndPos); } return; } } TRACE("%s - Dropping packet\n", __FUNCTION__); } void CUrlClient::SendCancelTransfer(Packet* /*packet*/) { if (socket) { STATIC_DOWNCAST(CHttpClientDownSocket, socket)->SetHttpState(HttpStateUnknown); socket->Safe_Delete(); } }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 463 ] ] ]
ad097baa5b06ca4ad57de59aaea0fab5733ab074
31a5e7570148149f0f7d8626274c22e15454a71f
/Simcraft/Simcraft/sc_gear_stats.cpp
95cf96e0a0647cdf2625e54a15c718d8590e3191
[]
no_license
imclab/SimcraftGearOptimizer
b54575e9fc330c97070168ade5bbd46a2de0627a
b5c1f82b2bf7579389d23b769e520a6b0968fc98
refs/heads/master
2021-01-22T13:37:15.010740
2010-05-04T00:46:44
2010-05-04T00:46:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,974
cpp
// ========================================================================== // Dedmonwakeen's Raid DPS/TPS Simulator. // Send questions to [email protected] // ========================================================================== #include "simulationcraft.h" // ========================================================================== // Gear Stats // ========================================================================== // gear_stats_t::add_stat =================================================== void gear_stats_t::add_stat( int stat, double value ) { switch ( stat ) { case STAT_NONE: break; case STAT_STRENGTH: attribute[ ATTR_STRENGTH ] += value; break; case STAT_AGILITY: attribute[ ATTR_AGILITY ] += value; break; case STAT_STAMINA: attribute[ ATTR_STAMINA ] += value; break; case STAT_INTELLECT: attribute[ ATTR_INTELLECT ] += value; break; case STAT_SPIRIT: attribute[ ATTR_SPIRIT ] += value; break; case STAT_HEALTH: resource[ RESOURCE_HEALTH ] += value; break; case STAT_MANA: resource[ RESOURCE_MANA ] += value; break; case STAT_RAGE: resource[ RESOURCE_RAGE ] += value; break; case STAT_ENERGY: resource[ RESOURCE_ENERGY ] += value; break; case STAT_FOCUS: resource[ RESOURCE_FOCUS ] += value; break; case STAT_RUNIC: resource[ RESOURCE_RUNIC ] += value; break; case STAT_SPELL_POWER: spell_power += value; break; case STAT_SPELL_PENETRATION: spell_penetration += value; break; case STAT_MP5: mp5 += value; break; case STAT_ATTACK_POWER: attack_power += value; break; case STAT_EXPERTISE_RATING: expertise_rating += value; break; case STAT_ARMOR_PENETRATION_RATING: armor_penetration_rating += value; break; case STAT_HIT_RATING: hit_rating += value; break; case STAT_CRIT_RATING: crit_rating += value; break; case STAT_HASTE_RATING: haste_rating += value; break; case STAT_WEAPON_DPS: weapon_dps += value; break; case STAT_WEAPON_SPEED: weapon_speed += value; break; case STAT_WEAPON_OFFHAND_DPS: weapon_offhand_dps += value; break; case STAT_WEAPON_OFFHAND_SPEED: weapon_offhand_speed += value; break; case STAT_ARMOR: armor += value; break; case STAT_BONUS_ARMOR: bonus_armor += value; break; case STAT_DEFENSE_RATING: defense_rating += value; break; case STAT_DODGE_RATING: dodge_rating += value; break; case STAT_PARRY_RATING: parry_rating += value; break; case STAT_BLOCK_RATING: block_rating += value; break; case STAT_BLOCK_VALUE: block_value += value; break; case STAT_MAX: for ( int i=0; i < ATTRIBUTE_MAX; i++ ) { attribute[ i ] += value; } break; default: assert( 0 ); } } // gear_stats_t::set_stat =================================================== void gear_stats_t::set_stat( int stat, double value ) { switch ( stat ) { case STAT_NONE: break; case STAT_STRENGTH: attribute[ ATTR_STRENGTH ] = value; break; case STAT_AGILITY: attribute[ ATTR_AGILITY ] = value; break; case STAT_STAMINA: attribute[ ATTR_STAMINA ] = value; break; case STAT_INTELLECT: attribute[ ATTR_INTELLECT ] = value; break; case STAT_SPIRIT: attribute[ ATTR_SPIRIT ] = value; break; case STAT_HEALTH: resource[ RESOURCE_HEALTH ] = value; break; case STAT_MANA: resource[ RESOURCE_MANA ] = value; break; case STAT_RAGE: resource[ RESOURCE_RAGE ] = value; break; case STAT_ENERGY: resource[ RESOURCE_ENERGY ] = value; break; case STAT_FOCUS: resource[ RESOURCE_FOCUS ] = value; break; case STAT_RUNIC: resource[ RESOURCE_RUNIC ] = value; break; case STAT_SPELL_POWER: spell_power = value; break; case STAT_SPELL_PENETRATION: spell_penetration = value; break; case STAT_MP5: mp5 = value; break; case STAT_ATTACK_POWER: attack_power = value; break; case STAT_EXPERTISE_RATING: expertise_rating = value; break; case STAT_ARMOR_PENETRATION_RATING: armor_penetration_rating = value; break; case STAT_HIT_RATING: hit_rating = value; break; case STAT_CRIT_RATING: crit_rating = value; break; case STAT_HASTE_RATING: haste_rating = value; break; case STAT_WEAPON_DPS: weapon_dps = value; break; case STAT_WEAPON_SPEED: weapon_speed = value; break; case STAT_WEAPON_OFFHAND_DPS: weapon_offhand_dps = value; break; case STAT_WEAPON_OFFHAND_SPEED: weapon_offhand_speed = value; break; case STAT_ARMOR: armor = value; break; case STAT_BONUS_ARMOR: bonus_armor = value; break; case STAT_DEFENSE_RATING: defense_rating = value; break; case STAT_DODGE_RATING: dodge_rating = value; break; case STAT_PARRY_RATING: parry_rating = value; break; case STAT_BLOCK_RATING: block_rating = value; break; case STAT_BLOCK_VALUE: block_value = value; break; case STAT_MAX: for ( int i=0; i < ATTRIBUTE_MAX; i++ ) { attribute[ i ] = value; } break; default: assert( 0 ); } } // gear_stats_t::get_stat =================================================== double gear_stats_t::get_stat( int stat ) SC_CONST { switch ( stat ) { case STAT_NONE: return 0; case STAT_STRENGTH: return attribute[ ATTR_STRENGTH ]; case STAT_AGILITY: return attribute[ ATTR_AGILITY ]; case STAT_STAMINA: return attribute[ ATTR_STAMINA ]; case STAT_INTELLECT: return attribute[ ATTR_INTELLECT ]; case STAT_SPIRIT: return attribute[ ATTR_SPIRIT ]; case STAT_HEALTH: return resource[ RESOURCE_HEALTH ]; case STAT_MANA: return resource[ RESOURCE_MANA ]; case STAT_RAGE: return resource[ RESOURCE_RAGE ]; case STAT_ENERGY: return resource[ RESOURCE_ENERGY ]; case STAT_FOCUS: return resource[ RESOURCE_FOCUS ]; case STAT_RUNIC: return resource[ RESOURCE_RUNIC ]; case STAT_SPELL_POWER: return spell_power; case STAT_SPELL_PENETRATION: return spell_penetration; case STAT_MP5: return mp5; case STAT_ATTACK_POWER: return attack_power; case STAT_EXPERTISE_RATING: return expertise_rating; case STAT_ARMOR_PENETRATION_RATING: return armor_penetration_rating; case STAT_HIT_RATING: return hit_rating; case STAT_CRIT_RATING: return crit_rating; case STAT_HASTE_RATING: return haste_rating; case STAT_WEAPON_DPS: return weapon_dps; case STAT_WEAPON_SPEED: return weapon_speed; case STAT_WEAPON_OFFHAND_DPS: return weapon_offhand_dps; case STAT_WEAPON_OFFHAND_SPEED: return weapon_offhand_speed; case STAT_ARMOR: return armor; case STAT_BONUS_ARMOR: return bonus_armor; case STAT_DEFENSE_RATING: return defense_rating; case STAT_DODGE_RATING: return dodge_rating; case STAT_PARRY_RATING: return parry_rating; case STAT_BLOCK_RATING: return block_rating; case STAT_BLOCK_VALUE: return block_value; default: assert( 0 ); } return 0; } // gear_stats_t::print ====================================================== void gear_stats_t::print( FILE* file ) { for ( int i=0; i < STAT_MAX; i++ ) { double value = get_stat( i ); if ( value != 0 ) { util_t::fprintf( file, " %s=%.*f", util_t::stat_type_abbrev( i ), ( ( ( value - ( int ) value ) > 0 ) ? 3 : 0 ), value ); } } util_t::fprintf( file, "\n" ); } // gear_stats_t::stat_mod =================================================== double gear_stats_t::stat_mod( int stat ) { switch ( stat ) { case STAT_MP5: return 2.50; case STAT_ATTACK_POWER: return 0.50; case STAT_SPELL_POWER: return 0.86; case STAT_SPELL_PENETRATION: return 0.80; } return 1.0; }
[ [ [ 1, 205 ] ] ]
96a49405a3de72f9242502170acfe9b5c43defc8
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranMath/ArnPlane.cpp
24400b0a4d8f57f0dd41652592e82075ad2f146f
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
#include "AranMathPCH.h" #include "ArnPlane.h" #include "ArnMath.h" #include "ArnConsts.h" ArnPlane::ArnPlane() : m_normal(ArnConsts::ARNVEC3_Z) , m_v0(ArnConsts::ARNVEC3_ZERO) { } ArnPlane::ArnPlane(const ArnVec3& normal, const ArnVec3& v0) : m_normal(normal) , m_v0(v0) { assert(ArnVec3IsNormalized(normal)); } ArnPlane::ArnPlane(const ArnVec3& v0, const ArnVec3& v1, const ArnVec3& v2) : m_v0(v0) { ArnVec3 a1 = v1 - v0; ArnVec3 a2 = v2 - v0; ArnVec3 normal = ArnVec3GetCrossProduct(a1, a2); m_normal = normal / ArnVec3GetLength(normal); } const ArnVec3& ArnPlane::getNormal() const { assert(ArnVec3IsNormalized(m_normal)); return m_normal; }
[ [ [ 1, 33 ] ] ]
5e236ed53e4fc7d01d53a9d6905a1bb6ee774323
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/src/Controls/VerticalScrollBar.cpp
f3683c157b1f3960ec8997ac9c8ff5024d7cc6c8
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
3,465
cpp
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #include "stdafx.h" #include "Gwen/Controls/ScrollBar.h" #include "Gwen/Controls/VerticalScrollBar.h" using namespace Gwen; using namespace Gwen::Controls; GWEN_CONTROL_CONSTRUCTOR( VerticalScrollBar ) { m_Bar->SetVertical(); m_ScrollButton[SCROLL_BUTTON_UP]->SetDirectionUp(); m_ScrollButton[SCROLL_BUTTON_UP]->onPress.Add( this, &VerticalScrollBar::NudgeUp ); m_ScrollButton[SCROLL_BUTTON_DOWN]->SetDirectionDown(); m_ScrollButton[SCROLL_BUTTON_DOWN]->onPress.Add( this, &VerticalScrollBar::NudgeDown ); m_Bar->onDragged.Add( this, &VerticalScrollBar::OnBarMoved ); } void VerticalScrollBar::Layout( Skin::Base* skin ) { BaseClass::Layout( skin ); m_ScrollButton[SCROLL_BUTTON_UP]->Dock(Pos::Top); m_ScrollButton[SCROLL_BUTTON_UP]->SetHeight( Width() ); m_ScrollButton[SCROLL_BUTTON_DOWN]->Dock(Pos::Bottom); m_ScrollButton[SCROLL_BUTTON_DOWN]->SetHeight( Width() ); m_Bar->SetWidth( GetButtonSize() ); //Add padding m_Bar->SetPadding( Padding(0, GetButtonSize(), 0, GetButtonSize() ) ); //Calculate bar sizes float barHeight = (m_fViewableContentSize / m_fContentSize) * (Height() - (GetButtonSize() * 2)); if ( barHeight < GetButtonSize() * 0.5 ) barHeight = GetButtonSize() * 0.5; m_Bar->SetHeight(barHeight); m_Bar->SetHidden( Height() - (GetButtonSize() * 2) <= barHeight ); if ( Hidden() ) SetScrolledAmount(0, true); //Based on our last scroll amount, produce a position for the bar if ( !m_Bar->IsDepressed() ) { SetScrolledAmount( GetScrolledAmount(), true ); } } void VerticalScrollBar::ScrollToTop() { SetScrolledAmount(0, true); } void VerticalScrollBar::ScrollToBottom() { SetScrolledAmount(1, true); } void VerticalScrollBar::NudgeUp( Base* control ) { if ( !IsDisabled() ) SetScrolledAmount(GetScrolledAmount() - GetNudgeAmount(), true); } void VerticalScrollBar::NudgeDown( Base* control ) { if ( !IsDisabled() ) SetScrolledAmount(GetScrolledAmount() + GetNudgeAmount(), true); } float VerticalScrollBar::GetNudgeAmount() { if ( m_bDepressed ) return m_fViewableContentSize / m_fContentSize; else return BaseClass::GetNudgeAmount(); } void VerticalScrollBar::OnMouseClickLeft( int x, int y, bool bDown ) { if ( bDown ) { m_bDepressed = true; Gwen::MouseFocus = this; } else { Point clickPos = CanvasPosToLocal( Point( x, y ) ); if ( clickPos.y < m_Bar->Y() ) NudgeUp(this); else if ( clickPos.y > m_Bar->Y() + m_Bar->Height() ) NudgeDown(this); m_bDepressed = false; Gwen::MouseFocus = NULL; } } float VerticalScrollBar::CalculateScrolledAmount() { return (float)(m_Bar->Y() - GetButtonSize()) / (float)(Height() - m_Bar->Height() - (GetButtonSize() * 2 )); } void VerticalScrollBar::SetScrolledAmount(float amount, bool forceUpdate) { if ( amount > 1 ) amount = 1; if ( amount < 0 ) amount = 0; BaseClass::SetScrolledAmount( amount, forceUpdate ); if ( forceUpdate ) { int newY = GetButtonSize() + (amount * ((Height() - m_Bar->Height()) - (GetButtonSize()*2))); m_Bar->MoveTo( m_Bar->X(), newY); } } void VerticalScrollBar::OnBarMoved( Controls::Base* control ) { if ( m_Bar->IsDepressed() ) { SetScrolledAmount( CalculateScrolledAmount(), false ); BaseClass::OnBarMoved(control); } else InvalidateParent(); }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 138 ] ] ]
024d2a2d816c44329f0767eaeb90676e4bf2bf74
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/test/nsrpcTest/P2pRelayTestFixture.h
c7aac627ed9ab0631270ee6a47ae68ed6365ba5c
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,742
h
#ifndef NSRPC_P2PRELAYTESTFIXTURE_H #define NSRPC_P2PRELAYTESTFIXTURE_H #ifdef _MSC_VER # pragma once #endif #include "P2pSessionTestFixture.h" #include <nsrpc/p2p/server/SimpleRelayService.h> #include <nsrpc/ReactorTask.h> #include <nsrpc/utility/AceUtil.h> #include <nsrpc/detail/PacketCoderFactory.h> using namespace nsrpc; /** * @class P2pRelayTestFixture * * P2P P2pSession Test */ class P2pRelayTestFixture : public P2pSessionTestFixture { protected: enum { relayServerPort = 1004 }; protected: virtual void SetUp() { P2pSessionTestFixture::SetUp(); reactorTask_ = new ReactorTask(true); relayService_ = new detail::SimpleRelayService( reactorTask_->getReactor(), PacketCoderFactory().createForP2p()); EXPECT_TRUE(relayService_->open(relayServerPort)) << "open relay server"; reactorTask_->start(1); hostSession_->setRelayServer( PeerAddress(ACE_LOCALHOST, relayServerPort)); for (int i = 0; i < 2; ++i) { hostSession_->tick(); } } virtual void TearDown() { P2pSessionTestFixture::TearDown(); relayService_->close(); reactorTask_->stop(); reactorTask_->wait(); delete relayService_; delete reactorTask_; } protected: virtual PeerAddresses getHostAddresses() const { PeerAddresses addresses; addresses.push_back( PeerAddress(ACE_LOCALHOST, ACE_DEFAULT_SERVER_PORT)); return addresses; } protected: ReactorTask* reactorTask_; detail::SimpleRelayService* relayService_; }; #endif // !defined(NSRPC_P2PRELAYTESTFIXTURE_H)
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 70 ] ] ]
ee5e69d4a392bcdc3beadb37242f571fac06cc7c
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/HTMLLite/PPDrawManager.cpp
809f33d9168f067161f145dbd4b293f9abd64ebb
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
WINDOWS-1251
C++
false
false
46,757
cpp
#include "stdafx.h" #include "PPDrawManager.h" /* #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif */ /* DIBs use RGBQUAD format: 0xbb 0xgg 0xrr 0x00 */ #ifndef CLR_TO_RGBQUAD #define CLR_TO_RGBQUAD(clr) (RGB(GetBValue(clr), GetGValue(clr), GetRValue(clr))) #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CPPDrawManager::CPPDrawManager() { } CPPDrawManager::~CPPDrawManager() { } void CPPDrawManager::GetSizeOfIcon(HICON hIcon, LPSIZE pSize) const { pSize->cx = 0; pSize->cy = 0; if (hIcon != NULL) { ICONINFO ii; // Gets icon dimension ::ZeroMemory(&ii, sizeof(ICONINFO)); if (::GetIconInfo(hIcon, &ii)) { pSize->cx = (DWORD)(ii.xHotspot * 2); pSize->cy = (DWORD)(ii.yHotspot * 2); //release icon mask bitmaps if(ii.hbmMask) ::DeleteObject(ii.hbmMask); if(ii.hbmColor) ::DeleteObject(ii.hbmColor); } //if } //if } //End GetSizeOfIcon void CPPDrawManager::GetSizeOfBitmap(HBITMAP hBitmap, LPSIZE pSize) const { pSize->cx = 0; pSize->cy = 0; if (hBitmap != NULL) { BITMAP csBitmapSize; // Get bitmap size int nRetValue = ::GetObject(hBitmap, sizeof(csBitmapSize), &csBitmapSize); if (nRetValue) { pSize->cx = (DWORD)csBitmapSize.bmWidth; pSize->cy = (DWORD)csBitmapSize.bmHeight; } //if } //if } //End GetSizeOfBitmap void CPPDrawManager::AlphaBitBlt(HDC hDestDC, int nDestX, int nDestY, DWORD dwWidth, DWORD dwHeight, HDC hSrcDC, int nSrcX, int nSrcY, int percent /* = 100 */) { _ASSERT ((NULL != hDestDC) || (NULL != hSrcDC)); if (percent >= 100) { ::BitBlt(hDestDC, nDestX, nDestY, dwWidth, dwHeight, hSrcDC, nSrcX, nSrcY, SRCCOPY); return; } //if HDC hTempDC = ::CreateCompatibleDC(hDestDC); if (NULL == hTempDC) return; //Creates Source DIB LPBITMAPINFO lpbiSrc; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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)) { HBITMAP hOldTempBmp = (HBITMAP)::SelectObject (hTempDC, hSrcDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hSrcDC, nSrcX, nSrcY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); //Creates Destination DIB LPBITMAPINFO lpbiDest; // Fill in the BITMAPINFOHEADER lpbiDest = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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 ( hDestDC, lpbiDest, DIB_RGB_COLORS, (void **)&pDestBits, NULL, NULL); if ((NULL != hDestDib) && (NULL != pDestBits)) { ::SelectObject (hTempDC, hDestDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hDestDC, nDestX, nDestY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); double src_darken = (double)percent / 100.0; double dest_darken = 1.0 - src_darken; for (DWORD pixel = 0; pixel < dwWidth * dwHeight; pixel++, pSrcBits++, pDestBits++) { *pDestBits = PixelAlpha(*pSrcBits, src_darken, *pDestBits, dest_darken); } //for ::SelectObject (hTempDC, hDestDib); ::BitBlt (hDestDC, nDestX, nDestY, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); delete lpbiDest; ::DeleteObject(hDestDib); } //if delete lpbiSrc; ::DeleteObject(hSrcDib); } //if ::DeleteDC(hTempDC); } //End AlphaBitBlt void CPPDrawManager::AlphaChannelBitBlt(HDC hDestDC, int nDestX, int nDestY, DWORD dwWidth, DWORD dwHeight, HDC hSrcDC, int nSrcX, int nSrcY) { _ASSERT ((NULL != hDestDC) || (NULL != hSrcDC)); HDC hTempDC = ::CreateCompatibleDC(hDestDC); if (NULL == hTempDC) return; //Creates Source DIB LPBITMAPINFO lpbiSrc; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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)) { HBITMAP hOldTempBmp = (HBITMAP)::SelectObject (hTempDC, hSrcDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hSrcDC, nSrcX, nSrcY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); //Creates Destination DIB LPBITMAPINFO lpbiDest; // Fill in the BITMAPINFOHEADER lpbiDest = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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 ( hDestDC, lpbiDest, DIB_RGB_COLORS, (void **)&pDestBits, NULL, NULL); if ((NULL != hDestDib) && (NULL != pDestBits)) { ::SelectObject (hTempDC, hDestDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hDestDC, nDestX, nDestY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); double src_darken; BYTE nAlpha; for (DWORD pixel = 0; pixel < dwWidth * dwHeight; pixel++, pSrcBits++, pDestBits++) { nAlpha = LOBYTE(*pSrcBits >> 24); src_darken = (double)nAlpha / 255.0; *pDestBits = PixelAlpha(*pSrcBits, src_darken, *pDestBits, 1.0 - src_darken); } //for ::SelectObject (hTempDC, hDestDib); ::BitBlt (hDestDC, nDestX, nDestY, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); delete lpbiDest; ::DeleteObject(hDestDib); } //if delete lpbiSrc; ::DeleteObject(hSrcDib); } //if ::DeleteDC(hTempDC); } //End of AlphaChannelBitBlt HBITMAP CPPDrawManager::CreateImageEffect(HBITMAP hBitmap, DWORD dwWidth, DWORD dwHeight, DWORD dwEffect, BOOL bUseMask /* = TRUE */, COLORREF clrMask /* = RGB(255, 0, 255) */, COLORREF clrMono /* = RGB(255, 255, 255) */) { HBITMAP hOldSrcBmp = NULL; HBITMAP hOldResBmp = NULL; HDC hMainDC = NULL; HDC hSrcDC = NULL; HDC hResDC = NULL; hMainDC = ::GetDC(NULL); hSrcDC = ::CreateCompatibleDC(hMainDC); hResDC = ::CreateCompatibleDC(hMainDC); hOldSrcBmp = (HBITMAP)::SelectObject(hSrcDC, hBitmap); LPBITMAPINFO lpbi; // Fill in the BITMAPINFOHEADER lpbi = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; lpbi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); lpbi->bmiHeader.biWidth = dwWidth; lpbi->bmiHeader.biHeight = dwHeight; lpbi->bmiHeader.biPlanes = 1; lpbi->bmiHeader.biBitCount = 32; lpbi->bmiHeader.biCompression = BI_RGB; lpbi->bmiHeader.biSizeImage = dwWidth * dwHeight; lpbi->bmiHeader.biXPelsPerMeter = 0; lpbi->bmiHeader.biYPelsPerMeter = 0; lpbi->bmiHeader.biClrUsed = 0; lpbi->bmiHeader.biClrImportant = 0; COLORREF* pBits = NULL; HBITMAP hDibBmp = CreateDIBSection ( hSrcDC, lpbi, DIB_RGB_COLORS, (void **)&pBits, NULL, NULL); if (hDibBmp == NULL || pBits == NULL) { delete lpbi; _ASSERT (FALSE); return NULL; } //if hOldResBmp = (HBITMAP)::SelectObject (hResDC, hDibBmp); ::BitBlt (hResDC, 0, 0, dwWidth, dwHeight, hSrcDC, 0, 0, SRCCOPY); clrMask = CLR_TO_RGBQUAD(clrMask); clrMono = CLR_TO_RGBQUAD(clrMono); DWORD dwAlpha; for (DWORD pixel = 0; pixel < dwWidth * dwHeight; pixel++, *pBits++) { COLORREF color = (COLORREF)*pBits; //ENG: Extract an original alpha value dwAlpha = color & 0xFF000000; if (dwAlpha != 0) m_bIsAlpha = TRUE; if (bUseMask && (color == clrMask)) { //This is transparent area color = RGB(0, 0, 0); } else { //ENG: Color conversion if (dwEffect & IMAGE_EFFECT_GRAYEN) color = GrayMirrorColor(color); if (dwEffect & IMAGE_EFFECT_DARKEN) color = DarkenColor(color, 0.75); if (dwEffect & IMAGE_EFFECT_LIGHTEN) color = LightenColor(color, 0.25); if (dwEffect & IMAGE_EFFECT_MONOCHROME) color = clrMono; } //if if (dwEffect & IMAGE_EFFECT_INVERT) color = InvertColor(color); //ENG: Merges a color with an original alpha value *pBits = (color | dwAlpha); } //for ::SelectObject(hSrcDC, hOldSrcBmp); ::SelectObject(hResDC, hOldResBmp); ::DeleteDC(hSrcDC); ::DeleteDC(hResDC); ::ReleaseDC(NULL, hMainDC); delete lpbi; return hDibBmp; } //End CreateImageEffect //---------------------------------------------------------- // CPPDrawManager::GrayMirrorColor() // Graying color in RGBQUAD format //---------------------------------------------------------- // Parameter: // clrColor - RGBQUAD value from DIB // Return value: // A grayed color in the RGBQUAD format //---------------------------------------------------------- COLORREF CPPDrawManager::GrayMirrorColor(COLORREF clrColor) { BYTE nGrayColor = (BYTE)((GetBValue(clrColor) * 0.299) + (GetGValue(clrColor) * 0.587) + (GetRValue(clrColor) * 0.114)); return RGB(nGrayColor, nGrayColor, nGrayColor); } //End of GrayMirrorColor COLORREF CPPDrawManager::GrayColor(COLORREF clrColor) { BYTE nGrayColor = (BYTE)((GetRValue(clrColor) * 0.299) + (GetGValue(clrColor) * 0.587) + (GetBValue(clrColor) * 0.114)); return RGB(nGrayColor, nGrayColor, nGrayColor); } //End GrayColor COLORREF CPPDrawManager::InvertColor(COLORREF clrColor) { return RGB(255 - GetRValue(clrColor), 255 - GetGValue(clrColor), 255 - GetBValue(clrColor)); } //End InvertColor COLORREF CPPDrawManager::DarkenColor(COLORREF clrColor, double darken) { if (darken >= 0.0 && darken < 1.0) { BYTE color_r, color_g, color_b; color_r = (BYTE)(GetRValue(clrColor) * darken); color_g = (BYTE)(GetGValue(clrColor) * darken); color_b = (BYTE)(GetBValue(clrColor) * darken); clrColor = RGB(color_r, color_g, color_b); } //if return clrColor; } //End DarkenColor COLORREF CPPDrawManager::LightenColor(COLORREF clrColor, double lighten) { if (lighten > 0.0 && lighten <= 1.0) { BYTE color_r, color_g, color_b; lighten += 1.0; color_r = (BYTE)min((DWORD)GetRValue(clrColor) * lighten, 255.0); color_g = (BYTE)min((DWORD)GetGValue(clrColor) * lighten, 255.0); color_b = (BYTE)min((DWORD)GetBValue(clrColor) * lighten, 255.0); clrColor = RGB(color_r, color_g, color_b); /* lighten *= 255 color_r = (BYTE)max(0, min(255, (int)((color_r - 128) * 2.0 + 128 + lighten))); color_g = (BYTE)max(0, min(255, (int)((color_g - 128) * 2.0 + 128 + lighten))); color_b = (BYTE)max(0, min(255, (int)((color_b - 128) * 2.0 + 128 + lighten))); clrColor = RGB(color_r, color_g, color_b); */ } //if return clrColor; } //End LightenColor COLORREF CPPDrawManager::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); } //End PixelAlpha HICON CPPDrawManager::StretchIcon(HICON hIcon, DWORD dwWidth, DWORD dwHeight) { HICON hStretchedIcon = NULL; HDC hMainDC = NULL; HDC hSrcDC = NULL; HDC hDestDC = NULL; BITMAP bmp; HBITMAP hOldSrcBitmap = NULL; HBITMAP hOldDestBitmap = NULL; ICONINFO csOriginal, csStretched; if (!::GetIconInfo(hIcon, &csOriginal)) return FALSE; hMainDC = ::GetDC(NULL); hSrcDC = ::CreateCompatibleDC(hMainDC); hDestDC = ::CreateCompatibleDC(hMainDC); if ((NULL == hMainDC) || (NULL == hSrcDC) || (NULL == hDestDC)) return NULL; if (::GetObject(csOriginal.hbmColor, sizeof(BITMAP), &bmp)) { DWORD dwWidthOrg = csOriginal.xHotspot * 2; DWORD dwHeightOrg = csOriginal.yHotspot * 2; csStretched.hbmColor = ::CreateBitmap(dwWidth, dwHeight, bmp.bmPlanes, bmp.bmBitsPixel, NULL); if (NULL != csStretched.hbmColor) { hOldSrcBitmap = (HBITMAP)::SelectObject(hSrcDC, csOriginal.hbmColor); hOldDestBitmap = (HBITMAP)::SelectObject(hDestDC, csStretched.hbmColor); ::StretchBlt(hDestDC, 0, 0, dwWidth, dwHeight, hSrcDC, 0, 0, dwWidthOrg, dwHeightOrg, SRCCOPY); if (::GetObject(csOriginal.hbmMask, sizeof(BITMAP), &bmp)) { csStretched.hbmMask = ::CreateBitmap(dwWidth, dwHeight, bmp.bmPlanes, bmp.bmBitsPixel, NULL); if (NULL != csStretched.hbmMask) { ::SelectObject(hSrcDC, csOriginal.hbmMask); ::SelectObject(hDestDC, csStretched.hbmMask); ::StretchBlt(hDestDC, 0, 0, dwWidth, dwHeight, hSrcDC, 0, 0, dwWidthOrg, dwHeightOrg, SRCCOPY); } //if } //if ::SelectObject(hSrcDC, hOldSrcBitmap); ::SelectObject(hDestDC, hOldDestBitmap); csStretched.fIcon = TRUE; hStretchedIcon = ::CreateIconIndirect(&csStretched); } //if ::DeleteObject(csStretched.hbmColor); ::DeleteObject(csStretched.hbmMask); } //if ::DeleteObject(csOriginal.hbmColor); ::DeleteObject(csOriginal.hbmMask); ::DeleteDC(hSrcDC); ::DeleteDC(hDestDC); ::ReleaseDC(NULL, hMainDC); return hStretchedIcon; } //End StretchIcon void CPPDrawManager::FillGradient (HDC hDC, LPCRECT lpRect, COLORREF colorStart, COLORREF colorFinish, BOOL bHorz/* = TRUE*/) { // this will make 2^6 = 64 fountain steps int nShift = 6; int nSteps = 1 << nShift; RECT r2; r2.top = lpRect->top; r2.left = lpRect->left; r2.right = lpRect->right; r2.bottom = lpRect->bottom; int nHeight = lpRect->bottom - lpRect->top; int nWidth = lpRect->right - lpRect->left; for (int i = 0; i < nSteps; i++) { // do a little alpha blending BYTE bR = (BYTE) ((GetRValue(colorStart) * (nSteps - i) + GetRValue(colorFinish) * i) >> nShift); BYTE bG = (BYTE) ((GetGValue(colorStart) * (nSteps - i) + GetGValue(colorFinish) * i) >> nShift); BYTE bB = (BYTE) ((GetBValue(colorStart) * (nSteps - i) + GetBValue(colorFinish) * i) >> nShift); HBRUSH hBrush = ::CreateSolidBrush(RGB(bR, bG, bB)); // then paint with the resulting color if (!bHorz) { r2.top = lpRect->top + ((i * nHeight) >> nShift); r2.bottom = lpRect->top + (((i + 1) * nHeight) >> nShift); if ((r2.bottom - r2.top) > 0) ::FillRect(hDC, &r2, hBrush); } else { r2.left = lpRect->left + ((i * nWidth) >> nShift); r2.right = lpRect->left + (((i + 1) * nWidth) >> nShift); if ((r2.right - r2.left) > 0) ::FillRect(hDC, &r2, hBrush); } //if if (NULL != hBrush) { ::DeleteObject(hBrush); hBrush = NULL; } //if } //for } //End FillGradient #ifdef USE_SHADE void CPPDrawManager::SetShade(LPCRECT lpRect, UINT shadeID /* = 0 */, BYTE granularity /* = 8 */, BYTE coloring /* = 0 */, COLORREF hicr /* = 0 */, COLORREF midcr /* = 0 */, COLORREF locr /* = 0 */) { long sXSize,sYSize,bytes,j,i,k,h; BYTE *iDst ,*posDst; sYSize = lpRect->bottom - lpRect->top; sXSize = lpRect->right - lpRect->left; m_dNormal.Create(sXSize,sYSize,8); //create the default bitmap long r,g,b; //build the shaded palette for(i = 0; i < 129; i++) { r=((128-i)*GetRValue(locr)+i*GetRValue(midcr))/128; g=((128-i)*GetGValue(locr)+i*GetGValue(midcr))/128; b=((128-i)*GetBValue(locr)+i*GetBValue(midcr))/128; m_dNormal.SetPaletteIndex((BYTE)i,(BYTE)r,(BYTE)g,(BYTE)b); } //for for(i=1;i<129;i++){ r=((128-i)*GetRValue(midcr)+i*GetRValue(hicr))/128; g=((128-i)*GetGValue(midcr)+i*GetGValue(hicr))/128; b=((128-i)*GetBValue(midcr)+i*GetBValue(hicr))/128; m_dNormal.SetPaletteIndex((BYTE)(i+127),(BYTE)r,(BYTE)g,(BYTE)b); } //for m_dNormal.BlendPalette(hicr,coloring); //color the palette bytes = m_dNormal.GetLineWidth(); iDst = m_dNormal.GetBits(); posDst =iDst; long a,x,y,d,xs,idxmax,idxmin; int grainx2 = RAND_MAX/(max(1,2*granularity)); idxmax=255-granularity; idxmin=granularity; switch (shadeID) { //---------------------------------------------------- case EFFECT_METAL: m_dNormal.Clear(); // create the strokes k=40; //stroke granularity for(a=0;a<200;a++){ x=rand()/(RAND_MAX/sXSize); //stroke postion y=rand()/(RAND_MAX/sYSize); //stroke position xs=rand()/(RAND_MAX/min(sXSize,sYSize))/2; //stroke lenght d=rand()/(RAND_MAX/k); //stroke color for(i=0;i<xs;i++){ if (((x-i)>0)&&((y+i)<sYSize)) m_dNormal.SetPixelIndex(x-i,y+i,(BYTE)d); if (((x+i)<sXSize)&&((y-i)>0)) m_dNormal.SetPixelIndex(sXSize-x+i,y-i,(BYTE)d); } //for } //for //blend strokes with SHS_DIAGONAL posDst =iDst; a=(idxmax-idxmin-k)/2; for(i = 0; i < sYSize; i++) { for(j = 0; j < sXSize; j++) { d=posDst[j]+((a*i)/sYSize+(a*(sXSize-j))/sXSize); posDst[j]=(BYTE)d; posDst[j]+=rand()/grainx2; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_HARDBUMP: // //set horizontal bump for(i = 0; i < sYSize; i++) { k=(255*i/sYSize)-127; k=(k*(k*k)/128)/128; k=(k*(128-granularity*2))/128+128; for(j = 0; j < sXSize; j++) { posDst[j]=(BYTE)k; posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for //set vertical bump d=min(16,sXSize/6); //max edge=16 a=sYSize*sYSize/4; posDst =iDst; for(i = 0; i < sYSize; i++) { y=i-sYSize/2; for(j = 0; j < sXSize; j++) { x=j-sXSize/2; xs=sXSize/2-d+(y*y*d)/a; if (x>xs) posDst[j]=(BYTE)idxmin+(BYTE)(((sXSize-j)*128)/d); if ((x+xs)<0) posDst[j]=(BYTE)idxmax-(BYTE)((j*128)/d); posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_SOFTBUMP: // for(i = 0; i < sYSize; i++) { h=(255*i/sYSize)-127; for(j = 0; j < sXSize; j++) { k=(255*(sXSize-j)/sXSize)-127; k=(h*(h*h)/128)/128+(k*(k*k)/128)/128; k=k*(128-granularity)/128+128; if (k<idxmin) k=idxmin; if (k>idxmax) k=idxmax; posDst[j]=(BYTE)k; posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_VBUMP: // for(j = 0; j < sXSize; j++) { k=(255*(sXSize-j)/sXSize)-127; k=(k*(k*k)/128)/128; k=(k*(128-granularity))/128+128; for(i = 0; i < sYSize; i++) { posDst[j+i*bytes]=(BYTE)k; posDst[j+i*bytes]+=rand()/grainx2-granularity; } //for } //for break; //---------------------------------------------------- case EFFECT_HBUMP: // for(i = 0; i < sYSize; i++) { k=(255*i/sYSize)-127; k=(k*(k*k)/128)/128; k=(k*(128-granularity))/128+128; for(j = 0; j < sXSize; j++) { posDst[j]=(BYTE)k; posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_DIAGSHADE: // a=(idxmax-idxmin)/2; for(i = 0; i < sYSize; i++) { for(j = 0; j < sXSize; j++) { posDst[j]=(BYTE)(idxmin+a*i/sYSize+a*(sXSize-j)/sXSize); posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_HSHADE: // a=idxmax-idxmin; for(i = 0; i < sYSize; i++) { k=a*i/sYSize+idxmin; for(j = 0; j < sXSize; j++) { posDst[j]=(BYTE)k; posDst[j]+=rand()/grainx2-granularity; } //for posDst+=bytes; } //for break; //---------------------------------------------------- case EFFECT_VSHADE: //: a=idxmax-idxmin; for(j = 0; j < sXSize; j++) { k=a*(sXSize-j)/sXSize+idxmin; for(i = 0; i < sYSize; i++) { posDst[j+i*bytes]=(BYTE)k; posDst[j+i*bytes]+=rand()/grainx2-granularity; } //for } //for break; //---------------------------------------------------- case EFFECT_NOISE: for(i = 0; i < sYSize; i++) { for(j = 0; j < sXSize; j++) { posDst[j]=128+rand()/grainx2-granularity; } //for posDst+=bytes; } //for } //switch //---------------------------------------------------- } //End SetShade #endif void CPPDrawManager::FillEffect(HDC hDC, DWORD dwEffect, LPCRECT lpRect, COLORREF clrBegin, COLORREF clrMid /* = 0 */, COLORREF clrEnd /* = 0 */, BYTE granularity /* = 0 */, BYTE coloring /* = 0 */) { HBRUSH hBrush = NULL; RECT rect; rect.left = lpRect->left; rect.top = lpRect->top; rect.right = lpRect->right; rect.bottom = lpRect->bottom; int nHeight = rect.bottom - rect.top; int nWidth = rect.right - rect.left; switch (dwEffect) { default: hBrush = ::CreateSolidBrush(clrBegin); ::FillRect(hDC, lpRect, hBrush); break; case EFFECT_HGRADIENT: FillGradient(hDC, lpRect, clrBegin, clrEnd, TRUE); break; case EFFECT_VGRADIENT: FillGradient(hDC, lpRect, clrBegin, clrEnd, FALSE); break; case EFFECT_HCGRADIENT: rect.right = rect.left + nWidth / 2; FillGradient(hDC, &rect, clrBegin, clrEnd, TRUE); rect.left = rect.right; rect.right = lpRect->right; FillGradient(hDC, &rect, clrEnd, clrBegin, TRUE); break; case EFFECT_3HGRADIENT: rect.right = rect.left + nWidth / 2; FillGradient(hDC, &rect, clrBegin, clrMid, TRUE); rect.left = rect.right; rect.right = lpRect->right; FillGradient(hDC, &rect, clrMid, clrEnd, TRUE); break; case EFFECT_VCGRADIENT: rect.bottom = rect.top + nHeight / 2; FillGradient(hDC, &rect, clrBegin, clrEnd, FALSE); rect.top = rect.bottom; rect.bottom = lpRect->bottom; FillGradient(hDC, &rect, clrEnd, clrBegin, FALSE); break; case EFFECT_3VGRADIENT: rect.bottom = rect.top + nHeight / 2; FillGradient(hDC, &rect, clrBegin, clrMid, FALSE); rect.top = rect.bottom; rect.bottom = lpRect->bottom; FillGradient(hDC, &rect, clrMid, clrEnd, FALSE); break; #ifdef USE_SHADE case EFFECT_NOISE: case EFFECT_DIAGSHADE: case EFFECT_HSHADE: case EFFECT_VSHADE: case EFFECT_HBUMP: case EFFECT_VBUMP: case EFFECT_SOFTBUMP: case EFFECT_HARDBUMP: case EFFECT_METAL: rect.left = 0; rect.top = 0; rect.right = nWidth; rect.bottom = nHeight; SetShade(&rect, dwEffect, granularity, coloring, clrBegin, clrMid, clrEnd); m_dNormal.Draw(hDC, lpRect->left, lpRect->top); break; #endif } //switch if (NULL != hBrush) { ::DeleteObject(hBrush); hBrush = NULL; } //if } //End FillEffect void CPPDrawManager::MultipleCopy(HDC hDestDC, int nDestX, int nDestY, DWORD dwDestWidth, DWORD dwDestHeight, HDC hSrcDC, int nSrcX, int nSrcY, DWORD dwSrcWidth, DWORD dwSrcHeight) { // Horizontal copying int right, bottom; int nDestRight = (int)(nDestX + dwDestWidth); int nDestBottom = (int)(nDestY + dwDestHeight); for (int x = nDestX; x < nDestRight; x+= dwSrcWidth) { right = min (x + (int)dwSrcWidth, nDestRight); // Vertical copying for (int y = nDestY; y < nDestBottom; y+= dwSrcHeight) { bottom = min (y + (int)dwSrcHeight, nDestBottom); ::BitBlt(hDestDC, x, y, right - x, bottom - y, hSrcDC, nSrcX, nSrcY, SRCCOPY); } //for } //for } //End MultipleCopy void CPPDrawManager::DrawBitmap(HDC hDC, int x, int y, DWORD dwWidth, DWORD dwHeight, HBITMAP hSrcBitmap, BOOL bUseMask, COLORREF crMask, DWORD dwEffect /* = IMAGE_EFFECT_NONE */, BOOL bShadow /* = FALSE */, DWORD dwCxShadow /* = PPDRAWMANAGER_SHADOW_XOFFSET */, DWORD dwCyShadow /* = PPDRAWMANAGER_SHADOW_YOFFSET */, DWORD dwCxDepth /* = PPDRAWMANAGER_SHADOW_XDEPTH */, DWORD dwCyDepth /* = PPDRAWMANAGER_SHADOW_YDEPTH */, COLORREF clrShadow /* = PPDRAWMANAGER_SHADOW_COLOR */) { m_bIsAlpha = FALSE; if (NULL == hSrcBitmap) return; SIZE sz; GetSizeOfBitmap(hSrcBitmap, &sz); HDC hSrcDC = ::CreateCompatibleDC(hDC); HDC hDestDC = ::CreateCompatibleDC(hDC); HBITMAP hBitmapTemp = ::CreateCompatibleBitmap(hDC, dwWidth, dwHeight); HBITMAP hOldSrcBitmap = (HBITMAP)::SelectObject(hSrcDC, hSrcBitmap); HBITMAP hOldDestBitmap = (HBITMAP)::SelectObject(hDestDC, hBitmapTemp); //Scales a bitmap if need if (((DWORD)sz.cx != dwWidth) || ((DWORD)sz.cy != dwHeight)) ::StretchBlt(hDestDC, 0, 0, dwWidth, dwHeight, hSrcDC, 0, 0, sz.cx, sz.cy, SRCCOPY); else ::BitBlt(hDestDC, 0, 0, dwWidth, dwHeight, hSrcDC, 0, 0, SRCCOPY); ::SelectObject(hDestDC, hOldDestBitmap); HBITMAP hMaskBmp = CreateImageEffect(hBitmapTemp, dwWidth, dwHeight, IMAGE_EFFECT_MASK, bUseMask, crMask); HBITMAP hBitmap = CreateImageEffect(hBitmapTemp, dwWidth, dwHeight, dwEffect, bUseMask, crMask, clrShadow); if (bShadow) { if (dwEffect & IMAGE_EFFECT_SHADOW) { POINT ptShadow; ptShadow.x = x + dwCxShadow; ptShadow.y = y + dwCyShadow; HBITMAP hShadowBmp = CreateImageEffect(hBitmapTemp, dwWidth, dwHeight, IMAGE_EFFECT_MASK, bUseMask, crMask, InvertColor(clrShadow)); DrawShadow(hDC, ptShadow.x, ptShadow.y, dwWidth, dwHeight, hShadowBmp, dwEffect & IMAGE_EFFECT_GRADIENT_SHADOW, dwCxDepth, dwCyDepth); ::DeleteObject(hShadowBmp); } else { x += dwCxShadow; y += dwCyShadow; } //if } //if if (m_bIsAlpha) { ::SelectObject(hSrcDC, hBitmap); AlphaChannelBitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0); } else { //Merge the image mask with background ::SelectObject(hSrcDC, hMaskBmp); ::BitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0, SRCAND); //Draw the image ::SelectObject(hSrcDC, hBitmap); ::BitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0, SRCPAINT); } ::SelectObject(hSrcDC, hOldSrcBitmap); ::DeleteDC(hDestDC); ::DeleteDC(hSrcDC); ::DeleteObject(hBitmap); ::DeleteObject(hMaskBmp); ::DeleteObject(hBitmapTemp); } //End DrawBitmap void CPPDrawManager::DrawIcon(HDC hDC, int x, int y, DWORD dwWidth, DWORD dwHeight, HICON hSrcIcon, DWORD dwEffect /* = IMAGE_EFFECT_NONE */, BOOL bShadow /* = FALSE */, DWORD dwCxShadow /* = PPDRAWMANAGER_SHADOW_XOFFSET */, DWORD dwCyShadow /* = PPDRAWMANAGER_SHADOW_YOFFSET */, DWORD dwCxDepth /* = PPDRAWMANAGER_SHADOW_XDEPTH */, DWORD dwCyDepth /* = PPDRAWMANAGER_SHADOW_YDEPTH */, COLORREF clrShadow /* = PPDRAWMANAGER_SHADOW_COLOR */) { m_bIsAlpha = FALSE; if (NULL == hSrcIcon) return; SIZE sz; GetSizeOfIcon(hSrcIcon, &sz); HICON hIcon = NULL; if (((DWORD)sz.cx == dwWidth) && ((DWORD)sz.cy == dwHeight)) hIcon = ::CopyIcon(hSrcIcon); else hIcon = StretchIcon(hSrcIcon, dwWidth, dwHeight); ICONINFO csOriginal; if (!::GetIconInfo(hIcon, &csOriginal)) return; HDC hSrcDC = ::CreateCompatibleDC(hDC); HBITMAP hBitmap; if (dwEffect & IMAGE_EFFECT_MONOCHROME) hBitmap = CreateImageEffect(csOriginal.hbmMask, dwWidth, dwHeight, dwEffect, TRUE, RGB(255, 255, 255), clrShadow); else hBitmap = CreateImageEffect(csOriginal.hbmColor, dwWidth, dwHeight, dwEffect, TRUE, RGB(0, 0, 0), clrShadow); HBITMAP hOldSrcBitmap = (HBITMAP)::SelectObject(hSrcDC, hBitmap); if (bShadow) { if (dwEffect & IMAGE_EFFECT_SHADOW) { POINT ptShadow; ptShadow.x = x + dwCxShadow; ptShadow.y = y + dwCyShadow; HBITMAP hShadowBmp = CreateImageEffect(csOriginal.hbmMask, dwWidth, dwHeight, IMAGE_EFFECT_MASK, TRUE, RGB(255, 255, 255), InvertColor(clrShadow)); DrawShadow(hDC, ptShadow.x, ptShadow.y, dwWidth, dwHeight, hShadowBmp, dwEffect & IMAGE_EFFECT_GRADIENT_SHADOW, dwCxDepth, dwCyDepth); ::DeleteObject(hShadowBmp); } else { x += dwCxShadow; y += dwCyShadow; } //if } //if if (m_bIsAlpha) { // ::SelectObject(hSrcDC, hBitmap); AlphaChannelBitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0); } else { //------------------------------------------------------------------- // !!! ATTENTION !!! // I don't know why a icon uses text's color // Therefore I change a text's color to BLACK and after draw I restore // original color //------------------------------------------------------------------- COLORREF crOldColor = ::SetTextColor(hDC, RGB(0, 0, 0)); //Merge the image mask with background ::SelectObject(hSrcDC, csOriginal.hbmMask); ::BitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0, SRCAND); //Draw the image ::SelectObject(hSrcDC, hBitmap); ::BitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0, SRCPAINT); ::SetTextColor(hDC, crOldColor); } //if ::SelectObject(hSrcDC, hOldSrcBitmap); ::DeleteDC(hSrcDC); ::DeleteObject(hBitmap); ::DestroyIcon(hIcon); ::DeleteObject(csOriginal.hbmColor); ::DeleteObject(csOriginal.hbmMask); } //End DrawIcon void CPPDrawManager::DrawShadow(HDC hDestDC, int nDestX, int nDestY, DWORD dwWidth, DWORD dwHeight, HBITMAP hMask, BOOL bGradient /* = FALSE */, DWORD dwDepthX /* = PPDRAWMANAGER_SHADOW_YOFFSET */, DWORD dwDepthY /* = PPDRAWMANAGER_SHADOW_XOFFSET */) { HDC hSrcDC = ::CreateCompatibleDC(hDestDC); if (NULL == hSrcDC) return; HDC hTempDC = ::CreateCompatibleDC(hDestDC); if (NULL == hTempDC) { ::DeleteDC(hSrcDC); return; } // if //Creates Source DIB LPBITMAPINFO lpbiSrc; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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)) { HBITMAP hOldSrcBmp = (HBITMAP)::SelectObject (hSrcDC, hSrcDib); HBITMAP hOldTempBmp = (HBITMAP)::SelectObject (hTempDC, hMask); if (bGradient) { if (!(dwDepthX & 0x1)) dwDepthX++; if (!(dwDepthY & 0x1)) dwDepthY++; ::BitBlt(hSrcDC, 0, 0, dwWidth, dwHeight, hTempDC, 0, 0, WHITENESS); ::StretchBlt (hSrcDC, dwDepthX / 2, dwDepthY / 2, dwWidth - dwDepthX, dwHeight - dwDepthY, hTempDC, 0, 0, dwWidth, dwHeight, SRCCOPY); } else { ::BitBlt(hSrcDC, 0, 0, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); } //if ::SelectObject (hTempDC, hOldTempBmp); ::SelectObject (hSrcDC, hOldSrcBmp); //Creates Destination DIB LPBITMAPINFO lpbiDest; // Fill in the BITMAPINFOHEADER lpbiDest = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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 ( hDestDC, lpbiDest, DIB_RGB_COLORS, (void **)&pDestBits, NULL, NULL); if ((NULL != hDestDib) && (NULL != pDestBits)) { ::SelectObject (hTempDC, hDestDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hDestDC, nDestX, nDestY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); if (bGradient) { double * depth = new double [dwWidth * dwHeight]; SmoothMaskImage(dwWidth, dwHeight, pSrcBits, dwDepthX, dwDepthY, depth); for(DWORD pixel = 0; pixel < dwWidth * dwHeight; pixel++, pDestBits++) *pDestBits = DarkenColor(*pDestBits, *(depth + pixel)); delete [] depth; } else { for(DWORD pixel = 0; pixel < dwWidth * dwHeight; pixel++, pSrcBits++, pDestBits++) *pDestBits = DarkenColor(*pDestBits, (double)GetRValue(*pSrcBits) / 255.0); } //if ::SelectObject (hTempDC, hDestDib); ::BitBlt (hDestDC, nDestX, nDestY, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); delete lpbiDest; ::DeleteObject(hDestDib); } //if delete lpbiSrc; ::DeleteObject(hSrcDib); } //if ::DeleteDC(hTempDC); ::DeleteDC(hSrcDC); } //End DrawIcon void CPPDrawManager::DrawImageList(HDC hDC, int x, int y, DWORD dwWidth, DWORD dwHeight, HBITMAP hSrcBitmap, int nIndex, int cx, int cy, BOOL bUseMask, COLORREF crMask, DWORD dwEffect /*= IMAGE_EFFECT_NONE*/, BOOL bShadow /*= FALSE*/, DWORD dwCxShadow /*= PPDRAWMANAGER_SHADOW_XOFFSET*/, DWORD dwCyShadow /*= PPDRAWMANAGER_SHADOW_YOFFSET*/, DWORD dwCxDepth /*= PPDRAWMANAGER_SHADOW_XDEPTH*/, DWORD dwCyDepth /*= PPDRAWMANAGER_SHADOW_YDEPTH*/, COLORREF clrShadow /*= PPDRAWMANAGER_SHADOW_COLOR*/) { if ((NULL == hSrcBitmap) || !cx || !cy) return; SIZE sz; GetSizeOfBitmap(hSrcBitmap, &sz); //ENG: Gets a max columns and rows of the images on the bitmap int nMaxCol = sz.cx / cx; int nMaxRow = sz.cy / cy; int nMaxImages = nMaxCol * nMaxRow; if ((nIndex < nMaxImages) && nMaxCol && nMaxRow) { //ENG: Gets an specified image from the bitmap HDC hSrcDC = ::CreateCompatibleDC(hDC); HDC hDestDC = ::CreateCompatibleDC(hDC); HBITMAP hIconBmp = ::CreateCompatibleBitmap(hDC, cx, cy); HBITMAP hOldSrcBmp = (HBITMAP)::SelectObject(hSrcDC, hSrcBitmap); HBITMAP hOldDestBmp = (HBITMAP)::SelectObject(hDestDC, hIconBmp); ::BitBlt(hDestDC, 0, 0, cx, cy, hSrcDC, (nIndex % nMaxCol) * cx, (nIndex / nMaxCol) * cy, SRCCOPY); ::SelectObject(hSrcDC, hOldSrcBmp); ::SelectObject(hDestDC, hOldDestBmp); ::DeleteDC(hSrcDC); ::DeleteDC(hDestDC); DrawBitmap( hDC, x, y, dwWidth, dwHeight, hIconBmp, bUseMask, crMask, dwEffect, bShadow, dwCxShadow, dwCyShadow, dwCxDepth, dwCyDepth, clrShadow); ::DeleteObject(hIconBmp); } //if } //End of DrawImageList void CPPDrawManager::MaskToDepth(HDC hDC, DWORD dwWidth, DWORD dwHeight, HBITMAP hMask, double * pDepth, BOOL bGradient /* = FALSE */, DWORD dwDepthX /* = PPDRAWMANAGER_CXSHADOW */, DWORD dwDepthY /* = PPDRAWMANAGER_CYSHADOW */) { HDC hSrcDC = ::CreateCompatibleDC(hDC); if (NULL == hSrcDC) { ::DeleteDC(hSrcDC); hSrcDC = NULL; return; } //if HDC hTempDC = ::CreateCompatibleDC(hDC); if (NULL == hTempDC) { ::DeleteDC(hTempDC); hTempDC = NULL; return; } //if //Creates Source DIB LPBITMAPINFO lpbiSrc; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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)) { HBITMAP hOldSrcBmp = (HBITMAP)::SelectObject (hSrcDC, hSrcDib); HBITMAP hOldTempBmp = (HBITMAP)::SelectObject (hTempDC, hMask); if (bGradient) { if (!(dwDepthX & 0x1)) dwDepthX++; if (!(dwDepthY & 0x1)) dwDepthY++; ::BitBlt(hSrcDC, 0, 0, dwWidth, dwHeight, hTempDC, 0, 0, WHITENESS); ::StretchBlt (hSrcDC, dwDepthX / 2, dwDepthY / 2, dwWidth - dwDepthX, dwHeight - dwDepthY, hTempDC, 0, 0, dwWidth, dwHeight, SRCCOPY); } else { ::BitBlt(hSrcDC, 0, 0, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); } //if ::SelectObject (hTempDC, hOldTempBmp); ::SelectObject (hSrcDC, hOldSrcBmp); if (bGradient) { SmoothMaskImage(dwWidth, dwHeight, pSrcBits, dwDepthX, dwDepthY, pDepth); } else { for (DWORD pixel = 0; pixel < (dwHeight * dwWidth); pixel++, pSrcBits++, pDepth++) { *pDepth = GetRValue(*pSrcBits) / 255; } //for } //if delete lpbiSrc; ::DeleteObject(hSrcDib); } //if ::DeleteDC(hTempDC); ::DeleteDC(hSrcDC); } //End MaskToDepth void CPPDrawManager::DarkenByDepth(HDC hDC, int x, int y, DWORD dwWidth, DWORD dwHeight, double * pDepth) { HDC hSrcDC = ::CreateCompatibleDC(hDC); if (NULL == hSrcDC) { ::DeleteDC(hSrcDC); hSrcDC = NULL; return; } //if //Creates Source DIB LPBITMAPINFO lpbiSrc; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; 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)) { HBITMAP hOldSrcBmp = (HBITMAP)::SelectObject (hSrcDC, hSrcDib); ::BitBlt(hSrcDC, 0, 0, dwWidth, dwHeight, hDC, x, y, SRCCOPY); ::SelectObject (hSrcDC, hOldSrcBmp); for (DWORD pixel = 0; pixel < (dwHeight * dwWidth); pixel++, pSrcBits++, pDepth++) { *pSrcBits = DarkenColor(*pSrcBits, *pDepth); } //for hOldSrcBmp = (HBITMAP)::SelectObject (hSrcDC, hSrcDib); ::BitBlt(hDC, x, y, dwWidth, dwHeight, hSrcDC, 0, 0, SRCCOPY); ::SelectObject (hSrcDC, hOldSrcBmp); delete lpbiSrc; ::DeleteObject(hSrcDib); } //if ::DeleteDC(hSrcDC); } //DarkenByDepth void CPPDrawManager::SmoothMaskImage(const int ImageWidth, const int ImageHeight, const COLORREF* const pInitImg, const int KerWidth, const int KerHeight, double* const pResImg_R /*= NULL*/) { double* const pfBuff1 = new double[(ImageWidth + KerWidth - 1) * (ImageHeight + KerHeight - 1)]; double* const pfBuff2 = new double[(ImageWidth + KerWidth - 1) * (ImageHeight + KerHeight - 1)]; // expanding initial image with a padding procdure double* p = pfBuff1; const COLORREF * pInitImg_It = pInitImg; if(NULL != pResImg_R) { for(int _i = - KerHeight/2; _i < ImageHeight + KerHeight/2; _i++) { for(int _j = -KerWidth/2; _j < ImageWidth + KerWidth/2; _j++, p++) { if ((_i >= 0) && (_i < ImageHeight) && (_j >= 0) && (_j < ImageWidth)) { *p = GetRValue(*pInitImg_It++); // pInitImg_It++; } else *p = 255; } //for } //for //--- GetPartialSums(pfBuff1, (ImageHeight + KerHeight - 1), (ImageWidth + KerWidth - 1), KerHeight, KerWidth, pfBuff2, pResImg_R); for(int i = 0; i < ImageHeight*ImageWidth; i++) *(pResImg_R + i) /= KerHeight*KerWidth*255; } //if delete []pfBuff1; delete []pfBuff2; } //End SmoothMaskImage void CPPDrawManager::GetPartialSums(const double* const pM, unsigned int nMRows, unsigned int nMCols, unsigned int nPartRows, unsigned int nPartCols, double* const pBuff, double* const pRes) { const double* it1; const double* it2; const double* it3; double* pRowsPartSums; const unsigned int nRowsPartSumsMRows = nMRows; const unsigned int nRowsPartSumsMCols = nMCols - nPartCols + 1; const unsigned int nResMRows = nMRows - nPartRows + 1; const unsigned int nResMCols = nMCols - nPartCols + 1; unsigned int i,j; double s; // частичные суммы строк it1 = pM; pRowsPartSums = pBuff; for(i = 0; i < nMRows; i++) { //------------- it2 = it1; s = 0; for(j = 0;j < nPartCols;j++)s+=*it2++; //------------- it3 = it1; *pRowsPartSums++ = s; for(/*j = nPartCols*/; j < nMCols; j++) { s+=*it2 - *it3; *pRowsPartSums++ = s; it2++; it3++; } //for //-- it1 += nMCols; } //for // формирование резуьтата const double* it4; const double* it5; const double* it6; double* pResIt; it4 = pBuff; pResIt = pRes; for(j = 0; j < nRowsPartSumsMCols; j++) { pResIt = pRes + j; //------------- it5 = it4; s = 0; for(i = 0; i < nPartRows; i++) { s += *it5; it5 += nRowsPartSumsMCols; } //for //------------- it6 = it4; *pResIt = s; pResIt += nRowsPartSumsMCols; for(; i < nRowsPartSumsMRows; i++) { s += *it5 - *it6;//cout<<s<<endl; *pResIt = s; pResIt += nResMCols; it5 += nRowsPartSumsMCols; it6 += nRowsPartSumsMCols; } //for //-- it4 ++; } //for } //End GetPartialSums void CPPDrawManager::DrawRectangle(HDC hDC, LPRECT lpRect, COLORREF crLight, COLORREF crDark, int nStyle /* = PEN_SOLID */, int nSize /* = 1 */) { DrawRectangle(hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, crLight, crDark, nStyle, nSize); } void CPPDrawManager::DrawRectangle(HDC hDC, int left, int top, int right, int bottom, COLORREF crLight, COLORREF crDark, int nStyle /* = PEN_SOLID */, int nSize /* = 1 */) { if ((PEN_NULL == nStyle) || (nSize < 1)) return; int nSysPenStyle = PS_SOLID; int nDoubleLineOffset = nSize * 2; switch (nStyle) { case PEN_DASH: nSysPenStyle = PS_DASH; break; case PEN_DOT: nSysPenStyle = PS_DOT; break; case PEN_DASHDOT: nSysPenStyle = PS_DASHDOT; break; case PEN_DASHDOTDOT: nSysPenStyle = PS_DASHDOTDOT; break; case PEN_DOUBLE: case PEN_SOLID: default: nSysPenStyle = PS_SOLID; break; } //switch //Insideframe left += nSize / 2; top += nSize / 2; right -= nSize / 2; bottom -= nSize / 2; //Creates a light pen HPEN hPen = ::CreatePen(nSysPenStyle, nSize, crLight); HPEN hOldPen = (HPEN)::SelectObject(hDC, hPen); //Draw light border ::MoveToEx(hDC, left, bottom, NULL); ::LineTo(hDC, left, top); ::LineTo(hDC, right, top); if (PEN_DOUBLE == nStyle) { ::MoveToEx(hDC, left + nDoubleLineOffset, bottom - nDoubleLineOffset, NULL); ::LineTo(hDC, left + nDoubleLineOffset, top + nDoubleLineOffset); ::LineTo(hDC, right - nDoubleLineOffset, top + nDoubleLineOffset); } //if //Creates a dark pen if needed if (crLight != crDark) { SelectObject(hDC, hOldPen); ::DeleteObject(hPen); hPen = ::CreatePen(nSysPenStyle, nSize, crDark); hOldPen = (HPEN)::SelectObject(hDC, hPen); } //if //Draw dark border ::MoveToEx(hDC, right, top, NULL); ::LineTo(hDC, right, bottom); ::LineTo(hDC, left, bottom); if (PEN_DOUBLE == nStyle) { ::MoveToEx(hDC, right - nDoubleLineOffset, top + nDoubleLineOffset, NULL); ::LineTo(hDC, right - nDoubleLineOffset, bottom - nDoubleLineOffset); ::LineTo(hDC, left + nDoubleLineOffset, bottom - nDoubleLineOffset); } //if SelectObject(hDC, hOldPen); ::DeleteObject(hPen); } //End DrawRectangle void CPPDrawManager::DrawLine(HDC hDC, int xStart, int yStart, int xEnd, int yEnd, COLORREF color, int nStyle /* = PEN_SOLID */, int nSize /* = 1 */) const { if ((PEN_NULL == nStyle) || (nSize < 1)) return; int nSysPenStyle; int nDoubleLineOffset = nSize * 2; switch (nStyle) { case PEN_DASH: nSysPenStyle = PS_DASH; break; case PEN_DOT: nSysPenStyle = PS_DOT; break; case PEN_DASHDOT: nSysPenStyle = PS_DASHDOT; break; case PEN_DASHDOTDOT: nSysPenStyle = PS_DASHDOTDOT; break; case PEN_DOUBLE: case PEN_SOLID: default: nSysPenStyle = PS_SOLID; break; } //switch HPEN hPen = ::CreatePen(nSysPenStyle, nSize, color); HPEN hOldPen = (HPEN)::SelectObject(hDC, hPen); ::MoveToEx(hDC, xStart, yStart, NULL); ::LineTo(hDC, xEnd, yEnd); if (PEN_DOUBLE == nStyle) { if (xStart != xEnd) { yStart += nDoubleLineOffset; yEnd += nDoubleLineOffset; } //if if (yStart != yEnd) { xStart += nDoubleLineOffset; xEnd += nDoubleLineOffset; } //if ::MoveToEx(hDC, xStart, yStart, NULL); ::LineTo(hDC, xEnd, yEnd); } //if SelectObject(hDC, hOldPen); ::DeleteObject(hPen); } //End DrawLine
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 1505 ] ] ]
97ce214358c5a5d3a3141a70d2612516b18a750a
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/tools/vector.h
082d5957c7a8d2afb7990a6d0f83965496b16222
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,195
h
// // This module contains a bunch of well understood functions // I apologise if the conventions used here are slightly // different than what you are used to. // #ifndef GENERIC_VECTOR_H #define GENERIC_VECTOR_H #include <stdio.h> #include <math.h> class Vector { public: float x,y,z; Vector(float _x=0.0,float _y=0.0,float _z=0.0){x=_x;y=_y;z=_z;}; operator float *() { return &x;}; }; float magnitude(Vector v); Vector normalize(Vector v); Vector operator+(Vector v1,Vector v2); Vector operator-(Vector v); Vector operator-(Vector v1,Vector v2); Vector operator*(Vector v1,float s) ; Vector operator*(float s,Vector v1) ; Vector operator/(Vector v1,float s) ; float operator^(Vector v1,Vector v2); // DOT product Vector operator*(Vector v1,Vector v2); // CROSS product Vector planelineintersection(Vector n,float d,Vector p1,Vector p2); class matrix{ public: Vector x,y,z; matrix(){x=Vector(1.0f,0.0f,0.0f); y=Vector(0.0f,1.0f,0.0f); z=Vector(0.0f,0.0f,1.0f);}; matrix(Vector _x,Vector _y,Vector _z){x=_x;y=_y;z=_z;}; }; matrix transpose(matrix m); Vector operator*(matrix m,Vector v); matrix operator*(matrix m1,matrix m2); class Quaternion{ public: float r,x,y,z; Quaternion(){x=y=z=0.0f;r=1.0f;}; Quaternion(Vector v,float t){v=normalize(v);r=(float)cos(t/2.0);v=v*(float)sin(t/2.0);x=v.x;y=v.y;z=v.z;}; Quaternion(float _r,float _x,float _y,float _z){r=_r;x=_x;y=_y;z=_z;}; float angle(){return (float)(acos(r)*2.0);} Vector axis(){Vector a(x,y,z); return a*(float)(1/sin(angle()/2.0));} Vector xdir(){return Vector(1-2*(y*y+z*z), 2*(x*y+r*z), 2*(x*z-r*y));} Vector ydir(){return Vector( 2*(x*y-r*z),1-2*(x*x+z*z), 2*(y*z+r*x));} Vector zdir(){return Vector( 2*(x*z+r*y), 2*(y*z-r*x),1-2*(x*x+y*y));} matrix getmatrix(){return matrix(xdir(),ydir(),zdir());} //operator matrix(){return getmatrix();} }; Quaternion operator-(Quaternion q); Quaternion operator*(Quaternion a,Quaternion b); Vector operator*(Quaternion q,Vector v); Vector operator*(Vector v,Quaternion q); Quaternion slerp(Quaternion a,Quaternion b,float interp); #endif
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 66 ] ] ]
59cc399214f2b477d0c3eb05a59453700fc518b1
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/functional/hash/examples/books.cpp
4ed5bdc2c73f63169e463ee0a9e02db9eb81c61b
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,514
cpp
// Copyright Daniel James 2005-2006. Use, modification, and distribution are // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "./books.hpp" #include <boost/functional/hash.hpp> #include <cassert> // If std::unordered_set was available: //#include <unordered_set> // This example illustrates how to use boost::hash with a custom hash function. // For full details, see the tutorial. int main() { library::book knife(3458, "Zane Grey", "The Hash Knife Outfit"); library::book dandelion(1354, "Paul J. Shanley", "Hash & Dandelion Greens"); boost::hash<library::book> book_hasher; std::size_t knife_hash_value = book_hasher(knife); // If std::unordered_set was available: // //std::unordered_set<library::book, boost::hash<library::book> > books; //books.insert(knife); //books.insert(library::book(2443, "Lindgren, Torgny", "Hash")); //books.insert(library::book(1953, "Snyder, Bernadette M.", // "Heavenly Hash: A Tasty Mix of a Mother's Meditations")); //assert(books.find(knife) != books.end()); //assert(books.find(dandelion) == books.end()); return 0; } namespace library { bool operator==(book const& a, book const& b) { return a.id == b.id; } std::size_t hash_value(book const& b) { boost::hash<int> hasher; return hasher(b.id); } }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 50 ] ] ]
035e8de9ed417dfb713639b06e9b896c7608b7fa
6dc976d19edc24eda572338646eb23b054880c55
/PS3/rom_list.cpp
6339aa9e7933d83af69eb8579ca5483345424f70
[]
no_license
wsz8/ps3sx
aae188451b93398795e98c1fbdad2a2163f3cfd1
06fe64c85acb406676d3cff8889736db8d6c749e
refs/heads/master
2020-04-20T16:59:17.347699
2011-01-06T11:34:52
2011-01-06T11:34:52
34,731,825
0
0
null
null
null
null
UTF-8
C++
false
false
18,232
cpp
/* * menu.cpp * * Created on: Oct 10, 2010 * Author: halsafar */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stack> #include <vector> #include "PS3Video.h" #include "rom_list.h" #include "input/Cellinput.h" #include "fileio/FileBrowser.h" #include <cell/pad.h> #include <cell/audio.h> #include <cell/sysmodule.h> #include <cell/cell_fs.h> #include <cell/dbgfont.h> #include <sysutil/sysutil_sysparam.h> extern int is_running; extern int RomType; SSettings Settings; #define stricmp strcasecmp #define MIN(x,y) ((x) < (y) ? (x) : (y)) #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define NUM_ENTRY_PER_PAGE 24 extern char rom_path[256]; extern PS3Graphics* Graphics; extern CellInputFacade* PS3input; // is the menu running bool menuRunning = false; // menu to render typedef void (*curMenuPtr)(); // std::stack<curMenuPtr> menuStack; // main file browser->for rom browser FileBrowser* browser = NULL; // tmp file browser->for everything else FileBrowser* tmpBrowser = NULL; void MenuStop() { menuRunning = false; } float FontSize() { return 100/100.0; } bool MenuIsRunning() { return menuRunning; } void UpdateBrowser(FileBrowser* b) { if (PS3input->WasButtonPressed(0,CTRL_DOWN) | PS3input->IsAnalogPressedDown(0,CTRL_LSTICK)) { b->IncrementEntry(); } if (PS3input->WasButtonPressed(0,CTRL_UP) | PS3input->IsAnalogPressedUp(0,CTRL_LSTICK)) { b->DecrementEntry(); } if (PS3input->WasButtonPressed(0,CTRL_RIGHT) | PS3input->IsAnalogPressedRight(0,CTRL_LSTICK)) { b->GotoEntry(MIN(b->GetCurrentEntryIndex()+5, b->GetCurrentDirectoryInfo().numEntries-1)); } if (PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->IsAnalogPressedLeft(0,CTRL_LSTICK)) { if (b->GetCurrentEntryIndex() <= 5) { b->GotoEntry(0); } else { b->GotoEntry(b->GetCurrentEntryIndex()-5); } } if (PS3input->WasButtonPressed(0,CTRL_R1)) { b->GotoEntry(MIN(b->GetCurrentEntryIndex()+NUM_ENTRY_PER_PAGE, b->GetCurrentDirectoryInfo().numEntries-1)); } if (PS3input->WasButtonPressed(0,CTRL_L1)) { if (b->GetCurrentEntryIndex() <= NUM_ENTRY_PER_PAGE) { b->GotoEntry(0); } else { b->GotoEntry(b->GetCurrentEntryIndex()-NUM_ENTRY_PER_PAGE); } } if (PS3input->WasButtonPressed(0, CTRL_CIRCLE)) { // don't let people back out past root if (b->DirectoryStackCount() > 1) { b->PopDirectory(); } } } void RenderBrowser(FileBrowser* b) { uint32_t file_count = b->GetCurrentDirectoryInfo().numEntries; int current_index = b->GetCurrentEntryIndex(); if (file_count <= 0) { printf("1: filecount <= 0"); cellDbgFontPuts (0.09f, 0.05f, FontSize(), RED, "No Roms founds!!!\n"); } else if (current_index > file_count) { printf("2: current_index >= file_count"); } else { int page_number = current_index / NUM_ENTRY_PER_PAGE; int page_base = page_number * NUM_ENTRY_PER_PAGE; float currentX = 0.05f; float currentY = 0.00f; float ySpacing = 0.035f; for (int i = page_base; i < file_count && i < page_base + NUM_ENTRY_PER_PAGE; ++i) { currentY = currentY + ySpacing; cellDbgFontPuts(currentX, currentY, FontSize(), i == current_index ? RED : (*b)[i]->d_type == CELL_FS_TYPE_DIRECTORY ? GREEN : WHITE, (*b)[i]->d_name); Graphics->FlushDbgFont(); } } Graphics->FlushDbgFont(); } void do_shaderChoice() { if (tmpBrowser == NULL) { tmpBrowser = new FileBrowser("/dev_hdd0/game/PCSX00001/USRDIR/shaders/\0"); } string path; if (PS3input->UpdateDevice(0) == CELL_PAD_OK) { UpdateBrowser(tmpBrowser); if (PS3input->WasButtonPressed(0,CTRL_CROSS)) { if(tmpBrowser->IsCurrentADirectory()) { tmpBrowser->PushDirectory( tmpBrowser->GetCurrentDirectoryInfo().dir + "/" + tmpBrowser->GetCurrentEntry()->d_name, CELL_FS_TYPE_REGULAR | CELL_FS_TYPE_DIRECTORY, "cg"); } else if (tmpBrowser->IsCurrentAFile()) { path = tmpBrowser->GetCurrentDirectoryInfo().dir + "/" + tmpBrowser->GetCurrentEntry()->d_name; //load shader Graphics->LoadFragmentShader(path); Graphics->SetSmooth(false); menuStack.pop(); } } if (PS3input->WasButtonHeld(0, CTRL_TRIANGLE)) { menuStack.pop(); } } cellDbgFontPuts(0.09f, 0.88f, FontSize(), YELLOW, "X - Select shader"); cellDbgFontPuts(0.09f, 0.92f, FontSize(), PURPLE, "Triangle - return to settings"); Graphics->FlushDbgFont(); RenderBrowser(tmpBrowser); } int currently_selected_setting = 0; void do_general_settings() { if(PS3input->UpdateDevice(0) == CELL_PAD_OK) { // back to ROM menu if CIRCLE is pressed if (PS3input->WasButtonPressed(0, CTRL_CIRCLE)) { menuStack.pop(); return; } if (PS3input->WasButtonPressed(0, CTRL_DOWN) | PS3input->WasAnalogPressedDown(0, CTRL_LSTICK)) // down to next setting { currently_selected_setting++; if (currently_selected_setting >= MAX_NO_OF_SETTINGS) { currently_selected_setting = 0; } } if (PS3input->WasButtonPressed(0, CTRL_UP) | PS3input->WasAnalogPressedUp(0, CTRL_LSTICK)) // up to previous setting { currently_selected_setting--; if (currently_selected_setting < 0) { currently_selected_setting = MAX_NO_OF_SETTINGS-1; } } switch(currently_selected_setting) { case SETTING_CHANGE_RESOLUTION: if(PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK)) { Graphics->NextResolution(); } if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK)) { Graphics->PreviousResolution(); } if(PS3input->WasButtonPressed(0, CTRL_CROSS)) { Graphics->SwitchResolution(Graphics->GetCurrentResolution(), Settings.PS3PALTemporalMode60Hz); } if(PS3input->IsButtonPressed(0, CTRL_START)) { Graphics->SwitchResolution(Graphics->GetInitialResolution(), Settings.PS3PALTemporalMode60Hz); } break; case SETTING_PAL60_MODE: if(PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0,CTRL_CROSS) | PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK)) { if (Graphics->GetCurrentResolution() == CELL_VIDEO_OUT_RESOLUTION_576) { if(Graphics->CheckResolution(CELL_VIDEO_OUT_RESOLUTION_576)) { Settings.PS3PALTemporalMode60Hz = !Settings.PS3PALTemporalMode60Hz; Graphics->SetPAL60Hz(Settings.PS3PALTemporalMode60Hz); Graphics->SwitchResolution(Graphics->GetCurrentResolution(), Settings.PS3PALTemporalMode60Hz); } } } break; case SETTING_SHADER: if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0, CTRL_LSTICK) | PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedRight(0, CTRL_LSTICK) | PS3input->WasButtonPressed(0, CTRL_CROSS)) { menuStack.push(do_shaderChoice); tmpBrowser = NULL; } break; case SETTING_FONT_SIZE: if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0,CTRL_CROSS)) { if(Settings.PS3FontSize > -100) { Settings.PS3FontSize--; } } if(PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedRight(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0,CTRL_CROSS)) { if((Settings.PS3OverscanAmount < 100)) { Settings.PS3FontSize++; } } if(PS3input->IsButtonPressed(0, CTRL_START)) { Settings.PS3FontSize = 100; } break; case SETTING_KEEP_ASPECT_RATIO: if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedRight(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0,CTRL_CROSS)) { Settings.PS3KeepAspect = !Settings.PS3KeepAspect; Graphics->SetAspectRatio(Settings.PS3KeepAspect); } if(PS3input->IsButtonPressed(0, CTRL_START)) { Settings.PS3KeepAspect = true; Graphics->SetAspectRatio(Settings.PS3KeepAspect); } break; case SETTING_HW_TEXTURE_FILTER: if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedRight(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0,CTRL_CROSS)) { Settings.PS3Smooth = !Settings.PS3Smooth; Graphics->SetSmooth(Settings.PS3Smooth); } if(PS3input->IsButtonPressed(0, CTRL_START)) { Settings.PS3Smooth = true; Graphics->SetSmooth(Settings.PS3Smooth); } break; case SETTING_PAD: if(PS3input->WasButtonPressed(0, CTRL_LEFT) ) { Settings.PAD = false; } if(PS3input->WasButtonPressed(0, CTRL_RIGHT)) { Settings.PAD = true; } break; case SETTING_FPS: if(PS3input->WasButtonPressed(0, CTRL_LEFT) ) { Settings.Fps = false; } if(PS3input->WasButtonPressed(0, CTRL_RIGHT)) { Settings.Fps = true; } break; case SETTING_CPU: if(PS3input->WasButtonPressed(0, CTRL_LEFT) ) { Settings.CPU = false; } if(PS3input->WasButtonPressed(0, CTRL_RIGHT)) { Settings.CPU = true; } break; case SETTING_HLE: if(PS3input->WasButtonPressed(0, CTRL_LEFT) ) { Settings.HLE = false; } if(PS3input->WasButtonPressed(0, CTRL_RIGHT)) { Settings.HLE = true; } break; case SETTING_DEFAULT_ALL: if(PS3input->WasButtonPressed(0, CTRL_LEFT) | PS3input->WasAnalogPressedLeft(0,CTRL_LSTICK) | PS3input->WasButtonPressed(0, CTRL_RIGHT) | PS3input->WasAnalogPressedRight(0,CTRL_LSTICK) | PS3input->IsButtonPressed(0, CTRL_START) | PS3input->WasButtonPressed(0, CTRL_CROSS)) { Settings.PS3KeepAspect = true; Settings.PS3Smooth = true; Settings.CPU = false; Settings.HLE = false; Settings.Fps = false; Graphics->SetAspectRatio(Settings.PS3KeepAspect); Graphics->SetSmooth(Settings.PS3Smooth); Settings.PAD = false; Settings.PS3PALTemporalMode60Hz = false; Graphics->SetPAL60Hz(Settings.PS3PALTemporalMode60Hz); } break; default: break; } // end of switch } float yPos = 0.09; float ySpacing = 0.04; cellDbgFontPuts (0.09f, 0.05f, FontSize(), RED, "GENERAL Setting"); yPos += ySpacing; cellDbgFontPuts (0.09f, yPos, FontSize(), RED, "PS3SX"); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_CHANGE_RESOLUTION ? YELLOW : WHITE, "Resolution"); switch(Graphics->GetCurrentResolution()) { case CELL_VIDEO_OUT_RESOLUTION_480: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_480 ? GREEN : RED, "720x480 (480p)"); break; case CELL_VIDEO_OUT_RESOLUTION_720: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_720 ? GREEN : RED, "1280x720 (720p)"); break; case CELL_VIDEO_OUT_RESOLUTION_1080: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_1080 ? GREEN : RED, "1920x1080 (1080p)"); break; case CELL_VIDEO_OUT_RESOLUTION_576: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_576 ? GREEN : RED, "720x576 (576p)"); break; case CELL_VIDEO_OUT_RESOLUTION_1600x1080: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_1600x1080 ? GREEN : RED, "1600x1080"); break; case CELL_VIDEO_OUT_RESOLUTION_1440x1080: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_1440x1080 ? GREEN : RED, "1440x1080"); break; case CELL_VIDEO_OUT_RESOLUTION_1280x1080: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_1280x1080 ? GREEN : RED, "1280x1080"); break; case CELL_VIDEO_OUT_RESOLUTION_960x1080: cellDbgFontPrintf(0.5f, yPos, FontSize(), Graphics->GetInitialResolution() == CELL_VIDEO_OUT_RESOLUTION_960x1080 ? GREEN : RED, "960x1080"); break; } Graphics->FlushDbgFont(); yPos += ySpacing; cellDbgFontPuts (0.09f, yPos, FontSize(), currently_selected_setting == SETTING_PAL60_MODE ? YELLOW : WHITE, "PAL60 Mode (576p only)"); cellDbgFontPrintf (0.5f, yPos, FontSize(), Settings.PS3PALTemporalMode60Hz == true ? RED : GREEN, Settings.PS3PALTemporalMode60Hz == true ? "ON" : "OFF"); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_SHADER ? YELLOW : WHITE, "Selected shader"); cellDbgFontPrintf(0.5f, yPos, FontSize(), GREEN, "%s", Graphics->GetFragmentShaderPath().substr(Graphics->GetFragmentShaderPath().find_last_of('/')).c_str()); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_FONT_SIZE ? YELLOW : WHITE, "Font size"); cellDbgFontPrintf(0.5f, yPos, FontSize(), Settings.PS3FontSize == 100 ? GREEN : RED, "%f", FontSize()); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_KEEP_ASPECT_RATIO ? YELLOW : WHITE, "Aspect Ratio"); cellDbgFontPrintf(0.5f, yPos, FontSize(), Settings.PS3KeepAspect == true ? GREEN : RED, "%s", Settings.PS3KeepAspect == true ? "Scaled" : "Stretched"); Graphics->FlushDbgFont(); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_HW_TEXTURE_FILTER ? YELLOW : WHITE, "Hardware Filtering"); cellDbgFontPrintf(0.5f, yPos, FontSize(), Settings.PS3Smooth == true ? GREEN : RED, "%s", Settings.PS3Smooth == true ? "Linear interpolation" : "Point filtering"); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_PAD ? YELLOW : WHITE, "PSX Dualshock PAD"); cellDbgFontPrintf(0.5f, yPos, FontSize(), Settings.PAD == true ? GREEN : RED, "%s", Settings.PAD == true ? "Enable" : "Disable"); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_FPS ? YELLOW : WHITE, "Display FPS"); cellDbgFontPrintf(0.5f, yPos, FontSize(), Settings.Fps == true ? GREEN : RED, "%s", Settings.Fps == true ? "Yes" : "No "); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_CPU ? YELLOW : WHITE, "Use CPU interpreter"); cellDbgFontPrintf(0.5f, yPos, FontSize(),Settings.CPU == true ? GREEN : RED, "%s", Settings.CPU == true ? "Yes" : "No"); yPos += ySpacing; cellDbgFontPuts(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_HLE ? YELLOW : WHITE, "Use HLE BIOS"); cellDbgFontPrintf(0.5f, yPos, FontSize(),Settings.HLE == true ? GREEN : RED, "%s", Settings.HLE == true ? "Yes" : "No"); yPos += ySpacing; cellDbgFontPrintf(0.09f, yPos, FontSize(), currently_selected_setting == SETTING_DEFAULT_ALL ? YELLOW : GREEN, "DEFAULT"); Graphics->FlushDbgFont(); if(currently_selected_setting == SETTING_CPU) cellDbgFontPuts(0.09f, 0.80f, FontSize(), WHITE, "Try to use Interpreter more compatible but Slow"); cellDbgFontPuts(0.09f, 0.88f, FontSize(), YELLOW, "UP/DOWN - select, X/LEFT/RIGHT - change, START - default"); cellDbgFontPuts(0.09f, 0.92f, FontSize(), YELLOW, "CIRCLE - return to Roms menu"); Graphics->FlushDbgFont(); } void GetExtension(const char *srcfile,char *outext) { strcpy(outext,srcfile + strlen(srcfile) - 3); } void do_ROMMenu() { string path; char ext[4]; if (PS3input->UpdateDevice(0) == CELL_PAD_OK) { UpdateBrowser(browser); if (PS3input->WasButtonPressed(0,CTRL_CROSS)) { if(browser->IsCurrentADirectory()) { browser->PushDirectory( browser->GetCurrentDirectoryInfo().dir + "/" + browser->GetCurrentEntry()->d_name, CELL_FS_TYPE_REGULAR | CELL_FS_TYPE_DIRECTORY, "iso|img|bin|ISO|BIN|IMG"); } else if (browser->IsCurrentAFile()) { // load game (standard controls), go back to main loop path = browser->GetCurrentDirectoryInfo().dir + "/" + browser->GetCurrentEntry()->d_name; MenuStop(); sprintf(rom_path,"%s",path.c_str()); GetExtension(path.c_str(),ext); if(!stricmp(ext,"psx")||!stricmp(ext,"PSX")||!stricmp(ext,"exe")||!stricmp(ext,"EXE")) RomType = 1; else RomType = 2; return; } } if (PS3input->WasButtonPressed(0,CTRL_CIRCLE)) { menuStack.push(do_general_settings); tmpBrowser = NULL; } if (PS3input->IsButtonPressed(0,CTRL_L2) && PS3input->IsButtonPressed(0,CTRL_R2)) { return; } } cellDbgFontPuts(0.09f, 0.88f, FontSize(), YELLOW, "CROSS - Enter directory/Load game"); cellDbgFontPuts(0.09f, 0.92f, FontSize(), YELLOW, "CIRCLE - Settings screen"); Graphics->FlushDbgFont(); RenderBrowser(browser); } void MenuMainLoop(char* path) { // create file browser->if null if (browser == NULL) { browser = new FileBrowser(path);//"/dev_usb000/genplus/roms"); } // FIXME: could always just return to last menu item... don't pop on resume kinda thing if (menuStack.empty()) { menuStack.push(do_ROMMenu); } // menu loop menuRunning = true; while (!menuStack.empty() && menuRunning) { Graphics->Clear(); menuStack.top()(); Graphics->Swap(); cellSysutilCheckCallback(); if(!is_running) { //BYE BYE sys_process_exit(0); } } }
[ "[email protected]@34f3eeab-e43a-e0a5-f347-2cf37759d9c2" ]
[ [ [ 1, 569 ] ] ]
c7c5aabebab9c506da920cf5a7edffeec0ba7dcb
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/obse/obse/PluginManager.h
ea30236317111e587b798f51773783fb15b481c8
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,175
h
#pragma once #include <string> #include <vector> #include "obse/PluginAPI.h" class PluginManager { public: PluginManager(); ~PluginManager(); bool Init(void); void DeInit(void); PluginInfo * GetInfoByName(const char * name); UInt32 GetNumPlugins(void); UInt32 GetBaseOpcode(UInt32 idx); PluginHandle LookupHandleFromBaseOpcode(UInt32 baseOpcode); static bool RegisterCommand(CommandInfo * _info); static void SetOpcodeBase(UInt32 opcode); static void * QueryInterface(UInt32 id); static PluginHandle GetPluginHandle(void); private: bool FindPluginDirectory(void); void InstallPlugins(void); struct LoadedPlugin { HMODULE handle; PluginInfo info; UInt32 baseOpcode; _OBSEPlugin_Query query; _OBSEPlugin_Load load; }; typedef std::vector <LoadedPlugin> LoadedPluginList; std::string m_pluginDirectory; LoadedPluginList m_plugins; static LoadedPlugin * s_currentLoadingPlugin; static PluginHandle s_currentPluginHandle; }; extern PluginManager g_pluginManager; extern CommandInfo kCommandInfo_IsPluginInstalled; extern CommandInfo kCommandInfo_GetPluginVersion;
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 54 ] ] ]
d955253c58a93abef24ddc52b35f794eec513ecd
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/vortex-client/Client.h
7206e894eced0cd0aa62003ba6e6df76ad6eb85f
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
UTF-8
C++
false
false
1,293
h
#ifndef CLIENT_H_ #define CLIENT_H_ extern "C" { #include <pthread.h> } #include "globals.h" #include "TCPClient.h" //#include "ChatManager.h" #include "EventManager.h" #include <vector> class ConnectionManagerIn; class ConnectionManagerOut; class TCPClient; class ApplicationManager; class WorldManager; class Client { private: //Thread Classes ConnectionManagerIn * connectionManagerInThread; ConnectionManagerOut * connectionManagerOutThread; WorldManager * worldManagerThread; //ChatManager * chatManagerThread; ApplicationManager * applicationManagerThread; //Event interface, has to point to a global scope variable //Clients will be registered in here by the TCPServer through the ConnectionManager TCPClient * client; public: inline void setClient(TCPClient * cli){client=cli;} inline TCPClient * getClient(){return client;} inline ConnectionManagerIn * getConnectionManagerInThread() { return connectionManagerInThread; } inline ConnectionManagerOut * getConnectionManagerOutThread() { return connectionManagerOutThread; } //inline Event * getEventManagerEvent(){return eventManagerEvent;} //Here event has to point to a global scope variable sharable by threads Client(); ~Client(); }; #endif
[ "twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
[ [ [ 1, 46 ] ] ]
afc48392fecbc4a4b2f9650b8168ca20dc296706
975d45994f670a7f284b0dc88d3a0ebe44458a82
/Docs/FINAIS/Fonte/cliente/Source/GameCore/CGameCore.cpp
816da678a3b74665c7f2d76c86da12b6ec40f743
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
ISO-8859-1
C++
false
false
37,861
cpp
#include "CGameCore.h" //----------------------------------------------------------------------------------------------------------------- CGameCore::CGameCore(int &startInit) { startInit = SUCESSO; _connected = false; _numMyChars = 0; _myUserID = -1; _myCharID = -1; _myCharSceneID = -1; _myMapSceneID = -1; _particleCount = 0; strcpy(_myLogin, ""); strcpy(_myPassword, ""); _fileCfg = new CArquivoConfig(); //_fileCfg->reset(); _gameConfig = _fileCfg->loadConfig(); /* RECT desktop; // Faz uma referência para a tela do desktop const HWND hDesktop = GetDesktopWindow(); // Captura a dimensão da tela GetWindowRect(hDesktop, &desktop); */ //_gameConfig->parametrosVideo.WindowSize.Width = 1024;//desktop.right; //_gameConfig->parametrosVideo.WindowSize.Height = 768;//desktop.bottom; //_gameConfig->parametrosVideo.Fullscreen = true; _dispositivoGrafico = createDevice(EDT_OPENGL,//EDT_DIRECT3D9, _gameConfig.parametrosVideo.WindowSize, _gameConfig.parametrosVideo.Bits, false,//_gameConfig.parametrosVideo.Fullscreen, _gameConfig.parametrosVideo.Stencilbuffer, _gameConfig.parametrosVideo.Vsync, &_gerenciadorEventos); sWidth = _gameConfig.parametrosVideo.WindowSize.Width; sHeight = _gameConfig.parametrosVideo.WindowSize.Height; if(!_dispositivoGrafico) { cout << "\nERRO 0x00: Falha ao inicializar o dispositivo grafico."; startInit = ERRO_SAIR; } if(startInit == SUCESSO) { _dispositivoAudio = createIrrKlangDevice(); if(!_dispositivoAudio) { cout << "\nERRO 0x01: Falha ao inicializar o dispositivo de audio."; startInit = ERRO_SAIR; } } _gerenciadorCena = _dispositivoGrafico->getSceneManager(); _gerenciadorVideo = _dispositivoGrafico->getVideoDriver(); _gerenciadorHud = _dispositivoGrafico->getGUIEnvironment(); _dispositivoGrafico->setWindowCaption(tituloJanela.c_str()); loadSkin(HS_PADRAO); _listaParticulas = new CListaParticulas(); _gameData = new CGameData(_dispositivoGrafico); //_gameScene = new CGameScene(); _listaPersonagens = new ListaPersonagem(); _listaBolsas = new ListaBolsa(); _fileMtx = new CArquivoMatrizes(); //_fileMtx->reset(); /* for(int i = 0; i < CS_COUNT; i++) _cutScene[i] = CVideoTexture::createVideoTexture(_dispositivoGrafico, pathCutScene[i]);*/ } //----------------------------------------------------------------------------------------------------------------- IParticleSystemSceneNode* CGameCore::addPaticleNode(TypeParticle tipo, int tempoVida, vector3df posicao, vector3df escala) { IParticleSystemSceneNode* ps = NULL; switch(tipo) { case P_FOGO: ps = _gerenciadorCena->addParticleSystemSceneNode(false); IParticleEmitter* emissor = ps->createBoxEmitter( aabbox3d<f32>(-5, 0, -5, 5, 1, 5), // tamanho do box do emissor vector3df(0.0f, 0.05f, 0.0f), // direção inicial 80, 100, // taxa de emissão SColor(0, 255, 255, 255), // cor mais escura SColor(0, 255, 255, 255), // cor mais clara (u32)tempoVida*0.4, tempoVida, 0, // idade mínima, máxima e ângulo dimension2df(5.0, 5.0), // tamanho mínimo dimension2df(10.0, 10.0)); // tamanho máximo ps->setEmitter(emissor); emissor->drop(); IParticleAffector* efeito = ps->createFadeOutParticleAffector(); ps->addAffector(efeito); efeito->drop(); ps->setPosition(posicao); ps->setScale(escala); ps->setMaterialFlag(EMF_LIGHTING, false); ps->setMaterialFlag(EMF_ZWRITE_ENABLE, false); ps->setMaterialTexture(0, _gerenciadorVideo->getTexture(pathParticleImage[P_FOGO])); ps->setMaterialType(EMT_TRANSPARENT_VERTEX_ALPHA); ps->setID(_particleCount); _listaParticulas->addElement(ps, _particleCount); _particleCount++; break; }; return ps; } //----------------------------------------------------------------------------------------------------------------- float CGameCore::getDistancia(vector3df v1, vector3df v2) { float dx = abs(v1.X - v2.X); float dz = abs(v1.Z - v2.Z); return sqrt(dx*dx + dz*dz); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::addContour(ISceneNode* oNode, f32 fThickness, SColor cColor) { if(!oNode) return; SMaterial originalMaterial[MATERIAL_MAX_TEXTURES], tempMaterial; tempMaterial.DiffuseColor = tempMaterial.SpecularColor = tempMaterial.AmbientColor = tempMaterial.EmissiveColor = cColor; tempMaterial.Lighting = true; tempMaterial.Wireframe = true; tempMaterial.Thickness = fThickness; tempMaterial.FrontfaceCulling = true; tempMaterial.BackfaceCulling = false; for(u32 i=0; i<oNode->getMaterialCount(); i++) { originalMaterial[i] = oNode->getMaterial(i); oNode->getMaterial(i) = tempMaterial; } oNode->render(); for(u32 i=0; i<oNode->getMaterialCount(); i++) oNode->getMaterial(i) = originalMaterial[i]; } //----------------------------------------------------------------------------------------------------------------- void CGameCore::contourAll(ISceneNode* node) { if (node->getType() == ESNT_MESH || node->getType() == ESNT_ANIMATED_MESH ) { if( getDistancia(node->getAbsolutePosition(), _gameCamera->getAbsolutePosition()) > 300) { node->setVisible(false); } else { node->setVisible(true); if( node->getAutomaticCulling() != EAC_OFF) addContour(node); } } list<ISceneNode*>::ConstIterator begin = node->getChildren().begin(); list<ISceneNode*>::ConstIterator end = node->getChildren().end(); for (; begin != end; ++begin) contourAll(*begin); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::drop() { if(_connected) { enviarPacote(DISCONNECT); _gameSocket->Close(); } //for(int i = 0; i < CS_COUNT; i++) // _cutScene[i]->drop(); _dispositivoGrafico->drop(); // Deleta o dispositivo grafico da memória _dispositivoAudio->drop(); // Deleta o dispositivo de audio da memória } //----------------------------------------------------------------------------------------------------------------- vector3df CGameCore::rotacaoResultante(f32 rotX, f32 rotY, f32 rotZ) { // Matrizes de rotação matrix4 mRotX; matrix4 mRotY; matrix4 mRotZ; matrix4 mRotResultante; mRotResultante.setRotationDegrees(vector3df(0, 0, 0)); // Matrizes separadas para os eixos coordenados mRotX.setRotationDegrees(vector3df(rotX, 0, 0)); mRotY.setRotationDegrees(vector3df(0, rotY, 0)); mRotZ.setRotationDegrees(vector3df(0, 0, rotZ)); // Produto de vetores mRotResultante *= mRotX; mRotResultante *= mRotY; mRotResultante *= mRotZ; return mRotResultante.getRotationDegrees(); } //----------------------------------------------------------------------------------------------------------------- IrrlichtDevice* CGameCore::getGraphicDevice() { return this->_dispositivoGrafico; } //----------------------------------------------------------------------------------------------------------------- ISoundEngine* CGameCore::getSoundDevice() { return this->_dispositivoAudio; } //----------------------------------------------------------------------------------------------------------------- CGerEventos * CGameCore::getEventManager() { return (CGerEventos*)_dispositivoGrafico->getEventReceiver(); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::getAllManagers(IrrlichtDevice*&dispGrafico, ISoundEngine*&dispAudio, CGerEventos*&gerEventos, ISceneManager*&gerCena, IVideoDriver*&gerVideo, IGUIEnvironment*&gerHud, TypeCfg &gameCfg) { dispGrafico = _dispositivoGrafico; dispAudio = _dispositivoAudio; gerEventos = (CGerEventos*)_dispositivoGrafico->getEventReceiver(); gerCena = _gerenciadorCena; gerVideo = _gerenciadorVideo; gerHud = _gerenciadorHud; gameCfg = _gameConfig = _fileCfg->loadConfig(); gerCena->clear(); // Limpa toda a cena do jogo dispAudio->removeAllSoundSources(); // Remove todos os sons pendentes } //----------------------------------------------------------------------------------------------------------------- void CGameCore::loadSkin(int idSkin) { IFileSystem* sistemaArquivos = _dispositivoGrafico->getFileSystem(); SImageGUISkinConfig hudCfg = LoadGUISkinFromFile(sistemaArquivos, _gerenciadorVideo, pathHudSkin[idSkin]); _gameSkin = new CHudImageSkin(_gerenciadorVideo, _gerenciadorHud->getSkin()); _gameSkin->loadConfig(hudCfg); _gameFont[FONT_PEQUENA] = _gerenciadorHud->getFont(pathFonts[FONT_PEQUENA]); _gameFont[FONT_GRANDE] = _gerenciadorHud->getFont(pathFonts[FONT_GRANDE]); if (_gameFont[FONT_PEQUENA] && _gameFont[FONT_GRANDE]) { _gameSkin->setFont(_gameFont[FONT_PEQUENA], EGDF_DEFAULT); // font padrão //_gameSkin->setFont(_gerenciadorHud->getBuiltInFont(), EGDF_BUTTON); // botoes _gameSkin->setFont(_gameFont[FONT_GRANDE], EGDF_WINDOW); // Titulo da janela //_gameSkin->setFont(_gerenciadorHud->getBuiltInFont(), EGDF_MENU); // itens de menu //_gameSkin->setFont(_gerenciadorHud->getBuiltInFont(), EGDF_TOOLTIP); // tooltips } _gerenciadorHud->setSkin(_gameSkin); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::playMusic( char* soundFile, bool looped, bool startPaused, bool track, E_STREAM_MODE modo, bool efeitos) { _gameMusic = _dispositivoAudio->play2D(soundFile, looped, startPaused, track, modo, efeitos); _dispositivoAudio->setSoundVolume(_gameConfig.parametrosAudio.volumeMusica); } //----------------------------------------------------------------------------------------------------------------- bool CGameCore::playCutScene( int idCutScene, int volume) { if(volume > 100) volume = 100; if(volume < 0) volume = 0; _cutScene[idCutScene]->setVolume(volume); return _cutScene[idCutScene]->playCutscene(); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::loadMenuScene(c8* sceneFile) { _gerenciadorCena->loadScene(sceneFile); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::loadGameScene(c8* sceneFile) { _gerenciadorCena->loadScene(sceneFile); if(_myMapSceneID >=0) { _sceneTerrain = (ITerrainSceneNode*)_gerenciadorCena->getSceneNodeFromType(ESNT_TERRAIN, 0); _sceneTris = _gerenciadorCena->createTerrainTriangleSelector(_sceneTerrain, 0); //createTerrainTriangleSelector (_sceneTerrain->getTriangleSelector(); _sceneTerrain->setTriangleSelector(_sceneTris); } } //----------------------------------------------------------------------------------------------------------------- ICameraSceneNode* CGameCore::createCamera( vector3df posicao, vector3df target, vector3df rotacao, ISceneNode *parent, float angulo/*bool isOrtogonal*/, bool bind) { _gameCamera = _gerenciadorCena->addCameraSceneNode(parent, posicao, target); _gameCamera->bindTargetAndRotation(bind); _gameCamera->setRotation(rotacao); /* if(angulo != 180.0f) _gameCamera->setFOV(PI / ( 180.0f / (180.0f - angulo))); else _gameCamera->setFOV(PI / ( 180.0f / (180.0f - 179.0f))); */ return _gameCamera; } //----------------------------------------------------------------------------------------------------------------- void CGameCore::createLight(ISceneNode *parent, vector3df posicao, f32 raio) { _luz = _gerenciadorCena->addLightSceneNode(parent, posicao, SColorf(1.0f, 0.6f, 0.7f, 1.0f), raio); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::loadGameData(int stage) { if(stage < LS_COUNT) { _gameData->loadStage(stage); _barraLoad->setProgress(_gameData->porcentagem/100.000); } else if(stage == LS_COUNT) _barraLoad->drop(); } //----------------------------------------------------------------------------------------------------------------- SMatrix CGameCore::loadSceneMatrix(int idScene) { _cenario = _fileMtx->getMatrix(idScene); return(_cenario); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::addBolsa(int idBolsa, float posX, float posZ) { // Inclui uma bolsa no cenário SBolsa *bolsa = new SBolsa(); bolsa->_idBolsa = idBolsa; bolsa->posicao = upd3DPosition(posX, posZ); _listaBolsas->addElement(bolsa, bolsa->_idBolsa); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::addPersonagem( CPersonagem *personagem ) { int r = personagem->_raca; int c = personagem->_classe; personagem->_modelo = _gerenciadorCena->addAnimatedMeshSceneNode(_gerenciadorCena->getMesh(pathMtxCharsModels[r][c])); personagem->_modelo->setMaterialFlag(EMF_LIGHTING, false); personagem->_modelo->setMaterialTexture(0, _gerenciadorVideo->getTexture(pathMtxCharsTextures[r][c])); personagem->_modelo->setPosition(personagem->_posicao + vector3df(0,0.2f,0)); _listaPersonagens->addElement(personagem, personagem->getId()); // TIRAR // modelo capacete capacete = _gerenciadorCena->addAnimatedMeshSceneNode(_gerenciadorCena->getMesh("recursos/modelos/i3d_elmo_barbaro.b3d"), 0, -2); capacete->setMaterialFlag(EMF_LIGHTING, false); capacete->setMaterialTexture(0, _gerenciadorVideo->getTexture("recursos/texturas/tx3d_elmo_barbaro.png")); // modelo maca maca = _gerenciadorCena->addAnimatedMeshSceneNode(_gerenciadorCena->getMesh("recursos/modelos/i3d_maca.b3d"), 0, -2); maca->setMaterialFlag(EMF_LIGHTING, false); maca->setMaterialTexture(0, _gerenciadorVideo->getTexture("recursos/texturas/tx3d_maca.png")); // joints besouro //boneCabeca = personagem->_modelo->getJointNode("visao"); //boneMao = personagem->_modelo->getJointNode("mao_L"); capacete->setPosition(vector3df(0.f,0.f,-1.5f)); capacete->setRotation(vector3df(90.f,180.f,0.f)); maca->setPosition(vector3df(-1.f,0.f,1.f)); maca->setRotation(vector3df(0.f,0.f,90.f)); // parents Besouro // boneCabeca->addChild(capacete); // boneMao->addChild(maca); capacete->setAnimationSpeed(30); maca->setAnimationSpeed(30); /////// personagem->_estado = ATAQUE2; personagem->_ultimoEstado = -1; personagem->updAnimation(true); personagem->_modelo->setAnimationSpeed(30); if(personagem->getId() == _myCharSceneID) { _myPlayerChar = personagem; _emptyCam = _gerenciadorCena->addEmptySceneNode(); _emptyCam->setPosition(_myPlayerChar->_modelo->getPosition()); _gameCamera->setParent(_emptyCam); _gameCamera->setPosition( vector3df(-20,20,0)); _gameCamera->setTarget(_emptyCam->getPosition()); } } //----------------------------------------------------------------------------------------------------------------- void CGameCore::removeBolsa(int idBolsa) { // Remove uma bolsa do cenário do cliente _listaBolsas->removeElement(idBolsa); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::removePersonagem( int idPersonagem ) { _listaPersonagens->removeElement(idPersonagem); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::updMoon(int idLua) { _sceneMoon = idLua; } //----------------------------------------------------------------------------------------------------------------- void CGameCore::updMapPortals(int idQuadPortal1, int idQuadPortal2, int idQuadPortal3, int idQuadPortal4) { _portal[0]._id = idQuadPortal1; getQuadLinhaColuna(idQuadPortal1, _portal[0]._linha, _portal[0]._coluna); _portal[0]._center = getQuadCenter(_portal[0]._linha, _portal[0]._coluna); _portal[1]._id = idQuadPortal2; getQuadLinhaColuna(idQuadPortal2, _portal[1]._linha, _portal[1]._coluna); _portal[1]._center = getQuadCenter(_portal[1]._linha, _portal[1]._coluna); _portal[2]._id = idQuadPortal3; getQuadLinhaColuna(idQuadPortal3, _portal[2]._linha, _portal[2]._coluna); _portal[2]._center = getQuadCenter(_portal[2]._linha, _portal[2]._coluna); _portal[3]._id = idQuadPortal4; getQuadLinhaColuna(idQuadPortal4, _portal[3]._linha, _portal[3]._coluna); _portal[3]._center = getQuadCenter(_portal[3]._linha, _portal[3]._coluna); } //----------------------------------------------------------------------------------------------------------------- vector3df CGameCore::getQuadCenter(int linha, int coluna) { vector3df center; center.X = (linha * TAMQUADRANTE) + (TAMQUADRANTE/2); center.Y = 0.0; center.Z = (coluna * TAMQUADRANTE) + (TAMQUADRANTE/2); return center; } //----------------------------------------------------------------------------------------------------------------- vector3df CGameCore::getQuadCenter(int idQuad) { int linha, coluna; getQuadLinhaColuna(idQuad, linha, coluna); return getQuadCenter(linha, coluna); } //----------------------------------------------------------------------------------------------------------------- vector3df CGameCore::getQuadCenter(vector3df posicao) { int linha, coluna; getQuadLinhaColuna(posicao, linha, coluna); return getQuadCenter(linha, coluna); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::getQuadLinhaColuna(vector3df posicao, int &linha, int &coluna) { linha = posicao.Z / TAMQUADRANTE; // TAMQUADRANTE é a dimensão de um quadrante em pixels coluna = posicao.X / TAMQUADRANTE; } //----------------------------------------------------------------------------------------------------------------- void CGameCore::getQuadLinhaColuna(int idQuad, int &linha, int &coluna) { linha = idQuad / MAPMAXCOL; coluna = idQuad % MAPMAXCOL; } //----------------------------------------------------------------------------------------------------------------- int CGameCore::getQuadID(vector3df posicao) { int linha, coluna; getQuadLinhaColuna(posicao, linha, coluna); return getQuadID(linha, coluna); } //----------------------------------------------------------------------------------------------------------------- int CGameCore::getQuadID(int linha, int coluna) { return ( coluna + (linha * MAPMAXCOL) ); } //----------------------------------------------------------------------------------------------------------------- bool CGameCore::conectar(char *login, char *password) { int retorno = PING_REQUEST; strcpy(_myLogin, ""); strcpy(_myPassword, ""); strcpy(_myLogin, login); strcpy(_myPassword, password); //_packageToSend.init(_dataToSend, PACKAGESIZE); // _packageReceived.init(_dataReceived, PACKAGESIZE); try { _gameSocket = new CBugSocketClient(SERVERHOST, SERVERPORT); //CBugSocketSelect::CBugSocketSelect(_gameSocket, 0, NonBlockingSocket); enviarPacote(LOGIN_REQUEST, _myLogin, _myPassword); while(retorno == PING_REQUEST) retorno = receberPacote(); } catch(...) { _connected = false; cout << "\nNão foi possivel criar o socket." << endl; } return _connected; } //-------------------------------------------------------------------------------------- void CGameCore::initToonShader() { if(_luz!= NULL && _dispositivoGrafico != NULL) _toonShader = new CToonShader(_dispositivoGrafico, _luz); } //-------------------------------------------------------------------------------------- IAnimatedMesh* CGameCore::getMAnimMesh(int idMesh) { return _gameData->dataGeometryChars[idMesh]; } //-------------------------------------------------------------------------------------- ITexture* CGameCore::getMTexture(int idTexture) { return _gameData->dataTxChars[idTexture]; } //-------------------------------------------------------------------------------------- bool CGameCore::isConnected() { return _connected; } //-------------------------------------------------------------------------------------- int CGameCore::getNumCharSlots() { return _numMyChars; } //-------------------------------------------------------------------------------------- vector3df CGameCore::upd3DPosition(float posX, float posZ) { return vector3df(posX, _sceneTerrain->getHeight(posX, posZ)+2.5f, posZ); } //-------------------------------------------------------------------------------------- int CGameCore::manhattan(int linhaO, int colunaO, int linhaD, int colunaD) { int deltaL, deltaC; deltaL = abs(linhaD - linhaO); deltaC = abs(colunaD - colunaO); return deltaL + deltaC; } //-------------------------------------------------------------------------------------- int CGameCore::pathfindingRTA(CPersonagem *personagem) { vector3df origem = personagem->_posicao; vector3df destino = personagem->_destino; int direcaoProximoPasso = -1; int idQuadSucessor = -1; int idQuadOrigem = getQuadID(origem); int idQuadDestino = getQuadID(destino); int melhorVizinho1 = -1; int melhorVizinho2 = -1; int lin_o, col_o, lin_d, col_d; int custoFuncao[8]; int custoVizinho, menorCusto1, menorCusto2; menorCusto1 = 9999999; menorCusto2 = 9999999; int custoAdjacencia = 0; float lembranca; getQuadLinhaColuna(idQuadDestino, lin_d, col_d); for (int i = 0; i < 8; i++) { getQuadLinhaColuna(idQuadOrigem, lin_o, col_o); switch (i) { default: case 0: col_o += 0; lin_o += 1; custoAdjacencia = 1; break; // Norte case 1: col_o += 1; lin_o += 1; custoAdjacencia = 2; break; // Nordeste case 2: col_o += 1; lin_o += 0; custoAdjacencia = 1; break; // Leste case 3: col_o += 1; lin_o += -1; custoAdjacencia = 2; break; // Sudeste case 4: col_o += 0; lin_o += -1; custoAdjacencia = 1; break; // Sul case 5: col_o += -1; lin_o += -1; custoAdjacencia = 2; break; // Sudoeste case 6: col_o += -1; lin_o += 0; custoAdjacencia = 1; break; // Oeste case 7: col_o += -1; lin_o += 1; custoAdjacencia = 2; break; // Noroeste } if (_cenario.isPassable[lin_o][col_o]) { idQuadSucessor = getQuadID(lin_o, col_o); // pega indice do quadrante vizinho lembranca = personagem->_memoria.Pesquisar(idQuadSucessor); // procura na memória o indice do sucessor if (lembranca == NULL) custoFuncao[i] = manhattan(lin_o, col_o, lin_d, col_d) + custoAdjacencia; else custoFuncao[i] = lembranca + custoAdjacencia; if (custoFuncao[i] < menorCusto1) { melhorVizinho2 = melhorVizinho1; menorCusto2 = menorCusto1; // atualiza o segundo menor melhorVizinho1 = idQuadSucessor; menorCusto1 = custoFuncao[i]; direcaoProximoPasso = i; } } else custoFuncao[i] = 9999999; } if (melhorVizinho2 == -1) // se teve apenas uma opção de movimento, segundo menor = menor de todos { melhorVizinho2 = melhorVizinho1; menorCusto2 = menorCusto1; } if (melhorVizinho2 != -1) // se teve alguma opção de movimento personagem->_memoria.Inserir(idQuadOrigem, menorCusto2); if(idQuadDestino == melhorVizinho1) personagem->_memoria.Reset(); return direcaoProximoPasso; } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _gameSocket->SendLine(&_packageToSend); if(packageID == DISCONNECT) Sleep(100); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, char *s1 ) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeString(s1); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, int i3) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeInt(i3); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, int i3, int i4) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeInt(i3); _packageToSend.writeInt(i4); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, int i3, int i4, int i5, int i6) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeInt(i3); _packageToSend.writeInt(i4); _packageToSend.writeInt(i5); _packageToSend.writeInt(i6); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeInt(i3); _packageToSend.writeInt(i4); _packageToSend.writeInt(i5); _packageToSend.writeInt(i6); _packageToSend.writeInt(i7); _packageToSend.writeInt(i8); _packageToSend.writeInt(i9); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, char *s1) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeString(s1); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, float f1, float f2) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeFloat(f1); _packageToSend.writeFloat(f2); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, int i1, int i2, int i3, float f1, float f2) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeInt(i1); _packageToSend.writeInt(i2); _packageToSend.writeInt(i3); _packageToSend.writeFloat(f1); _packageToSend.writeFloat(f2); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- void CGameCore::enviarPacote(int packageID, char *s1, char *s2) { //_packageToSend.init(); _packageToSend.clear(); _packageToSend.writeInt(packageID); _packageToSend.writeString(s1); _packageToSend.writeString(s2); _gameSocket->SendLine(&_packageToSend); } //----------------------------------------------------------------------------------------------------------------- int CGameCore::receberPacote() { int retorno = SUCESSO; short buffs; float x, z; int potencia; int i; CPersonagem *personagem = new CPersonagem(); //_packageReceived; //_packageReceived.init(); _packageReceived.clear(); _gameSocket->ReceiveLine(&_packageReceived); if(_packageReceived.getSize() != 0) // Se o pacote não extiver vazio { _packageReceived.beginReading(); i = _packageReceived.readInt(); switch(i) // Lê o byte de identificação do pacote { case SHOW_PERSONAGENS: // CODIGO: MOSTRAR PERSONAGENS DO JOGADOR _numMyChars = _packageReceived.readInt(); // número de personagens cadastrados for(int i=0; i<_numMyChars; i++) { _myStructChar[i]._id = _packageReceived.readInt(); _myStructChar[i]._nome = _packageReceived.readString(); _myStructChar[i]._nivel = _packageReceived.readInt(); _myStructChar[i]._agilidade = _packageReceived.readInt(); _myStructChar[i]._destreza = _packageReceived.readInt(); _myStructChar[i]._forca = _packageReceived.readInt(); _myStructChar[i]._instinto = _packageReceived.readInt(); _myStructChar[i]._resistencia = _packageReceived.readInt(); _myStructChar[i]._taxaAtaque = _packageReceived.readInt(); _myStructChar[i]._tempoCarga = _packageReceived.readInt(); _myStructChar[i]._defesa = _packageReceived.readInt(); _myStructChar[i]._ataqueCorporal = _packageReceived.readInt(); _myStructChar[i]._danoCorporal = _packageReceived.readInt(); _myStructChar[i]._raioAtaque = _packageReceived.readInt(); _myStructChar[i]._raioDano = _packageReceived.readInt(); _myStructChar[i]._idModelo = _packageReceived.readInt(); _myStructChar[i]._idTextura = _packageReceived.readInt(); _myStructChar[i]._idHud = _packageReceived.readInt(); _myChar[i] = _gerenciadorCena->addAnimatedMeshSceneNode( getMAnimMesh(_myStructChar[i]._idModelo), 0, _myStructChar[i]._id ); _myChar[i]->setMaterialFlag(EMF_LIGHTING, false); _myChar[i]->setMaterialTexture(0, _gerenciadorVideo->getTexture(pathTextureModels[_myStructChar[i]._idTextura])); // _toonShader->apply( _myChar[i], pathTextureModels[_myStructChar[i]._idTextura] ); _myChar[i]->setAnimationSpeed(5); switch (i) { case 0: _myChar[i]->setPosition(vector3df(-10,-5,30)); _myChar[i]->setRotation(vector3df(0,-10,0)); break; case 1: _myChar[i]->setPosition(vector3df(10,-5,30)); _myChar[i]->setRotation(vector3df(0,20,0)); break; }; } break; case ENTER_CENARIO: // CODIGO: ENTROU EM UM CENÁRIO COM SUCESSO. _myMapSceneID = _packageReceived.readInt(); loadGameScene(pathCenario[_myMapSceneID]); _myCharSceneID = _packageReceived.readInt(); updMapPortals(_packageReceived.readInt(), _packageReceived.readInt(), _packageReceived.readInt(), _packageReceived.readInt()); cout << "\nPersonagem entrou no cenário." << endl; break; case START_GAME_FAIL: // CODIGO: INICIALIZAÇÃO DO CENÁRIO FALHOU. enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; cout << "\nErro ao inicializar o cenário." << endl; break; case UPDATE_POSITION: // CODIGO: ATUALIZA A POSIÇÃO DE UM PERSONAGEM personagem = _listaPersonagens->getElement(_packageReceived.readInt()); x = (_packageReceived.readFloat()); z = (_packageReceived.readFloat()); personagem->_posicao = upd3DPosition(x, z); personagem->_modelo->setPosition(personagem->_posicao); personagem->_direcao = (_packageReceived.readFloat()); //cout << "\nPosição de personagem atualizada." << endl; break; case ADD_PERSONAGEM: // CODIGO: INSERÇÃO DE PERSONAGEM NO CENÁRIO personagem->_id = _packageReceived.readInt(); //personagem->_nome = new char[30]; //strcpy(personagem->_nome, _packageReceived.readString()); personagem->_posicao = upd3DPosition(_packageReceived.readFloat(), _packageReceived.readFloat()); personagem->_pv = _packageReceived.readInt(); personagem->_pp = _packageReceived.readInt(); personagem->_xp = _packageReceived.readInt(); personagem->_pvMax = _packageReceived.readInt(); personagem->_ppMax = _packageReceived.readInt(); personagem->_xpMax = _packageReceived.readInt(); personagem->_nivel = _packageReceived.readInt(); buffs = _packageReceived.readShort(); for(int i = 0; i < BUFF_COUNT; i++) { potencia = 1; for(int j = 0; j < i; j++) potencia = potencia * 2; personagem->_buff[i] = (bool)(buffs & potencia); } //for(int i=0; i<BUFF_COUNT; i++) // buffs & pow(2, i); personagem->_raca = _packageReceived.readInt(); personagem->_classe = _packageReceived.readInt(); personagem->_estado = _packageReceived.readInt(); personagem->_ultimoEstado = personagem->_estado; personagem->_velAnim = _packageReceived.readFloat(); personagem->_direcao = _packageReceived.readInt(); personagem->_idBaseArma = _packageReceived.readInt(); personagem->_idBaseArmadura = _packageReceived.readInt(); addPersonagem(personagem); break; case ADD_BOLSA: // CODIGO: ADICIONAR BOLSA AO CENÁRIO addBolsa(_packageReceived.readInt(), _packageReceived.readFloat(), _packageReceived.readFloat()); cout << "\nBolsa inserida no cenário." << endl; break; case REMOVE_BOLSA: // CODIGO: REMOVER BOLSA DO CENÁRIO removeBolsa(_packageReceived.readInt()); cout << "\nBolsa removida do cenário." << endl; break; case SCENE_FULL: // CODIGO: FALHA AO ENTRAR NO CENÁRIO. CAPACIDADE MÁXIMA ATINGIDA. cout << "\nO cenário de destino atingiu a capacidade máxima." << endl; break; case PING: // CODIGO: PING. retorno = PING_REQUEST; enviarPacote(PING); cout << "\nPing." << endl; break; case NO_LOYALTY: // CODIGO: FALHA AO ENTRAR NO CENÁRIO. FALTA LEALDADE. cout << "\nSeu personagem não possui lealdade suficiente para entrar nesse cenário." << endl; break; case PORTAL_FAIL: // CODIGO: FALHA AO CARREGAR O NOVO CENÁRIO. enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; cout << "\nFalha ao carregar o novo cenário." << endl; break; case CREATE_PLAYER_OK: // CODIGO: CRIAÇÃO DE PERSONAGEM OK cout << "\nPersonagem criado com sucesso." << endl; break; case CREATE_PLAYER_FAIL: // CODIGO: CRIAÇÃO DE PERSONAGEM FALHOU retorno = ERRO_CONTINUE; cout << "\nErro ao criar personagem." << endl; break; case DELETE_PLAYER_OK: // CODIGO: REMOÇÃO DE PERSONAGEM OK cout << "\nPersonagem excluido com sucesso." << endl; break; case DELETE_PLAYER_FAIL: // CODIGO: REMOÇÃO DE PERSONAGEM FALHOU retorno = ERRO_CONTINUE; cout << "\nErro ao excluir personagem." << endl; break; case END_FRAME: // CODIGO: FINAL DE UM CICLO DE PACOTES retorno = FINAL_PACOTES; //cout << "\nEnd-Frame." << endl; break; case LOGIN_OK: // CODIGO: LOGIN EFETUADO COM SUCESSO _myUserID = _packageReceived.readInt(); cout << "\nConectado." << endl; _connected = true; break; case LOGIN_FAIL: // CODIGO: FALHA NA AUTENTICAÇÃO DO LOGIN cout << "\nFalha ao conectar. Verificar login e senha." << endl; enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; break; case DOUBLE_LOGIN: // CODIGO: FALHA DE LOGIN SIMULTÂNEO cout << "\nErro de login simultaneo." << endl; //enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; break; case DISCONNECT: // CODIGO: RECEBEU DISCONNECT DO SERVIDOR cout << "\nO servidor te desconectou." << endl; //enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; break; default: // CODIGO: MENSAGEM NÃO IDENTIFICADA / NÃO IMPLEMENTADA cout << "\nMensagem não identificada. ID: " << i << endl; break; }; } else // CODIGO: SERVIDOR NÃO RESPONDE { cout << "\nServidor não responde." << endl; enviarPacote(DISCONNECT); _gameSocket->Close(); _connected = false; retorno = ERRO_SAIR; } return retorno; }
[ [ [ 1, 1266 ] ] ]
8a2e629885e9df73fd9befe0e6c001545486d2e5
53e5698f899750b717a1a3a4d205af422990b4a2
/core/hltimer.h
b2bc5212cb9d06b66e1e1a5e2fb440f39dad5e3a
[]
no_license
kvantetore/PyProp
e25f07e670369ad774aee6f47115e1ec0ad680d0
0fcdd3d5944de5c54c43a5205eb6e830f5edbf4c
refs/heads/master
2016-09-10T21:17:56.054886
2011-05-30T08:52:44
2011-05-30T08:52:44
462,062
7
7
null
null
null
null
UTF-8
C++
false
false
8,268
h
/* -*- C++ -*- */ /* Heap Layers: An Extensible Memory Allocation Infrastructure Copyright (C) 2000-2003 by Emery Berger http://www.cs.umass.edu/~emery [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <assert.h> #include <stdio.h> #ifndef _TIMER_H_ #define _TIMER_H_ #if !defined(__cplusplus) void createTimer (void ** timerObject); void destroyTimer (void ** timerObject); void startTimer (void ** timerObject); void stopTimer (void ** timerObject); double getTime (void ** timerObject); #else /** * @class Timer * @brief A portable class for high-resolution timing. * @author Emery Berger <http://www.cs.umass.edu/~emery> * * This class simplifies timing measurements across a number of platforms. * * @code * Timer t; * t.start(); * // do some work * t.stop(); * cout << "That took " << (double) t << " seconds." << endl; * @endcode * */ #if defined(linux) && defined(__GNUG__) #include <stdio.h> #include <limits.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <string.h> static void getTime (unsigned long& tlo, unsigned long& thi) { asm volatile ("rdtsc" : "=a"(tlo), "=d" (thi)); } static double getFrequency (void) { static double freq = 0.0; unsigned long LTime0, LTime1, HTime0, HTime1; if (freq == 0.0) { // Parse out the CPU frequency from the /proc/cpuinfo file. enum { MAX_PROCFILE_SIZE = 32768 }; const char searchStr[] = "cpu MHz : "; char line[MAX_PROCFILE_SIZE]; int fd = open ("/proc/cpuinfo", O_RDONLY); read (fd, line, MAX_PROCFILE_SIZE); char * pos = strstr (line, searchStr); if (pos == NULL) { // Compute MHz directly. // Wait for approximately one second. getTime (LTime0, HTime0); sleep (1); getTime (LTime1, HTime1); freq = (double)(LTime1 - LTime0) + (double)(UINT_MAX)*(double)(HTime1 - HTime0); if(LTime1 < LTime0) { freq -= (double)UINT_MAX; } } else { // Move the pointer over to the MHz number itself. pos += strlen(searchStr); float f; sscanf (pos, "%f", &f); freq = (double) f * 1000000.0; } } return freq; } namespace HL { class Timer { public: Timer (void) : timeElapsed (0.0) {} void start (void) { getTime (currentLo, currentHi); } void stop (void) { unsigned long lo, hi; getTime (lo, hi); double d = 0; #ifndef LONGSIZE_32BIT // if (sizeof(unsigned long) == 8) // { unsigned long current = currentLo + (currentHi << 32); unsigned long value = lo + (hi << 32); d = (double)(value - current); // } // else // { #else d = (double) (lo - currentLo) + (double) (UINT_MAX)*(double)(hi - currentHi); if (lo < currentLo) { d -= (double) UINT_MAX; } // } #endif timeElapsed = d; } operator double (void) { static double freq = getFrequency (); return timeElapsed / freq; } private: double timeElapsed; unsigned long currentLo, currentHi; }; }; #else #ifdef __SVR4 // Solaris #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <sys/procfs.h> #include <stdio.h> #endif // __SVR4 #include <time.h> #if defined(unix) || defined(__linux) #include <sys/time.h> #include <unistd.h> #endif #ifdef __sgi #include <sys/types.h> #include <sys/times.h> #include <limits.h> #endif #if defined(_WIN32) #include <windows.h> #endif #if defined(__BEOS__) #include <OS.h> #endif namespace HL { class Timer { public: /// Initializes the timer. Timer (void) #if !defined(_WIN32) : _starttime (0), _elapsedtime (0) #endif { } /// Start the timer. void start (void) { _starttime = _time(); } /// Stop the timer. void stop (void) { _elapsedtime += _time() - _starttime; } /// Reset the timer. void reset (void) { _starttime = _elapsedtime; } #if 0 // Set the timer. void set (double secs) { _starttime = 0; _elapsedtime = _sectotime (secs);} #endif /// Return the number of seconds elapsed. operator double (void) { return _timetosec (_elapsedtime); } static double currentTime (void) { TimeType t; t = _time(); return _timetosec (t); } private: // The _timer variable will be different depending on the OS. // We try to use the best timer available. #ifdef __sgi #define TIMER_FOUND long _starttime, _elapsedtime; long _time (void) { struct tms t; long ticks = times (&t); return ticks; } static double _timetosec (long t) { return ((double) (t) / CLK_TCK); } static long _sectotime (double sec) { return (long) sec * CLK_TCK; } #endif #ifdef __SVR4 // Solaris #define TIMER_FOUND typedef hrtime_t TimeType; TimeType _starttime, _elapsedtime; static TimeType _time (void) { return gethrtime(); } static TimeType _sectotime (double sec) { return (hrtime_t) (sec * 1.0e9); } static double _timetosec (TimeType& t) { return ((double) (t) / 1.0e9); } #endif // __SVR4 #if defined(MAC) || defined(macintosh) #define TIMER_FOUND double _starttime, _elapsedtime; double _time (void) { return get_Mac_microseconds(); } double _timetosec (hrtime_t& t) { return t; } #endif // MAC #ifdef _WIN32 #define TIMER_FOUND #ifndef __GNUC__ class TimeType { public: TimeType (void) { largeInt.QuadPart = 0; } operator double& (void) { return (double&) largeInt.QuadPart; } operator LARGE_INTEGER& (void) { return largeInt; } double timeToSec (void) { return (double) largeInt.QuadPart / getFreq(); } private: double getFreq (void) { QueryPerformanceFrequency (&freq); return (double) freq.QuadPart; } LARGE_INTEGER largeInt; LARGE_INTEGER freq; }; TimeType _starttime, _elapsedtime; static TimeType _time (void) { TimeType t; int r = QueryPerformanceCounter (&((LARGE_INTEGER&) t)); assert (r); return t; } static double _timetosec (TimeType& t) { return t.timeToSec(); } #else typedef DWORD TimeType; DWORD _starttime, _elapsedtime; static DWORD _time (void) { return GetTickCount(); } static double _timetosec (DWORD& t) { return (double) t / 100000.0; } static unsigned long _sectotime (double sec) { return (unsigned long)(sec); } #endif #endif // _WIN32 #ifdef __BEOS__ #define TIMER_FOUND bigtime_t _starttime, _elapsedtime; bigtime_t _time(void) { return system_time(); } double _timetosec (bigtime_t& t) { return (double) t / 1000000.0; } bigtime_t _sectotime (double sec) { return (bigtime_t)(sec * 1000000.0); } #endif // __BEOS__ #ifndef TIMER_FOUND typedef long TimeType; TimeType _starttime, _elapsedtime; static TimeType _time (void) { struct timeval t; gettimeofday (&t, NULL); return t.tv_sec * 1000000 + t.tv_usec; } static double _timetosec (TimeType t) { return ((double) (t) / 1000000.0); } static TimeType _sectotime (double sec) { return (TimeType) (sec * 1000000.0); } #endif // TIMER_FOUND #undef TIMER_FOUND }; #ifdef __SVR4 // Solaris class VirtualTimer : public Timer { public: hrtime_t _time (void) { return gethrvtime(); } }; #endif }; #endif #endif #endif
[ "tore.birkeland@354cffb3-6528-0410-8d42-45ce437ad3c5" ]
[ [ [ 1, 393 ] ] ]
262533fa487ca396b78008b774311b4759db9209
9d5310143784a780aa951492df3180b22b6410bd
/main.cpp
4fba4369d9c7940d64b42355ec72263f2e0ab19e
[]
no_license
zarvox/moussage
978c8c66c92468d9fc40d073b7a6cf8e5170f67d
6b04f355cea4dd05a2c82dc992ac7545dfee0114
refs/heads/master
2016-09-07T19:12:55.579534
2011-10-15T04:21:10
2011-10-15T04:21:10
2,573,012
1
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
#include <QApplication> #include "mousesocket.h" #include "mousemux.h" int main(int argc, char** argv) { QApplication* app = new QApplication(argc, argv); MouseSocket* ms = new MouseSocket(); MouseMux* mm = new MouseMux(); QObject::connect(ms, SIGNAL(imageUpdate(qint64,QByteArray)), mm, SLOT(imageUpdate(qint64,QByteArray))); return app->exec(); }
[ [ [ 1, 12 ] ] ]
f77dec9d3ef3982cfe6bb128f89e8d36ef1df64e
ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc
/computer_graphics/lab5/Src/Application/axes.h
d2a93e2ea6fd32960f92bd16cb5493b6f3585bd6
[]
no_license
smi13/semester07
6789be72d74d8d502f0a0d919dca07ad5cbaed0d
4d1079a446269646e1a0e3fe12e8c5e74c9bb409
refs/heads/master
2021-01-25T09:53:45.424234
2011-01-07T16:08:11
2011-01-07T16:08:11
859,509
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
#ifndef _cube_h #define _cube_h #include "object.h" namespace cg_labs { class Axes : public Object { public: Axes( const char *name, float a, DWORD Color = D3DCOLOR_XRGB(255, 0, 0), bool to_render = true ); virtual D3DPRIMITIVETYPE getPrimitiveType(); virtual void render(); virtual ~Axes(); private: }; } #endif /* _cube_h */
[ [ [ 1, 26 ] ] ]
c5233aaa23106f2a05aab585fdba82e5ecc047b4
69aab86a56c78cdfb51ab19b8f6a71274fb69fba
/Code/inc/BallsInformations.h
56bfb01633ba36e2457dfa6fc2673bd5e8acf660
[ "BSD-3-Clause" ]
permissive
zc5872061/wonderland
89882b6062b4a2d467553fc9d6da790f4df59a18
b6e0153eaa65a53abdee2b97e1289a3252b966f1
refs/heads/master
2021-01-25T10:44:13.871783
2011-08-11T20:12:36
2011-08-11T20:12:36
38,088,714
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
/* * BallsInformations.h * * Created on: 2011-01-07 * Author: artur.m */ #ifndef BALLSINFORMATIONS_H_ #define BALLSINFORMATIONS_H_ #include "Actor.h" #include "pi.h" #include "Vector.h" #include "shared_ptr.h" #include <string> #include <vector> class BallsInformations : public Actor { public: static const std::string TYPE; typedef const std::vector<Vector>& LocationsContainer; static shared_ptr<BallsInformations> spawn(const Vector& direction, float size, const Vector& position); virtual ~BallsInformations(); LocationsContainer getLocations() const; virtual std::string getType() const; private: BallsInformations(const Vector& direction, float size, const Vector& position); void preparePositions(float size, const Vector& direction); private: std::vector<Vector> m_locations; }; #endif /* BALLSINFORMATIONS_H_ */
[ [ [ 1, 43 ] ] ]
69da5984916ddab033c2c86e076c579caace9e33
77aa13a51685597585abf89b5ad30f9ef4011bde
/src/hearthstone-world/StrandOfTheAncients.h
d8eaa111e359dc45ce706736029b006ddb27c2e9
[]
no_license
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
1,828
h
/* * made by jajcer */ #ifndef _SOTA_H #define _SOTA_H static const float SOTAStartLocations[2][3] = { { 1601.004395f, -105.182663f, 8.873691f }, //attackers { 922.102234f, -111.102646f, 97.178421f }, //defenders }; class StrandOfTheAncients : public CBattleground { public: StrandOfTheAncients(MapMgrPointer mgr, uint32 id, uint32 lgroup, uint32 t); ~StrandOfTheAncients(); virtual void Init(); void HookOnPlayerDeath(PlayerPointer plr); void HookFlagDrop(PlayerPointer plr, GameObjectPointer obj); void HookFlagStand(PlayerPointer plr, GameObjectPointer obj); void HookOnMount(PlayerPointer plr); void HookOnAreaTrigger(PlayerPointer plr, uint32 id); bool HookHandleRepop(PlayerPointer plr); void OnAddPlayer(PlayerPointer plr); void OnRemovePlayer(PlayerPointer plr); void OnCreate(); void HookOnPlayerKill(PlayerPointer plr, UnitPointer pVictim); void HookOnHK(PlayerPointer plr); void HookOnShadowSight(); LocationVector GetStartingCoords(uint32 Team); static BattlegroundPointer Create(MapMgrPointer m, uint32 i, uint32 l, uint32 t) { return shared_ptr<StrandOfTheAncients>(new StrandOfTheAncients(m, i, l, t)); } const char * GetName() { return "Strand of the Ancients"; } void OnStart(); bool SupportsPlayerLoot() { return true; } bool HookSlowLockOpen(GameObjectPointer pGo, PlayerPointer pPlayer, SpellPointer pSpell); void HookGenerateLoot(PlayerPointer plr, CorpsePointer pCorpse); void SetIsWeekend(bool isweekend); void SetTime(uint32 secs, uint32 WorldState); uint32 GetRoundTime(){ return RoundTime; }; void SetRoundTime(uint32 secs){ RoundTime = secs; }; void TimeTick(); void PrepareRound(); protected: uint32 Attackers; // 0 - horde / 1 - alliance uint32 BattleRound; uint32 RoundTime; }; #endif // _SOTA_H
[ "jajcer@a6a5f009-272a-4b40-a74d-5f9816a51f88", "Aceindy@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 15 ], [ 17, 20 ], [ 23, 33 ], [ 35, 39 ], [ 41, 41 ], [ 43, 56 ] ], [ [ 16, 16 ], [ 21, 22 ], [ 34, 34 ], [ 40, 40 ], [ 42, 42 ] ] ]
6a25c0c3eca85a2b8a7e571f7fbbb9e6ceda92f7
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Gui/GuiMgr.h
35a83e3381a6498e6afd8f4a834de93409ad974c
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
1,784
h
#pragma once namespace Engine { class CoreMgr; class GuiSystemInterface; class GuiRenderInterface; class GuiEventManager; class GuiEventInstancer; class GuiMgr //: public Rocket::Core::EventListener { public: GuiMgr(CoreMgr *coreMgr, const bool &fullscr, const int &width, const int &height, const int &depth, const int &vsync, const bool &debug); ~GuiMgr(); bool isWindowOpen() const; int getWidth() const; int getHeight() const; void setCaptionText(const char *text); void swapBuffers(); void update(float dt); void render(); void resize(int w, int h); GuiEventManager *getGuiEventMgr() const { return eventMgr; } Rocket::Core::Context *addContext(const CL_String &name, const int &width, const int &height); Rocket::Core::Context *getContext(unsigned int i) { return contexts[i]; } Rocket::Core::ElementDocument *addDocument(const CL_String &context_name, const CL_String &path); void addFont(const CL_String &path); Rocket::Core::ElementDocument *loadCursor(const CL_String &path); void inject(const unsigned int &key, bool state, int key_modifier_state); void injectText(const Rocket::Core::word &key); void inject(const CL_Vec2i &mouse_pos, int key_modifier_state); void injectMouse(const int &button, bool state, int key_modifier_state); // Process the incoming event. //virtual void ProcessEvent(Rocket::Core::Event& event); private: CoreMgr *coreMgr; GuiSystemInterface *system; GuiRenderInterface *renderer; GuiEventManager *eventMgr; GuiEventInstancer *eventInstancer; std::vector<Rocket::Core::Context*> contexts; std::vector<Rocket::Core::ElementDocument*> documents; CL_Mat4f orthoMatrix; CL_Vec2i mousePos, lastMousePos; }; }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 57 ] ] ]
d571b19c0b0a3ba650d31b950a2469d6b9d26e96
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/handle.hpp
e3b0a34bffa7d2efc49903e9f1daef77a73edeed
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
3,754
hpp
// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_HANDLE_050420_HPP #define LUABIND_HANDLE_050420_HPP #include <luabind/lua_include.hpp> #include <luabind/value_wrapper.hpp> #include <luabind/detail/ref.hpp> namespace luabind { // A reference to a Lua value. Represents an entry in the // registry table. class handle { public: handle(); handle( lua_State* interpreter, int stack_index ); handle( handle const& other ); ~handle(); handle& operator=( handle const& other ); void swap( handle& other ); void push( lua_State* interpreter ) const; lua_State* interpreter() const; void replace( lua_State* interpreter, int stack_index ); private: lua_State* m_interpreter; int m_index; }; inline handle::handle() : m_interpreter( 0 ) , m_index( LUA_NOREF ) {} inline handle::handle( handle const& other ) : m_interpreter( other.m_interpreter ) , m_index( LUA_NOREF ) { if ( m_interpreter == 0 ) return; detail::getref( m_interpreter, other.m_index ); m_index = detail::ref( m_interpreter ); } inline handle::handle( lua_State* interpreter, int stack_index ) : m_interpreter( interpreter ) , m_index( LUA_NOREF ) { lua_pushvalue( interpreter, stack_index ); m_index = detail::ref( interpreter ); } inline handle::~handle() { if ( m_interpreter && m_index != LUA_NOREF ) detail::unref( m_interpreter, m_index ); } inline handle& handle::operator=( handle const& other ) { handle( other ).swap( *this ); return *this; } inline void handle::swap( handle& other ) { std::swap( m_interpreter, other.m_interpreter ); std::swap( m_index, other.m_index ); } inline void handle::push( lua_State* interpreter ) const { detail::getref( interpreter, m_index ); } inline lua_State* handle::interpreter() const { return m_interpreter; } inline void handle::replace( lua_State* interpreter, int stack_index ) { lua_pushvalue( interpreter, stack_index ); lua_rawseti( interpreter, LUA_REGISTRYINDEX, m_index ); } template<> struct value_wrapper_traits<handle> { typedef boost::mpl::true_ is_specialized; static lua_State* interpreter( handle const& value ) { return value.interpreter(); } static void unwrap( lua_State* interpreter, handle const& value ) { value.push( interpreter ); } static bool check( ... ) { return true; } }; } // namespace luabind #endif // LUABIND_HANDLE_050420_HPP
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 138 ] ] ]
33b2788f5c4bc1232f45419366ab33d1a1c5a7cd
dba70d101eb0e52373a825372e4413ed7600d84d
/RendererComplement/source/TextureManager.cpp
ef72d0c533b044359d735932e21afea203e92760
[]
no_license
nustxujun/simplerenderer
2aa269199f3bab5dc56069caa8162258e71f0f96
466a43a1e4f6e36e7d03722d0d5355395872ad86
refs/heads/master
2021-03-12T22:38:06.759909
2010-10-02T03:30:26
2010-10-02T03:30:26
32,198,944
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include "TextureManager.h" #include "Texture.h" namespace RCP { Texture* TextureManager::createTexture(unsigned int width, unsigned int height, unsigned int numMipmap,TextureType type, PixelFormat pf) { Texture* tex = new Texture(width,height, numMipmap + 1 ,type,pf, this); tex->initialize(); tex->addRef(); add((Resource*)tex); return tex; } }
[ "[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3" ]
[ [ [ 1, 14 ] ] ]
e7980d3e14dd41c0c98cad33fb838f3c0fc16389
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavtalk/telemetrymonitor.h
ddef7200bd06a801a4f66c493f4a94d7c23f7571
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,466
h
/** ****************************************************************************** * * @file telemetrymonitor.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVTalkPlugin UAVTalk Plugin * @{ * @brief The UAVTalk protocol plugin *****************************************************************************/ /* * 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 3 of the License, or * (at your option) 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. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef TELEMETRYMONITOR_H #define TELEMETRYMONITOR_H #include <QObject> #include <QQueue> #include <QTimer> #include <QTime> #include <QMutex> #include <QMutexLocker> #include "uavobjects/uavobjectmanager.h" #include "uavobjects/gcstelemetrystats.h" #include "uavobjects/flighttelemetrystats.h" #include "uavobjects/systemstats.h" #include "telemetry.h" class TelemetryMonitor : public QObject { Q_OBJECT public: TelemetryMonitor(UAVObjectManager* objMngr, Telemetry* tel); signals: void connected(); void disconnected(); public slots: void transactionCompleted(UAVObject* obj, bool success); void processStatsUpdates(); void flightStatsUpdated(UAVObject* obj); private: static const int STATS_UPDATE_PERIOD_MS = 4000; static const int STATS_CONNECT_PERIOD_MS = 1000; static const int CONNECTION_TIMEOUT_MS = 8000; UAVObjectManager* objMngr; Telemetry* tel; QQueue<UAVObject*> queue; GCSTelemetryStats* gcsStatsObj; FlightTelemetryStats* flightStatsObj; QTimer* statsTimer; UAVObject* objPending; QMutex* mutex; QTime* connectionTimer; void startRetrievingObjects(); void retrieveNextObject(); void stopRetrievingObjects(); }; #endif // TELEMETRYMONITOR_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 79 ] ] ]
b1590417991ac3bd0f6857b971808ce8bcf7a69d
3e1a7d458b265a2689e02c51847eeee2fe242b38
/mainwindow.cpp
e9ee0f26f522093008196f47ebad49aa3c219c25
[]
no_license
przenz/ramek
93b656d94b061a62c2048c29aad86c584b771ff0
9dac2ec0b97f976d00dcc8c3615d12c5a196fc8b
refs/heads/master
2020-04-03T06:10:59.748202
2011-09-07T17:16:25
2011-09-07T17:16:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,625
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFile> #include <QTextStream> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); show(); wczytajCeny(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::wczytajCeny(){ //wczytujemy ceny QString fileName = "ceny.txt"; QFile file(fileName); if ( file.open(QIODevice::ReadOnly) ){ QString line; QTextStream strim( &file ); while( !strim.atEnd() ){ line = strim.readLine(); if( line.contains("#SZKLO FLOAT") ){ line = strim.readLine(); cenaSzkloFloat=line.toFloat(); } else if( line.contains("#SZKLO ANTYREFLEKS") ){ line = strim.readLine(); cenaAntyrefleks=line.toFloat(); } else if ( line.contains("#PASPARTU") ){ line = strim.readLine(); cenaPaspartu=line.toFloat(); } else if ( line.contains("#LUSTRO") ){ line = strim.readLine(); cenaLustra=line.toFloat(); } else if ( line.contains("#KLEJENIE") ){ line = strim.readLine(); cenaKlejenia=line.toFloat(); } else if ( line.contains("#PODPORKA") ){ line = strim.readLine(); cenaPodporki=line.toFloat(); } else if ( line.contains("#DODATKOWO") ){ line = strim.readLine(); cenaDodatkowa=line.toFloat(); } } file.close(); obliczCene(); } else { setDisabled(true); QMessageBox::critical(this, tr("Blad!"),tr("Nie odnaleziono pliku z cenami (ceny.txt)!")); } } void MainWindow::wczytajEdytowaneCeny(){ cenaAntyrefleks = cenyDialog->cenaAntyrefleks; cenaDodatkowa = cenyDialog->cenaDodatkowa; cenaKlejenia = cenyDialog->cenaKlejenia; cenaLustra = cenyDialog->cenaLustra; cenaPaspartu = cenyDialog->cenaPaspartu; cenaPodporki = cenyDialog->cenaPodporki; cenaSzkloFloat = cenyDialog->cenaSzkloFloat; obliczCene(); } void MainWindow::obliczCene(){ float cena=0; float powierzchnia=0; float cenaMetra=0; float cenaOpcje=0; float cenaRamki=0; float obrazWysokosc=0; float obrazSzerokosc=0; float paspartu=0; float ramkaSzer=0; /* cenaPaspartu = 100; cenaKlejenia = 30; cenaSzkloFloat = 58; cenaAntyrefleks = 78; cenaPodporki = 5; cenaDodatkowa = 0; */ if( ui->editPaspartu->text().isEmpty() ){ //jesli NIE mamy paspartu if( !ui->editObrazSzer->text().isEmpty() && !ui->editObrazWys->text().isEmpty() ){ obrazWysokosc = ui->editObrazWys->text().toFloat()/100; obrazSzerokosc = ui->editObrazSzer->text().toFloat()/100; powierzchnia = (obrazSzerokosc) * (obrazWysokosc); } } else { //jesli mamy paspartu if( !ui->editObrazSzer->text().isEmpty() && !ui->editObrazWys->text().isEmpty() ){ obrazWysokosc = ui->editObrazWys->text().toFloat()/100; obrazSzerokosc = ui->editObrazSzer->text().toFloat()/100; paspartu = ui->editPaspartu->text().toFloat()/100; powierzchnia = ((obrazSzerokosc+(2*paspartu)))*((obrazWysokosc+(2*paspartu))); cenaMetra+=cenaPaspartu; } } //szklo int switchSzklo=0; if( ui->radioSzkloFloat->isChecked() ) { cenaMetra+=cenaSzkloFloat; switchSzklo=1; } else if( ui->radioSzkloAnty->isChecked() ){ cenaMetra+=cenaAntyrefleks; switchSzklo=2; } else if( ui->radioLustro->isChecked() ){ cenaMetra+=cenaLustra; switchSzklo=3; } else { switchSzklo=0; } //ramka if( !ui->editRamkaSzer->text().isEmpty() && !ui->editRamkaCena->text().isEmpty() ){ ramkaSzer=ui->editRamkaSzer->text().toFloat(); float calaSzerokosc = obrazSzerokosc+(paspartu*2)+(2*ramkaSzer/100); float calaWysokosc = obrazWysokosc+(paspartu*2)+(2*ramkaSzer/100); cenaRamki=2*(calaSzerokosc+calaWysokosc)*ui->editRamkaCena->text().toFloat(); } //klejenie za metr^2 if( ui->checkKlejenie->isChecked() ) cenaMetra+=cenaKlejenia; //podporka if( ui->checkPodporka->isChecked() ) cenaOpcje+=cenaPodporki; //obliczanie ceny cena = (powierzchnia*cenaMetra)+cenaRamki+cenaOpcje+cenaDodatkowa; ui->textCena->setText(QString::number(cena, 'g', 4)); ui->wizualizacja->ustawWymiary(obrazWysokosc,obrazSzerokosc,paspartu,ramkaSzer,switchSzklo); } void MainWindow::on_actionZako_triggered() { qApp->exit(0); } void MainWindow::on_actionOprogramie_triggered() { QMessageBox::information(this, tr("O programie"),tr("Program dedykuje mojej Kochanej Esterce :) \n - Mateusz")); } void MainWindow::on_actionEdytuj_ceny_triggered() { cenyDialog = new edytujCeny(this); connect(cenyDialog,SIGNAL(zapisanoCeny()),this,SLOT(wczytajCeny())); } void MainWindow::on_wyczyscButton_clicked() { ui->checkKlejenie->setChecked(false); ui->checkPodporka->setChecked(false); ui->radioSzkloFloat->setChecked(true); ui->editRamkaCena->clear(); ui->editRamkaSzer->clear(); ui->editPaspartu->clear(); ui->editObrazWys->clear(); ui->editObrazSzer->clear(); ui->editObrazWys->setFocus(); obliczCene(); }
[ [ [ 1, 181 ] ] ]
843f6e19671af36deec4a26755072c5f4fa7eb6c
7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d
/AppData/Sources/VS 6.0 Win32 MFC 6.0 dialog/Source/MainDialog.cpp
705bef35d4c0958db15ba10b7e4c7614b754f5e0
[]
no_license
SchweinDeBurg/afx-scratch
895585e98910f79127338bdca5b19c5e36921453
3181b779b4bb36ef431e5ce39e297cece1ca9cca
refs/heads/master
2021-01-19T04:50:48.770595
2011-06-18T05:14:22
2011-06-18T05:14:22
32,185,218
0
0
null
null
null
null
UTF-8
C++
false
false
2,895
cpp
// $PROJECT$ application. // Copyright (c) $YEAR$ by $AUTHOR$, // All rights reserved. // MainDialog.cpp - implementation of the CMainDialog class // initially generated by $GENERATOR$ on $DATE$ at $TIME$ // visit http://zarezky.spb.ru/projects/afx_scratch.html for more info ////////////////////////////////////////////////////////////////////////////////////////////// // PCH includes #include "stdafx.h" ////////////////////////////////////////////////////////////////////////////////////////////// // resource includes #include "Resource.h" ////////////////////////////////////////////////////////////////////////////////////////////// // other includes #include "MainDialog.h" #include "$PROJECT$App.h" ////////////////////////////////////////////////////////////////////////////////////////////// // debugging support #if defined(_DEBUG) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // _DEBUG ////////////////////////////////////////////////////////////////////////////////////////////// // object model IMPLEMENT_DYNAMIC(CMainDialog, CDialog) ////////////////////////////////////////////////////////////////////////////////////////////// // message map BEGIN_MESSAGE_MAP(CMainDialog, CDialog) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////////////////////////// // construction/destruction CMainDialog::CMainDialog(CWnd* pParentWnd): CDialog(IDD_MAIN, pParentWnd), m_hIcon(NULL), m_hSmIcon(NULL) { C$PROJECT$App* pApp = DYNAMIC_DOWNCAST(C$PROJECT$App, AfxGetApp()); ASSERT_VALID(pApp); // load dialog's icons m_hIcon = pApp->LoadIcon(IDI_APP_ICON); m_hSmIcon = pApp->LoadSmIcon(MAKEINTRESOURCE(IDI_APP_ICON)); } CMainDialog::~CMainDialog(void) { ::DestroyIcon(m_hSmIcon); ::DestroyIcon(m_hIcon); } ////////////////////////////////////////////////////////////////////////////////////////////// // overridables BOOL CMainDialog::OnInitDialog(void) { CDialog::OnInitDialog(); // set dialog's icons SetIcon(m_hIcon, TRUE); SetIcon(m_hSmIcon, FALSE); // initialized return (TRUE); } ////////////////////////////////////////////////////////////////////////////////////////////// // diagnostic services #if defined(_DEBUG) void CMainDialog::AssertValid(void) const { // first perform inherited validity check... CDialog::AssertValid(); // ...and then verify our own state as well } void CMainDialog::Dump(CDumpContext& dumpCtx) const { try { // first invoke inherited dumper... CDialog::Dump(dumpCtx); // ...and then dump own unique members dumpCtx << "m_hIcon = " << m_hIcon; dumpCtx << "\nm_hSmIcon = " << m_hSmIcon; } catch (CFileException* pXcpt) { pXcpt->ReportError(); pXcpt->Delete(); } } #endif // _DEBUG // end of file
[ "Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b" ]
[ [ [ 1, 116 ] ] ]
1029d2a713b4dd87861faaf45226097e387e7d90
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Applications/Miscellaneous/QuadToQuadMapping/QuadToQuadMapping.cpp
7c09fc611831a2db3fa18d6e771f13e67c0db771
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
13,128
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlQuadToQuadTransforms.h" #include "WmlImages.h" using namespace Wml; //---------------------------------------------------------------------------- void DoHmSqrToQuad (const Vector2f& rkP00, const Vector2f& rkP10, const Vector2f& rkP11, const Vector2f& rkP01) { HmSqrToQuadf kMap(rkP00,rkP10,rkP11,rkP01); float fXMin, fXMax, fXRange, fYMin, fYMax, fYRange; fXMax = fXMin = rkP00.X(); fYMax = fYMin = rkP00.Y(); if ( rkP10.X() < fXMin ) fXMin = rkP10.X(); if ( rkP10.X() > fXMax ) fXMax = rkP10.X(); if ( rkP10.Y() < fYMin ) fYMin = rkP10.Y(); if ( rkP10.Y() > fYMax ) fYMax = rkP10.Y(); if ( rkP11.X() < fXMin ) fXMin = rkP11.X(); if ( rkP11.X() > fXMax ) fXMax = rkP11.X(); if ( rkP11.Y() < fYMin ) fYMin = rkP11.Y(); if ( rkP11.Y() > fYMax ) fYMax = rkP11.Y(); if ( rkP01.X() < fXMin ) fXMin = rkP01.X(); if ( rkP01.X() > fXMax ) fXMax = rkP01.X(); if ( rkP01.Y() < fYMin ) fYMin = rkP01.Y(); if ( rkP01.Y() > fYMax ) fYMax = rkP01.Y(); fXRange = fXMax-fXMin; fYRange = fYMax-fYMin; int iXBase, iYBase; if ( fXRange <= fYRange ) { iYBase = 256; iXBase = (int)(256.0f*fXRange/fYRange); if ( iXBase % 2 ) iXBase++; } else { iXBase = 256; iYBase = (int)(256.0f*fYRange/fXRange); if ( iYBase % 2 ) iYBase++; } ImageUChar2D kQuad(iXBase,iYBase); kQuad = 255; int iX, iY, iXMap, iYMap; Vector2f kInput, kOutput; // transform columns of square for (iX = 0; iX < 256; iX += 16) { kInput.X() = iX/255.0f; for (iY = 0; iY < 256; iY++) { kInput.Y() = iY/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } } // transform last column kInput.X() = 1.0f; for (iY = 0; iY < 256; iY++) { kInput.Y() = iY/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } // transform rows of square for (iY = 0; iY < 256; iY += 16) { kInput.Y() = iY/255.0f; for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } } // transform last row kInput.Y() = 1.0f; for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } // transform diagonals of square for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kInput.Y() = kInput.X(); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; kInput.Y() = 1.0f-kInput.X(); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } kQuad.Save("HmSqrToQuad.im"); } //---------------------------------------------------------------------------- void DoBiSqrToQuad (const Vector2f& rkP00, const Vector2f& rkP10, const Vector2f& rkP11, const Vector2f& rkP01) { BiSqrToQuadf kMap(rkP00,rkP10,rkP11,rkP01); float fXMin, fXMax, fXRange, fYMin, fYMax, fYRange; fXMax = fXMin = rkP00.X(); fYMax = fYMin = rkP00.Y(); if ( rkP10.X() < fXMin ) fXMin = rkP10.X(); if ( rkP10.X() > fXMax ) fXMax = rkP10.X(); if ( rkP10.Y() < fYMin ) fYMin = rkP10.Y(); if ( rkP10.Y() > fYMax ) fYMax = rkP10.Y(); if ( rkP11.X() < fXMin ) fXMin = rkP11.X(); if ( rkP11.X() > fXMax ) fXMax = rkP11.X(); if ( rkP11.Y() < fYMin ) fYMin = rkP11.Y(); if ( rkP11.Y() > fYMax ) fYMax = rkP11.Y(); if ( rkP01.X() < fXMin ) fXMin = rkP01.X(); if ( rkP01.X() > fXMax ) fXMax = rkP01.X(); if ( rkP01.Y() < fYMin ) fYMin = rkP01.Y(); if ( rkP01.Y() > fYMax ) fYMax = rkP01.Y(); fXRange = fXMax-fXMin; fYRange = fYMax-fYMin; int iXBase, iYBase; if ( fXRange <= fYRange ) { iYBase = 256; iXBase = (int)(256.0f*fXRange/fYRange); if ( iXBase % 2 ) iXBase++; } else { iXBase = 256; iYBase = (int)(256.0f*fYRange/fXRange); if ( iYBase % 2 ) iYBase++; } ImageUChar2D kQuad(iXBase,iYBase); kQuad = 255; int iX, iY, iXMap, iYMap; Vector2f kInput, kOutput; // transform columns of square for (iX = 0; iX < 256; iX += 16) { kInput.X() = iX/255.0f; for (iY = 0; iY < 256; iY++) { kInput.Y() = iY/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } } // transform last column kInput.X() = 1.0f; for (iY = 0; iY < 256; iY++) { kInput.Y() = iY/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } // transform rows of square for (iY = 0; iY < 256; iY += 16) { kInput.Y() = iY/255.0f; for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } } // transform last row kInput.Y() = 1.0f; for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } // transform diagonals of square for (iX = 0; iX < 256; iX++) { kInput.X() = iX/255.0f; kInput.Y() = kInput.X(); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; kInput.Y() = 1.0f-kInput.X(); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*(kOutput.X()-fXMin)/fXRange); iYMap = int((iYBase-1)*(kOutput.Y()-fYMin)/fYRange); kQuad(iXMap,iYMap) = 0; } kQuad.Save("BiSqrToQuad.im"); } //---------------------------------------------------------------------------- void DoHmQuadToSqr (const Vector2f& rkP00, const Vector2f& rkP10, const Vector2f& rkP11, const Vector2f& rkP01) { HmQuadToSqrf kMap(rkP00,rkP10,rkP11,rkP01); float fXMin, fXMax, fXRange, fYMin, fYMax, fYRange; fXMax = fXMin = rkP00.X(); fYMax = fYMin = rkP00.Y(); if ( rkP10.X() < fXMin ) fXMin = rkP10.X(); if ( rkP10.X() > fXMax ) fXMax = rkP10.X(); if ( rkP10.Y() < fYMin ) fYMin = rkP10.Y(); if ( rkP10.Y() > fYMax ) fYMax = rkP10.Y(); if ( rkP11.X() < fXMin ) fXMin = rkP11.X(); if ( rkP11.X() > fXMax ) fXMax = rkP11.X(); if ( rkP11.Y() < fYMin ) fYMin = rkP11.Y(); if ( rkP11.Y() > fYMax ) fYMax = rkP11.Y(); if ( rkP01.X() < fXMin ) fXMin = rkP01.X(); if ( rkP01.X() > fXMax ) fXMax = rkP01.X(); if ( rkP01.Y() < fYMin ) fYMin = rkP01.Y(); if ( rkP01.Y() > fYMax ) fYMax = rkP01.Y(); fXRange = fXMax-fXMin; fYRange = fYMax-fYMin; int iXBase = 256, iYBase = 256; ImageUChar2D kSquare(iXBase,iYBase); kSquare = 255; int iX, iY, iXMap, iYMap; Vector2f kInput, kOutput; // transform columns const int iYSample = 1000; for (iX = 0; iX < 16; iX++) { kInput.X() = fXMin+fXRange*iX/15.0f; for (iY = 0; iY < iYSample; iY++) { kInput.Y() = fYMin+fYRange*iY/(iYSample-1.0f); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*kOutput.X()); iYMap = int((iYBase-1)*kOutput.Y()); if ( 0 <= iXMap && iXMap < iXBase && 0 <= iYMap && iYMap < iYBase ) { kSquare(iXMap,iYMap) = 0; } } } // transform rows const int iXSample = 1000; for (iY = 0; iY < 16; iY++) { kInput.Y() = fYMin+fYRange*iY/15.0f; for (iX = 0; iX < iXSample; iX++) { kInput.X() = fXMin+fXRange*iX/(iXSample-1.0f); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*kOutput.X()); iYMap = int((iYBase-1)*kOutput.Y()); if ( 0 <= iXMap && iXMap < iXBase && 0 <= iYMap && iYMap < iYBase ) { kSquare(iXMap,iYMap) = 0; } } } kSquare.Save("HmQuadToSqr.im"); } //---------------------------------------------------------------------------- void DoBiQuadToSqr (const Vector2f& rkP00, const Vector2f& rkP10, const Vector2f& rkP11, const Vector2f& rkP01) { BiQuadToSqrf kMap(rkP00,rkP10,rkP11,rkP01); float fXMin, fXMax, fXRange, fYMin, fYMax, fYRange; fXMax = fXMin = rkP00.X(); fYMax = fYMin = rkP00.Y(); if ( rkP10.X() < fXMin ) fXMin = rkP10.X(); if ( rkP10.X() > fXMax ) fXMax = rkP10.X(); if ( rkP10.Y() < fYMin ) fYMin = rkP10.Y(); if ( rkP10.Y() > fYMax ) fYMax = rkP10.Y(); if ( rkP11.X() < fXMin ) fXMin = rkP11.X(); if ( rkP11.X() > fXMax ) fXMax = rkP11.X(); if ( rkP11.Y() < fYMin ) fYMin = rkP11.Y(); if ( rkP11.Y() > fYMax ) fYMax = rkP11.Y(); if ( rkP01.X() < fXMin ) fXMin = rkP01.X(); if ( rkP01.X() > fXMax ) fXMax = rkP01.X(); if ( rkP01.Y() < fYMin ) fYMin = rkP01.Y(); if ( rkP01.Y() > fYMax ) fYMax = rkP01.Y(); fXRange = fXMax-fXMin; fYRange = fYMax-fYMin; int iXBase = 256, iYBase = 256; ImageUChar2D kSquare(iXBase,iYBase); kSquare = 255; int iX, iY, iXMap, iYMap; Vector2f kInput, kOutput; // transform columns const int iYSample = 1000; for (iX = 0; iX < 16; iX++) { kInput.X() = fXMin+fXRange*iX/15.0f; for (iY = 0; iY < iYSample; iY++) { kInput.Y() = fYMin+fYRange*iY/(iYSample-1.0f); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*kOutput.X()); iYMap = int((iYBase-1)*kOutput.Y()); if ( 0 <= iXMap && iXMap < iXBase && 0 <= iYMap && iYMap < iYBase ) { kSquare(iXMap,iYMap) = 0; } } } // transform rows const int iXSample = 1000; for (iY = 0; iY < 16; iY++) { kInput.Y() = fYMin+fYRange*iY/15.0f; for (iX = 0; iX < iXSample; iX++) { kInput.X() = fXMin+fXRange*iX/(iXSample-1.0f); kOutput = kMap.Transform(kInput); iXMap = int((iXBase-1)*kOutput.X()); iYMap = int((iYBase-1)*kOutput.Y()); if ( 0 <= iXMap && iXMap < iXBase && 0 <= iYMap && iYMap < iYBase ) { kSquare(iXMap,iYMap) = 0; } } } kSquare.Save("BiQuadToSqr.im"); } //---------------------------------------------------------------------------- int main () { Vector2f kP00(1.0f,1.0f); Vector2f kP10(2.0f,1.0f); Vector2f kP11(4.0f,3.0f); Vector2f kP01(1.0f,2.0f); DoHmSqrToQuad(kP00,kP10,kP11,kP01); DoBiSqrToQuad(kP00,kP10,kP11,kP01); DoHmQuadToSqr(kP00,kP10,kP11,kP01); DoBiQuadToSqr(kP00,kP10,kP11,kP01); return 0; } //----------------------------------------------------------------------------
[ [ [ 1, 418 ] ] ]
4604ecdadddb11ba50fba0c4191328f7c43772a1
eb869f3bc7728e55b5bd6ab2ad5f2a25e7f2a0a6
/S60_MCL/TMApp/inc/TraceManagerSettingList.h
f7535caaebb9b2277de6a8da32703312cb631f13
[]
no_license
runforu/musti-emulator
257420f505a519113fe7c529a3eaeda4e91d918c
0254eb549e5e0ec8e8a0a4da796b5652268aa17c
refs/heads/master
2020-05-19T07:49:09.924331
2010-11-30T06:28:37
2010-11-30T06:28:37
32,321,074
0
1
null
null
null
null
UTF-8
C++
false
false
1,772
h
/* ======================================================================== Name : TraceManagerSettingList.h Author : DH Copyright : All right is reserved! Version : E-Mail : [email protected] Description : Copyright (c) 2009-2015 DH. This material, including documentation and any related computer programs, is protected by copyright controlled BY Du Hui(DH) ======================================================================== */ #ifndef TRACEMANAGERSETTING_H #define TRACEMANAGERSETTING_H #include <aknsettingitemlist.h> class MEikCommandObserver; class TTraceManagerSettings; /** * @class CTmSettingList TraceManagerSettingList.h */ class CTmSettingList : public CAknSettingItemList { public: // constructors and destructor CTmSettingList( TTraceManagerSettings& settings, MEikCommandObserver* aCommandObserver ); virtual ~CTmSettingList(); static CTmSettingList* NewL( TTraceManagerSettings& aSettings, MEikCommandObserver* aCommandObserver ); public: // from CCoeControl void HandleResourceChange( TInt aType ); // overrides of CAknSettingItemList CAknSettingItem* CreateSettingItemL( TInt id ); void EditItemL( TInt aIndex, TBool aCalledFromMenu ); TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ); // utility function for menu void ChangeSelectedItemL(); private: // override of CAknSettingItemList void SizeChanged(); void ConstructL(); private: // current settings values TTraceManagerSettings& iSettings; MEikCommandObserver* iCommandObserver; }; #endif // TRACEMANAGERSETTING_H
[ "[email protected]@c3ffc87a-496d-339f-d77d-193528aa0bc0" ]
[ [ [ 1, 66 ] ] ]
ce1b9aec9e613cdb6e31ef85180c1bf5b87ef491
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/toolkit/nsh3/nsh3.cc
e14279ea45d9ecdf2902df80935ce1593d7f33ef
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
842
cc
//------------------------------------------------------------------------------ // nsh3.cc // (C) 2006 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "toolkit/nsh3/shellapplication.h" using namespace Tools; using namespace Util; //------------------------------------------------------------------------------ /** NOTE: we cannot use ImplementNebulaApplication here, since nsh3 is a command line tool. */ void __cdecl main(int argc, const char** argv) { CommandLineArgs args(argc, argv); ShellApplication app; app.SetCompanyName("Radon Labs GmbH"); app.SetAppTitle("Nebula3 Shell"); app.SetCmdLineArgs(args); if (app.Open()) { app.Run(); app.Close(); } app.Exit(); }
[ [ [ 1, 30 ] ] ]
4b0b38d54564324d1a39117f128da7a29f6963f3
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/ver.hpp
a16e525d77ea1b4a01dd8d25868409f5477c1360
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
UTF-8
C++
false
false
190
hpp
#ifndef VER_HPP #define VER_HPP extern char const* plugin_ver; extern char const* only_ver; extern char const* mode_only_ver; extern int build_id_ver; #endif // VER_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 8 ] ] ]
049c1aee7ded924b4759594a9d68cc042f13ce92
c58b7487c69d596d08dafba52361aab43ed25ed3
/json_test/json_spirit_utils_test.h
e149a849db9d6cc2c18f6b573e4abbebe3e0a2a1
[ "MIT" ]
permissive
deweerdt/JSON-Spirit
a2508d6272aa058ff9902c2c6494b7f1d70dec09
7dd32ece9c700c3e4a51e6c466cddcefd1054766
refs/heads/master
2020-04-04T13:14:06.281332
2009-12-07T16:13:55
2009-12-07T16:13:55
403,942
4
2
null
null
null
null
UTF-8
C++
false
false
361
h
#ifndef JASON_SPIRIT_UTILS_TEST #define JASON_SPIRIT_UTILS_TEST // Copyright John W. Wilkinson 2007 - 2009. // Distributed under the MIT License, see accompanying file LICENSE.txt // json spirit version 4.02 #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif namespace json_spirit { void test_utils(); } #endif
[ [ [ 1, 18 ] ] ]
94431ffc3497562599754474e5c3849c08b14472
96e96a73920734376fd5c90eb8979509a2da25c0
/BulletPhysics/BulletMultiThreaded/SpuNarrowPhaseCollisionTask/SpuMinkowskiPenetrationDepthSolver.cpp
662357e5167482ba1b20b2e8565f223c2006853f
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
12,083
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SpuMinkowskiPenetrationDepthSolver.h" #include "SpuVoronoiSimplexSolver.h" #include "SpuGjkPairDetector.h" #include "SpuContactResult.h" #include "SpuPreferredPenetrationDirections.h" #include "SpuCollisionShapes.h" #define NUM_UNITSPHERE_POINTS 42 static btVector3 sPenetrationDirections[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] = { btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)), btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)), btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)), btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)), btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)), btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)), btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)), btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)), btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)), btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)), btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)), btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)), btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)), btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)), btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)), btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)), btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)), btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)), btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)), btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)), btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)), btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)), btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)), btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)), btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)), btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)), btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)), btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)), btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)), btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)), btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)), btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)), btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)), btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)), btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)), btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)), btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)), btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)), btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)), btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)), btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)), btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654)) }; bool SpuMinkowskiPenetrationDepthSolver::calcPenDepth( SpuVoronoiSimplexSolver& simplexSolver, void* convexA,void* convexB,int shapeTypeA, int shapeTypeB, float marginA, float marginB, btTransform& transA,const btTransform& transB, btVector3& v, btVector3& pa, btVector3& pb, class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc, struct SpuConvexPolyhedronVertexData* convexVertexDataA, struct SpuConvexPolyhedronVertexData* convexVertexDataB ) const { (void)stackAlloc; (void)v; struct btIntermediateResult : public SpuContactResult { btIntermediateResult():m_hasResult(false) { } btVector3 m_normalOnBInWorld; btVector3 m_pointInWorld; btScalar m_depth; bool m_hasResult; virtual void setShapeIdentifiers(int partId0,int index0, int partId1,int index1) { (void)partId0; (void)index0; (void)partId1; (void)index1; } void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { m_normalOnBInWorld = normalOnBInWorld; m_pointInWorld = pointInWorld; m_depth = depth; m_hasResult = true; } }; //just take fixed number of orientation, and sample the penetration depth in that direction btScalar minProj = btScalar(BT_LARGE_FLOAT); btVector3 minNorm; btVector3 minVertex; btVector3 minA,minB; btVector3 seperatingAxisInA,seperatingAxisInB; btVector3 pInA,qInB,pWorld,qWorld,w; //#define USE_BATCHED_SUPPORT 1 #ifdef USE_BATCHED_SUPPORT btVector3 supportVerticesABatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2]; btVector3 supportVerticesBBatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2]; btVector3 seperatingAxisInABatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2]; btVector3 seperatingAxisInBBatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2]; int i; int numSampleDirections = NUM_UNITSPHERE_POINTS; for (i=0;i<numSampleDirections;i++) { const btVector3& norm = sPenetrationDirections[i]; seperatingAxisInABatch[i] = (-norm) * transA.getBasis() ; seperatingAxisInBBatch[i] = norm * transB.getBasis() ; } { int numPDA = convexA->getNumPreferredPenetrationDirections(); if (numPDA) { for (int i=0;i<numPDA;i++) { btVector3 norm; convexA->getPreferredPenetrationDirection(i,norm); norm = transA.getBasis() * norm; sPenetrationDirections[numSampleDirections] = norm; seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis(); seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis(); numSampleDirections++; } } } { int numPDB = convexB->getNumPreferredPenetrationDirections(); if (numPDB) { for (int i=0;i<numPDB;i++) { btVector3 norm; convexB->getPreferredPenetrationDirection(i,norm); norm = transB.getBasis() * norm; sPenetrationDirections[numSampleDirections] = norm; seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis(); seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis(); numSampleDirections++; } } } convexA->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInABatch,supportVerticesABatch,numSampleDirections); convexB->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInBBatch,supportVerticesBBatch,numSampleDirections); for (i=0;i<numSampleDirections;i++) { const btVector3& norm = sPenetrationDirections[i]; seperatingAxisInA = seperatingAxisInABatch[i]; seperatingAxisInB = seperatingAxisInBBatch[i]; pInA = supportVerticesABatch[i]; qInB = supportVerticesBBatch[i]; pWorld = transA(pInA); qWorld = transB(qInB); w = qWorld - pWorld; btScalar delta = norm.dot(w); //find smallest delta if (delta < minProj) { minProj = delta; minNorm = norm; minA = pWorld; minB = qWorld; } } #else int numSampleDirections = NUM_UNITSPHERE_POINTS; ///this is necessary, otherwise the normal is not correct, and sphere will rotate forever on a sloped triangle mesh #define DO_PREFERRED_DIRECTIONS 1 #ifdef DO_PREFERRED_DIRECTIONS { int numPDA = spuGetNumPreferredPenetrationDirections(shapeTypeA,convexA); if (numPDA) { for (int i=0;i<numPDA;i++) { btVector3 norm; spuGetPreferredPenetrationDirection(shapeTypeA,convexA,i,norm); norm = transA.getBasis() * norm; sPenetrationDirections[numSampleDirections] = norm; numSampleDirections++; } } } { int numPDB = spuGetNumPreferredPenetrationDirections(shapeTypeB,convexB); if (numPDB) { for (int i=0;i<numPDB;i++) { btVector3 norm; spuGetPreferredPenetrationDirection(shapeTypeB,convexB,i,norm); norm = transB.getBasis() * norm; sPenetrationDirections[numSampleDirections] = norm; numSampleDirections++; } } } #endif //DO_PREFERRED_DIRECTIONS for (int i=0;i<numSampleDirections;i++) { const btVector3& norm = sPenetrationDirections[i]; seperatingAxisInA = (-norm)* transA.getBasis(); seperatingAxisInB = norm* transB.getBasis(); pInA = localGetSupportingVertexWithoutMargin(shapeTypeA, convexA, seperatingAxisInA,convexVertexDataA);//, NULL); qInB = localGetSupportingVertexWithoutMargin(shapeTypeB, convexB, seperatingAxisInB,convexVertexDataB);//, NULL); // pInA = convexA->localGetSupportingVertexWithoutMargin(seperatingAxisInA); // qInB = convexB->localGetSupportingVertexWithoutMargin(seperatingAxisInB); pWorld = transA(pInA); qWorld = transB(qInB); w = qWorld - pWorld; btScalar delta = norm.dot(w); //find smallest delta if (delta < minProj) { minProj = delta; minNorm = norm; minA = pWorld; minB = qWorld; } } #endif //USE_BATCHED_SUPPORT //add the margins minA += minNorm*marginA; minB -= minNorm*marginB; //no penetration if (minProj < btScalar(0.)) return false; minProj += (marginA + marginB) + btScalar(1.00); //#define DEBUG_DRAW 1 #ifdef DEBUG_DRAW if (debugDraw) { btVector3 color(0,1,0); debugDraw->drawLine(minA,minB,color); color = btVector3 (1,1,1); btVector3 vec = minB-minA; btScalar prj2 = minNorm.dot(vec); debugDraw->drawLine(minA,minA+(minNorm*minProj),color); } #endif //DEBUG_DRAW SpuGjkPairDetector gjkdet(convexA,convexB,shapeTypeA,shapeTypeB,marginA,marginB,&simplexSolver,0); btScalar offsetDist = minProj; btVector3 offset = minNorm * offsetDist; SpuClosestPointInput input; input.m_convexVertexData[0] = convexVertexDataA; input.m_convexVertexData[1] = convexVertexDataB; btVector3 newOrg = transA.getOrigin() + offset; btTransform displacedTrans = transA; displacedTrans.setOrigin(newOrg); input.m_transformA = displacedTrans; input.m_transformB = transB; input.m_maximumDistanceSquared = btScalar(BT_LARGE_FLOAT);//minProj; btIntermediateResult res; gjkdet.getClosestPoints(input,res); btScalar correctedMinNorm = minProj - res.m_depth; //the penetration depth is over-estimated, relax it btScalar penetration_relaxation= btScalar(1.); minNorm*=penetration_relaxation; if (res.m_hasResult) { pa = res.m_pointInWorld - minNorm * correctedMinNorm; pb = res.m_pointInWorld; #ifdef DEBUG_DRAW if (debugDraw) { btVector3 color(1,0,0); debugDraw->drawLine(pa,pb,color); } #endif//DEBUG_DRAW } else { // could not seperate shapes //btAssert (false); } return res.m_hasResult; }
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 347 ] ] ]
a67578a1859e06baf766a8780f0f6eeb86ff4142
016774685beb74919bb4245d4d626708228e745e
/iOS/GLEssentials/ozcollide/vec3f.h
22beca2639bd5c0dd6a91ded0857d8786214cb28
[]
no_license
sutuglon/Motor
10ec08954d45565675c9b53f642f52f404cb5d4d
16f667b181b1516dc83adc0710f8f5a63b00cc75
refs/heads/master
2020-12-24T16:59:23.348677
2011-12-20T20:44:19
2011-12-20T20:44:19
1,925,770
1
0
null
null
null
null
UTF-8
C++
false
false
3,746
h
/* OZCollide - Collision Detection Library Copyright (C) 2006 Igor Kravtchenko This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact the author: [email protected] */ #ifndef OZCOLLIDE_VEC3F_H #define OZCOLLIDE_VEC3F_H #ifndef OZCOLLIDE_PCH #include <ozcollide/ozcollide.h> #endif #define ZEROVEC3F Vec3f(0, 0, 0) #define UNITVEC3F Vec3f(1, 1, 1) ENTER_NAMESPACE_OZCOLLIDE class Vec3f { public: ozinline Vec3f() { } ozinline Vec3f(float _x, float _y, float _z) : x(_x), y(_y), z(_z) { } ozinline void set(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } ozinline Vec3f operator - () const { return Vec3f(-x, -y, -z); } ozinline void operator -= (const Vec3f &_v) { x -= _v.x; y -= _v.y; z -= _v.z; } ozinline void operator += (const Vec3f &_v) { x += _v.x; y += _v.y; z += _v.z; } ozinline void operator *= (float _mul) { x *= _mul; y *= _mul; z *= _mul; } ozinline void operator *= (const Vec3f &_v) { x *= _v.x; y *= _v.y; z *= _v.z; } ozinline void operator /= (float _div) { float mul = 1.0f / _div; x *= mul; y *= mul; z *= mul; } ozinline Vec3f operator - (const Vec3f &_v) const { return Vec3f(x - _v.x, y - _v.y, z - _v.z); } ozinline Vec3f operator + (const Vec3f &_v) const { return Vec3f(x + _v.x, y + _v.y, z + _v.z); } ozinline Vec3f operator * (const Vec3f &_v) const { return Vec3f(x * _v.x, y * _v.y, z * _v.z); } ozinline Vec3f operator * (float _m) const { return Vec3f(x * _m, y * _m, z * _m); } ozinline Vec3f operator / (const Vec3f &_v) const { return Vec3f(x / _v.x, y / _v.y, z / _v.z); } ozinline Vec3f operator / (float _d) const { float m = 1.0f / _d; return Vec3f(x * m, y * m, z * m); } ozinline Vec3f operator | (const Vec3f &_d) const { return Vec3f(y * _d.z - z * _d.y, z * _d.x - x * _d.z, x * _d.y - y * _d.x); } ozinline bool operator == (const Vec3f &_v) const { if (x == _v.x && y == _v.y && z == _v.z) return true; return false; } ozinline bool operator != (const Vec3f &_v) const { if (x != _v.x || y != _v.y || z != _v.z) return true; return false; } ozinline float operator [] (int _i) const { const float *val = &x; return val[_i]; } ozinline float len() const { float len = x * x + y * y + z * z; return (float) sqrt(len); } ozinline float lenSq() const { return x * x + y * y + z * z; } ozinline float dot(const Vec3f &_v) const { return x * _v.x + y * _v.y + z * _v.z; } ozinline void normalize() { float ln = len(); if (!ln) return; float div = 1.0f / ln; x *= div; y *= div; z *= div; } ozinline void positive() { if (x < 0) x = -x; if (y < 0) y = -y; if (z < 0) z = -z; } float x, y, z; }; ozinline Vec3f operator * (float _m, const Vec3f &_v) { return Vec3f(_v.x * _m, _v.y * _m, _v.z * _m); } LEAVE_NAMESPACE #endif
[ [ [ 1, 195 ] ] ]
8dd207665a57c45c9c65c9fa0cfe84631061828a
7d5bde00c1d3f3e03a0f35ed895068f0451849b2
/treethread.h
182fe744742104c590602b2cac4590f1e15d9ac9
[]
no_license
jkackley/jeremykackley-dfjobs-improvment
6638af16515d140e9d68c7872b11b47d4f6d7587
73f53a26daa7f66143f35956150c8fe2b922c2e2
refs/heads/master
2021-01-16T01:01:38.642050
2011-05-16T18:03:23
2011-05-16T18:03:23
32,128,889
0
0
null
null
null
null
UTF-8
C++
false
false
1,645
h
/*- * Copyright (c) 2011, Derek Young * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 TREETHREAD_H #define TREETHREAD_H #include <QThread> class TreeThread : public QThread { Q_OBJECT public: void run(); void cutTree(uint32_t, uint32_t); signals: public slots: }; #endif // TREETHREAD_H
[ "Devek@localhost" ]
[ [ [ 1, 46 ] ] ]
45bcbad74942c09166f4247d83f5b747d2a1fcdf
29c5bc6757634a26ac5103f87ed068292e418d74
/src/tlclasses/CWeaponTrail.h
c2ae99dfa40aac8b1e612d9af1418591706932ce
[]
no_license
drivehappy/tlapi
d10bb75f47773e381e3ba59206ff50889de7e66a
56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9
refs/heads/master
2021-03-19T07:10:57.343889
2011-04-18T22:58:29
2011-04-18T22:58:29
32,191,364
5
0
null
null
null
null
UTF-8
C++
false
false
157
h
#pragma once #include "CRunicCore.h" namespace TLAPI { #pragma pack(1) struct CWeaponTrail : CRunicCore { }; #pragma pack() };
[ "drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522" ]
[ [ [ 1, 17 ] ] ]
3194f1d6b850af84755a1870f950d9d2636c7c8e
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-01-03/pcbnew/plotgerb.cpp
c6df8ad176a4132f7ff0aaa8cffb586e2b7ca5b0
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-2
C++
false
false
25,099
cpp
/****************************************/ /**** Routine de trace GERBER RS274X ****/ /****************************************/ #include "fctsys.h" #include "common.h" #include "plot_common.h" #include "pcbnew.h" #include "pcbplot.h" #include "trigo.h" #include "protos.h" /* Format Gerber : NOTES : Fonctions preparatoires: Gn = G01 interpolation lineaire ( trace de droites ) G02,G20,G21 Interpolation circulaire , sens trigo < 0 G03,G30,G31 Interpolation circulaire , sens trigo > 0 G04 commentaire G06 Interpolation parabolique G07 Interpolation cubique G10 interpolation lineaire ( echelle 10x ) G11 interpolation lineaire ( echelle 0.1x ) G12 interpolation lineaire ( echelle 0.01x ) G36 Start polygon description G37 End polygon description G52 plot symbole reference par Dnn code G53 plot symbole reference par Dnn ; symbole tourne de -90 degres G54 Selection d'outil G55 Mode exposition photo G56 plot symbole reference par Dnn A code G57 affiche le symbole reference sur la console G58 plot et affiche le symbole reference sur la console G60 interpolation lineaire ( echelle 100x ) G70 Unites = Inches G71 Unites = Millimetres G74 supprime interpolation circulaire sur 360 degre, revient a G01 G75 Active interpolation circulaire sur 360 degre G90 Mode Coordonnees absolues G91 Mode Coordonnees Relatives Coordonnees X,Y X,Y sont suivies de + ou - et de m+n chiffres (non separes) m = partie entiere n = partie apres la virgule formats classiques : m = 2, n = 3 (format 2.3) m = 3, n = 4 (format 3.4) ex: G__ X00345Y-06123 D__* Outils et D_CODES numero d'outil ( identification des formes ) 1 a 99 (classique) 1 a 999 D_CODES: D01 ... D9 = codes d'action: D01 = activation de lumiere ( baisser de plume) D02 = extinction de lumiere ( lever de plume) D03 = Flash D09 = VAPE Flash D51 = precede par G54 -> Select VAPE D10 ... D255 = Indentification d'outils ( d'ouvertures ) Ne sont pas tj dans l'ordre ( voir tableau ci dessous) */ #define DIM_TRAIT 120 /* largeur des traits (serigraphie,contours) en 0.1 mils */ /* Variables locales : */ static int last_D_code ; static float Gerb_scale_plot; /*Coeff de conversion d'unites des traces */ static int scale_spot_mini; /* Ouverture mini (pour remplissages) */ static D_CODE * ListeDCode; /* Pointeur sur la zone de stockage des D_CODES (typiquement adr_himem - MAX_D_CODE - 10 ) */ wxString GerberFullFileName; static double scale_x , scale_y ; /* echelles de convertion en X et Y (compte tenu des unites relatives du PCB et des traceurs*/ /* Routines Locales */ static void Init_Trace_GERBER(WinEDA_BasePcbFrame * frame, FILE * gerbfile); static void Fin_Trace_GERBER(WinEDA_BasePcbFrame * frame, FILE * gerbfile); static void Plot_1_CIRCLE_pad_GERBER(wxPoint pos,int diametre) ; static void trace_1_pastille_OVALE_GERBER(wxPoint pos, wxSize size,int orient); static void PlotRectangularPad_GERBER(wxPoint pos, wxSize size, int orient); static int get_D_code(int dx,int dy, int type, int drill ) ; static void trace_1_pad_TRAPEZE_GERBER(wxPoint pos, wxSize size,wxSize delta, int orient,int modetrace); /********************************************************************************/ void WinEDA_BasePcbFrame::Genere_GERBER(const wxString & FullFileName, int Layer) /********************************************************************************/ /* Genere les divers fichiers de trace: Pour chaque couche 1 fichier xxxc.PHO au format RS274X */ { int tracevia = 1; EraseMsgBox(); GerberFullFileName = FullFileName; g_PlotOrient = 0; if (Plot_Set_MIROIR) g_PlotOrient |= PLOT_MIROIR; /* Calcul des echelles de conversion */ Gerb_scale_plot = 1.0; /* pour unites gerber en 0,1 Mils, format 3.4 */ scale_spot_mini = (int)(spot_mini * 10 * Gerb_scale_plot); scale_x = Scale_X * Gerb_scale_plot; scale_y = Scale_Y * Gerb_scale_plot; g_PlotOffset.x = 0; g_PlotOffset.y = 0; InitPlotParametresGERBER(g_PlotOffset, scale_x, scale_y); ListeDCode = (D_CODE *) adr_himem - (MAX_D_CODE + 2 ); memset(ListeDCode, 0, sizeof(D_CODE)); /* code indiquant a la routine get_D_code la fin de la zone de description des D_CODES */ dest = wxFopen(FullFileName, wxT("wt")); if (dest == NULL) { wxString msg = _("unable to create file ") + FullFileName; DisplayError(this, msg); return ; } Affiche_1_Parametre(this, 0, _("File"),FullFileName,CYAN) ; Init_Trace_GERBER(this, dest) ; nb_plot_erreur = 0 ; int layer_mask = g_TabOneLayerMask[Layer]; switch(Layer) { case CUIVRE_N : case LAYER_N_2 : case LAYER_N_3 : case LAYER_N_4 : case LAYER_N_5 : case LAYER_N_6 : case LAYER_N_7 : case LAYER_N_8 : case LAYER_N_9 : case LAYER_N_10 : case LAYER_N_11: case LAYER_N_12: case LAYER_N_13 : case LAYER_N_14 : case LAYER_N_15 : case CMP_N : Plot_Layer_GERBER(dest,layer_mask, 0, 1); break; case SOLDERMASK_N_CU : case SOLDERMASK_N_CMP : /* Trace du vernis epargne */ if ( g_DrawViaOnMaskLayer ) tracevia = 1; else tracevia = 0; Plot_Layer_GERBER(dest, layer_mask, g_DesignSettings.m_MaskMargin, tracevia); break; case SOLDERPASTE_N_CU : case SOLDERPASTE_N_CMP : /* Trace du masque de pate de soudure */ Plot_Layer_GERBER(dest, layer_mask, 0, 0); break; default: Plot_Serigraphie(PLOT_FORMAT_GERBER,dest, layer_mask); break; } Fin_Trace_GERBER(this, dest) ; } /***********************************************************************/ void WinEDA_BasePcbFrame::Plot_Layer_GERBER(FILE * File,int masque_layer, int garde, int tracevia) /***********************************************************************/ /* Trace en format GERBER. d'une couche cuivre ou masque */ { wxPoint pos; wxSize size; MODULE * Module; D_PAD * PtPad; TRACK * track ; EDA_BaseStruct * PtStruct; wxString msg; masque_layer |= EDGE_LAYER; /* Les elements de la couche EDGE sont tj traces */ /* trace des elements type Drawings Pcb : */ PtStruct = m_Pcb->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext ) { switch( PtStruct->m_StructType ) { case TYPEDRAWSEGMENT: PlotDrawSegment( (DRAWSEGMENT*) PtStruct, PLOT_FORMAT_GERBER, masque_layer); break; case TYPETEXTE: PlotTextePcb((TEXTE_PCB*) PtStruct,PLOT_FORMAT_GERBER, masque_layer); break; case TYPECOTATION: PlotCotation((COTATION*) PtStruct, PLOT_FORMAT_GERBER, masque_layer); break; case TYPEMIRE: PlotMirePcb((MIREPCB*) PtStruct, PLOT_FORMAT_GERBER, masque_layer); break; case TYPEMARQUEUR: break; default: DisplayError(this, wxT("Type Draw non gere")); break; } } /* Trace des Elements des modules autres que pads */ nb_items = 0 ; Affiche_1_Parametre(this, 38, wxT("DrawMod"), wxEmptyString,GREEN) ; Module = m_Pcb->m_Modules; for( ; Module != NULL ;Module = (MODULE *)Module->Pnext ) { PtStruct = Module->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext ) { switch( PtStruct->m_StructType ) { case TYPEEDGEMODULE: if( masque_layer & g_TabOneLayerMask[((EDGE_MODULE*)PtStruct)->m_Layer] ) Plot_1_EdgeModule(PLOT_FORMAT_GERBER, (EDGE_MODULE*) PtStruct); break; default: break; } } } /* Trace des Elements des modules : Pastilles */ nb_items = 0 ; Affiche_1_Parametre(this, 48, wxT("Pads"),wxEmptyString,GREEN) ; Module = m_Pcb->m_Modules; for( ; Module != NULL ;Module = (MODULE *)Module->Pnext ) { PtPad = (D_PAD*) Module->m_Pads; for ( ; PtPad != NULL ; PtPad = (D_PAD*)PtPad->Pnext ) { wxPoint shape_pos; if( (PtPad->m_Masque_Layer & masque_layer) == 0) continue ; shape_pos = PtPad->ReturnShapePos(); pos =shape_pos; size.x = PtPad->m_Size.x + (garde * 2) ; size.y = PtPad->m_Size.y + (garde * 2) ; nb_items++ ; switch (PtPad->m_PadShape) { case CIRCLE : Plot_1_CIRCLE_pad_GERBER(pos,size.x) ; break ; case OVALE : { trace_1_pastille_OVALE_GERBER(pos, size,PtPad->m_Orient); break ; } case TRAPEZE : { wxSize delta = PtPad->m_DeltaSize; trace_1_pad_TRAPEZE_GERBER(pos,size, delta, PtPad->m_Orient, FILLED) ; break ; } case RECT: default: PlotRectangularPad_GERBER(pos,size, PtPad->m_Orient) ; break ; } msg.Printf( wxT("%d"),nb_items) ; Affiche_1_Parametre(this, 48,wxEmptyString, msg,GREEN) ; } } /* trace des VIAS : */ if(tracevia) { nb_items = 0 ; Affiche_1_Parametre(this, 56, wxT("Vias"), wxEmptyString,RED) ; for( track = m_Pcb->m_Track; track != NULL; track = (TRACK*) track->Pnext) { if( track->m_StructType != TYPEVIA ) continue; SEGVIA * Via = (SEGVIA *) track; /* vias not plotted if not on selected layer, but if layer == SOLDERMASK_LAYER_CU or SOLDERMASK_LAYER_CMP, vias are drawn , if they are on a external copper layer */ int via_mask_layer = Via->ReturnMaskLayer(); if ( (via_mask_layer & CUIVRE_LAYER ) ) via_mask_layer |= SOLDERMASK_LAYER_CU; if ( (via_mask_layer & CMP_LAYER ) ) via_mask_layer |= SOLDERMASK_LAYER_CMP; if( (via_mask_layer & masque_layer) == 0 ) continue; pos = Via->m_Start; size.x = size.y = Via->m_Width + (garde * 2); Plot_1_CIRCLE_pad_GERBER(pos,size.x) ; nb_items++ ; msg.Printf( wxT("%d"),nb_items) ; Affiche_1_Parametre(this, 56,wxEmptyString, msg,RED) ; } } /* trace des pistes : */ nb_items = 0 ; Affiche_1_Parametre(this, 64, wxT("Tracks"),wxEmptyString,YELLOW) ; for( track = m_Pcb->m_Track; track != NULL; track = (TRACK*) track->Pnext) { wxPoint end; if ( track->m_StructType == TYPEVIA ) continue ; if( (g_TabOneLayerMask[track->m_Layer] & masque_layer) == 0 ) continue; size.x = size.y = track->m_Width; pos = track->m_Start; end = track->m_End; PlotGERBERLine(pos,end, size.x) ; nb_items++ ; msg.Printf( wxT("%d"),nb_items) ; Affiche_1_Parametre(this, 64, wxEmptyString, msg,YELLOW) ; } /* trace des zones: */ nb_items = 0 ; if ( m_Pcb->m_Zone ) Affiche_1_Parametre(this, 72, wxT("Zones "),wxEmptyString,YELLOW) ; for( track = m_Pcb->m_Zone; track != NULL; track = (TRACK*) track->Pnext) { wxPoint end; if( (g_TabOneLayerMask[track->m_Layer] & masque_layer) == 0 ) continue; size.x = size.y = track->m_Width; pos = track->m_Start; end = track->m_End; PlotGERBERLine(pos,end, size.x) ; nb_items++ ; msg.Printf( wxT("%d"),nb_items) ; Affiche_1_Parametre(this, 72, wxEmptyString,msg,YELLOW) ; } } /**********************************************************************/ void trace_1_pastille_OVALE_GERBER(wxPoint pos, wxSize size, int orient) /**********************************************************************/ /* Trace 1 pastille OVALE en position pos_X,Y: dimensions dx,dy, orientation orient Pour une orientation verticale ou horizontale, la forme est flashee Pour une orientation quelconque la forme est tracee comme un segment */ { int ii ; int x0, y0, x1, y1, delta; if( (orient == 900) || (orient == 2700)) /* orient tournee de 90 deg */ { EXCHG(size.x,size.y); } /* Trace de la forme flashee */ if( (orient == 0) || (orient == 900) || (orient == 1800) || (orient == 2700) ) { UserToDeviceCoordinate(pos) ; UserToDeviceSize(size); ii = get_D_code(size.x,size.y,GERB_OVALE,0) ; if (ii != last_D_code ) { sprintf(cbuf,"G54D%d*\n",ref_D_CODE[ii]) ; fputs(cbuf,dest) ; last_D_code = ii ; } sprintf(cbuf,"X%5.5dY%5.5dD03*\n", pos.x, pos.y); fputs(cbuf,dest) ; } else /* Forme tracee comme un segment */ { if(size.x > size.y ) { EXCHG(size.x,size.y); orient += 900; } /* la pastille est ramenee a une pastille ovale avec dy > dx */ delta = size.y - size.x; x0 = 0; y0 = -delta / 2; x1 = 0; y1 = delta / 2; RotatePoint(&x0,&y0, orient); RotatePoint(&x1,&y1, orient); PlotGERBERLine( wxPoint(pos.x + x0, pos.y + y0), wxPoint(pos.x + x1, pos.y + y1), size.x); } } /******************************************************************/ void Plot_1_CIRCLE_pad_GERBER(wxPoint pos,int diametre) /******************************************************************/ /* Plot a circulat pad or via at the user position pos */ { int ii ; wxSize size(diametre, diametre); UserToDeviceCoordinate(pos); UserToDeviceSize(size); ii = get_D_code(size.x,size.x,GERB_CIRCLE,0) ; if (ii != last_D_code ) { sprintf(cbuf,"G54D%d*\n",ref_D_CODE[ii]) ; fputs(cbuf,dest) ; last_D_code = ii ; } sprintf(cbuf,"X%5.5dY%5.5dD03*\n", pos.x, pos.y); fputs(cbuf,dest) ; } /**************************************************************************/ void PlotRectangularPad_GERBER(wxPoint pos, wxSize size, int orient) /**************************************************************************/ /* Trace 1 pad rectangulaire d'orientation quelconque donne par son centre, ses dimensions, et son orientation Pour une orientation verticale ou horizontale, la forme est flashee Pour une orientation quelconque la forme est tracee par 4 segments de largeur 1/2 largeur pad */ { int ii ; /* Trace de la forme flashee */ switch (orient) { case 900 : case 2700 : /* la rotation de 90 ou 270 degres revient a permutter des dimensions */ EXCHG(size.x,size.y); case 1800 : case 0 : UserToDeviceCoordinate(pos) ; UserToDeviceSize(size); ii = get_D_code(size.x,size.y,GERB_RECT,0) ; if (ii != last_D_code ) { sprintf(cbuf,"G54D%d*\n",ref_D_CODE[ii]) ; fputs(cbuf,dest) ; last_D_code = ii ; } sprintf(cbuf,"X%5.5dY%5.5dD03*\n", pos.x, pos.y); fputs(cbuf,dest) ; break; default: /* Forme tracee par remplissage */ trace_1_pad_TRAPEZE_GERBER(pos, size, wxSize(0, 0), orient,FILLED); break; } } /*****************************************************************/ void trace_1_contour_GERBER(wxPoint pos, wxSize size, wxSize delta, int penwidth, int orient) /*****************************************************************/ /* Trace 1 contour rectangulaire ou trapezoidal d'orientation quelconque donne par son centre, ses dimensions , ses variations , l'epaisseur du trait, et son orientation orient */ { int ii; wxPoint coord[4]; size.x /= 2; size.y /= 2 ; delta.x /= 2; delta.y /= 2 ; /* demi dim dx et dy */ coord[0].x = pos.x - size.x - delta.y; coord[0].y = pos.y + size.y + delta.x; coord[1].x = pos.x - size.x + delta.y; coord[1].y = pos.y - size.y - delta.x; coord[2].x = pos.x + size.x - delta.y; coord[2].y = pos.y - size.y + delta.x; coord[3].x = pos.x + size.x + delta.y; coord[3].y = pos.y + size.y - delta.x; for (ii = 0; ii < 4; ii++) { RotatePoint(&coord[ii].x, &coord[ii].y, pos.x, pos.y, orient); } PlotGERBERLine( coord[0], coord[1], penwidth); PlotGERBERLine( coord[1], coord[2], penwidth); PlotGERBERLine( coord[2], coord[3], penwidth); PlotGERBERLine( coord[3], coord[0], penwidth); } /*******************************************************************/ void trace_1_pad_TRAPEZE_GERBER(wxPoint pos, wxSize size,wxSize delta, int orient,int modetrace) /*******************************************************************/ /* Trace 1 pad trapezoidal donne par : son centre pos.x,pos.y ses dimensions size.x et size.y les variations delta.x et delta.y ( 1 des deux au moins doit etre nulle) son orientation orient en 0.1 degres le mode de trace (FILLED, SKETCH, FILAIRE) Le trace n'est fait que pour un trapeze, c.a.d que delta.x ou delta.y = 0. les notation des sommets sont ( vis a vis de la table tracante ) " 0 ------------- 3 " " . . " " . O . " " . . " " 1 ---- 2 " exemple de Disposition pour delta.y > 0, delta.x = 0 " 1 ---- 2 " " . . " " . O . " " . . " " 0 ------------- 3 " exemple de Disposition pour delta.y = 0, delta.x > 0 " 0 " " . . " " . . " " . 3 " " . . " " . O . " " . . " " . 2 " " . . " " . . " " 1 " */ { int ii , jj; int dx,dy; wxPoint polygone[4]; /* coord sommets */ int coord[8]; int ddx, ddy ; /* calcul des dimensions optimales du spot choisi = 1/4 plus petite dim */ dx = size.x - abs(delta.y); dy = size.y - abs(delta.x); dx = size.x / 2; dy = size.y / 2 ; ddx = delta.x / 2; ddy = delta.y / 2 ; polygone[0].x = - dx - ddy; polygone[0].y = + dy + ddx; polygone[1].x = - dx + ddy; polygone[1].y = - dy - ddx; polygone[2].x = + dx - ddy; polygone[2].y = - dy + ddx; polygone[3].x = + dx + ddy; polygone[3].y = + dy - ddx; /* Dessin du polygone et Remplissage eventuel de l'interieur */ for (ii = 0, jj = 0; ii < 4; ii++) { RotatePoint(&polygone[ii].x, &polygone[ii].y, orient); coord[jj] = polygone[ii].x += pos.x; jj++; coord[jj] = polygone[ii].y += pos.y; jj++; } if(modetrace != FILLED ) { PlotGERBERLine( polygone[0], polygone[1], scale_spot_mini); PlotGERBERLine( polygone[1], polygone[2], scale_spot_mini); PlotGERBERLine( polygone[2], polygone[3], scale_spot_mini); PlotGERBERLine( polygone[3], polygone[0], scale_spot_mini); } else PlotPolygon_GERBER(4, coord, TRUE); } /**********************************************************/ void PlotGERBERLine(wxPoint start, wxPoint end, int large) /**********************************************************/ /* Trace 1 segment de piste : */ { int ii ; UserToDeviceCoordinate(start); UserToDeviceCoordinate(end); ii = get_D_code(large,large,GERB_LINE,0) ; if (ii != last_D_code ) { sprintf(cbuf,"G54D%d*\n",ref_D_CODE[ii]) ; fputs(cbuf,dest) ; last_D_code = ii ; } sprintf(cbuf,"X%5.5dY%5.5dD02*\n",start.x,start.y) ; fputs(cbuf,dest) ; sprintf(cbuf,"X%5.5dY%5.5dD01*\n",end.x,end.y) ; fputs(cbuf,dest) ; } /********************************************************************/ void PlotCircle_GERBER( wxPoint centre, int rayon, int epaisseur) /********************************************************************/ /* routine de trace de 1 cercle de centre centre par approximation de segments */ { int ii ; int ox, oy, fx, fy; int delta; /* increment (en 0.1 degres) angulaire pour trace de cercles */ delta = 120; /* un cercle sera trace en 3600/delta segments */ /* Correction pour petits cercles par rapport a l'epaisseur du trait */ if( rayon < (epaisseur * 10) ) delta = 225; /* 16 segm pour 360 deg */ if( rayon < (epaisseur * 5) ) delta = 300; /* 12 segm pour 360 deg */ if( rayon < (epaisseur * 2) ) delta = 600; /* 6 segm pour 360 deg */ ox = centre.x + rayon; oy = centre.y; for (ii = delta ; ii < 3600 ; ii += delta ) { fx = centre.x + (int)(rayon * fcosinus[ii]); fy = centre.y + (int)(rayon * fsinus[ii]); PlotGERBERLine(wxPoint(ox,oy), wxPoint(fx,fy), epaisseur) ; ox = fx; oy = fy; } fx = centre.x + rayon; fy = centre.y; PlotGERBERLine(wxPoint(ox,oy), wxPoint(fx,fy), epaisseur) ; } /***************************************************************/ void PlotPolygon_GERBER(int nb_segm, int * coord, bool fill) /***************************************************************/ { int ii; wxPoint pos; fputs("G36*\n", dest); pos.x = *coord; coord++; pos.y = *coord; coord++; UserToDeviceCoordinate(pos); fprintf(dest, "X%5.5dY%5.5dD02*\n", pos.x, pos.y ); for ( ii = 1; ii < nb_segm; ii++ ) { pos.x = *coord; coord++; pos.y = *coord; coord++; UserToDeviceCoordinate(pos); fprintf(dest, "X%5.5dY%5.5dD01*\n", pos.x, pos.y ); } fputs("G37*\n", dest); } /*****************************************************/ int get_D_code(int dx,int dy, int type, int drill ) /*****************************************************/ /* Fonction Recherchant et Creant eventuellement la description du D_CODE du type et dimensions demandees */ { D_CODE * ptr_tool; int num_new_D_code = 1 ; ptr_tool = ListeDCode; while(ptr_tool->dx != 0 ) { if( ( ptr_tool->dx == dx ) && ( ptr_tool->dy == dy ) && ( ptr_tool->type == type ) ) /* D_code deja existant */ return(ptr_tool->num_dcode) ; ptr_tool++ ; num_new_D_code++ ; } /* Ici de D_CODE demande n'existe pas : il va etre cree */ if( ref_D_CODE[num_new_D_code] < 0 ) { /* Tous les DCODES prevus sont epuises */ nb_plot_erreur++ ;Affiche_erreur(nb_plot_erreur) ; return (-1) ; } ptr_tool->dx = dx ; ptr_tool->dy = dy ; ptr_tool->type = type ; ptr_tool->drill = drill ; ptr_tool->num_dcode = num_new_D_code ; (ptr_tool+1)->dx = 0 ; return(ptr_tool->num_dcode) ; } /******************************************************************/ void Init_Trace_GERBER(WinEDA_BasePcbFrame * frame, FILE * gerbfile) /******************************************************************/ { char Line[1024]; memset(ListeDCode, 0, sizeof(D_CODE)); /* code indiquant a la routine get_D_code la fin de la zone de description des D_CODES */ last_D_code = 0 ; DateAndTime(Line); fprintf(gerbfile,"G04 (Genere par %s) le %s*\n",Main_Title.GetData(), Line); // Specify linear interpol (G01), unit = INCH (G70), abs format (G90): fputs("G01*\nG70*\nG90*\n", gerbfile); fputs("%MOIN*%\n", gerbfile); // set unites = INCHES /* Set gerber format to 3.4 */ strcpy(Line,"G04 Gerber Fmt 3.4, Leading zero omitted, Abs format*\n%FSLAX34Y34*%\n") ; fputs(Line,gerbfile); fputs("G04 APERTURE LIST*\n", gerbfile); } /*****************************************************************/ void Fin_Trace_GERBER(WinEDA_BasePcbFrame * frame, FILE * gerbfile) /*****************************************************************/ { char line[1024]; wxString TmpFileName, msg; FILE * outfile; fputs("M02*\n",gerbfile); fclose(gerbfile); // Reouverture gerbfile pour ajout des Apertures gerbfile = wxFopen(GerberFullFileName, wxT("rt") ); if (gerbfile == NULL) { msg.Printf( _("unable to reopen file <%s>"),GerberFullFileName.GetData() ) ; DisplayError(frame, msg); return ; } // Ouverture tmpfile TmpFileName = GerberFullFileName + wxT(".$$$"); outfile = wxFopen(TmpFileName, wxT("wt") ); if ( outfile == NULL ) { fclose(gerbfile); DisplayError(frame, wxT("Fin_Trace_GERBER(): Can't Open tmp file")); return; } // Placement des Apertures en RS274X rewind(gerbfile); while ( fgets(line, 1024, gerbfile) ) { fputs(line, outfile); if ( strcmp(strtok(line, "\n\r"),"G04 APERTURE LIST*") == 0 ) { frame->Gen_D_CODE_File(outfile); fputs("G04 APERTURE END LIST*\n", outfile); } } fclose(outfile); fclose(gerbfile); wxRemoveFile(GerberFullFileName); wxRenameFile(TmpFileName, GerberFullFileName); } /******************************************************/ int WinEDA_BasePcbFrame::Gen_D_CODE_File(FILE * penfile) /******************************************************/ /* Genere la liste courante des D_CODES Retourne le nombre de D_Codes utilises Genere une sequence RS274X */ { D_CODE * ptr_tool, * pt_lim ; int nb_dcodes = 0 ; /* Init : */ ptr_tool = ListeDCode; pt_lim = ptr_tool + MAX_D_CODE; while((ptr_tool->dx != 0 ) && (ptr_tool <= pt_lim) ) { float fscale = 0.0001; // For 3.4 format char * text; sprintf(cbuf,"%%ADD%d", ref_D_CODE[ptr_tool->num_dcode]); text = cbuf + strlen(cbuf); switch ( ptr_tool->type ) { case 1: // Circle (flash ) sprintf(text,"C,%f*%%\n", ptr_tool->dx * fscale); break; case 2: // RECT sprintf(text,"R,%fX%f*%%\n", ptr_tool->dx * fscale, ptr_tool->dy * fscale); break; case 3: // Circle ( lines ) sprintf(text,"C,%f*%%\n", ptr_tool->dx * fscale); break; case 4: // OVALE sprintf(text,"O,%fX%f*%%\n", ptr_tool->dx * fscale, ptr_tool->dy * fscale); break; default: DisplayError(this, wxT("Gen_D_CODE_File(): Dcode Type err") ); break; } // compensation localisation printf (float x.y généré x,y) to_point ( text + 2 ); fputs(cbuf,penfile) ; ptr_tool++ ; nb_dcodes++ ; } return(nb_dcodes); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 868 ] ] ]
71f9a0d33f4a2c4349460f81461b772a309b1bae
4f913cc1a50e8e649fd40313631a161234e3c59d
/NokomoSystem/BasicArithmetics.h
f17ac38f1e13d83a3ee41180d20c08902917d6ab
[]
no_license
autch/kpiadx.kpi
abb1f084163478796e202196a7411a049a76116c
f482c3871d948e71a3b3839e9066f845ecdb5915
refs/heads/master
2021-12-16T01:22:32.824315
2010-12-15T06:34:48
2010-12-15T06:34:48
1,170,398
1
0
null
null
null
null
UTF-8
C++
false
false
282
h
#pragma once #include "NokomoSystem.h" namespace Nokomo { namespace BasicArith { // absolute difference template<class T, class tmp> inline T DAbs(const T x, const T y) { tmp d = x - y; return (d >= 0) ? (T)d: (T)-d; } }; };
[ "autch@f88602a7-bc0e-0410-bfba-c07ee007e53c" ]
[ [ [ 1, 17 ] ] ]
4b207eaa363f7e12f7df0a20a14ad1f18ec1f359
4ea18bdd6e29708401219df82fd2ea63fa3e3c59
/source/Game/ActorTypes.hpp
5176eee6f5a788f2d68720ea9fdce9ef45b5065d
[]
no_license
sitc428/fyp3dgame
e4a11f027474f0eb52c711ab577034edcae86a17
6b06dc8a44d8e057336579c5e11c16b438720e63
refs/heads/master
2020-04-05T14:54:58.764314
2011-01-24T04:16:24
2011-01-24T04:16:24
32,114,726
0
0
null
null
null
null
UTF-8
C++
false
false
889
hpp
#ifndef __ACTOR_TYPES_HPP__ #define __ACTOR_TYPES_HPP__ // all the distinct types of actors we have enum EActorType { ACTOR_NONE = 0x00000000, ACTOR_CAMERA = 0x00000001, ACTOR_PLAYER = 0x00000002, ACTOR_ROBOT = 0x00000004, ACTOR_ENEMY = 0x00000008, ACTOR_PROJECTILE = 0x00000010, ACTOR_SNOWBALL = 0x00000020, ACTOR_DYNAMITE = 0x00000040, ACTOR_DYNAMITE_PICKUP = 0x00000080, ACTOR_SNOWPLOW_PICKUP = 0x00000100, ACTOR_EXPLOSION_EFFECT_SNOWBALL = 0x00000200, ACTOR_EXPLOSION_EFFECT_DYNAMITE = 0x00000400, ACTOR_LANDMINE = 0x00000800, ACTOR_ENEMY_TWO = 0x00001000, ACTOR_ENEMY_BOSS = 0x00002000, ACTOR_EXPLOSION_EFFECT_ENEMYDEATH = 0x00004000, ACTOR_INTERACTIVE = 0x0008000, ACTOR_SELLING_MACHINE = 0x0010000, ACTOR_TALKACTIVE_NPC = 0x0020000, ACTOR_TRIGGER_EVENT_ITEM = 0x0040000, ACTOR_TIMED = 0x0080000, }; #endif //__ACTOR_TYPES_HPP__
[ "[email protected]@723dad30-d554-0410-9681-1d1d8597b35f", "wd.acgrs@723dad30-d554-0410-9681-1d1d8597b35f", "[email protected]@723dad30-d554-0410-9681-1d1d8597b35f" ]
[ [ [ 1, 9 ], [ 11, 22 ], [ 28, 30 ] ], [ [ 10, 10 ], [ 23, 24 ], [ 26, 27 ] ], [ [ 25, 25 ] ] ]
dc624e8a3310d070458720c70fd94cb0d05f1ad9
b6a6fa4324540b94fb84ee68de3021a66f5efe43
/Duplo/Modules/Oscillators/SineOscillator.h
8b38dc37940fb45933f09e9f8e8acd2545cbbadb
[]
no_license
southor/duplo-scs
dbb54061704f8a2ec0514ad7d204178bfb5a290e
403cc209039484b469d602b6752f66b9e7c811de
refs/heads/master
2021-01-20T10:41:22.702098
2010-02-25T16:44:39
2010-02-25T16:44:39
34,623,992
0
0
null
null
null
null
UTF-8
C++
false
false
560
h
#ifndef _SINE_OSCILLATOR_ #define _SINE_OSCILLATOR_ #include "ContPhaseOscillator1.h" class SineOscillator : public ContPhaseOscillator1 { public: static const dup_int16 PATHID = 102; static const dup_uint16 N_INPUTS = 1; static const dup_uint16 N_OUTPUTS = 1; SineOscillator(Dup::ModuleHandler *moduleH, dup_uint32 id, Dup::MessageParser msgParser) : ContPhaseOscillator1(moduleH, id, N_INPUTS, N_OUTPUTS) { } virtual void run() { checkFreChanged(); out = Dup::sine(contPhasePos()); } }; #endif
[ "t.soderberg8@2b3d9118-3c8b-11de-9b50-8bb2048eb44c" ]
[ [ [ 1, 34 ] ] ]
c81cf15eec6c165be5c3a824079fd07d1c6bace9
f743a66d26a815034f94a0448a8f029cf0fa82b4
/main.cpp
31c1a8a8e55900f363afe42b8631087f56961fbc
[]
no_license
greevex/bassplayer
8f8cc669f6df09e43fb3cd0aee52376289635be7
6f167319d7e3ff21b661b4fc0f08b31ac31daea2
refs/heads/master
2016-09-06T03:23:24.514501
2010-05-03T05:14:21
2010-05-03T05:14:21
33,921,958
1
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
#include <QtGui/QApplication> #include "config.h" #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
[ "[email protected]@5d8c80e0-51be-f5f6-80af-d883e43c1320" ]
[ [ [ 1, 10 ] ] ]
a5ec76601d69b09d1d559ca77317828c58abaf6d
ea2ebb5e92b4391e9793c5a326d0a31758c2a0ec
/Bomberman/Bomberman/GameEngine.h
398087ee36a64be4c0e799618d4ddec3aa2e30e3
[]
no_license
weimingtom/bombman
d0f022541e9c550af7c6dbd26481771c94828460
d73ee4c680423a79826187013d343111a62f89b7
refs/heads/master
2021-01-10T01:36:39.712497
2011-05-01T07:03:16
2011-05-01T07:03:16
44,462,509
1
0
null
null
null
null
UTF-8
C++
false
false
439
h
#pragma once #include"Engine.h" #include"Scene.h" class Scene; class GameEngine: public Engine { public: GameEngine(); GameEngine(const TCHAR* windowName, bool fullScreen, int width, int height, int b):Engine(windowName, fullScreen,width, height, b) { //currentScene = new Scene(); } ~GameEngine(); protected: virtual void OnPrepare(); virtual Scene* OnGetScene(); virtual void OnKeyDown(int nVirkey); };
[ "yvetterowe1116@d9104e88-05a6-3fce-0cda-3a6fd9c40cd8" ]
[ [ [ 1, 21 ] ] ]
442273a80ad3b164b3e0bb9a40c4b2b04aaf1c0c
bc3073755ed70dd63a7c947fec63ccce408e5710
/src/Game/Graphics/Shader.cpp
fd23b8808c7945e368e75119d527c814621f9196
[]
no_license
ptrefall/ste6274gamedesign
9e659f7a8a4801c5eaa060ebe2d7edba9c31e310
7d5517aa68910877fe9aa98243f6bb2444d533c7
refs/heads/master
2016-09-07T18:42:48.012493
2011-10-13T23:41:40
2011-10-13T23:41:40
32,448,466
1
0
null
null
null
null
UTF-8
C++
false
false
2,172
cpp
#include "Shader.h" #include <GL/glew.h> #include <GL/wglew.h> using namespace Graphics; Shader::Shader(U32 id, const T_String &filename, const T_String &source) : id(id), name(filename), source(source), uniformBlockSlotBinding(0) { } Shader::~Shader() { if(name == T_String()) GL( glDeleteProgram(id); ) else GL( glDeleteShader(id); ) } void Shader::link() { GLint linked; int infologLength = 0; int charsWritten = 0; GLchar *infoLog; // Link the program object and print out the info log GL( glLinkProgram(id); ) GL( glGetProgramiv(id, GL_LINK_STATUS, &linked); ) GL( glGetProgramiv(id, GL_INFO_LOG_LENGTH, &infologLength); ) if (infologLength > 0) { infoLog = (GLchar *)malloc(infologLength); if (infoLog == NULL) printf("Could not allocate InfoLog buffer for Shader program"); GL( glGetProgramInfoLog(id, infologLength, &charsWritten, infoLog); ) if(charsWritten > 0) printf("Program InfoLog: %s", infoLog); free(infoLog); } if(!linked) throw T_Exception("Failed to link shader program!"); } void Shader::bind() { GL( glUseProgram(id); ) } void Shader::unbind() { GL( glUseProgram(0); ) } U32 Shader::createUniformBlockSlotBinding(const T_String &block_name) { for(U32 i = 0; i < block_names.size(); i++) { if(block_names[i]->name == block_name) { // Block names that are duplicate indicates that this shader should be duplicated... //CL_Console::write_line(cl_format("The shader %1 seems to require a unique copy for each instance, due to the following Uniform Block: %2", name, block_name)); return block_names[i]->slot; } } UniformBlock *block = new UniformBlock(block_name, uniformBlockSlotBinding); block_names.push_back(block); uniformBlockSlotBinding++; return block->slot; } U32 Shader::getUniformBlockSlotBinding(const T_String &block_name) { for(U32 i = 0; i < block_names.size(); i++) { if(block_names[i]->name == block_name) return block_names[i]->slot; } //CL_Console::write_line(cl_format("The shader %1 couldn't find the Uniform Block: %2", name, block_name)); return 0; }
[ "[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79" ]
[ [ [ 1, 87 ] ] ]
5102219fe03e811e40dde53e34173cb23433da37
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Mob/MobDrawer/MobDrawer.h
c5ff0df06a75486f1986fd2a21f8b77af5d832ac
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
513
h
#include <string> #include <vector> #include <exception> using namespace std; #pragma once //! 描画 /****************************************************************//** * 描画の方法を示すオブジェクト * \nosubgrouping ********************************************************************/ class MobDrawer { public: //! 描画の方法 virtual void Draw() = 0; //! このオブジェクトのコピーを返します virtual MobDrawer* Clone() = 0; };
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 23 ] ] ]
17153a360aab08ae7db64315b8367422ac0c2636
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/HUD/HUDTextEvents.cpp
05240f1bf7d93df5fcb8e16dc29f4dc329e9bd0a
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,951
cpp
#include "StdAfx.h" #include "HUD.h" #include "GameFlashAnimation.h" #include "GameFlashLogic.h" #include "HUDObituary.h" #include "GameRules.h" #include "HUDTextChat.h" #include "PlayerInput.h" #include "StringUtils.h" #include "CryPath.h" #include "IUIDraw.h" #include "GameCVars.h" #include "Menus/FlashMenuObject.h" namespace NSKeyTranslation { typedef CryFixedStringT<512> TFixedString; typedef CryFixedWStringT<512> TFixedWString; static const int MAX_KEYS = 3; SActionMapBindInfo gBindInfo = { 0, 0, 0 }; // truncate wchar_t to char template<class T> void TruncateToChar(const wchar_t* wcharString, T& outString) { outString.resize(TFixedWString::_strlen(wcharString)); char* dst = outString.begin(); const wchar_t* src = wcharString; while (char c=(char)(*src++ & 0xFF)) { *dst++ = c; } } // simple expand wchar_t to char template<class T> void ExpandToWChar(const char* charString, T& outString) { outString.resize(TFixedString::_strlen(charString)); wchar_t* dst = outString.begin(); const char* src = charString; while (const wchar_t c=(wchar_t)(*src++)) { *dst++ = c; } } bool LookupBindInfo(const char* actionMap, const char* actionName, bool bPreferXI, SActionMapBindInfo& bindInfo) { if (bindInfo.keys == 0) { bindInfo.keys = new const char*[MAX_KEYS]; for (int i=0; i<MAX_KEYS; ++i) bindInfo.keys[i] = 0; } IActionMapManager* pAmMgr = g_pGame->GetIGameFramework()->GetIActionMapManager(); if (pAmMgr == 0) return false; IActionMap* pAM = pAmMgr->GetActionMap(actionMap); if (pAM == 0) return false; ActionId actionId (actionName); bool bFound = pAM->GetBindInfo(actionId, bindInfo, MAX_KEYS); // if no XI lookup required -> return result if (!bPreferXI) return bFound; // it's either found or not found, but XI needs to be looked up anyway // we found it, so now look if there are xi keys in if (bFound) { for (int i = 0; i<bindInfo.nKeys; ++i) { const char* keyName = bindInfo.keys[i]; if (keyName && keyName[0] == 'x' && keyName[1] == 'i' && keyName[2] == '_') { // ok, this is an xi key, put it into front of list and return std::swap(bindInfo.keys[0], bindInfo.keys[i]); return true; } } } // we didn't find an XI key in the same action, so use for an action named xi_actionName CryFixedStringT<64> xiActionName ("xi_"); xiActionName+=actionName; bFound = pAM->GetBindInfo(ActionId(xiActionName.c_str()), bindInfo, MAX_KEYS); if (bFound) // ok, we found an xi action return true; // no, we didn't find an xi key nor an xi action, re-do first lookup and return bFound = pAM->GetBindInfo(actionId, bindInfo, MAX_KEYS); return bFound; } bool LookupBindInfo(const wchar_t* actionMap, const wchar_t* actionName, bool bPreferXI, SActionMapBindInfo& bindInfo) { CryFixedStringT<64> actionMapString; TruncateToChar(actionMap, actionMapString); CryFixedStringT<64> actionNameString; TruncateToChar(actionName, actionNameString); return LookupBindInfo(actionMapString.c_str(), actionNameString.c_str(), bPreferXI, bindInfo); } template<class T> void InsertString(T& inString, size_t pos, const wchar_t* s) { inString.insert(pos, s); } template<size_t S> void InsertString(CryFixedWStringT<S>& inString, size_t pos, const char* s) { CryFixedWStringT<64> wcharString; ExpandToWChar(s, wcharString); inString.insert(pos, wcharString.c_str()); } /* template<size_t S> void InsertString(CryFixedStringT<S>& inString, size_t pos, const wchar_t* s) { CryFixedStringT<64> charString; TruncateToChar(s, charString); inString.insert(pos, charString.c_str()); } template<size_t S> void InsertString(CryFixedStringT<S>& inString, size_t pos, const char* s) { inString.insert(pos, s); } */ // Replaces all occurrences of %[actionmap:actionid] with the current key binding template<size_t S> void ReplaceActions(ILocalizationManager* pLocMgr, CryFixedWStringT<S>& inString) { typedef CryFixedWStringT<S> T; static const typename T::value_type* actionPrefix = L"%["; static const size_t actionPrefixLen = T::_strlen(actionPrefix); static const typename T::value_type actionDelim = L':'; static const typename T::value_type actionDelimEnd = L']'; static const char* keyPrefix = "@cc_"; // how keys appear in the localization sheet static const size_t keyPrefixLen = strlen(keyPrefix); CryFixedStringT<32> fullKeyName; static wstring realKeyName; size_t pos = inString.find(actionPrefix, 0); const bool bPreferXI = g_pGame && g_pGame->GetMenu() && g_pGame->GetMenu()->IsControllerConnected() ? true : false; while (pos != T::npos) { size_t pos1 = inString.find(actionDelim, pos+actionPrefixLen); if (pos1 != T::npos) { size_t pos2 = inString.find(actionDelimEnd, pos1+1); if (pos2 != T::npos) { // found end of action descriptor typename T::value_type* t1 = inString.begin()+pos1; typename T::value_type* t2 = inString.begin()+pos2; *t1 = 0; *t2 = 0; const typename T::value_type* actionMapName = inString.begin()+pos+actionPrefixLen; const typename T::value_type* actionName = inString.begin()+pos1+1; // CryLogAlways("Found: '%S' '%S'", actionMapName, actionName); bool bFound = LookupBindInfo(actionMapName, actionName, bPreferXI, gBindInfo); *t1 = actionDelim; // re-replace ':' *t2 = actionDelimEnd; // re-replace ']' if (bFound && gBindInfo.nKeys >= 1) { inString.erase(pos, pos2-pos+1); const char* keyName = gBindInfo.keys[0]; // first key fullKeyName.assign(keyPrefix, keyPrefixLen); fullKeyName.append(keyName); bFound = pLocMgr->LocalizeLabel(fullKeyName.c_str(), realKeyName); if (bFound) { InsertString(inString, pos, realKeyName); } else { // not found, insert original (untranslated name from actionmap) InsertString(inString, pos, keyName); } } } } pos = inString.find(actionPrefix, pos+1); } } }; // namespace NSKeyTranslation const wchar_t* CHUD::LocalizeWithParams(const char* label, bool bAdjustActions, const char* param1, const char* param2, const char* param3, const char* param4) { static NSKeyTranslation::TFixedWString finalLocalizedString; if (label[0] == '@') { ILocalizationManager* pLocMgr = gEnv->pSystem->GetLocalizationManager(); wstring localizedString, finalString; pLocMgr->LocalizeLabel(label, localizedString); const bool bFormat = param1 || param2 || param3 || param4; if(bFormat) { wstring p1, p2, p3, p4; if(param1) { if (param1[0] == '@') pLocMgr->LocalizeLabel(param1, p1); else NSKeyTranslation::ExpandToWChar(param1, p1); } if(param2) { if (param2[0] == '@') pLocMgr->LocalizeLabel(param2, p2); else NSKeyTranslation::ExpandToWChar(param2, p2); } if(param3) { if (param3[0] == '@') pLocMgr->LocalizeLabel(param3, p3); else NSKeyTranslation::ExpandToWChar(param3, p3); } if(param4) { if (param4[0] == '@') pLocMgr->LocalizeLabel(param4, p4); else NSKeyTranslation::ExpandToWChar(param4, p4); } pLocMgr->FormatStringMessage(finalString, localizedString, p1.empty()?0:p1.c_str(), p2.empty()?0:p2.c_str(), p3.empty()?0:p3.c_str(), p4.empty()?0:p4.c_str()); } else finalString = localizedString; finalLocalizedString.assign(finalString.c_str(), finalString.length()); if (bAdjustActions) { NSKeyTranslation::ReplaceActions(pLocMgr, finalLocalizedString); } } else { // we expand always to wchar_t, as Flash will translate into wchar anyway NSKeyTranslation::ExpandToWChar(label, finalLocalizedString); // in non-localized case replace potential line-breaks finalLocalizedString.replace(L"\\n",L"\n"); if (bAdjustActions) { ILocalizationManager* pLocMgr = gEnv->pSystem->GetLocalizationManager(); NSKeyTranslation::ReplaceActions(pLocMgr, finalLocalizedString); } } return finalLocalizedString.c_str(); } void CHUD::DisplayFlashMessage(const char* label, int pos /* = 1 */, const ColorF &col /* = Col_White */, bool formatWStringWithParams /* = false */, const char* paramLabel1 /* = 0 */, const char* paramLabel2 /* = 0 */, const char* paramLabel3 /* = 0 */, const char* paramLabel4 /* = 0 */) { if(!label || m_quietMode) return; unsigned int packedColor = col.pack_rgb888(); if (pos < 1 || pos > 4) pos = 1; if(pos == 2 && m_fMiddleTextLineTimeout <= 0.0f) m_fMiddleTextLineTimeout = gEnv->pTimer->GetFrameStartTime().GetSeconds() + 3.0f; const wchar_t* localizedText = L""; if(formatWStringWithParams) localizedText = LocalizeWithParams(label, true, paramLabel1, paramLabel2, paramLabel3, paramLabel4); else localizedText = LocalizeWithParams(label, true); if(m_animSpectate.GetVisible()) m_animSpectate.Invoke("setInfoText", localizedText); else { SFlashVarValue args[3] = {localizedText, pos, packedColor}; m_animMessages.Invoke("setMessageText", args, 3); } } void CHUD::DisplayOverlayFlashMessage(const char* label, const ColorF &col /* = Col_White */, bool formatWStringWithParams /* = false */, const char* paramLabel1 /* = 0 */, const char* paramLabel2 /* = 0 */, const char* paramLabel3 /* = 0 */, const char* paramLabel4 /* = 0 */) { if(!label) return; unsigned int packedColor = col.pack_rgb888(); if(m_fOverlayTextLineTimeout <= 0.0f) m_fOverlayTextLineTimeout = gEnv->pTimer->GetFrameStartTime().GetSeconds() + 3.0f; const wchar_t* localizedText = L""; if(formatWStringWithParams) localizedText = LocalizeWithParams(label, true, paramLabel1, paramLabel2, paramLabel3, paramLabel4); else localizedText = LocalizeWithParams(label, true); SFlashVarValue args[3] = {localizedText, 2, packedColor}; // hard-coded pos 2 = middle m_animOverlayMessages.Invoke("setMessageText", args, 3); if (localizedText && *localizedText == 0) m_animOverlayMessages.SetVisible(false); else if (m_animOverlayMessages.GetVisible() == false) m_animOverlayMessages.SetVisible(true); } void CHUD::FadeOutBigOverlayFlashMessage() { if (m_bigOverlayText.empty() == false && m_animBigOverlayMessages.GetVisible()) { m_fBigOverlayTextLineTimeout = -1.0f; // this will trigger fade-out of current text m_bigOverlayText.assign(""); } } void CHUD::DisplayBigOverlayFlashMessage(const char* label, float duration, int posX, int posY, ColorF col) { if(!label) return; unsigned int packedColor = col.pack_rgb888(); const float now = gEnv->pTimer->GetFrameStartTime().GetSeconds(); if(duration <= 0.0f) m_fBigOverlayTextLineTimeout = 0.0f; else m_fBigOverlayTextLineTimeout = now + duration; const wchar_t* localizedText = L""; if (label && *label) { bool bFound = false; // see, if a gamepad is connected, then use gamepad specific messages if available const bool bLookForController = g_pGame->GetMenu() && g_pGame->GetMenu()->IsControllerConnected(); if (bLookForController && label[0] == '@') { // look for a xi_label key CryFixedStringT<128> gamePadLabel ("@GamePad_"); gamePadLabel += (label+1); // skip @ ILocalizationManager::SLocalizedInfo tempInfo; // looking up the key (without @ sign) bFound = gEnv->pSystem->GetLocalizationManager()->GetLocalizedInfo(gamePadLabel.c_str()+1, tempInfo); if (bFound) { // this one needs the @ sign in front localizedText = LocalizeWithParams(gamePadLabel.c_str(), true); } } if (!bFound) localizedText = LocalizeWithParams(label, true); } SFlashVarValue pos[2] = {posX*1024/800, posY*768/512}; m_animBigOverlayMessages.Invoke("setPosition", pos, 2); // Ok this is a big hack, so here is an explanation. // A flow graph node using that function has been created to take coordinates relative to (800,600) // First problem: 512 has been used instead of 600, certainly as a bad copy/paste or as a temporary fix // and the node stayed like this at the point it couldn't be changed (it was already used everywhere "as this") // Second problem: in aspect ratio like 5/4 or 16/9, it does not work as the flash animation (and thus text) is clipped or badly placed. // Solution: // When the animation is used for a tutorial text (posX==400), we do nothing, it should work in all resolutions. // When the animation is used for a chapter title (posX<100, at least we hope!), we just move the animation in the bottom left corner. const char *szTextAlignment = NULL; if(posX<100) { m_animBigOverlayMessages.SetDock(eFD_Left); szTextAlignment = "left"; } else { m_animBigOverlayMessages.SetDock(eFD_Center); szTextAlignment = "center"; } m_animBigOverlayMessages.RepositionFlashAnimation(); // End of the big hack SFlashVarValue args[4] = {localizedText, 2, packedColor, szTextAlignment}; // hard-coded pos 2 = middle m_animBigOverlayMessages.Invoke("setMessageText", args, 4); if (localizedText && *localizedText == 0) { if (m_bigOverlayText.empty()) m_animBigOverlayMessages.SetVisible(false); else m_fBigOverlayTextLineTimeout = -1.0f; // this will trigger fade-out of current text } else if (m_animBigOverlayMessages.GetVisible() == false) m_animBigOverlayMessages.SetVisible(true); m_bigOverlayText = label; m_bigOverlayTextColor = col; m_bigOverlayTextX = posX; m_bigOverlayTextY = posY; } void CHUD::DisplayTempFlashText(const char* label, float seconds, const ColorF &col) { if(seconds > 60.0f) seconds = 60.0f; m_fMiddleTextLineTimeout = gEnv->pTimer->GetFrameStartTime().GetSeconds() + seconds; DisplayFlashMessage(label, 2, col); } void CHUD::SetQuietMode(bool enabled) { m_quietMode = enabled; } void CHUD::BattleLogEvent(int type, const char *msg, const char *p0, const char *p1, const char *p2, const char *p3) { wstring localizedString, finalString; ILocalizationManager *pLocalizationMan = gEnv->pSystem->GetLocalizationManager(); pLocalizationMan->LocalizeString(msg, localizedString); if (p0) { wstring p0localized; pLocalizationMan->LocalizeString(p0, p0localized); wstring p1localized; if (p1) pLocalizationMan->LocalizeString(p1, p1localized); wstring p2localized; if (p2) pLocalizationMan->LocalizeString(p2, p2localized); wstring p3localized; if (p3) pLocalizationMan->LocalizeString(p3, p3localized); pLocalizationMan->FormatStringMessage(finalString, localizedString, p0localized.empty()?0:p0localized.c_str(), p1localized.empty()?0:p1localized.c_str(), p2localized.empty()?0:p2localized.c_str(), p3localized.empty()?0:p3localized.c_str()); } else finalString=localizedString; const static int maxCharsInBattleLogLine = 50; int numLines = 1 + (finalString.length() / maxCharsInBattleLogLine); if(numLines > 1) { wstring partStringA = finalString.substr(0, maxCharsInBattleLogLine); wstring partStringB = finalString.substr(maxCharsInBattleLogLine, finalString.size()); SFlashVarValue argsA[2] = {partStringA.c_str(), type}; m_animBattleLog.Invoke("setMPLogText", argsA, 2); SFlashVarValue argsB[2] = {partStringB.c_str(), 0}; m_animBattleLog.Invoke("setMPLogText", argsB, 2); } else { SFlashVarValue args[2] = {finalString.c_str(), type}; m_animBattleLog.Invoke("setMPLogText", args, 2); } } const char *CHUD::GetPlayerRank(EntityId playerId, bool shortName) { if (CGameRules *pGameRules=g_pGame->GetGameRules()) { int rank=0; if(IScriptTable *pGameRulesTable=pGameRules->GetEntity()->GetScriptTable()) { HSCRIPTFUNCTION pfnGetPlayerRank=0; if(pGameRulesTable->GetValue("GetPlayerRank", pfnGetPlayerRank) && pfnGetPlayerRank) { Script::CallReturn(gEnv->pScriptSystem,pfnGetPlayerRank,pGameRulesTable,ScriptHandle(playerId), rank); gEnv->pScriptSystem->ReleaseFunc(pfnGetPlayerRank); } } static string rankFormatter; if(rank) { if (!shortName) rankFormatter.Format("@ui_rank_%d", rank); else rankFormatter.Format("@ui_short_rank_%d", rank); return rankFormatter.c_str(); } } return 0; } // returns ptr to static string buffer. const char* GetSoundKey(const char* soundName) { static string buf; static const char* prefix = "Languages/dialog/"; static const int prefixLen = strlen(prefix); buf.assign("@"); // check if it already starts Languages/dialog. then replace it if (CryStringUtils::stristr(soundName, prefix) == soundName) { buf.append (soundName+prefixLen); } else { buf.append (soundName); } PathUtil::RemoveExtension(buf); return buf.c_str(); } void CHUD::ShowSubtitle(ISound *pSound, bool bShow) { assert (pSound != 0); if (pSound == 0) return; const char* soundKey = GetSoundKey(pSound->GetName()); InternalShowSubtitle(soundKey, pSound, bShow); } void CHUD::ShowSubtitle(const char* subtitleLabel, bool bShow) { InternalShowSubtitle(subtitleLabel, 0, bShow); } void CHUD::SubtitleCreateChunks(CHUD::SSubtitleEntry& entry, const wstring& localizedString) { // no time, no chunks if (entry.timeRemaining <= 0.0f) return; // look for tokens const wchar_t token[] = { L"##" }; const size_t tokenLen = (sizeof(token) / sizeof(token[0])) - 1; size_t len = localizedString.length(); size_t startPos = 0; size_t pos = localizedString.find(token, 0); size_t nChunks = 0; size_t MAX_CHUNKS = 10; static const bool bIgnoreSpecialCharsAfterToken = true; while (pos != wstring::npos) { SSubtitleEntry::Chunk& chunk = entry.chunks[nChunks]; chunk.start = startPos; chunk.len = pos-startPos; ++nChunks; if (nChunks == MAX_CHUNKS-1) { GameWarning("CHUD::SubtitleCreateChunks: Localization Entry '%s' exceeds max. number of chunks [%d]", entry.key.c_str(), MAX_CHUNKS); break; } startPos = pos+tokenLen; if (bIgnoreSpecialCharsAfterToken) { // currently ignore line-breaks and spaces after token ## size_t found = localizedString.find_first_not_of(L"\n ", startPos); startPos = found != wstring::npos ? found : startPos; } pos = localizedString.find(token, startPos); } // care about the last one, but only if we found at least one // otherwise there is no splitter at all, and it's only one chunk if (nChunks > 0) { { SSubtitleEntry::Chunk& chunk = entry.chunks[nChunks]; chunk.start = startPos; chunk.len = len-startPos; } ++nChunks; // now we have the total number of chunks, calc the string length without tokens size_t realCharLength = len - (nChunks-1) * tokenLen; float time = entry.timeRemaining; for (size_t i=0; i<nChunks; ++i) { SSubtitleEntry::Chunk& chunk = entry.chunks[i]; chunk = entry.chunks[i]; size_t realPos = chunk.start - i * tokenLen; // calculated with respect to realCharLength float pos = (float) realPos / (float) realCharLength; // pos = [0,1] chunk.time = time - time * pos; // we put in the remaining time if (g_pGameCVars->hud_subtitlesDebug) { wstring s = localizedString.substr(chunk.start, chunk.len); CryLogAlways("[SUB] %s chunk=%d time=%f '%S'", entry.key.c_str(), i, chunk.time, s.c_str()); } } entry.localized = localizedString; entry.nCurChunk = -1; } entry.nChunks = nChunks; /* static const bool bDebug = true; if (bDebug && entry.nChunks > 0) { CryLogAlways("Key: %s SoundLength=%f NumChunks=%d", entry.key.c_str(), entry.timeRemaining, entry.nChunks); CryFixedWStringT<128> tmp; for (size_t i=0; i<entry.nChunks; ++i) { SSubtitleEntry::Chunk& chunk = entry.chunks[i]; tmp.assign(entry.localized.c_str(), chunk.start, chunk.len); CryLogAlways("Chunk %d: Time=%f S=%d L=%d Text=%S", i, chunk.time, chunk.start, chunk.len, tmp.c_str()); } } */ } namespace { // language specific rules for CharacterName : Text struct LanguageCharacterPrefix { const char* language; const wchar_t* prefix; }; LanguageCharacterPrefix g_languageCharacterPrefixes[] = { { "French", L" : " }, }; size_t g_languageCharacterPrefixesCount = sizeof(g_languageCharacterPrefixes) / sizeof(g_languageCharacterPrefixes[0]); }; void CHUD::SubtitleAssignCharacterName(CHUD::SSubtitleEntry& entry) { if (g_pGame->GetCVars()->hud_subtitlesShowCharName) { const char* subtitleLabel = entry.key.c_str(); ILocalizationManager* pLocMgr = gEnv->pSystem->GetLocalizationManager(); ILocalizationManager::SLocalizedInfo locInfo; const char* key = (*subtitleLabel == '@') ? subtitleLabel+1 : subtitleLabel; if (pLocMgr->GetLocalizedInfo(key, locInfo) == true && locInfo.sWho && *locInfo.sWho) { entry.localized.assign(locInfo.sWho); const wchar_t* charPrefix = L": "; // assign language specific character name prefix const char* currentLanguage = pLocMgr->GetLanguage(); for (int i = 0; i < g_languageCharacterPrefixesCount; ++i) { if (stricmp(g_languageCharacterPrefixes[i].language, currentLanguage) == 0) { charPrefix = g_languageCharacterPrefixes[i].prefix; break; } } entry.localized.append(charPrefix); } } } void CHUD::SubtitleAppendCharacterName(const CHUD::SSubtitleEntry& entry, CryFixedWStringT<1024>& locString) { if (g_pGame->GetCVars()->hud_subtitlesShowCharName) { const char* subtitleLabel = entry.key.c_str(); ILocalizationManager* pLocMgr = gEnv->pSystem->GetLocalizationManager(); ILocalizationManager::SLocalizedInfo locInfo; const char* key = (*subtitleLabel == '@') ? subtitleLabel+1 : subtitleLabel; if (pLocMgr->GetLocalizedInfo(key, locInfo) == true && locInfo.sWho && *locInfo.sWho) { locString.append(locInfo.sWho); locString.append(L": "); } } } void CHUD::InternalShowSubtitle(const char* subtitleLabel, ISound* pSound, bool bShow) { ILocalizationManager* pLocMgr = gEnv->pSystem->GetLocalizationManager(); if (bShow) { TSubtitleEntries::iterator iter = std::find(m_subtitleEntries.begin(), m_subtitleEntries.end(), subtitleLabel); if (iter == m_subtitleEntries.end()) { wstring localizedString; const bool bFound = pLocMgr->GetSubtitle(subtitleLabel, localizedString); if (bFound) { SSubtitleEntry entry; entry.key = subtitleLabel; if (pSound) { entry.soundId = pSound->GetId(); float timeToShow = pSound->GetLengthMs() * 0.001f; // msec to sec if (g_pGameCVars->hud_subtitlesDebug) { float now = gEnv->pTimer->GetCurrTime(); CryLogAlways("[SUB] Sound %s started at %f for %f secs, endtime=%f", pSound->GetName(), now, timeToShow, now+timeToShow); } #if 1 // make the text stay longer than the sound // timeToShow = std::min(timeToShow*1.2f, timeToShow+2.0f); // 10 percent longer, but max 2 seconds #endif entry.timeRemaining = timeToShow; entry.bPersistant = false; } else { entry.soundId = INVALID_SOUNDID; entry.timeRemaining = 0.0f; entry.bPersistant = true; } // replace actions NSKeyTranslation::TFixedWString finalDisplayString; finalDisplayString.assign(localizedString, localizedString.length()); NSKeyTranslation::ReplaceActions(pLocMgr, finalDisplayString); if (pSound) SubtitleCreateChunks(entry, localizedString); // if we have no chunks if (entry.nChunks == 0) { entry.timeRemaining = std::max(entry.timeRemaining, 0.8f); // minimum is 0.8 seconds // entry.timeRemaining = std::min(entry.timeRemaining*1.3f, entry.timeRemaining+2.5f); // 30 percent longer, but max 2.5 seconds SubtitleAssignCharacterName(entry); entry.localized.append(localizedString.c_str(), localizedString.length()); } static const bool bSubtitleLastIsFirst = false; const size_t MAX_SUBTITLES = g_pGameCVars->hud_subtitlesQueueCount; if (bSubtitleLastIsFirst) { m_subtitleEntries.push_front(entry); if (m_subtitleEntries.size() > MAX_SUBTITLES) m_subtitleEntries.resize(MAX_SUBTITLES); } else { m_subtitleEntries.push_back(entry); if (m_subtitleEntries.size() > MAX_SUBTITLES) m_subtitleEntries.erase(m_subtitleEntries.begin()); } m_bSubtitlesNeedUpdate = true; } } } else // if (bShow) { tSoundID soundId = pSound ? pSound->GetId() : INVALID_SOUNDID; if (pSound && g_pGameCVars->hud_subtitlesDebug) { float now = gEnv->pTimer->GetCurrTime(); CryLogAlways("[SUB] Sound %s requested to stop at %f", pSound->GetName(), now); } for (TSubtitleEntries::iterator iter = m_subtitleEntries.begin(); iter != m_subtitleEntries.end(); ) { const SSubtitleEntry& entry = *iter; // subtitles without associated sound are erase // subtitles with associated sound are only erased if they contain chunks // non-chunked sounds timeout, when the sound's time has passed // this may introduce some subtitles staying longer on screen than the sound can be heard, but is ok I think // [e.g. the sound is cancelled in the middle] if (iter->key == subtitleLabel && (soundId == INVALID_SOUNDID || (iter->soundId == soundId && iter->nChunks > 0 && iter->nCurChunk < iter->nChunks-1 && iter->timeRemaining > 0.8f))) { if (g_pGameCVars->hud_subtitlesDebug) { float now = gEnv->pTimer->GetCurrTime(); CryLogAlways("[SUB] Entry '%s' stopped at %f", entry.key.c_str(), now); } iter = m_subtitleEntries.erase(iter); m_bSubtitlesNeedUpdate = true; } else { ++iter; } } } } void CHUD::SetRadioButtons(bool active, int buttonNo /* = 0 */) { if(active) { if(GetModalHUD() == &m_animPDA) ShowPDA(false); else if(GetModalHUD() == &m_animBuyMenu) ShowPDA(false, true); m_animRadioButtons.Invoke("showRadioButtons", buttonNo); m_animRadioButtons.SetVisible(true); wstring group0(LocalizeWithParams("@mp_radio_group_0")); wstring group1(LocalizeWithParams("@mp_radio_group_1")); wstring group2(LocalizeWithParams("@mp_radio_group_2")); wstring group3(LocalizeWithParams("@mp_radio_group_3")); SFlashVarValue args[4] = {group0.c_str(), group1.c_str(), group2.c_str(), group3.c_str()}; m_animRadioButtons.Invoke("setRadioButtonText", args, 4); } else { m_animRadioButtons.Invoke("showRadioButtons", 0); m_animRadioButtons.SetVisible(false); } } void CHUD::ShowVirtualKeyboard(bool active) { if(m_pHUDTextChat) m_pHUDTextChat->ShowVirtualKeyboard(active); m_animGamepadConnected.Reload(); m_animGamepadConnected.Invoke("GamepadAvailable", active); } void CHUD::ObituaryMessage(EntityId targetId, EntityId shooterId, const char *weaponClassName, int material, int hit_type) { CGameRules *pGameRules=g_pGame->GetGameRules(); if (!pGameRules) return; if(!m_animKillLog.IsLoaded()) return; ILocalizationManager *pLM=gEnv->pSystem->GetLocalizationManager(); // TODO: refactor by Jan N bool bMounted = false; bool bSuicide = false; if (targetId == shooterId) bSuicide = true; // code below is checking if hits are melee and headshot... // TODO: Jan N: use these bools bool melee=false; if (hit_type>0) { const char *hittypename=pGameRules->GetHitType(hit_type); melee=strstr(hittypename?hittypename:"", "melee") != 0; } bool headshot=false; if (material>0) { if (ISurfaceType *pSurfaceType=pGameRules->GetHitMaterial(material)) { const char *matname=pSurfaceType->GetName(); headshot=strstr(matname?matname:"", "head") != 0; } } const char *targetName=g_pGame->GetGameRules()->GetActorNameByEntityId(targetId); const char *shooterName=g_pGame->GetGameRules()->GetActorNameByEntityId(shooterId); wstring entity[3]; if (targetName && targetName[0]) pLM->LocalizeString(targetName, entity[0], true); if (shooterName && shooterName[0]) pLM->LocalizeString(shooterName, entity[1], true); bool processed = false; IEntityClass* pWeaponClass = NULL; pWeaponClass=gEnv->pEntitySystem->GetClassRegistry()->FindClass(weaponClassName); if(pWeaponClass == CItem::sSOCOMClass) { CPlayer *pPlayer = static_cast<CPlayer *>(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(shooterId)); if(pPlayer) { if(pPlayer->GetCurrentItem() && pPlayer->GetCurrentItem()->IsDualWield()) { pLM->LocalizeString("doubleSOCOM", entity[2], true); processed = true; } } } if (!processed) { if(pWeaponClass) pLM->LocalizeString(pWeaponClass->GetName(), entity[2], true); else pLM->LocalizeString(weaponClassName, entity[2], true); } // if there is no shooter, use the suicide icon if ((!shooterName || !shooterName[0]) && !g_pGame->GetIGameFramework()->GetIItemSystem()->IsItemClass(weaponClassName)) bSuicide=true; if(g_pGame->GetIGameFramework()->GetIVehicleSystem()->IsVehicleClass(weaponClassName)) { SFlashVarValue args[4] = {entity[1].c_str(), "RunOver", entity[0].c_str(), headshot}; m_animKillLog.Invoke("addLog",args,4); } else if(bMounted) { SFlashVarValue args[4] = {entity[1].c_str(), "Mounted", entity[0].c_str(), headshot}; m_animKillLog.Invoke("addLog",args,4); } else if(bSuicide) { SFlashVarValue args[4] = {entity[0].c_str(), "Suicide", "", headshot}; m_animKillLog.Invoke("addLog",args,4); } else if(melee) { SFlashVarValue args[4] = {entity[1].c_str(), "Melee", entity[0].c_str(), headshot}; m_animKillLog.Invoke("addLog",args,4); } else { SFlashVarValue args[4] = {entity[1].c_str(), entity[2].c_str(), entity[0].c_str(), headshot}; m_animKillLog.Invoke("addLog",args,4); } } void CHUD::ShowWarningMessage(EWarningMessages message, const char* optionalText) { switch(message) { case EHUD_SPECTATOR: m_animWarningMessages.Invoke("showErrorMessage", "spectator"); break; case EHUD_SWITCHTOTAN: m_animWarningMessages.Invoke("showErrorMessage", "switchtotan"); break; case EHUD_SWITCHTOBLACK: m_animWarningMessages.Invoke("showErrorMessage", "switchtous"); break; case EHUD_SUICIDE: m_animWarningMessages.Invoke("showErrorMessage", "suicide"); break; case EHUD_CONNECTION_LOST: m_animWarningMessages.Invoke("showErrorMessage", "connectionlost"); break; case EHUD_OK: m_animWarningMessages.Invoke("showErrorMessage", "Box1"); if(optionalText) m_animWarningMessages.Invoke("setErrorText", optionalText); break; case EHUD_YESNO: m_animWarningMessages.Invoke("showErrorMessage", "Box2"); if(optionalText) m_animWarningMessages.Invoke("setErrorText", optionalText); break; case EHUD_CANCEL: m_animWarningMessages.Invoke("showErrorMessage", "Box3"); if(optionalText) m_animWarningMessages.Invoke("setErrorText", optionalText); break; default: return; break; } m_animWarningMessages.SetVisible(true); if(m_pModalHUD == &m_animPDA) ShowPDA(false); SwitchToModalHUD(&m_animWarningMessages,true); CPlayer *pPlayer = static_cast<CPlayer *>(g_pGame->GetIGameFramework()->GetClientActor()); if(pPlayer && pPlayer->GetPlayerInput()) pPlayer->GetPlayerInput()->DisableXI(true); } void CHUD::HandleWarningAnswer(const char* warning /* = NULL */) { m_animWarningMessages.SetVisible(false); CPlayer *pPlayer = static_cast<CPlayer *>(g_pGame->GetIGameFramework()->GetClientActor()); if(warning) { if(!strcmp(warning, "suicide")) { //SwitchToModalHUD(NULL,false); gEnv->pConsole->ExecuteString("kill me"); } else if(!strcmp(warning, "spectate")) { ShowPDA(false); gEnv->pConsole->ExecuteString("spectator"); } else if(!strcmp(warning, "switchTeam")) { CGameRules* pRules = g_pGame->GetGameRules(); if(pRules->GetTeamCount() > 1) { const char* command = "team black"; if(pRules->GetTeamId("black") == pRules->GetTeam(pPlayer->GetEntityId())) command = "team tan"; gEnv->pConsole->ExecuteString(command); } } } SwitchToModalHUD(NULL,false); if(pPlayer && pPlayer->GetPlayerInput()) pPlayer->GetPlayerInput()->DisableXI(false); } void CHUD::UpdateSubtitlesManualRender(float frameTime) { if (m_subtitleEntries.empty() == false) { for (TSubtitleEntries::iterator iter = m_subtitleEntries.begin(); iter != m_subtitleEntries.end();) { SSubtitleEntry& entry = *iter; // chunk handling if (entry.nChunks > 0) { if (entry.nCurChunk < 0) { // first time entry.nCurChunk = 0; m_bSubtitlesNeedUpdate = true; } else if (entry.nCurChunk < entry.nChunks-1) { SSubtitleEntry::Chunk& nextChunk = entry.chunks[entry.nCurChunk+1]; if (entry.timeRemaining <= nextChunk.time) { ++entry.nCurChunk; m_bSubtitlesNeedUpdate = true; if (entry.nCurChunk == entry.nChunks-1) { // last chunk, if that's too small, make it a bit longer if (entry.timeRemaining < .8f) { entry.timeRemaining = 0.8f; if (g_pGameCVars->hud_subtitlesDebug) { float now = gEnv->pTimer->GetCurrTime(); CryLogAlways("[SUB] Chunked entry '%s' last chunk end delayed by 0.8 secs [now=%f]", entry.key.c_str(), now); } } } } } } // if (entry.bPersistant == false) { entry.timeRemaining -= frameTime; const bool bDelete = entry.timeRemaining <= 0.0f; if (bDelete) { if (g_pGameCVars->hud_subtitlesDebug) { float now = gEnv->pTimer->GetCurrTime(); CryLogAlways("[SUB] Chunked entry '%s' time-end delete at %f", entry.key.c_str(), now); } TSubtitleEntries::iterator toDelete = iter; ++iter; m_subtitleEntries.erase(toDelete); m_bSubtitlesNeedUpdate = true; continue; } } ++iter; } } if (g_pGameCVars->hud_subtitlesRenderMode == 0) { if(g_pGameCVars->hud_subtitles) //should be a switch { m_animSubtitles.Reload(); if (m_bSubtitlesNeedUpdate) { int nToDisplay = g_pGameCVars->hud_subtitlesVisibleCount; // re-set text CryFixedWStringT<1024> subtitleString; bool bFirst = true; TSubtitleEntries::iterator iterEnd = m_subtitleEntries.end(); for (TSubtitleEntries::iterator iter = m_subtitleEntries.begin(); iter != iterEnd && nToDisplay > 0; ++iter, --nToDisplay) { if (!bFirst) subtitleString+=L"\n"; else bFirst = false; SSubtitleEntry& entry = *iter; if (entry.nChunks == 0) subtitleString+=entry.localized; else { assert (entry.nCurChunk >= 0 && entry.nCurChunk < entry.nChunks); if (entry.nCurChunk < 0 || entry.nCurChunk >= entry.nChunks) { CRY_ASSERT(0); } const SSubtitleEntry::Chunk& chunk = entry.chunks[entry.nCurChunk]; if (entry.bNameShown == false) // only first visible chunk will display the character's name { SubtitleAppendCharacterName(entry, subtitleString); entry.bNameShown = true; } subtitleString.append(entry.localized.c_str() + chunk.start, chunk.len); } } m_animSubtitles.Invoke("setText", subtitleString.c_str()); m_bSubtitlesNeedUpdate = false; } m_animSubtitles.GetFlashPlayer()->Advance(frameTime); m_animSubtitles.GetFlashPlayer()->Render(); } else if(m_animSubtitles.IsLoaded()) { m_animSubtitles.Unload(); } } else // manual render { if (m_subtitleEntries.empty()) return; IUIDraw* pUIDraw = g_pGame->GetIGameFramework()->GetIUIDraw(); if (pUIDraw==0) // should never happen! { m_subtitleEntries.clear(); m_bSubtitlesNeedUpdate = true; return; } IRenderer* pRenderer = gEnv->pRenderer; const float x = 0.0f; const float maxWidth = 700.0f; // float y = 600.0f - (g_pGameCVars->hud_panoramicHeight * 600.0f / 768.0f) + 2.0f; float y = 600.0f - (g_pGameCVars->hud_subtitlesHeight * 6.0f) + 1.0f; // subtitles height is in percent of screen height (600.0) pUIDraw->PreRender(); int nToDisplay = g_pGameCVars->hud_subtitlesVisibleCount; CryFixedWStringT<1024> tmpString; // now draw 2D texts overlay for (TSubtitleEntries::iterator iter = m_subtitleEntries.begin(); iter != m_subtitleEntries.end() && nToDisplay > 0; --nToDisplay) { SSubtitleEntry& entry = *iter; ColorF clr = Col_White; static const float TEXT_SPACING = 2.0f; const float textSize = g_pGameCVars->hud_subtitlesFontSize; float sizeX,sizeY; const string& textLabel = entry.key; if (!textLabel.empty() && textLabel[0] == '@' && entry.localized.empty() == false) { const wchar_t* szLocText = entry.localized.c_str(); if (entry.nChunks > 0) { SSubtitleEntry::Chunk& chunk = entry.chunks[entry.nCurChunk]; tmpString.clear(); if (entry.bNameShown == false) { SubtitleAppendCharacterName(entry, tmpString); entry.bNameShown = true; } tmpString.append(entry.localized.c_str() + chunk.start, chunk.len); szLocText = tmpString.c_str(); } pUIDraw->GetWrappedTextDimW(m_pDefaultFont,&sizeX, &sizeY, maxWidth, textSize, textSize, szLocText); pUIDraw->DrawWrappedTextW(m_pDefaultFont,x, y, maxWidth, textSize, textSize, szLocText, clr.a, clr.r, clr.g, clr.b, // UIDRAWHORIZONTAL_LEFT,UIDRAWVERTICAL_TOP,UIDRAWHORIZONTAL_LEFT,UIDRAWVERTICAL_TOP); UIDRAWHORIZONTAL_CENTER,UIDRAWVERTICAL_TOP,UIDRAWHORIZONTAL_CENTER,UIDRAWVERTICAL_TOP); } else { pUIDraw->GetTextDim(m_pDefaultFont,&sizeX, &sizeY, textSize, textSize, textLabel.c_str()); pUIDraw->DrawText(m_pDefaultFont,x, y, textSize, textSize, textLabel.c_str(), clr.a, clr.r, clr.g, clr.b, UIDRAWHORIZONTAL_CENTER,UIDRAWVERTICAL_TOP,UIDRAWHORIZONTAL_CENTER,UIDRAWVERTICAL_TOP); } y+=sizeY+TEXT_SPACING; ++iter; } pUIDraw->PostRender(); } } //----------------------------------------------------------------------------------------------------- void CHUD::ShowTutorialText(const wchar_t* text, int pos) { // NB: text is displayed as passed - fetch the localised string before calling this. if(text != NULL) { m_animTutorial.Invoke("setFixPosition", pos); m_animTutorial.Invoke("showTutorial", true); m_animTutorial.Invoke("setTutorialTextNL",text); } else { m_animTutorial.Invoke("showTutorial", false); } } //----------------------------------------------------------------------------------------------------- void CHUD::SetTutorialTextPosition(int pos) { m_animTutorial.Invoke("setFixPosition", pos); } //----------------------------------------------------------------------------------------------------- void CHUD::SetTutorialTextPosition(float posX, float posY) { SFlashVarValue args[2] = {posX*1024.0f, posY * 768.0f}; m_animTutorial.Invoke("setPosition", args, 2); } //----------------------------------------------------------------------------------------------------- void CHUD::DisplayAmmoPickup(const char* ammoName, int ammoAmount) { if(!m_bShow || m_quietMode) return; int type = stl::find_in_map(m_hudAmmunition, ammoName, 0); if(!type) type = 1; string ammoLoc = "@"; ammoLoc.append(ammoName); SFlashVarValue args[3] = {ammoAmount, type, ammoLoc.c_str()}; m_animAmmoPickup.Invoke("setPickup", args, 3); }
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 12 ], [ 14, 48 ], [ 50, 63 ], [ 99, 100 ], [ 102, 106 ], [ 108, 154 ], [ 156, 172 ], [ 174, 214 ], [ 221, 221 ], [ 228, 228 ], [ 235, 235 ], [ 242, 271 ], [ 273, 274 ], [ 276, 291 ], [ 299, 300 ], [ 417, 425 ], [ 431, 462 ], [ 509, 547 ], [ 700, 717 ], [ 725, 740 ], [ 752, 752 ], [ 767, 773 ], [ 782, 783 ], [ 790, 790 ], [ 796, 810 ], [ 816, 817 ], [ 824, 840 ], [ 842, 842 ], [ 848, 850 ], [ 877, 885 ], [ 891, 891 ], [ 893, 893 ], [ 896, 896 ], [ 902, 903 ], [ 906, 906 ], [ 909, 909 ], [ 936, 937 ], [ 941, 995 ], [ 997, 1001 ], [ 1003, 1006 ], [ 1008, 1021 ], [ 1026, 1035 ], [ 1071, 1076 ], [ 1082, 1099 ], [ 1101, 1103 ], [ 1106, 1110 ], [ 1129, 1161 ], [ 1166, 1166 ], [ 1168, 1176 ], [ 1192, 1239 ], [ 1258, 1258 ] ], [ [ 13, 13 ], [ 49, 49 ], [ 64, 98 ], [ 101, 101 ], [ 107, 107 ], [ 155, 155 ], [ 173, 173 ], [ 215, 220 ], [ 222, 227 ], [ 229, 234 ], [ 236, 241 ], [ 272, 272 ], [ 275, 275 ], [ 292, 298 ], [ 301, 416 ], [ 426, 430 ], [ 463, 508 ], [ 548, 699 ], [ 718, 724 ], [ 741, 751 ], [ 753, 766 ], [ 774, 781 ], [ 784, 789 ], [ 791, 795 ], [ 811, 815 ], [ 818, 823 ], [ 841, 841 ], [ 843, 847 ], [ 851, 876 ], [ 886, 890 ], [ 892, 892 ], [ 894, 895 ], [ 897, 901 ], [ 904, 905 ], [ 907, 908 ], [ 910, 935 ], [ 938, 940 ], [ 996, 996 ], [ 1002, 1002 ], [ 1007, 1007 ], [ 1022, 1025 ], [ 1036, 1070 ], [ 1077, 1081 ], [ 1100, 1100 ], [ 1104, 1105 ], [ 1111, 1128 ], [ 1162, 1165 ], [ 1167, 1167 ], [ 1177, 1191 ], [ 1240, 1257 ] ] ]
3788ae0d6f3a94c23d801faf7638296541c2a969
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Code/Flosti Engine/GUI/StaticText.cpp
47dff2f88ab1abbfdf11dd64337b414aab0cc36e
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,277
cpp
#include "__PCH_GUI.h" #include "StaticText.h" #include "RenderManager.h" #include "Logger/Logger.h" #include "Core/Core.h" //---Constructor CStaticText::CStaticText( uint32 windowsHeight, uint32 windowsWidth, float height_precent, float witdh_percent, const Vect2f position_percent, std::string lit, bool isVisible, bool isActive) : CGuiElement( windowsHeight, windowsWidth, height_precent, witdh_percent, position_percent, STATIC_TEXT, lit, 0, 0, isVisible,isActive) {} //---------------Interfaz de GuiElement---------------------- void CStaticText::Render (CRenderManager *renderManager, CFontManager* fm) { if( CGuiElement::m_bIsVisible) { //Primero renderizamos todos los hijos que pudiera tener el Static Text: CGuiElement::Render(renderManager, fm); //Finalmente renderizamos el texto: CGuiElement::RenderText(renderManager, fm); } } void CStaticText::Update(CInputManager* intputManager, float elapsedTime) { if( CGuiElement::m_bIsVisible && CGuiElement::m_bIsActive ) { //Primero actualizamos todos los hijos que pudiera tener el checkButton: CGuiElement::Update(intputManager, elapsedTime); } } void CStaticText::SetLiteral( const std::string& lit) { CGuiElement::m_sLiteral = lit; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 41 ] ] ]
f3c5d967776d75a4b4e34901861ef420220158a9
b144663dd43236066d70be6c09a3c4f8ab5541fd
/src/boost/os_services/notify_filters.hpp
28d7a7b385f985a635e604a63e7d26cf8d9a39fb
[]
no_license
nkzxw/schwimmer-hund
a1ffbf9243fba148461d65b5ad9cee4519f70f9a
2d0e11efef9f401bbccbba838d516341bc9b3283
refs/heads/master
2021-01-10T05:41:38.207721
2011-02-03T14:57:10
2011-02-03T14:57:10
47,530,533
0
0
null
null
null
null
UTF-8
C++
false
false
799
hpp
#ifndef BOOST_OS_SERVICES_NOTIFY_FILTERS_HPP_INCLUDED #define BOOST_OS_SERVICES_NOTIFY_FILTERS_HPP_INCLUDED //enum NotifyFilters //TODO: por ahora muy atado a Win32 namespace boost { namespace os_services { namespace notify_filters { static const int file_name = 0x00000001; //1; static const int directory_name = 0x00000002; //2; static const int attributes = 0x00000004; //4; static const int size = 0x00000008; //8; static const int last_write = 0x00000010; //16; static const int last_access = 0x00000020; //32; static const int creation_time = 0x00000040; //64; static const int security = 0x00000100; //256; } // namespace notify_filters } // namespace os_services } // namespace boost #endif // BOOST_OS_SERVICES_NOTIFY_FILTERS_HPP_INCLUDED
[ "fpelliccioni@07e413c0-050a-11df-afc1-2de6fd616bef" ]
[ [ [ 1, 24 ] ] ]
72afb3173dc754f278a8caae6cad16dc79abd184
63fc6506b8e438484a013b3c341a1f07f121686b
/apps/examples/moviePlayerExample/src/testApp.h
f939048de72edc64b63a4e094426e312e281d029
[]
no_license
progen/ofx-dev
c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8
45125fcab657715abffc7e84819f8097d594e28c
refs/heads/master
2021-01-20T07:15:39.755316
2009-03-03T22:33:37
2009-03-03T22:33:37
140,479
1
0
null
null
null
null
UTF-8
C++
false
false
502
h
#ifndef _TEST_APP #define _TEST_APP #include "ofMain.h" #include "ofAddons.h" class testApp : public ofBaseApp { public: testApp(); 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); ofVideoPlayer fingerMovie; }; #endif
[ [ [ 1, 27 ] ] ]
7c2656c1e82999d3858bbcddf9d504f7744823b1
62874cd4e97b2cfa74f4e507b798f6d5c7022d81
/src/Midi-Me/ChainItem.cpp
1619760cdd17025cf6d8a9fd0b856eb8ac108d96
[]
no_license
rjaramih/midi-me
6a4047e5f390a5ec851cbdc1b7495b7fe80a4158
6dd6a1a0111645199871f9951f841e74de0fe438
refs/heads/master
2021-03-12T21:31:17.689628
2011-07-31T22:42:05
2011-07-31T22:42:05
36,944,802
0
0
null
null
null
null
UTF-8
C++
false
false
1,615
cpp
// Includes #include "ChainItem.h" #include "ChainWidget.h" using namespace MidiMe; #include <QtGui/QGraphicsScene> #include <QtGui/QGraphicsView> #include <QtGui/QGraphicsSceneMouseEvent> /// The hardcoded margin between items const float ChainItem::margin = 5.0f; const float ChainItem::width = 50.0f; const float ChainItem::height = 15.0f; /****************************** * Constructors and destructor * ******************************/ ChainItem::ChainItem(ChainWidget *pChainWidget, QGraphicsItem *pParent) : QGraphicsRectItem(pParent), m_pChainWidget(pChainWidget), m_pMeterItem(0) { assert(m_pChainWidget); // Make this a top-level item if no parent is provided if(!pParent) m_pChainWidget->getScene()->addItem(this); // Setup item //setFlag(ItemIsSelectable); //setFlag(ItemIsMovable); //setFlag(ItemIsFocusable); setRect(0,0, width, height); setBrush(Qt::NoBrush); // Create the meter item m_pMeterItem = new QGraphicsRectItem(this); m_pMeterItem->setBrush(Qt::green); m_pMeterItem->setRect(0, 0, 0, height); } ChainItem::~ChainItem() { delete m_pMeterItem; } /****************** * Other functions * ******************/ bool ChainItem::isColliding() const { // TEMP /*int numColliders = ChainWidget::getColliders(this).count(); if(numColliders > 0) cerr << "[ChainItem::DEBUG] " << numColliders << " colliders" << endl;*/ // TEMP: There seems to be always one item colliding return ChainWidget::getColliders(this).count() > 1; } /********************** * Protected functions * **********************/
[ "Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f" ]
[ [ [ 1, 67 ] ] ]
e1e49c451fed3fa5577ab8e48e64b3991375f15b
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK5.0/bctestbutton/inc/bctestbuttonview.h
03347ab2d48a9a798784992221fb68072e5ec37b
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,112
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Test BC for Template control API. * */ #ifndef C_BCTEST_BUTTON_VIEW_H #define C_BCTEST_BUTTON_VIEW_H #include <aknview.h> const TUid KBCTestButtonViewId = { 1 }; class CBCTestButtonContainer; class CBCTestUtil; /** * Application UI class * * @lib bctestutil.lib */ class CBCTestButtonView : public CAknView { public: // Constructors and destructor /** * Symbian static 2nd constructor */ static CBCTestButtonView* NewL(CBCTestUtil* aUtil); /** * dtor */ virtual ~CBCTestButtonView(); public: // from CAknView /** * Return view Id. */ TUid Id() const; /** * From CAknView, HandleCommandL. * @param aCommand Command to be handled. */ void HandleCommandL( TInt aCommand ); /** * getter of Container */ CBCTestButtonContainer* Container(); protected: // from CAknView /** * When view is activated, do something */ void DoActivateL( const TVwsViewId&, TUid, const TDesC8& ); /** * When view is deactivated, do something */ void DoDeactivate(); private: // constructor /** * C++ default constructor */ CBCTestButtonView(); /** * symbian 2nd ctor */ void ConstructL(CBCTestUtil* aUtil); private: // data /** * pointor to the BC Test framework utility. * not own just refer to */ CBCTestUtil* iTestUtil; /** * pointor to the container. * own */ CBCTestButtonContainer* iContainer; }; #endif // C_BCTEST_BUTTON_VIEW_H // End of File
[ "none@none" ]
[ [ [ 1, 108 ] ] ]
3ab9ce677d4a240ee4bb7a0f1b69604534ce2f00
fd4a071ba9d8f0abf82e7a4d2cb41f48b9339b51
/QConfigStorage.h
4ca3781eaa06f0583cc771111fa01ab229ed467f
[]
no_license
rafalka/rs232testng
c4a6e4c1777ee92b2d67056739b2524569f5be5d
634d38cf8745841cf0509fb10c1faf6943516cbc
refs/heads/master
2020-05-18T17:14:51.166302
2011-01-12T22:00:01
2011-01-12T22:00:01
37,258,102
0
0
null
null
null
null
UTF-8
C++
false
false
3,977
h
/****************************************************************************** * @file QConfigStorage.h * * @brief * * @date 02-12-2010 * @author Rafal Kukla ****************************************************************************** * Copyright (C) 2010 Rafal Kukla ( [email protected] ) * This file is a part of rs232testng project and is released * under the terms of the license contained in the file LICENSE ****************************************************************************** */ #ifndef QCONFIGSTORAGE_H_ #define QCONFIGSTORAGE_H_ #define ORGANIZATION_NAME "RAFi" #define APPLICATION_NAME "RS232TestNG" #include <QSettings> #include <QMutex> #include <QMutexLocker> #include <QByteArray> #include <QStringList> /* * */ #define CONF_START_GROUP(_name_not_as_string_) \ QConfigStorageGroupCreator config_group_##_name_not_as_string_ ( #_name_not_as_string_ ); #define CONF_END_GROUP(_name_not_as_string_) \ config_group_##_name_not_as_string_.EndGroup(); #define CONF_READ_VAL( _variable_ , _default_ ) QConfigStorage::getVal( #_variable_ , &_variable_ , _default_ ); #define CONF_STORE_VAL( _variable_ ) QConfigStorage::setVal( #_variable_ , _variable_ ); class QConfigStorage { private: static QConfigStorage s; QSettings storage; QMutex lock; public: static QConfigStorage& instance() { return QConfigStorage::s; } static QMutex& getConfigStorageLock() { return s.lock; } static void Lock() { s.lock.lock(); } static void Unlock() { s.lock.unlock(); } static void BeginGroup(const char* name) { s.storage.beginGroup( name ); } static void EndGroup() { s.storage.endGroup(); } static void setVal(const char* key, const QVariant& value) { s.storage.setValue(key,value); } static void getVal(const char* key, QVariant & value, const QVariant& defval) { value = s.storage.value(key,defval); } static void getVal(const char* key, int* value, int defval) { if (value) *value = s.storage.value(key,defval).toInt(); } static int getVal(const char* key, int defval) { return s.storage.value(key,defval).toInt(); } static void getVal(const char* key, QString* value, const QString& defval) { if (value) *value = s.storage.value(key,defval).toString(); } static QString getVal(const char* key, const QString& defval) { return s.storage.value(key,defval).toString(); } static void getVal(const char* key, QByteArray* value, const QByteArray& defval) { if (value) *value = s.storage.value(key,defval).toByteArray(); } static QByteArray getVal(const char* key, const QByteArray& defval) { return s.storage.value(key,defval).toByteArray(); } static void getVal(const char* key, QStringList* value, const QStringList& defval) { if (value) *value = s.storage.value(key,defval).toStringList(); } static QStringList getVal(const char* key, const QStringList& defval) { return s.storage.value(key,defval).toStringList(); } static void Save() { s.storage.sync(); } QConfigStorage(): storage(ORGANIZATION_NAME,APPLICATION_NAME), lock(QMutex::Recursive) { } ~QConfigStorage() { storage.sync(); } }; class QConfigStorageGroupCreator { private: bool isCreated; QConfigStorageGroupCreator(); public: QConfigStorageGroupCreator(const char* groupName) { QConfigStorage::Lock(); QConfigStorage::BeginGroup(groupName); isCreated = true; } void EndGroup() { if (isCreated) { QConfigStorage::EndGroup(); QConfigStorage::Unlock(); isCreated = false; } } ~QConfigStorageGroupCreator() { EndGroup(); } }; #endif /* QCONFIGSTORAGE_H_ */
[ "rkdevel@ef62a7f8-4c9b-1a64-55d9-32abd1026911" ]
[ [ [ 1, 116 ] ] ]
93601778a7e3fb166c1661cf5e27ef11c1417a06
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swFrameworkDependent/FrameFactory/swFrameFactory.cpp
cb54692b017783144569fe666a8bcfa0665ff040
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
1,347
cpp
/////////////////////////////////////////////////////////////////////////////// // Name: swFrameworkDependent/FrameFactory/swFrameFactory.cpp // Author: Yann Rouillard, Viet Bui Xuan, Reinhold Füreder // Created: 2002 // Copyright: (c) 2002 Yann Rouillard, Viet Bui Xuan, Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ #pragma implementation "swFrameFactory.h" #endif #include "swFrameFactory.h" #include "swToolBarRegistry.h" namespace sw { FrameFactory *FrameFactory::ms_instance = NULL; FrameFactory::FrameFactory () { // Nothing to do } FrameFactory::~FrameFactory () { if (ms_instance == this) { ms_instance = NULL; } } FrameFactory * FrameFactory::GetInstance () { return ms_instance; } void FrameFactory::SetInstance (FrameFactory *frameFactory) { if (ms_instance != NULL) { delete ms_instance; } ms_instance = frameFactory; } ToolBar * FrameFactory::CreateNamedToolBar (const wxString &name, const long style) { ToolBar *toolbar = this->CreateToolBar (style); wxASSERT (toolbar != NULL); ToolBarRegistry::GetInstance ()->Register (toolbar, name); return toolbar; } } // End namespace sw
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 65 ] ] ]
d756af6e9dbf85b87aa631451eb708a3e77c9a55
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/gtx/vector_angle.hpp
c86ffbfd25520ba0ac26066e0858b7dc429a9b0f
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
2,298
hpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-12-30 // Updated : 2006-11-13 // Licence : This source is under MIT License // File : glm/gtx/vector_angle.h /////////////////////////////////////////////////////////////////////////////////////////////////// // Dependency: // - GLM core // - GLM_GTX_quaternion // - GLM_GTX_epsilon /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_gtx_vector_angle #define glm_gtx_vector_angle // Dependency: #include "../glm.hpp" #include "../gtx/quaternion.hpp" #include "../gtx/epsilon.hpp" namespace glm { namespace test{ void main_gtx_vector_angle(); }//namespace test namespace gtx{ //! GLM_GTX_vector_angle extension: Compute angle between vectors namespace vector_angle { //! Returns the absolute angle between x and y. //! Parameters need to be normalized. //! From GLM_GTX_vector_angle extension template <typename vecType> typename vecType::value_type angle( vecType const & x, vecType const & y); //! Returns the oriented angle between x and y //! Parameters need to be normalized. //! From GLM_GTX_vector_angle extension. template <typename vecType> typename vecType::value_type orientedAngle( vecType const & x, vecType const & y); //! Returns the orientation of a two vector base from a normal. //! Parameters need to be normalized. //! From GLM_GTX_vector_angle extension. template <typename vecType> typename vecType::value_type orientedAngleFromRef( vecType const & x, vecType const & y, detail::tvec3<typename vecType::value_type> const & ref); }//namespace vector_angle }//namespace gtx }//namespace glm #define GLM_GTX_vector_angle namespace gtx::quaternion; using namespace gtx::epsilon; using namespace gtx::vector_angle #ifndef GLM_GTX_GLOBAL namespace glm {using GLM_GTX_vector_angle;} #endif//GLM_GTX_GLOBAL #include "vector_angle.inl" #endif//glm_gtx_vector_angle
[ [ [ 1, 68 ] ] ]
ff0c1de47b81d9c14ce0b043c10c46e21a7d1eba
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch15/Fig15_22/Fig15_22.cpp
5a5251cb8535ef8a3abab0f3995040b3c3a30ef9
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
UTF-8
C++
false
false
2,268
cpp
// Fig. 15.22: Fig15_22.cpp // Testing error states. #include <iostream> using std::cin; using std::cout; using std::endl; int main() { int integerValue; // display results of cin functions cout << "Before a bad input operation:" << "\ncin.rdstate(): " << cin.rdstate() << "\n cin.eof(): " << cin.eof() << "\n cin.fail(): " << cin.fail() << "\n cin.bad(): " << cin.bad() << "\n cin.good(): " << cin.good() << "\n\nExpects an integer, but enter a character: "; cin >> integerValue; // enter character value cout << endl; // display results of cin functions after bad input cout << "After a bad input operation:" << "\ncin.rdstate(): " << cin.rdstate() << "\n cin.eof(): " << cin.eof() << "\n cin.fail(): " << cin.fail() << "\n cin.bad(): " << cin.bad() << "\n cin.good(): " << cin.good() << endl << endl; cin.clear(); // clear stream // display results of cin functions after clearing cin cout << "After cin.clear()" << "\ncin.fail(): " << cin.fail() << "\ncin.good(): " << cin.good() << endl; return 0; } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 53 ] ] ]
6f83f63595a028b4efcd4e320732ef29e6ae8af1
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/factory_p.h
93a88da5eed006cdd20d2af8010c0bd17e38c605
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
6,150
h
/* This file is part of the KDE project Copyright (C) 2004-2007 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PHONON_FACTORY_P_H #define PHONON_FACTORY_P_H #include "phonon_export.h" #include <QtCore/QObject> #include <QtCore/QStringList> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE class QUrl; class QIcon; namespace Phonon { class PlatformPlugin; class MediaNodePrivate; class AbstractMediaStream; /** * \internal * \brief Factory to access the preferred Backend. * * This class is used internally to get the backend's implementation. * It keeps track of the objects that were created. When a * request for a backend change comes, it asks all frontend objects to delete * their backend objects and then checks whether they were all deleted. Only * then the old backend is unloaded and the new backend is loaded. * * \author Matthias Kretz <[email protected]> */ namespace Factory { /** * Emits signals for Phonon::Factory. */ class Sender : public QObject { Q_OBJECT Q_SIGNALS: /** * Emitted after the backend has successfully been changed. */ void backendChanged(); /** * \copydoc BackendCapabilities::Notifier::availableAudioOutputDevicesChanged */ void availableAudioOutputDevicesChanged(); /** * \copydoc BackendCapabilities::Notifier::availableAudioCaptureDevicesChanged */ void availableAudioCaptureDevicesChanged(); }; /** * Returns a pointer to the object emitting the signals. * * \see Sender::backendChanged() */ PHONON_EXPORT Sender *sender(); /** * Create a new backend object for a MediaObject. * * \return a pointer to the MediaObject the backend provides. */ QObject *createMediaObject(QObject *parent = 0); /** * Create a new backend object for a Effect. * * \return a pointer to the Effect the backend provides. */ #ifndef QT_NO_PHONON_EFFECT QObject *createEffect(int effectId, QObject *parent = 0); #endif //QT_NO_PHONON_EFFECT /** * Create a new backend object for a VolumeFaderEffect. * * \return a pointer to the VolumeFaderEffect the backend provides. */ #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT QObject *createVolumeFaderEffect(QObject *parent = 0); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT /** * Create a new backend object for a AudioOutput. * * \return a pointer to the AudioOutput the backend provides. */ QObject *createAudioOutput(QObject *parent = 0); /** * Create a new backend object for a VideoWidget. * * \return a pointer to the VideoWidget the backend provides. */ #ifndef QT_NO_PHONON_VIDEO QObject *createVideoWidget(QObject *parent = 0); #endif //QT_NO_PHONON_VIDEO /** * \return a pointer to the backend interface. */ PHONON_EXPORT QObject *backend(bool createWhenNull = true); /** * Unique identifier for the Backend. Can be used in configuration files * for example. */ QString identifier(); /** * Get the name of the Backend. It's the name from the .desktop file. */ PHONON_EXPORT QString backendName(); /** * Get the comment of the Backend. It's the comment from the .desktop file. */ QString backendComment(); /** * Get the version of the Backend. It's the version from the .desktop file. * * The version is especially interesting if there are several versions * available for binary incompatible versions of the backend's media * framework. */ QString backendVersion(); /** * Get the icon (name) of the Backend. It's the icon from the .desktop file. */ QString backendIcon(); /** * Get the website of the Backend. It's the website from the .desktop file. */ QString backendWebsite(); /** * registers the backend object */ PHONON_EXPORT QObject *registerQObject(QObject *o); bool isMimeTypeAvailable(const QString &mimeType); PHONON_EXPORT void registerFrontendObject(MediaNodePrivate *); PHONON_EXPORT void deregisterFrontendObject(MediaNodePrivate *); PHONON_EXPORT void setBackend(QObject *); //PHONON_EXPORT void createBackend(const QString &library, const QString &version = QString()); PHONON_EXPORT PlatformPlugin *platformPlugin(); //X It is probably better if we can get away with internal handling of //X freeing the soundcard device when it's not needed anymore and //X providing an IPC method to stop all MediaObjects -> free all //X devices //X /** //X * \internal //X * This is called when the application needs to free the soundcard //X * device(s). //X */ //X void freeSoundcardDevices(); } // namespace Factory } // namespace Phonon QT_END_NAMESPACE QT_END_HEADER #endif // PHONON_FACTORY_P_H // vim: sw=4 ts=4
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 196 ] ] ]
72647cb874d1e4cc3b65676a47d40c8582b1b3dd
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/DVRMD_Filter/DVRMD_Filter/PlayerMgr.h
5282818801fda9090f903d7ef8f81e987f3a59f4
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
h
// PlayerMgr.h: interface for the CPlayerMgr class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PLAYERMGR_H__448B2740_E614_4457_9F1D_0B156F80B93C__INCLUDED_) #define AFX_PLAYERMGR_H__448B2740_E614_4457_9F1D_0B156F80B93C__INCLUDED_ #include "Player.h" #include "Sync_Locks.h" #include "Utilities.h" #define MAX_PLAYER 36 #define STOP_STATUS 0 #define RUN_STATUS 1 class CPlayerMgr { public: CPlayerMgr(); virtual ~CPlayerMgr(); VOID Init(HWND hNotifyWnd); VOID Clearup(); INT StartMonitor(HWND hWnd, HHV_CLIENT_INFO* clientInfo); INT StopMonitor( int handle ); int StartPlayBackByTime(HWND hWnd, SYSTEM_VIDEO_FILE* recdFile, char* ssIP, int ssPort); int StopPlayBackByTime(int realHandle); void ResetRenderWindow(LONG lWidth, LONG lHeight); private: int GetIdlePlayer(); private: CPlayer* m_player[MAX_PLAYER]; CMutex m_csLock; int m_status; }; //extern CPlayerMgr g_playerMgr; #endif // !defined(AFX_PLAYERMGR_H__448B2740_E614_4457_9F1D_0B156F80B93C__INCLUDED_)
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 46 ] ] ]
e4d274d15f68f0e75b01a02cd3f024498ace4d09
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/app/Logger_buffer.cpp
04ef8cda0782b7ab8b8fd96fe3e12a30096b2d55
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,781
cpp
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * Portions of this source file are based on the code of Dietmar Kuehl from * http://www.inf.uni-konstanz.de/~kuehl/iostream/ * * $Id: Logger_buffer.cpp 737 2009-05-16 15:40:46Z miklosb $ */ #include <gui/app/Logger_buffer.h> #include <gui/app/Logger.h> Logger_buffer::Logger_buffer(Logger* l, int bsize) : std::streambuf(), logger(l) { if (bsize) { char *ptr = new char[bsize]; setp(ptr, ptr + bsize); } else setp(0, 0); setg(0, 0, 0); } Logger_buffer::~Logger_buffer() { sync(); delete[] pbase(); } int Logger_buffer::overflow(int c) { // mutex.lock(); put_buffer(); if (c != EOF) if (pbase() == epptr()) put_char(c); else sputc(c); return 0; } int Logger_buffer::sync() { put_buffer(); // mutex.unlock(); return 0; } void Logger_buffer::put_char(int chr) { char app[2]; app[0] = chr; app[1] = 0; if (app[0]==10) { logger->set_next_line(); } else logger->print_to_log(app); // originally // XmTextInsert(text, XmTextGetLastPosition(text), app); } void Logger_buffer::put_buffer() { if (pbase() != pptr() && logger != 0) { int len = (pptr() - pbase()); char *buffer = new char[len + 1]; strncpy(buffer, pbase(), len); buffer[len] = 0; if (buffer[len-1]==10) { logger->set_next_line(); } else logger->print_to_log(buffer); // originally // XmTextInsert(text, XmTextGetLastPosition(text), buffer); setp(pbase(), epptr()); delete [] buffer; } }
[ "balint.miklos@localhost" ]
[ [ [ 1, 81 ] ] ]
31fda13a0b3e9fe49deb899f2f0fce78cd9d049e
4763f35af09e206c95301a455afddcf10ffbc1fe
/Game Developers Club Puzzle Fighter/Game Developers Club Puzzle Fighter/World States/Splash_Screen_State.cpp
a1d932d18b7b9d75d8ac8991a2e94a44245a91e1
[]
no_license
robertmcconnell2007/gdcpuzzlefighter
c7388634677875387ae165fc21f8ff977cea7cfb
63dd1daec36d85f6a36ddccffde9f15496a6a1c2
refs/heads/master
2021-01-20T23:26:48.386768
2010-08-25T02:48:00
2010-08-25T02:48:00
32,115,139
0
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
#include "Splash_Screen_State.h" //////////////////////////////////////////////////// /////////////////Splash Screen////////////////////// //////////////////////////////////////////////////// Splash_Screen* Splash_Screen::Ins() { static Splash_Screen instance; return & instance; } void Splash_Screen::begin() { splashSurface = load_my_image("World Art Assets/Splash Screen 1.bmp"); SSRect = GDH::Ins()->getScreen()->clip_rect; } void Splash_Screen::update(int msPassed) { } void Splash_Screen::draw() { drawATile(splashSurface, &SSRect, 0, GDH::Ins()->getScreen(), SSRect.x, SSRect.y); } void Splash_Screen::input(SDL_Event e) { if(e.key.keysym.sym == SDLK_1) GDH::Ins()->changeState((World_State*)Main_Menu::Ins()); } void Splash_Screen::exit() { SDL_FreeSurface(splashSurface); }
[ "IxAtreusAzai@7fdb7857-aad3-6fc1-1239-45cb07d991c5" ]
[ [ [ 1, 37 ] ] ]
9d799c882534d7d85b682322f82e3a32b89eab95
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaTransmission/ClientTransmissionManager.hpp
e65278df012d18b01ad784e6929adb9c876b3ee0
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,192
hpp
#ifndef CLIENTTRANSMISSIONMANAGER_HPP_INCLUDED #define CLIENTTRANSMISSIONMANAGER_HPP_INCLUDED /* Copyright © 2009 Christopher Joseph Dean Schaefer (disks86) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "IClientTransmissionManager.hpp" #include "ClientSessionManager.hpp" #include "enet.hpp" #include "ThreadedManager.hpp" #include <boost/thread.hpp> namespace Enigma { class DllExport ClientTransmissionManager : public IClientTransmissionManager, public ThreadedManager { private: bool mShouldReconnect; bool mIsStopped; bool mIsUnloaded; bool mIsConnected; int mClientLimit; int mUpstreamLimit; int mDownstreamLimit; int mPollTimeout; ClientSessionManager mClientSessionManager; ENetHost* mClient; ENetAddress mAddress; ENetPeer* mPeer; std::string mHost; int mPort; boost::mutex mHostMutex; //Send a message to a server. virtual void ReallySendMessage(ENetPeer* peer, enet_uint8 channel, ENetPacket* packet); //Send a message to a server. virtual void ReallySendMessage(MessageContainer& message); //Poll Enet for more packets. int Poll(ENetEvent* event); protected: public: ClientTransmissionManager(); ~ClientTransmissionManager(); //Performs any tasks needed before init can fire. void PreInit(); //Initializes needed variables. void Init(); //Loads resources. void Load(); //Loads resources. void LoadUnsafely(); //Unloads resources. void Unload(); //Does one Iteration of the main loop. void Poll(); //Does one Iteration of the main loop. void PollUnsafely(); //Connect to an Enigma Server. void Connect(const std::string& host, int port); //Connect to an Enigma Server. void Connect(); //Disconnection from current Enigma Server. void Disconnect(); //Disconect from the current Enigma Server and then connect again. virtual void Reconnect(); //Send a message to a server. virtual void SendMessageToServer(MessageContainer& message); ClientSessionManager& GetClientSessionManager(){return mClientSessionManager;} }; }; #endif // CLIENTTRANSMISSIONMANAGER_HPP_INCLUDED
[ [ [ 1, 105 ] ] ]
5f52b3a956a83978452a2434d628dde3a0a3309f
515e917815568d213e75bfcbd3fb9f0e08cf2677
/tengine/game/baseentity.h
1648d0d003b5bd5b4859d486bfa509a18ef264f9
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
20,157
h
#ifndef TINKER_BASEENTITY_H #define TINKER_BASEENTITY_H #include <EASTL/map.h> #include <EASTL/vector.h> #include <vector.h> #include <matrix.h> #include <quaternion.h> #include <common.h> #include <tengine_config.h> #include <network/network.h> #include "entityhandle.h" typedef enum { DAMAGE_GENERIC = 1, DAMAGE_EXPLOSION, DAMAGE_COLLISION, DAMAGE_BURN, DAMAGE_LASER, } damagetype_t; namespace raytrace { class CRaytracer; }; typedef void (*EntityRegisterCallback)(); typedef size_t (*EntityCreateCallback)(); template<typename T> size_t NewEntity() { T* pT = new T(); return pT->GetHandle(); } template <class C> void ResizeVectorTmpl(char* pData, size_t iVectorSize) { eastl::vector<C>* pVector = (eastl::vector<C>*)pData; pVector->resize(iVectorSize); } class CSaveData { public: typedef enum { DATA_OMIT = 0, DATA_COPYTYPE, DATA_COPYARRAY, DATA_COPYVECTOR, DATA_NETVAR, DATA_STRING, DATA_STRING16, DATA_OUTPUT, } datatype_t; typedef void (*ResizeVector)(char* pData, size_t iVectorSize); datatype_t m_eType; const char* m_pszVariableName; size_t m_iOffset; size_t m_iSizeOfVariable; size_t m_iSizeOfType; ResizeVector m_pfnResizeVector; }; typedef void (*EntityInputCallback)(const class CBaseEntity* pTarget, const eastl::vector<tstring>& sArgs); class CEntityInput { public: eastl::string m_sName; EntityInputCallback m_pfnCallback; }; #define DECLARE_ENTITY_INPUT(name) \ virtual void name(const eastl::vector<tstring>& sArgs); \ static void name##InputCallback(const class CBaseEntity* pTarget, const eastl::vector<tstring>& sArgs) \ { \ ((ThisClass*)pTarget)->name(sArgs); \ } class CEntityOutput { public: void Call(); void AddTarget(const eastl::string& sTargetName, const eastl::string& sInput, const eastl::string& sArgs, bool bKill); void Clear(); public: class CEntityOutputTarget { public: eastl::string m_sTargetName; eastl::string m_sInput; eastl::string m_sArgs; bool m_bKill; }; eastl::vector<CEntityOutputTarget> m_aTargets; }; #define DECLARE_ENTITY_OUTPUT(name) \ CEntityOutput m_Output_##name; \ class CEntityRegistration { public: const char* m_pszEntityName; const char* m_pszParentClass; EntityRegisterCallback m_pfnRegisterCallback; EntityCreateCallback m_pfnCreateCallback; eastl::vector<CSaveData> m_aSaveData; eastl::vector<CNetworkedVariableData> m_aNetworkVariables; eastl::map<eastl::string, CEntityInput> m_aInputs; }; #define REGISTER_ENTITY_CLASS_NOBASE(entity) \ DECLARE_CLASS(entity, entity); \ public: \ static void RegisterCallback##entity() \ { \ entity* pEntity = new entity(); \ pEntity->m_sClassName = #entity; \ CBaseEntity::Register(pEntity); \ delete pEntity; \ } \ static const char* Get##entity##ParentClass() { return NULL; } \ \ virtual const char* GetClassName() { return #entity; } \ virtual void RegisterNetworkVariables(); \ virtual void RegisterSaveData(); \ virtual void RegisterInputData(); \ virtual size_t SizeOfThis() \ { \ /* -4 because the vtable is 4 bytes */ \ return sizeof(entity) - 4; \ } \ \ virtual void Serialize(std::ostream& o) \ { \ CBaseEntity::Serialize(o, #entity, this); \ } \ \ virtual bool Unserialize(std::istream& i) \ { \ return CBaseEntity::Unserialize(i, #entity, this); \ } \ // Third parameter: how many interfaces does the class have? #define REGISTER_ENTITY_CLASS_INTERFACES(entity, base, iface) \ DECLARE_CLASS(entity, base); \ public: \ static void RegisterCallback##entity() \ { \ entity* pEntity = new entity(); \ pEntity->m_sClassName = #entity; \ CBaseEntity::Register(pEntity); \ delete pEntity; \ } \ static const char* Get##entity##ParentClass() { return #base; } \ \ virtual const char* GetClassName() { return #entity; } \ virtual void RegisterNetworkVariables(); \ virtual void RegisterSaveData(); \ virtual void RegisterInputData(); \ virtual size_t SizeOfThis() \ { \ return sizeof(entity) - sizeof(BaseClass) - iface*4; \ } \ \ virtual void Serialize(std::ostream& o) \ { \ BaseClass::Serialize(o); \ \ CBaseEntity::Serialize(o, #entity, this); \ } \ \ virtual bool Unserialize(std::istream& i) \ { \ if (!BaseClass::Unserialize(i)) \ return false; \ \ return CBaseEntity::Unserialize(i, #entity, this); \ } \ #define REGISTER_ENTITY_CLASS(entity, base) \ REGISTER_ENTITY_CLASS_INTERFACES(entity, base, 0) #define NETVAR_TABLE_BEGIN(entity) \ void entity::RegisterNetworkVariables() \ { \ const char* pszEntity = #entity; \ CEntityRegistration* pRegistration = GetRegisteredEntity(GetClassName()); \ pRegistration->m_aNetworkVariables.clear(); \ CGameServer* pGameServer = GameServer(); \ CNetworkedVariableData* pVarData = NULL; \ #define NETVAR_DEFINE(type, name) \ pRegistration->m_aNetworkVariables.push_back(CNetworkedVariableData()); \ pVarData = &pRegistration->m_aNetworkVariables[pRegistration->m_aNetworkVariables.size()-1]; \ TAssert(!!dynamic_cast<CNetworkedVariableBase*>(&name)); \ pVarData->m_iOffset = (((size_t)((void*)((CNetworkedVariableBase*)&name)))) - ((size_t)((CBaseEntity*)this)); \ pVarData->m_pszName = #name; \ pVarData->m_pfnChanged = NULL; \ pVarData->m_flUpdateInterval = 0; \ #define NETVAR_DEFINE_CALLBACK(type, name, callback) \ NETVAR_DEFINE(type, name); \ pVarData->m_pfnChanged = callback; \ #define NETVAR_DEFINE_INTERVAL(type, name, interval) \ NETVAR_DEFINE(type, name); \ pVarData->m_flUpdateInterval = interval; \ #define NETVAR_TABLE_END() \ CheckTables(pszEntity); \ } \ #define SAVEDATA_TABLE_BEGIN(entity) \ void entity::RegisterSaveData() \ { \ CEntityRegistration* pRegistration = GetRegisteredEntity(GetClassName()); \ pRegistration->m_aSaveData.clear(); \ CGameServer* pGameServer = GameServer(); \ CSaveData* pSaveData = NULL; \ #define SAVEDATA_DEFINE(copy, type, name) \ pSaveData = &pRegistration->m_aSaveData.push_back(); \ pSaveData->m_eType = copy; \ pSaveData->m_pszVariableName = #name; \ if (copy == CSaveData::DATA_NETVAR) \ pSaveData->m_iOffset = (((size_t)((void*)((CNetworkedVariableBase*)&name)))) - ((size_t)((void*)this)); \ else \ pSaveData->m_iOffset = (((size_t)((void*)&name))) - ((size_t)((void*)this)); \ pSaveData->m_iSizeOfVariable = sizeof(name); \ pSaveData->m_iSizeOfType = sizeof(type); \ pSaveData->m_pfnResizeVector = &ResizeVectorTmpl<type>; \ pGameServer->GenerateSaveCRC(pSaveData->m_eType); \ pGameServer->GenerateSaveCRC(pSaveData->m_iOffset); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfVariable); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfType); \ #define SAVEDATA_OMIT(name) \ pSaveData = &pRegistration->m_aSaveData.push_back(); \ pSaveData->m_eType = CSaveData::DATA_OMIT; \ pSaveData->m_pszVariableName = #name; \ pSaveData->m_iOffset = (((size_t)((void*)&name))) - ((size_t)((void*)this)); \ pSaveData->m_iSizeOfVariable = sizeof(name); \ pSaveData->m_iSizeOfType = 0; \ pSaveData->m_pfnResizeVector = NULL; \ pGameServer->GenerateSaveCRC(pSaveData->m_eType); \ pGameServer->GenerateSaveCRC(pSaveData->m_iOffset); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfVariable); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfType); \ #define SAVEDATA_DEFINE_OUTPUT(name) \ pSaveData = &pRegistration->m_aSaveData.push_back(); \ pSaveData->m_eType = CSaveData::DATA_OUTPUT; \ pSaveData->m_pszVariableName = "m_Output_" #name; \ pSaveData->m_iOffset = (((size_t)((void*)&m_Output_##name))) - ((size_t)((void*)this)); \ pSaveData->m_iSizeOfVariable = sizeof(m_Output_##name); \ pSaveData->m_iSizeOfType = sizeof(CEntityOutput); \ pSaveData->m_pfnResizeVector = NULL; \ pGameServer->GenerateSaveCRC(pSaveData->m_eType); \ pGameServer->GenerateSaveCRC(pSaveData->m_iOffset); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfVariable); \ pGameServer->GenerateSaveCRC(pSaveData->m_iSizeOfType); \ #define SAVEDATA_TABLE_END() \ CheckSaveDataSize(pRegistration); \ } \ #define INPUTS_TABLE_BEGIN(entity) \ void entity::RegisterInputData() \ { \ CEntityRegistration* pRegistration = GetRegisteredEntity(GetClassName()); \ pRegistration->m_aInputs.clear(); \ #define INPUT_DEFINE(name) \ pRegistration->m_aInputs[#name].m_sName = #name; \ pRegistration->m_aInputs[#name].m_pfnCallback = &name##InputCallback; \ #define INPUTS_TABLE_END() \ } \ class CTeam; class CBaseEntity { friend class CGameServer; REGISTER_ENTITY_CLASS_NOBASE(CBaseEntity); public: CBaseEntity(); virtual ~CBaseEntity(); public: virtual void Precache() {}; virtual void Spawn(); DECLARE_ENTITY_OUTPUT(OnSpawn); void SetName(const eastl::string& sName) { m_sName = sName; }; eastl::string GetName() { return m_sName; }; virtual TFloat GetBoundingRadius() const { return 0; }; virtual TFloat GetRenderRadius() const { return GetBoundingRadius(); }; void SetModel(const tstring& sModel); void SetModel(size_t iModel); size_t GetModel() const { return m_iModel; }; virtual Matrix4x4 GetRenderTransform() const { return Matrix4x4(GetGlobalTransform()); }; virtual Vector GetRenderOrigin() const { return Vector(GetGlobalOrigin()); }; virtual EAngle GetRenderAngles() const { return GetGlobalAngles(); }; void SetMoveParent(CBaseEntity* pParent); CBaseEntity* GetMoveParent() const { return m_hMoveParent; }; bool HasMoveParent() const { return m_hMoveParent != NULL; }; void InvalidateGlobalTransforms(); const TMatrix& GetGlobalTransform(); TMatrix GetGlobalTransform() const; void SetGlobalTransform(const TMatrix& m); TMatrix GetGlobalToLocalTransform(); TMatrix GetGlobalToLocalTransform() const; virtual TVector GetGlobalOrigin(); virtual EAngle GetGlobalAngles(); virtual TVector GetGlobalOrigin() const; virtual EAngle GetGlobalAngles() const; void SetGlobalOrigin(const TVector& vecOrigin); void SetGlobalAngles(const EAngle& angAngles); virtual TVector GetGlobalVelocity(); virtual TVector GetGlobalVelocity() const; virtual inline TVector GetGlobalGravity() const { return m_vecGlobalGravity; }; void SetGlobalGravity(const TVector& vecGravity) { m_vecGlobalGravity = vecGravity; }; const TMatrix& GetLocalTransform() const { return m_mLocalTransform; } void SetLocalTransform(const TMatrix& m); const Quaternion& GetLocalRotation() const { return m_qLocalRotation; } void SetLocalRotation(const Quaternion& q); virtual inline TVector GetLocalOrigin() const { return m_vecLocalOrigin; }; void SetLocalOrigin(const TVector& vecOrigin); virtual void OnSetLocalOrigin(const TVector& vecOrigin) {} inline TVector GetLastLocalOrigin() const { return m_vecLastLocalOrigin; }; void SetLastLocalOrigin(const TVector& vecOrigin) { m_vecLastLocalOrigin = vecOrigin; }; inline TVector GetLastGlobalOrigin() const; inline TVector GetLocalVelocity() const { return m_vecLocalVelocity; }; void SetLocalVelocity(const TVector& vecVelocity); inline EAngle GetLocalAngles() const { return m_angLocalAngles; }; void SetLocalAngles(const EAngle& angLocalAngles); virtual TVector GetUpVector() const { return TVector(0, 1, 0); }; bool GetSimulated() const { return m_bSimulated; }; void SetSimulated(bool bSimulated) { m_bSimulated = bSimulated; }; size_t GetHandle() const { return m_iHandle; } virtual float GetTotalHealth() const { return m_flTotalHealth; } virtual void SetTotalHealth(float flHealth) { m_flTotalHealth = m_flHealth = flHealth; } virtual float GetHealth() const { return m_flHealth; } virtual bool IsAlive() { return m_flHealth > 0; } class CTeam* GetTeam() const; void SetTeam(class CTeam* pTeam); virtual void OnTeamChange() {}; virtual void ClientUpdate(int iClient); virtual void ClientEnterGame(); virtual void TakeDamage(CBaseEntity* pAttacker, CBaseEntity* pInflictor, damagetype_t eDamageType, float flDamage, bool bDirectHit = true); virtual bool TakesDamage() const { return m_bTakeDamage; }; DECLARE_ENTITY_OUTPUT(OnTakeDamage); void Kill(); void Killed(CBaseEntity* pKilledBy); virtual void OnKilled(CBaseEntity* pKilledBy) {}; DECLARE_ENTITY_OUTPUT(OnKilled); void SetActive(bool bActive); bool IsActive() const { return m_bActive; }; virtual void OnActivated() {}; virtual void OnDeactivated() {}; DECLARE_ENTITY_INPUT(Activate); DECLARE_ENTITY_INPUT(Deactivate); DECLARE_ENTITY_INPUT(ToggleActive); DECLARE_ENTITY_OUTPUT(OnActivated); DECLARE_ENTITY_OUTPUT(OnDeactivated); virtual bool ShouldRender() const { return false; }; virtual bool ShouldRenderModel() const { return true; }; virtual void PreRender(bool bTransparent) const {}; virtual void ModifyContext(class CRenderingContext* pContext, bool bTransparent) const {}; void Render(bool bTransparent) const; virtual void OnRender(class CRenderingContext* pContext, bool bTransparent) const {}; virtual void PostRender(bool bTransparent) const {}; void Delete(); virtual void OnDeleted() {}; virtual void OnDeleted(class CBaseEntity* pEntity) {}; bool IsDeleted() { return m_bDeleted; } void SetDeleted() { m_bDeleted = true; } DECLARE_ENTITY_INPUT(Delete); virtual void Think() {}; virtual bool ShouldSimulate() const { return GetSimulated(); }; virtual void Touching(CBaseEntity* pOther) {}; void CallInput(const eastl::string& sName, const tstring& sArgs); void CallOutput(const eastl::string& sName); void AddOutputTarget(const eastl::string& sName, const eastl::string& sTargetName, const eastl::string& sInput, const eastl::string& sArgs = "", bool bKill = false); void RemoveOutputs(const eastl::string& sName); DECLARE_ENTITY_INPUT(RemoveOutput); void EmitSound(const tstring& sSound, float flVolume = 1.0f, bool bLoop = false); void StopSound(const tstring& sModel); bool IsSoundPlaying(const tstring& sModel); void SetSoundVolume(const tstring& sModel, float flVolume); virtual TFloat Distance(const TVector& vecSpot) const; virtual bool CollideLocal(const TVector& v1, const TVector& v2, TVector& vecPoint, TVector& vecNormal); virtual bool Collide(const TVector& v1, const TVector& v2, TVector& vecPoint, TVector& vecNormal); virtual bool ShouldCollide() const { return false; } virtual bool UsesRaytracedCollision() { return false; } size_t GetSpawnSeed() const { return m_iSpawnSeed; } void SetSpawnSeed(size_t iSpawnSeed); float GetSpawnTime() const { return m_flSpawnTime; } void SetSpawnTime(float flSpawnTime) { m_flSpawnTime = flSpawnTime; }; bool HasIssuedClientSpawn() { return m_bClientSpawn; } void IssueClientSpawn(); virtual void ClientSpawn(); CSaveData* GetSaveData(const char* pszName); CNetworkedVariableData* GetNetworkVariable(const char* pszName); CEntityInput* GetInput(const char* pszName); virtual void OnSerialize(std::ostream& o) {}; virtual bool OnUnserialize(std::istream& i) { return true; }; void CheckSaveDataSize(CEntityRegistration* pRegistration); void CheckTables(const char* pszEntity); static CBaseEntity* GetEntity(size_t iHandle); template <class T> static T* GetEntityType(size_t iHandle) { CBaseEntity* pEntity = GetEntity(iHandle); if (!pEntity) return NULL; return dynamic_cast<T*>(pEntity); } static size_t GetNumEntities(); static void PrecacheModel(const tstring& sModel, bool bStatic = true); static void PrecacheParticleSystem(const tstring& sSystem); static void PrecacheSound(const tstring& sSound); static void PrecacheTexture(const tstring& sTexture); public: static void RegisterEntity(const char* pszClassName, const char* pszParentClass, EntityCreateCallback pfnCreateCallback, EntityRegisterCallback pfnRegisterCallback); static void Register(CBaseEntity* pEntity); static CEntityRegistration* GetRegisteredEntity(tstring sClassName); static void SerializeEntity(std::ostream& o, CBaseEntity* pEntity); static bool UnserializeEntity(std::istream& i); static void Serialize(std::ostream& o, const char* pszClassName, void* pEntity); static bool Unserialize(std::istream& i, const char* pszClassName, void* pEntity); template <class T> static T* FindClosest(const TVector& vecPoint, CBaseEntity* pFurther = NULL); static void FindEntitiesByName(const eastl::string& sName, eastl::vector<CBaseEntity*>& apEntities); protected: static eastl::map<tstring, CEntityRegistration>& GetEntityRegistration(); protected: eastl::string m_sName; tstring m_sClassName; CNetworkedHandle<CBaseEntity> m_hMoveParent; CNetworkedSTLVector<CEntityHandle<CBaseEntity>> m_ahMoveChildren; bool m_bGlobalTransformsDirty; TMatrix m_mGlobalTransform; CNetworkedVector m_vecGlobalGravity; TMatrix m_mLocalTransform; Quaternion m_qLocalRotation; CNetworkedVector m_vecLocalOrigin; TVector m_vecLastLocalOrigin; CNetworkedEAngle m_angLocalAngles; CNetworkedVector m_vecLocalVelocity; size_t m_iHandle; CNetworkedVariable<bool> m_bTakeDamage; CNetworkedVariable<float> m_flTotalHealth; CNetworkedVariable<float> m_flHealth; float m_flTimeKilled; CNetworkedVariable<bool> m_bActive; CNetworkedHandle<CTeam> m_hTeam; bool m_bSimulated; bool m_bDeleted; bool m_bClientSpawn; eastl::vector<CEntityHandle<CBaseEntity> > m_ahTouching; CNetworkedVariable<int> m_iCollisionGroup; class raytrace::CRaytracer* m_pTracer; CNetworkedVariable<size_t> m_iModel; size_t m_iSpawnSeed; CNetworkedVariable<float> m_flSpawnTime; private: static eastl::vector<CBaseEntity*> s_apEntityList; static size_t s_iEntities; static size_t s_iOverrideEntityListIndex; static size_t s_iNextEntityListIndex; }; #define REGISTER_ENTITY(entity) \ class CRegister##entity \ { \ public: \ CRegister##entity() \ { \ CBaseEntity::RegisterEntity(#entity, entity::Get##entity##ParentClass(), &NewEntity<entity>, &entity::RegisterCallback##entity); \ } \ } s_Register##entity = CRegister##entity(); \ #include "gameserver.h" #include "template_functions.h" template <class T> T* CBaseEntity::FindClosest(const TVector& vecPoint, CBaseEntity* pFurther) { T* pClosest = NULL; TFloat flFurtherDistance = 0; if (pFurther) flFurtherDistance = pFurther->Distance(vecPoint); for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); if (!pEntity) continue; T* pT = dynamic_cast<T*>(pEntity); if (!pT) continue; if (pT == pFurther) continue; TFloat flEntityDistance = pT->Distance(vecPoint); if (pFurther && (flEntityDistance <= flFurtherDistance)) continue; if (!pClosest) { pClosest = pT; continue; } if (flEntityDistance < pClosest->Distance(vecPoint)) pClosest = pT; } return pClosest; } #endif
[ [ [ 1, 2 ], [ 7, 9 ], [ 11, 13 ], [ 36, 36 ], [ 59, 59 ], [ 61, 61 ], [ 74, 111 ], [ 121, 121 ], [ 130, 130 ], [ 139, 139 ], [ 156, 157 ], [ 163, 163 ], [ 172, 172 ], [ 175, 175 ], [ 193, 195 ], [ 199, 200 ], [ 208, 208 ], [ 212, 212 ], [ 218, 221 ], [ 229, 229 ], [ 235, 235 ], [ 251, 251 ], [ 263, 275 ], [ 280, 292 ], [ 307, 308 ], [ 310, 314 ], [ 316, 316 ], [ 318, 318 ], [ 320, 322 ], [ 324, 334 ], [ 336, 337 ], [ 339, 340 ], [ 342, 343 ], [ 345, 370 ], [ 372, 373 ], [ 379, 379 ], [ 381, 381 ], [ 392, 393 ], [ 397, 407 ], [ 411, 415 ], [ 422, 422 ], [ 429, 438 ], [ 440, 440 ], [ 442, 443 ], [ 445, 445 ], [ 449, 450 ], [ 452, 453 ], [ 455, 459 ], [ 461, 461 ], [ 467, 467 ], [ 482, 485 ], [ 488, 488 ], [ 490, 490 ], [ 499, 499 ], [ 501, 502 ], [ 504, 504 ], [ 507, 522 ], [ 531, 533 ], [ 535, 535 ], [ 537, 537 ], [ 562, 562 ], [ 566, 568 ], [ 570, 570 ], [ 574, 577 ], [ 593, 594 ] ], [ [ 3, 6 ], [ 10, 10 ], [ 14, 35 ], [ 37, 58 ], [ 60, 60 ], [ 62, 73 ], [ 112, 120 ], [ 122, 129 ], [ 131, 138 ], [ 140, 155 ], [ 158, 162 ], [ 164, 171 ], [ 173, 174 ], [ 176, 192 ], [ 196, 198 ], [ 201, 207 ], [ 209, 211 ], [ 213, 217 ], [ 222, 228 ], [ 230, 234 ], [ 236, 250 ], [ 252, 262 ], [ 276, 279 ], [ 293, 306 ], [ 309, 309 ], [ 315, 315 ], [ 317, 317 ], [ 319, 319 ], [ 323, 323 ], [ 335, 335 ], [ 338, 338 ], [ 341, 341 ], [ 344, 344 ], [ 371, 371 ], [ 374, 378 ], [ 380, 380 ], [ 382, 391 ], [ 394, 396 ], [ 408, 410 ], [ 416, 421 ], [ 423, 428 ], [ 439, 439 ], [ 441, 441 ], [ 444, 444 ], [ 446, 448 ], [ 451, 451 ], [ 454, 454 ], [ 460, 460 ], [ 462, 466 ], [ 468, 481 ], [ 486, 487 ], [ 489, 489 ], [ 491, 498 ], [ 500, 500 ], [ 503, 503 ], [ 505, 506 ], [ 523, 530 ], [ 534, 534 ], [ 536, 536 ], [ 538, 561 ], [ 563, 565 ], [ 569, 569 ], [ 571, 573 ], [ 578, 592 ], [ 595, 610 ] ] ]
d773d832bd3ace0f62babc08f5dddbbbd078abfe
c85f27488ce1a1d93a2a3eb0a1ca160100c6d3ad
/Light.cpp
16432a36cfe7baae8448d3fc6e79cda4c0e83b4c
[]
no_license
cheokwan/cs184-ds-dw-raytracer
ce57e682338afdd5ecdef9cbaba09f32bcf9e2be
f84d21eb9d39ee1316acea857dc36e1ef51070ac
refs/heads/master
2021-01-19T08:26:39.715985
2010-04-27T22:48:39
2010-04-27T22:48:39
32,121,050
0
0
null
null
null
null
UTF-8
C++
false
false
328
cpp
#include "Light.h" Light::Light(double x, double y, double z, Color c, bool lightType){ pos = vec4(x, y, z, 1); color = c; directional = !lightType; attn = vec3(1, 0, 0); } Light::Light(){ color = Color(0, 0, 0); pos = vec4(0, 0, 0, 0); attn = vec3(1, 0, 0); directional = false; } Light::~Light(){ }
[ "samwong99@0be72354-b10b-e666-8ac9-db255acbfd61" ]
[ [ [ 1, 18 ] ] ]
36ac6dabb6be978ea00d86a8cd7e367a84d725e6
40e58042e635ea2a61a6216dc3e143fd3e14709c
/WPILib/Vision/AxisCamera.cpp
45139e733a05be934ee6badbef38c5e23bd45241
[]
no_license
chopshop-166/frc-2011
005bb7f0d02050a19bdb2eb33af145d5d2916a4d
7ef98f84e544a17855197f491fc9f80247698dd3
refs/heads/master
2016-09-05T10:59:54.976527
2011-10-20T22:50:17
2011-10-20T22:50:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,182
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include <string.h> #include "Synchronized.h" #include "AxisCamera.h" #include "PCVideoServer.h" /** Private NI function to decode JPEG */ IMAQ_FUNC int Priv_ReadJPEGString_C(Image* _image, const unsigned char* _string, UINT32 _stringLength); // Max packet without jumbo frames is 1500... add 36 because?? #define kMaxPacketSize 1536 #define kImageBufferAllocationIncrement 1000 AxisCamera* AxisCamera::m_instance = NULL; /** * AxisCamera constructor */ AxisCamera::AxisCamera(const char *ipAddress) : AxisCameraParams(ipAddress) , m_cameraSocket (0) , m_protectedImageBuffer(NULL) , m_protectedImageBufferLength (0) , m_protectedImageSize (0) , m_protectedImageSem (NULL) , m_freshImage (false) , m_imageStreamTask("cameraTask", (FUNCPTR)s_ImageStreamTaskFunction) { m_protectedImageSem = semMCreate(SEM_Q_PRIORITY | SEM_INVERSION_SAFE | SEM_DELETE_SAFE); m_imageStreamTask.Start((int)this); } /** * Destructor */ AxisCamera::~AxisCamera() { m_imageStreamTask.Stop(); close(m_cameraSocket); SemSet_t::iterator it = m_newImageSemSet.begin(); SemSet_t::iterator end = m_newImageSemSet.end(); for (;it != end; it++) { semDelete(*it); } m_newImageSemSet.clear(); semDelete(m_protectedImageSem); m_instance = NULL; } /** * Get a pointer to the AxisCamera object, if the object does not exist, create it * @return reference to AxisCamera object */ AxisCamera& AxisCamera::GetInstance() { if (NULL == m_instance) { // Since this is a singleton for now, just use the default IP address. m_instance = new AxisCamera(); // TODO: Keep track of this so it can be shut down! new PCVideoServer(); } return *m_instance; } /** * Called by Java to delete the camera... how thoughtful */ void AxisCamera::DeleteInstance() { delete m_instance; } /** * Return true if the latest image from the camera has not been retrieved by calling GetImage() yet. * @return true if the image has not been retrieved yet. */ bool AxisCamera::IsFreshImage() { return m_freshImage; } /** * Get the semaphore to be used to synchronize image access with camera acquisition * * Call semTake on the returned semaphore to block until a new image is acquired. * * The semaphore is owned by the AxisCamera class and will be deleted when the class is destroyed. * @return A semaphore to notify when new image is received */ SEM_ID AxisCamera::GetNewImageSem() { SEM_ID sem = semBCreate (SEM_Q_PRIORITY, SEM_EMPTY); m_newImageSemSet.insert(sem); return sem; } /** * Get an image from the camera and store it in the provided image. * @param image The imaq image to store the result in. This must be an HSL or RGB image * This function is called by Java. * @return 1 upon success, zero on a failure */ int AxisCamera::GetImage(Image* imaqImage) { if (m_protectedImageBuffer == NULL) return 0; Synchronized sync(m_protectedImageSem); Priv_ReadJPEGString_C(imaqImage, (unsigned char*)m_protectedImageBuffer, m_protectedImageSize); m_freshImage = false; return 1; } /** * Get an image from the camera and store it in the provided image. * @param image The image to store the result in. This must be an HSL or RGB image * @return 1 upon success, zero on a failure */ int AxisCamera::GetImage(ColorImage* image) { return GetImage(image->GetImaqImage()); } /** * Instantiate a new image object and fill it with the latest image from the camera. * * The returned pointer is owned by the caller and is their responsibility to delete. * @return a pointer to an HSLImage object */ HSLImage* AxisCamera::GetImage() { HSLImage *image = new HSLImage(); GetImage(image); return image; } /** * Copy an image into an existing buffer. * This copies an image into an existing buffer rather than creating a new image * in memory. That way a new image is only allocated when the image being copied is * larger than the destination. * This method is called by the PCVideoServer class. * @param imageData The destination image. * @param numBytes The size of the destination image. * @return 0 if failed (no source image or no memory), 1 if success. */ int AxisCamera::CopyJPEG(char **destImage, int &destImageSize, int &destImageBufferSize) { Synchronized sync(m_protectedImageSem); wpi_assert(destImage != NULL); if (m_protectedImageBuffer == NULL) return 0; // if no source image if (destImageBufferSize < m_protectedImageSize) // if current destination buffer too small { if (*destImage != NULL) delete [] *destImage; destImageBufferSize = m_protectedImageSize + kImageBufferAllocationIncrement; *destImage = new char[destImageBufferSize]; if (*destImage == NULL) return 0; } // copy this image into destination buffer wpi_assert(*destImage != NULL); wpi_assert(m_protectedImageBuffer != NULL); wpi_assert(m_protectedImageSize > 0); // TODO: Is this copy realy necessary... perhaps we can simply transmit while holding the protected buffer memcpy(*destImage, m_protectedImageBuffer, m_protectedImageSize); destImageSize = m_protectedImageSize; return 1; } /** * Static interface that will cause an instantiation if necessary. * This static stub is directly spawned as a task to read images from the camera. */ int AxisCamera::s_ImageStreamTaskFunction(AxisCamera *thisPtr) { return thisPtr->ImageStreamTaskFunction(); } /** * Task spawned by AxisCamera constructor to receive images from cam * If setNewImageSem has been called, this function does a semGive on each new image * Images can be accessed by calling getImage() */ int AxisCamera::ImageStreamTaskFunction() { // Loop on trying to setup the camera connection. This happens in a background // thread so it shouldn't effect the operation of user programs. while (1) { char * requestString = "GET /mjpg/video.mjpg HTTP/1.1\n\ User-Agent: HTTPStreamClient\n\ Connection: Keep-Alive\n\ Cache-Control: no-cache\n\ Authorization: Basic RlJDOkZSQw==\n\n"; semTake(m_socketPossessionSem, WAIT_FOREVER); m_cameraSocket = CreateCameraSocket(requestString); if (m_cameraSocket == 0) { // Don't hammer the camera if it isn't ready. semGive(m_socketPossessionSem); taskDelay(1000); } else { ReadImagesFromCamera(); } } } /** * This function actually reads the images from the camera. */ int AxisCamera::ReadImagesFromCamera() { char *imgBuffer = NULL; int imgBufferLength = 0; //Infinite loop, task deletion handled by taskDeleteHook // Socket cleanup handled by destructor // TODO: these recv calls must be non-blocking. Otherwise if the camera // fails during a read, the code hangs and never retries when the camera comes // back up. int counter = 2; while (1) { char initialReadBuffer[kMaxPacketSize] = ""; char intermediateBuffer[1]; char *trailingPtr = initialReadBuffer; int trailingCounter = 0; while (counter) { // TODO: fix me... this cannot be the most efficient way to approach this, reading one byte at a time. if(recv(m_cameraSocket, intermediateBuffer, 1, 0) == ERROR) { perror ("AxisCamera: Failed to read image header"); close (m_cameraSocket); return (ERROR); } strncat(initialReadBuffer, intermediateBuffer, 1); // trailingCounter ensures that we start looking for the 4 byte string after // there is at least 4 bytes total. Kind of obscure. // look for 2 blank lines (\r\n) if (NULL != strstr(trailingPtr, "\r\n\r\n")) { --counter; } if (++trailingCounter >= 4) { trailingPtr++; } } counter = 1; char *contentLength = strstr(initialReadBuffer, "Content-Length: "); if (contentLength == NULL) { perror("AxisCamera: No content-length token found in packet"); close(m_cameraSocket); return(ERROR); } contentLength = contentLength + 16; // skip past "content length" int readLength = atol(contentLength); // get the image byte count // Make sure buffer is large enough if (imgBufferLength < readLength) { if (imgBuffer) delete[] imgBuffer; imgBufferLength = readLength + kImageBufferAllocationIncrement; imgBuffer = new char[imgBufferLength]; if (imgBuffer == NULL) { imgBufferLength = 0; continue; } } // Read the image data for "Content-Length" bytes int bytesRead = 0; int remaining = readLength; while(bytesRead < readLength) { int bytesThisRecv = recv(m_cameraSocket, &imgBuffer[bytesRead], remaining, 0); bytesRead += bytesThisRecv; remaining -= bytesThisRecv; } // Update image UpdatePublicImageFromCamera(imgBuffer, readLength); if (semTake(m_paramChangedSem, NO_WAIT) == OK) { // params need to be updated: close the video stream; release the camera. close(m_cameraSocket); semGive(m_socketPossessionSem); return(0); } } } /** * Copy the image from private buffer to shared buffer. * @param imgBuffer The buffer containing the image * @param bufLength The length of the image */ void AxisCamera::UpdatePublicImageFromCamera(char *imgBuffer, int imgSize) { { Synchronized sync(m_protectedImageSem); // Adjust the buffer size if current destination buffer is too small. if (m_protectedImageBufferLength < imgSize) { if (m_protectedImageBuffer != NULL) delete [] m_protectedImageBuffer; m_protectedImageBufferLength = imgSize + kImageBufferAllocationIncrement; m_protectedImageBuffer = new char[m_protectedImageBufferLength]; if (m_protectedImageBuffer == NULL) { m_protectedImageBufferLength = 0; return; } } memcpy(m_protectedImageBuffer, imgBuffer, imgSize); m_protectedImageSize = imgSize; } m_freshImage = true; // Notify everyone who is interested. SemSet_t::iterator it = m_newImageSemSet.begin(); SemSet_t::iterator end = m_newImageSemSet.end(); for (;it != end; it++) { semGive(*it); } } /** * Implement the pure virtual interface so that when parameter changes require a restart, the image task can be bounced. */ void AxisCamera::RestartCameraTask() { m_imageStreamTask.Stop(); m_imageStreamTask.Start((int)this); } // C bindings used by Java // These need to stay as is or Java has to change void AxisCameraStart() { AxisCamera::GetInstance(); } int AxisCameraGetImage (Image* image) { return AxisCamera::GetInstance().GetImage(image); } void AxisCameraWriteBrightness(int brightness) { AxisCamera::GetInstance().WriteBrightness(brightness); } int AxisCameraGetBrightness() { return AxisCamera::GetInstance().GetBrightness(); } void AxisCameraWriteWhiteBalance(AxisCameraParams::WhiteBalance_t whiteBalance) { AxisCamera::GetInstance().WriteWhiteBalance(whiteBalance); } AxisCameraParams::WhiteBalance_t AxisCameraGetWhiteBalance() { return AxisCamera::GetInstance().GetWhiteBalance(); } void AxisCameraWriteColorLevel(int colorLevel) { AxisCamera::GetInstance().WriteColorLevel(colorLevel); } int AxisCameraGetColorLevel() { return AxisCamera::GetInstance().GetColorLevel(); } void AxisCameraWriteExposureControl(AxisCameraParams::Exposure_t exposure) { AxisCamera::GetInstance().WriteExposureControl(exposure); } AxisCameraParams::Exposure_t AxisCameraGetExposureControl() { return AxisCamera::GetInstance().GetExposureControl(); } void AxisCameraWriteExposurePriority(int exposure) { AxisCamera::GetInstance().WriteExposurePriority(exposure); } int AxisCameraGetExposurePriority() { return AxisCamera::GetInstance().GetExposurePriority(); } void AxisCameraWriteMaxFPS(int maxFPS) { AxisCamera::GetInstance().WriteMaxFPS(maxFPS); } int AxisCameraGetMaxFPS() { return AxisCamera::GetInstance().GetMaxFPS(); } void AxisCameraWriteResolution(AxisCameraParams::Resolution_t resolution) { AxisCamera::GetInstance().WriteResolution(resolution); } AxisCameraParams::Resolution_t AxisCameraGetResolution() { return AxisCamera::GetInstance().GetResolution(); } void AxisCameraWriteCompression(int compression) { AxisCamera::GetInstance().WriteCompression(compression); } int AxisCameraGetCompression() { return AxisCamera::GetInstance().GetCompression(); } void AxisCameraWriteRotation(AxisCameraParams::Rotation_t rotation) { AxisCamera::GetInstance().WriteRotation(rotation); } AxisCameraParams::Rotation_t AxisCameraGetRotation() { return AxisCamera::GetInstance().GetRotation(); } void AxisCameraDeleteInstance() { AxisCamera::GetInstance().DeleteInstance(); } int AxisCameraFreshImage() { return AxisCamera::GetInstance().IsFreshImage(); }
[ [ [ 1, 11 ], [ 14, 92 ], [ 94, 94 ], [ 96, 134 ], [ 136, 202 ], [ 204, 207 ], [ 209, 210 ], [ 215, 226 ], [ 228, 295 ], [ 303, 464 ] ], [ [ 12, 13 ], [ 93, 93 ], [ 95, 95 ], [ 135, 135 ], [ 203, 203 ], [ 208, 208 ], [ 211, 214 ], [ 227, 227 ], [ 296, 302 ] ] ]
a359dceb6a2091cf93a6403540e8e563554bcba3
fd3f2268460656e395652b11ae1a5b358bfe0a59
/cryptopp/test.cpp
ec81f0d704d45fccbe42a5bbc1062d1e2503b1c7
[ "LicenseRef-scancode-cryptopp", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
26,803
cpp
// test.cpp - written and placed in the public domain by Wei Dai #define _CRT_SECURE_NO_DEPRECATE #define CRYPTOPP_DEFAULT_NO_DLL #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include "dll.h" #include "md5.h" #include "ripemd.h" #include "rng.h" #include "gzip.h" #include "default.h" #include "randpool.h" #include "ida.h" #include "base64.h" #include "socketft.h" #include "wait.h" #include "factory.h" #include "whrlpool.h" #include "tiger.h" #include "validate.h" #include "bench.h" #include <iostream> #include <time.h> #ifdef CRYPTOPP_WIN32_AVAILABLE #include <windows.h> #endif #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh) #include <netinet/in.h> #include <netinet/tcp.h> #endif #if (_MSC_VER >= 1000) #include <crtdbg.h> // for the debug heap #endif #if defined(__MWERKS__) && defined(macintosh) #include <console.h> #endif #ifdef __BORLANDC__ #pragma comment(lib, "cryptlib_bds.lib") #pragma comment(lib, "ws2_32.lib") #endif USING_NAMESPACE(CryptoPP) USING_NAMESPACE(std) const int MAX_PHRASE_LENGTH=250; void RegisterFactories(); void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed); string RSAEncryptString(const char *pubFilename, const char *seed, const char *message); string RSADecryptString(const char *privFilename, const char *ciphertext); void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename); bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename); void DigestFile(const char *file); void HmacFile(const char *hexKey, const char *file); void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile); string EncryptString(const char *plaintext, const char *passPhrase); string DecryptString(const char *ciphertext, const char *passPhrase); void EncryptFile(const char *in, const char *out, const char *passPhrase); void DecryptFile(const char *in, const char *out, const char *passPhrase); void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed); void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames); void InformationDisperseFile(int threshold, int nShares, const char *filename); void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames); void GzipFile(const char *in, const char *out, int deflate_level); void GunzipFile(const char *in, const char *out); void Base64Encode(const char *infile, const char *outfile); void Base64Decode(const char *infile, const char *outfile); void HexEncode(const char *infile, const char *outfile); void HexDecode(const char *infile, const char *outfile); void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort); void FIPS140_SampleApplication(); void FIPS140_GenerateRandomFiles(); bool Validate(int, bool, const char *); int (*AdhocTest)(int argc, char *argv[]) = NULL; static OFB_Mode<AES>::Encryption s_globalRNG; RandomNumberGenerator & GlobalRNG() { return s_globalRNG; } int CRYPTOPP_API main(int argc, char *argv[]) { #ifdef _CRTDBG_LEAK_CHECK_DF // Turn on leak-checking int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tempflag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag( tempflag ); #endif #if defined(__MWERKS__) && defined(macintosh) argc = ccommand(&argv); #endif try { RegisterFactories(); std::string seed = IntToString(time(NULL)); seed.resize(16); s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data()); std::string command, executableName, macFilename; if (argc < 2) command = 'h'; else command = argv[1]; if (command == "g") { char seed[1024], privFilename[128], pubFilename[128]; unsigned int keyLength; cout << "Key length in bits: "; cin >> keyLength; cout << "\nSave private key to file: "; cin >> privFilename; cout << "\nSave public key to file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); GenerateRSAKey(keyLength, privFilename, pubFilename, seed); } else if (command == "rs") RSASignFile(argv[2], argv[3], argv[4]); else if (command == "rv") { bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]); cout << (verified ? "valid signature" : "invalid signature") << endl; } else if (command == "r") { char privFilename[128], pubFilename[128]; char seed[1024], message[1024]; cout << "Private key file: "; cin >> privFilename; cout << "\nPublic key file: "; cin >> pubFilename; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); cout << "\nMessage: "; cin.getline(message, 1024); string ciphertext = RSAEncryptString(pubFilename, seed, message); cout << "\nCiphertext: " << ciphertext << endl; string decrypted = RSADecryptString(privFilename, ciphertext.c_str()); cout << "\nDecrypted: " << decrypted << endl; } else if (command == "mt") { MaurerRandomnessTest mt; FileStore fs(argv[2]); fs.TransferAllTo(mt); cout << "Maurer Test Value: " << mt.GetTestValue() << endl; } else if (command == "mac_dll") { // sanity check on file size std::fstream dllFile(argv[2], ios::in | ios::out | ios::binary); std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg(); if (fileEnd > 20*1000*1000) { cerr << "Input file too large (more than 20 MB).\n"; return 1; } // read file into memory unsigned int fileSize = (unsigned int)fileEnd; SecByteBlock buf(fileSize); dllFile.seekg(0, std::ios_base::beg); dllFile.read((char *)buf.begin(), fileSize); // find positions of relevant sections in the file, based on version 8 of documentation from http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx word32 coffPos = *(word16 *)(buf+0x3c); word32 optionalHeaderPos = coffPos + 24; word16 optionalHeaderMagic = *(word16 *)(buf+optionalHeaderPos); if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b) { cerr << "Target file is not a PE32 or PE32+ image.\n"; return 3; } word32 checksumPos = optionalHeaderPos + 64; word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144); word32 certificateTablePos = *(word32 *)(buf+certificateTableDirectoryPos); word32 certificateTableSize = *(word32 *)(buf+certificateTableDirectoryPos+4); if (certificateTableSize != 0) cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n"; // find where to place computed MAC byte mac[] = CRYPTOPP_DUMMY_DLL_MAC; byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac)); if (found == buf.end()) { cerr << "MAC placeholder not found. Possibly the actual MAC was already placed.\n"; return 2; } word32 macPos = (unsigned int)(found-buf.begin()); // compute MAC member_ptr<MessageAuthenticationCode> pMac(NewIntegrityCheckingMAC()); assert(pMac->DigestSize() == sizeof(mac)); MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac)))); f.AddRangeToSkip(0, checksumPos, 4); f.AddRangeToSkip(0, certificateTableDirectoryPos, 8); f.AddRangeToSkip(0, macPos, sizeof(mac)); f.AddRangeToSkip(0, certificateTablePos, certificateTableSize); f.PutMessageEnd(buf.begin(), buf.size()); // place MAC cout << "Placing MAC in file " << argv[2] << ", location " << macPos << ".\n"; dllFile.seekg(macPos, std::ios_base::beg); dllFile.write((char *)mac, sizeof(mac)); } else if (command == "m") DigestFile(argv[2]); else if (command == "tv") { std::string fname = argv[2]; if (fname.find(".txt") == std::string::npos) fname = "TestVectors/" + fname + ".txt"; return !RunTestDataFile(fname.c_str()); } else if (command == "t") { // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024]; cout << "Passphrase: "; cin.getline(passPhrase, MAX_PHRASE_LENGTH); cout << "\nPlaintext: "; cin.getline(plaintext, 1024); string ciphertext = EncryptString(plaintext, passPhrase); cout << "\nCiphertext: " << ciphertext << endl; string decrypted = DecryptString(ciphertext.c_str(), passPhrase); cout << "\nDecrypted: " << decrypted << endl; return 0; } else if (command == "e64") Base64Encode(argv[2], argv[3]); else if (command == "d64") Base64Decode(argv[2], argv[3]); else if (command == "e16") HexEncode(argv[2], argv[3]); else if (command == "d16") HexDecode(argv[2], argv[3]); else if (command == "e" || command == "d") { char passPhrase[MAX_PHRASE_LENGTH]; cout << "Passphrase: "; cin.getline(passPhrase, MAX_PHRASE_LENGTH); if (command == "e") EncryptFile(argv[2], argv[3], passPhrase); else DecryptFile(argv[2], argv[3], passPhrase); } else if (command == "ss") { char seed[1024]; cout << "\nRandom Seed: "; ws(cin); cin.getline(seed, 1024); SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed); } else if (command == "sr") SecretRecoverFile(argc-3, argv[2], argv+3); else if (command == "id") InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]); else if (command == "ir") InformationRecoverFile(argc-3, argv[2], argv+3); else if (command == "v" || command == "vv") return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL); else if (command == "b") BenchmarkAll(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9); else if (command == "b2") BenchmarkAll2(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9); else if (command == "z") GzipFile(argv[3], argv[4], argv[2][0]-'0'); else if (command == "u") GunzipFile(argv[2], argv[3]); else if (command == "fips") FIPS140_SampleApplication(); else if (command == "fips-rand") FIPS140_GenerateRandomFiles(); else if (command == "ft") ForwardTcpPort(argv[2], argv[3], argv[4]); else if (command == "a") { if (AdhocTest) return (*AdhocTest)(argc, argv); else { cerr << "AdhocTest not defined.\n"; return 1; } } else if (command == "hmac") HmacFile(argv[2], argv[3]); else if (command == "ae") AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]); else if (command == "h") { FileSource usage("TestData/usage.dat", true, new FileSink(cout)); return 1; } else if (command == "V") { cout << CRYPTOPP_VERSION / 100 << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << endl; } else { cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n"; return 1; } return 0; } catch(CryptoPP::Exception &e) { cout << "\nCryptoPP::Exception caught: " << e.what() << endl; return -1; } catch(std::exception &e) { cout << "\nstd::exception caught: " << e.what() << endl; return -2; } } void FIPS140_GenerateRandomFiles() { #ifdef OS_RNG_AVAILABLE DefaultAutoSeededRNG rng; RandomNumberStore store(rng, ULONG_MAX); for (unsigned int i=0; i<100000; i++) store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000); #else cout << "OS provided RNG not available.\n"; exit(-1); #endif } SecByteBlock HexDecodeString(const char *hex) { StringSource ss(hex, true, new HexDecoder); SecByteBlock result((size_t)ss.MaxRetrievable()); ss.Get(result, result.size()); return result; } void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed) { RandomPool randPool; randPool.IncorporateEntropy((byte *)seed, strlen(seed)); RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength); HexEncoder privFile(new FileSink(privFilename)); priv.DEREncode(privFile); privFile.MessageEnd(); RSAES_OAEP_SHA_Encryptor pub(priv); HexEncoder pubFile(new FileSink(pubFilename)); pub.DEREncode(pubFile); pubFile.MessageEnd(); } string RSAEncryptString(const char *pubFilename, const char *seed, const char *message) { FileSource pubFile(pubFilename, true, new HexDecoder); RSAES_OAEP_SHA_Encryptor pub(pubFile); RandomPool randPool; randPool.IncorporateEntropy((byte *)seed, strlen(seed)); string result; StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result)))); return result; } string RSADecryptString(const char *privFilename, const char *ciphertext) { FileSource privFile(privFilename, true, new HexDecoder); RSAES_OAEP_SHA_Decryptor priv(privFile); string result; StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result)))); return result; } void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename) { FileSource privFile(privFilename, true, new HexDecoder); RSASS<PKCS1v15, SHA>::Signer priv(privFile); FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename)))); } bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename) { FileSource pubFile(pubFilename, true, new HexDecoder); RSASS<PKCS1v15, SHA>::Verifier pub(pubFile); FileSource signatureFile(signatureFilename, true, new HexDecoder); if (signatureFile.MaxRetrievable() != pub.SignatureLength()) return false; SecByteBlock signature(pub.SignatureLength()); signatureFile.Get(signature, signature.size()); VerifierFilter *verifierFilter = new VerifierFilter(pub); verifierFilter->Put(signature, pub.SignatureLength()); FileSource f(messageFilename, true, verifierFilter); return verifierFilter->GetLastResult(); } void DigestFile(const char *filename) { SHA1 sha; RIPEMD160 ripemd; SHA256 sha256; Tiger tiger; SHA512 sha512; Whirlpool whirlpool; vector_member_ptrs<HashFilter> filters(6); filters[0].reset(new HashFilter(sha)); filters[1].reset(new HashFilter(ripemd)); filters[2].reset(new HashFilter(tiger)); filters[3].reset(new HashFilter(sha256)); filters[4].reset(new HashFilter(sha512)); filters[5].reset(new HashFilter(whirlpool)); auto_ptr<ChannelSwitch> channelSwitch(new ChannelSwitch); size_t i; for (i=0; i<filters.size(); i++) channelSwitch->AddDefaultRoute(*filters[i]); FileSource(filename, true, channelSwitch.release()); HexEncoder encoder(new FileSink(cout), false); for (i=0; i<filters.size(); i++) { cout << filters[i]->AlgorithmName() << ": "; filters[i]->TransferTo(encoder); cout << "\n"; } } void HmacFile(const char *hexKey, const char *file) { member_ptr<MessageAuthenticationCode> mac; if (strcmp(hexKey, "selftest") == 0) { cerr << "Computing HMAC/SHA1 value for self test.\n"; mac.reset(NewIntegrityCheckingMAC()); } else { std::string decodedKey; StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey))); mac.reset(new HMAC<SHA1>((const byte *)decodedKey.data(), decodedKey.size())); } FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout)))); } void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile) { SecByteBlock key = HexDecodeString(hexKey); SecByteBlock iv = HexDecodeString(hexIV); CTR_Mode<AES>::Encryption aes(key, key.size(), iv); FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile))); } string EncryptString(const char *instr, const char *passPhrase) { string outstr; DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr))); encryptor.Put((byte *)instr, strlen(instr)); encryptor.MessageEnd(); return outstr; } string DecryptString(const char *instr, const char *passPhrase) { string outstr; HexDecoder decryptor(new DefaultDecryptorWithMAC(passPhrase, new StringSink(outstr))); decryptor.Put((byte *)instr, strlen(instr)); decryptor.MessageEnd(); return outstr; } void EncryptFile(const char *in, const char *out, const char *passPhrase) { FileSource f(in, true, new DefaultEncryptorWithMAC(passPhrase, new FileSink(out))); } void DecryptFile(const char *in, const char *out, const char *passPhrase) { FileSource f(in, true, new DefaultDecryptorWithMAC(passPhrase, new FileSink(out))); } void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed) { assert(nShares<=1000); RandomPool rng; rng.IncorporateEntropy((byte *)seed, strlen(seed)); ChannelSwitch *channelSwitch; FileSource source(filename, false, new SecretSharing(rng, threshold, nShares, channelSwitch = new ChannelSwitch)); vector_member_ptrs<FileSink> fileSinks(nShares); string channel; for (int i=0; i<nShares; i++) { char extension[5] = ".000"; extension[1]='0'+byte(i/100); extension[2]='0'+byte((i/10)%10); extension[3]='0'+byte(i%10); fileSinks[i].reset(new FileSink((string(filename)+extension).c_str())); channel = WordToString<word32>(i); fileSinks[i]->Put((byte *)channel.data(), 4); channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL); } source.PumpAll(); } void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames) { assert(threshold<=1000); SecretRecovery recovery(threshold, new FileSink(outFilename)); vector_member_ptrs<FileSource> fileSources(threshold); SecByteBlock channel(4); int i; for (i=0; i<threshold; i++) { fileSources[i].reset(new FileSource(inFilenames[i], false)); fileSources[i]->Pump(4); fileSources[i]->Get(channel, 4); fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4))); } while (fileSources[0]->Pump(256)) for (i=1; i<threshold; i++) fileSources[i]->Pump(256); for (i=0; i<threshold; i++) fileSources[i]->PumpAll(); } void InformationDisperseFile(int threshold, int nShares, const char *filename) { assert(nShares<=1000); ChannelSwitch *channelSwitch; FileSource source(filename, false, new InformationDispersal(threshold, nShares, channelSwitch = new ChannelSwitch)); vector_member_ptrs<FileSink> fileSinks(nShares); string channel; for (int i=0; i<nShares; i++) { char extension[5] = ".000"; extension[1]='0'+byte(i/100); extension[2]='0'+byte((i/10)%10); extension[3]='0'+byte(i%10); fileSinks[i].reset(new FileSink((string(filename)+extension).c_str())); channel = WordToString<word32>(i); fileSinks[i]->Put((byte *)channel.data(), 4); channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL); } source.PumpAll(); } void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames) { assert(threshold<=1000); InformationRecovery recovery(threshold, new FileSink(outFilename)); vector_member_ptrs<FileSource> fileSources(threshold); SecByteBlock channel(4); int i; for (i=0; i<threshold; i++) { fileSources[i].reset(new FileSource(inFilenames[i], false)); fileSources[i]->Pump(4); fileSources[i]->Get(channel, 4); fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4))); } while (fileSources[0]->Pump(256)) for (i=1; i<threshold; i++) fileSources[i]->Pump(256); for (i=0; i<threshold; i++) fileSources[i]->PumpAll(); } void GzipFile(const char *in, const char *out, int deflate_level) { // FileSource(in, true, new Gzip(new FileSink(out), deflate_level)); // use a filter graph to compare decompressed data with original // // Source ----> Gzip ------> Sink // \ | // \ Gunzip // \ | // \ v // > ComparisonFilter EqualityComparisonFilter comparison; Gunzip gunzip(new ChannelSwitch(comparison, "0")); gunzip.SetAutoSignalPropagation(0); FileSink sink(out); ChannelSwitch *cs; Gzip gzip(cs = new ChannelSwitch(sink), deflate_level); cs->AddDefaultRoute(gunzip); cs = new ChannelSwitch(gzip); cs->AddDefaultRoute(comparison, "1"); FileSource source(in, true, cs); comparison.ChannelMessageSeriesEnd("0"); comparison.ChannelMessageSeriesEnd("1"); } void GunzipFile(const char *in, const char *out) { FileSource(in, true, new Gunzip(new FileSink(out))); } void Base64Encode(const char *in, const char *out) { FileSource(in, true, new Base64Encoder(new FileSink(out))); } void Base64Decode(const char *in, const char *out) { FileSource(in, true, new Base64Decoder(new FileSink(out))); } void HexEncode(const char *in, const char *out) { FileSource(in, true, new HexEncoder(new FileSink(out))); } void HexDecode(const char *in, const char *out) { FileSource(in, true, new HexDecoder(new FileSink(out))); } void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, const char *destinationPortName) { #ifdef SOCKETS_AVAILABLE SocketsInitializer sockInit; Socket sockListen, sockSource, sockDestination; int sourcePort = Socket::PortNameToNumber(sourcePortName); int destinationPort = Socket::PortNameToNumber(destinationPortName); sockListen.Create(); sockListen.Bind(sourcePort); setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1); cout << "Listing on port " << sourcePort << ".\n"; sockListen.Listen(); sockListen.Accept(sockSource); cout << "Connection accepted on port " << sourcePort << ".\n"; sockListen.CloseSocket(); cout << "Making connection to " << destinationHost << ", port " << destinationPort << ".\n"; sockDestination.Create(); sockDestination.Connect(destinationHost, destinationPort); cout << "Connection made to " << destinationHost << ", starting to forward.\n"; SocketSource out(sockSource, false, new SocketSink(sockDestination)); SocketSource in(sockDestination, false, new SocketSink(sockSource)); WaitObjectContainer waitObjects; while (!(in.SourceExhausted() && out.SourceExhausted())) { waitObjects.Clear(); out.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - out", NULL)); in.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - in", NULL)); waitObjects.Wait(INFINITE_TIME); if (!out.SourceExhausted()) { cout << "o" << flush; out.PumpAll2(false); if (out.SourceExhausted()) cout << "EOF received on source socket.\n"; } if (!in.SourceExhausted()) { cout << "i" << flush; in.PumpAll2(false); if (in.SourceExhausted()) cout << "EOF received on destination socket.\n"; } } #else cout << "Socket support was not enabled at compile time.\n"; exit(-1); #endif } bool Validate(int alg, bool thorough, const char *seedInput) { bool result; std::string seed = seedInput ? std::string(seedInput) : IntToString(time(NULL)); seed.resize(16); cout << "Using seed: " << seed << endl << endl; s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data()); switch (alg) { case 0: result = ValidateAll(thorough); break; case 1: result = TestSettings(); break; case 2: result = TestOS_RNG(); break; case 3: result = ValidateMD5(); break; case 4: result = ValidateSHA(); break; case 5: result = ValidateDES(); break; case 6: result = ValidateIDEA(); break; case 7: result = ValidateARC4(); break; case 8: result = ValidateRC5(); break; case 9: result = ValidateBlowfish(); break; // case 10: result = ValidateDiamond2(); break; case 11: result = ValidateThreeWay(); break; case 12: result = ValidateBBS(); break; case 13: result = ValidateDH(); break; case 14: result = ValidateRSA(); break; case 15: result = ValidateElGamal(); break; case 16: result = ValidateDSA(thorough); break; // case 17: result = ValidateHAVAL(); break; case 18: result = ValidateSAFER(); break; case 19: result = ValidateLUC(); break; case 20: result = ValidateRabin(); break; // case 21: result = ValidateBlumGoldwasser(); break; case 22: result = ValidateECP(); break; case 23: result = ValidateEC2N(); break; // case 24: result = ValidateMD5MAC(); break; case 25: result = ValidateGOST(); break; case 26: result = ValidateTiger(); break; case 27: result = ValidateRIPEMD(); break; case 28: result = ValidateHMAC(); break; // case 29: result = ValidateXMACC(); break; case 30: result = ValidateSHARK(); break; case 32: result = ValidateLUC_DH(); break; case 33: result = ValidateLUC_DL(); break; case 34: result = ValidateSEAL(); break; case 35: result = ValidateCAST(); break; case 36: result = ValidateSquare(); break; case 37: result = ValidateRC2(); break; case 38: result = ValidateRC6(); break; case 39: result = ValidateMARS(); break; case 40: result = ValidateRW(); break; case 41: result = ValidateMD2(); break; case 42: result = ValidateNR(); break; case 43: result = ValidateMQV(); break; case 44: result = ValidateRijndael(); break; case 45: result = ValidateTwofish(); break; case 46: result = ValidateSerpent(); break; case 47: result = ValidateCipherModes(); break; case 48: result = ValidateCRC32(); break; case 49: result = ValidateECDSA(); break; case 50: result = ValidateXTR_DH(); break; case 51: result = ValidateSKIPJACK(); break; case 52: result = ValidateSHA2(); break; case 53: result = ValidatePanama(); break; case 54: result = ValidateAdler32(); break; case 55: result = ValidateMD4(); break; case 56: result = ValidatePBKDF(); break; case 57: result = ValidateESIGN(); break; case 58: result = ValidateDLIES(); break; case 59: result = ValidateBaseCode(); break; case 60: result = ValidateSHACAL2(); break; case 61: result = ValidateCamellia(); break; case 62: result = ValidateWhirlpool(); break; case 63: result = ValidateTTMAC(); break; case 64: result = ValidateSalsa(); break; case 65: result = ValidateSosemanuk(); break; case 66: result = ValidateVMAC(); break; case 67: result = ValidateCCM(); break; case 68: result = ValidateGCM(); break; case 69: result = ValidateCMAC(); break; default: return false; } time_t endTime = time(NULL); cout << "\nTest ended at " << asctime(localtime(&endTime)); cout << "Seed used was: " << seed << endl; return result; }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 96 ], [ 104, 120 ], [ 125, 307 ], [ 309, 339 ], [ 341, 561 ], [ 563, 611 ], [ 613, 762 ], [ 764, 766 ], [ 769, 770 ], [ 772, 840 ], [ 844, 852 ] ], [ [ 97, 103 ], [ 121, 124 ], [ 308, 308 ], [ 340, 340 ], [ 562, 562 ], [ 612, 612 ], [ 763, 763 ], [ 767, 768 ], [ 771, 771 ], [ 841, 843 ] ] ]
df7e0f8ecd2f90dad22e21e9fccd2c164c00b78d
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/ytk_bak/sqlitebrowser/debug/moc_editformwindow.cpp
84167bf41ed697ed1f0a9523e544485257a2b243
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
3,658
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'editformwindow.h' ** ** Created: Sun Jan 3 14:58:44 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../editformwindow.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'editformwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_editFormWindow[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 16, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // slots: signature, parameters, type, tag, flags 16, 15, 15, 15, 0x0a, 26, 15, 15, 15, 0x0a, 37, 15, 15, 15, 0x0a, 48, 15, 15, 15, 0x0a, 61, 15, 15, 15, 0x0a, 73, 15, 15, 15, 0x0a, 84, 15, 15, 15, 0x0a, 95, 15, 15, 15, 0x0a, 106, 15, 15, 15, 0x0a, 116, 15, 15, 15, 0x0a, 127, 15, 15, 15, 0x0a, 139, 15, 15, 15, 0x0a, 150, 15, 15, 15, 0x0a, 162, 15, 15, 15, 0x0a, 177, 15, 15, 15, 0x0a, 189, 15, 15, 15, 0x09, 0 // eod }; static const char qt_meta_stringdata_editFormWindow[] = { "editFormWindow\0\0fileNew()\0fileOpen()\0" "fileSave()\0fileSaveAs()\0filePrint()\0" "fileExit()\0editUndo()\0editRedo()\0" "editCut()\0editCopy()\0editPaste()\0" "editFind()\0helpIndex()\0helpContents()\0" "helpAbout()\0languageChange()\0" }; const QMetaObject editFormWindow::staticMetaObject = { { &Q3MainWindow::staticMetaObject, qt_meta_stringdata_editFormWindow, qt_meta_data_editFormWindow, 0 } }; const QMetaObject *editFormWindow::metaObject() const { return &staticMetaObject; } void *editFormWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_editFormWindow)) return static_cast<void*>(const_cast< editFormWindow*>(this)); if (!strcmp(_clname, "Ui::editFormWindow")) return static_cast< Ui::editFormWindow*>(const_cast< editFormWindow*>(this)); return Q3MainWindow::qt_metacast(_clname); } int editFormWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = Q3MainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: fileNew(); break; case 1: fileOpen(); break; case 2: fileSave(); break; case 3: fileSaveAs(); break; case 4: filePrint(); break; case 5: fileExit(); break; case 6: editUndo(); break; case 7: editRedo(); break; case 8: editCut(); break; case 9: editCopy(); break; case 10: editPaste(); break; case 11: editFind(); break; case 12: helpIndex(); break; case 13: helpContents(); break; case 14: helpAbout(); break; case 15: languageChange(); break; default: ; } _id -= 16; } return _id; } QT_END_MOC_NAMESPACE
[ "yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 110 ] ] ]
6d44e6540ff429510e9eea558d06888222dfc559
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/SyncFilter/SyncFilterApp.h
b20846ae965c7dc68b6ddd17963613aeb6e60df1
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
BIG5
C++
false
false
438
h
// SyncFilter.h : SyncFilter DLL 的主要標頭檔 // #pragma once #ifndef __AFXWIN_H__ #error "對 PCH 包含此檔案前先包含 'stdafx.h'" #endif #include "resource.h" // 主要符號 // CSyncFilterApp // 這個類別的實作請參閱 SyncFilter.cpp // class CSyncFilterApp : public CWinApp { public: CSyncFilterApp(); // 覆寫 public: virtual BOOL InitInstance(); DECLARE_MESSAGE_MAP() };
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 27 ] ] ]