blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
02b61596bc4ce1101fec0e1dc78e344064af782f
216ae2fd7cba505c3690eaae33f62882102bd14a
/utils/nxogre/include/NxOgreArchiveResourceIdentifier.h
bd66e4942cda069bcf0c64775cb1ed3a5cbff86a
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,112
h
/** File: NxOgreArchiveResourceIdentifier.h Created on: 15-Nov-08 Author: Robin Southern "betajaen" SVN: $Id$ © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre 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 3 of the License, or (at your option) any later version. NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NXOGRE_ARCHIVERESOURCEIDENTIFIER_H #define NXOGRE_ARCHIVERESOURCEIDENTIFIER_H #include "NxOgreStable.h" #include "NxOgrePointerClass.h" #include "NxOgreClasses.h" namespace NxOgre_Namespace { /* \brief Identifies a resource name and archive both at once. It uses a string to represent them both, concatenated together with a seperator character ":". As archives are pre-registered, a protocol specifing what the resource isn't needed. ResourceNames generally are filenames (a string with an extension), if the archive is something different then it could be an integer or pointer both as strings. Some protocols that use a single archive; take on the name of their protocol, and some that don't use resource names use a empty string for the resource name. "Memory" from MemoryResourceProtocol is an example of both of these. \example - "physx_media:mesh.nxs" - "cakestuff.zip:island.xhf" - "memory:" - "www.nxogre.org:test.html" - "collision.dat:303" */ class NxOgrePublicClass ArchiveResourceIdentifier { public: // Functions /** \brief Text */ ArchiveResourceIdentifier(void); /** \brief Text */ ArchiveResourceIdentifier(const char* archive_resource_identifier); /** \brief Text */ ArchiveResourceIdentifier(const ArchiveResourceIdentifier&); /** \brief Text */ ~ArchiveResourceIdentifier(void); /** \brief Text */ ArchiveResourceIdentifier& operator=(const ArchiveResourceIdentifier&); /** \brief Text */ ArchiveResourceIdentifier& operator=(const char*); /** \brief Text */ void set(const char*); /** \brief Text */ void set(const ArchiveResourceIdentifier&); /** \brief Text */ const char* getArchive(void) const; /** \brief Text */ void setArchive(const char*, unsigned int where = 0, unsigned int length = 0); /** \brief Text */ unsigned long getArchiveHash(void) const; /** \brief Text */ const char* getResourceName(void) const; /** \brief Text */ void setResourceName(const char*, unsigned int where = 0, unsigned int length = 0); /** \brief Text */ unsigned long getResourceNameHash(void) const; protected: // Classes class ARIHash : public PointerClass<Classes::_URIHash> { friend class ArchiveResourceIdentifier; protected: /** \internal */ ARIHash(void); /** \internal */ ~ARIHash(void); char* mArchive; char* mResourceName; unsigned long mArchiveHash; unsigned long mResourceNameHash; }; protected: // Variables ARIHash* mARI; unsigned short* mReferences; }; // class ClassName } // namespace NxOgre_Namespace #endif
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 155 ] ] ]
e686722d8d5c29148d5486ce375f069dc0450a07
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.7/cbear.berlios.de/vm/commands.hpp
1ccdb983ca3e96c74ad5b4357fc7038a4b2bf524
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
hpp
#ifndef CBEAR_BERLIOS_DE_VM_COMMANDS_HPP_INCLUDED #define CBEAR_BERLIOS_DE_VM_COMMANDS_HPP_INCLUDED #include <cbear.berlios.de/vm/process.hpp> namespace cbear_berlios_de { namespace vm { // command(stop), inline void stop(process &P) { P.result = process::stop; } // command(goto), code inline void goto_(process &P) { P.code = P.code[1].code; } // command(if_goto), condition, code inline void if_goto(process &P) { if(P.code[1].condition) { P.code = P.code[2].code; } else { P.code += 3; } } // command(unless_goto), condition, code inline void unless_goto(process &P) { if(P.code[1].condition) { P.code += 3; } else { P.code = P.code[2].code; } } // command(push), value inline void push(process &P) { if(!P.push()) return; *P.stack = P.code[1]; P.code += 2; } // command(call), code inline void call(process &P) { if(!P.push()) return; P.stack->code = P.code + 2; P.code = P.code[1].code; } // command(return) inline void return_(process &P) { P.code = (P.stack++)->code; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 71 ] ] ]
19703d2f948b2d46cd13f37456602fe4e4baa5fc
cf2bff0beb9b0adf5f5118f10a04bc2f99f8d5f5
/rtloc/src/inc/processor.h
64a8235205b909628defd5e2ea0b36dd0e71b3c9
[]
no_license
bsv/rtloc
80b35386723642d4a1dc7405fa5d2a2c7df1a793
ad1dec4a18192a911aee3a681b3c269aa65095b8
refs/heads/master
2016-09-05T17:03:10.055157
2011-06-26T11:41:51
2011-06-26T11:41:51
32,209,082
0
0
null
null
null
null
UTF-8
C++
false
false
2,874
h
#ifndef PROCESSOR_H_ #define PROCESSOR_H_ #include <QList> #include <QObject> #include <QTimer> #include <QPoint> #include "RFTag.h" #include "../wlanapi/wlanapi.h" typedef QList<RFTag *> TagList; typedef QList<QPoint *> PointList; typedef MapItem Man; /// Масштаб для максимаольной видимости точки в метрах #define SCALE_RSSI 50 /** * Класс для обработки данных */ class Processor : public QObject { Q_OBJECT public: Processor(QObject *parent = 0); virtual ~Processor(); TagList * getActiveTags(); Man * getMan(); /** * Расчет позиции объекта */ void calcPos(TagList * all_tags); /** * Обновление информации о мощности сигнала меток, * отмеченных на карте * * @param all_tags - метки, отмеченные на карте. * * @param calc_tags - метки, по которым будет производится * расчет положения объекта. Это метки, которые находятся * в радиусе действия антенны приемника и отмечены на карте. */ void updateRfTags(TagList * all_tags, TagList * calc_tags); /** * Расчет центра тяжести треугольника (пересечение медиан) */ QPoint calcCentroid(float x1, float y1, float x2, float y2, float x3, float y3); /** * Нахождение таких точек пересечения окружностей, которые * принадлежат одновременно всем окружностям. * * @param calc_tags - список точек доступа, * по которым будет производиться расчет * * @param points - список точек пересечения окружностей */ void getAllIntersec(TagList * calc_tags, PointList * points); /** * Расчет точек пересечения окружностей */ QList<QPoint> calcIntersec(float x1, float y1, float r1, float x2, float y2, float r2); private: /// Список обнаруженных меток /// Обнавляется с помощью getActiveTags() TagList rftags; Man man; wlanapi * wi; void clearTagList(); /** * Удаляет список точек пересечения * * @param list - указатель на список, который * требуется удалить. */ void deleteList(PointList * list); }; #endif /* PROCESSOR_H_ */
[ "bsv.serg@855bd57e-ac1b-27fc-9e9a-e8348851c20a" ]
[ [ [ 1, 90 ] ] ]
0f675af31e3a096f1929ff38e2e7d5b194d551b7
2f72d621e6ec03b9ea243a96e8dd947a952da087
/lol4/gui/InventoryWindow.h
8eea19c4590d65e0a7a476fe2f2f9ca865e19dbf
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
UTF-8
C++
false
false
2,144
h
#ifndef _inventorywindow #define _inventorywindow #include <SlotView.h> #include <EquipmentView.h> #include <GameWindow.h> #include <InventoryDisplayWindow.h> //the actual window class InventoryWindow: public InventoryDisplayWindow { public: InventoryWindow(); ~InventoryWindow(); void show(); inline void show(Inventory *inv) { slotView->setInventory(inv); show(); } void setInventory(Inventory *inv) { mInv = inv; slotView->setInventory(inv); /*if(isShown()) slotView->updateView();*/ eqView->updateInventoryDisplay(); } //to be called from InventorySlotView when something has been taken out or added //for updating the items left display void inventoryChanged(); //to be called from EquipmentView when something was changed void equipmentChanged(); //to be called from InventorySlotView when it wants to adapt the window size //void resizeWindow(Ogre::Real delta_x,Ogre::Real delta_y,bool force = false); //setting absolute sizes for the window //void setWindowSize(Ogre::Real width,Ogre::Real height); inline Inventory *getInventory() { return mInv; } //to enable and disable the part of the window where the inventory is displayed void showInventoryView(); void hideInventoryView(); bool eventMouseUp(const CEGUI::EventArgs& e) { return InventoryDisplayWindow::eventMouseUp(e); } bool eventCloseClicked(const CEGUI::EventArgs& e); //a little workaround... bool eventShown(const CEGUI::EventArgs& e) { return InventoryDisplayWindow::eventShown(e); } private: //virtual void initLayout(); //InventorySlotView *slotView; EquipmentView *eqView; //CEGUI::URect oldWndArea;//for checking if resizing is necessary //CEGUI::Rect oldWndAreaRect;//for checking if resizing is necessary ////CEGUI::URect inventoryWndArea;//backupping the area when the inventory window is open //Ogre::Real inventoryDelta;//backupping the delta height value //bool eventMouseUp(const CEGUI::EventArgs& e); // ////a little workaround... //bool eventShown(const CEGUI::EventArgs& e); }; #endif
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 87 ] ] ]
da5b526bc1090229e7eab161be0810536189c0b8
0045750d824d633aba04e1d92987e91fb87e0ee7
/mythread.cpp
b678f8ba4f0802d1745c32fa69e12283125febde
[]
no_license
mirelon/vlaciky
eaab3cbae7d7438c4fcb87d2b5582b0492676efc
30f5155479a3f3556199aa2d845fcac0c9a2d225
refs/heads/master
2020-05-23T15:05:26.370548
2010-06-16T18:55:52
2010-06-16T18:55:52
33,381,959
0
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
#include "mythread.h" #include <QDebug> bool OpacityEvent::operator <(OpacityEvent &oe){ return priority < oe.priority; } MyThread::MyThread() { stopped = true; } void MyThread::init(){ connect(this,SIGNAL(ssetOpacity(int,int)),graphics,SLOT(setOpacity(int,int))); connect(this,SIGNAL(updateStatus(QString)),graphics,SLOT(updateStatus(QString))); epoch = 0; avgPriority=0; sumPriority=0; } void MyThread::run(){ stopped = false; while(!stopped){ if(!opac.empty()){ OpacityEvent* oe = opac.top(); //qDebug() << "top: " << oe->priority; sumPriority -= oe->priority; if(opac.size()<2)avgPriority=0;else avgPriority = (float)sumPriority/opac.size(); opac.pop(); if(lastEpoch[oe->pos]<oe->epoch){ lastOpacity[oe->pos]=oe->value; lastEpoch[oe->pos]=oe->epoch; emit ssetOpacity(oe->pos,oe->value); } delete oe; } this->msleep(2); } } void MyThread::setOpacity(int i, int opacity){ //ak je halda velka, tak to do nej pridam //len ak to ma vacsiu prioritu ako je polovica priemeru v halde if(abs(opacity-lastOpacity.value(i,0)) <= avgPriority/2) return; OpacityEvent* oe = new OpacityEvent(); oe->priority = abs(opacity-lastOpacity.value(i,0)); oe->epoch = epoch; oe->pos = i; oe->value = opacity; opac.push(oe); sumPriority += oe->priority; avgPriority = (float)sumPriority/opac.size(); } void MyThread::updateEpoch(){ epoch++; emit updateStatus("Epoch: "+QString::number(epoch)+"\nAverage priority: "+QString::number(avgPriority)+"\nHeap size: "+QString::number(opac.size())); }
[ "mirelon@a6d88fff-da04-0f23-7c93-28760c376c6a" ]
[ [ [ 1, 60 ] ] ]
a803504a16c3c1548967c02f3e4db69ab6af0edb
1704fbdd0c606e44b78bc2618db2192618c9cf71
/ui_contextview.h
5d733b4f704954bb000d7be31e4001c927f84b71
[]
no_license
djselbeck/qmpdplasmoid
57c47e6f441fbfc61edee8a735d30221b0b869cc
5fd7fe5e3d6d0138e931c4c61434c22c9b45c1cd
refs/heads/master
2016-09-02T03:36:50.624480
2011-06-17T13:35:31
2011-06-17T13:35:31
32,138,586
0
0
null
null
null
null
UTF-8
C++
false
false
3,539
h
#ifndef UI_CONTEXTVIEW_H #define UI_CONTEXTVIEW_H #include <QWidget> #include <QMenu> #include <QListWidgetItem> #include <QPushButton> #include <QMessageBox> #include <QInputDialog> #include <QLabel> //Local includes #include "networkaccess.h" #include "mpdalbum.h" #include "mpdartist.h" #include "mpdtrack.h" #include "mpdfileentry.h" #include "wlitrack.h" #include "wlifile.h" #include "ui_songinfo.h" #include "QsKineticScroller.h" #include "commondebug.h" //DEFINE FOR KDE PLASMOID #define QMPDPLASMOID_KDE //DEFINE FOR QMOBILEMPD don't set unless compiling qmobilempd //#define QMOBILEMPD enum viewmode {viewmode_currentplaylist,viewmode_artistalbums,viewmode_artists,viewmode_albums,viewmode_albumtracks,viewmode_alltracks,viewmode_savedplaylists,viewmode_playlisttracks,viewmode_files,viewmode_currentsonginfo,viewmode_count}; namespace Ui { class Ui_ContextView; } class Ui_ContextView : public QWidget { Q_OBJECT public: explicit Ui_ContextView(QWidget *parent = 0); Ui_ContextView(QWidget *parent, NetworkAccess *netaccess); ~Ui_ContextView(); void setCurrentPlayingId(qint32 id,quint8 play); bool doubleClickToSelect(); private: Ui::Ui_ContextView *ui; qint32 playingid; quint32 playlistversion; int currentmode; QString currentartist; QString currentalbum; QString currentplaylist; QString currentpath; //Holds current tracks in playlist for performance ui_SongInfo *songinfo; NetworkAccess *netaccess; QsKineticScroller *kineticscroller; QMenu *m_contextMenu; QAction *act_addToPlaylist; void disconnectSelectSignals(); void setupAnimations(); //Bounces out void slideListWidgetLeft(); //Bounces in void slideListWidgetRight(); //Bounce Out animation QPropertyAnimation *listoutanimation; //Bounce In animation QPropertyAnimation *listinanimation; void setupContextMenu(); bool playlistchanged; quint8 playinglaststate; bool doubleclick; QList<MpdTrack*> *lastplaylist; QString backscrolltext; void scrollTo(QString itemtext); public slots: void showArtists(); void showAlbums(); void showTracks(); void showFiles(QString path); void showArtistAlbums(QListWidgetItem *item); void showAlbumTracks(QListWidgetItem *item); void showPlaylistTracks(QListWidgetItem *item); void showLibrarySongInfo(QListWidgetItem *item); void hideLibrarySongInfo(); void playSelectedSong(QListWidgetItem *item); void showCurrentPlaylist(); void setPlaylistVersion(int version); void setDoubleClickNeeded(bool dbl); protected slots: void playButtonDispatcher(); void addButtonDispatcher(); void addAlbumToPlaylist(); void backButtonDispatcher(); void afterAnimationshowArtists(); void afterAnimationshowAlbums(); void afterAnimationshowCurrentPlaylist(); void realignWidgets(); void savePlaylist(); void showPlaylists(); void clearPlaylist(); void quitApplication(); void updateStatus(status_struct tempstruct); void disconnectedFromServer(); void connectedToServer(); void filesClickedDispatcher(QListWidgetItem *item); void selectedDispatcher(QListWidgetItem *item); void scrollTo(); signals: void exitrequested(); void requestMaximised(bool); void showCurrentSongInfo(); }; #endif // UI_CONTEXTVIEW_H
[ "[email protected]@8ca6bbd1-3964-57dc-d96c-3592e88f7f0c" ]
[ [ [ 1, 127 ] ] ]
ddde6fd030cdeb7c6cb02bf465dcba9b790389d5
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/wave/cpplexer/cpp_lex_iterator.hpp
e3d623ee4090d0dffb6010dc2e9f72f69026ad35
[ "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
6,862
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Definition of the lexer iterator http://www.boost.org/ Copyright (c) 2001-2007 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(CPP_LEX_ITERATOR_HPP_AF0C37E3_CBD8_4F33_A225_51CF576FA61F_INCLUDED) #define CPP_LEX_ITERATOR_HPP_AF0C37E3_CBD8_4F33_A225_51CF576FA61F_INCLUDED #include <string> #include <iostream> #include <boost/assert.hpp> #include <boost/shared_ptr.hpp> #include <boost/spirit/iterator/multi_pass.hpp> #include <boost/wave/wave_config.hpp> #include <boost/wave/util/file_position.hpp> #include <boost/wave/util/functor_input.hpp> #include <boost/wave/cpplexer/cpp_lex_interface.hpp> #include <boost/wave/language_support.hpp> // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif #if 0 != __COMO_VERSION__ #define BOOST_WAVE_EOF_PREFIX static #else #define BOOST_WAVE_EOF_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace cpplexer { namespace impl { /////////////////////////////////////////////////////////////////////////////// // // lex_iterator_functor_shim // /////////////////////////////////////////////////////////////////////////////// template <typename TokenT> class lex_iterator_functor_shim { typedef typename TokenT::position_type position_type; public: template <typename IteratorT> lex_iterator_functor_shim(IteratorT const &first, IteratorT const &last, position_type const &pos, boost::wave::language_support language) : functor_ptr(lex_input_interface<TokenT> ::new_lexer(first, last, pos, language)) #if 0 != __DECCXX_VER || BOOST_INTEL_CXX_VERSION >= 900 , eof() #endif // 0 != __DECCXX_VER {} // interface to the boost::spirit::multi_pass_policies::functor_input policy typedef TokenT result_type; BOOST_WAVE_EOF_PREFIX result_type const eof; result_type operator()() { BOOST_ASSERT(0 != functor_ptr.get()); return functor_ptr->get(); } void set_position(position_type const &pos) { BOOST_ASSERT(0 != functor_ptr.get()); functor_ptr->set_position(pos); } #if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0 bool has_include_guards(std::string& guard_name) const { return functor_ptr->has_include_guards(guard_name); } #endif private: boost::shared_ptr<lex_input_interface<TokenT> > functor_ptr; }; /////////////////////////////////////////////////////////////////////////////// // eof token #if 0 != __COMO_VERSION__ template <typename TokenT> typename lex_iterator_functor_shim<TokenT>::result_type const lex_iterator_functor_shim<TokenT>::eof; #endif // 0 != __COMO_VERSION__ /////////////////////////////////////////////////////////////////////////////// } // namespace impl /////////////////////////////////////////////////////////////////////////////// // // lex_iterator // // A generic C++ lexer interface class, which allows to plug in different // lexer implementations. The interface between the lexer type used and // the preprocessor component depends on the token type only (template // parameter TokenT). // Additionally, the following requirements apply: // // - the lexer type should have a function implemented, which returnes // the next lexed token from the input stream: // typename TokenT get(); // - at the end of the input stream this function should return the // eof token equivalent // - the lexer should implement a constructor taking two iterators // pointing to the beginning and the end of the input stream, // a third parameter containing the name of the parsed input file // and a 4th parameter of the type boost::wave::language_support // which specifies, which language subset should be supported (C++, // C99, C++0x etc.). // /////////////////////////////////////////////////////////////////////////////// template <typename TokenT> class lex_iterator : public boost::spirit::multi_pass< impl::lex_iterator_functor_shim<TokenT>, boost::wave::util::functor_input > { typedef impl::lex_iterator_functor_shim<TokenT> input_policy_type; typedef boost::spirit::multi_pass<input_policy_type, boost::wave::util::functor_input> base_type; public: typedef TokenT token_type; lex_iterator() {} template <typename IteratorT> lex_iterator(IteratorT const &first, IteratorT const &last, typename TokenT::position_type const &pos, boost::wave::language_support language) : base_type(input_policy_type(first, last, pos, language)) {} void set_position(typename TokenT::position_type const &pos) { typedef typename TokenT::position_type position_type; // set the new position in the current token token_type& currtoken = base_type::get_input(); position_type currpos = currtoken.get_position(); currpos.set_file(pos.get_file()); currpos.set_line(pos.get_line()); currtoken.set_position(currpos); // set the new position for future tokens as well if (token_type::string_type::npos != currtoken.get_value().find_first_of('\n')) { currpos.set_line(pos.get_line() + 1); } base_type::get_functor().set_position(currpos); } #if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0 // return, whether the current file has include guards // this function returns meaningful results only if the file was scanned // completely bool has_include_guards(std::string& guard_name) const { return base_type::get_functor().has_include_guards(guard_name); } #endif }; /////////////////////////////////////////////////////////////////////////////// } // namespace cpplexer } // namespace wave } // namespace boost // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #undef BOOST_WAVE_EOF_PREFIX #endif // !defined(CPP_LEX_ITERATOR_HPP_AF0C37E3_CBD8_4F33_A225_51CF576FA61F_INCLUDED)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 200 ] ] ]
78469f28141bf499642a20056751b4b6970d6872
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/MobiHealth/ActionItemWidget.cpp
c8055f89ae13b73699a8e92af559065842087260
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,111
cpp
#include "ActionItemWidget.h" #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QFlag> #include <QPixmap> #include "buttonlabel.h" ActionItemWidget::ActionItemWidget(QString actionName, int actionNum, QWidget *parent) : QWidget(parent) { setAutoFillBackground(true); actionNumber = actionNum; //QLabel *actionIcon = new QLabel(this); //actionIcon->setPixmap(QPixmap(":/icons/visitaverde.png")); ButtonLabel *actionButton = new ButtonLabel(QPixmap(":/icons/visitaverde.png"), QPixmap(":/icons/visitaverde.png"), this); connect(actionButton, SIGNAL(released()), this, SLOT(clickWithID())); QLabel *actionLabel = new QLabel(actionName,this); QHBoxLayout *hLayout = new QHBoxLayout(); //hLayout->setSpacing(10); QVBoxLayout *iconVLayout = new QVBoxLayout(); QVBoxLayout *labelVLayout = new QVBoxLayout(); iconVLayout->addSpacing(7); iconVLayout->addWidget(actionButton); iconVLayout->addStretch(); labelVLayout->addSpacing(20); labelVLayout->addWidget(actionLabel); labelVLayout->addStretch(); hLayout->addLayout(iconVLayout); hLayout->addSpacing(10); hLayout->addLayout(labelVLayout); hLayout->addStretch(); setLayout(hLayout); } void ActionItemWidget::setBackgroundImage() { //Using QPalette you can set background image as follows. QPalette p = palette(); //Load image to QPixmap, Give full path of image QPixmap pixmap1(":/icons/actionBg.png"); //For emulator C: is ..\epoc32\winscw\c so image must be at that location //resize image if it is larger than screen size. //QDesktopWidget* desktopWidget = QApplication::desktop(); //QRect rect = desktopWidget->availableGeometry(); QRect rect = this->geometry(); QSize size(rect.width(), rect.height()); //resize as per your reqirement.. //QPixmap pixmap(pixmap1.scaled(size, Qt::IgnoreAspectRatio)); p.setBrush(QPalette::Background, pixmap1); setPalette(p); } void ActionItemWidget::clickWithID() { emit clickedWithID(this->actionNumber); } ActionItemWidget::~ActionItemWidget() { }
[ [ [ 1, 71 ] ] ]
c3e49ee75b316df6b66f3c02f087592e45e1d7ca
a590fbaf14f8e623cdbad4751df1a4e17569051c
/Headers/Base/Frame.h
2afe4424acb704e7ebd0369a1d8424bf46ed6c46
[]
no_license
ninoles/snake-3d
e47326d26f37622b907bf980f8c05c9cc84a1dea
11b9c1b5054c85814872d6ecf628de6a38c743a8
refs/heads/master
2016-09-05T21:53:57.403056
2010-02-05T02:23:32
2010-02-05T02:23:32
41,636,616
0
0
null
null
null
null
UTF-8
C++
false
false
3,559
h
/* * File: Frame.h * Author: Henrique Jonas * * Created on 3 de Outubro de 2009, 22:03 */ #ifndef _FRAME_H #define _FRAME_H #include <irrlicht.h> #include "../Events/WrapperEvent.h" namespace base{ enum idFrames{ FRAME_ID_BASE = 1000, FRAME_ID_ABOUT, FRAME_ID_MAIN_MENU, FRAME_ID_NEW_GAME }; class Frame{ private: irr::IrrlichtDevice *_device; irr::video::IVideoDriver *_driver; irr::gui::IGUIEnvironment *_guiEnv; irr::scene::ISceneManager *_sceneMang; irr::video::SColor _colorFrame; irr::gui::IGUIFont *_font; Events::WrapperEvents *_eventReceiver; irr::SIrrlichtCreationParameters parameters; bool _activateJoyStick; public: //Constructor Frame(int __width, int __heigth, irr::u8 __bitsPerPixel, bool __fullScreen, bool __stencilBuffer, bool __activateJoystick, bool __antiAliasing); //Main Methods void setFont(const irr::c8* __filename); void setModeCursor(bool __visible); void setEventReceiver(Events::WrapperEvents *__eventReceiver); void setTitleFrame(const wchar_t* __titleFrame); void setResizable(bool __resizable); void setColor(int __alpha, int __red, int __green, int __blue); //Getters irr::IrrlichtDevice* getDevice(); irr::video::IVideoDriver* getVideoDriver(); irr::gui::IGUIEnvironment* getGUIEnviroment(); irr::scene::ISceneManager* getSceneManager(); irr::gui::IGUIFont *getFont(); irr::video::SColor getColorFrame(); Events::NodeMoviment* getNodeMoviment(); Events::ButtonEvents* getButtonEvents(); int getFPS(); int getWidth(); int getHeigth(); int getBitsPerPixel(); bool isFullScreen(); bool isStencilBuffer(); bool isJoystick(); bool isAntiAliasing(); //Frame Methods void repaint(int __width, int __heigth, irr::u8 __bitsPerPixel, bool __fullScreen, bool __stencilBuffer, bool __activateJoystick, bool __antiAliasing); void drop(); void show(); bool isVisible(); //GUI Methods irr::video::ITexture* getTexture(const irr::c8* __filename); irr::gui::IGUIButton* addButton(const irr::core::rect<irr::s32>& __rectangle, irr::gui::IGUIElement* __parent, irr::s32 __id, const wchar_t* __text, const wchar_t* __tooltiptext); irr::gui::IGUIStaticText* addText(const wchar_t *__text, const irr::core::rect<irr::s32> __rectangle, bool __border, bool __worldWrapper, irr::gui::IGUIElement *__parent, irr::s32 __id, bool __fillBackground); irr::gui::IGUIFont* addFontFrame(const irr::c8* __filename); irr::gui::IGUIImage* addImage(const irr::c8* __filename, irr::core::position2d<irr::s32> __pos, bool __useAlphaChannel, irr::gui::IGUIElement* __parent, irr::s32 __id, const wchar_t* __text); irr::gui::IGUIFileOpenDialog* addOpenDialog(const wchar_t* __title, bool __modal, irr::gui::IGUIElement* __parent, irr::s32 __id); irr::gui::IGUIContextMenu* addMenu(irr::gui::IGUIElement *__parent, irr::s32 __id); }; }; #endif /* _FRAME_H */
[ "[email protected]", "henrique@henrique-laptop", "henrique@localhost" ]
[ [ [ 1, 1 ], [ 27, 27 ], [ 40, 41 ], [ 46, 47 ], [ 79, 79 ], [ 82, 83 ], [ 106, 106 ] ], [ [ 2, 26 ], [ 28, 36 ], [ 38, 39 ], [ 42, 45 ], [ 48, 67 ], [ 69, 78 ], [ 80, 81 ], [ 84, 95 ], [ 97, 102 ], [ 105, 105 ], [ 107, 109 ] ], [ [ 37, 37 ], [ 68, 68 ], [ 96, 96 ], [ 103, 104 ] ] ]
2fd19e5f6b92c7c9c0553e4cb5e423a5824c03cf
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/SearchProp.cpp
181cb69d36be55a9d360190f334abd9f1d452abf
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
4,383
cpp
// ----------------------------------------------------------------------- // // // MODULE : SearchProp.cpp // // PURPOSE : Searchable Prop - Implementation // // CREATED : 12/21/2001 // // (c) 2001-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "SearchProp.h" #include "ObjectMsgs.h" LINKFROM_MODULE( SearchProp ); BEGIN_CLASS(SearchProp) ADD_DESTRUCTIBLE_MODEL_AGGREGATE(PF_GROUP(1), PF_HIDDEN) // Hide all of our parent properties (these are all set via the // PropTypes.txt bute file) ADD_STRINGPROP_FLAG(Filename, "", PF_HIDDEN | PF_MODEL) // The list of available prop types... ADD_STRINGPROP_FLAG(Type, "", PF_STATICLIST | PF_DIMS | PF_LOCALDIMS) ADD_SEARCHABLE_AGGREGATE(PF_GROUP(3), 0) ADD_STRINGPROP_FLAG(SearchSoundName, "Interface\\Snd\\SearchPropLoop.wav",PF_GROUP(3) | PF_FILENAME) END_CLASS_DEFAULT_FLAGS_PLUGIN(SearchProp, PropType, NULL, NULL, 0, CSearchPropPlugin) // Register with the CommandMgr... CMDMGR_BEGIN_REGISTER_CLASS( SearchProp ) CMDMGR_END_REGISTER_CLASS( SearchProp, PropType ) // ----------------------------------------------------------------------- // // // ROUTINE: CSearchProp::CSearchProp() // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // SearchProp::SearchProp() : PropType() { AddAggregate(&m_search); } // ----------------------------------------------------------------------- // // // ROUTINE: SearchProp::EngineMessageFn // // PURPOSE: Handle engine messages // // ----------------------------------------------------------------------- // uint32 SearchProp::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_PRECREATE: { uint32 dwRet = PropType::EngineMessageFn(messageID, pData, fData); m_search.Enable(true); m_bTouchable = LTFALSE; m_damage.SetMaxHitPoints(1.0f); m_damage.SetHitPoints(1.0f); m_damage.SetCanDamage(LTFALSE); return dwRet; } break; case MID_INITIALUPDATE: { uint32 dwRet = PropType::EngineMessageFn(messageID, pData, fData); g_pCommonLT->SetObjectFlags( m_hObject, OFT_User, m_search.IsEnabled() ? USRFLG_CAN_SEARCH : 0, USRFLG_CAN_SEARCH ); return dwRet; }; break; default : break; } return PropType::EngineMessageFn(messageID, pData, fData); } #ifndef __PSX2 LTRESULT CSearchPropPlugin::PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength) { if (_strcmpi("Type", szPropName) == 0) { if (m_PropTypeMgrPlugin.PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) == LT_OK) { //strip out strings associated with non-searchable props uint32 n = 0; for (uint32 i = 0; i < (*pcStrings); i++) { //assume each proptype is not searchable bool bGood = false; PROPTYPE* pPropType = g_pPropTypeMgr->GetPropType(aszStrings[i]); //if we do have a searchable prop, keep it if (pPropType && pPropType->bSearchable) { bGood = true; } if (bGood) { //if we have a searchable prop, copy it to the next slot if (n < i) { SAFE_STRCPY(aszStrings[n],aszStrings[i]); } n++; } } //adjust our count (*pcStrings) = n; return LT_OK; } } else if ( LT_OK == CPropTypePlugin::PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) ) { return LT_OK; } else if (m_SearchItemPlugin.PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) == LT_OK) { return LT_OK; } return LT_UNSUPPORTED; } LTRESULT CSearchPropPlugin::PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims) { if (LT_OK == CPropTypePlugin::PreHook_Dims(szRezPath, szPropValue, szModelFilenameBuf, nModelFilenameBufLen, vDims)) { return LT_OK; } return LT_UNSUPPORTED; } #endif
[ [ [ 1, 180 ] ] ]
2e4a6e8fff287713bdd19db652fb86c8a7c4aec5
bd37f7b494990542d0d9d772368239a2d44e3b2d
/server/src/Operacion.h
f2f5040cd2e7cf225e4f8c6a2662f919719960dd
[]
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
718
h
/////////////////////////////////////////////////////////// // Operacion.h // Implementation of the Class Operacion // Created on: 21-Nov-2007 23:40:20 /////////////////////////////////////////////////////////// #if !defined(EA_9A3DFB1D_40D2_4167_894A_F5464BCE129F__INCLUDED_) #define EA_9A3DFB1D_40D2_4167_894A_F5464BCE129F__INCLUDED_ /** * Clase Abstracta que permite implementar mediante el polimorfismo ejecutar cada * operacion hija. */ class Operacion { public: Operacion(); virtual ~Operacion(); // Valida y aplica la operacion* retorna TRUE(exito),FALSE(error) virtual bool ejecutar()=0; }; #endif // !defined(EA_9A3DFB1D_40D2_4167_894A_F5464BCE129F__INCLUDED_)
[ "scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8", "nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 17 ], [ 19, 19 ], [ 23, 25 ] ], [ [ 18, 18 ], [ 20, 22 ] ] ]
d1d15fe1e893081c35cbdefc6b0207e3702b5f66
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/CanonNoir/CanonNoirLib/GeneratedCode/AttentePremLancerDe.h
3720a0beeaa6fbd842dcc53cb4b4bc1e9100f1d0
[]
no_license
Issam-Engineer/tp4infoinsa
3538644b40d19375b6bb25f030580004ed4a056d
1576c31862ffbc048890e72a81efa11dba16338b
refs/heads/master
2021-01-10T17:53:31.102683
2011-01-27T07:46:51
2011-01-27T07:46:51
55,446,817
0
0
null
null
null
null
UTF-8
C++
false
false
749
h
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /// <remarks> /// le tableau resDe contient les résultats du lancement des deux dé par joueur(non ordonné) /// j_indJoueur = 0 /// </remarks> class AttentePremLancerDe : public Etat { private : static int[] resDe; Moteur motor; static int nbLance; protected : public : private : protected : public : virtual void execute(); virtual void determinerOrdre(); };
[ "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 38 ] ] ]
2ed9f3e0f3426d92d12936061638d43e1bd42911
857b85d77dfcf9d82c445ad44fedf5c83b902b7c
/source/Headers/ITexture.h
158fb379b2f5531fccda1a99cefa690fc479022f
[]
no_license
TheProjecter/nintendo-ds-homebrew-framework
7ecf88ef5b02a0b1fddc8939011adde9eabf9430
8ab54265516e20b69fbcbb250677557d009091d9
refs/heads/master
2021-01-10T15:13:28.188530
2011-05-19T12:24:39
2011-05-19T12:24:39
43,224,572
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#ifndef I_TEXTURE_H #define I_TEXTURE_H /* Texture base class */ class ITexture { public: virtual ~ITexture() {} virtual const char* GetType() = 0; virtual bool Load(int width, int height, const char* filename) = 0; int Get() { return m_texture; } protected: ITexture() {} int m_texture; }; #endif
[ [ [ 1, 26 ] ] ]
7b2b6105867acff36158de6a313e4a3370eab6e1
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/gfx/particles/ParticleRenderHelper.h
553d06ae88132db7eff9173d53bf67a2e3d0628d
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,296
h
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #ifndef __PARTICLE_RENDER_HELPER_H #define __PARTICLE_RENDER_HELPER_H #include "../../math/Vector3.h" #include "../../math/Matrix4x4.h" #include "../../utils/Singleton.h" namespace dingus { // -------------------------------------------------------------------------- class CParticleRenderHelper : public CSingleton<CParticleRenderHelper> { public: enum { CORNERS_COUNT = 4 }; public: void begin( const SMatrix4x4& camRotMatrix, float particleSize ); SVector3 const& getTransformedCorner( int corner ) const { return mTransformedCorners[corner]; } private: IMPLEMENT_SIMPLE_SINGLETON(CParticleRenderHelper); private: SVector3 mTransformedCorners[CORNERS_COUNT]; }; // -------------------------------------------------------------------------- class CRotParticleRenderHelper : public CSingleton<CRotParticleRenderHelper> { public: enum { CORNERS_COUNT = 4 }; enum { ROTATIONS_COUNT = 64 }; public: void begin( const SMatrix4x4& camRotMatrix ); int getRotationIndex( float rot ) const { return (int)(rot*SPIN2INDEX) & (ROTATIONS_COUNT-1); } SVector3 const& getTransformedCorner( int rot, int corner ) const { return mTransformedCorners[rot][corner]; } private: CRotParticleRenderHelper(); IMPLEMENT_SIMPLE_SINGLETON(CRotParticleRenderHelper); private: SVector3 mCorners[ROTATIONS_COUNT][CORNERS_COUNT]; SVector3 mTransformedCorners[ROTATIONS_COUNT][CORNERS_COUNT]; static const float SPIN2INDEX; }; // -------------------------------------------------------------------------- /* class CLineParticleHelper { public: virtual void begin( const SVector3& cameraPosition ); SVector3 getPerpendicular( const SVector3& position, const SVector3& direction, float width ); SVector3 getStripPerpendicular( const SVector3& position, const SVector3& direction, float width ); const SVector3& getPreviousStripPerpendicular() const { return mPrevP; } private: SVector3 mCameraPosition; SVector3 mPrevP; SVector3 mV; }; */ }; // namespace #endif
[ [ [ 1, 80 ] ] ]
af5f65f1f68303809283c9d5f1e22728a6d89724
847cccd728e768dc801d541a2d1169ef562311cd
/src/EntitySystem/ComponentMgr/ComponentEnums.cpp
9044c7dbb08b0d83ad8af484e30239d91799c4e1
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include "Common.h" #include "ComponentEnums.h" #include <cstring> EntitySystem::eComponentType EntitySystem::DetectComponentType( const string& type ) { const char* typeStr = type.c_str(); for (int32 i=0; i<NUM_COMPONENT_TYPES; ++i) if (strcmp(typeStr, ComponentTypeNames[i]) == 0) return static_cast<eComponentType>(i); ocError << "DetectComponentType: Unknown type '" << type << "'"; return CT_INVALID; } string EntitySystem::GetComponentTypeName(const eComponentType type) { return ComponentTypeNames[type]; }
[ [ [ 1, 2 ], [ 4, 19 ] ], [ [ 3, 3 ] ] ]
206bc31802b5ebc4a80632b3828a65d81a689e1d
be3d7c318d79cd33d306aba58a1159147cac91fd
/modules/wgd_models/include/wgd/model.h
e8aeb1ecea589d769690df5ead19c9d45a4b1cc2
[]
no_license
knicos/Cadence
827149b53bb3e92fe532b0ad4234b7d0de11ca43
7e1e1cf1bae664f77afce63407b61c7b2b0a4fff
refs/heads/master
2020-05-29T13:19:07.595099
2011-10-31T13:05:48
2011-10-31T13:05:48
1,238,039
2
0
null
null
null
null
UTF-8
C++
false
false
2,628
h
#ifndef _WGD_MODEL_ #define _WGD_MODEL_ #include <wgd/dll.h> #include <cadence/agent.h> #include <cadence/dstring.h> #include <wgd/vector.h> #include <wgd/index.h> #include <wgd/bone.h> #include <wgd/mesh.h> #include <wgd/animationset.h> #include <cadence/file.h> #include <wgd/loader.h> #include <vector> namespace wgd{ class Material; class ModelLoader; class MODELSIMPORT Model : public cadence::Agent { friend class ModelLoader; public: Model(const char* filename); Model(cadence::File *file); Model(const cadence::doste::OID&); ~Model(); void load(); /** is the model loaded? */ PROPERTY_RF(bool, loaded, "loaded"); /** Model file name */ PROPERTY_RF(cadence::File, file, "file"); PROPERTY_WF(cadence::File, file, "file"); PROPERTY_RF(float, fps, ix::fps); ///< the default fps for this model PROPERTY_WF(float, fps, ix::fps); ///< set the default fps for this model OBJECT(Agent, Model); BEGIN_EVENTS(Agent); EVENT(evt_file, (*this)("file")); END_EVENTS; /** Get a meterial from teh model */ Material *material(const cadence::doste::OID&) const; //Mesh functions int meshes(); Mesh *mesh(int) const; //Animation Sets AnimationSet *animationSet(const cadence::doste::OID &name); // Bone functions // int bones() const { return m_bones.size(); }; Bone *bone(const cadence::doste::OID &name); Bone *boneID(int bid) const; private: int m_nMeshes; //map of bones in this model cadence::Map m_boneMap; std::vector<wgd::Bone*> m_bones; //AnimationSets cadence::Map m_animationMap; //Bounding sphere float m_radius; wgd::vector3d m_centre; //Loading bool m_loaded; ModelLoader *m_loader; }; class ModelLoader : public Loader { public: BASE_LOADER(ModelLoader); ModelLoader(cadence::File *f) : Loader(f), m_materialCounter(99), m_meshCounter(0) {}; virtual ~ModelLoader() {} // Set the parent model // void parent(Model* m) { m_model = m; }; // Load the model // virtual void load() = 0; protected: Model *m_model; Bone *createBone(const cadence::doste::OID &name); Mesh *createMesh(); Material *createMaterial(cadence::doste::OID &name); AnimationSet *createAnimation(const cadence::doste::OID &name); // texture directory // char* directory(cadence::dstring, char*) const; private: //Used for automatically naming materials and meshes int m_materialCounter; int m_meshCounter; }; }; #endif
[ [ [ 1, 117 ] ] ]
b9723f336462381859db74d4cadf832d21976677
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXTabClientWnd.h
2730282211433b979ef3ac67f83ecacd1f9844fa
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
18,038
h
// ========================================================================== // Class Specification : // COXTabClientWnd & COXTabWorkspace & COXTabWorkspaceDropTarget // ========================================================================== // Header file : OXTabClientWnd.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ////////////////////////////////////////////////////////////////////////// #ifndef _OXTABCLIENTWND_H__ #define _OXTABCLIENTWND_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" #include "OXMainRes.h" #ifndef __AFXTEMPL_H__ #include <afxtempl.h> #define __AFXTEMPL_H__ #endif #ifndef __AFXOLE_H__ #include <afxole.h> #define __AFXOLE_H__ #endif #include "OXSkinnedTabCtrl.h" #include "UTB64Bit.h" /* Description. We introduce a new interface extension for MDI(multiple document interface) based applications - tabbed MDI interface or MTI (just make it sound familiar). We haven't changed anything in the relationships between a frame window (MDIFrame window) and its children (MDIChild windows). We changed the functionality of the window that is usually overlooked while developing MDI applications, being the MDIClient window which resides in the client area of the MDIFrame window and manages MDIChild windows. Instead of just displaying the MDIClient window we also display a standard tab control (that's why "tabbed" MDI) in which we create an item for every MDIChild window. The window icon and text will be associated with the corresponding tab item. Using the tab control you can switch very quickly between MDIChild windows by just clicking on the tab item. If you double click over a tab item then the corresponding MDIChild window will be maximized/restored. And, finally, when any object is dragged over the tab control items (using standard OLE drag and drop) the corresponding MDIChild window will be activated. Of course, as long as we use a standard tab control you can customize its appearance using the standard set of applicable functions. We developed three classes in order to provide the above described functionality: COXTabWorkspaceDropTarget - COleDropTarget derived class used to support the changing of active MDIChild when any object is dragged over tab control items. COXTabWorkspace - CTabCtrl derived class. Covers MDIClient area. For every MDIChild window there will be the tab item that will use the window text and icon as the item text and icon. Whenever you click on an item the corresponding child window will be activated. Whenever you double click on the item the corresponding MDIChild window will be maximized/restored. COXTabClientWnd - CWnd derived class. Subclasses MDIClient window. Manages the placement of the MDIClient and tab control regarding each other. Almost all the logic of the classes is implemented internally and there is not that many public members. Refer to the COXTabWorkspace reference for the list of functions available to customize the tab control appearance. COXTabClientWnd class has a few public functions (refer to COXTabClientWnd reference for details) but primarily you will be interested in the following ones: BOOL Attach(const CMDIFrameWnd* pParentFrame, DWORD dwTabCtrlStyle=DEFAULT_TABCTRLSTYLE); // --- In : pParentFrame - pointer to MDIFrame window of // the application // dwTabCtrlStyle - tab control styles that will be // used while creating the tab control. // Refer to the Windows SDK documentation // for list of all available styles. // The following styles are used by // default: // // TCS_MULTILINE // TCS_BOTTOM // TCS_HOTTRACK // TCS_SCROLLOPPOSITE // TCS_RIGHTJUSTIFY // // --- Out : // --- Returns: TRUE if success or FALSE otherwise. // --- Effect : Substitutes the standard MDI interface with enhanced // tabbed MDI BOOL Detach(); // --- In : // --- Out : // --- Returns: TRUE if success or FALSE otherwise. // --- Effect : Restore the standard MDI interface So in order to implement a tabbed MDI application you could take the following steps: 1) Create the standard MDI application or use the existing one. 2) Define the object of COXTabClientWnd class in your CMDIFrameWnd derived class (usually CMainFrame) // MTI client window COXTabClientWnd m_MTIClientWnd; 3) In the OnCreate() function of your CMDIFrameWnd derived class call the COXTabClientWnd::Attach function m_MTIClientWnd.Attach(this); That's it. Example. We updated the CoolToolBar sample that is found in the .\Samples\gui\CoolToolBar subdirectory of your Ultimate Toolbox directory. There you will see how you can customize the tabbed MDI interface appearance. */ #define ID_TABOFFSET 1 #define IDT_MDI_STATUS_TIMER 333 #define IDC_TABWORKSPACE 1000 const DWORD DEFAULT_TABCTRLSTYLE = TCS_HOTTRACK | TCS_RIGHTJUSTIFY; ///////////////////////////////////////////////////////////////////////////// // COXTabWorkspaceDropTarget drop target for COXTabWorkspace, used to facilitate // auto-selection on drag over. class OX_CLASS_DECL COXTabWorkspaceDropTarget : public COleDropTarget { public: COXTabWorkspaceDropTarget() : m_nOldItem(-1) {}; virtual ~COXTabWorkspaceDropTarget() {}; protected: int m_nOldItem; protected: // Change tab on drag over handler. virtual DROPEFFECT OnDragOver(CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point); virtual void OnDragLeave( CWnd* pWnd ); }; // Structure used internally to represent information about any created // MDIChild window. typedef struct _tagTAB_ITEM_ENTRY { CString sText; CString sWndClass; CWnd* pWnd; BOOL bFound; } TAB_ITEM_ENTRY; // // sText - MDIChild window text. // sWndClass - Name of the window class. // pWnd - Pointer to MDIChild window object. // bFound - Parameter used for integrity testing. Set to TRUE if // corresponding MDIChild window is still active. // ////////////////////////////////////////////////////////////////////////// class COXTabClientWnd; class COXTabSkin; ///////////////////////////////////////////////////////////////////////////// // COXTabWorkspace window class OX_CLASS_DECL COXTabWorkspace : public COXSkinnedTabCtrl { friend class COXTabSkinClassic; DECLARE_DYNAMIC(COXTabWorkspace) // Construction public: // --- In : // --- Out : // --- Returns: // --- Effect : Constructs the object. COXTabWorkspace(); // Attributes public: protected: // Array of tab items (every item corresponds to a MDIChild window) CArray<TAB_ITEM_ENTRY, TAB_ITEM_ENTRY> m_arrTab; // Array of MDIChild windows icons used in the tab control CArray<HICON, HICON> m_arrImage; // Image list associated with the tab control CImageList m_imageList; // Drop target object for OLE dragging support (when any object is // dragged over tab items the corresponding MDIChild windows will be // activated). COXTabWorkspaceDropTarget m_dropTarget; // Pointer to our substitute for the MDIClient window. If it is NULL then // the tab control is not defined and there shouldn't be any action // taken on it. COXTabClientWnd* m_pTabClientWnd; // Offset from the borders of the client area of the MDIFrame window // where the tab control will be displayed. DWORD m_dwOffset; // If TRUE then when any object is dragged over tab items the // corresponding MDIChild windows will be activated BOOL m_bAcceptDraggedObject; // Operations public: // --- In : dwOffset - Offset in points from the MDIFrame window // client area where the tab control will be // displayed. // bRecalcLayout - If TRUE then layout of the parent frame window // will be recalculated right away. // --- Out : // --- Returns: // --- Effect : Sets the tab control offset from MDIFrame borders inline void SetOffset(DWORD dwOffset, BOOL bRecalcLayout=TRUE) { m_dwOffset=dwOffset; if(::IsWindow(GetSafeHwnd())) { SetWindowPos(NULL,0,0,0,0, SWP_NOMOVE|SWP_DRAWFRAME|SWP_NOSIZE|SWP_NOZORDER); if(bRecalcLayout) { CMDIFrameWnd* pFrame=GetParentFrame(); if(pFrame!=NULL) pFrame->RecalcLayout(); } } } // --- In : // --- Out : // --- Returns: Offset in points from the MDIFrame window client area // where the tab control will be displayed // --- Effect : Retrieves the tab control offset from MDIFrame borders inline DWORD GetOffset() const { return m_dwOffset; } // --- In : bAccept - If TRUE then when any object is dragged // over tab items the corresponding MDIChild // windows will be activated. // --- Out : // --- Returns: // --- Effect : Set/Remove drag object over support for the tab control. inline void AcceptDraggedObject(BOOL bAccept=TRUE) { m_bAcceptDraggedObject=bAccept; } // --- In : // --- Out : // --- Returns: TRUE if dragging an object over tab items causes the // corresponding MDIChild windows will be activated. // --- Effect : Retrieves the flag that specifies whether the control // activates the corresponding MDIChild window when an object // is dragged over tab control items. inline BOOL IsAcceptingDraggedObject() const { return m_bAcceptDraggedObject; } // Scan through all MDIChild windows and update corresponding // tab items if any changes occurred (e.g. window text or active MDIChild). // If bAddNewWindows is set to TRUE then for any new found MDIChild // window the new tab item will be created (this option is useful when // it is called for the first time and there are already some MDIChild windows // created). void UpdateContents(BOOL bAddNewWindows=FALSE, BOOL bUpdateWindowsInfo=FALSE); protected: // Returns the pointer for MDIFrame window CMDIFrameWnd* GetParentFrame() const; // Returns text for child window to be displayed in corresponding // tab item virtual CString GetTextForTabItem(const CWnd* pChildWnd) const; // Finds the tab item that corresponds to the specified window inline int FindTabItem(const CWnd* pWnd) const { ASSERT(pWnd!=NULL); ASSERT(::IsWindow(pWnd->GetSafeHwnd())); return FindTabItem(pWnd->GetSafeHwnd()); } // Finds the tab item that corresponds to the specified window int FindTabItem(HWND hWnd) const; // Adds new tab item for the specified window inline BOOL AddTabItem(const CWnd* pChildWnd, BOOL bRedraw=TRUE, BOOL bOnlyVisible=TRUE) { return InsertTabItem(PtrToInt(m_arrTab.GetSize()),pChildWnd,bRedraw,bOnlyVisible); } // Adds new tab item for the specified window BOOL InsertTabItem(int nIndex, const CWnd* pChildWnd, BOOL bRedraw=TRUE, BOOL bOnlyVisible=TRUE); // Removes the tab item for the specified window BOOL RemoveTabItem(const CWnd* pChildWnd, BOOL bRedraw=TRUE); // Retrieves an icon associated with the specified window static HICON GetWindowIcon(HWND hWnd); // Saves specified icon into internal image list int AddTabItemIcon(HICON hIcon); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COXTabWorkspace) //}}AFX_VIRTUAL // Implementation public: // --- In : // --- Out : // --- Returns: // --- Effect : Destroys the object. virtual ~COXTabWorkspace(); // Generated message map functions protected: //{{AFX_MSG(COXTabWorkspace) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnTimer(UINT nIDEvent); afx_msg BOOL OnSelchange(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp); afx_msg void OnNcPaint(); afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() friend class COXTabWorkspaceDropTarget; friend class COXTabClientWnd; public: afx_msg BOOL OnEraseBkgnd(CDC* pDC); }; ///////////////////////////////////////////////////////////////////////////// // COXTabClientWnd window class OX_CLASS_DECL COXTabClientWnd : public CWnd { friend class COXTabSkinClassic; friend class COXTabSkinXP; // Construction public: // --- In : // --- Out : // --- Returns: // --- Effect : Constructs the object. COXTabClientWnd(); // Attributes public: protected: // Tab control COXTabWorkspace m_tab; // Pointer to the corresponding parent MDIFrame window. CMDIFrameWnd* m_pParentFrame; // Flag which specifies that the layout of the tab control and MDIClient // must be recalculated BOOL m_bForceToRecalc; // There is only one tab BOOL m_bOneTabMode; // Operations public: // --- In : pParentFrame - Pointer to MDIFrame window of // the application. // dwTabCtrlStyle - Tab control styles that will be // used while creating the tab control. // Refer to the Windows SDK documentation // for a list of all available styles. // The following styles are used by // default: // // TCS_MULTILINE // TCS_BOTTOM // TCS_HOTTRACK // TCS_SCROLLOPPOSITE // TCS_RIGHTJUSTIFY // // --- Out : // --- Returns: TRUE if success or FALSE otherwise. // --- Effect : Substitutes the standard MDI interface with enhanced // tabbed MDI. BOOL Attach(const CMDIFrameWnd* pParentFrame, DWORD dwTabCtrlStyle=DEFAULT_TABCTRLSTYLE); // --- In : // --- Out : // --- Returns: TRUE if successful, FALSE otherwise. // --- Effect : Restores the standard MDI interface. BOOL Detach(); // --- In : // --- Out : // --- Returns: TRUE if the tabbed MDI interface is active. // --- Effect : Retrieves the flag that specifies whether the // standard MDI interface was substituted with enhanced // tabbed MDI or not. inline BOOL IsAttached() const { return (m_pParentFrame!=NULL ? TRUE : FALSE); } // --- In : // --- Out : // --- Returns: Pointer to the tab control. // --- Effect : Retrieves a pointer to the tab control. inline COXTabWorkspace* GetTabCtrl() { if(!IsAttached()) return NULL; return &m_tab; } // --- In : // --- Out : // --- Returns: Pointer to the parent MDIFrame window or NULL if none // was attached. // --- Effect : Retrieves a pointer to the parent MDIFrame window. inline CMDIFrameWnd* GetParentFrame() { #ifdef _DEBUG if(!IsAttached()) ASSERT(m_pParentFrame==NULL); else { ASSERT(m_pParentFrame!=NULL); ASSERT(m_pParentFrame->IsKindOf(RUNTIME_CLASS(CMDIFrameWnd))); } #endif return m_pParentFrame; } // --- In : lpszProfileName - The name of the .ini file group or // hive in registry where all information // about the TabbedMDI workspace state will be saved. // --- Out : // --- Returns: TRUE if successful, FALSE otherwise. // --- Effect: Saves the TabbedMDI workspace state into the registry or *.ini file. // In order to forward all output in the registry you have to call the // CWinApp::SetRegistryKey() function while initializing your // application (usually in InitInstance() function). BOOL SaveState(LPCTSTR lpszProfileName); // --- In : lpszProfileName - The name of the .ini file group or // hive in registry from which all information // about TabbedMDI workspace state will be // retrieved // --- Out : // --- Returns: TRUE if successful, or FALSE otherwise. // --- Effect: Loads the TabbedMDI workspace state from the registry or *.ini file. // In order to read saved info. from the registry you have to call the // CWinApp::SetRegistryKey() function while initializing your // application (usually in InitInstance() function). BOOL LoadState(LPCTSTR lpszProfileName); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COXTabClientWnd) protected: virtual void CalcWindowRect(LPRECT lpClientRect,UINT nAdjustType=adjustBorder); //}}AFX_VIRTUAL // Implementation public: // --- In : // --- Out : // --- Returns: // --- Effect : Destroys the object virtual ~COXTabClientWnd(); // Generated message map functions protected: //{{AFX_MSG(COXTabClientWnd) afx_msg LRESULT OnMDIActivate(UINT wParam, LONG lParam); afx_msg LRESULT OnMDICreate(UINT wParam, LONG lParam); afx_msg LRESULT OnMDIDestroy(UINT wParam, LONG lParam); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnNcPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() friend class COXTabWorkspace; private: COXTabSkin* m_pTabSkin; COXTabSkin* GetTabSkin(); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // _OXTABCLIENTWND_H__
[ [ [ 1, 556 ] ] ]
4f8648dee0007c78d1433285230a7f8fc7ee196c
df96cbce59e3597f2aecc99ae123311abe7fce94
/watools/plugins/JscriptAudit/V8_domshell/V8_domshell.cpp
f3a87bdf22190b1da52d19fbef830bf1cfd37032
[]
no_license
abhishekbhalani/webapptools
f08b9f62437c81e0682497923d444020d7b319a2
93b6034e0a9e314716e072eb6d3379d92014f25a
refs/heads/master
2021-01-22T17:58:00.860044
2011-12-14T10:54:11
2011-12-14T10:54:11
40,562,019
2
0
null
null
null
null
UTF-8
C++
false
false
13,509
cpp
// V8_domshell.cpp : Defines the entry point for the console application. // #include "stdafx.h" #define V8_DOMSHELL 1 #include <v8.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <weHelper.h> #include <boost/filesystem.hpp> #include <boost/filesystem/operations.hpp> #include <boost/regex.hpp> #include <weDispatch.h> #include <weTask.h> #ifdef WIN32 __declspec(dllexport) double _HUGE; #endif using namespace webEngine; namespace bfs = boost::filesystem; // from common/ #include <jsWrappers/jsBrowser.h> class shellExecutor : public jsBrowser { public: static v8::Persistent<v8::ObjectTemplate> global_object() { return global; } }; void RunShell(v8::Handle<v8::Context> context); bool ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> name, bool print_result, bool report_exceptions); v8::Handle<v8::Value> Print(const v8::Arguments& args); v8::Handle<v8::Value> Read(const v8::Arguments& args); v8::Handle<v8::Value> Load(const v8::Arguments& args); v8::Handle<v8::Value> Quit(const v8::Arguments& args); v8::Handle<v8::Value> Version(const v8::Arguments& args); v8::Handle<v8::Value> Location(const v8::Arguments& args); void SetLocationHref(v8::Local<v8::String> name, v8::Local<v8::Value> val, const v8::AccessorInfo& info); v8::Handle<v8::Value> GetLocationHref(v8::Local<v8::String> name, const v8::AccessorInfo& info); v8::Handle<v8::String> ReadFile(const char* name); void ReportException(v8::TryCatch* handler); std::vector< v8::Persistent<v8::Value> > objects; v8::Handle<v8::Value> GetAnyObject(v8::Local<v8::String> name, const v8::AccessorInfo &info) { //this only shows information on what object is being used... just for fun // { // v8::String::AsciiValue prop(name); // v8::String::AsciiValue self(info.This()->ToString()); // LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("js::BrowserGet: self(")<< *self <<_T("), property(")<< *prop<<_T(")")); // } v8::HandleScope scope; v8::Local<v8::Array> res = v8::Array::New(); for(size_t i = 0; i < objects.size(); i++) { v8::Local<v8::Value> val = v8::Local<v8::Value>::New(objects[i]); res->Set(v8::Int32::New(i), val); } return scope.Close(res); } // Extracts a C string from a V8 Utf8Value. const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } int RunMain(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; // init global objects engine_dispatcher we_dispatcer; bfs::path plg_path = "."; we_dispatcer.refresh_plugin_list(plg_path); i_plugin* plg = we_dispatcer.load_plugin("soci_storage"); if (plg == NULL) { LOG4CXX_FATAL(iLogger::GetLogger(), _T("Can't load plug-in for Storage DB connection: soci_storage")); return 0; } i_storage* storage = (i_storage*)plg->get_interface("i_storage"); if (plg == NULL) { LOG4CXX_FATAL(iLogger::GetLogger(), _T("No iStorage interface in the plugin ") << plg->get_id() << _T("(ID=") << plg->get_id() ); return 0; } string params = "sqlite3://v8_domshell.sqlite"; storage->init_storage(params); we_dispatcer.storage(storage); plugin_list plgs = we_dispatcer.get_plugin_list(); vector<i_plugin*> scan_plugins; for (size_t i = 0; i < plgs.size(); i++) { plg = we_dispatcer.load_plugin(plgs[i].plugin_id); scan_plugins.push_back(plg->get_interface("i_plugin")); //(webEngine::i_plugin*) } task* tsk = new webEngine::task(&we_dispatcer); tsk->store_plugins(scan_plugins); tsk->set_profile_id(string("0")); // todo - take it from params // Create a new execution environment containing the built-in // functions shellExecutor::init_globals(); shellExecutor::global_object()->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read)); // Bind the global 'load' function to the C++ Load callback. shellExecutor::global_object()->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load)); // Bind the 'quit' function shellExecutor::global_object()->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit)); // Bind the 'version' function shellExecutor::global_object()->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version)); // Bind the 'echo' function shellExecutor::global_object()->Set(v8::String::New("echo2"), v8::FunctionTemplate::New(Print)); // init global objects shellExecutor::global_object()->SetAccessor(v8::String::NewSymbol("objects"), GetAnyObject); shellExecutor executor; executor.allow_network(tsk); v8::Persistent<v8::Context> context = executor.get_child_context(); // Enter the newly created execution environment. v8::Context::Scope context_scope(context); executor.window->history->push_back("http://www.ru"); executor.window->history->push_back("http://www.ya.ru"); bool run_shell = (argc == 1); for (int i = 1; i < argc; i++) { const char* str = argv[i]; if (strcmp(str, "--shell") == 0) { run_shell = true; } else if (strcmp(str, "-f") == 0) { // Ignore any -f flags for compatibility with the other stand- // alone JavaScript engines. continue; } else if (strncmp(str, "--", 2) == 0) { printf("Warning: unknown flag %s.\nTry --help for options\n", str); } else if (strcmp(str, "-e") == 0 && i + 1 < argc) { // Execute argument given to -e option directly v8::HandleScope handle_scope; v8::Handle<v8::String> file_name = v8::String::New("unnamed"); v8::Handle<v8::String> source = v8::String::New(argv[i + 1]); if (!ExecuteString(source, file_name, false, true)) return 1; i++; } else { // Use all other arguments as names of files to load and run. v8::HandleScope handle_scope; v8::Handle<v8::String> file_name = v8::String::New(str); v8::Handle<v8::String> source = ReadFile(str); if (source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; } if (!ExecuteString(source, file_name, false, true)) return 1; } } if (run_shell) RunShell(context); executor.allow_network(NULL); delete tsk; executor.close_child_context(context); return 0; } int main(int argc, char* argv[]) { webEngine::LibInit(".\\trace.config"); int result = RunMain(argc, argv); v8::V8::Dispose(); webEngine::LibClose(); return result; } // The callback that is invoked by v8 whenever the JavaScript 'print' // function is called. Prints its arguments on stdout separated by // spaces and ending with a newline. v8::Handle<v8::Value> Print(const v8::Arguments& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; if (first) { first = false; } else { printf(" "); } v8::String::Utf8Value str(args[i]); const char* cstr = ToCString(str); printf("%s", cstr); } printf("\n"); fflush(stdout); return v8::Undefined(); } // The callback that is invoked by v8 whenever the JavaScript 'read' // function is called. This function loads the content of the file named in // the argument into a JavaScript string. v8::Handle<v8::Value> Read(const v8::Arguments& args) { if (args.Length() != 1) { return v8::ThrowException(v8::String::New("Bad parameters")); } v8::String::Utf8Value file(args[0]); if (*file == NULL) { return v8::ThrowException(v8::String::New("Error loading file")); } v8::Handle<v8::String> source = ReadFile(*file); if (source.IsEmpty()) { return v8::ThrowException(v8::String::New("Error loading file")); } return source; } // The callback that is invoked by v8 whenever the JavaScript 'load' // function is called. Loads, compiles and executes its argument // JavaScript file. v8::Handle<v8::Value> Load(const v8::Arguments& args) { for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); if (*file == NULL) { return v8::ThrowException(v8::String::New("Error loading file")); } v8::Handle<v8::String> source = ReadFile(*file); if (source.IsEmpty()) { return v8::ThrowException(v8::String::New("Error loading file")); } if (!ExecuteString(source, v8::String::New(*file), false, true)) { return v8::ThrowException(v8::String::New("Error executing file")); } } return v8::Undefined(); } // The callback that is invoked by v8 whenever the JavaScript 'quit' // function is called. Quits. v8::Handle<v8::Value> Quit(const v8::Arguments& args) { // If not arguments are given args[0] will yield undefined which // converts to the integer value 0. int exit_code = args[0]->Int32Value(); exit(exit_code); return v8::Undefined(); } v8::Handle<v8::Value> Version(const v8::Arguments& args) { return v8::String::New(v8::V8::GetVersion()); } // Reads a file into a v8 string. v8::Handle<v8::String> ReadFile(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); v8::Handle<v8::String> result = v8::String::New(chars, size); delete[] chars; return result; } // The read-eval-execute loop of the shell. void RunShell(v8::Handle<v8::Context> context) { printf("V8 version %s\n", v8::V8::GetVersion()); static const int kBufferSize = 256; while (true) { char buffer[kBufferSize]; printf("> "); char* str = fgets(buffer, kBufferSize, stdin); if (str == NULL) break; v8::HandleScope handle_scope; ExecuteString(v8::String::New(str), v8::String::New("(shell)"), true, true); } printf("\n"); } // Executes a string within the current v8 context. bool ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> name, bool print_result, bool report_exceptions) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) ReportException(&try_catch); return false; } else { v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { // Print errors that happened during execution. if (report_exceptions) ReportException(&try_catch); return false; } else { if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); const char* cstr = ToCString(str); printf("%s\n", cstr); } return true; } } } void ReportException(v8::TryCatch* try_catch) { v8::HandleScope handle_scope; v8::String::Utf8Value exception(try_catch->Exception()); const char* exception_string = ToCString(exception); v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { // V8 didn't provide any extra information about this error; just // print the exception. printf("%s\n", exception_string); } else { // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); printf("%s:%i: %s\n", filename_string, linenum, exception_string); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); printf("%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { printf(" "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { printf("^"); } printf("\n"); } }
[ "stinger911@79c36d58-6562-11de-a3c1-4985b5740c72" ]
[ [ [ 1, 375 ] ] ]
1e02ede17a10adcc58ee157a4afec68197be0ad6
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.3/cbear.berlios.de/locale/cast.hpp
33ac301b4ed12e1e2951679224f061ee15b64281
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
2,631
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) 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 CBEAR_BERLIOS_DE_LOCALE_CAST_HPP_INCLUDED #define CBEAR_BERLIOS_DE_LOCALE_CAST_HPP_INCLUDED #include <locale> #include <cbear.berlios.de/range/value_type.hpp> #include <cbear.berlios.de/range/transform.hpp> namespace cbear_berlios_de { namespace locale { namespace detail { /// Casting. template<class To, class From> struct cast; /// Returns std::ctype<Char>. template<class Char> const std::ctype<Char> &get_ctype() { return std::use_facet<std::ctype<Char> >(std::locale()); } /// Converts from wchar_t to char. template<> struct cast<char, wchar_t> { /// Main function. static char run(wchar_t C) { return get_ctype<wchar_t>().narrow(C, '@'); } }; /// Converts from char to wchar_t. template<> struct cast<wchar_t, char> { /// Main function. static wchar_t run(char C) { return get_ctype<char>().widen(C); } }; /// Converts to std::basic_string<Char>. template<class Char, class From> struct cast<std::basic_string<Char>, From> { typedef std::basic_string<Char> result_type; ///< A result type. /// Main function. static result_type run(const From &Source) { typedef typename range::value_type<From>::type source_char_type; result_type Result; range::transform( Source, std::back_inserter(Result), cast<Char, source_char_type>::run); return Result; } }; } /// Casting. template<class To, class From> To cast(const From &X) { return detail::cast<To, From>::run(X); } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 93 ] ] ]
4f2e3c59509b4d9b20a26c7c6e82c40f9378f9bd
39f755afd5f4f3abe91a24342746774781704fa7
/cob_generic_can/common/src/CanESD.cpp
e106a6a182e11b8e83c13dd81476d6a8ff14f25a
[]
no_license
attilaachenbach/cob_driver
b1e280259521a47a07838a13fd35f218ae0c0f24
46acb2fe8114f04ce9909ef9488b6302d2530f9e
refs/heads/master
2021-01-15T20:48:35.405544
2011-04-29T17:28:25
2011-04-29T17:28:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,351
cpp
/**************************************************************** * * Copyright (c) 2010 * * Fraunhofer Institute for Manufacturing Engineering * and Automation (IPA) * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Project name: care-o-bot * ROS stack name: cob_drivers * ROS package name: cob_generic_can * Description: This class implements the interface to an ESD can node * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Author: Christian Connette, email:[email protected] * Supervised by: Christian Connette, email:[email protected] * * Date of creation: April 2010 * ToDo: - Remove Mutex.h search for a Boost lib * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Fraunhofer Institute for Manufacturing * Engineering and Automation (IPA) nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License LGPL 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 Lesser General Public License LGPL for more details. * * You should have received a copy of the GNU Lesser General Public * License LGPL along with this program. * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************/ // general includes // Headers provided by other cob-packages #include <cob_generic_can/CanESD.h> // Headers provided by other cob-packages which should be avoided/removed //----------------------------------------------- CanESD::CanESD(const char* cIniFile, bool bObjectMode) { m_bObjectMode = bObjectMode; m_bIsTXError = false; m_IniFile.SetFileName(cIniFile, "CanESD.cpp"); initIntern(); } //----------------------------------------------- /** * Destructor. * Release the allocated resources. */ CanESD::~CanESD() { std::cout << "Closing CAN handle" << std::endl; canClose(m_Handle); } //----------------------------------------------- void CanESD::initIntern() { int ret=0; ret = 0; int iCanNet = 1; m_IniFile.GetKeyInt( "CanCtrl", "NetESD", &iCanNet, true); int iBaudrateVal = 2; m_IniFile.GetKeyInt( "CanCtrl", "BaudrateVal", &iBaudrateVal, true); std::cout << "Initializing CAN network with id =" << iCanNet << ", baudrate=" << iBaudrateVal << std::endl; int iRet; if( m_bObjectMode ) iRet = canOpen(iCanNet, NTCAN_MODE_OBJECT, 10000, 10000, 1000, 0, &m_Handle); else iRet = canOpen(iCanNet, 0, 10000, 10000, 1000, 0, &m_Handle); Sleep(300); if(iRet == NTCAN_SUCCESS) std::cout << "CanESD::CanESD(), init ok" << std::endl; else std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl; iRet = canSetBaudrate(m_Handle, iBaudrateVal); if(iRet == NTCAN_SUCCESS) std::cout << "CanESD::CanESD(), canSetBaudrate ok" << std::endl; else std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl; Sleep(300); long lArg; iRet = canIoctl(m_Handle, NTCAN_IOCTL_FLUSH_RX_FIFO, NULL); // MMB/24.02.2006: Add all 11-bit identifiers as there is no loss in performance. for( int i=0; i<=0x7FF; ++i ) { iRet = canIdAdd( m_Handle, i ); if(iRet != NTCAN_SUCCESS) std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl; } Sleep(300); m_LastID = -1; } //----------------------------------------------- /** * Transmit a message via the CAN bus. * Additionally, an error flag is set internally if the transmission does not succeed. * @param CMsg Structure containing the CAN message. * @return true on success, false on failure. */ bool CanESD::transmitMsg(CanMsg CMsg, bool bBlocking) { CMSG NTCANMsg; NTCANMsg.id = CMsg.m_iID; NTCANMsg.len = CMsg.m_iLen; for(int i=0; i<8; i++) NTCANMsg.data[i] = CMsg.getAt(i); int ret; int32_t len; bool bRet = true; len = 1; if (bBlocking) ret = canWrite(m_Handle, &NTCANMsg, &len, NULL); else ret = canSend(m_Handle, &NTCANMsg, &len); if( ret != NTCAN_SUCCESS) { std::cout << "error in CANESD::transmitMsg: " << GetErrorStr(ret) << std::endl; bRet = false; } m_LastID = (int)NTCANMsg.data[0]; m_bIsTXError = !bRet; return bRet; } //----------------------------------------------- bool CanESD::receiveMsgRetry(CanMsg* pCMsg, int iNrOfRetry) { int id = pCMsg->m_iID; CMSG NTCANMsg; NTCANMsg.len = 8; int32_t len; int i, ret; bool bRet = true; i=0; len = 1; do { len = 1; ret = canTake(m_Handle, &NTCANMsg, &len); i++; Sleep(10); } while((len == 0) && (i < iNrOfRetry)); if(i == iNrOfRetry) { if( ret != NTCAN_SUCCESS ) std::cout << "error in CANESD::receiveMsgRetry: " << GetErrorStr(ret) << std::endl; bRet = false; } else { pCMsg->m_iID = NTCANMsg.id; pCMsg->m_iLen = NTCANMsg.len; pCMsg->set(NTCANMsg.data[0], NTCANMsg.data[1], NTCANMsg.data[2], NTCANMsg.data[3], NTCANMsg.data[4], NTCANMsg.data[5], NTCANMsg.data[6], NTCANMsg.data[7]); } return bRet; } //----------------------------------------------- bool CanESD::receiveMsg(CanMsg* pCMsg) { CMSG NTCANMsg; NTCANMsg.len = 8; int ret; int32_t len; bool bRet = true; len = 1; // Debug valgrind NTCANMsg.data[0] = 0; NTCANMsg.data[1] = 0; NTCANMsg.data[2] = 0; NTCANMsg.data[3] = 0; NTCANMsg.data[4] = 0; NTCANMsg.data[5] = 0; NTCANMsg.data[6] = 0; NTCANMsg.data[7] = 0; NTCANMsg.msg_lost = 0; NTCANMsg.id = 0; NTCANMsg.len = 0; pCMsg->set(0,0,0,0,0,0,0,0); if( !isObjectMode() ) { pCMsg->m_iID = 0; } else { NTCANMsg.id = pCMsg->m_iID; } ret = canTake(m_Handle, &NTCANMsg, &len); if( !isObjectMode() ) { if( (len == 1) && (ret == NTCAN_SUCCESS) ) { // message received pCMsg->m_iID = NTCANMsg.id; pCMsg->m_iLen = NTCANMsg.len; pCMsg->set(NTCANMsg.data[0], NTCANMsg.data[1], NTCANMsg.data[2], NTCANMsg.data[3], NTCANMsg.data[4], NTCANMsg.data[5], NTCANMsg.data[6], NTCANMsg.data[7]); bRet = true; } else { // no message if( ret != NTCAN_SUCCESS) { // error std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(ret) << std::endl; } pCMsg->m_iID = NTCANMsg.id; pCMsg->set(0,0,0,0,0,0,0,0); bRet = false; } } else { if( len == 16 ) { // No message was received yet. pCMsg->m_iID = NTCANMsg.id; pCMsg->set(0,0,0,0,0,0,0,0); bRet = false; } else { pCMsg->m_iID = NTCANMsg.id; pCMsg->m_iLen = NTCANMsg.len; pCMsg->set(NTCANMsg.data[0], NTCANMsg.data[1], NTCANMsg.data[2], NTCANMsg.data[3], NTCANMsg.data[4], NTCANMsg.data[5], NTCANMsg.data[6], NTCANMsg.data[7]); bRet = true; } } if( NTCANMsg.msg_lost != 0 ) std::cout << (int)(NTCANMsg.msg_lost) << " messages lost!" << std::endl; return bRet; } /** * Add a group of CAN identifier to the handle, so it can be received. * The identifiers are generated by inverting the id and adding each value between 0 and 7 * This is used for generating the answer commands by the RCS5000. * @param handle The handle to add the identifiers to. * @param id The command id sent to the RCS5000. * @return NTCAN_SUCESS if ok, or an error code. */ int CanESD::canIdAddGroup(NTCAN_HANDLE handle, int id) { int result = NTCAN_SUCCESS; int i = 0; int iRes = 0; int cmd_id = invert(id); for( i=0; i<8; ++i) { iRes = canIdAdd(m_Handle, cmd_id+i); if( iRes != NTCAN_SUCCESS ) { std::cout << "Adding CAN ID " << cmd_id+i << " failed with errorcode: " << iRes << " " << GetErrorStr(iRes) << std::endl; result = iRes; } } return result; } //----------------------------------------------- std::string CanESD::GetErrorStr(int ntstatus) const { switch (ntstatus) { case NTCAN_SUCCESS: return "NTCAN_SUCCESS"; case NTCAN_RX_TIMEOUT: return "NTCAN_RX_TIMEOUT"; case NTCAN_TX_TIMEOUT: return "NTCAN_TX_TIMEOUT"; case NTCAN_TX_ERROR: return "NTCAN_TX_ERROR"; case NTCAN_CONTR_OFF_BUS: return "NTCAN_CONTR_OFF_BUS"; case NTCAN_CONTR_BUSY: return "NTCAN_CONTR_BUSY"; case NTCAN_CONTR_WARN: return "NTCAN_CONTR_WARN"; case NTCAN_NO_ID_ENABLED: return "NTCAN_NO_ID_ENABLED"; case NTCAN_ID_ALREADY_ENABLED: return "NTCAN_ID_ALREADY_ENABLED"; case NTCAN_ID_NOT_ENABLED: return "NTCAN_ID_NOT_ENABLED"; case NTCAN_INVALID_FIRMWARE: return "NTCAN_INVALID_FIRMWARE"; case NTCAN_MESSAGE_LOST: return "NTCAN_MESSAGE_LOST"; case NTCAN_INVALID_HARDWARE: return "NTCAN_INVALID_HARDWARE"; case NTCAN_PENDING_WRITE: return "NTCAN_PENDING_WRITE"; case NTCAN_PENDING_READ: return "NTCAN_PENDING_READ"; case NTCAN_INVALID_DRIVER: return "NTCAN_INVALID_DRIVER"; case NTCAN_INVALID_PARAMETER: return "NTCAN_INVALID_PARAMETER"; case NTCAN_INVALID_HANDLE: return "NTCAN_INVALID_HANDLE"; case NTCAN_NET_NOT_FOUND: return "NTCAN_NET_NOT_FOUND"; case NTCAN_INSUFFICIENT_RESOURCES: return "NTCAN_INSUFFICIENT_RESOURCES"; case NTCAN_OPERATION_ABORTED: return "NTCAN_OPERATION_ABORTED"; } char msg[100]; sprintf(msg, "unknown error code %d", ntstatus); return msg; } /** * Check if errors occured on the CAN bus. * @return - 0 if everthing is fine. * - -1 if an error occured. * - -3 if messages were lost. * - -5 if a FIFO overflow occured. * - -6 if the CAN controller is BUS OFF. * - -7 if the CAN controller is WARN, i.e. error passive. */ int CanESD::readEvent() { EVMSG evmsg; int iRet = 0; int ret; ret = canReadEvent(m_Handle, &evmsg, NULL); if(ret == NTCAN_SUCCESS) { if( (int)evmsg.evid == NTCAN_EV_CAN_ERROR ) { switch( evmsg.evdata.s[0] ) { case 0x00: iRet = 0; break; case 0xC0: iRet = -6; std::cout << "BUS OFF" << std::endl; break; case 0x40: iRet = -7; std::cout << "ERROR PASSIVE" << std::endl; break; } if( evmsg.evdata.s[3] != 0 ) { iRet = -3; std::cout << "Lost " << (int)evmsg.evdata.s[3] << " messages" << std::endl; } else if( evmsg.evdata.s[5] != 0 ) { iRet = -5; std::cout << "Lost " << (int)evmsg.evdata.s[5] << " messages from fifo" << std::endl; } } } return iRet; }
[ "cpc@tethys.(none)", "cpc@COB3-Navigation.(none)" ]
[ [ [ 1, 87 ], [ 89, 90 ], [ 92, 302 ], [ 304, 402 ] ], [ [ 88, 88 ], [ 91, 91 ], [ 303, 303 ] ] ]
28450075c6f97b53bd6333de29dbfa1321896b29
1dba10648f60dea02c9be242c668f3488ae8dec4
/kalibrator/src/main.cpp
91b963026075beed3bbc99903c45b989ee37e77e
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
#include <qapplication.h> #include "mainform.h" #pragma comment(lib,"qtmain.lib") #pragma comment(lib,"qt-mt3.lib") int main( int argc, char ** argv ) { QApplication a( argc, argv ); MainForm w; w.show(); a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) ); return a.exec(); }
[ "jasinski.andrzej@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 14 ] ] ]
f585bb588d88a12c223948fbbe35c9f3c28c0ccc
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/shortlinksrv/Bluetooth/T_BTSockAPI/src/T_CBluetoothSocketData.cpp
5a22562695b8a7ed3b9101235605aadbe012dcd9
[]
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
74,343
cpp
/* * Copyright (c) 2006-2007 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: * */ #include "T_CBluetoothSocketData.h" #include "T_BTUtil.h" #include "T_TBTSockAddrChild.h" #include "T_BTDevAddrData.h" #include "T_BTSockAddrData.h" // EPOC includes #include <e32math.h> /*@{*/ /// Constant Literals used. /// Parameters _LIT(KExpectedReply, "expectedreply"); _LIT(KCBluetoothSocket, "cbluetoothsocket"); _LIT(KConnectData, "connectdata"); _LIT(KData, "data"); _LIT(KDesOption, "desoption"); _LIT(KDisconnectData, "disconnectData"); _LIT(KEquals, "equals"); _LIT(KExpectNull, "expectnull"); _LIT(KFlags, "flags"); _LIT(KGetDes, "getdes"); _LIT(KIntOption, "intoption"); _LIT(KNamedIntOption, "namedintoption"); _LIT(KNamedProtocol, "named_protocol"); _LIT(KOptionLevel, "optionlevel"); _LIT(KOptionName, "optionname"); _LIT(KPort, "port"); _LIT(KProtocol, "protocol"); _LIT(KQueueSize, "queuesize"); _LIT(KRSocket, "rsocket"); _LIT(KServiceBits, "servicebits"); _LIT(KSockType, "socktype"); _LIT(KTBTSockAddr, "tbtsockaddr"); _LIT(KTSockAddr, "tsockaddr"); _LIT(KUid, "uid"); _LIT(KUseAccept2, "useaccept2"); _LIT(KUseAlternateNotifier, "usealternatenotifier"); _LIT(KUseDeprecated, "usedeprecated"); _LIT(KUseRecv2, "userecv2"); _LIT(KUseSend2, "usesend2"); _LIT(KHexBTAddrL, "hex_btaddr_l"); _LIT(KHexBTAddrR, "hex_btaddr_r"); _LIT(KTBTDevAddr, "tbtdevaddr"); _LIT(KCallTwice, "calltwice"); _LIT(KMTUSize, "mtusize"); _LIT(KState, "state"); _LIT(KConstructorType, "constructortype"); _LIT(KSniffMode, "sniffmode"); _LIT(KSniffDelay, "sniffdelay"); /// CBluetoothSocket _LIT(KCmdAccept, "Accept"); _LIT(KCmdActivateBasebandEventNotifier, "ActivateBasebandEventNotifier"); _LIT(KCmdActivateParkRequester, "ActivateParkRequester"); _LIT(KCmdActivateSniffRequester, "ActivateSniffRequester"); _LIT(KCmdAllowLowPowerModes, "AllowLowPowerModes"); _LIT(KCmdAllowRoleSwitch, "AllowRoleSwitch"); _LIT(KCmdBind, "Bind"); _LIT(KCmdCancelAccept, "CancelAccept"); _LIT(KCmdCancelAll, "CancelAll"); _LIT(KCmdCancelBasebandEventNotifier, "CancelBasebandEventNotifier"); _LIT(KCmdCancelConnect, "CancelConnect"); _LIT(KCmdCancelIoctl, "CancelIoctl"); _LIT(KCmdCancelLowPowerModeRequester, "CancelLowPowerModeRequester"); _LIT(KCmdCancelRead, "CancelRead"); _LIT(KCmdCancelRecv, "CancelRecv"); _LIT(KCmdCancelSend, "CancelSend"); _LIT(KCmdCancelWrite, "CancelWrite"); _LIT(KCmdConnect, "Connect"); _LIT(KCmdDestructor, "~"); _LIT(KCmdGetDisconnectData, "GetDisconnectData"); _LIT(KCmdGetOpt, "GetOpt"); _LIT(KCmdInfo, "Info"); _LIT(KCmdIoctl, "Ioctl"); _LIT(KCmdListen, "Listen"); _LIT(KCmdLocalName, "LocalName"); _LIT(KCmdLocalPort, "LocalPort"); _LIT(KCmdName, "Name"); _LIT(KCmdNewL, "NewL"); _LIT(KCmdNewLC, "NewLC"); _LIT(KCmdPhysicalLinkState, "PhysicalLinkState"); _LIT(KCmdPreventLowPowerModes, "PreventLowPowerModes"); _LIT(KCmdPreventRoleSwitch, "PreventRoleSwitch"); _LIT(KCmdRConnectionClose, "RConnectionClose"); _LIT(KCmdRConnectionStart, "RConnectionStart"); _LIT(KCmdRead, "Read"); _LIT(KCmdRecv, "Recv"); _LIT(KCmdRecvFrom, "RecvFrom"); _LIT(KCmdRecvOneOrMore, "RecvOneOrMore"); _LIT(KCmdRemoteName, "RemoteName"); _LIT(KCmdRequestChangeSupportedPacketTypes, "RequestChangeSupportedPacketTypes"); _LIT(KCmdRequestMasterRole, "RequestMasterRole"); _LIT(KCmdRequestSlaveRole, "RequestSlaveRole"); _LIT(KCmdRSocketServerClose, "RSocketServerClose"); _LIT(KCmdRSocketServerConnect, "RSocketServerConnect"); _LIT(KCmdSend, "Send"); _LIT(KCmdSendTo, "SendTo"); _LIT(KCmdSetAutomaticSniffMode, "SetAutomaticSniffMode"); _LIT(KCmdSetLocalPort, "SetLocalPort"); _LIT(KCmdSetOpt, "SetOpt"); _LIT(KCmdSetOption, "SetOption"); _LIT(KCmdSetRsocketServerFromCBTSocket, "SetRsocketServerFromCBTSocket"); _LIT(KCmdSetTransferAble, "SetTransferAble"); _LIT(KCmdShutdown, "Shutdown"); _LIT(KCmdSetNotifier, "SetNotifier"); _LIT(KCmdTestMBSN_ExtensionInterfaceL, "TestMBSN_ExtensionInterfaceL"); _LIT(KCmdTransfer, "Transfer"); _LIT(KCmdWrite, "Write"); /// Other _LIT_SECURITY_POLICY_C2(KProcPolicy, ECapabilityNetworkServices, ECapabilityNetworkControl); /*@}*/ CT_CBluetoothSocketData* CT_CBluetoothSocketData::NewL() { CT_CBluetoothSocketData* ret=new (ELeave) CT_CBluetoothSocketData(); CleanupStack::PushL(ret); ret->ConstructL(); CleanupStack::Pop(ret); return ret; } /** * First phase construction */ CT_CBluetoothSocketData::CT_CBluetoothSocketData() : iData(NULL) , iHasConnectDataToExpect(EFalse) , iHasAcceptDataToExpect(EFalse) , iHasReceiveDataToExpect(EFalse) , iConnectIndex(0) , iAcceptIndex(0) , iShutdownIndex(0) , iIoctlIndex(0) , iNotifierIndex(0) , iReceiveIndex(0) , iSendIndex(0) { } /** * Second phase construction */ void CT_CBluetoothSocketData::ConstructL() { iData=new (ELeave) CT_BluetoothSocketNotifier(); iData->SetServer(this); } CT_CBluetoothSocketData::~CT_CBluetoothSocketData() { } // Service methods TAny* CT_CBluetoothSocketData::GetObject() { return iData; } void CT_CBluetoothSocketData::SetObjectL(TAny* aObject) { //called when loading up persistent data delete iData; iData = static_cast<CT_BluetoothSocketNotifier*>(aObject); iData->SetServer(this); } void CT_CBluetoothSocketData::DisownObjectL() { if ( iData ) { iData->SetServer(NULL); iData=NULL; } } inline TCleanupOperation CT_CBluetoothSocketData::CleanupOperation() { return CleanupOperation; } void CT_CBluetoothSocketData::CleanupOperation(TAny* aAny) { //may be unnecessary CT_BluetoothSocketNotifier* arg=static_cast<CT_BluetoothSocketNotifier*>(aAny); delete arg; } TBool CT_CBluetoothSocketData::DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex) { TBool retVal=ETrue; //------------------------------------------------------------------------- // CBluetoothSocket //------------------------------------------------------------------------- if (aCommand==KCmdRSocketServerConnect) { DoCmdCloseSocketServer(); User::LeaveIfError(iData->iSocketServer.Connect()); iData->iSocketServerConnected=ETrue; } else if (aCommand==KCmdRSocketServerClose) { DoCmdCloseSocketServer(); } else if (aCommand==KCmdRConnectionStart) { TInt err = iData->iConnection.Open(iData->iSocketServer, KBTAddrFamily); if( err!=KErrNone ) { INFO_PRINTF2(_L("RConnection::Open() err=%d" ),err); SetError(err); } err = iData->iConnection.Start(); if( err!=KErrNone ) { INFO_PRINTF2(_L("RConnection::Start() err=%d" ),err); SetError(219); } } else if (aCommand==KCmdRConnectionClose) { iData->iConnection.Close(); } else if (aCommand==KCmdDestructor) { delete iData->iBluetoothSocket; iData->iBluetoothSocket=NULL; } else if ( aCommand==KCmdNewL ) { DoCmdNewL(aSection,EFalse); } else if ( aCommand==KCmdNewLC ) { DoCmdNewL(aSection,ETrue); } else if ( aCommand==KCmdBind) { DoCmdBind(aSection); } else if ( aCommand==KCmdListen) { DoCmdListen(aSection); } else if ( aCommand==KCmdLocalName) { DoCmdLocalName(aSection); } else if ( aCommand==KCmdLocalPort) { DoCmdLocalPort(aSection); } else if ( aCommand==KCmdSetLocalPort) { DoCmdSetLocalPort(aSection); } else if ( aCommand==KCmdSetOpt) { DoCmdSetOpt(aSection); } else if ( aCommand==KCmdSetOption) { DoCmdSetOption(aSection); } else if ( aCommand==KCmdGetOpt) { DoCmdGetOpt(aSection); } else if ( aCommand==KCmdName) { DoCmdName(); } else if ( aCommand==KCmdSetTransferAble) { DoCmdSetTransferAble(); } else if ( aCommand==KCmdTransfer) { DoCmdTransfer(aSection); } else if ( aCommand==KCmdInfo) { DoCmdInfo(aSection); } else if ( aCommand==KCmdAccept) { DoCmdAccept(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdCancelAccept) { DoCmdCancelAccept(); } else if ( aCommand==KCmdConnect) { DoCmdConnect(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdSend) { DoCmdSend(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdRecv) { DoCmdRecv(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdRecvOneOrMore) { DoCmdRecvOneOrMore(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdShutdown) { DoCmdShutdown(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdSetNotifier) { DoCmdSetNotifierL(aSection); } else if ( aCommand==KCmdCancelConnect) { DoCmdCancelConnect(); } else if ( aCommand==KCmdSetRsocketServerFromCBTSocket) { DoCmdSetRsocketServerFromCBTSocket(aSection); } else if ( aCommand==KCmdIoctl) { DoCmdIoctl(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdCancelIoctl) { DoCmdCancelIoctl(); } else if ( aCommand==KCmdAllowLowPowerModes) { DoCmdAllowLowPowerModes(aSection); } else if ( aCommand==KCmdCancelLowPowerModeRequester) { DoCmdCancelLowPowerModeRequester(aSection); } else if ( aCommand==KCmdPreventLowPowerModes) { DoCmdPreventLowPowerModes(aSection); } else if ( aCommand==KCmdActivateBasebandEventNotifier) { DoCmdActivateBasebandEventNotifier(aSection, aAsyncErrorIndex); } else if ( aCommand==KCmdCancelBasebandEventNotifier) { DoCmdCancelBasebandEventNotifier(); } else if ( aCommand==KCmdPhysicalLinkState) { DoCmdPhysicalLinkState(aSection); } else if ( aCommand==KCmdPreventRoleSwitch) { DoCmdPreventRoleSwitch(); } else if ( aCommand==KCmdAllowRoleSwitch) { DoCmdAllowRoleSwitch(); } else if ( aCommand==KCmdRequestMasterRole) { DoCmdRequestMasterRole(); } else if ( aCommand==KCmdRequestSlaveRole) { DoCmdRequestSlaveRole(); } else if ( aCommand==KCmdActivateSniffRequester) { DoCmdActivateSniffRequester(); } else if ( aCommand==KCmdActivateParkRequester) { DoCmdActivateParkRequester(); } else if ( aCommand==KCmdCancelSend) { DoCmdCancelSend(); } else if ( aCommand==KCmdCancelAll) { DoCmdCancelAll(); } else if ( aCommand==KCmdWrite) { DoCmdWrite(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdCancelWrite) { DoCmdCancelWrite(); } else if ( aCommand==KCmdSendTo) { DoCmdSendTo(aSection, aAsyncErrorIndex); } else if ( aCommand==KCmdRecvFrom) { DoCmdRecvFrom(aSection,aAsyncErrorIndex); } else if ( aCommand==KCmdGetDisconnectData) { DoCmdGetDisconnectData(); } else if ( aCommand==KCmdRequestChangeSupportedPacketTypes) { DoCmdRequestChangeSupportedPacketTypes(aSection); } else if ( aCommand==KCmdCancelRecv) { DoCmdCancelRecv(); } else if ( aCommand==KCmdRead) { DoCmdRead(aSection, aAsyncErrorIndex); } else if ( aCommand==KCmdCancelRead) { DoCmdCancelRead(); } else if ( aCommand==KCmdRemoteName) { DoCmdRemoteName(aSection); } else if ( aCommand==KCmdTestMBSN_ExtensionInterfaceL) { DoCmdTestMBSN_ExtensionInterfaceL(aSection); } else if ( aCommand==KCmdSetAutomaticSniffMode) { DoCmdSetAutomaticSniffMode(aSection); } else { retVal=EFalse; } return retVal; } inline void CT_CBluetoothSocketData::DoCmdAccept(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC expectedReply; iAcceptFlag = EFalse; iHasAcceptDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasAcceptDataToExpect ) { iAcceptDataToExpect.Copy(expectedReply); } TBool useAccept2 =EFalse; GetBoolFromConfig(aSection, KUseAccept2(), useAccept2); // Get the blank session socket TPtrC bluetoothSocketName; CBluetoothSocket* bluetoothSocket=NULL; if( GetStringFromConfig(aSection, KCBluetoothSocket(), bluetoothSocketName)) { bluetoothSocket=(static_cast<CT_BluetoothSocketNotifier*>(GetDataObjectL(bluetoothSocketName))->iBluetoothSocket); if ( bluetoothSocket!=NULL ) { TInt status; if ( useAccept2 ) { INFO_PRINTF1(_L("Using Accept 2")); status = iData->iBluetoothSocket->Accept(*bluetoothSocket, iDataToRead8); } else { INFO_PRINTF1(_L("Using Accept 1")); status = iData->iBluetoothSocket->Accept(*bluetoothSocket); } if(status==KErrNone) { IncOutstanding(); iAcceptFlag = ETrue; iAcceptIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("Accept failed: %d"),status); SetError(status); } } else { ERR_PRINTF1(_L("Bind TSockAddr is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdActivateBasebandEventNotifier(const TDesC& aSection,const TInt aAsyncErrorIndex) { // loop through all values in the ini file and add them up TUint32 flags=0; CT_BTUtil::GetLinkStateNotifierBits(*this, aSection, flags); TInt errCode = iData->iBluetoothSocket->ActivateBasebandEventNotifier(flags); if ( errCode==KErrNone ) { IncOutstanding(); iNotifierIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("ActivateBasebandEventNotifier failed with error code: %d"), errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdActivateParkRequester() { TInt errCode = iData->iBluetoothSocket->ActivateParkRequester(); if (errCode != KErrNone) { ERR_PRINTF2(_L("ActivateParkRequester failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdActivateSniffRequester() { TInt errCode = iData->iBluetoothSocket->ActivateSniffRequester(); if (errCode != KErrNone) { ERR_PRINTF2(_L("ActivateSniffRequester failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdAllowLowPowerModes(const TDesC& aSection) { TUint32 mode=0; CT_BTUtil::GetLowPowerMode(*this, aSection, mode); TInt errCode=iData->iBluetoothSocket->AllowLowPowerModes(mode); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send AllowLowPowerModes failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdAllowRoleSwitch() { TInt errCode = iData->iBluetoothSocket->AllowRoleSwitch(); if (errCode != KErrNone) { ERR_PRINTF2(_L("AllowRoleSwitch failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdBind(const TDesC& aSection) { TPtrC sockAddrName; if( GetStringFromConfig(aSection, KTSockAddr(), sockAddrName)) { INFO_PRINTF2(_L("Binding with: %S TSockAddr"), &sockAddrName); TBTSockAddr* sockAddr=static_cast<TBTSockAddr*>(GetDataObjectL(sockAddrName)); if ( sockAddr!=NULL ) { TInt errCode = iData->iBluetoothSocket->Bind(*sockAddr); if(errCode!=KErrNone) { ERR_PRINTF2(_L("Bind failed: %d"), errCode); SetError(errCode); } } else { ERR_PRINTF1(_L("Bind TSockAddr is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdCancelAccept() { iData->iBluetoothSocket->CancelAccept(); if(Outstanding() && iAcceptFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelAll() { iData->iBluetoothSocket->CancelAll(); } inline void CT_CBluetoothSocketData::DoCmdCancelBasebandEventNotifier() { iData->iBluetoothSocket->CancelBasebandEventNotifier(); if(Outstanding() && iNotifierFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelConnect() { iData->iBluetoothSocket->CancelConnect(); if(Outstanding() && iConnectFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelIoctl() { iData->iBluetoothSocket->CancelIoctl(); if(Outstanding() && iIoctlFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelLowPowerModeRequester(const TDesC& /*aSection*/) { TInt errCode=iData->iBluetoothSocket->CancelLowPowerModeRequester(); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send CancelLowPowerModeRequester failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdCancelRead() { iData->iBluetoothSocket->CancelRead(); if (Outstanding() && iReadFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelRecv() { iData->iBluetoothSocket->CancelRecv(); if (Outstanding() && iRecvFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelSend() { iData->iBluetoothSocket->CancelSend(); if (Outstanding() && iSendFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCancelWrite() { iData->iBluetoothSocket->CancelWrite(); if (Outstanding() && iWriteFlag) { DecOutstanding(); } } inline void CT_CBluetoothSocketData::DoCmdCloseSocketServer() { if(iData->iSocketServerConnected) { iData->iSocketServer.Close(); } iData->iSocketServerConnected=EFalse; } inline void CT_CBluetoothSocketData::DoCmdConnect(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC expectedReply; iConnectFlag = EFalse; iHasConnectDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasConnectDataToExpect ) { iConnectDataToExpect.Copy(expectedReply); } TPtrC sockAddrName; if( GetStringFromConfig(aSection, KTBTSockAddr(), sockAddrName)) { INFO_PRINTF2(_L("Connecting with: %S TBTSockAddr"), &sockAddrName); TBTSockAddr* myTBTSockAddr=static_cast<TBTSockAddr*>(GetDataObjectL(sockAddrName)); if ( myTBTSockAddr!=NULL ) { TInt errCode=KErrNone; TInt serviceBits; if ( GetIntFromConfig(aSection, KServiceBits(), serviceBits) ) { INFO_PRINTF1(_L("Using Connect 3")); TBTDevAddr tempAddress = myTBTSockAddr->BTAddr(); TBuf<KMaxSockAddrSize> tmpBuf; tempAddress.GetReadable(tmpBuf); INFO_PRINTF2(_L("Connecting to address (%S)"), &tmpBuf); errCode=iData->iBluetoothSocket->Connect(*myTBTSockAddr, serviceBits); } else { TPtrC connectData; if ( GetStringFromConfig(aSection, KConnectData(), connectData) ) { INFO_PRINTF1(_L("Using Connect 2")); TBuf8<DATASIZE> connectData8(_L8("")); connectData8.Copy(connectData); TBTDevAddr tempAddress = myTBTSockAddr->BTAddr(); TBuf<KMaxSockAddrSize> tmpBuf; tempAddress.GetReadable(tmpBuf); INFO_PRINTF2(_L("Connecting to address (%S)"), &tmpBuf); errCode =iData->iBluetoothSocket->Connect(*myTBTSockAddr, iDataToRead8, connectData8); } else { INFO_PRINTF1(_L("Using Connect 1")); TBTDevAddr tempAddress = myTBTSockAddr->BTAddr(); TBuf<KMaxSockAddrSize> tmpBuf; tempAddress.GetReadable(tmpBuf); INFO_PRINTF2(_L("Connecting to address (%S)"), &tmpBuf); errCode =iData->iBluetoothSocket->Connect(*myTBTSockAddr); } } if ( errCode == KErrNone) { IncOutstanding(); iConnectFlag = ETrue; iConnectIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("Connect failed: %d"), errCode); SetError(errCode); } } else { ERR_PRINTF1(_L("Connect TBTSockAddr is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdGetDisconnectData() { TInt errCode = iData->iBluetoothSocket->GetDisconnectData(iDisconnectDes8); if (errCode != KErrNone) { ERR_PRINTF2(_L("GetDisconnectData failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdGetOpt(const TDesC& aSection) { TBool found; TBool equals = ETrue; GetBoolFromConfig(aSection, KEquals(), equals); if (equals) { INFO_PRINTF1(_L("The comparison is expected to be equal.")); } else { INFO_PRINTF1(_L("The comparison is not expected to be equal.")); } TBool dataOk=ETrue; TPtrC optionName; TInt optionNameValue=0; if ( GetStringFromConfig(aSection, KOptionName(), optionName) ) { dataOk=CT_BTUtil::GetIntValue(optionName, optionNameValue); //Report error but continue as it may still make sense if (dataOk) { INFO_PRINTF3(_L("The name of the option to set: %S , its value: %d" ), &optionName, optionNameValue); } else { ERR_PRINTF2(_L("Option Level not found in lookup: %S"),&optionName); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Data %S missing"), &KOptionName()); SetBlockResult(EFail); } TPtrC optionLevel; TInt optionLevelValue; if( GetStringFromConfig(aSection, KOptionLevel(), optionLevel)) { found=CT_BTUtil::GetIntValue(optionLevel, optionLevelValue); //Report error but continue as it may still make sense if (found) { INFO_PRINTF3(_L("The name of the option level to set: %S , its value: %d" ),&optionLevel, optionLevelValue); } else { dataOk=EFalse; ERR_PRINTF2(_L("Option Level not found in lookup: %S"),&optionLevel); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Data %S missing"), &KOptionLevel()); SetBlockResult(EFail); } if ( dataOk ) { TBool getDes=EFalse; GetBoolFromConfig(aSection, KGetDes(), getDes); if ( getDes ) { TBuf8<DATASIZE> tempData8(_L8("")); TInt err = iData->iBluetoothSocket->GetOpt(optionNameValue, optionLevelValue, tempData8); if( err != KErrNone ) { INFO_PRINTF2(_L("GetOpt() return error %d" ), err); SetError(err); } TBuf<DATASIZE> tempData; tempData.Copy(tempData8); INFO_PRINTF3(_L("The value of the option retrived as des: %S, descriptor length: %d" ), &tempData, tempData.Length()); TPtrC desOption; // descriptor to compare with if getdes is TRUE if( GetStringFromConfig(aSection, KDesOption(), desOption)) { INFO_PRINTF2(_L("The expected descriptor value: %S" ), &desOption); if ( (desOption==tempData) == equals ) { INFO_PRINTF1(_L("Option is as expected")); } else { ERR_PRINTF1(_L("Option is not as expected")); SetBlockResult(EFail); } } } else { TInt val; TInt err = iData->iBluetoothSocket->GetOpt(optionNameValue, optionLevelValue, val); if( err != KErrNone ) { INFO_PRINTF2(_L("GetOpt() return error %d" ), err); SetError(err); } INFO_PRINTF2(_L("The value of the option retrived: %d" ),val); TInt intOption; // int value to compare with if getdes is FALSE or not defined if( GetIntFromConfig(aSection, KIntOption(), intOption)) { INFO_PRINTF1(_L("Comparing results")); if ( (intOption==val) == equals ) { INFO_PRINTF1(_L("Option is as expected")); } else { ERR_PRINTF1(_L("Option is not as expected")); SetBlockResult(EFail); } } } } } inline void CT_CBluetoothSocketData::DoCmdInfo(const TDesC& aSection) { TProtocolDesc protocolDesc; TInt err = iData->iBluetoothSocket->Info(protocolDesc); if ( err!=KErrNone ) { ERR_PRINTF2(_L("iBluetoothSocket->Info error: %d"), err); SetError(err); } INFO_PRINTF2(_L("iBluetoothSocket->Info() = %S"), &protocolDesc.iName); TPtrC expectedValue; if( GetStringFromConfig(aSection, KExpectedReply(), expectedValue) ) { if( expectedValue != protocolDesc.iName ) { ERR_PRINTF3(_L("Expected Info (%S) != Actual Info (%S)"), &expectedValue, &protocolDesc.iName); SetBlockResult(EFail); } } } inline void CT_CBluetoothSocketData::DoCmdIoctl(const TDesC& aSection,const TInt aAsyncErrorIndex) { TBool dataOk = ETrue; iIoctlFlag = EFalse; TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TBool useDeprecated=EFalse; GetBoolFromConfig(aSection, KUseDeprecated(), useDeprecated); TBool found = EFalse; TPtrC optionName; TInt optionNameValue=0; if( GetStringFromConfig(aSection, KOptionName(), optionName)) { found=CT_BTUtil::GetIntValue(optionName, optionNameValue); //Report error but continue as it may still make sense if (found) { INFO_PRINTF3(_L("The name of the option to set: %S , its value: %d" ), &optionName, optionNameValue); } else { dataOk=EFalse; ERR_PRINTF2(_L("Option not found in lookup: %S"), &optionName); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing: %S"), &KOptionName()); SetBlockResult(EFail); } TPtrC optionLevel; TInt optionLevelValue; if( GetStringFromConfig(aSection, KOptionLevel(), optionLevel)) { found=CT_BTUtil::GetIntValue(optionLevel, optionLevelValue); //Report error but continue as it may still make sense if (found) { INFO_PRINTF3(_L("The name of the option level to set: %S , its value: %d" ), &optionLevel, optionLevelValue); } else { ERR_PRINTF2(_L("Option Level not found in lookup: %S"), &optionLevel); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing: %S"), &KOptionLevel()); SetBlockResult(EFail); } if ( dataOk ) { TInt mtuOptionBufferSize = 0; GetIntFromConfig(aSection, KMTUSize(), mtuOptionBufferSize); if( mtuOptionBufferSize > DATASIZE ) { mtuOptionBufferSize = DATASIZE; WARN_PRINTF3(_L("mtuOptionBufferSize %d is large, using %d"), mtuOptionBufferSize, DATASIZE); } iMTUOptionBuffer = TPckgBuf<TUint16>(mtuOptionBufferSize); TInt errCode=KErrNone; if (useDeprecated) { errCode=iData->iBluetoothSocket->Ioctl(optionNameValue, &iMTUOptionBuffer, optionLevelValue); } else { errCode=iData->iBluetoothSocket->Ioctl(optionLevelValue, optionNameValue, &iMTUOptionBuffer); } if (errCode == KErrNone) { IncOutstanding(); iIoctlFlag = ETrue; iIoctlIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("Send Ioctl failed with error code: %d"), errCode); SetError(errCode); } if( boolCallTwice ) { if (useDeprecated) { errCode=iData->iBluetoothSocket->Ioctl(optionNameValue, &iMTUOptionBuffer, optionLevelValue); } else { errCode=iData->iBluetoothSocket->Ioctl(optionLevelValue, optionNameValue, &iMTUOptionBuffer); } if (errCode != KErrNone) { ERR_PRINTF2(_L("Send Ioctl failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iIoctlFlag = ETrue; //NB! May be not necessary, because the second call must call panics iIoctlIndex = aAsyncErrorIndex; } } } } inline void CT_CBluetoothSocketData::DoCmdListen(const TDesC& aSection) { TInt queueSize; if ( GetIntFromConfig(aSection, KQueueSize(), queueSize) ) { TInt errCode=KErrNone; TPtrC connectData; if ( GetStringFromConfig(aSection, KConnectData(), connectData) ) { iConnectData8 = _L8(""); iConnectData8.Copy(connectData); errCode=iData->iBluetoothSocket->Listen(queueSize, iConnectData8); } else { TInt serviceBits; if ( GetIntFromConfig(aSection, KServiceBits(), serviceBits) ) { INFO_PRINTF2(_L("Using Listen 3 Service bits is: %d"),serviceBits); errCode=iData->iBluetoothSocket->Listen(queueSize, serviceBits); } else { INFO_PRINTF1(_L("Using Listen 1")); errCode=iData->iBluetoothSocket->Listen(queueSize); } } if ( errCode!=KErrNone ) { ERR_PRINTF2(_L("Listen failed: %d"),errCode); SetError(errCode); } } else { ERR_PRINTF2(_L("Missing: %Sfailed"), &KServiceBits()); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdLocalName(const TDesC& aSection) { T_TBTSockAddrChild addr; iData->iBluetoothSocket->LocalName(addr); TBTDevAddr currentAddr = addr.BTAddr(); TBuf<KMaxSockAddrSize> tmpBuf; currentAddr.GetReadable(tmpBuf); INFO_PRINTF2(_L("LocalName() = 0x%S"), &tmpBuf); TPtrC myTBTDevAddrName; if ( GetStringFromConfig(aSection, KTBTDevAddr(), myTBTDevAddrName) ) { CT_BTDevAddrData* myTBTDevAddrData=static_cast<CT_BTDevAddrData*>(GetDataWrapperL(myTBTDevAddrName)); TBTDevAddr btDevAddr = *myTBTDevAddrData->GetAddress(); TBuf<KMaxSockAddrSize> tmpBuf2; btDevAddr.GetReadable(tmpBuf2); if (tmpBuf2 != tmpBuf) { ERR_PRINTF3(_L("Expected address (%S) != actual address (%S)"),&tmpBuf2,&tmpBuf); SetBlockResult(EFail); } } else { TInt lhs; TInt rhs; TBool lhsGiven = EFalse; TBool rhsGiven = EFalse; lhsGiven = GetHexFromConfig(aSection, KHexBTAddrL(), lhs ); rhsGiven = GetHexFromConfig(aSection, KHexBTAddrR(), rhs ); if (lhsGiven && rhsGiven) { TBTDevAddr btDevAddr (MAKE_TINT64(lhs, rhs)); TBuf<KMaxSockAddrSize> tmpBuf2; btDevAddr.GetReadable(tmpBuf2); if (tmpBuf2 != tmpBuf) { ERR_PRINTF3(_L("Expected address (%S) != actual address (%S)"),&tmpBuf2,&tmpBuf); SetBlockResult(EFail); } } } // Set in TBTSockAddr Data object so that it can be verified TPtrC myTSockAddrName; CT_BTSockAddrData* myTSockAddrData=NULL; if( GetStringFromConfig(aSection, KTSockAddr(), myTSockAddrName)) { myTSockAddrData=static_cast<CT_BTSockAddrData*>(GetDataWrapperL(myTSockAddrName)); if ( myTSockAddrData!=NULL ) { myTSockAddrData->SetObject(&addr,EFalse); } } } inline void CT_CBluetoothSocketData::DoCmdLocalPort(const TDesC& aSection) { TInt actualPort = iData->iBluetoothSocket->LocalPort(); INFO_PRINTF2(_L("Actual port is: %d"), actualPort); TInt port; if ( GetIntFromConfig(aSection, KPort(), port) ) { INFO_PRINTF2(_L("Expected port is: %d"), port); if ( actualPort!=port ) { ERR_PRINTF1(_L("LocalPort is not as expected")); SetBlockResult(EFail); } } } inline void CT_CBluetoothSocketData::DoCmdName() { TName theName; TInt err=iData->iBluetoothSocket->Name(theName); if ( err==KErrNone ) { // good print the name INFO_PRINTF2(_L("The socket name is: (%S)" ), &theName); } else { ERR_PRINTF2(_L("Failed to get the Name of the Bluetoothsocket, error code %d returned"),err); SetError(err); } } inline void CT_CBluetoothSocketData::DoCmdNewL(const TDesC& aSection, TBool aUseLC) { TInt constructorType = 0; GetIntFromConfig(aSection, KConstructorType(), constructorType); if ((constructorType >0 )&&(constructorType < 6)) { TBool dataOk=ETrue; TBool found = EFalse; delete iData->iBluetoothSocket; iData->iBluetoothSocket = NULL; if( constructorType == 1 ) { INFO_PRINTF1(_L("CBluetoothSocket Standard Constructor Call")); TInt intSockType=0; TPtrC sockType; if( GetStringFromConfig(aSection, KSockType(), sockType) ) { found=CT_BTUtil::GetIntValue(sockType, intSockType); if ( !found ) { dataOk=EFalse; ERR_PRINTF2(_L("Socket type not found in lookup: %S"),&sockType); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing :%S"), &KSockType()); SetBlockResult(EFail); } TInt intProtocol; TPtrC protocol; if ( GetStringFromConfig(aSection, KProtocol(), protocol) ) { found=CT_BTUtil::GetIntValue(protocol, intProtocol); if ( !found ) { dataOk=EFalse; ERR_PRINTF2(_L("Socket type not found in lookup: %S"),&sockType); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing :%S"), &KProtocol()); SetBlockResult(EFail); } if ( dataOk ) { if(aUseLC) { INFO_PRINTF1(_L("CBluetoothSocket Standard Constructor NewLC" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewLC(*iData, iData->iSocketServer, intSockType, intProtocol); CleanupStack::Pop();); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Standard Constructor NewLC err=%d" ),err); SetError(err); } } else { INFO_PRINTF1(_L("CBluetoothSocket Standard Constructor NewL" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewL(*iData, iData->iSocketServer, intSockType, intProtocol)); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Standard Constructor NewL err=%d" ),err); SetError(err); } } } } else if( constructorType == 2 ) { INFO_PRINTF1(_L("CBluetoothSocket RConnection Constructor Call")); TInt theSockType=0; TPtrC sockType; if ( GetStringFromConfig(aSection, KSockType(), sockType) ) { found=CT_BTUtil::GetIntValue(sockType, theSockType); if ( !found ) { dataOk=EFalse; ERR_PRINTF2(_L("Socket type not found in lookup: %S"), &sockType); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing :%S"), &KSockType()); SetBlockResult(EFail); } TInt theProtocol; TPtrC protocol; if ( GetStringFromConfig(aSection, KProtocol(), protocol) ) { found=CT_BTUtil::GetIntValue(protocol, theProtocol); if (!found) { dataOk=EFalse; ERR_PRINTF2(_L("Protocol not found in lookup: %S"), &protocol); SetBlockResult(EFail); } } else { dataOk=EFalse; ERR_PRINTF2(_L("Missing :%S"), &KProtocol()); SetBlockResult(EFail); } if ( dataOk ) { if ( aUseLC ) { INFO_PRINTF1(_L("CBluetoothSocket RConnection Constructor NewLC" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewLC(*iData, iData->iSocketServer, theSockType, theProtocol, iData->iConnection); CleanupStack::Pop();); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket RConnection Constructor NewLC err=%d" ),err); SetError(err); } } else { INFO_PRINTF1(_L("CBluetoothSocket RConnection Constructor NewL" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewL(*iData, iData->iSocketServer, theSockType, theProtocol,iData->iConnection)); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket RConnection Constructor NewL err=%d" ),err); SetError(err); } } } } else if( constructorType == 3 ) { INFO_PRINTF1(_L("CBluetoothSocket Named Protocol Constructor Call")); TPtrC namedProtocol; if( GetStringFromConfig(aSection, KNamedProtocol(), namedProtocol)) { if (aUseLC) { INFO_PRINTF1(_L("CBluetoothSocket Named Protocol Constructor NewLC" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewLC(*iData, iData->iSocketServer, namedProtocol); CleanupStack::Pop();); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Named Protocol Constructor NewLC err=%d" ),err); SetError(err); } } else { INFO_PRINTF1(_L("CBluetoothSocket Named Protocol Constructor NewL" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewL(*iData, iData->iSocketServer, namedProtocol)); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Named Protocol Constructor NewL err=%d" ),err); SetError(err); } } } else { ERR_PRINTF2(_L("Missing :%s"), &KNamedProtocol()); SetBlockResult(EFail); } } else if( constructorType == 4 ) { if (aUseLC) { INFO_PRINTF1(_L("CBluetoothSocket Blank Constructor NewLC")); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewLC(*iData, iData->iSocketServer); CleanupStack::Pop();); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Blank Constructor NewLC err=%d" ),err); SetError(err); } } else { INFO_PRINTF1(_L("CBluetoothSocket Blank Constructor NewL")); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewL(*iData, iData->iSocketServer)); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket Blank Constructor NewL err=%d" ),err); SetError(err); } } } else if( constructorType == 5 ) { INFO_PRINTF1(_L("CBluetoothSocket RSocket Constructor Call")); TPtrC myRSocketName; if( GetStringFromConfig(aSection, KRSocket(), myRSocketName)) { RSocket* myRSocket=static_cast<RSocket*>(GetDataObjectL(myRSocketName)); if ( myRSocket!=NULL ) { if (aUseLC) { INFO_PRINTF1(_L("CBluetoothSocket RSocket Constructor NewLC" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewLC(*iData, iData->iSocketServer, *myRSocket); CleanupStack::Pop();); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket RSocket Constructor NewLC err=%d" ),err); SetError(err); } } else { INFO_PRINTF1(_L("CBluetoothSocket RSocket Constructor NewL" )); TRAPD(err, iData->iBluetoothSocket = CBluetoothSocket::NewL(*iData, iData->iSocketServer, *myRSocket)); if( err!=KErrNone ) { INFO_PRINTF2(_L("CBluetoothSocket RSocket Constructor NewL err=%d" ),err); SetError(err); } } } else { ERR_PRINTF2(_L("Failed to fetch RSocket named %S"),&myRSocketName); SetBlockResult(EFail); } } else { ERR_PRINTF2(_L("Missing :%S"), &KRSocket()); SetBlockResult(EFail); } } else { INFO_PRINTF2(_L("Incorrect constructorType = %d" ),constructorType); SetBlockResult(EFail); } } else { ERR_PRINTF2(_L("Ilegal value for constructor type value in range 1-5 expected found: %d"),constructorType); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdPhysicalLinkState(const TDesC& aSection) { TUint32 tmpstate; TInt errCode = iData->iBluetoothSocket->PhysicalLinkState(tmpstate); if (errCode != KErrNone) { ERR_PRINTF2(_L("PhysicalLinkState failed with error code: %d"),errCode); SetError(errCode); } TInt state = static_cast<TInt>(tmpstate); //Process the state we can do a nice report here as we know what the bits are // See CT_BTUtil as a starting point INFO_PRINTF2(_L("PhysicalLinkState: %d" ), state ); TInt expectedState; if( GetIntFromConfig(aSection, KState(), expectedState) ) { if( expectedState != state ) { ERR_PRINTF3(_L("Expected PhysicalLinkState (%d) != Actual PhysicalLinkState (%d)"), state, expectedState); SetBlockResult(EFail); } } } inline void CT_CBluetoothSocketData::DoCmdPreventLowPowerModes(const TDesC& aSection) { TUint32 mode =0; CT_BTUtil::GetLowPowerMode(*this, aSection, mode); TInt errCode=iData->iBluetoothSocket->PreventLowPowerModes(mode); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send PreventLowPowerModes failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdPreventRoleSwitch() { TInt errCode = iData->iBluetoothSocket->PreventRoleSwitch(); if (errCode != KErrNone) { ERR_PRINTF2(_L("PreventRoleSwitch failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdRead(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC expectedReply; iReadFlag = EFalse; iHasReceiveDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasReceiveDataToExpect ) { iReceiveDataToExpect.Copy(expectedReply); } TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TInt errCode = iData->iBluetoothSocket->Read(iDataToRead8); if (errCode == KErrNone) { IncOutstanding(); iReadFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("Read failed with error code: %d"),errCode); SetError(errCode); } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Read(iDataToRead8); if (errCode != KErrNone) { ERR_PRINTF2(_L("Read failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iReadFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } } } inline void CT_CBluetoothSocketData::DoCmdRecv(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC expectedReply; iRecvFlag = EFalse; iHasReceiveDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasReceiveDataToExpect ) { iReceiveDataToExpect.Copy(expectedReply); } TInt flags=0; GetIntFromConfig(aSection, KFlags(), flags); TBool useRecv2 = EFalse; GetBoolFromConfig(aSection, KUseRecv2(), useRecv2); TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); if (useRecv2) { INFO_PRINTF1(_L("Using Recv 2")); INFO_PRINTF2(_L("Flags: %d"),flags); TSockXfrLength actuallengthSent; TInt errCode = iData->iBluetoothSocket->Recv(iDataToRead8, flags, actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("Recv failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iRecvFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Recv(iDataToRead8, flags, actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("Recv failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iRecvFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } } TInt& lenSentInt=actuallengthSent(); INFO_PRINTF2(_L("Returned actual length received: %d"), lenSentInt); if ( lenSentInt!=iDataToRead8.Length() ) { ERR_PRINTF3(_L("Returned length received: %d != Actual length received: %d"), lenSentInt, iDataToRead8.Length()); SetBlockResult(EFail); } } else { INFO_PRINTF1(_L("Using Recv 1")); INFO_PRINTF2(_L("Flags: %d"),flags); TInt errCode = iData->iBluetoothSocket->Recv(iDataToRead8, flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("Recv failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iRecvFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Recv(iDataToRead8, flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("Recv failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iRecvFlag = ETrue; iReceiveIndex = aAsyncErrorIndex; } } } } inline void CT_CBluetoothSocketData::DoCmdRecvFrom(const TDesC& aSection,const TInt aAsyncErrorIndex) { TPtrC expectedReply; iHasReceiveDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasReceiveDataToExpect ) { iReceiveDataToExpect.Copy(expectedReply); } TBool useRecv2 = EFalse; GetBoolFromConfig(aSection, KUseRecv2(), useRecv2); TInt flags = 0; // read in, if not found send 0 GetIntFromConfig(aSection, KFlags(), flags); TPtrC myTSockAddrName; TBTSockAddr* myTSockAddr=NULL; if( GetStringFromConfig(aSection, KTSockAddr(), myTSockAddrName)) { INFO_PRINTF2(_L("Binding with: %S TSockAddr"), &myTSockAddrName); myTSockAddr=static_cast<TBTSockAddr*>(GetDataObjectL(myTSockAddrName)); if ( myTSockAddr!=NULL ) { if (!useRecv2) { TInt errCode = iData->iBluetoothSocket->RecvFrom(iDataToRead8, *myTSockAddr, flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("RecvFrom failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iReceiveIndex = aAsyncErrorIndex; } } else { TSockXfrLength lenSent; TInt errCode = iData->iBluetoothSocket->RecvFrom(iDataToRead8, *myTSockAddr, flags, lenSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("RecvFrom failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iReceiveIndex = aAsyncErrorIndex; } TInt& lenSentInt=lenSent(); INFO_PRINTF2(_L("Returned actual length received: %d"), lenSentInt); if ( lenSentInt!=iDataToRead8.Length() ) { ERR_PRINTF3(_L("Returned length received: %d != Actual length received: %d"), lenSentInt, iDataToRead8.Length()); SetBlockResult(EFail); } } } else { ERR_PRINTF1(_L("RecvFrom TBTSockAddr is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdRecvOneOrMore(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC expectedReply; iHasReceiveDataToExpect=GetStringFromConfig(aSection, KExpectedReply(), expectedReply); if ( iHasReceiveDataToExpect ) { iReceiveDataToExpect.Copy(expectedReply); } TInt flags=0; GetIntFromConfig(aSection, KFlags(), flags); TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TSockXfrLength actuallengthSent; TInt errCode = iData->iBluetoothSocket->RecvOneOrMore(iDataToRead8, flags, actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("RecvOneOrMore failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iReceiveIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->RecvOneOrMore(iDataToRead8, flags, actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("RecvOneOrMore failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iReceiveIndex = aAsyncErrorIndex; } } TInt& lenSentInt=actuallengthSent(); INFO_PRINTF2(_L("Returned actual length received: %d"), lenSentInt); if ( lenSentInt!=iDataToRead8.Length() ) { ERR_PRINTF3(_L("Returned length received: %d != Actual length received: %d"), lenSentInt, iDataToRead8.Length()); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdRemoteName(const TDesC& aSection) { T_TBTSockAddrChild addr; iData->iBluetoothSocket->RemoteName(addr); TBTDevAddr currentAddr = addr.BTAddr(); TBuf<KMaxSockAddrSize> tmpBuf; currentAddr.GetReadable(tmpBuf); INFO_PRINTF2(_L("RemoteName() = 0x%S"),&tmpBuf); TPtrC myTBTDevAddrName; if( GetStringFromConfig(aSection, KTBTDevAddr(), myTBTDevAddrName)) { CT_BTDevAddrData* myTBTDevAddrData=static_cast<CT_BTDevAddrData*>(GetDataWrapperL(myTBTDevAddrName)); TBTDevAddr btDevAddr = *myTBTDevAddrData->GetAddress(); TBuf<KMaxSockAddrSize> tmpBuf2; btDevAddr.GetReadable(tmpBuf2); if (tmpBuf2 != tmpBuf) { ERR_PRINTF3(_L("Expected address (%S) != actual address (%S)"),&tmpBuf2,&tmpBuf); SetBlockResult(EFail); } } else { TInt lhs; TInt rhs; TBool lhsGiven = EFalse; TBool rhsGiven = EFalse; lhsGiven = GetHexFromConfig(aSection, KHexBTAddrL(), lhs ); rhsGiven = GetHexFromConfig(aSection, KHexBTAddrR(), rhs ); if (lhsGiven && rhsGiven) { TBTDevAddr btDevAddr (MAKE_TINT64(lhs, rhs)); TBuf<KMaxSockAddrSize> tmpBuf2; btDevAddr.GetReadable(tmpBuf2); if (tmpBuf2 != tmpBuf) { ERR_PRINTF3(_L("Expected address (%S) != actual address (%S)"),&tmpBuf2,&tmpBuf); SetBlockResult(EFail); } } } // Set in TBTSockAddr Data object so that it can be verified TPtrC myTSockAddrName; CT_BTSockAddrData* myTSockAddrData=NULL; if( GetStringFromConfig(aSection, KTSockAddr(), myTSockAddrName)) { myTSockAddrData=static_cast<CT_BTSockAddrData*>(GetDataWrapperL(myTSockAddrName)); if ( myTSockAddrData!=NULL ) { myTSockAddrData->SetObject(&addr,EFalse); } } } inline void CT_CBluetoothSocketData::DoCmdRequestChangeSupportedPacketTypes(const TDesC& aSection) { TInt mask = 0; CT_BTUtil::GetTBTPacketType(*this, aSection, mask); TInt errCode = iData->iBluetoothSocket->RequestChangeSupportedPacketTypes(mask); if (errCode != KErrNone) { ERR_PRINTF2(_L("RequestChangeSupportedPacketTypes failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdRequestMasterRole() { TInt errCode = iData->iBluetoothSocket->RequestMasterRole(); if (errCode != KErrNone) { ERR_PRINTF2(_L("RequestMasterRole failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdRequestSlaveRole() { TInt errCode = iData->iBluetoothSocket->RequestSlaveRole(); if (errCode != KErrNone) { ERR_PRINTF2(_L("RequestSlaveRole failed with error code: %d"),errCode); SetError(errCode); } } inline void CT_CBluetoothSocketData::DoCmdSend(const TDesC& aSection, const TInt aAsyncErrorIndex) { TPtrC dataToSend; iSendFlag = EFalse; if( GetStringFromConfig(aSection, KData(), dataToSend)) { INFO_PRINTF2(_L("About to send: [%S]"), &dataToSend); TBuf8<DATASIZE> dataToSend8(_L8("")); dataToSend8.Copy(dataToSend); for ( ;dataToSend8.Length()<DATASIZE;) { dataToSend8.Append(_L8("#")); } TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TInt flags=0; GetIntFromConfig(aSection, KFlags(), flags); TBool useSend2 =EFalse; GetBoolFromConfig(aSection, KUseSend2(), useSend2); if (useSend2!=EFalse) { INFO_PRINTF1(_L("Using Send 2")); INFO_PRINTF2(_L("Flags: %d"),flags); TSockXfrLength actuallengthSent; TInt errCode = iData->iBluetoothSocket->Send(dataToSend8,flags,actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Send(dataToSend8,flags,actuallengthSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendFlag = ETrue; iSendIndex = aAsyncErrorIndex; } } if (errCode == KErrNone) { TInt& lenSentInt=actuallengthSent(); INFO_PRINTF2(_L("Returned length actual sent: %d"), lenSentInt); if (lenSentInt != dataToSend8.Length()) { INFO_PRINTF3(_L("Returned length sent: %d != Actual length sent: %d"),lenSentInt,dataToSend8.Length()); SetBlockResult(EFail); } } } else { INFO_PRINTF1(_L("Using Send 1")); INFO_PRINTF2(_L("Flags: %d"),flags); TInt errCode = iData->iBluetoothSocket->Send(dataToSend8,flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendFlag = ETrue; iSendIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Send(dataToSend8,flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("Send failed: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendFlag = ETrue; iSendIndex = aAsyncErrorIndex; } } } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSendTo(const TDesC& aSection,const TInt aAsyncErrorIndex) { TBool useSend2 =EFalse; GetBoolFromConfig(aSection, KUseSend2(), useSend2); TInt flags = 0; // read in, if not found send 0 GetIntFromConfig(aSection, KFlags(), flags); TPtrC dataToSend; if( GetStringFromConfig(aSection, KData(), dataToSend)) { INFO_PRINTF2(_L("About to send: [%S]"), &dataToSend); TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TBuf8<DATASIZE> dataToSend8(_L8("")); dataToSend8.Copy(dataToSend); TPtrC myTSockAddrName; TBTSockAddr* myTSockAddr=NULL; if( GetStringFromConfig(aSection, KTSockAddr(), myTSockAddrName)) { INFO_PRINTF2(_L("Binding with: %S TSockAddr"), &myTSockAddrName); myTSockAddr=static_cast<TBTSockAddr*>(GetDataObjectL(myTSockAddrName)); if ( myTSockAddr!=NULL ) { if (!useSend2) { TInt errCode = iData->iBluetoothSocket->SendTo(dataToSend8,*myTSockAddr,flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("SendTo failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->SendTo(dataToSend8,*myTSockAddr,flags); if (errCode != KErrNone) { ERR_PRINTF2(_L("SendTo failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendIndex = aAsyncErrorIndex; } } } else { TSockXfrLength lenSent; TInt errCode = iData->iBluetoothSocket->SendTo(dataToSend8,*myTSockAddr,flags,lenSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("SendTo failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->SendTo(dataToSend8,*myTSockAddr,flags,lenSent); if (errCode != KErrNone) { ERR_PRINTF2(_L("SendTo failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iSendIndex = aAsyncErrorIndex; } } if (errCode == KErrNone) { TInt& lenSentInt=lenSent(); INFO_PRINTF2(_L("Returned actual length sent: %d"), lenSentInt); if (lenSentInt != dataToSend8.Length()) { INFO_PRINTF3(_L("Returned length sent: %d != Actual length sent: %d"),lenSentInt,dataToSend8.Length()); } } } } else { ERR_PRINTF1(_L("SendTo TBTSockAddr is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSetAutomaticSniffMode(const TDesC& aSection) { #if 0 //Commented by Vaibhav : Not Needed TBool sniffMode = EFalse; GetBoolFromConfig(aSection, KSniffMode(), sniffMode); TInt errCode = KErrNone; TInt sniffDelay = 0; if( GetIntFromConfig(aSection, KSniffDelay(), sniffDelay) ) { INFO_PRINTF3(_L("SetAutomaticSniffMode(%d, %d)"), sniffMode, sniffDelay); errCode = iData->iBluetoothSocket->SetAutomaticSniffMode(sniffMode, sniffDelay); } else { INFO_PRINTF2(_L("SetAutomaticSniffMode(%d)"), sniffMode); errCode = iData->iBluetoothSocket->SetAutomaticSniffMode(sniffMode); } if (errCode!=KErrNone) { ERR_PRINTF2(_L("SetAutomaticSniffMode failed: %d"),errCode); SetError(errCode); } #endif } inline void CT_CBluetoothSocketData::DoCmdSetLocalPort(const TDesC& aSection) { TInt port; if( GetIntFromConfig(aSection, KPort(), port)) { INFO_PRINTF2(_L("Port to set is: %d"), port); TInt errCode = iData->iBluetoothSocket->SetLocalPort(port); if (errCode!=KErrNone) { ERR_PRINTF2(_L("SetLocalPort failed: %d"),errCode); SetError(errCode); } } else { ERR_PRINTF2(_L("Missing :%S"), &KPort()); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSetNotifierL(const TDesC& aSection) { MBluetoothSocketNotifier* theNotifier = iData; TBool useAlternate =EFalse; GetBoolFromConfig(aSection, KUseAlternateNotifier(), useAlternate); if (useAlternate) { theNotifier=this; } iData->iBluetoothSocket->SetNotifier(*theNotifier); } inline void CT_CBluetoothSocketData::DoCmdSetOpt(const TDesC& aSection) { TPtrC optionName; TPtrC optionLevel; TInt optionNameValue; TInt optionLevelValue; TBool found = EFalse; if( GetStringFromConfig(aSection, KOptionName(), optionName)) { found=CT_BTUtil::GetIntValue(optionName, optionNameValue); //Report error but continue as it may still make sense if (!found) { ERR_PRINTF2(_L("Option not found in lookup: %S"),&optionName); SetBlockResult(EFail); } INFO_PRINTF3(_L("The name of the option to set: %S , its value: %d" ),&optionName, optionNameValue); if( GetStringFromConfig(aSection, KOptionLevel(), optionLevel)) { found=CT_BTUtil::GetIntValue(optionLevel, optionLevelValue); //Report error but continue as it may still make sense if (!found) { ERR_PRINTF2(_L("Option Level not found in lookup: %S"),&optionLevel); SetBlockResult(EFail); } INFO_PRINTF3(_L("The name of the option level to set: %S , its value: %d" ),&optionLevel, optionLevelValue); TPtrC intOptionName; if( GetStringFromConfig(aSection, KNamedIntOption(), intOptionName)) { INFO_PRINTF1(_L("Using SetOpt1 with named constant value")); TInt intOption; found=CT_BTUtil::GetIntValue(intOptionName, intOption); //Report error but continue as it may still make sense if (!found) { ERR_PRINTF2(_L("Option not found in lookup: %S"),&optionLevel); SetBlockResult(EFail); } INFO_PRINTF3(_L("The name of the option level to set: %S its value: %d" ),&intOptionName, intOption); iData->iBluetoothSocket->SetOpt(optionNameValue,optionLevelValue,intOption); } else { TInt intOption; if( GetIntFromConfig(aSection, KIntOption(), intOption)) { INFO_PRINTF1(_L("Using SetOpt1 with int value")); INFO_PRINTF2(_L("The value of the option level to set: %d" ),intOption); iData->iBluetoothSocket->SetOpt(optionNameValue,optionLevelValue,intOption); } else { TPtrC desOption; if( GetStringFromConfig(aSection, KDesOption(), desOption)) { INFO_PRINTF2(_L("The option level to set: %S" ),&desOption); TBuf8<DATASIZE> desOption8(_L8("")); desOption8.Copy(desOption); INFO_PRINTF3(_L("desOption len %d, desOption8 len %d" ),desOption.Length(), desOption8.Length()); INFO_PRINTF1(_L("Using Deprecated SetOpt2")); iData->iBluetoothSocket->SetOpt(optionNameValue,optionLevelValue,desOption8); } else { // Use default parameter for SetOpt i.e. call with two parameters only INFO_PRINTF1(_L("Using Deprecated SetOpt2 with default value")); iData->iBluetoothSocket->SetOpt(optionNameValue,optionLevelValue); } } } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSetOption(const TDesC& aSection) { TPtrC optionName; TPtrC optionLevel; TInt optionNameValue; TInt optionLevelValue; TBool found = EFalse; if( GetStringFromConfig(aSection, KOptionName(), optionName)) { found=CT_BTUtil::GetIntValue(optionName, optionNameValue); //Report error but continue as it may still make sense if (!found) { ERR_PRINTF2(_L("Option not found in lookup: %S"),&optionName); SetBlockResult(EFail); } INFO_PRINTF3(_L("The name of the option to set: %S , its value: %d" ),&optionName, optionNameValue); if( GetStringFromConfig(aSection, KOptionLevel(), optionLevel)) { found=CT_BTUtil::GetIntValue(optionLevel, optionLevelValue); //Report error but continue as it may still make sense if (!found) { ERR_PRINTF2(_L("Option Level not found in lookup: %S"),&optionLevel); SetBlockResult(EFail); } TPtrC desOption; if( GetStringFromConfig(aSection, KDesOption(), desOption)) { INFO_PRINTF2(_L("The option level to set: %S" ),&desOption); TBuf8<DATASIZE> desOption8(_L8("")); desOption8.Copy(desOption); INFO_PRINTF3(_L("desOption len %d, desOption8 len %d" ),desOption.Length(), desOption8.Length()); INFO_PRINTF1(_L("Using SetOption")); iData->iBluetoothSocket->SetOption(optionNameValue,optionLevelValue,desOption8); } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdShutdown(const TDesC& aSection, const TInt aAsyncErrorIndex) { TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); RSocket::TShutdown shutdown=RSocket::ENormal; TBool dataOk=CT_BTUtil::GetShutdown(*this, aSection, shutdown); if ( dataOk ) { TInt err=KErrNone; TBuf8<DATASIZE> dataToSend8(_L8("")); TPtrC disconnectData; TBool hasDisconnectData=GetStringFromConfig(aSection, KDisconnectData(), disconnectData); if( hasDisconnectData ) { INFO_PRINTF1(_L("Using second shutdown")); dataToSend8.Copy(disconnectData); err = iData->iBluetoothSocket->Shutdown(shutdown, dataToSend8, iDataAtDisconnect8); } else { INFO_PRINTF1(_L("Using standard shutdown")); err = iData->iBluetoothSocket->Shutdown(shutdown); } if ( err==KErrNone ) { IncOutstanding(); iShutdownIndex = aAsyncErrorIndex; } else { ERR_PRINTF2(_L("Shutdown of iBluetoothSocket failed with error code %d"), err); SetError(err); } if( boolCallTwice ) { if ( hasDisconnectData ) { err = iData->iBluetoothSocket->Shutdown(shutdown, dataToSend8, iDataAtDisconnect8); } else { err = iData->iBluetoothSocket->Shutdown(shutdown); } if (err != KErrNone ) { ERR_PRINTF2(_L("Shutdown of iBluetoothSocket failed with error code %d"),err); SetError(err); } } } } inline void CT_CBluetoothSocketData::DoCmdTransfer(const TDesC& aSection) { INFO_PRINTF1(_L("Transfer the Bluetooth socket to this testddata object" )); TPtrC myRSocketName; RSocket* myRSocket=NULL; if( GetStringFromConfig(aSection, KRSocket(), myRSocketName)) { INFO_PRINTF2(_L("Transfering: %S to this RSocketServer"), &myRSocketName); myRSocket=static_cast<RSocket*>(GetDataObjectL(myRSocketName)); if ( myRSocket!=NULL ) { TName myRSockName; myRSocket->Name(myRSockName); if (myRSockName.Length()>0) { TInt err = iData->iBluetoothSocket->Transfer(iData->iSocketServer, myRSockName); if (err == KErrNone ) { INFO_PRINTF1(_L("Transfer successful" )); } else { ERR_PRINTF2(_L("Transfer failed with error code %d"),err); SetError(err); } } else { ERR_PRINTF1(_L("Failed to fetch RSocket name")); SetBlockResult(EFail); } } else { ERR_PRINTF2(_L("Failed to fetch RSocket from %S"),&myRSocketName); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdWrite(const TDesC& aSection,const TInt aAsyncErrorIndex) { TPtrC dataToSend; iWriteFlag = EFalse; if( GetStringFromConfig(aSection, KData(), dataToSend)) { INFO_PRINTF2(_L("About to write: [%S]"), &dataToSend); TBool boolCallTwice = EFalse; GetBoolFromConfig(aSection, KCallTwice(), boolCallTwice); TBuf8<DATASIZE> dataToSend8(_L8("")); dataToSend8.Copy(dataToSend); for ( ;dataToSend8.Length()<DATASIZE;) { dataToSend8.Append(_L8("#")); } TInt errCode = iData->iBluetoothSocket->Write(dataToSend8); if (errCode != KErrNone) { ERR_PRINTF2(_L("ActivateBasebandEventNotifier failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iWriteFlag = ETrue; iSendIndex = aAsyncErrorIndex; } if( boolCallTwice ) { errCode = iData->iBluetoothSocket->Write(dataToSend8); if (errCode != KErrNone) { ERR_PRINTF2(_L("ActivateBasebandEventNotifier failed with error code: %d"),errCode); SetError(errCode); } else { IncOutstanding(); iWriteFlag = ETrue; iSendIndex = aAsyncErrorIndex; } } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdTestMBSN_ExtensionInterfaceL(const TDesC& aSection) { TInt tmp; void* theExtensionObjectPtr; TBool expectNull = EFalse; GetBoolFromConfig(aSection, KExpectNull(), expectNull); if( GetIntFromConfig(aSection, KUid(), tmp)) { TUid uid=TUid::Uid(tmp); TRAPD(err, iData->MBSN_ExtensionInterfaceL(uid,theExtensionObjectPtr)); if( err!=KErrNone ) { ERR_PRINTF2(_L("MBSN_ExtensionInterfaceL err=%d"),err); SetError(EFail); } if (expectNull) { //Fail if not NULL if (theExtensionObjectPtr!=NULL) { ERR_PRINTF1(_L("Expected Null pointer but object found")); SetBlockResult(EFail); } } else { //Fail if NULL if (theExtensionObjectPtr!=NULL) { } else { ERR_PRINTF1(_L("Expected object but found NULL")); SetBlockResult(EFail); } } } else { ERR_PRINTF1(_L("GetIntFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSetRsocketServerFromCBTSocket(const TDesC& aSection) { // Get the blank session socket TPtrC myCT_CBluetoothSocketDataName; CT_CBluetoothSocketData* myCT_CBluetoothSocketData=NULL; if( GetStringFromConfig(aSection, KCBluetoothSocket(), myCT_CBluetoothSocketDataName)) { myCT_CBluetoothSocketData=static_cast<CT_CBluetoothSocketData*>(GetDataWrapperL(myCT_CBluetoothSocketDataName)); if ( myCT_CBluetoothSocketData!=NULL ) { iData->iSocketServer=myCT_CBluetoothSocketData->GetRServer(); } else { ERR_PRINTF1(_L("CBluetoothSocket is NULL")); SetBlockResult(EFail); } } else { ERR_PRINTF1(_L("GetStringFromConfig failed")); SetBlockResult(EFail); } } inline void CT_CBluetoothSocketData::DoCmdSetTransferAble() { iData->iBluetoothSocket->SetOpt(KSOEnableTransfer, KSOLSocket, KProcPolicy().Package()); } RSocketServ& CT_CBluetoothSocketData::GetRServer() { return iData->iSocketServer; } // MBluetoothSocketNotifier implementation void CT_CBluetoothSocketData::HandleConnectCompleteL(TInt aErr) { INFO_PRINTF2(_L("HandleConnectCompleteL : Status (%d)" ), aErr); if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleConnectCompleteL called with error code: %d"),aErr); SetAsyncError(iConnectIndex, aErr); } else { INFO_PRINTF1(_L("HandleConnectCompleteL successful" )); } TBuf<DATASIZE> dataToRead(_L("")); dataToRead.Copy(iDataToRead8); INFO_PRINTF2(_L("Retrived: [%S]"), &dataToRead); if ( iHasConnectDataToExpect ) { TBuf<DATASIZE> dataExpected; dataExpected.Copy(iConnectDataToExpect); // If dataExpected is shorter add filler chars as we did in send // We just need to use a TBuf so that we can change it if ( dataExpected.Length()<dataToRead.Length() ) { for ( ;dataExpected.Length()<DATASIZE;) { dataExpected.Append(_L("#")); } } //Verify the data INFO_PRINTF2(_L("Expected: [%S]"), &dataExpected); if ( dataExpected != dataToRead ) { ERR_PRINTF1(_L("Data is not as expected")); SetBlockResult(EFail); } } DecOutstanding(); } void CT_CBluetoothSocketData::HandleAcceptCompleteL(TInt aErr) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleAcceptCompleteL called with error code: %d"),aErr); SetAsyncError(iAcceptIndex, aErr); } else { INFO_PRINTF1(_L("HandleAcceptCompleteL successful" )); } TBuf<DATASIZE> dataToRead(_L("")); dataToRead.Copy(iDataToRead8); INFO_PRINTF2(_L("Retrived: [%S]"),&dataToRead); if ( iHasAcceptDataToExpect ) { TBuf<DATASIZE> dataExpected; dataExpected.Copy(iAcceptDataToExpect); // If dataExpected is shorter add filler chars as we did in send // We just need to use a TBuf so that we can change it if ( dataExpected.Length()<dataToRead.Length() ) { for ( ;dataExpected.Length()<DATASIZE;) { dataExpected.Append(_L("#")); } } //Verify the data INFO_PRINTF2(_L("Expected: [%S]"),&dataExpected); if (dataExpected != dataToRead) { ERR_PRINTF1(_L("Data is not as expected")); SetBlockResult(EFail); } } DecOutstanding(); } void CT_CBluetoothSocketData::HandleShutdownCompleteL(TInt aErr) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleShutdownCompleteL called with error code: %d"),aErr); SetAsyncError(iShutdownIndex, aErr); } else { INFO_PRINTF1(_L("HandleShutdownCompleteL successful" )); } DecOutstanding(); } void CT_CBluetoothSocketData::HandleSendCompleteL(TInt aErr) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleSendCompleteL called with error code: %d"),aErr); SetAsyncError(iSendIndex, aErr); } else { INFO_PRINTF1(_L("HandleSendCompleteL successful" )); } DecOutstanding(); } void CT_CBluetoothSocketData::HandleReceiveCompleteL(TInt aErr) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleReceiveCompleteL called with error code: %d"),aErr); SetAsyncError(iReceiveIndex, aErr); } else { INFO_PRINTF1(_L("HandleReceiveCompleteL successful" )); } TBuf<DATASIZE> dataToRead(_L("")); dataToRead.Copy(iDataToRead8); INFO_PRINTF2(_L("Retrived: [%S]"), &dataToRead); if ( iHasReceiveDataToExpect ) { TBuf<DATASIZE> dataExpected; dataExpected.Copy(iReceiveDataToExpect); // If dataExpected is shorter add filler chars as we did in send // We just need to use a TBuf so that we can change it if ( dataExpected.Length()<dataToRead.Length() ) { for ( ;dataExpected.Length()<DATASIZE;) { dataExpected.Append(_L("#")); } } // Verify the data if (dataExpected != dataToRead) { ERR_PRINTF1(_L("Data is not as expected")); SetBlockResult(EFail); } INFO_PRINTF2(_L("Expected: [%S]"), &dataExpected); } DecOutstanding(); } void CT_CBluetoothSocketData::HandleIoctlCompleteL(TInt aErr) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleIoctlCompleteL called with error code: %d"),aErr); SetAsyncError(iIoctlIndex, aErr); } else { INFO_PRINTF1(_L("HandleIoctlCompleteL successful" )); TBuf8<DATASIZE> tempBuffer(_L8("")); tempBuffer.Copy(iMTUOptionBuffer); INFO_PRINTF2(_L("HandleIoctlCompleteL = %S" ), &tempBuffer); } DecOutstanding(); } void CT_CBluetoothSocketData::HandleActivateBasebandEventNotifierCompleteL(TInt aErr, TBTBasebandEventNotification & aEventNotification) { if (aErr != KErrNone) { ERR_PRINTF2(_L("HandleActivateBasebandEventNotifierCompleteL called with error code: %d"),aErr); SetAsyncError(iNotifierIndex, aErr); } else { INFO_PRINTF1(_L("HandleActivateBasebandEventNotifierCompleteL successful" )); //Commented and changed by Vaibhav : Not Needed // INFO_PRINTF4(_L("Even type: %d Error code: %d Symbian Error Code: %d"), aEventNotification.EventType(), aEventNotification.ErrorCode(), aEventNotification.SymbianErrorCode()); INFO_PRINTF4(_L("Even type: %d Error code: %d Symbian Error Code: %d"), aEventNotification.EventType(), aEventNotification.ErrorCode(), KErrGeneral); } DecOutstanding(); }
[ "none@none" ]
[ [ [ 1, 2746 ] ] ]
7b6edae08f1f0a7d8d3874b24a056bbb35245200
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Core/include/Process.h
c0df30fdb54a0207beb5308f14e5f6554b490278
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,189
h
#pragma once #include "base.h" //Forward declarations--------------------- class CCamera; class CRenderManager; //----------------------------------------- /** * Intefície bàsica d'un procés. * Classe que designa l'interfície principal que ha de tenir un procés que faci servir l'engine. **/ class CProcess: public CBaseControl { public: /** * Constructor per defecte. * Constructor de la classe. Permet especificar el nom que rebrà el procés. * @param _szProcessName Nom que rebrà el procés. **/ CProcess(const string& _szProcessName): m_pCamera(0),m_szProcessName(_szProcessName),m_bRenderInfo(true) {}; /** * Mètode d'update. * Aquest mètode s'executa a cada iteració. Durant aquest es realitzaran els càlculs de lògica del procés. * @param _fElapsedTime És necessari facilitar-hi el temps transcorregut desde l'última crida al mètode. **/ virtual void Update(float _fElapsedTime) = 0; virtual void RenderINFO(CRenderManager* _pRM) = 0; /** * Mètode per mostrar informació de debug. * Aquest mètode mostrarà per pantalla diversa informació que pot ser d'utilitat per al debug: * - Nom del procés * - FramesPerSecond **/ void DebugInformation(CRenderManager* _pRM); /** * Mètode d'inicialització. * Aquest mètode inicialitzarà el procés, deixant-lo llest pel seu funcionament. **/ virtual bool Init() = 0; /** * Getter de la càmara. * Aquest mètode retorna l'actual càmara assignada al procés i sobre la qual es dibuixa l'escena. * @return CCamera* que representa l'actual càmara assignada al procés. **/ virtual CCamera* GetCamera () {return m_pCamera;}; /** * Mètode d'execució d'accions. * Aquest mètode executarà accions concretes del procés durant un temps determinat. * @param _fDeltaSeconds Temps de duració de l'acció. * @param _fDelta Temps de duració de l'acció. TODO ???? * @param _pcAction Nom identificatiu de l'acció a realitzar. * @return True si l'acció existeix. False si no. **/ bool ExecuteAction (float _fDeltaSeconds, float _fDelta, const char* _pcAction); /** * Mètode d'execució d'accions scriptades. * Aquest mètode executarà accions scriptades que contingui el procés. * @param _fDeltaSeconds Temps de duració de l'acció. * @param _fDelta Temps de duració de l'acció. TODO ???? * @param _pcScript Nom identificatiu de l'acció scriptada a realitzar. * @return True si l'acció existeix. False si no. **/ bool ExecuteScript (float _fDeltaSeconds, float _fDelta, const char* _pcScript); /** * TODO * Mètode d'execució d'accions. * Aquest mètode executarà accions concretes del procés durant un temps determinat. * @param _fDeltaSeconds Temps de duració de l'acció. * @param _fDelta Temps de duració de l'acció. TODO ???? * @param _pcAction Nom identificatiu de l'acció a realitzar. * @return True si l'acció existeix. False si no. **/ virtual bool ExecuteProcessAction (float _fDeltaSeconds, float _fDelta, const char* _pcAction) = 0; bool getRenderInfo() {return m_bRenderInfo;} virtual void RegisterLuaFunctions () {} protected: /** * Punter a càmara. * Punter que representa l'actual càmara assignada al procés. L'escena es dibuixarà a partir d'aquesta càmara. **/ CCamera* m_pCamera; /** * Setter del DebugInfo. * Aquest mètode permet determinar si es farà o no el pintat de debug. * @param _bRenderInfo Si es vol o no mostrar la informació de debug. **/ virtual void SetDebugInfo (bool _bRenderInfo) { m_bRenderInfo = _bRenderInfo; }; private: /** * Nom del procés. **/ string m_szProcessName; /** * Control de pintat. * Variable utilitzada per determinar si s'ha de fer el pintat de debug o no. **/ bool m_bRenderInfo; };
[ "[email protected]", "mudarra@576ee6d0-068d-96d9-bff2-16229cd70485", "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485", "[email protected]", "galindix@576ee6d0-068d-96d9-bff2-16229cd70485", "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 1 ], [ 3, 3 ], [ 13, 17 ], [ 44, 45 ], [ 87, 87 ], [ 100, 101 ], [ 105, 105 ], [ 110, 112 ] ], [ [ 2, 2 ], [ 4, 4 ], [ 6, 7 ], [ 9, 12 ], [ 18, 23 ], [ 25, 29 ], [ 32, 37 ], [ 40, 43 ], [ 46, 60 ], [ 62, 69 ], [ 72, 80 ], [ 88, 91 ], [ 93, 99 ], [ 102, 104 ], [ 106, 109 ] ], [ [ 5, 5 ], [ 8, 8 ], [ 24, 24 ], [ 38, 39 ], [ 71, 71 ], [ 83, 83 ], [ 86, 86 ], [ 92, 92 ] ], [ [ 30, 30 ] ], [ [ 31, 31 ], [ 82, 82 ] ], [ [ 61, 61 ], [ 70, 70 ], [ 81, 81 ], [ 84, 85 ] ] ]
80ef5b120bcf123191e952d467046309ea18f542
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/TreeInformation.cpp
1a49e0c397925f624ab1bdad81821039ef3fa07a
[]
no_license
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,015
cpp
#include "StdAfx.h" #include "TreeInformation.h" #if __VER >= 15 /* __IMPROVE_QUEST_INTERFACE */ && defined( __CLIENT ) //----------------------------------------------------------------------------- CTreeInformation::CTreeInformation( void ) : m_dwData( 0 ), m_bOpen( TRUE ) { } //----------------------------------------------------------------------------- CTreeInformation::~CTreeInformation( void ) { } //----------------------------------------------------------------------------- void CTreeInformation::SetData( DWORD dwData ) { m_dwData = dwData; } //----------------------------------------------------------------------------- DWORD CTreeInformation::GetData( void ) const { return m_dwData; } //----------------------------------------------------------------------------- void CTreeInformation::SetOpen( BOOL bOpen ) { m_bOpen = bOpen; } //----------------------------------------------------------------------------- BOOL CTreeInformation::GetOpen( void ) const { return m_bOpen; } //----------------------------------------------------------------------------- int CTreeInformationManager::m_nSelectedTabNumber = 0; CTreeInformationManager::QuestListGroup CTreeInformationManager::m_eQuestListGroup = CTreeInformationManager::CURRENT_QUEST_LIST; //----------------------------------------------------------------------------- CTreeInformationManager::CTreeInformationManager( void ) { } //----------------------------------------------------------------------------- CTreeInformationManager::~CTreeInformationManager( void ) { DeleteAllTreeInformation(); } //----------------------------------------------------------------------------- TreeInformationList* CTreeInformationManager::GetTreeInformationList( void ) { return &m_TreeInformationList; } //----------------------------------------------------------------------------- CTreeInformation* CTreeInformationManager::GetTreeInformation( DWORD dwData ) const { for( TreeInformationList::const_iterator Itor = m_TreeInformationList.begin(); Itor != m_TreeInformationList.end(); ++Itor ) { CTreeInformation* pTreeInformation = ( CTreeInformation* )( *Itor ); DWORD dwIteratorData = pTreeInformation->GetData(); if( dwIteratorData == dwData ) return pTreeInformation; } return NULL; } //----------------------------------------------------------------------------- void CTreeInformationManager::InsertTreeInformation( DWORD dwData, BOOL bOpen ) { CTreeInformation* pTreeInformation = new CTreeInformation; pTreeInformation->SetData( dwData ); pTreeInformation->SetOpen( bOpen ); m_TreeInformationList.push_back( pTreeInformation ); } //----------------------------------------------------------------------------- void CTreeInformationManager::DeleteTreeInformation( DWORD dwData ) { for( TreeInformationList::iterator Itor = m_TreeInformationList.begin(); Itor != m_TreeInformationList.end(); ++Itor ) { CTreeInformation* pTreeInformation = ( CTreeInformation* )( *Itor ); DWORD dwIteratorData = pTreeInformation->GetData(); if( dwIteratorData == dwData ) { SAFE_DELETE( pTreeInformation ); m_TreeInformationList.erase( Itor ); return; } } } //----------------------------------------------------------------------------- void CTreeInformationManager::DeleteAllTreeInformation( void ) { for( TreeInformationList::iterator Itor = m_TreeInformationList.begin(); Itor != m_TreeInformationList.end(); ++Itor ) SAFE_DELETE( *Itor ); m_TreeInformationList.clear(); m_nSelectedTabNumber = 0; m_eQuestListGroup = CTreeInformationManager::CURRENT_QUEST_LIST; } //----------------------------------------------------------------------------- int CTreeInformationManager::GetTreeInformationListSize( void ) const { return m_TreeInformationList.size(); } //----------------------------------------------------------------------------- #endif // defined( __IMPROVE_QUEST_INTERFACE ) && defined( __CLIENT )
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 102 ] ] ]
4d231d12f12a584b448bc7a9346c43822645d8bc
009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd
/S60_3rd_QT/FrameWidget.h
b559da80006476c405d6cab6bb7549224738d75e
[]
no_license
AnthonyNystrom/MobiVU
c849857784c09c73b9ee11a49f554b70523e8739
b6b8dab96ae8005e132092dde4792cb363e732a2
refs/heads/master
2021-01-10T19:36:50.695911
2010-10-25T03:39:25
2010-10-25T03:39:25
1,015,426
3
3
null
null
null
null
UTF-8
C++
false
false
468
h
#ifndef FRAMEWIDGET_H #define FRAMEWIDGET_H #include <QWidget> #include <QPixmap> class CFrame : public QWidget { QPixmap *_pix; QImage *_video; bool _bDrawVideo; int _iW, _iH; protected: virtual void paintEvent(QPaintEvent *pe); public: CFrame(QWidget *Parent); ~CFrame(); void DrawVideo(bool bDraw); void RefreshVideo(unsigned char *p); void SetSize(int iW, int iH); }; #endif // FRAMEWIDGET_H
[ [ [ 1, 25 ] ] ]
35ecbe43db408b9638d1b1b8e83d7f747604e15e
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/Switch.cpp
01b9e8dc907eed1d39b7be4f7a35de171e624d1c
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
3,400
cpp
// ----------------------------------------------------------------------- // // // MODULE : Switch.CPP // // PURPOSE : A Switch object // // CREATED : 12/3/97 // // ----------------------------------------------------------------------- // // // Includes... // #include "stdafx.h" #include "Switch.h" LINKFROM_MODULE( Switch ); BEGIN_CLASS( Switch ) // Set AWM Type AWM_SET_TYPE_STATIC // Overrides... // Override the options group... ADD_BOOLPROP_FLAG(PlayerActivate, LTTRUE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(AIActivate, LTTRUE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(StartOn, LTFALSE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(TriggerOff, LTTRUE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(RemainOn, LTTRUE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(ForceMove, LTFALSE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(Locked, LTFALSE, PF_GROUP(3)) ADD_BOOLPROP_FLAG(RotateAway, LTFALSE, PF_GROUP(3)) ADD_STRINGPROP_FLAG(Waveform, "Linear", PF_STATICLIST | PF_GROUP(3)) // Override the sounds group... ADD_STRINGPROP_FLAG(PowerOnSound, "", PF_FILENAME | PF_GROUP(4)) ADD_STRINGPROP_FLAG(OnSound, "", PF_FILENAME | PF_GROUP(4)) ADD_STRINGPROP_FLAG(PowerOffSound, "", PF_FILENAME | PF_GROUP(4)) ADD_STRINGPROP_FLAG(OffSound, "", PF_FILENAME | PF_GROUP(4)) ADD_STRINGPROP_FLAG(LockedSound, "", PF_FILENAME | PF_GROUP(4)) ADD_VECTORPROP_VAL_FLAG(SoundPos, 0.0f, 0.0f, 0.0f, PF_GROUP(4)) ADD_REALPROP_FLAG(SoundRadius, 1000.0f, PF_RADIUS | PF_GROUP(4)) ADD_BOOLPROP_FLAG(LoopSounds, LTFALSE, PF_GROUP(4)) // Override the commands group... ADD_STRINGPROP_FLAG(OnCommand, "", PF_GROUP(5) | PF_NOTIFYCHANGE) ADD_STRINGPROP_FLAG(OffCommand, "", PF_GROUP(5) | PF_NOTIFYCHANGE) ADD_STRINGPROP_FLAG(PowerOnCommand, "", PF_GROUP(5) | PF_NOTIFYCHANGE) ADD_STRINGPROP_FLAG(PowerOffCommand, "", PF_GROUP(5) | PF_NOTIFYCHANGE) ADD_STRINGPROP_FLAG(LockedCommand, "", PF_GROUP(5) | PF_NOTIFYCHANGE) // Override the movement properties... ADD_VECTORPROP_VAL_FLAG(MoveDir, 0.0f, 0.0f, 1.0f, 0) ADD_REALPROP_FLAG(MoveDist, 8.0f, 0) // Override the rotation properties... ADD_STRINGPROP_FLAG(RotationPoint, "", PF_OBJECTLINK) ADD_VECTORPROP_VAL_FLAG(RotationAngles, 0.0f, 90.0f, 0.0f, 0) // Override the common props... ADD_REALPROP_FLAG(PowerOnTime, AWM_DEFAULT_POWERONTIME, 0) ADD_REALPROP_FLAG(PowerOffTime, AWM_DEFAULT_POWEROFFTIME, 0) ADD_REALPROP_FLAG(MoveDelay, AWM_DEFAULT_MOVEDELAY, 0) ADD_REALPROP_FLAG(OnWaitTime, AWM_DEFAULT_ONWAITTIME, 0) ADD_REALPROP_FLAG(OffWaitTime, AWM_DEFAULT_OFFWAITTIME, 0) END_CLASS_DEFAULT_FLAGS( Switch, ActiveWorldModel, NULL, NULL, CF_HIDDEN | CF_WORLDMODEL ) // // Register the calss with the command mgr plugin and add any messages to the class // CMDMGR_BEGIN_REGISTER_CLASS( Switch ) CMDMGR_END_REGISTER_CLASS( Switch, ActiveWorldModel ) // ----------------------------------------------------------------------- // // // ROUTINE: Switch::Switch() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // Switch::Switch() : ActiveWorldModel( ) { } // ----------------------------------------------------------------------- // // // ROUTINE: Switch::~Switch() // // PURPOSE: Destroy object // // ----------------------------------------------------------------------- // Switch::~Switch() { }
[ [ [ 1, 112 ] ] ]
7e613c385d71d921e5372dff016a1087b26ac274
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/common/hySignatureBase.cpp
ba9cda916416ae6a6ac2f3db701fd91c0a1cf15f
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,877
cpp
/* -*- coding: sjis-dos; -*- */ /* * copyright 2010 FUKUZAWA Tadashi. All rights reserved. */ #include "hySignatureBase.h" using namespace Hayat::Common; #ifndef WIN32 // gccではこれが必要… const SignatureBase::Sig_t SignatureBase::MULTI; // = 0xf0; const SignatureBase::Sig_t SignatureBase::MULTI2; // = 0xf1; #endif const SignatureBase::Sig_t SignatureBase::PREDEFINED_PARAMS[SignatureBase::NUM_PREDEFINED_PARAMS][3] = { { SignatureBase::NESTNUM_1, 0 }, // (0) { SignatureBase::NESTNUM_1, 1 }, // (1) { SignatureBase::NESTNUM_1, 2 }, // (2) { SignatureBase::NESTNUM_1, 3 }, // (3) { SignatureBase::NESTNUM_1, 4 }, // (4) { SignatureBase::NESTNUM_1, 5 }, // (5) { SignatureBase::NESTNUM_1, 6 }, // (6) { SignatureBase::NESTNUM_1, 7 }, // (7) { SignatureBase::NESTNUM_1, 8 }, // (8) { SignatureBase::NESTNUM_1, SignatureBase::MULTI }, // (*) { SignatureBase::NESTNUM_1, SignatureBase::MULTI2 }, // (...) { SignatureBase::NESTNUM_1, SignatureBase::DEFVAL }, // ($0) { SignatureBase::NESTNUM_2, 1, SignatureBase::DEFVAL }, // (1,$0) { SignatureBase::NESTNUM_2, 2, SignatureBase::DEFVAL }, // (2,$0) { SignatureBase::NESTNUM_2, 3, SignatureBase::DEFVAL }, // (3,$0) { SignatureBase::NESTNUM_2, 1, SignatureBase::MULTI }, // (1,*) { SignatureBase::NESTNUM_2, 2, SignatureBase::MULTI }, // (2,*) { SignatureBase::NESTNUM_2, 3, SignatureBase::MULTI }, // (3,*) { SignatureBase::NESTNUM_2, SignatureBase::DEFVAL, SignatureBase::DEFVAL+1 }, // ($0,$1) }; // PREDEFINED_PARAMS[][0] は NESTNUM_1 もしくは NESTNUM_2 でなければならない // → Compiler::Package::initialize() に依存コードあり // ネスティングの中身を丸ごとスキップ void SignatureBase::m_skip(const Sig_t*& p) { HMD_DEBUG_ASSERT(m_isNestnum(*p)); int n = m_sig2nestnum(*p++); while (n-- > 0) { if (m_isNestnum(*p)) m_skip(p); } } // 引数の個数 int SignatureBase::m_arity(const Sig_t*& p) { int a = 0; int n = m_sig2nestnum(*p++); while (n-- > 0) { Sig_t s = *p; if (m_isNestnum(s)) { int x = m_arity(p); if (x == 0) ++a; else a += x; } else if (m_isMulti(s)) { ++a; ++p; } else if (m_isNormal(s)) { a += s; ++p; } else if (m_isDefaultVal(s)) { ++a; } else { HMD_FATAL_ERROR("unknown signature byte %x", s); } } return a; } // デフォルト値インデックスの調整 void SignatureBase::m_adjustDefaultValIdx(Sig_t*& p, int& idx) { int n = m_sig2nestnum(*p++); while (n-- > 0) { Sig_t s = *p; if (m_isNestnum(s)) { m_adjustDefaultValIdx(p, idx); } else if (m_isMulti(s)) { if (s < MULTI) { // デフォルト値付きマルチ *p = defaultValIdx2multisig(idx++); } ++p; } else if (m_isNormal(s)) { ++p; } else if (m_isDefaultVal(s)) { *p++ = defaultValIdx2sig(idx++); } else { HMD_FATAL_ERROR("unknown signature byte %x", s); } } } void SignatureBase::debugPrintSignature(const Sig_t* p) { char buf[256]; buf[0] = '\0'; snAddPrintSig(buf, 256, p); HMD_PRINTF(buf); } void SignatureBase::snAddPrintSig(char* buf, size_t bufSize, const Sig_t*& p) { HMD_STRSCAT(buf,"(",bufSize); int n = m_sig2nestnum(*p); while (n-- > 0) { Sig_t s = *++p; if (m_isNormal(s)) { char xx[16]; HMD_SNPRINTF(xx,16,"%d",s); HMD_STRSCAT(buf,xx,bufSize); } else if (s == MULTI2) HMD_STRSCAT(buf,"...",bufSize); else if (m_isMultiDefaultVal(*p)) HMD_STRSCAT(buf,"*$",bufSize); else if (m_isMulti(s)) HMD_STRSCAT(buf,"*",bufSize); else if (m_isDefaultVal(*p)) HMD_STRSCAT(buf,"$",bufSize); else if (m_isSep(s)) HMD_STRSCAT(buf,"/",bufSize); else snAddPrintSig(buf,bufSize,p); if (n>0) HMD_STRSCAT(buf,",",bufSize); } HMD_STRSCAT(buf,")",bufSize); } void SignatureBase::printPredefinedSignatures() { char buf[256]; for (hyu32 i = 0; i < NUM_PREDEFINED_PARAMS; ++i) { const Sig_t* p = PREDEFINED_PARAMS[i]; HMD_SNPRINTF(buf, 256, "%d:%d:", i, m_arity(p)); p = PREDEFINED_PARAMS[i]; snAddPrintSig(buf, 256, p); HMD_PRINTF(buf); HMD_PRINTF("\n"); } }
[ [ [ 1, 161 ] ] ]
b3859b076863d73387b9f23ec0581e6b974b3673
5bc5d779cacf86327d641a588b59a446aa535ba5
/Sklep/sklep.h
d5513c0106d7a3c902359032f2824069776834c6
[]
no_license
korredMS/projekt
03dceae447e05bf6d2cd9da3791ab7b627569083
d5d1f7702018dee4cb78fdb172b2c6ca36d59514
refs/heads/master
2020-04-16T04:23:14.650709
2010-06-15T06:59:08
2010-06-15T06:59:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
h
#ifndef SKLEP_H #define SKLEP_H #include <QDebug> #include <QtSql> #include <QMainWindow> #include <QGridLayout> #include <QListWidgetItem> #include <QMessageBox> #include "sprzedawca.h" #include "kierownik.h" #include "zamawiajacy.h" #include "../DBProxy/dbproxy.h" namespace Ui { class Sklep; } class Sklep : public QMainWindow { Q_OBJECT public: Sklep(QWidget *parent = 0); ~Sklep(); protected: void changeEvent(QEvent *e); private: Ui::Sklep *ui; DBProxy baza; QString posadaLogowanie; QString osobaLogowanie; QList< DBProxy::Pracownik > pracownicy; private slots: void on_listWidget_itemClicked(QListWidgetItem* item); void on_pushButton_clicked(); void on_comboBox_currentIndexChanged(QString ); }; #endif // SKLEP_H
[ [ [ 1, 47 ] ] ]
b39fd33953adfad71de102bc96d0b8f49aa4bca7
252e638cde99ab2aa84922a2e230511f8f0c84be
/graphlib/src/TripDiagramForm.h
9c3abbba7bbf4fd5c5893d4752aa416d021a5bf3
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
22,555
h
//--------------------------------------------------------------------------- #ifndef TripDiagramFormH #define TripDiagramFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ExtCtrls.hpp> #include <ADODB.hpp> #include <Db.hpp> #include <ComCtrls.hpp> #include <DBGrids.hpp> #include <Grids.hpp> #include <DBCtrls.hpp> #include "RXDBCtrl.h" #include "VDBSortGrid.h" #include "VDBLookupComboBox.h" #include "Placemnt.h" #include "VADODataSourceOrdering.h" #include "VCustomDataSourceOrdering.h" #include <ImgList.hpp> #include <Menus.hpp> #include <ActnList.hpp> #include "VStringStorage.h" #include <vector> #include <string> #include <VCanvas.h> #include "TourDataCU.h" //#include <TripDiagramData.h> #include <TourData.h> //--------------------------------------------------------------------------- #define TripDiagramTourIndexUndefined (0xFFFFFFFFL) #define TripDiagramStopIndexUndefined (0xFFFFFFFFL) #define TripDiagramTourSpeedUndefined (-1) #define TripDiagramTourDinstanceUndefined (-1) extern int TripDiagramCompareDouble (AnsiString FirstValueStr, AnsiString SecondValueStr); extern int TripDiagramCompareTime (AnsiString Time1ValueStr, AnsiString Time2ValueStr); extern AnsiString TripDiagramTimeInMinutesToStr (unsigned int Time); extern unsigned int TripDiagramTimeInStrToMinutes (AnsiString TimeStr); typedef struct { AnsiString StopIdStr; AnsiString StopNameStr; AnsiString TripStepInTimeStr; AnsiString TripStepWaitTimeStr; } TripDiagramTimeTableItemType; typedef struct { float Distance; std::string StopIdStr; } TripDiagramStopDistanceInfoType; class TripDiagramStopDistanceCacheClass { #define Self TripDiagramStopDistanceCacheClass public : Self (void); void Load (TourDataPtrClass SourceDataPtr); void Clear (void); float Distance (unsigned int FromStopIndex, unsigned int ToStopIndex); float DistanceFromFirst (unsigned int ToStopIndex); float DistanceToLast (unsigned int FromStopIndex); float DistanceFromFirst (const std::string &ToStopIdStr); private : bool GetStopIndexByIdStr(unsigned int *StopIndexPtr, const std::string &StopIdStr); std::vector<TripDiagramStopDistanceInfoType> DistanceArray; #undef Self }; typedef std::vector<TripDiagramTimeTableItemType> TripDiagramTimeTableItemStoreVectorType; extern unsigned int TripDiagramTourIndexById (TourTourSetPtrClass TourSetPtr, AnsiString TourIdStr); extern bool TripDiagramTourIsACopy (TourTourSetPtrClass TourSetPtr, unsigned int TourIndex); extern bool TripDiagramTourCopyAttributes (TourTourSetPtrClass TourSetPtr, unsigned int TourIndex, AnsiString &TourIdStrRef, AnsiString &TourFirstNameStrRef, AnsiString &TourSecondNameStrRef); extern bool TripDiagramMoveTour (TourTourSchedulePtrClass TourSchedulePtr, TDateTime DateTimeValue); extern bool TripDiagramReflectTour (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr); extern TourTourPtrClass TripDiagramAppendTour (TourDataPtrClass TourDataPtr, AnsiString NewTourIdStr); extern void TripDiagramFillTour (TourTourPtrClass DestTourPtr, TourTourPtrClass SrcTourPtr); extern bool TripDiagramInvertTour (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr); extern bool TripDiagramPrepareToReflectTour (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr); extern bool TripDiagramCanReflectTour (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr); float TripDiagramTourStepSpeed (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr, unsigned int StepIndex); float TripDiagramTourStepDistance (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr, unsigned int StepIndex); extern bool TripDiagramNextStopPreliminaryTimeIn (TourTourSchedulePtrClass TourSchedulePtr, TourTopologyPtrClass TopologyPtr, unsigned int StopIndex, float SpeedValue, unsigned short &HoursRef, unsigned short &MinutesRef); class TTourTripDiagramForm; class TTourTripDiagramCanvasEventHandlerClass : public VCanvasEventHandlerClass { #define Self TTourTripDiagramCanvasEventHandlerClass public : Self (TTourTripDiagramForm *FormPtr); virtual void OnClick (VCanvasHandleType ItemHandle, unsigned int ButtonCode, int PosX, int PosY); private : TTourTripDiagramForm *FormPtr; #undef Self }; typedef struct { bool VisibleFlag; VCanvasColorType Color; VCanvasPenType PenStyle; } TripDiagramTourViewType; class TTourTripDiagramForm : public TForm { friend class TTourTripDiagramCanvasEventHandlerClass; __published: // IDE-managed Components TScrollBox *ChartScrollBox; TPanel *EditPanel; TFormStorage *FormStorage; TImageList *FakeImageList; TPopupMenu *ChartPopupMenu; TMenuItem *ScalePopupMenuItem; TMenuItem *Scale25PrcPopupMenuItem; TMenuItem *Scale50PrcPopupMenuItem; TMenuItem *Scale75PrcPopupMenuItem; TMenuItem *Scale100PrcPopupMenuItem; TMenuItem *Scale150PrcPopupMenuItem; TMenuItem *Scale200PrcPopupMenuItem; TPaintBox *ChartPaintBox; TMenuItem *ShowGridPopupMenuItem; TMenuItem *ShowForwardToursPopupMenuItem; TMenuItem *ShowBackwardToursPopupMenuItem; TMenuItem *OptionsDialogPopupMenuItem; TListView *TourListView; TListView *TimetableListView; TMenuItem *MonoColorToursPopupMenuItem; TMenuItem *PrintPopupMenuItem; TMenuItem *PrintTourInfoPopupMenuItem; TMenuItem *PrintStopPopupMenuItem; TMenuItem *Scale500PrcPopupMenuItem; TMenuItem *PrintDiagramPopupMenuItem; TSplitter *GroupToTimetableSplitter; TSplitter *HorizSplitter; TMenuItem *PrintDiagramFullPopupMenuItem; TMenuItem *ScaleFitToHeightPrcPopupMenuItem; TPopupMenu *TourListViewPopupMenu; TMenuItem *TourMoveMenuItem; TActionList *TourListViewActionList; TAction *TourMoveAction; TAction *TourInvertAction; TAction *TourCopyAction; TMenuItem *TourInvertMenuItem; TMenuItem *TourCopyMenuItem; TVStringStorage *VStringStorage; TAction *TourDeleteAction; TMenuItem *TourDeleteMenuItem; TMenuItem *ShowTourInOutRowPopupMenuItem; TPanel *InfoPanel; TSplitter *TimetableToHintSplitter; TPanel *Panel1; TLabel *BusModelLabel; TLabel *BusModelValueLabel; TLabel *BusCapacityLabel; TLabel *BusCapacityValueLabel; TLabel *TripPathLengthLabel; TLabel *TripPathLengthValueLabel; TLabel *TripPathTimeLabel; TLabel *TripPathTimeValueLabel; TPanel *HintPanel; TLabel *HintTimeLabel; TLabel *HintTimeValueLabel; TLabel *HintFromLabel; TLabel *HintToLabel; TLabel *HintFromValueLabel; TLabel *HintToValueLabel; TPanel *ButtonsPanel; TButton *OkButton; TButton *CancelButton; void __fastcall FormClose (TObject *Sender, TCloseAction &Action); void __fastcall ChartPaintBoxPaint (TObject *Sender); void __fastcall FormCreate (TObject *Sender); void __fastcall TourListViewSelectItem (TObject *Sender, TListItem *Item, bool Selected); void __fastcall TourListViewCustomDrawItem(TCustomListView *Sender,TListItem *Item, TCustomDrawState State, bool &DefaultDraw); void __fastcall ChartPaintBoxMouseDown(TObject *Sender,TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Scale25PrcPopupMenuItemClick(TObject *Sender); void __fastcall Scale50PrcPopupMenuItemClick(TObject *Sender); void __fastcall Scale75PrcPopupMenuItemClick(TObject *Sender); void __fastcall Scale100PrcPopupMenuItemClick(TObject *Sender); void __fastcall Scale150PrcPopupMenuItemClick(TObject *Sender); void __fastcall Scale200PrcPopupMenuItemClick(TObject *Sender); void __fastcall ShowGridPopupMenuItemClick(TObject *Sender); void __fastcall ShowForwardToursPopupMenuItemClick(TObject *Sender); void __fastcall ShowBackwardToursPopupMenuItemClick(TObject *Sender); void __fastcall OptionsDialogPopupMenuItemClick(TObject *Sender); void __fastcall ChartPaintBoxMouseMove(TObject *Sender,TShiftState Shift, int X, int Y); void __fastcall ChartPaintBoxMouseUp(TObject *Sender,TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall MonoColorToursPopupMenuItemClick(TObject *Sender); void __fastcall PrintTourInfoPopupMenuItemClick(TObject *Sender); void __fastcall PrintStopPopupMenuItemClick(TObject *Sender); void __fastcall Scale500PrcPopupMenuItemClick(TObject *Sender); void __fastcall PrintDiagramPopupMenuItemClick(TObject *Sender); void __fastcall TourListViewChange(TObject *Sender, TListItem *Item, TItemChange Change); void __fastcall TourListViewDblClick(TObject *Sender); void __fastcall TimetableListViewDblClick(TObject *Sender); void __fastcall PrintDiagramFullPopupMenuItemClick(TObject *Sender); void __fastcall ScaleFitToHeightPrcPopupMenuItemClick(TObject *Sender); void __fastcall ScaleFitToWidthPrcPopupMenuItemClick(TObject *Sender); void __fastcall TourListViewColumnClick(TObject *Sender, TListColumn *Column); void __fastcall TourListViewCompare(TObject *Sender, TListItem *Item1, TListItem *Item2, int Data, int &Compare); void __fastcall TourMoveActionExecute(TObject *Sender); void __fastcall TourInvertActionExecute(TObject *Sender); void __fastcall TourCopyActionExecute(TObject *Sender); void __fastcall CancelButtonClick(TObject *Sender); void __fastcall OkButtonClick(TObject *Sender); void __fastcall TourDeleteActionExecute(TObject *Sender); void __fastcall ShowTourInOutRowPopupMenuItemClick( TObject *Sender); private: // User declarations TTourTripDiagramCanvasEventHandlerClass CanvasEventHandler; unsigned int SelectedTourIndex; unsigned int BaseStopIndex; // Notify methods - call them if something changed in diagram state void NotifySelectedTourChanged (void); void NotifySelectedTourScheduleChanged (void); void NotifyBaseStopChanged (void); // Chart state methods void SetViewScale (float Scale); void ShowForwardTours (void); void ShowBackwardTours (void); void HideForwardTours (void); void HideBackwardTours (void); void HideTour (unsigned int TourIndex); void ShowTour (unsigned int TourIndex); bool MoveTour (unsigned int TourIndex, TDateTime DateTimeValue); TourTourPtrClass DublicateTour (unsigned int TourIndex, AnsiString NewTourIdStr, AnsiString NewTourNameStr); bool IsTourVisible (unsigned int TourIndex); bool IsTourForward (unsigned int TourIndex); // Call this method if any of the tour data has been changed void UpdateChart (void); void DrawToRow (int PosX, int PosY, bool UpFlag); void DrawFromRow (int PosX, int PosY, bool UpFlag); // Loading data from database methods void LoadDBData (const std::vector<std::string> &StopIdStrArray, const AnsiString &BaseTourIdStr); /* void LoadStopInfoDBData (TripDiagramStopInfoType &TargetStopInfo, const AnsiString &StopIdStr); */ void UpdateColorTable (void); void RecalcTimeScale (void); void ScrollToTour (unsigned int TourIndex); VCanvasClass ChartCanvas; // Chart support functions int TimeToPixels (float Time); int DistanceToPixels (float Distance); // Convert metods // TOFIX: Параметр TourIndex или TourPtr избыточен, пока это необходимо // для повышения быстродействия (после реализации кэша необходимо удалить // параметр TourPtr) // TourListView methods bool TourListViewTourAppend (unsigned int TourIndex, TourTourPtrClass TourPtr); bool FillTourListView (void); void FreeTourListView (void); void UpdateTourListBaseOutTime (void); TListItem *TourListViewItemByData (unsigned int DataValue); // bool FillTourListViewStateFlag; int TourListViewColumnToSort; bool TourListSortLockFlag; // TimetableListView methods bool FillTimetableListView (unsigned int TourIndex); // Tour info metods float TourStepSpeed (TourTourSchedulePtrClass TourPtr, unsigned int StepIndex); AnsiString TourStepSpeedStr (TourTourSchedulePtrClass TourPtr, unsigned int StepIndex); float TourStepDistance (TourTourSchedulePtrClass TourPtr, unsigned int StepIndex); AnsiString TourStepDistanceStr (TourTourSchedulePtrClass TourPtr, unsigned int StepIndex); AnsiString GetTourListTourCaptionStr (TourTourPtrClass TourPtr); AnsiString GetTourListTourAverageSpeedStr (TourTourPtrClass TourPtr); AnsiString GetTourListTourTotalDistanceStr (TourTourPtrClass TourPtr); AnsiString GetTourListTourBaseInTimeStr (TourTourSchedulePtrClass TourSchedulePtr); AnsiString GetTourListTourBaseOutTimeStr (TourTourSchedulePtrClass TourSchedulePtr); void ApplyChanges (void); void CancelChanges (void); // User actions (visualisation) bool TourSelectDialogExec (void); // User actions (functionality) bool TourTimetableDialogExec (unsigned int TourIndex); bool TourCopyDialogExec (unsigned int TourIndex, TourTourPtrClass &TourPtrRef, bool InvertTourNameFlag); bool GetTourCopyAttributes (unsigned int TourIndex, AnsiString &TourIdStrRef, AnsiString &TourFirstNameStrRef, AnsiString &TourSecondNameStrRef); // Chart parameters float TimeBaseScale; // Pixels/Hour for ViewScale = 1 float DistanceBaseScale; // Pixel/Km for ViewScale = 1 float TimeViewScale; // Scale = 1 is 100% (24 hours fills X axis) float DistanceViewScale; // Scale = 1 is 100% (Max distance fills Y axis) float BaseSpeed; unsigned int BaseSpeedAngle; bool ShowDistanceGridFlag; bool ShowTimeGridFlag; bool ShowForwardToursFlag; bool ShowBackwardToursFlag; bool ShowTourInOutRowsFlag; bool MonoColorTourModeFlag; unsigned int StopNameMaxWidth; bool ZeroWaitTimeCircleModeFlag; VCanvasColorType ChartGridColor; VCanvasColorType ChartCommonTourColor; VCanvasColorType ChartSelectedTourColor; // MouseState parameters int LastMousePosX; int LastMousePosY; bool ButtonLeftPressedFlag; int CompareDouble (AnsiString FirstValueStr, AnsiString SecondValueStr); int CompareTime (AnsiString Time1ValueStr, AnsiString Time2ValueStr); TourDataPtrClass DataStoragePtr; TourDataPtrClass ChartDataStoragePtr; TourCachedUpdateDataClass *CachedUpdateDataStoragePtr; std::vector<TripDiagramTourViewType> TourViewInfoArray; TripDiagramStopDistanceCacheClass DistanceCache; public: // User declarations bool InfoPanelUpdate(); __fastcall TTourTripDiagramForm (TComponent *Owner); __fastcall TTourTripDiagramForm (TComponent *Owner, const std::vector<std::string> &StopIdStrArray, AnsiString BaseTourIdStr = ""); }; //--------------------------------------------------------------------------- extern PACKAGE TTourTripDiagramForm *TourTripDiagramForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 511 ] ] ]
234f90464a1e00c2229306ab3f65a409d30c9327
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/q3_ui/ui_confirm.cpp
9eebc992a91f8016d8def1f5172b37c44a8def23
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
7,171
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // /* ======================================================================= CONFIRMATION MENU ======================================================================= */ #include"ui_pch.h" #define ART_CONFIRM_FRAME "menu/art/cut_frame" #define ID_CONFIRM_NO 10 #define ID_CONFIRM_YES 11 typedef struct { menuframework_s menu; menutext_s no; menutext_s yes; int slashX; const char * question; void (*draw)( void ); void (*action)( qboolean result ); int style; const char **lines; } confirmMenu_t; static confirmMenu_t s_confirm; /* ================= ConfirmMenu_Event ================= */ static void ConfirmMenu_Event( void* ptr, int event ) { qboolean result; if( event != QM_ACTIVATED ) { return; } UI_PopMenu(); if( ((menucommon_s*)ptr)->id == ID_CONFIRM_NO ) { result = qfalse; } else { result = qtrue; } if( s_confirm.action ) { s_confirm.action( result ); } } /* ================= ConfirmMenu_Key ================= */ static sfxHandle_t ConfirmMenu_Key( int key ) { switch ( key ) { case K_KP_LEFTARROW: case K_LEFTARROW: case K_KP_RIGHTARROW: case K_RIGHTARROW: key = K_TAB; break; case 'n': case 'N': ConfirmMenu_Event( &s_confirm.no, QM_ACTIVATED ); break; case 'y': case 'Y': ConfirmMenu_Event( &s_confirm.yes, QM_ACTIVATED ); break; } return Menu_DefaultKey( &s_confirm.menu, key ); } /* ================= MessaheMenu_Draw ================= */ static void MessageMenu_Draw( void ) { int i,y; UI_DrawNamedPic( GFIXED(142,0), GFIXED(118,0), GFIXED(359,0), GFIXED(256,0), ART_CONFIRM_FRAME ); y = 188; for(i=0; s_confirm.lines[i]; i++) { UI_DrawProportionalString( 320, y, s_confirm.lines[i], s_confirm.style, color_red ); y += 18; } Menu_Draw( &s_confirm.menu ); if( s_confirm.draw ) { s_confirm.draw(); } } /* ================= ConfirmMenu_Draw ================= */ static void ConfirmMenu_Draw( void ) { UI_DrawNamedPic( GFIXED(142,0), GFIXED(118,0), GFIXED(359,0), GFIXED(256,0), ART_CONFIRM_FRAME ); UI_DrawProportionalString( 320, 204, s_confirm.question, s_confirm.style, color_red ); UI_DrawProportionalString( s_confirm.slashX, 265, "/", UI_LEFT|UI_INVERSE, color_red ); Menu_Draw( &s_confirm.menu ); if( s_confirm.draw ) { s_confirm.draw(); } } /* ================= ConfirmMenu_Cache ================= */ void ConfirmMenu_Cache( void ) { _UI_trap_R_RegisterShaderNoMip( ART_CONFIRM_FRAME ); } /* ================= UI_ConfirmMenu_Stlye ================= */ void UI_ConfirmMenu_Style( const char *question, int style, void (*draw)( void ), void (*action)( qboolean result ) ) { uiClientState_t cstate; int n1, n2, n3; int l1, l2, l3; // zero set all our globals memset( &s_confirm, 0, sizeof(s_confirm) ); ConfirmMenu_Cache(); n1 = UI_ProportionalStringWidth( "YES/NO" ); n2 = UI_ProportionalStringWidth( "YES" ) + PROP_GAP_WIDTH; n3 = UI_ProportionalStringWidth( "/" ) + PROP_GAP_WIDTH; l1 = 320 - ( n1 / 2 ); l2 = l1 + n2; l3 = l2 + n3; s_confirm.slashX = l2; s_confirm.question = question; s_confirm.draw = draw; s_confirm.action = action; s_confirm.style = style; s_confirm.menu.draw = ConfirmMenu_Draw; s_confirm.menu.key = ConfirmMenu_Key; s_confirm.menu.wrapAround = qtrue; _UI_trap_GetClientState( &cstate ); if ( cstate.connState >= CA_CONNECTED ) { s_confirm.menu.fullscreen = qfalse; } else { s_confirm.menu.fullscreen = qtrue; } s_confirm.yes.generic.type = MTYPE_PTEXT; s_confirm.yes.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; s_confirm.yes.generic.callback = ConfirmMenu_Event; s_confirm.yes.generic.id = ID_CONFIRM_YES; s_confirm.yes.generic.x = l1; s_confirm.yes.generic.y = 264; s_confirm.yes.string = strdup("YES"); s_confirm.yes.color = color_red; s_confirm.yes.style = UI_LEFT; s_confirm.no.generic.type = MTYPE_PTEXT; s_confirm.no.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; s_confirm.no.generic.callback = ConfirmMenu_Event; s_confirm.no.generic.id = ID_CONFIRM_NO; s_confirm.no.generic.x = l3; s_confirm.no.generic.y = 264; s_confirm.no.string = strdup("NO"); s_confirm.no.color = color_red; s_confirm.no.style = UI_LEFT; Menu_AddItem( &s_confirm.menu, &s_confirm.yes ); Menu_AddItem( &s_confirm.menu, &s_confirm.no ); UI_PushMenu( &s_confirm.menu ); Menu_SetCursorToItem( &s_confirm.menu, &s_confirm.no ); } /* ================= UI_ConfirmMenu ================= */ void UI_ConfirmMenu( const char *question, void (*draw)( void ), void (*action)( qboolean result ) ) { UI_ConfirmMenu_Style(question, UI_CENTER|UI_INVERSE, draw, action); } /* ================= UI_Message hacked over from Confirm stuff ================= */ void UI_Message( const char **lines ) { uiClientState_t cstate; int n1, l1; // zero set all our globals memset( &s_confirm, 0, sizeof(s_confirm) ); ConfirmMenu_Cache(); n1 = UI_ProportionalStringWidth( "OK" ); l1 = 320 - ( n1 / 2 ); s_confirm.lines = lines; s_confirm.style = UI_CENTER|UI_INVERSE|UI_SMALLFONT; s_confirm.menu.draw = MessageMenu_Draw; s_confirm.menu.key = ConfirmMenu_Key; s_confirm.menu.wrapAround = qtrue; _UI_trap_GetClientState( &cstate ); if ( cstate.connState >= CA_CONNECTED ) { s_confirm.menu.fullscreen = qfalse; } else { s_confirm.menu.fullscreen = qtrue; } s_confirm.yes.generic.type = MTYPE_PTEXT; s_confirm.yes.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; s_confirm.yes.generic.callback = ConfirmMenu_Event; s_confirm.yes.generic.id = ID_CONFIRM_YES; s_confirm.yes.generic.x = l1; s_confirm.yes.generic.y = 280; s_confirm.yes.string = strdup("OK"); s_confirm.yes.color = color_red; s_confirm.yes.style = UI_LEFT; Menu_AddItem( &s_confirm.menu, &s_confirm.yes ); UI_PushMenu( &s_confirm.menu ); Menu_SetCursorToItem( &s_confirm.menu, &s_confirm.yes ); }
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac", "crioux@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 213 ], [ 215, 223 ], [ 225, 283 ], [ 285, 293 ] ], [ [ 214, 214 ], [ 224, 224 ], [ 284, 284 ] ] ]
04abcd9ac3d1207bd3d7439e7f8f50e9aab947e8
2b80036db6f86012afcc7bc55431355fc3234058
/src/win32cpp/FolderBrowseDialog.hpp
38c4d27ff2345360bb96cd09c72231f360998191
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,618
hpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2007, Casey Langen // // Sources and Binaries of: win32cpp // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <win32cpp/Win32Config.hpp> #include <win32cpp/Window.hpp> ////////////////////////////////////////////////////////////////////////////// namespace win32cpp { ////////////////////////////////////////////////////////////////////////////// class FolderBrowseDialog { public: // types enum Result { ResultOK = 0, ResultCanceled }; public: // ctor FolderBrowseDialog(); public: // methods Result Show(Window* owner = NULL, const uichar* initialPath = NULL); uistring Directory(); private: // instance data uistring directory; }; ////////////////////////////////////////////////////////////////////////////// } // win32cpp
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 72 ] ] ]
91c52f6f2b44b8511c0f3ac56cce4487da7fe6d8
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdcpp/apps/BCCppWrap/src/BCCppWrap.cpp
b004149669e429454a85cd0990aa127ae7573d91
[]
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
5,499
cpp
/* * Copyright (c) 2008-2009 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: * */ // INCLUDE FILES #include <Stiftestinterface.h> #include "BCCppWrap.h" #include <SettingServerClient.h> // EXTERNAL DATA STRUCTURES //extern ?external_data; // EXTERNAL FUNCTION PROTOTYPES //extern ?external_function( ?arg_type,?arg_type ); // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def // LOCAL CONSTANTS AND MACROS //const ?type ?constant_var = ?constant; //#define ?macro_name ?macro_def // MODULE DATA STRUCTURES //enum ?declaration //typedef ?declaration // LOCAL FUNCTION PROTOTYPES //?type ?function_name( ?arg_type, ?arg_type ); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; // ============================= LOCAL FUNCTIONS =============================== // ----------------------------------------------------------------------------- // ?function_name ?description. // ?description // Returns: ?value_1: ?description // ?value_n: ?description_line1 // ?description_line2 // ----------------------------------------------------------------------------- // /* ?type ?function_name( ?arg_type arg, // ?description ?arg_type arg) // ?description { ?code // ?comment // ?comment ?code } */ // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CBCCppWrap::CBCCppWrap // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CBCCppWrap::CBCCppWrap( CTestModuleIf& aTestModuleIf ): CScriptBase( aTestModuleIf ) { } // ----------------------------------------------------------------------------- // CBCCppWrap::ConstructL // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CBCCppWrap::ConstructL() { //Read logger settings to check whether test case name is to be //appended to log file name. RSettingServer settingServer; TInt ret = settingServer.Connect(); if(ret != KErrNone) { User::Leave(ret); } // Struct to StifLogger settigs. TLoggerSettings loggerSettings; // Parse StifLogger defaults from STIF initialization file. ret = settingServer.GetLoggerSettings(loggerSettings); if(ret != KErrNone) { User::Leave(ret); } // Close Setting server session settingServer.Close(); TFileName logFileName; if(loggerSettings.iAddTestCaseTitle) { TName title; TestModuleIf().GetTestCaseTitleL(title); logFileName.Format(KBCCppWrapLogFileWithTitle, &title); } else { logFileName.Copy(KBCCppWrapLogFile); } iLog = CStifLogger::NewL( KBCCppWrapLogPath, logFileName, CStifLogger::ETxt, CStifLogger::EFile, EFalse ); SendTestClassVersion(); } // ----------------------------------------------------------------------------- // CBCCppWrap::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CBCCppWrap* CBCCppWrap::NewL( CTestModuleIf& aTestModuleIf ) { CBCCppWrap* self = new (ELeave) CBCCppWrap( aTestModuleIf ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop(); return self; } // Destructor CBCCppWrap::~CBCCppWrap() { // Delete resources allocated from test methods Delete(); // Delete logger delete iLog; } //----------------------------------------------------------------------------- // CBCCppWrap::SendTestClassVersion // Method used to send version of test class //----------------------------------------------------------------------------- // void CBCCppWrap::SendTestClassVersion() { TVersion moduleVersion; moduleVersion.iMajor = TEST_CLASS_VERSION_MAJOR; moduleVersion.iMinor = TEST_CLASS_VERSION_MINOR; moduleVersion.iBuild = TEST_CLASS_VERSION_BUILD; TFileName moduleName; moduleName = _L("BCCppWrap.dll"); TestModuleIf().SendTestModuleVersion(moduleVersion, moduleName); } // ========================== OTHER EXPORTED FUNCTIONS ========================= // ----------------------------------------------------------------------------- // LibEntryL is a polymorphic Dll entry point. // Returns: CScriptBase: New CScriptBase derived object // ----------------------------------------------------------------------------- // EXPORT_C CScriptBase* LibEntryL( CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework { return ( CScriptBase* ) CBCCppWrap::NewL( aTestModuleIf ); } // End of File
[ "none@none" ]
[ [ [ 1, 198 ] ] ]
7cc52cf1286fe8b6966e1f4b188302c8e4db3e61
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十五章 面向对象编程/20090308_习题15.22_重新定义Bulk_item类和Lds_item类.cpp
933da69caeb076dd6d56a634c0bed039e20b43e3
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
class Bulk_item : public Disc_item { public: Bulk_item(const std::string& book = "", double sales_price = 0.0, size_t qty = 0, double disc_rate = 0.0): Disc_item(book, sales_price, qty, disc_rate) {} double net_price(size_t cnt) const { if (cnt >= quantity) return cnt * (1 - discount) * price; else return cnt * price; } }; class Lds_item : public Disc_item { public: Lds_item(const std::string& book = "", double sales_price = 0.0, size_t qty = 0, double disc_rate = 0.0): Disc_item(book, sales_price, qty, disc_rate) {} double net_price(size_t cnt) const { if (cnt <= quantity) return cnt * (1 - discount) * price; else return cnt * price - quantity * discount * price; } };
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 31 ] ] ]
4672ef2e796e5ccc2357d28f61744333fd08b5fc
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/AIPI_Engine/Aipi_RETE_Operations.h
8f64aabe89ce6ca9c9dcbc381aa37202fd8d899a
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,096
h
// Aipi_RETE_Operations.h: interface for the CAipi_RETE_Operations class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_AIPI_RETE_OPERATIONS_H__BAC9821A_1B0C_4A2D_91D6_DC2947E85019__INCLUDED_) #define AFX_AIPI_RETE_OPERATIONS_H__BAC9821A_1B0C_4A2D_91D6_DC2947E85019__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 /* /// Operations (RETE Operations) /// This is a helper class that saves information for numeric operations. It will be helpfull to check consistent between attibutes data types in the debbuging process. *** Symbols *** LeftVar = Variable that is left from the operator RightVar= Variable that is right form the operator AttrType= The identifier type ( int ,long string etc...) AM = Alpha Memory BM = Beta Memory WM = Working Memory PM = Production Memory Cond = Condition I = Identifier (Id) A = Atribute (Attr) V = Value (Val) e = Don`t care *** Function Parameters *** am = Alpha Memory bm = Beta Memory wm = Working Memory pm = Production Memory lhs = Left Hand Side Function cond = Condition */ class CAipi_RETE_Operations { public: CAipi_RETE_Operations(); virtual ~CAipi_RETE_Operations(); inline CAipi_RETE_Operations(int c, tstring v1, tstring v2, int type1, int type2, int rel) { m_Cond = c; m_LeftVar = v1; m_RightVar = v2; m_LeftType = type1; m_RightType = type2; m_Rel = rel; } inline void CAipi_RETE_Operations::setCond(int c) { m_Cond = c; } inline void CAipi_RETE_Operations::setLeftVar(tstring v1) { m_LeftVar = v1; } inline void CAipi_RETE_Operations::setRightVar(tstring v2) { m_RightVar = v2; } inline void CAipi_RETE_Operations::setLeftType(int type1) { m_LeftType = type1; } inline void CAipi_RETE_Operations::setRightType(int type2) { m_RightType = type2; } inline void CAipi_RETE_Operations::setRel(int rel) { m_Rel = rel;; } inline int CAipi_RETE_Operations::getCond() { return m_Cond; } inline tstring CAipi_RETE_Operations::getLeftVar() { return m_LeftVar; } inline tstring CAipi_RETE_Operations::getRightVar() { return m_RightVar; } inline int CAipi_RETE_Operations::getLeftType() { return m_LeftType; } inline int CAipi_RETE_Operations::getRightType() { return m_RightType; } inline int CAipi_RETE_Operations::getRel() { return m_Rel; } public: CAipi_RETE_Operations* CAipi_RETE_Operations::addOperation(int pm, int c, tstring v1, tstring v2, int type1, int type2, int rel); void clearOperation(); void addAttr_Type(tstring attr, int type); void clearAttrType(); int findAttr_Type(tstring attr); void printOperation(); void printAttr_Type(); public: int m_Cond; int m_LeftType; int m_RightType; int m_Rel; tstring m_LeftVar; tstring m_RightVar; }; #endif // !defined(AFX_AIPI_RETE_OPERATIONS_H__BAC9821A_1B0C_4A2D_91D6_DC2947E85019__INCLUDED_)
[ [ [ 1, 148 ] ] ]
117cc26a1dea27fa93f63e727a6eafd280077429
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/ic2005demo/nanobots/src/demo/GameInfo.cpp
b3342bca283858ac56042252a3004c6acac6e19f
[]
no_license
BackupTheBerlios/dingus-svn
331d7546a6e7a5a3cb38ffb106e57b224efbf5df
1223efcf4c2079f58860d7fa685fa5ded8f24f32
refs/heads/master
2016-09-05T22:15:57.658243
2006-09-02T10:10:47
2006-09-02T10:10:47
40,673,143
0
0
null
null
null
null
UTF-8
C++
false
false
3,084
cpp
#include "stdafx.h" #include "GameInfo.h" #include "map/GameMap.h" #include "map/LevelMesh.h" #include "map/PointsMesh.h" #include "game/GameReplay.h" #include "game/ReplayReader.h" #include "entity/EntityManager.h" #include "MinimapRenderer.h" #include "EntityInfoRenderer.h" std::string gErrorMsg = ""; // -------------------------------------------------------------------------- // singleton CGameInfo* CGameInfo::mSingleInstance = 0; void CGameInfo::initialize( const char* replayFile ) { assert( !mSingleInstance ); mSingleInstance = new CGameInfo( replayFile ); } void CGameInfo::finalize() { assert( mSingleInstance ); delete mSingleInstance; } // -------------------------------------------------------------------------- // multi-step initialization const char* CGameInfo::initBegin() { return "Loading replay..."; gErrorMsg = ""; } const char* CGameInfo::initStep() { gErrorMsg = ""; // load replay? if( !mReplay ) { mReplay = new CGameReplay(); bool ok = gReadReplay( ("replays/" + mReplayFile).c_str(), *mReplay ); if( !ok ) { gErrorMsg = "Error loading replay '" + mReplayFile + "'"; return NULL; } return "Loading game map..."; } assert( mReplay ); // load game map? if( !mGameMap ) { mGameMap = new CGameMap(); std::string errMsg = mGameMap->initialize( "tissues/" + mReplay->getGameMapName(), mReplay->getGameMapName() ); if( !errMsg.empty() ) { gErrorMsg = "Error loading game map: " + errMsg; return NULL; } return "Calculating level mesh..."; } assert( mGameMap ); // calculate level mesh? if( !mLevelMesh ) { // TBD: error processing mLevelMesh = new CLevelMesh( *mGameMap ); return "Initializing level points mesh..."; } assert( mLevelMesh ); // calculate level points mesh? if( !mPointsMesh ) { // TBD: error processing mPointsMesh = new CPointsMesh( *mGameMap, *mLevelMesh ); return "Creating renderers..."; } assert( mPointsMesh ); // create renderers? if( !mMinimapRenderer ) { mMinimapRenderer = new CMinimapRenderer( *RGET_IB(RID_IB_QUADS) ); mEntityBlobsRenderer = new CMinimapRenderer( *RGET_IB(RID_IB_QUADS) ); mEntityInfoRenderer = new CEntityInfoRenderer( *RGET_IB(RID_IB_QUADS) ); return "Creating entities..."; } // create entity manager? if( !mEntities ) { mEntities = new CEntityManager(); return NULL; // all done! } assert( false ); // shouldn't get here... return NULL; } CGameInfo::CGameInfo( const char* replayFile ) : mTime( 0.0f ), mReplay(NULL), mGameMap(NULL), mLevelMesh(NULL), mPointsMesh(NULL), mMinimapRenderer(NULL), mEntityBlobsRenderer(NULL), mEntityInfoRenderer(NULL), mEntities(NULL) { mReplayFile = replayFile; } CGameInfo::~CGameInfo() { safeDelete( mEntities ); safeDelete( mMinimapRenderer ); safeDelete( mEntityBlobsRenderer ); safeDelete( mEntityInfoRenderer ); safeDelete( mPointsMesh ); safeDelete( mLevelMesh ); safeDelete( mReplay ); safeDelete( mGameMap ); }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 130 ] ] ]
9f5a02e50a8f1115432f2652532d667fdb929e9a
3182b05c41f13237825f1ee59d7a0eba09632cd5
/renderInstance/renderTranslucentMgr.cpp
4b047b02a6f26cea2539a2e6055ed29bf3378a59
[]
no_license
adhistac/ee-client-2-0
856e8e6ce84bfba32ddd8b790115956a763eec96
d225fc835fa13cb51c3e0655cb025eba24a8cdac
refs/heads/master
2021-01-17T17:13:48.618988
2010-01-04T17:35:12
2010-01-04T17:35:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,548
cpp
//----------------------------------------------------------------------------- // Torque 3D // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "renderInstance/renderTranslucentMgr.h" #include "materials/sceneData.h" #include "sceneGraph/sceneGraph.h" #include "sceneGraph/sceneObject.h" #include "sceneGraph/sceneState.h" #include "materials/matInstance.h" #include "gfx/gfxPrimitiveBuffer.h" #include "gfx/gfxTransformSaver.h" #include "gfx/gfxDebugEvent.h" #include "renderInstance/renderParticleMgr.h" #include "math/util/matrixSet.h" #define HIGH_NUM ((U32(-1)/2) - 1) IMPLEMENT_CONOBJECT(RenderTranslucentMgr); RenderTranslucentMgr::RenderTranslucentMgr() : RenderBinManager( RenderPassManager::RIT_Custom, 1.0f, 1.0f ), mParticleRenderMgr(NULL) { } RenderTranslucentMgr::~RenderTranslucentMgr() { } void RenderTranslucentMgr::setupSGData(MeshRenderInst *ri, SceneGraphData &data ) { Parent::setupSGData(ri, data); data.backBuffTex = NULL; data.cubemap = NULL; data.lightmap = NULL; } RenderBinManager::AddInstResult RenderTranslucentMgr::addElement( RenderInst *inst ) { // See if we support this instance type. if ( inst->type != RenderPassManager::RIT_ObjectTranslucent && inst->type != RenderPassManager::RIT_Translucent && inst->type != RenderPassManager::RIT_Particle) return RenderBinManager::arSkipped; // See if this instance is translucent. if (!inst->translucentSort) return RenderBinManager::arSkipped; BaseMatInstance* matInst = getMaterial(inst); bool translucent = (!matInst || matInst->getMaterial()->isTranslucent()); if (!translucent) return RenderBinManager::arSkipped; // We made it this far, add the instance. mElementList.increment(); MainSortElem& elem = mElementList.last(); elem.inst = inst; // Override the instances default key to be the sort distance. All // the pointer dereferencing is in there to prevent us from losing // information when converting to a U32. elem.key = *((U32*)&inst->sortDistSq); AssertFatal( inst->defaultKey != 0, "RenderTranslucentMgr::addElement() - Got null sort key... did you forget to set it?" ); // Then use the instances primary key as our secondary key elem.key2 = inst->defaultKey; // We are the only thing to handle translucent "things" right now. return RenderBinManager::arStop; } GFXStateBlockRef RenderTranslucentMgr::_getStateBlock( U8 transFlag ) { if ( mStateBlocks[transFlag].isValid() ) return mStateBlocks[transFlag]; GFXStateBlockDesc d; d.cullDefined = true; d.cullMode = GFXCullNone; d.blendDefined = true; d.blendEnable = true; d.blendSrc = (GFXBlend)((transFlag >> 4) & 0x0f); d.blendDest = (GFXBlend)(transFlag & 0x0f); d.alphaDefined = true; // See http://www.garagegames.com/mg/forums/result.thread.php?qt=81397 d.alphaTestEnable = (d.blendSrc == GFXBlendSrcAlpha && (d.blendDest == GFXBlendInvSrcAlpha || d.blendDest == GFXBlendOne)); d.alphaTestRef = 1; d.alphaTestFunc = GFXCmpGreaterEqual; d.zDefined = true; d.zWriteEnable = false; d.samplersDefined = true; d.samplers[0] = GFXSamplerStateDesc::getClampLinear(); d.samplers[0].alphaOp = GFXTOPModulate; d.samplers[0].alphaArg1 = GFXTATexture; d.samplers[0].alphaArg2 = GFXTADiffuse; mStateBlocks[transFlag] = GFX->createStateBlock(d); return mStateBlocks[transFlag]; } void RenderTranslucentMgr::render( SceneState *state ) { PROFILE_SCOPE(RenderTranslucentMgr_render); // Early out if nothing to draw. if(!mElementList.size()) return; GFXDEBUGEVENT_SCOPE(RenderTranslucentMgr_Render, ColorI::BLUE); // Find the particle render manager (if we don't have it) if(mParticleRenderMgr == NULL) { RenderPassManager *rpm = state->getRenderPass(); for( U32 i = 0; i < rpm->getManagerCount(); i++ ) { RenderBinManager *bin = rpm->getManager(i); if( bin->getRenderInstType() == RenderParticleMgr::RIT_Particles ) { mParticleRenderMgr = reinterpret_cast<RenderParticleMgr *>(bin); break; } } } GFXTransformSaver saver; SceneGraphData sgData; GFXVertexBuffer * lastVB = NULL; GFXPrimitiveBuffer * lastPB = NULL; // Restore transforms MatrixSet &matrixSet = getParentManager()->getMatrixSet(); matrixSet.restoreSceneViewProjection(); U32 binSize = mElementList.size(); for( U32 j=0; j<binSize; ) { RenderInst *baseRI = mElementList[j].inst; U32 matListEnd = j; // render these separately... if ( baseRI->type == RenderPassManager::RIT_ObjectTranslucent ) { ObjectRenderInst* objRI = static_cast<ObjectRenderInst*>(baseRI); objRI->renderDelegate( objRI, state, NULL ); lastVB = NULL; lastPB = NULL; j++; continue; } else if ( baseRI->type == RenderPassManager::RIT_Particle ) { ParticleRenderInst *ri = static_cast<ParticleRenderInst*>(baseRI); // Tell Particle RM to draw the system. (This allows the particle render manager // to manage drawing offscreen particle systems, and allows the systems // to be composited back into the scene with proper translucent // sorting order) mParticleRenderMgr->renderInstance(ri, state); lastVB = NULL; // no longer valid, null it lastPB = NULL; // no longer valid, null it j++; continue; } else if ( baseRI->type == RenderPassManager::RIT_Translucent ) { MeshRenderInst* ri = static_cast<MeshRenderInst*>(baseRI); BaseMatInstance *mat = ri->matInst; // .ifl? if( !mat ) { GFX->setStateBlock( _getStateBlock( ri->transFlags ) ); GFX->pushWorldMatrix(); GFX->setWorldMatrix(*ri->objectToWorld ); GFX->setTexture( 0, ri->miscTex ); GFX->setPrimitiveBuffer( *ri->primBuff ); GFX->setVertexBuffer( *ri->vertBuff ); GFX->disableShaders(); GFX->setupGenericShaders( GFXDevice::GSModColorTexture ); GFX->drawPrimitive( ri->primBuffIndex ); GFX->popWorldMatrix(); lastVB = NULL; // no longer valid, null it lastPB = NULL; // no longer valid, null it j++; continue; } setupSGData( ri, sgData ); bool firstmatpass = true; while( mat->setupPass( state, sgData ) ) { U32 a; for( a=j; a<binSize; a++ ) { RenderInst* nextRI = mElementList[a].inst; if ( nextRI->type != RenderPassManager::RIT_Translucent ) break; MeshRenderInst *passRI = static_cast<MeshRenderInst*>(nextRI); // if new matInst is null or different, break // The visibility check prevents mesh elements with different visibility from being // batched together. This can happen when visibility is animated in the dts model. if (newPassNeeded(mat, passRI) || passRI->visibility != ri->visibility) break; // Z sorting and stuff is still not working in this mgr... setupSGData( passRI, sgData ); mat->setSceneInfo(state, sgData); matrixSet.setWorld(*passRI->objectToWorld); matrixSet.setView(*passRI->worldToCamera); matrixSet.setProjection(*passRI->projection); mat->setTransforms(matrixSet, state); mat->setBuffers(passRI->vertBuff, passRI->primBuff); // draw it if ( passRI->prim ) GFX->drawPrimitive( *passRI->prim ); else GFX->drawPrimitive( passRI->primBuffIndex ); } matListEnd = a; firstmatpass = false; } // force increment if none happened, otherwise go to end of batch j = ( j == matListEnd ) ? j+1 : matListEnd; } } }
[ [ [ 1, 256 ] ] ]
87d70ad9c54d648a17d5181972e5dc38e8e98b6c
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/spot_Time_native_System_Environment.h
096886dd3f81605a8fc4bdd7a2aa17a464891b65
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
920
h
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #ifndef _SPOT_TIME_NATIVE_SYSTEM_ENVIRONMENT_H_ #define _SPOT_TIME_NATIVE_SYSTEM_ENVIRONMENT_H_ namespace System { struct Environment { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static INT32 get_TickCount( HRESULT &hr ); }; } #endif //_SPOT_TIME_NATIVE_SYSTEM_ENVIRONMENT_H_
[ [ [ 1, 26 ] ] ]
91dd9ba5eafdfd0364be5f72e4d31b2175f1a0f4
f8c4a7b2ed9551c01613961860115aaf427d3839
/src/cCritter.h
14450a16d744a4904e89fc41212a8f22ffc959c3
[]
no_license
ifgrup/mvj-grupo5
de145cd57d7c5ff2c140b807d2d7c5bbc57cc5a9
6ba63d89b739c6af650482d9c259809e5042a3aa
refs/heads/master
2020-04-19T15:17:15.490509
2011-12-19T17:40:19
2011-12-19T17:40:19
34,346,323
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,656
h
#ifndef __CRITTER_H__ #define __CRITTER_H__ #include <windows.h> #include "cTrajectory.h" #include "cPath.h" #include "cWalkabilityFunctor.h" #include "cScene.h" #define CRITTER_LIVES 9 class cScene; class cCritter { public: cCritter(void); virtual ~cCritter(void); void GoToCell(CTile2D **map,int destcx,int destcy); void GoToEnemy(CTile2D **map,int destcx,int destcy); void Move(); void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectLife(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectRadar(RECT *rc,int *posx,int *posy); void SetPosition(int posx,int posy); void GetPosition(int *posx,int *posy); void SetCell(int cellx,int celly); void GetCell(int *cellx,int *celly); void SetSelected(bool sel); bool GetSelected(); bool GetShooting(); bool IsFiring(); bool IsMoving(); bool AlAtaquue(); void Damage(); //llamada cuando nos ha contactado un enemigo bool IsAlive();//Indica si está vivo o no int GetLives(); int Faced(); //Devuelve la orientación de su movimiento private: int x,y; //Position in total map int cx,cy; //Cell position in total map bool selected; //Selected for move or attack //cTrajectory Trajectory; cPath* Trajectory; int seq; //Sequence animation control int delay; //Animation delay bool attack; //Order to attack established (moving for attack) bool shoot; //Begin attack (to shoot) int shoot_seq; //Shooter sequence animation control int shoot_delay;//Shooter animation delay bool move; bool pupita; int Lives; }; #endif
[ "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c", "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c", "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c" ]
[ [ [ 1, 10 ], [ 12, 36 ], [ 43, 58 ], [ 62, 64 ] ], [ [ 11, 11 ], [ 39, 42 ], [ 61, 61 ] ], [ [ 37, 38 ], [ 59, 60 ] ] ]
a165e210be112c65f560f2d8d8188e2da7c2950a
216ae2fd7cba505c3690eaae33f62882102bd14a
/source/BulletProperty.h
47001c30d57a7eb38a005f7809e99a0c8ae7b165
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
UTF-8
C++
false
false
1,111
h
#pragma once #include <string> /** * this class holds all the information * for creating a bullet including static * attributes including explosion or particles. * Objects of this class should be owned by weapon * so that bullets can be created in the game controller **/ namespace Balyoz { class BulletController; enum ENUM_EFFECT{ EFFECT_NONE = 0, EFFECT_LINEER, EFFECT_EXPONENTIAL }; class BulletProperty { public: BulletProperty(); BulletProperty( float InitialSpeed, float MaximumSpeed, float Power, float Radius, float LifeTime, const std::string& Explosion, const std::string& Particles, const std::string& Controller, ENUM_EFFECT Effect, BulletController* pBulletController = 0 ); ~BulletProperty(void){}; BulletController* m_pBulletController; float m_MaximumSpeed; float m_InitialSpeed; float m_Power; float m_Radius; ENUM_EFFECT m_Effect; float m_LifeTime; std::string m_Explosion; std::string m_Particles; std::string m_Controller; }; };
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 52 ] ] ]
5ea66639114b992aefe300cdf231515ab6938830
8f5d0d23e857e58ad88494806bc60c5c6e13f33d
/FMod/fmod.h
92ae6dffdea107ae9fb75cea98ac280cad89af63
[]
no_license
markglenn/projectlife
edb14754118ec7b0f7d83bd4c92b2e13070dca4f
a6fd3502f2c2713a8a1a919659c775db5309f366
refs/heads/master
2021-01-01T15:31:30.087632
2011-01-30T16:03:41
2011-01-30T16:03:41
1,704,290
1
1
null
null
null
null
UTF-8
C++
false
false
62,665
h
/* ========================================================================================== */ /* FMOD Main header file. Copyright (c), Firelight Technologies Pty, Ltd 1999-2002. */ /* ========================================================================================== */ #ifndef _FMOD_H_ #define _FMOD_H_ /* ========================================================================================== */ /* DEFINITIONS */ /* ========================================================================================== */ #if !defined(WIN32) || (defined(__GNUC__) && defined(WIN32)) #ifndef _cdecl #define _cdecl #endif #ifndef _stdcall #define _stdcall #endif #endif #define F_API _stdcall #ifdef DLL_EXPORTS #define DLL_API __declspec(dllexport) #else #if defined(__LCC__) || defined(__MINGW32__) || defined(__CYGWIN32__) #define DLL_API F_API #else #define DLL_API #endif /* __LCC__ || __MINGW32__ || __CYGWIN32__ */ #endif /* DLL_EXPORTS */ #define FMOD_VERSION 3.6f /* FMOD defined types */ typedef struct FSOUND_SAMPLE FSOUND_SAMPLE; typedef struct FSOUND_STREAM FSOUND_STREAM; typedef struct FSOUND_DSPUNIT FSOUND_DSPUNIT; typedef struct FMUSIC_MODULE FMUSIC_MODULE; /* Callback types */ typedef void * (_cdecl *FSOUND_DSPCALLBACK) (void *originalbuffer, void *newbuffer, int length, int param); typedef signed char (_cdecl *FSOUND_STREAMCALLBACK) (FSOUND_STREAM *stream, void *buff, int len, int param); typedef void * (_cdecl *FSOUND_ALLOCCALLBACK) (unsigned int size); typedef void * (_cdecl *FSOUND_REALLOCCALLBACK)(void *ptr, unsigned int size); typedef void (_cdecl *FSOUND_FREECALLBACK) (void *ptr); typedef unsigned int(_cdecl *FSOUND_OPENCALLBACK) (const char *name); typedef void (_cdecl *FSOUND_CLOSECALLBACK) (unsigned int handle); typedef int (_cdecl *FSOUND_READCALLBACK) (void *buffer, int size, unsigned int handle); typedef int (_cdecl *FSOUND_SEEKCALLBACK) (unsigned int handle, int pos, signed char mode); typedef int (_cdecl *FSOUND_TELLCALLBACK) (unsigned int handle); typedef void (_cdecl *FMUSIC_CALLBACK) (FMUSIC_MODULE *mod, unsigned char param); /* [ENUM] [ [DESCRIPTION] On failure of commands in FMOD, use FSOUND_GetError to attain what happened. [SEE_ALSO] FSOUND_GetError ] */ enum FMOD_ERRORS { FMOD_ERR_NONE, /* No errors */ FMOD_ERR_BUSY, /* Cannot call this command after FSOUND_Init. Call FSOUND_Close first. */ FMOD_ERR_UNINITIALIZED, /* This command failed because FSOUND_Init or FSOUND_SetOutput was not called */ FMOD_ERR_INIT, /* Error initializing output device. */ FMOD_ERR_ALLOCATED, /* Error initializing output device, but more specifically, the output device is already in use and cannot be reused. */ FMOD_ERR_PLAY, /* Playing the sound failed. */ FMOD_ERR_OUTPUT_FORMAT, /* Soundcard does not support the features needed for this soundsystem (16bit stereo output) */ FMOD_ERR_COOPERATIVELEVEL, /* Error setting cooperative level for hardware. */ FMOD_ERR_CREATEBUFFER, /* Error creating hardware sound buffer. */ FMOD_ERR_FILE_NOTFOUND, /* File not found */ FMOD_ERR_FILE_FORMAT, /* Unknown file format */ FMOD_ERR_FILE_BAD, /* Error loading file */ FMOD_ERR_MEMORY, /* Not enough memory or resources */ FMOD_ERR_VERSION, /* The version number of this file format is not supported */ FMOD_ERR_INVALID_PARAM, /* An invalid parameter was passed to this function */ FMOD_ERR_NO_EAX, /* Tried to use an EAX command on a non EAX enabled channel or output. */ FMOD_ERR_CHANNEL_ALLOC, /* Failed to allocate a new channel */ FMOD_ERR_RECORD, /* Recording is not supported on this machine */ FMOD_ERR_MEDIAPLAYER, /* Windows Media Player not installed so cannot play wma or use internet streaming. */ FMOD_ERR_CDDEVICE /* An error occured trying to open the specified CD device */ }; /* [ENUM] [ [DESCRIPTION] These output types are used with FSOUND_SetOutput, to choose which output driver to use. FSOUND_OUTPUT_DSOUND will not support hardware 3d acceleration if the sound card driver does not support DirectX 6 Voice Manager Extensions. FSOUND_OUTPUT_WINMM is recommended for NT and CE. [SEE_ALSO] FSOUND_SetOutput FSOUND_GetOutput ] */ enum FSOUND_OUTPUTTYPES { FSOUND_OUTPUT_NOSOUND, /* NoSound driver, all calls to this succeed but do nothing. */ FSOUND_OUTPUT_WINMM, /* Windows Multimedia driver. */ FSOUND_OUTPUT_DSOUND, /* DirectSound driver. You need this to get EAX2 or EAX3 support, or FX api support. */ FSOUND_OUTPUT_A3D, /* A3D driver. not supported any more. */ FSOUND_OUTPUT_OSS, /* Linux/Unix OSS (Open Sound System) driver, i.e. the kernel sound drivers. */ FSOUND_OUTPUT_ESD, /* Linux/Unix ESD (Enlightment Sound Daemon) driver. */ FSOUND_OUTPUT_ALSA, /* Linux Alsa driver. */ FSOUND_OUTPUT_ASIO, /* Low latency ASIO driver */ FSOUND_OUTPUT_XBOX, /* Xbox driver */ FSOUND_OUTPUT_PS2, /* PlayStation 2 driver */ FSOUND_OUTPUT_MAC /* Mac SoundMager driver */ }; /* [ENUM] [ [DESCRIPTION] These mixer types are used with FSOUND_SetMixer, to choose which mixer to use, or to act upon for other reasons using FSOUND_GetMixer. It is not nescessary to set the mixer. FMOD will autodetect the best mixer for you. [SEE_ALSO] FSOUND_SetMixer FSOUND_GetMixer ] */ enum FSOUND_MIXERTYPES { FSOUND_MIXER_AUTODETECT, /* CE/PS2 Only - Non interpolating/low quality mixer. */ FSOUND_MIXER_BLENDMODE, /* removed / obsolete. */ FSOUND_MIXER_MMXP5, /* removed / obsolete. */ FSOUND_MIXER_MMXP6, /* removed / obsolete. */ FSOUND_MIXER_QUALITY_AUTODETECT,/* All platforms - Autodetect the fastest quality mixer based on your cpu. */ FSOUND_MIXER_QUALITY_FPU, /* Win32/Linux only - Interpolating/volume ramping FPU mixer. */ FSOUND_MIXER_QUALITY_MMXP5, /* Win32/Linux only - Interpolating/volume ramping P5 MMX mixer. */ FSOUND_MIXER_QUALITY_MMXP6, /* Win32/Linux only - Interpolating/volume ramping ppro+ MMX mixer. */ FSOUND_MIXER_MONO, /* CE/PS2 only - MONO non interpolating/low quality mixer. For speed*/ FSOUND_MIXER_QUALITY_MONO, /* CE/PS2 only - MONO Interpolating mixer. For speed */ FSOUND_MIXER_MAX }; /* [ENUM] [ [DESCRIPTION] These definitions describe the type of song being played. [SEE_ALSO] FMUSIC_GetType ] */ enum FMUSIC_TYPES { FMUSIC_TYPE_NONE, FMUSIC_TYPE_MOD, /* Protracker / Fasttracker */ FMUSIC_TYPE_S3M, /* ScreamTracker 3 */ FMUSIC_TYPE_XM, /* FastTracker 2 */ FMUSIC_TYPE_IT, /* Impulse Tracker. */ FMUSIC_TYPE_MIDI /* MIDI file */ }; /* [DEFINE_START] [ [NAME] FSOUND_DSP_PRIORITIES [DESCRIPTION] These default priorities are used by FMOD internal system DSP units. They describe the position of the DSP chain, and the order of how audio processing is executed. You can actually through the use of FSOUND_DSP_GetxxxUnit (where xxx is the name of the DSP unit), disable or even change the priority of a DSP unit. [SEE_ALSO] FSOUND_DSP_Create FSOUND_DSP_SetPriority FSOUND_DSP_GetSpectrum ] */ #define FSOUND_DSP_DEFAULTPRIORITY_CLEARUNIT 0 /* DSP CLEAR unit - done first */ #define FSOUND_DSP_DEFAULTPRIORITY_SFXUNIT 100 /* DSP SFX unit - done second */ #define FSOUND_DSP_DEFAULTPRIORITY_MUSICUNIT 200 /* DSP MUSIC unit - done third */ #define FSOUND_DSP_DEFAULTPRIORITY_USER 300 /* User priority, use this as reference */ #define FSOUND_DSP_DEFAULTPRIORITY_FFTUNIT 900 /* This reads data for FSOUND_DSP_GetSpectrum, so it comes after user units */ #define FSOUND_DSP_DEFAULTPRIORITY_CLIPANDCOPYUNIT 1000 /* DSP CLIP AND COPY unit - last */ /* [DEFINE_END] */ /* [DEFINE_START] [ [NAME] FSOUND_CAPS [DESCRIPTION] Driver description bitfields. Use FSOUND_Driver_GetCaps to determine if a driver enumerated has the settings you are after. The enumerated driver depends on the output mode, see FSOUND_OUTPUTTYPES [SEE_ALSO] FSOUND_GetDriverCaps FSOUND_OUTPUTTYPES ] */ #define FSOUND_CAPS_HARDWARE 0x1 /* This driver supports hardware accelerated 3d sound. */ #define FSOUND_CAPS_EAX2 0x2 /* This driver supports EAX 2 reverb */ #define FSOUND_CAPS_EAX3 0x10 /* This driver supports EAX 3 reverb */ /* [DEFINE_END] */ /* [DEFINE_START] [ [NAME] FSOUND_MODES [DESCRIPTION] Sample description bitfields, OR them together for loading and describing samples. NOTE. If the file format being loaded already has a defined format, such as WAV or MP3, then trying to override the pre-defined format with a new set of format flags will not work. For example, an 8 bit WAV file will not load as 16bit if you specify FSOUND_16BITS. It will just ignore the flag and go ahead loading it as 8bits. For these type of formats the only flags you can specify that will really alter the behaviour of how it is loaded, are the following. FSOUND_LOOP_OFF FSOUND_LOOP_NORMAL FSOUND_LOOP_BIDI FSOUND_HW3D FSOUND_2D FSOUND_STREAMABLE FSOUND_LOADMEMORY FSOUND_LOADRAW FSOUND_MPEGACCURATE See flag descriptions for what these do. ] */ #define FSOUND_LOOP_OFF 0x00000001 /* For non looping samples. */ #define FSOUND_LOOP_NORMAL 0x00000002 /* For forward looping samples. */ #define FSOUND_LOOP_BIDI 0x00000004 /* For bidirectional looping samples. (no effect if in hardware). */ #define FSOUND_8BITS 0x00000008 /* For 8 bit samples. */ #define FSOUND_16BITS 0x00000010 /* For 16 bit samples. */ #define FSOUND_MONO 0x00000020 /* For mono samples. */ #define FSOUND_STEREO 0x00000040 /* For stereo samples. */ #define FSOUND_UNSIGNED 0x00000080 /* For user created source data containing unsigned samples. */ #define FSOUND_SIGNED 0x00000100 /* For user created source data containing signed data. */ #define FSOUND_DELTA 0x00000200 /* For user created source data stored as delta values. */ #define FSOUND_IT214 0x00000400 /* For user created source data stored using IT214 compression. */ #define FSOUND_IT215 0x00000800 /* For user created source data stored using IT215 compression. */ #define FSOUND_HW3D 0x00001000 /* Attempts to make samples use 3d hardware acceleration. (if the card supports it) */ #define FSOUND_2D 0x00002000 /* Tells software (not hardware) based sample not to be included in 3d processing. */ #define FSOUND_STREAMABLE 0x00004000 /* For a streamimg sound where you feed the data to it. */ #define FSOUND_LOADMEMORY 0x00008000 /* "name" will be interpreted as a pointer to data for streaming and samples. */ #define FSOUND_LOADRAW 0x00010000 /* Will ignore file format and treat as raw pcm. */ #define FSOUND_MPEGACCURATE 0x00020000 /* For FSOUND_Stream_OpenFile - for accurate FSOUND_Stream_GetLengthMs/FSOUND_Stream_SetTime. WARNING, see FSOUND_Stream_OpenFile for inital opening time performance issues. */ #define FSOUND_FORCEMONO 0x00040000 /* For forcing stereo streams and samples to be mono - needed if using FSOUND_HW3D and stereo data - incurs a small speed hit for streams */ #define FSOUND_HW2D 0x00080000 /* 2D hardware sounds. allows hardware specific effects */ #define FSOUND_ENABLEFX 0x00100000 /* Allows DX8 FX to be played back on a sound. Requires DirectX 8 - Note these sounds cannot be played more than once, be 8 bit, be less than a certain size, or have a changing frequency */ #define FSOUND_MPEGHALFRATE 0x00200000 /* For FMODCE only - decodes mpeg streams using a lower quality decode, but faster execution */ #define FSOUND_XADPCM 0x00400000 /* For XBOX only - Describes a user sample that its contents are compressed as XADPCM */ #define FSOUND_VAG 0x00800000 /* For PS2 only - Describes a user sample that its contents are compressed as Sony VAG format */ #define FSOUND_NONBLOCKING 0x01000000 /* For FSOUND_Stream_OpenFile - Causes stream to open in the background and not block the foreground app - stream functions only work when ready. Poll any stream function determine when it IS ready. */ #define FSOUND_NORMAL (FSOUND_16BITS | FSOUND_SIGNED | FSOUND_MONO) /* [DEFINE_END] */ /* [DEFINE_START] [ [NAME] FSOUND_CDPLAYMODES [DESCRIPTION] Playback method for a CD Audio track, with FSOUND_CD_SetPlayMode [SEE_ALSO] FSOUND_CD_SetPlayMode FSOUND_CD_Play ] */ #define FSOUND_CD_PLAYCONTINUOUS 0 /* Starts from the current track and plays to end of CD. */ #define FSOUND_CD_PLAYONCE 1 /* Plays the specified track then stops. */ #define FSOUND_CD_PLAYLOOPED 2 /* Plays the specified track looped, forever until stopped manually. */ #define FSOUND_CD_PLAYRANDOM 3 /* Plays tracks in random order */ /* [DEFINE_END] */ /* [DEFINE_START] [ [NAME] FSOUND_MISC_VALUES [DESCRIPTION] Miscellaneous values for FMOD functions. [SEE_ALSO] FSOUND_PlaySound FSOUND_PlaySoundEx FSOUND_Sample_Alloc FSOUND_Sample_Load FSOUND_SetPan ] */ #define FSOUND_FREE -1 /* value to play on any free channel, or to allocate a sample in a free sample slot. */ #define FSOUND_UNMANAGED -2 /* value to allocate a sample that is NOT managed by FSOUND or placed in a sample slot. */ #define FSOUND_ALL -3 /* for a channel index , this flag will affect ALL channels available! Not supported by every function. */ #define FSOUND_STEREOPAN -1 /* value for FSOUND_SetPan so that stereo sounds are not played at half volume. See FSOUND_SetPan for more on this. */ #define FSOUND_SYSTEMCHANNEL -1000 /* special 'channel' ID for all channel based functions that want to alter the global FSOUND software mixing output channel */ #define FSOUND_SYSTEMSAMPLE -1000 /* special 'sample' ID for all sample based functions that want to alter the global FSOUND software mixing output sample */ /* [DEFINE_END] */ /* [STRUCTURE] [ [DESCRIPTION] Structure defining a reverb environment. For more indepth descriptions of the reverb properties under win32, please see the EAX2 and EAX3 documentation at http://developer.creative.com/ under the 'downloads' section. If they do not have the EAX3 documentation, then most information can be attained from the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of EAX2. Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset. Note that integer values that typically range from -10,000 to 1000 are represented in decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear. PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox). Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then the reverb should product a similar effect on either platform. Linux and FMODCE do not support the reverb api. The numerical values listed below are the maximum, minimum and default values for each variable respectively. [SEE_ALSO] FSOUND_Reverb_SetProperties FSOUND_Reverb_GetProperties FSOUND_REVERB_PRESETS FSOUND_REVERB_FLAGS ] */ typedef struct _FSOUND_REVERB_PROPERTIES /* MIN MAX DEFAULT DESCRIPTION */ { unsigned int Environment; /* 0 , 25 , 0 , sets all listener properties (win32/ps2 only) */ float EnvSize; /* 1.0 , 100.0 , 7.5 , environment size in meters (win32 only) */ float EnvDiffusion; /* 0.0 , 1.0 , 1.0 , environment diffusion (win32/xbox) */ int Room; /* -10000, 0 , -1000 , room effect level (at mid frequencies) (win32/xbox/ps2) */ int RoomHF; /* -10000, 0 , -100 , relative room effect level at high frequencies (win32/xbox) */ int RoomLF; /* -10000, 0 , 0 , relative room effect level at low frequencies (win32 only) */ float DecayTime; /* 0.1 , 20.0 , 1.49 , reverberation decay time at mid frequencies (win32/xbox) */ float DecayHFRatio; /* 0.1 , 2.0 , 0.83 , high-frequency to mid-frequency decay time ratio (win32/xbox) */ float DecayLFRatio; /* 0.1 , 2.0 , 1.0 , low-frequency to mid-frequency decay time ratio (win32 only) */ int Reflections; /* -10000, 1000 , -2602 , early reflections level relative to room effect (win32/xbox) */ float ReflectionsDelay; /* 0.0 , 0.3 , 0.007 , initial reflection delay time (win32/xbox) */ float ReflectionsPan[3]; /* , , [0,0,0], early reflections panning vector (win32 only) */ int Reverb; /* -10000, 2000 , 200 , late reverberation level relative to room effect (win32/xbox) */ float ReverbDelay; /* 0.0 , 0.1 , 0.011 , late reverberation delay time relative to initial reflection (win32/xbox) */ float ReverbPan[3]; /* , , [0,0,0], late reverberation panning vector (win32 only) */ float EchoTime; /* .075 , 0.25 , 0.25 , echo time (win32 only) */ float EchoDepth; /* 0.0 , 1.0 , 0.0 , echo depth (win32 only) */ float ModulationTime; /* 0.04 , 4.0 , 0.25 , modulation time (win32 only) */ float ModulationDepth; /* 0.0 , 1.0 , 0.0 , modulation depth (win32 only) */ float AirAbsorptionHF; /* -100 , 0.0 , -5.0 , change in level per meter at high frequencies (win32 only) */ float HFReference; /* 1000.0, 20000 , 5000.0 , reference high frequency (hz) (win32/xbox) */ float LFReference; /* 20.0 , 1000.0, 250.0 , reference low frequency (hz) (win32 only) */ float RoomRolloffFactor; /* 0.0 , 10.0 , 0.0 , like FSOUND_3D_Listener_SetRolloffFactor but for room effect (win32/xbox) */ float Diffusion; /* 0.0 , 100.0 , 100.0 , Value that controls the echo density in the late reverberation decay. (xbox only) */ float Density; /* 0.0 , 100.0 , 100.0 , Value that controls the modal density in the late reverberation decay (xbox only) */ unsigned int Flags; /* FSOUND_REVERB_FLAGS - modifies the behavior of above properties (win32 only) */ } FSOUND_REVERB_PROPERTIES; /* [DEFINE_START] [ [NAME] FSOUND_REVERB_FLAGS [DESCRIPTION] Values for the Flags member of the FSOUND_REVERB_PROPERTIES structure. [SEE_ALSO] FSOUND_REVERB_PROPERTIES ] */ #define FSOUND_REVERB_FLAGS_DECAYTIMESCALE 0x00000001 /* 'EnvSize' affects reverberation decay time */ #define FSOUND_REVERB_FLAGS_REFLECTIONSSCALE 0x00000002 /* 'EnvSize' affects reflection level */ #define FSOUND_REVERB_FLAGS_REFLECTIONSDELAYSCALE 0x00000004 /* 'EnvSize' affects initial reflection delay time */ #define FSOUND_REVERB_FLAGS_REVERBSCALE 0x00000008 /* 'EnvSize' affects reflections level */ #define FSOUND_REVERB_FLAGS_REVERBDELAYSCALE 0x00000010 /* 'EnvSize' affects late reverberation delay time */ #define FSOUND_REVERB_FLAGS_DECAYHFLIMIT 0x00000020 /* AirAbsorptionHF affects DecayHFRatio */ #define FSOUND_REVERB_FLAGS_ECHOTIMESCALE 0x00000040 /* 'EnvSize' affects echo time */ #define FSOUND_REVERB_FLAGS_MODULATIONTIMESCALE 0x00000080 /* 'EnvSize' affects modulation time */ #define FSOUND_REVERB_FLAGS_CORE0 0x00000100 /* PS2 Only - Reverb is applied to CORE0 (hw voices 0-23) */ #define FSOUND_REVERB_FLAGS_CORE1 0x00000200 /* PS2 Only - Reverb is applied to CORE1 (hw voices 24-47) */ #define FSOUND_REVERB_FLAGS_DEFAULT (FSOUND_REVERB_FLAGS_DECAYTIMESCALE | \ FSOUND_REVERB_FLAGS_REFLECTIONSSCALE | \ FSOUND_REVERB_FLAGS_REFLECTIONSDELAYSCALE | \ FSOUND_REVERB_FLAGS_REVERBSCALE | \ FSOUND_REVERB_FLAGS_REVERBDELAYSCALE | \ FSOUND_REVERB_FLAGS_DECAYHFLIMIT | \ FSOUND_REVERB_FLAGS_CORE0 | \ FSOUND_REVERB_FLAGS_CORE1 ) /* [DEFINE_END] */ /* [DEFINE_START] [ [NAME] FSOUND_REVERB_PRESETS [DESCRIPTION] A set of predefined environment PARAMETERS, created by Creative Labs These are used to initialize an FSOUND_REVERB_PROPERTIES structure statically. ie FSOUND_REVERB_PROPERTIES prop = FSOUND_PRESET_GENERIC; [SEE_ALSO] FSOUND_Reverb_SetProperties ] */ /* Env Size Diffus Room RoomHF RmLF DecTm DecHF DecLF Refl RefDel RefPan Revb RevDel ReverbPan EchoTm EchDp ModTm ModDp AirAbs HFRef LFRef RRlOff Diffus Densty FLAGS */ #define FSOUND_PRESET_OFF {0, 7.5f, 1.00f, -10000, -10000, 0, 1.00f, 1.00f, 1.0f, -2602, 0.007f, { 0.0f,0.0f,0.0f }, 200, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 0.0f, 0.0f, 0x33f } #define FSOUND_PRESET_GENERIC {0, 7.5f, 1.00f, -1000, -100, 0, 1.49f, 0.83f, 1.0f, -2602, 0.007f, { 0.0f,0.0f,0.0f }, 200, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_PADDEDCELL {1, 1.4f, 1.00f, -1000, -6000, 0, 0.17f, 0.10f, 1.0f, -1204, 0.001f, { 0.0f,0.0f,0.0f }, 207, 0.002f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_ROOM {2, 1.9f, 1.00f, -1000, -454, 0, 0.40f, 0.83f, 1.0f, -1646, 0.002f, { 0.0f,0.0f,0.0f }, 53, 0.003f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_BATHROOM {3, 1.4f, 1.00f, -1000, -1200, 0, 1.49f, 0.54f, 1.0f, -370, 0.007f, { 0.0f,0.0f,0.0f }, 1030, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 60.0f, 0x3f } #define FSOUND_PRESET_LIVINGROOM {4, 2.5f, 1.00f, -1000, -6000, 0, 0.50f, 0.10f, 1.0f, -1376, 0.003f, { 0.0f,0.0f,0.0f }, -1104, 0.004f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_STONEROOM {5, 11.6f, 1.00f, -1000, -300, 0, 2.31f, 0.64f, 1.0f, -711, 0.012f, { 0.0f,0.0f,0.0f }, 83, 0.017f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_AUDITORIUM {6, 21.6f, 1.00f, -1000, -476, 0, 4.32f, 0.59f, 1.0f, -789, 0.020f, { 0.0f,0.0f,0.0f }, -289, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_CONCERTHALL {7, 19.6f, 1.00f, -1000, -500, 0, 3.92f, 0.70f, 1.0f, -1230, 0.020f, { 0.0f,0.0f,0.0f }, -2, 0.029f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_CAVE {8, 14.6f, 1.00f, -1000, 0, 0, 2.91f, 1.30f, 1.0f, -602, 0.015f, { 0.0f,0.0f,0.0f }, -302, 0.022f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f } #define FSOUND_PRESET_ARENA {9, 36.2f, 1.00f, -1000, -698, 0, 7.24f, 0.33f, 1.0f, -1166, 0.020f, { 0.0f,0.0f,0.0f }, 16, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_HANGAR {10, 50.3f, 1.00f, -1000, -1000, 0, 10.05f, 0.23f, 1.0f, -602, 0.020f, { 0.0f,0.0f,0.0f }, 198, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_CARPETTEDHALLWAY {11, 1.9f, 1.00f, -1000, -4000, 0, 0.30f, 0.10f, 1.0f, -1831, 0.002f, { 0.0f,0.0f,0.0f }, -1630, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_HALLWAY {12, 1.8f, 1.00f, -1000, -300, 0, 1.49f, 0.59f, 1.0f, -1219, 0.007f, { 0.0f,0.0f,0.0f }, 441, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_STONECORRIDOR {13, 13.5f, 1.00f, -1000, -237, 0, 2.70f, 0.79f, 1.0f, -1214, 0.013f, { 0.0f,0.0f,0.0f }, 395, 0.020f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_ALLEY {14, 7.5f, 0.30f, -1000, -270, 0, 1.49f, 0.86f, 1.0f, -1204, 0.007f, { 0.0f,0.0f,0.0f }, -4, 0.011f, { 0.0f,0.0f,0.0f }, 0.125f, 0.95f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_FOREST {15, 38.0f, 0.30f, -1000, -3300, 0, 1.49f, 0.54f, 1.0f, -2560, 0.162f, { 0.0f,0.0f,0.0f }, -229, 0.088f, { 0.0f,0.0f,0.0f }, 0.125f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 79.0f, 100.0f, 0x3f } #define FSOUND_PRESET_CITY {16, 7.5f, 0.50f, -1000, -800, 0, 1.49f, 0.67f, 1.0f, -2273, 0.007f, { 0.0f,0.0f,0.0f }, -1691, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 50.0f, 100.0f, 0x3f } #define FSOUND_PRESET_MOUNTAINS {17, 100.0f, 0.27f, -1000, -2500, 0, 1.49f, 0.21f, 1.0f, -2780, 0.300f, { 0.0f,0.0f,0.0f }, -1434, 0.100f, { 0.0f,0.0f,0.0f }, 0.250f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 27.0f, 100.0f, 0x1f } #define FSOUND_PRESET_QUARRY {18, 17.5f, 1.00f, -1000, -1000, 0, 1.49f, 0.83f, 1.0f, -10000, 0.061f, { 0.0f,0.0f,0.0f }, 500, 0.025f, { 0.0f,0.0f,0.0f }, 0.125f, 0.70f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } #define FSOUND_PRESET_PLAIN {19, 42.5f, 0.21f, -1000, -2000, 0, 1.49f, 0.50f, 1.0f, -2466, 0.179f, { 0.0f,0.0f,0.0f }, -1926, 0.100f, { 0.0f,0.0f,0.0f }, 0.250f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 21.0f, 100.0f, 0x3f } #define FSOUND_PRESET_PARKINGLOT {20, 8.3f, 1.00f, -1000, 0, 0, 1.65f, 1.50f, 1.0f, -1363, 0.008f, { 0.0f,0.0f,0.0f }, -1153, 0.012f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f } #define FSOUND_PRESET_SEWERPIPE {21, 1.7f, 0.80f, -1000, -1000, 0, 2.81f, 0.14f, 1.0f, 429, 0.014f, { 0.0f,0.0f,0.0f }, 1023, 0.021f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 80.0f, 60.0f, 0x3f } #define FSOUND_PRESET_UNDERWATER {22, 1.8f, 1.00f, -1000, -4000, 0, 1.49f, 0.10f, 1.0f, -449, 0.007f, { 0.0f,0.0f,0.0f }, 1700, 0.011f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 1.18f, 0.348f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f } /* Non I3DL2 presets */ #define FSOUND_PRESET_DRUGGED {23, 1.9f, 0.50f, -1000, 0, 0, 8.39f, 1.39f, 1.0f, -115, 0.002f, { 0.0f,0.0f,0.0f }, 985, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 0.25f, 1.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f } #define FSOUND_PRESET_DIZZY {24, 1.8f, 0.60f, -1000, -400, 0, 17.23f, 0.56f, 1.0f, -1713, 0.020f, { 0.0f,0.0f,0.0f }, -613, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 1.00f, 0.81f, 0.310f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f } #define FSOUND_PRESET_PSYCHOTIC {25, 1.0f, 0.50f, -1000, -151, 0, 7.56f, 0.91f, 1.0f, -626, 0.020f, { 0.0f,0.0f,0.0f }, 774, 0.030f, { 0.0f,0.0f,0.0f }, 0.250f, 0.00f, 4.00f, 1.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f } /* PlayStation 2 Only presets */ #define FSOUND_PRESET_PS2_ROOM {1, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_STUDIO_A {2, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_STUDIO_B {3, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_STUDIO_C {4, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_HALL {5, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_SPACE {6, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_ECHO {7, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_DELAY {8, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } #define FSOUND_PRESET_PS2_PIPE {9, 0, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0, 0.000f, { 0.0f,0.0f,0.0f }, 0.000f, 0.00f, 0.00f, 0.000f, 0.0f, 0000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0x31f } /* [DEFINE_END] */ /* [STRUCTURE] [ [DESCRIPTION] Structure defining the properties for a reverb source, related to a FSOUND channel. For more indepth descriptions of the reverb properties under win32, please see the EAX3 documentation at http://developer.creative.com/ under the 'downloads' section. If they do not have the EAX3 documentation, then most information can be attained from the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of EAX2. Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset. Note that integer values that typically range from -10,000 to 1000 are represented in decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear. PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox). Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then the reverb should product a similar effect on either platform. Linux and FMODCE do not support the reverb api. The numerical values listed below are the maximum, minimum and default values for each variable respectively. [SEE_ALSO] FSOUND_Reverb_SetChannelProperties FSOUND_Reverb_GetChannelProperties FSOUND_REVERB_CHANNELFLAGS ] */ typedef struct _FSOUND_REVERB_CHANNELPROPERTIES /* MIN MAX DEFAULT */ { int Direct; /* -10000, 1000, 0, direct path level (at low and mid frequencies) (win32/xbox) */ int DirectHF; /* -10000, 0, 0, relative direct path level at high frequencies (win32/xbox) */ int Room; /* -10000, 1000, 0, room effect level (at low and mid frequencies) (win32/xbox) */ int RoomHF; /* -10000, 0, 0, relative room effect level at high frequencies (win32/xbox) */ int Obstruction; /* -10000, 0, 0, main obstruction control (attenuation at high frequencies) (win32/xbox) */ float ObstructionLFRatio; /* 0.0, 1.0, 0.0, obstruction low-frequency level re. main control (win32/xbox) */ int Occlusion; /* -10000, 0, 0, main occlusion control (attenuation at high frequencies) (win32/xbox) */ float OcclusionLFRatio; /* 0.0, 1.0, 0.25, occlusion low-frequency level re. main control (win32/xbox) */ float OcclusionRoomRatio; /* 0.0, 10.0, 1.5, relative occlusion control for room effect (win32) */ float OcclusionDirectRatio; /* 0.0, 10.0, 1.0, relative occlusion control for direct path (win32) */ int Exclusion; /* -10000, 0, 0, main exlusion control (attenuation at high frequencies) (win32) */ float ExclusionLFRatio; /* 0.0, 1.0, 1.0, exclusion low-frequency level re. main control (win32) */ int OutsideVolumeHF; /* -10000, 0, 0, outside sound cone level at high frequencies (win32) */ float DopplerFactor; /* 0.0, 10.0, 0.0, like DS3D flDopplerFactor but per source (win32) */ float RolloffFactor; /* 0.0, 10.0, 0.0, like DS3D flRolloffFactor but per source (win32) */ float RoomRolloffFactor; /* 0.0, 10.0, 0.0, like DS3D flRolloffFactor but for room effect (win32/xbox) */ float AirAbsorptionFactor; /* 0.0, 10.0, 1.0, multiplies AirAbsorptionHF member of FSOUND_REVERB_PROPERTIES (win32) */ int Flags; /* FSOUND_REVERB_CHANNELFLAGS - modifies the behavior of properties (win32) */ } FSOUND_REVERB_CHANNELPROPERTIES; /* [DEFINE_START] [ [NAME] FSOUND_REVERB_CHANNELFLAGS [DESCRIPTION] Values for the Flags member of the FSOUND_REVERB_CHANNELPROPERTIES structure. [SEE_ALSO] FSOUND_REVERB_CHANNELPROPERTIES ] */ #define FSOUND_REVERB_CHANNELFLAGS_DIRECTHFAUTO 0x00000001 /* Automatic setting of 'Direct' due to distance from listener */ #define FSOUND_REVERB_CHANNELFLAGS_ROOMAUTO 0x00000002 /* Automatic setting of 'Room' due to distance from listener */ #define FSOUND_REVERB_CHANNELFLAGS_ROOMHFAUTO 0x00000004 /* Automatic setting of 'RoomHF' due to distance from listener */ #define FSOUND_REVERB_CHANNELFLAGS_DEFAULT (FSOUND_REVERB_CHANNELFLAGS_DIRECTHFAUTO | \ FSOUND_REVERB_CHANNELFLAGS_ROOMAUTO| \ FSOUND_REVERB_CHANNELFLAGS_ROOMHFAUTO) /* [DEFINE_END] */ /* [ENUM] [ [DESCRIPTION] These values are used with FSOUND_FX_Enable to enable DirectX 8 FX for a channel. [SEE_ALSO] FSOUND_FX_Enable FSOUND_FX_Disable FSOUND_FX_SetChorus FSOUND_FX_SetCompressor FSOUND_FX_SetDistortion FSOUND_FX_SetEcho FSOUND_FX_SetFlanger FSOUND_FX_SetGargle FSOUND_FX_SetI3DL2Reverb FSOUND_FX_SetParamEQ FSOUND_FX_SetWavesReverb ] */ enum FSOUND_FX_MODES { FSOUND_FX_CHORUS, FSOUND_FX_COMPRESSOR, FSOUND_FX_DISTORTION, FSOUND_FX_ECHO, FSOUND_FX_FLANGER, FSOUND_FX_GARGLE, FSOUND_FX_I3DL2REVERB, FSOUND_FX_PARAMEQ, FSOUND_FX_WAVES_REVERB, FSOUND_FX_MAX }; /* [ENUM] [ [DESCRIPTION] These are speaker types defined for use with the FSOUND_SetSpeakerMode command. Note - Only reliably works with FSOUND_OUTPUT_DSOUND or FSOUND_OUTPUT_XBOX output modes. Other output modes will only interpret FSOUND_SPEAKERMODE_MONO and set everything else to be stereo. [SEE_ALSO] FSOUND_SetSpeakerMode ] */ enum FSOUND_SPEAKERMODES { FSOUND_SPEAKERMODE_DOLBYDIGITAL, /* The audio is played through a speaker arrangement of surround speakers with a subwoofer. */ FSOUND_SPEAKERMODE_HEADPHONES, /* The speakers are headphones. */ FSOUND_SPEAKERMODE_MONO, /* The speakers are monaural. */ FSOUND_SPEAKERMODE_QUAD, /* The speakers are quadraphonic. */ FSOUND_SPEAKERMODE_STEREO, /* The speakers are stereo (default value). */ FSOUND_SPEAKERMODE_SURROUND, /* The speakers are surround sound. */ FSOUND_SPEAKERMODE_DTS /* (XBOX Only) The audio is played through a speaker arrangement of surround speakers with a subwoofer. */ }; /* [DEFINE_START] [ [NAME] FSOUND_INIT_FLAGS [DESCRIPTION] Initialization flags. Use them with FSOUND_Init in the flags parameter to change various behaviour. FSOUND_INIT_ENABLEOUTPUTFX Is an init mode which enables the FSOUND mixer buffer to be affected by DirectX 8 effects. Note that due to limitations of DirectSound, FSOUND_Init may fail if this is enabled because the buffersize is too small. This can be fixed with FSOUND_SetBufferSize. Increase the BufferSize until it works. When it is enabled you can use the FSOUND_FX api, and use FSOUND_SYSTEMCHANNEL as the channel id when setting parameters. [SEE_ALSO] FSOUND_Init ] */ #define FSOUND_INIT_USEDEFAULTMIDISYNTH 0x01 /* Causes MIDI playback to force software decoding. */ #define FSOUND_INIT_GLOBALFOCUS 0x02 /* For DirectSound output - sound is not muted when window is out of focus. */ #define FSOUND_INIT_ENABLEOUTPUTFX 0x04 /* For DirectSound output - Allows FSOUND_FX api to be used on global software mixer output! */ #define FSOUND_INIT_ACCURATEVULEVELS 0x08 /* This latency adjusts FSOUND_GetCurrentLevels, but incurs a small cpu and memory hit */ #define FSOUND_INIT_DISABLE_CORE0_REVERB 0x10 /* PS2 only - Disable reverb on CORE 0 to regain SRAM */ #define FSOUND_INIT_DISABLE_CORE1_REVERB 0x20 /* PS2 only - Disable reverb on CORE 1 to regain SRAM */ /* [DEFINE_END] */ /* ========================================================================================== */ /* FUNCTION PROTOTYPES */ /* ========================================================================================== */ #ifdef __cplusplus extern "C" { #endif /* ================================== */ /* Initialization / Global functions. */ /* ================================== */ /* PRE - FSOUND_Init functions. These can't be called after FSOUND_Init is called (they will fail). They set up FMOD system functionality. */ DLL_API signed char F_API FSOUND_SetOutput(int outputtype); DLL_API signed char F_API FSOUND_SetDriver(int driver); DLL_API signed char F_API FSOUND_SetMixer(int mixer); DLL_API signed char F_API FSOUND_SetBufferSize(int len_ms); DLL_API signed char F_API FSOUND_SetHWND(void *hwnd); DLL_API signed char F_API FSOUND_SetMinHardwareChannels(int min); DLL_API signed char F_API FSOUND_SetMaxHardwareChannels(int max); DLL_API signed char F_API FSOUND_SetMemorySystem(void *pool, int poollen, FSOUND_ALLOCCALLBACK useralloc, FSOUND_REALLOCCALLBACK userrealloc, FSOUND_FREECALLBACK userfree); /* Main initialization / closedown functions. Note : Use FSOUND_INIT_USEDEFAULTMIDISYNTH with FSOUND_Init for software override with MIDI playback. : Use FSOUND_INIT_GLOBALFOCUS with FSOUND_Init to make sound audible no matter which window is in focus. (FSOUND_OUTPUT_DSOUND only) */ DLL_API signed char F_API FSOUND_Init(int mixrate, int maxsoftwarechannels, unsigned int flags); DLL_API void F_API FSOUND_Close(); /* Runtime system level functions */ DLL_API void F_API FSOUND_SetSpeakerMode(unsigned int speakermode); DLL_API void F_API FSOUND_SetSFXMasterVolume(int volume); DLL_API void F_API FSOUND_SetPanSeperation(float pansep); DLL_API void F_API FSOUND_File_SetCallbacks(FSOUND_OPENCALLBACK useropen, FSOUND_CLOSECALLBACK userclose, FSOUND_READCALLBACK userread, FSOUND_SEEKCALLBACK userseek, FSOUND_TELLCALLBACK usertell); /* System information functions. */ DLL_API int F_API FSOUND_GetError(); DLL_API float F_API FSOUND_GetVersion(); DLL_API int F_API FSOUND_GetOutput(); DLL_API void * F_API FSOUND_GetOutputHandle(); DLL_API int F_API FSOUND_GetDriver(); DLL_API int F_API FSOUND_GetMixer(); DLL_API int F_API FSOUND_GetNumDrivers(); DLL_API signed char * F_API FSOUND_GetDriverName(int id); DLL_API signed char F_API FSOUND_GetDriverCaps(int id, unsigned int *caps); DLL_API int F_API FSOUND_GetOutputRate(); DLL_API int F_API FSOUND_GetMaxChannels(); DLL_API int F_API FSOUND_GetMaxSamples(); DLL_API int F_API FSOUND_GetSFXMasterVolume(); DLL_API int F_API FSOUND_GetNumHardwareChannels(); DLL_API int F_API FSOUND_GetChannelsPlaying(); DLL_API float F_API FSOUND_GetCPUUsage(); DLL_API void F_API FSOUND_GetMemoryStats(unsigned int *currentalloced, unsigned int *maxalloced); /* =================================== */ /* Sample management / load functions. */ /* =================================== */ /* Sample creation and management functions Note : Use FSOUND_LOADMEMORY flag with FSOUND_Sample_Load to load from memory. Use FSOUND_LOADRAW flag with FSOUND_Sample_Load to treat as as raw pcm data. */ DLL_API FSOUND_SAMPLE * F_API FSOUND_Sample_Load(int index, const char *name_or_data, unsigned int mode, int memlength); DLL_API FSOUND_SAMPLE * F_API FSOUND_Sample_Alloc(int index, int length, unsigned int mode, int deffreq, int defvol, int defpan, int defpri); DLL_API void F_API FSOUND_Sample_Free(FSOUND_SAMPLE *sptr); DLL_API signed char F_API FSOUND_Sample_Upload(FSOUND_SAMPLE *sptr, void *srcdata, unsigned int mode); DLL_API signed char F_API FSOUND_Sample_Lock(FSOUND_SAMPLE *sptr, int offset, int length, void **ptr1, void **ptr2, unsigned int *len1, unsigned int *len2); DLL_API signed char F_API FSOUND_Sample_Unlock(FSOUND_SAMPLE *sptr, void *ptr1, void *ptr2, unsigned int len1, unsigned int len2); /* Sample control functions */ DLL_API signed char F_API FSOUND_Sample_SetMode(FSOUND_SAMPLE *sptr, unsigned int mode); DLL_API signed char F_API FSOUND_Sample_SetLoopPoints(FSOUND_SAMPLE *sptr, int loopstart, int loopend); DLL_API signed char F_API FSOUND_Sample_SetDefaults(FSOUND_SAMPLE *sptr, int deffreq, int defvol, int defpan, int defpri); DLL_API signed char F_API FSOUND_Sample_SetMinMaxDistance(FSOUND_SAMPLE *sptr, float min, float max); DLL_API signed char F_API FSOUND_Sample_SetMaxPlaybacks(FSOUND_SAMPLE *sptr, int max); /* Sample information functions */ DLL_API FSOUND_SAMPLE * F_API FSOUND_Sample_Get(int sampno); DLL_API char * F_API FSOUND_Sample_GetName(FSOUND_SAMPLE *sptr); DLL_API unsigned int F_API FSOUND_Sample_GetLength(FSOUND_SAMPLE *sptr); DLL_API signed char F_API FSOUND_Sample_GetLoopPoints(FSOUND_SAMPLE *sptr, int *loopstart, int *loopend); DLL_API signed char F_API FSOUND_Sample_GetDefaults(FSOUND_SAMPLE *sptr, int *deffreq, int *defvol, int *defpan, int *defpri); DLL_API unsigned int F_API FSOUND_Sample_GetMode(FSOUND_SAMPLE *sptr); /* ============================ */ /* Channel control functions. */ /* ============================ */ /* Playing and stopping sounds. Note : Use FSOUND_FREE as the 'channel' variable, to let FMOD pick a free channel for you. Use FSOUND_ALL as the 'channel' variable to control ALL channels with one function call! */ DLL_API int F_API FSOUND_PlaySound(int channel, FSOUND_SAMPLE *sptr); DLL_API int F_API FSOUND_PlaySoundEx(int channel, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused); DLL_API signed char F_API FSOUND_StopSound(int channel); /* Functions to control playback of a channel. Note : FSOUND_ALL can be used on most of these functions as a channel value. */ DLL_API signed char F_API FSOUND_SetFrequency(int channel, int freq); DLL_API signed char F_API FSOUND_SetVolume(int channel, int vol); DLL_API signed char F_API FSOUND_SetVolumeAbsolute(int channel, int vol); DLL_API signed char F_API FSOUND_SetPan(int channel, int pan); DLL_API signed char F_API FSOUND_SetSurround(int channel, signed char surround); DLL_API signed char F_API FSOUND_SetMute(int channel, signed char mute); DLL_API signed char F_API FSOUND_SetPriority(int channel, int priority); DLL_API signed char F_API FSOUND_SetReserved(int channel, signed char reserved); DLL_API signed char F_API FSOUND_SetPaused(int channel, signed char paused); DLL_API signed char F_API FSOUND_SetLoopMode(int channel, unsigned int loopmode); DLL_API signed char F_API FSOUND_SetCurrentPosition(int channel, unsigned int offset); /* Channel information functions. */ DLL_API signed char F_API FSOUND_IsPlaying(int channel); DLL_API int F_API FSOUND_GetFrequency(int channel); DLL_API int F_API FSOUND_GetVolume(int channel); DLL_API int F_API FSOUND_GetPan(int channel); DLL_API signed char F_API FSOUND_GetSurround(int channel); DLL_API signed char F_API FSOUND_GetMute(int channel); DLL_API int F_API FSOUND_GetPriority(int channel); DLL_API signed char F_API FSOUND_GetReserved(int channel); DLL_API signed char F_API FSOUND_GetPaused(int channel); DLL_API unsigned int F_API FSOUND_GetLoopMode(int channel); DLL_API unsigned int F_API FSOUND_GetCurrentPosition(int channel); DLL_API FSOUND_SAMPLE * F_API FSOUND_GetCurrentSample(int channel); DLL_API signed char F_API FSOUND_GetCurrentLevels(int channel, float *l, float *r); /* =================== */ /* FX functions. */ /* =================== */ /* Functions to control DX8 only effects processing. - FX enabled samples can only be played once at a time, not multiple times at once. - Sounds have to be created with FSOUND_HW2D or FSOUND_HW3D for this to work. - FSOUND_INIT_ENABLEOUTPUTFX can be used to apply hardware effect processing to the global mixed output of FMOD's software channels. - FSOUND_FX_Enable returns an FX handle that you can use to alter fx parameters. - FSOUND_FX_Enable can be called multiple times in a row, even on the same FX type, it will return a unique handle for each FX. - FSOUND_FX_Enable cannot be called if the sound is playing or locked. - FSOUND_FX_Disable must be called to reset/clear the FX from a channel. */ DLL_API int F_API FSOUND_FX_Enable(int channel, unsigned int fx); /* See FSOUND_FX_MODES */ DLL_API signed char F_API FSOUND_FX_Disable(int channel); DLL_API signed char F_API FSOUND_FX_SetChorus(int fxid, float WetDryMix, float Depth, float Feedback, float Frequency, int Waveform, float Delay, int Phase); DLL_API signed char F_API FSOUND_FX_SetCompressor(int fxid, float Gain, float Attack, float Release, float Threshold, float Ratio, float Predelay); DLL_API signed char F_API FSOUND_FX_SetDistortion(int fxid, float Gain, float Edge, float PostEQCenterFrequency, float PostEQBandwidth, float PreLowpassCutoff); DLL_API signed char F_API FSOUND_FX_SetEcho(int fxid, float WetDryMix, float Feedback, float LeftDelay, float RightDelay, int PanDelay); DLL_API signed char F_API FSOUND_FX_SetFlanger(int fxid, float WetDryMix, float Depth, float Feedback, float Frequency, int Waveform, float Delay, int Phase); DLL_API signed char F_API FSOUND_FX_SetGargle(int fxid, int RateHz, int WaveShape); DLL_API signed char F_API FSOUND_FX_SetI3DL2Reverb(int fxid, int Room, int RoomHF, float RoomRolloffFactor, float DecayTime, float DecayHFRatio, int Reflections, float ReflectionsDelay, int Reverb, float ReverbDelay, float Diffusion, float Density, float HFReference); DLL_API signed char F_API FSOUND_FX_SetParamEQ(int fxid, float Center, float Bandwidth, float Gain); DLL_API signed char F_API FSOUND_FX_SetWavesReverb(int fxid, float InGain, float ReverbMix, float ReverbTime, float HighFreqRTRatio); /* =================== */ /* 3D sound functions. */ /* =================== */ /* See also FSOUND_Sample_SetMinMaxDistance (above) */ DLL_API void F_API FSOUND_3D_Update(); /* you must call this once a frame */ DLL_API signed char F_API FSOUND_3D_SetAttributes(int channel, float *pos, float *vel); DLL_API signed char F_API FSOUND_3D_GetAttributes(int channel, float *pos, float *vel); DLL_API void F_API FSOUND_3D_Listener_SetAttributes(float *pos, float *vel, float fx, float fy, float fz, float tx, float ty, float tz); DLL_API void F_API FSOUND_3D_Listener_GetAttributes(float *pos, float *vel, float *fx, float *fy, float *fz, float *tx, float *ty, float *tz); DLL_API void F_API FSOUND_3D_Listener_SetDopplerFactor(float scale); DLL_API void F_API FSOUND_3D_Listener_SetDistanceFactor(float scale); DLL_API void F_API FSOUND_3D_Listener_SetRolloffFactor(float scale); /* ========================= */ /* File Streaming functions. */ /* ========================= */ /* Note : Use FSOUND_LOADMEMORY flag with FSOUND_Stream_OpenFile to stream from memory. Use FSOUND_LOADRAW flag with FSOUND_Stream_OpenFile to treat stream as raw pcm data. Use FSOUND_MPEGACCURATE flag with FSOUND_Stream_OpenFile to open mpegs in 'accurate mode' for settime/gettime/getlengthms. Use FSOUND_FREE as the 'channel' variable, to let FMOD pick a free channel for you. */ DLL_API signed char F_API FSOUND_Stream_SetBufferSize(int ms); /* call this before opening streams, not after */ DLL_API FSOUND_STREAM * F_API FSOUND_Stream_OpenFile(const char *filename, unsigned int mode, int memlength); DLL_API FSOUND_STREAM * F_API FSOUND_Stream_Create(FSOUND_STREAMCALLBACK callback, int length, unsigned int mode, int samplerate, int userdata); DLL_API int F_API FSOUND_Stream_Play(int channel, FSOUND_STREAM *stream); DLL_API int F_API FSOUND_Stream_PlayEx(int channel, FSOUND_STREAM *stream, FSOUND_DSPUNIT *dsp, signed char startpaused); DLL_API signed char F_API FSOUND_Stream_Stop(FSOUND_STREAM *stream); DLL_API signed char F_API FSOUND_Stream_Close(FSOUND_STREAM *stream); DLL_API signed char F_API FSOUND_Stream_SetEndCallback(FSOUND_STREAM *stream, FSOUND_STREAMCALLBACK callback, int userdata); DLL_API signed char F_API FSOUND_Stream_SetSynchCallback(FSOUND_STREAM *stream, FSOUND_STREAMCALLBACK callback, int userdata); DLL_API FSOUND_SAMPLE * F_API FSOUND_Stream_GetSample(FSOUND_STREAM *stream); /* every stream contains a sample to playback on */ DLL_API FSOUND_DSPUNIT *F_API FSOUND_Stream_CreateDSP(FSOUND_STREAM *stream, FSOUND_DSPCALLBACK callback, int priority, int param); DLL_API signed char F_API FSOUND_Stream_SetPosition(FSOUND_STREAM *stream, unsigned int position); DLL_API unsigned int F_API FSOUND_Stream_GetPosition(FSOUND_STREAM *stream); DLL_API signed char F_API FSOUND_Stream_SetTime(FSOUND_STREAM *stream, int ms); DLL_API int F_API FSOUND_Stream_GetTime(FSOUND_STREAM *stream); DLL_API int F_API FSOUND_Stream_GetLength(FSOUND_STREAM *stream); DLL_API int F_API FSOUND_Stream_GetLengthMs(FSOUND_STREAM *stream); /* =================== */ /* CD audio functions. */ /* =================== */ /* Note : 0 = default cdrom. Otherwise specify the drive letter, for example. 'D'. */ DLL_API signed char F_API FSOUND_CD_Play(char drive, int track); DLL_API void F_API FSOUND_CD_SetPlayMode(char drive, signed char mode); DLL_API signed char F_API FSOUND_CD_Stop(char drive); DLL_API signed char F_API FSOUND_CD_SetPaused(char drive, signed char paused); DLL_API signed char F_API FSOUND_CD_SetVolume(char drive, int volume); DLL_API signed char F_API FSOUND_CD_Eject(char drive); DLL_API signed char F_API FSOUND_CD_GetPaused(char drive); DLL_API int F_API FSOUND_CD_GetTrack(char drive); DLL_API int F_API FSOUND_CD_GetNumTracks(char drive); DLL_API int F_API FSOUND_CD_GetVolume(char drive); DLL_API int F_API FSOUND_CD_GetTrackLength(char drive, int track); DLL_API int F_API FSOUND_CD_GetTrackTime(char drive); /* ============== */ /* DSP functions. */ /* ============== */ /* DSP Unit control and information functions. These functions allow you access to the mixed stream that FMOD uses to play back sound on. */ DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_Create(FSOUND_DSPCALLBACK callback, int priority, int param); DLL_API void F_API FSOUND_DSP_Free(FSOUND_DSPUNIT *unit); DLL_API void F_API FSOUND_DSP_SetPriority(FSOUND_DSPUNIT *unit, int priority); DLL_API int F_API FSOUND_DSP_GetPriority(FSOUND_DSPUNIT *unit); DLL_API void F_API FSOUND_DSP_SetActive(FSOUND_DSPUNIT *unit, signed char active); DLL_API signed char F_API FSOUND_DSP_GetActive(FSOUND_DSPUNIT *unit); /* Functions to get hold of FSOUND 'system DSP unit' handles. */ DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_GetClearUnit(); DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_GetSFXUnit(); DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_GetMusicUnit(); DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_GetFFTUnit(); DLL_API FSOUND_DSPUNIT *F_API FSOUND_DSP_GetClipAndCopyUnit(); /* Miscellaneous DSP functions Note for the spectrum analysis function to work, you have to enable the FFT DSP unit with the following code FSOUND_DSP_SetActive(FSOUND_DSP_GetFFTUnit(), TRUE); It is off by default to save cpu usage. */ DLL_API signed char F_API FSOUND_DSP_MixBuffers(void *destbuffer, void *srcbuffer, int len, int freq, int vol, int pan, unsigned int mode); DLL_API void F_API FSOUND_DSP_ClearMixBuffer(); DLL_API int F_API FSOUND_DSP_GetBufferLength(); /* Length of each DSP update */ DLL_API int F_API FSOUND_DSP_GetBufferLengthTotal(); /* Total buffer length due to FSOUND_SetBufferSize */ DLL_API float * F_API FSOUND_DSP_GetSpectrum(); /* Array of 512 floats - call FSOUND_DSP_SetActive(FSOUND_DSP_GetFFTUnit(), TRUE)) for this to work. */ /* ========================================================================== */ /* Reverb functions. (eax2/eax3 reverb) (NOT SUPPORTED IN LINUX/CE) */ /* ========================================================================== */ /* See top of file for definitions and information on the reverb parameters. */ DLL_API signed char F_API FSOUND_Reverb_SetProperties(FSOUND_REVERB_PROPERTIES *prop); DLL_API signed char F_API FSOUND_Reverb_GetProperties(FSOUND_REVERB_PROPERTIES *prop); DLL_API signed char F_API FSOUND_Reverb_SetChannelProperties(int channel, FSOUND_REVERB_CHANNELPROPERTIES *prop); DLL_API signed char F_API FSOUND_Reverb_GetChannelProperties(int channel, FSOUND_REVERB_CHANNELPROPERTIES *prop); /* ================================================ */ /* Recording functions (NOT SUPPORTED IN LINUX/MAC) */ /* ================================================ */ /* Recording initialization functions */ DLL_API signed char F_API FSOUND_Record_SetDriver(int outputtype); DLL_API int F_API FSOUND_Record_GetNumDrivers(); DLL_API signed char * F_API FSOUND_Record_GetDriverName(int id); DLL_API int F_API FSOUND_Record_GetDriver(); /* Recording functionality. Only one recording session will work at a time. */ DLL_API signed char F_API FSOUND_Record_StartSample(FSOUND_SAMPLE *sptr, signed char loop); DLL_API signed char F_API FSOUND_Record_Stop(); DLL_API int F_API FSOUND_Record_GetPosition(); /* ========================================================================================== */ /* FMUSIC API (MOD,S3M,XM,IT,MIDI PLAYBACK) */ /* ========================================================================================== */ /* Song management / playback functions. */ DLL_API FMUSIC_MODULE * F_API FMUSIC_LoadSong(const char *name); DLL_API FMUSIC_MODULE * F_API FMUSIC_LoadSongMemory(void *data, int length); DLL_API signed char F_API FMUSIC_FreeSong(FMUSIC_MODULE *mod); DLL_API signed char F_API FMUSIC_PlaySong(FMUSIC_MODULE *mod); DLL_API signed char F_API FMUSIC_StopSong(FMUSIC_MODULE *mod); DLL_API void F_API FMUSIC_StopAllSongs(); DLL_API signed char F_API FMUSIC_SetZxxCallback(FMUSIC_MODULE *mod, FMUSIC_CALLBACK callback); DLL_API signed char F_API FMUSIC_SetRowCallback(FMUSIC_MODULE *mod, FMUSIC_CALLBACK callback, int rowstep); DLL_API signed char F_API FMUSIC_SetOrderCallback(FMUSIC_MODULE *mod, FMUSIC_CALLBACK callback, int orderstep); DLL_API signed char F_API FMUSIC_SetInstCallback(FMUSIC_MODULE *mod, FMUSIC_CALLBACK callback, int instrument); DLL_API signed char F_API FMUSIC_SetSample(FMUSIC_MODULE *mod, int sampno, FSOUND_SAMPLE *sptr); DLL_API signed char F_API FMUSIC_OptimizeChannels(FMUSIC_MODULE *mod, int maxchannels, int minvolume); /* Runtime song functions. */ DLL_API signed char F_API FMUSIC_SetReverb(signed char reverb); /* MIDI only */ DLL_API signed char F_API FMUSIC_SetLooping(FMUSIC_MODULE *mod, signed char looping); DLL_API signed char F_API FMUSIC_SetOrder(FMUSIC_MODULE *mod, int order); DLL_API signed char F_API FMUSIC_SetPaused(FMUSIC_MODULE *mod, signed char pause); DLL_API signed char F_API FMUSIC_SetMasterVolume(FMUSIC_MODULE *mod, int volume); DLL_API signed char F_API FMUSIC_SetMasterSpeed(FMUSIC_MODULE *mode, float speed); DLL_API signed char F_API FMUSIC_SetPanSeperation(FMUSIC_MODULE *mod, float pansep); /* Static song information functions. */ DLL_API char * F_API FMUSIC_GetName(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetType(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetNumOrders(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetNumPatterns(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetNumInstruments(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetNumSamples(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetNumChannels(FMUSIC_MODULE *mod); DLL_API FSOUND_SAMPLE * F_API FMUSIC_GetSample(FMUSIC_MODULE *mod, int sampno); DLL_API int F_API FMUSIC_GetPatternLength(FMUSIC_MODULE *mod, int orderno); /* Runtime song information. */ DLL_API signed char F_API FMUSIC_IsFinished(FMUSIC_MODULE *mod); DLL_API signed char F_API FMUSIC_IsPlaying(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetMasterVolume(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetGlobalVolume(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetOrder(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetPattern(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetSpeed(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetBPM(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetRow(FMUSIC_MODULE *mod); DLL_API signed char F_API FMUSIC_GetPaused(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetTime(FMUSIC_MODULE *mod); DLL_API int F_API FMUSIC_GetRealChannel(FMUSIC_MODULE *mod, int modchannel); #ifdef __cplusplus } #endif #endif
[ [ [ 1, 1063 ] ] ]
dc03c2081ab6af470e19df18e8e5a4f7c8096d64
0b66a94448cb545504692eafa3a32f435cdf92fa
/branches/nn/cbear.berlios.de/base/abs.hpp
388ca717df88ba88386aee09d7619d33431448a7
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
238
hpp
#ifndef CBEAR_BERLIOS_DE_BASE_ABS_HPP_INCLUDED #define CBEAR_BERLIOS_DE_BASE_ABS_HPP_INCLUDED namespace cbear_berlios_de { namespace base { template<class T> T abs(T const &x) { return x < T() ? -x: x; } } } #endif
[ "nn0@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 18 ] ] ]
bd55047f850c5439950a732bf0ff69278330a8be
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/tecmo16.h
1e594494341288026cfb1137559ca8950771f996
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
h
class tecmo16_state : public driver_device { public: tecmo16_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } UINT16 *m_videoram; UINT16 *m_colorram; UINT16 *m_videoram2; UINT16 *m_colorram2; UINT16 *m_charram; tilemap_t *m_fg_tilemap; tilemap_t *m_bg_tilemap; tilemap_t *m_tx_tilemap; bitmap_t *m_sprite_bitmap; bitmap_t *m_tile_bitmap_bg; bitmap_t *m_tile_bitmap_fg; int m_flipscreen; int m_game_is_riot; UINT16 m_scroll_x_w; UINT16 m_scroll_y_w; UINT16 m_scroll2_x_w; UINT16 m_scroll2_y_w; UINT16 m_scroll_char_x_w; UINT16 m_scroll_char_y_w; UINT16 *m_spriteram; size_t m_spriteram_size; }; /*----------- defined in video/tecmo16.c -----------*/ WRITE16_HANDLER( tecmo16_videoram_w ); WRITE16_HANDLER( tecmo16_colorram_w ); WRITE16_HANDLER( tecmo16_videoram2_w ); WRITE16_HANDLER( tecmo16_colorram2_w ); WRITE16_HANDLER( tecmo16_charram_w ); WRITE16_HANDLER( tecmo16_flipscreen_w ); WRITE16_HANDLER( tecmo16_scroll_x_w ); WRITE16_HANDLER( tecmo16_scroll_y_w ); WRITE16_HANDLER( tecmo16_scroll2_x_w ); WRITE16_HANDLER( tecmo16_scroll2_y_w ); WRITE16_HANDLER( tecmo16_scroll_char_x_w ); WRITE16_HANDLER( tecmo16_scroll_char_y_w ); VIDEO_START( fstarfrc ); VIDEO_START( ginkun ); VIDEO_START( riot ); SCREEN_UPDATE( tecmo16 );
[ "Mike@localhost" ]
[ [ [ 1, 50 ] ] ]
6acc311eead63379110896b1443260dc5bcf96e2
e3f4283e488dabbc45cbeeb6309503f8334571e9
/I2C/I2CProtocol.cpp
221fbeb155f3993c3d452a369e94819fa80aa06d
[]
no_license
igouss/RobotProto
139a81fe4fc2faa9b3520749bf9bf716c6de3264
74833be50b68eb7dc27ec2e60ef9cfa9cb128064
refs/heads/master
2021-01-17T06:33:41.452786
2011-09-10T01:43:01
2011-09-10T01:43:01
2,166,120
0
0
null
null
null
null
UTF-8
C++
false
false
12,376
cpp
/* I2C.cpp - I2C library Copyright (c) 2011 Wayne Truchsess. All right reserved. Rev 1.0 - August 8th, 2011 This is a modified version of the Arduino Wire/TWI library. Functions were rewritten to provide more functionality and also the use of Repeated Start. Some I2C devices will not function correctly without the use of a Repeated Start. The initial version of this library only supports the Master. 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 */ #include "WProgram.h" #include "I2CProtocol.h" uint8_t I2CProtocol::bytesAvailable = 0; uint8_t I2CProtocol::bufferIndex = 0; uint8_t I2CProtocol::totalBytes = 0; I2CProtocol::I2CProtocol() { } ////////////// Public Methods //////////////////////////////////////// void I2CProtocol::begin() { #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__) // activate internal pull-ups for twi // as per note from atmega8 manual pg167 sbi(PORTC, 4); sbi(PORTC, 5); #else // activate internal pull-ups for twi // as per note from atmega128 manual pg204 sbi(PORTD, 0); sbi(PORTD, 1); #endif // initialize twi prescaler and bit rate cbi(TWSR, TWPS0); cbi(TWSR, TWPS1); TWBR = ((CPU_FREQ / 100000) - 16) / 2; // enable twi module, acks, and twi interrupt TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA); } void I2CProtocol::end() { TWCR = 0; } void I2CProtocol::setSpeed(boolean _fast) { if(!_fast) { TWBR = ((CPU_FREQ / 100000) - 16) / 2; } else { TWBR = ((CPU_FREQ / 400000) - 16) / 2; } } void I2CProtocol::pullup(boolean activate) { if(activate) { #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__) // activate internal pull-ups for twi // as per note from atmega8 manual pg167 sbi(PORTC, 4); sbi(PORTC, 5); #else // activate internal pull-ups for twi // as per note from atmega128 manual pg204 sbi(PORTD, 0); sbi(PORTD, 1); #endif } else { #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__) // deactivate internal pull-ups for twi // as per note from atmega8 manual pg167 cbi(PORTC, 4); cbi(PORTC, 5); #else // deactivate internal pull-ups for twi // as per note from atmega128 manual pg204 cbi(PORTD, 0); cbi(PORTD, 1); #endif } } /////////////carry over from Wire library /////////// uint8_t I2CProtocol::beginTransmission(uint8_t address) { returnStatusWire = 0; returnStatus = 0; returnStatus = start(); returnStatusWire = returnStatus; if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); returnStatusWire = returnStatus; return(returnStatus); } uint8_t I2CProtocol::beginTransmission(int address) { return(beginTransmission((uint8_t) address)); } uint8_t I2CProtocol::send(uint8_t data) { if(returnStatusWire) { return(returnStatusWire); } returnStatus = 0; returnStatus = sendByte(data); returnStatusWire = returnStatus; return(returnStatus); } uint8_t I2CProtocol::send(int data) { return(send((uint8_t) data)); } uint8_t I2CProtocol::endTransmission() { stop(); return(returnStatusWire); } uint8_t I2CProtocol::requestFrom(int address, int numberBytes) { return(requestFrom((uint8_t) address, (uint8_t) numberBytes)); } uint8_t I2CProtocol::requestFrom(uint8_t address, uint8_t numberBytes) { returnStatus = 0; returnStatus = read(address,numberBytes); if(!returnStatus) { return(numberBytes); } return(0); } uint8_t I2CProtocol::available() { return(bytesAvailable); } uint8_t I2CProtocol::receive() { bufferIndex = totalBytes - bytesAvailable; if(!bytesAvailable) { bufferIndex = 0; return(0); } bytesAvailable--; return(data[bufferIndex]); } ///////////////////////////////////////////////////// uint8_t I2CProtocol::write(uint8_t address, uint8_t registerAddress) { returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); if(returnStatus){return(returnStatus);} returnStatus = sendByte(registerAddress); if(returnStatus){return(returnStatus);} stop(); return(returnStatus); } uint8_t I2CProtocol::write(int address, int registerAddress) { return(write((uint8_t) address, (uint8_t) registerAddress)); } uint8_t I2CProtocol::write(uint8_t address, uint8_t registerAddress, uint8_t data) { returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); if(returnStatus){return(returnStatus);} returnStatus = sendByte(registerAddress); if(returnStatus){return(returnStatus);} returnStatus = sendByte(data); if(returnStatus){return(returnStatus);} stop(); return(returnStatus); } uint8_t I2CProtocol::write(int address, int registerAddress, int data) { return(write((uint8_t) address, (uint8_t) registerAddress, (uint8_t) data)); } uint8_t I2CProtocol::write(uint8_t address, uint8_t registerAddress, char *data) { uint8_t bufferLength = strlen(data); returnStatus = 0; returnStatus = write(address, registerAddress, (uint8_t*)data, bufferLength); return(returnStatus); } uint8_t I2CProtocol::write(uint8_t address, uint8_t registerAddress, uint8_t *data, uint8_t numberBytes) { returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); if(returnStatus){return(returnStatus);} returnStatus = sendByte(registerAddress); if(returnStatus){return(returnStatus);} for (uint8_t i = 0; i < numberBytes; i++) { returnStatus = sendByte(data[i]); if(returnStatus){return(returnStatus);} } stop(); return(returnStatus); } uint8_t I2CProtocol::read(int address, int numberBytes) { return(read((uint8_t) address, (uint8_t) numberBytes)); } uint8_t I2CProtocol::read(uint8_t address, uint8_t numberBytes) { bytesAvailable = 0; bufferIndex = 0; if(numberBytes == 0){numberBytes++;} nack = numberBytes - 1; returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_R(address)); if(returnStatus){return(returnStatus);} for(uint8_t i = 0; i < numberBytes; i++) { if( i == nack ) { returnStatus = receiveByte(0); if(returnStatus != MR_DATA_NACK){return(returnStatus);} } else { returnStatus = receiveByte(1); if(returnStatus != MR_DATA_ACK){return(returnStatus);} } data[i] = TWDR; bytesAvailable = i+1; totalBytes = i+1; } stop(); return(0); } uint8_t I2CProtocol::read(int address, int registerAddress, int numberBytes) { return(read((uint8_t) address, (uint8_t) registerAddress, (uint8_t) numberBytes)); } uint8_t I2CProtocol::read(uint8_t address, uint8_t registerAddress, uint8_t numberBytes) { bytesAvailable = 0; bufferIndex = 0; if(numberBytes == 0){numberBytes++;} nack = numberBytes - 1; returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); if(returnStatus){return(returnStatus);} returnStatus = sendByte(registerAddress); if(returnStatus){return(returnStatus);} returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_R(address)); if(returnStatus){return(returnStatus);} for(uint8_t i = 0; i < numberBytes; i++) { if( i == nack ) { returnStatus = receiveByte(0); if(returnStatus != MR_DATA_NACK){return(returnStatus);} } else { returnStatus = receiveByte(1); if(returnStatus != MR_DATA_ACK){return(returnStatus);} } data[i] = TWDR; bytesAvailable = i+1; totalBytes = i+1; } stop(); return(0); } uint8_t I2CProtocol::read(uint8_t address, uint8_t numberBytes, uint8_t *dataBuffer) { bytesAvailable = 0; bufferIndex = 0; if(numberBytes == 0){numberBytes++;} nack = numberBytes - 1; returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_R(address)); if(returnStatus){return(returnStatus);} for(uint8_t i = 0; i < numberBytes; i++) { if( i == nack ) { returnStatus = receiveByte(0); if(returnStatus != MR_DATA_NACK){return(returnStatus);} } else { returnStatus = receiveByte(1); if(returnStatus != MR_DATA_ACK){return(returnStatus);} } dataBuffer[i] = TWDR; bytesAvailable = i+1; totalBytes = i+1; } stop(); return(0); } uint8_t I2CProtocol::read(uint8_t address, uint8_t registerAddress, uint8_t numberBytes, uint8_t *dataBuffer) { bytesAvailable = 0; bufferIndex = 0; if(numberBytes == 0){numberBytes++;} nack = numberBytes - 1; returnStatus = 0; returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_W(address)); if(returnStatus){return(returnStatus);} returnStatus = sendByte(registerAddress); if(returnStatus){return(returnStatus);} returnStatus = start(); if(returnStatus){return(returnStatus);} returnStatus = sendAddress(SLA_R(address)); if(returnStatus){return(returnStatus);} for(uint8_t i = 0; i < numberBytes; i++) { if( i == nack ) { returnStatus = receiveByte(0); if(returnStatus != MR_DATA_NACK){return(returnStatus);} } else { returnStatus = receiveByte(1); if(returnStatus != MR_DATA_ACK){return(returnStatus);} } dataBuffer[i] = TWDR; bytesAvailable = i+1; totalBytes = i+1; } stop(); return(0); } /////////////// Private Methods //////////////////////////////////////// uint8_t I2CProtocol::start() { TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); while (!(TWCR & (1<<TWINT))) { } if ((TWI_STATUS == START) || (TWI_STATUS == REPEATED_START)) { return(0); } return(TWI_STATUS); } uint8_t I2CProtocol::sendAddress(uint8_t i2cAddress) { TWDR = i2cAddress; TWCR = (1<<TWINT) | (1<<TWEN); while (!(TWCR & (1<<TWINT))) { } if ((TWI_STATUS == MT_SLA_ACK) || (TWI_STATUS == MR_SLA_ACK)) { return(0); } return(TWI_STATUS); } uint8_t I2CProtocol::sendByte(uint8_t i2cData) { TWDR = i2cData; TWCR = (1<<TWINT) | (1<<TWEN); while (!(TWCR & (1<<TWINT))) { } if (TWI_STATUS == MT_DATA_ACK) { return(0); } return(TWI_STATUS); } uint8_t I2CProtocol::receiveByte(boolean ack) { if(ack) { TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA); } else { TWCR = (1<<TWINT) | (1<<TWEN); } while (!(TWCR & (1<<TWINT))) { } return(TWI_STATUS); } void I2CProtocol::stop() { TWCR = (1<<TWINT)|(1<<TWEN)| (1<<TWSTO); while ((TWCR & (1<<TWSTO))) { } } SIGNAL(TWI_vect) { switch(TWI_STATUS){ case 0x20: case 0x30: case 0x48: TWCR = (1<<TWINT)|(1<<TWEN)| (1<<TWSTO); // send a stop break; case 0x38: case 0x68: case 0x78: case 0xB0: TWCR = 0; //releases SDA and SCL lines to high impedance TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA); //reinitialize TWI break; } } I2CProtocol i2cProtocol = I2CProtocol();
[ [ [ 1, 499 ] ] ]
655a596ff8c412e72fa76f12320e479d347ff014
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/GraphStudio/GraphStudio/CJToolBarBase.h
6ec08462c4298f82c96dff3aad98611bc555ec79
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,689
h
// CJToolBarBase.h : header file // // The majority of this source was copied from MFC, Visual C++ 6, to // extend functionality to Visual C++ 5 users, with some ideas taken // from Luis Barreira's article 'Classes for new IE4 controls' // http://www.codeguru.com/controls/ie4_controls_classes.shtml // // Copyright © 1998-1999 Kirk W. Stowell // mailto:[email protected] // http://www.codejockeys.com/kstowell/ // // This source code may be used in compiled form in any way you desire. // Source file(s) may be redistributed unmodified by any means PROVIDING // they ARE NOT sold for profit without the authors expressed written // consent, and providing that this notice and the authors name and all // copyright notices remain intact. This software is by no means to be // included as part of any third party components library, or as part any // development solution that offers MFC extensions that are sold for profit. // // If the source code is used in any commercial applications then a statement // along the lines of: // // "Portions Copyright © 1998-99 Kirk Stowell" must be included in the startup // banner, "About" box or printed documentation. This software is provided // "as is" without express or implied warranty. Use it at your own risk! The // author(s) accepts no liability for any damage/loss of business that this // product may cause. // ///////////////////////////////////////////////////////////////////////////// /**************************************************************************** * * $Date: 7/25/99 12:42a $ * $Revision: 5 $ * $Archive: /CodeJockey/Include/CJToolBarBase.h $ * * $History: CJToolBarBase.h $ * * ***************** Version 5 ***************** * User: Kirk Stowell Date: 7/25/99 Time: 12:42a * Updated in $/CodeJockey/Include * * ***************** Version 4 ***************** * User: Kirk Stowell Date: 7/25/99 Time: 12:12a * Updated in $/CodeJockey/Include * * ***************** Version 3 ***************** * User: Kirk Stowell Date: 6/23/99 Time: 12:33a * Updated in $/CodeJockey/Include * * ***************** Version 2 ***************** * User: Kirk Stowell Date: 7/18/99 Time: 10:10p * Updated in $/CodeJockey/Include * Cleaned up inline functions, and import/export macro so that class will * be imported when linked to, and exported at compile time. * * ***************** Version 1 ***************** * User: Kirk Stowell Date: 7/14/99 Time: 10:29p * Created in $/CodeJockey/Include * Copied from MFC v6 and techno preview for v5. Added to extend * functionality to Visual C++ 5.0 users. * ***************************************************************************/ ///////////////////////////////////////////////////////////////////////////// #ifndef __CCJTOOLBARBASE_H__ #define __CCJTOOLBARBASE_H__ #ifdef _VC_VERSION_5 typedef struct tagAFX_OLDTOOLINFO { UINT cbSize; UINT uFlags; HWND hwnd; UINT uId; RECT rect; HINSTANCE hinst; LPTSTR lpszText; } AFX_OLDTOOLINFO; #define CBRS_GRIPPER 0x00400000L #endif // _VC_VERSION_5 // CCJToolBarBase is a CControlBar derived class whis is used // by the CCJToolBar class. class CCJToolBarBase : public CControlBar { DECLARE_DYNAMIC(CCJToolBarBase) // Construction protected: CCJToolBarBase(); // Attributes // getting and setting border space void SetBorders(LPCRECT lpRect); void SetBorders(int cxLeft = 0, int cyTop = 0, int cxRight = 0, int cyBottom = 0); CRect GetBorders() const; // Implementation public: bool m_bInReBar; // true if rebar is parent. bool m_bExStyle; // true if created with the CreateEx style. virtual ~CCJToolBarBase(); virtual void DoPaint(CDC* pDC); void DrawGripper(CDC* pDC, const CRect& rect); // implementation helpers virtual LRESULT WindowProc(UINT nMsg, WPARAM wParam, LPARAM lParam); void CalcInsideRect(CRect& rect, BOOL bHorz) const; // adjusts borders etc void EraseNonClient(); void DrawBorders(CDC* pDC, CRect& rect); //{{AFX_MSG(CCJToolBarBase) afx_msg void OnPaint(); afx_msg void OnWindowPosChanging(LPWINDOWPOS lpWndPos); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // inline functions ///////////////////////////////////////////////////////////////////////////// inline void CCJToolBarBase::SetBorders(LPCRECT lpRect) { SetBorders(lpRect->left, lpRect->top, lpRect->right, lpRect->bottom); } #endif //__CCJTOOLBARBASE_H__ /////////////////////////////////////////////////////////////////////////////
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 130 ] ] ]
4e1143b129f56535cceddd5d3660d4a52c55c229
ad59241b534bd17660dfbff28cdf8145f53aac92
/CLIENT/Inventory.h
2821c40ed15cfd63dee165501a0a4e6bb4dc3ef1
[]
no_license
CromFr/CromTPS
dc0e5c42d8c37b6169e014975d9f0ca8c9d3ad1f
145ff39c2ab319e1d53e065ca8e92f137131cb38
refs/heads/master
2021-01-19T22:14:01.984408
2011-09-21T22:09:10
2011-09-21T22:09:10
2,282,991
0
0
null
null
null
null
UTF-8
C++
false
false
2,471
h
#ifndef INVENTORY_H_INCLUDED #define INVENTORY_H_INCLUDED #include "Items.h" class Inventory { public: ///Créé un inventaire par défaut (arme=pistolet, armure=ø...) Inventory(); ///Supprime tous les items de l'inventaire, en supprimant les items puis reset des pointeurs ~Inventory(); //=================================================== ///Créé un item correspondant au template dans l'inventaire ///Renvoie l'adresse de l'item créé Item::Item* AddItem(struct itTemplate Template); ///Supprime nStack items correspondant au template et était dans l'inventaire void DelItemByTemplate(struct itTemplate Template, int nStack=1); ///Supprime UN item correspondant à l'adresse donnée. ///Regarde si l'item est dans l'inventaire avant de le supprimer void DelItem(Item::Item* pItem); ///Compte le nb d'items correspondant au template dans l'inventaire int GetItemStack(struct itTemplate Template) const; ///Renvoie la position de l'item dans l'inventaire, -1 si l'item n'a pas été trouvé int GetItemRowInInventory(const Item::Item* pItem)const; ///Equippe l'item si celui ci est equippable bool EquipItem(Item::Item* pItemToEquip); ///Renvoie l'adresse de l'item qui est equippé à tel endroit Item::Item* GetEquipedItem(int nEquipmentPart) const; ///Renvoie l'adresse du 1er item de l'inventaire correspondant au template Item::Item* GetFirstItem(struct itTemplate Template) const; ///Vide l'inventaire en supprimant les items à l'interieur void Empty(); ///Liste sur la console la liste des items de l'inventaire void Display() const; ///Ouvre l'écran d'inventaire du joueur void OpenInventory(); //=================================================== private: ///Il faut IMPERATIVEMENT linker l'item à un inventaire, sinon il y a fuite de mémoire ///=====> LinkItem(CreateItem(struct itTemplate Template)); Item::Item* CreateItem(struct itTemplate Template) const; ///Lie l'item à l'inventaire et place son pointeur dans la 1ere case vide. ///Attention : N'enlève pas les autres liens déja en place /// A la suppr de l'inventaire, les items sont supprimés ! void LinkItem(Item::Item* pItem); std::vector<Item::Item*> m_pItemList; Item::Item *m_pWeaponEquipped; Item::Item *m_pArmorEquipped; }; #endif // INVENTORY_H_INCLUDED
[ [ [ 1, 81 ] ] ]
b89dd10be8edd35eaabd38d7628432f4cd11403a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/core/matcher/lookahead_matcher.hpp
de61e520861ce2c9c41ee2620a891917bdc5aae8
[ "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,928
hpp
/////////////////////////////////////////////////////////////////////////////// // lookahead_matcher.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_MATCHER_LOOKAHEAD_MATCHER_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_LOOKAHEAD_MATCHER_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/assert.hpp> #include <boost/mpl/bool.hpp> #include <boost/xpressive/detail/detail_fwd.hpp> #include <boost/xpressive/detail/core/quant_style.hpp> #include <boost/xpressive/detail/core/state.hpp> #include <boost/xpressive/detail/static/is_pure.hpp> #include <boost/xpressive/detail/utility/save_restore.hpp> #include <boost/xpressive/detail/utility/ignore_unused.hpp> namespace boost { namespace xpressive { namespace detail { /////////////////////////////////////////////////////////////////////////////// // lookahead_matcher // Xpr can be either a static_xpression, or a shared_ptr<matchable> // template<typename Xpr> struct lookahead_matcher : quant_style<quant_none, mpl::size_t<0>, is_pure<Xpr> > { lookahead_matcher(Xpr const &xpr, bool no = false, bool do_save = !is_pure<Xpr>::value) : xpr_(xpr) , not_(no) , do_save_(do_save) { } template<typename BidiIter, typename Next> bool match(state_type<BidiIter> &state, Next const &next) const { // Note that if is_pure<Xpr>::value is true, the compiler can optimize this. return is_pure<Xpr>::value || !this->do_save_ ? this->match_(state, next, mpl::true_()) : this->match_(state, next, mpl::false_()); } template<typename BidiIter, typename Next> bool match_(state_type<BidiIter> &state, Next const &next, mpl::true_) const { BidiIter const tmp = state.cur_; if(this->not_) { // negative look-ahead assertions do not trigger partial matches. save_restore<bool> partial_match(state.found_partial_match_); detail::ignore_unused(&partial_match); if(get_pointer(this->xpr_)->match(state)) { state.cur_ = tmp; return false; } else if(next.match(state)) { return true; } } else { if(!get_pointer(this->xpr_)->match(state)) { return false; } state.cur_ = tmp; if(next.match(state)) { return true; } } BOOST_ASSERT(state.cur_ == tmp); return false; } template<typename BidiIter, typename Next> bool match_(state_type<BidiIter> &state, Next const &next, mpl::false_) const { BidiIter const tmp = state.cur_; // matching xpr could produce side-effects, save state memento<BidiIter> mem = save_sub_matches(state); if(this->not_) { // negative look-ahead assertions do not trigger partial matches. save_restore<bool> partial_match(state.found_partial_match_); detail::ignore_unused(&partial_match); if(get_pointer(this->xpr_)->match(state)) { restore_sub_matches(mem, state); state.cur_ = tmp; return false; } else if(next.match(state)) { reclaim_sub_matches(mem, state); return true; } reclaim_sub_matches(mem, state); } else { if(!get_pointer(this->xpr_)->match(state)) { reclaim_sub_matches(mem, state); return false; } state.cur_ = tmp; if(next.match(state)) { reclaim_sub_matches(mem, state); return true; } restore_sub_matches(mem, state); } BOOST_ASSERT(state.cur_ == tmp); return false; } Xpr xpr_; bool not_; bool do_save_; // true if matching xpr_ could modify the sub-matches }; }}} #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 144 ] ] ]
b8ba5c8c3c2215aa6a9acea925d3275b0f850551
b236da3776ea1085448f6d8669e1f36189ad3a3b
/public-ro/mlc/src/dusememptyerrtab.cpp
9e960c5c3b469ebd3d8ea484cf3632ad4036d312
[]
no_license
jirihelmich/mlaskal
f79a9461b9bbf00d0c9c8682ac52811e397a0c5d
702cb0e1e81dc3524719d361ba48e7ec9e68cf91
refs/heads/master
2021-01-13T01:40:09.443603
2010-12-14T18:33:02
2010-12-14T18:33:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
/* DUSEMEMPTYERRTAB.CPP JY Empty semantic error table */ #include "duerr.h" using namespace mlaskal; using namespace mlc; namespace { errs sem_errors_int_[] = { { DUSEMERR_NOERROR, DUERRT_VOID, 0 }, }; } namespace mlc { carray<errs> sem_errors(sem_errors_int_); }
[ [ [ 1, 28 ] ] ]
132b9d2962163f2e9857da8ad35dc2197af7cd32
fe202e665e666decce19b2c4c2840d03903f357f
/VideoSpring/VideoSpring/Player.h
2f90c1077a668391fedc6e2a39706d419bf9a7aa
[]
no_license
woodcom/videospring
e038ee9aa67d4a38566a2d9740773c07e6882c95
04b08649da189fe6f093b944e5f70eace4fee416
refs/heads/master
2021-01-01T06:45:15.377090
2010-11-10T04:10:35
2010-11-10T04:10:35
33,705,206
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
h
#ifndef H_PLAYER #define H_PLAYER #include <atlbase.h> #include <DShow.h> #include <d3d9.h> #include <vmr9.h> // {34C5751E-A6E1-4A6A-895E-BC4797001848} DEFINE_GUID(CLSID_VideoSpringRecv, 0x34c5751e, 0xa6e1, 0x4a6a, 0x89, 0x5e, 0xbc, 0x47, 0x97, 0x0, 0x18, 0x48); // {270C94BC-49A7-4C33-ACEA-3211F3C6873B} DEFINE_GUID(IID_IVideoSpringRecv, 0x270c94bc, 0x49a7, 0x4c33, 0xac, 0xea, 0x32, 0x11, 0xf3, 0xc6, 0x87, 0x3b); interface IVideoSpringRecv : public IUnknown { STDMETHOD(SetServerSocket)(SOCKET s) = 0; STDMETHOD(SetPresenterId)(long id) = 0; virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { return -1; } virtual ULONG STDMETHODCALLTYPE AddRef() { return -1; } virtual ULONG STDMETHODCALLTYPE Release() { return -1; } }; class Player { private: CComPtr<IGraphBuilder> graph; CComPtr<IMediaControl> control; CComPtr<IMediaEvent> event; CComPtr<IVideoWindow> video; SOCKET server; long presenterId; int createGraph(); int runGraph(); public: Player(unsigned long ip, long id); ~Player(); }; #endif
[ "[email protected]@97fa9fb9-d99c-c0a3-0dfb-269dd1aed276", "[email protected]@97fa9fb9-d99c-c0a3-0dfb-269dd1aed276" ]
[ [ [ 1, 3 ], [ 25, 40 ], [ 42, 44 ] ], [ [ 4, 24 ], [ 41, 41 ] ] ]
a50ae534302ea930d501b04613782f14b5247ece
7f980896deef4d39fc88627f98f3cba8fa4c3e37
/src/st.h
114e794344ee1632ac3d23c1a9bef744f651c4ce
[ "MIT" ]
permissive
mshogin/node-occi
226ede27d1b355530312cd4841fc6dae4c96c50a
ad0a7b33854e7005ba8af57f7acb92f5c0192155
refs/heads/master
2020-04-06T04:41:06.842206
2011-08-26T13:41:53
2011-08-26T13:41:53
2,211,402
1
0
null
null
null
null
UTF-8
C++
false
false
1,005
h
/*! * Copyright by Shogin Michael * See contributors list in README */ #pragma once #ifndef H_NODE_OCCI_ST #define H_NODE_OCCI_ST #include <v8.h> #include <node.h> #include <node_events.h> #include "occi.h" using namespace v8; using namespace oracle::occi; class st : public node::EventEmitter { public: Statement *_stmt; st(); ~st(); static Persistent<FunctionTemplate> persistent_function_template; static void Init(Handle<Object> target); static Handle<Value> Bind_Param(const v8::Arguments& args); static Handle<Value> Bind_Param_InOut(const v8::Arguments& args); static Handle<Value> Execute(const v8::Arguments& args); static Handle<Value> Get_Cursor(const v8::Arguments& args); static Handle<Value> Get_Clob(const v8::Arguments& args); static Handle<Value> Get_String(const v8::Arguments& args); protected: static Handle<Value> New(const Arguments& args); }; #endif // SRC_ORACLE_ST_H_
[ [ [ 1, 48 ] ] ]
2da9e72568d4c19c0adab4c8bbf9b63f151dbe34
1eb8863bc5f0ce755c55e6bf89768574e34cfece
/GPGPU_Segment/src/Electrostatics.cpp
24340d4e1053a1431d972ef92498cd885f254850
[]
no_license
jmainpri/electromag-with-cuda
a6699c1df6197f1bfdcc828c5e1f4e33f8643329
cd19c87ffb9d8f7d8e49cc5f21823363a51db871
refs/heads/master
2021-01-10T09:50:56.361062
2011-09-11T09:15:36
2011-09-11T09:15:36
43,094,533
0
2
null
null
null
null
UTF-8
C++
false
false
2,237
cpp
/* * Copyright (C) 2010 - Alexandru Gagniuc - <[email protected]> * This file is part of ElectroMag. * * ElectroMag 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. * * ElectroMag 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 ElectroMag. If not, see <http://www.gnu.org/licenses/>. */ #include "CL_Electrostatics.hpp" /* ***************************************************************************** * Define specializations of the field function that call the generic template * These guarantee that the specializations will be compiled and included in the * export library ******************************************************************************/ using electro::pointCharge; int CalcField(Array<Vector3<float> >& fieldLines, Array<pointCharge<float> >& pointCharges, size_t n, float resolution, perfPacket& perfData, bool useCurvature) { return -1; } int CalcField(Array<Vector3<double> >& fieldLines, Array<pointCharge<double> >& pointCharges, size_t n, double resolution, perfPacket& perfData, bool useCurvature) { return -1; } #include <iostream> using std::cout; using std::endl; void TestCL(Vector3<Array<float> >& fieldLines, Array<pointCharge<float> >& pointCharges, size_t n, float resolution, perfPacket& perfData, bool useCurvature) { CLElectrosFunctor<float>::BindDataParams dataParams = {&fieldLines, &pointCharges, n, resolution, perfData, useCurvature}; cout<<"TestCL: Binding data"<<endl; CLtest.BindData((void*) &dataParams); cout<<"TestCL: Starting run"<<endl; CLtest.Run(); cout<<"TestCL: done"<<endl; }
[ "mr.nuke.me@8eae5a90-4648-11de-84a6-839b6ed6c72e", "[email protected]" ]
[ [ [ 1, 33 ], [ 35, 41 ], [ 43, 62 ] ], [ [ 34, 34 ], [ 42, 42 ] ] ]
76cfad03e103556f284b6dc4745511da2226148f
c6f4fe2766815616b37beccf07db82c0da27e6c1
/OutletMgr.h
67321c2136c724515e0d6f48deb1f2069db37626
[]
no_license
fragoulis/gpm-sem1-spacegame
c600f300046c054f7ab3cbf7193ccaad1503ca09
85bdfb5b62e2964588f41d03a295b2431ff9689f
refs/heads/master
2023-06-09T03:43:53.175249
2007-12-13T03:03:30
2007-12-13T03:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#pragma once #include <list> #include "Object.h" using namespace std; using tlib::Object; class Tile3d; class Outlet; typedef list<Outlet*> OutletList; /** * This class should actually be a singleton but there would * be implications given the fact that it already inherits from * Object. * To get around this we declare the date we care for as static */ class OutletMgr : public Object { private: static OutletList m_vOutlets; public: /** * Initializes the object */ void init(); /** * Renders all the Outlets in the game */ void render(); /** * Updates the animations for all Outlets * Note: this has no overhead [except of course of the function call] * unless the animation is actually running */ void update(); static Outlet* add( Tile3d *oTile ); }; // end of OutletMgr class
[ "john.fragkoulis@201bd241-053d-0410-948a-418211174e54" ]
[ [ [ 1, 42 ] ] ]
2287520a2384e0f15821744e85cea29cee35fb51
986d745d6a1653d73a497c1adbdc26d9bef48dba
/oldnewthing/079_scratch.cpp
f70329a3faf4e4288a8a7506715a36b46f72b50e
[]
no_license
AnarNFT/books-code
879f75327c1dad47a13f9c5d71a96d69d3cc7d3c
66750c2446477ac55da49ade229c21dd46dffa99
refs/heads/master
2021-01-20T23:40:30.826848
2011-01-17T11:14:34
2011-01-17T11:14:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,940
cpp
#define STRICT #include <windows.h> #include <windowsx.h> #include <ole2.h> #include <commctrl.h> #include <shlwapi.h> HINSTANCE g_hinst; /* This application's HINSTANCE */ HWND g_hwndChild; /* Optional child window */ void OnSize(HWND hwnd, UINT state, int cx, int cy) { if (g_hwndChild) { MoveWindow(g_hwndChild, 0, 0, cx, cy, TRUE); } } BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpcs) { return TRUE; } void OnDestroy(HWND hwnd) { PostQuitMessage(0); } void PaintContent(HWND hwnd, PAINTSTRUCT *pps) { } void OnPaint(HWND hwnd) { PAINTSTRUCT ps; BeginPaint(hwnd, &ps); PaintContent(hwnd, &ps); EndPaint(hwnd, &ps); } void OnPrintClient(HWND hwnd, HDC hdc) { PAINTSTRUCT ps; ps.hdc = hdc; GetClientRect(hwnd, &ps.rcPaint); ps.fErase = FALSE; PaintContent(hwnd, &ps); } LRESULT CALLBACK WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam) { switch (uiMsg) { HANDLE_MSG(hwnd, WM_CREATE, OnCreate); HANDLE_MSG(hwnd, WM_SIZE, OnSize); HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy); HANDLE_MSG(hwnd, WM_PAINT, OnPaint); case WM_PRINTCLIENT: OnPrintClient(hwnd, (HDC)wParam); return 0; } return DefWindowProc(hwnd, uiMsg, wParam, lParam); } BOOL InitApp(void) { WNDCLASS wc; wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = g_hinst; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; wc.lpszClassName = TEXT("Scratch"); if (!RegisterClass(&wc)) return FALSE; InitCommonControls(); /* In case we use a common control */ return TRUE; } int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev, LPSTR lpCmdLine, int nShowCmd) { MSG msg; HWND hwnd; g_hinst = hinst; if (!InitApp()) return 0; if (SUCCEEDED(CoInitialize(NULL))) {/* In case we use COM */ hwnd = CreateWindow( TEXT("Scratch"), /* Class Name */ TEXT("Scratch"), /* Title */ WS_OVERLAPPEDWINDOW, /* Style */ CW_USEDEFAULT, CW_USEDEFAULT, /* Position */ CW_USEDEFAULT, CW_USEDEFAULT, /* Size */ NULL, /* Parent */ NULL, /* No menu */ hinst, /* Instance */ 0); /* No special parameters */ ShowWindow(hwnd, nShowCmd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } CoUninitialize(); } return 0; }
[ [ [ 1, 125 ] ] ]
514a66dfde6d6eb767bdc7e5ad06d124be8beac7
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/qt/WebCoreSupport/InspectorClientQt.h
acd978cb9e91ef1c2ff8ec68e45e9e17549b6e27
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,712
h
/* * Copyright (C) 2007 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef InspectorClientQt_h #define InspectorClientQt_h #include "InspectorClient.h" #include "InspectorFrontendClientLocal.h" #include "OwnPtr.h" #include "PassOwnPtr.h" #include <QtCore/QString> #include <wtf/Forward.h> class QWebPage; class QWebView; namespace WebCore { class InspectorFrontendClientQt; class Node; class Page; class InspectorClientQt : public InspectorClient { public: InspectorClientQt(QWebPage*); virtual void inspectorDestroyed(); virtual void openInspectorFrontend(WebCore::InspectorController*); virtual void highlight(Node*); virtual void hideHighlight(); virtual void populateSetting(const String& key, String* value); virtual void storeSetting(const String& key, const String& value); virtual bool sendMessageToFrontend(const String&); void releaseFrontendPage(); private: QWebPage* m_inspectedWebPage; QWebPage* m_frontendWebPage; InspectorFrontendClientQt* m_frontendClient; }; class InspectorFrontendClientQt : public InspectorFrontendClientLocal { public: InspectorFrontendClientQt(QWebPage* inspectedWebPage, PassOwnPtr<QWebView> inspectorView, InspectorClientQt* inspectorClient); virtual ~InspectorFrontendClientQt(); virtual void frontendLoaded(); virtual String localizedStringsURL(); virtual String hiddenPanels(); virtual void bringToFront(); virtual void closeWindow(); virtual void disconnectFromBackend(); virtual void attachWindow(); virtual void detachWindow(); virtual void setAttachedWindowHeight(unsigned height); virtual void inspectedURLChanged(const String& newURL); void inspectorClientDestroyed(); private: void updateWindowTitle(); void destroyInspectorView(bool notifyInspectorController); QWebPage* m_inspectedWebPage; OwnPtr<QWebView> m_inspectorView; QString m_inspectedURL; bool m_destroyingInspectorView; InspectorClientQt* m_inspectorClient; }; } #endif
[ [ [ 1, 107 ] ] ]
e2e573ac311e67b175c7f901591047d7d24bbd6a
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestpreviewpopup/src/bctestpreviewpopupview.cpp
ed47a201537dd1238d41a7495224f1bc9d9f4bf9
[]
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
4,228
cpp
/* * 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: view class * */ #include <aknviewappui.h> #include "bctestpreviewpopup.hrh" #include <bctestpreviewpopup.rsg> #include "bctestpreviewpopupview.h" #include "bctestpreviewpopupcontainer.h" #include "bctestutil.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // Symbian 2nd static Constructor // --------------------------------------------------------------------------- // CBCTestPreviewPopupView* CBCTestPreviewPopupView::NewL(CBCTestUtil* aUtil) { CBCTestPreviewPopupView* self = new( ELeave ) CBCTestPreviewPopupView(); CleanupStack::PushL( self ); self->ConstructL(aUtil); CleanupStack::Pop( self ); return self; } // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::CBCTestPreviewPopupView() { } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestPreviewPopupView::ConstructL(CBCTestUtil* aUtil) { BaseConstructL( R_BCTESTPREVIEWPOPUP_VIEW ); iContainer = new( ELeave ) CBCTestPreviewPopupContainer(); iContainer->SetMopParent( this ); iContainer->ConstructL( ClientRect() ); AppUi()->AddToStackL( *this, iContainer ); iContainer->MakeVisible( ETrue ); iTestUtil = aUtil; } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::~CBCTestPreviewPopupView() { if ( iContainer ) { AppUi()->RemoveFromStack( iContainer ); } delete iContainer; } // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::Id // --------------------------------------------------------------------------- // TUid CBCTestPreviewPopupView::Id() const { return KBCTestPreviewPopupViewId; } // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::DoActivateL // --------------------------------------------------------------------------- // void CBCTestPreviewPopupView::DoActivateL( const TVwsViewId&, TUid, const TDesC8& ) { } // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::DoDeactivate // --------------------------------------------------------------------------- // void CBCTestPreviewPopupView::DoDeactivate() { } // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::Container // --------------------------------------------------------------------------- // CBCTestPreviewPopupContainer* CBCTestPreviewPopupView::Container() { return iContainer; } // --------------------------------------------------------------------------- // CBCTestPreviewPopupView::HandleCommandL // --------------------------------------------------------------------------- // void CBCTestPreviewPopupView::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EProgCmdAutoTest: iTestUtil->RunL(); break; default: if ( aCommand > EBCTestCmdEmptyOutline && aCommand < EBCTestCmdMaxOutline ) { iTestUtil->RunL( aCommand ); } break; } }
[ "none@none" ]
[ [ [ 1, 134 ] ] ]
1f32f1fc3c17dcd9ac65ff9790a07cf6195fe769
6629f18d84dc8d5a310b95fedbf5be178b00da92
/SDK-2008-05-27/foobar2000/SDK/input.h
ccf54af82461fe3182762118f9fd7b6daee29fd1
[]
no_license
thenfour/WMircP
317f7b36526ebf8061753469b10f164838a0a045
ad6f4d1599fade2ae4e25656a95211e1ca70db31
refs/heads/master
2021-01-01T17:42:20.670266
2008-07-11T03:10:48
2008-07-11T03:10:48
16,931,152
3
0
null
null
null
null
UTF-8
C++
false
false
14,454
h
enum { input_flag_no_seeking = 1 << 0, input_flag_no_looping = 1 << 1, input_flag_playback = 1 << 2, input_flag_testing_integrity = 1 << 3, input_flag_allow_inaccurate_seeking = 1 << 4, input_flag_simpledecode = input_flag_no_seeking|input_flag_no_looping, }; //! Class providing interface for retrieval of information (metadata, duration, replaygain, other tech infos) from files. Also see: file_info. \n //! Instantiating: see input_entry.\n //! Implementing: see input_impl. class input_info_reader : public service_base { public: //! Retrieves count of subsongs in the file. 1 for non-multisubsong-enabled inputs. //! Note: multi-subsong handling is disabled for remote files (see: filesystem::is_remote) for performance reasons. Remote files are always assumed to be single-subsong, with null index. virtual t_uint32 get_subsong_count() = 0; //! Retrieves identifier of specified subsong; this identifier is meant to be used in playable_location as well as a parameter for input_info_reader::get_info(). //! @param p_index Index of subsong to query. Must be >=0 and < get_subsong_count(). virtual t_uint32 get_subsong(t_uint32 p_index) = 0; //! Retrieves information about specified subsong. //! @param p_subsong Identifier of the subsong to query. See: input_info_reader::get_subsong(), playable_location. //! @param p_info file_info object to fill. Must be empty on entry. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) = 0; //! Retrieves file stats. Equivalent to calling get_stats() on file object. virtual t_filestats get_file_stats(abort_callback & p_abort) = 0; FB2K_MAKE_SERVICE_INTERFACE(input_info_reader,service_base); }; //! Class providing interface for retrieval of PCM audio data from files.\n //! Instantiating: see input_entry.\n //! Implementing: see input_impl. class input_decoder : public input_info_reader { public: //! Prepares to decode specified subsong; resets playback position to the beginning of specified subsong. This must be called first, before any other input_decoder methods (other than those inherited from input_info_reader). \n //! It is legal to set initialize() more than once, with same or different subsong, to play either the same subsong again or another subsong from same file without full reopen.\n //! Warning: this interface inherits from input_info_reader, it is legal to call any input_info_reader methods even during decoding! Call order is not defined, other than initialize() requirement before calling other input_decoder methods.\n //! @param p_subsong Subsong to decode. Should always be 0 for non-multi-subsong-enabled inputs. //! @param p_flags Specifies additional hints for decoding process. It can be null, or a combination of one or more following constants: \n //! input_flag_no_seeking - Indicates that seek() will never be called. Can be used to avoid building potentially expensive seektables when only sequential reading is needed.\n //! input_flag_no_looping - Certain input implementations can be configured to utilize looping info from file formats they process and keep playing single file forever, or keep repeating it specified number of times. This flag indicates that such features should be disabled, for e.g. ReplayGain scan or conversion.\n //! input_flag_playback - Indicates that decoding process will be used for realtime playback rather than conversion. This can be used to reconfigure features that are relevant only for conversion and take a lot of resources, such as very slow secure CDDA reading. \n //! input_flag_testing_integrity - Indicates that we're testing integrity of the file. Any recoverable problems where decoding would normally continue should cause decoder to fail with exception_io_data. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) = 0; //! Reads/decodes one chunk of audio data. Use false return value to signal end of file (no more data to return). Before calling run(), decoding must be initialized by initialize() call. //! @param p_chunk audio_chunk object receiving decoded data. Contents are valid only the method returns true. //! @param p_abort abort_callback object signaling user aborting the operation. //! @returns true on success (new data decoded), false on EOF. virtual bool run(audio_chunk & p_chunk,abort_callback & p_abort) = 0; //! Seeks to specified time offset. Before seeking or other decoding calls, decoding must be initialized with initialize() call. //! @param p_seconds Time to seek to, in seconds. If p_seconds exceeds length of the object being decoded, succeed, and then return false from next run() call. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void seek(double p_seconds,abort_callback & p_abort) = 0; //! Queries whether resource being read/decoded is seekable. If p_value is set to false, all seek() calls will fail. Before calling can_seek() or other decoding calls, decoding must be initialized with initialize() call. virtual bool can_seek() = 0; //! This function is used to signal dynamic VBR bitrate, etc. Called after each run() (or not called at all if caller doesn't care about dynamic info). //! @param p_out Initially contains currently displayed info (either last get_dynamic_info result or current cached info), use this object to return changed info. //! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0. //! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed. virtual bool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) = 0; //! This function is used to signal dynamic live stream song titles etc. Called after each run() (or not called at all if caller doesn't care about dynamic info). The difference between this and get_dynamic_info() is frequency and relevance of dynamic info changes - get_dynamic_info_track() returns new info only on track change in the stream, returning new titles etc. //! @param p_out Initially contains currently displayed info (either last get_dynamic_info_track result or current cached info), use this object to return changed info. //! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0. //! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed. virtual bool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) = 0; //! Called from playback thread before sleeping. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void on_idle(abort_callback & p_abort) = 0; FB2K_MAKE_SERVICE_INTERFACE(input_decoder,input_info_reader); }; //! Class providing interface for writing metadata and replaygain info to files. Also see: file_info. \n //! Instantiating: see input_entry.\n //! Implementing: see input_impl. class input_info_writer : public input_info_reader { public: //! Tells the service to update file tags with new info for specified subsong. //! @param p_subsong Subsong to update. Should be always 0 for non-multisubsong-enabled inputs. //! @param p_info New info to write. Sometimes not all contents of p_info can be written. Caller will typically read info back after successful write, so e.g. tech infos that change with retag are properly maintained. //! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first. virtual void set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) = 0; //! Commits pending updates. In case of multisubsong inputs, set_info should queue the update and perform actual file access in commit(). Otherwise, actual writing can be done in set_info() and then Commit() can just do nothing and always succeed. //! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first. virtual void commit(abort_callback & p_abort) = 0; FB2K_MAKE_SERVICE_INTERFACE(input_info_writer,input_info_reader); }; class input_entry : public service_base { public: //! Determines whether specified content type can be handled by this input. //! @param p_type Content type string to test. virtual bool is_our_content_type(const char * p_type)=0; //! Determines whether specified file type can be handled by this input. This must not use any kind of file access; the result should be only based on file path / extension. //! @param p_full_path Full URL of file being tested. //! @param p_extension Extension of file being tested, provided by caller for performance reasons. virtual bool is_our_path(const char * p_full_path,const char * p_extension)=0; //! Opens specified resource for decoding. //! @param p_instance Receives new input_decoder instance if successful. //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). //! @param p_path URL of resource being opened. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0; //! Opens specified file for reading info. //! @param p_instance Receives new input_info_reader instance if successful. //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). //! @param p_path URL of resource being opened. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0; //! Opens specified file for writing info. //! @param p_instance Receives new input_info_writer instance if successful. //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). //! @param p_path URL of resource being opened. //! @param p_abort abort_callback object signaling user aborting the operation. virtual void open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0; //! Reserved for future use. Do nothing and return until specifications are finalized. virtual void get_extended_data(service_ptr_t<file> p_filehint,const playable_location & p_location,const GUID & p_guid,mem_block_container & p_out,abort_callback & p_abort) = 0; enum { //! Indicates that this service implements some kind of redirector that opens another input for decoding, used to avoid circular call possibility. flag_redirect = 1, //! Indicates that multi-CPU optimizations should not be used. flag_parallel_reads_slow = 2, }; //! See flag_* enums. virtual unsigned get_flags() = 0; inline bool is_redirect() {return (get_flags() & flag_redirect) != 0;} inline bool are_parallel_reads_slow() {return (get_flags() & flag_parallel_reads_slow) != 0;} static bool g_find_service_by_path(service_ptr_t<input_entry> & p_out,const char * p_path); static bool g_find_service_by_content_type(service_ptr_t<input_entry> & p_out,const char * p_content_type); static void g_open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); static void g_open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); static void g_open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); static void g_open_for_info_write_timeout(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,double p_timeout,bool p_from_redirect = false); static bool g_is_supported_path(const char * p_path); void open(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_decoding(p_instance,p_filehint,p_path,p_abort);} void open(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_read(p_instance,p_filehint,p_path,p_abort);} void open(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_write(p_instance,p_filehint,p_path,p_abort);} FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_entry); };
[ "carl@72871cd9-16e1-0310-933f-800000000000" ]
[ [ [ 1, 173 ] ] ]
fc026c542e521ee2520177386af223998f2677e9
42a799a12ffd61672ac432036b6fc8a8f3b36891
/cpp/IGC_Tron/IGC_Tron/Singleton.h
5176671276ff164428859838336774653db468e1
[]
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
ISO-8859-1
C++
false
false
742
h
// Singleton.h // Déclaration de la classe Singleton #ifndef __SINGLETON_H__ #define __SINGLETON_H__ template <typename T> class Singleton { public: // Renvoi l'instance du singleton static T *GetInstance () { if ( theSingleton == 0 ) { theSingleton = new T; } return ( static_cast<T*> ( theSingleton ) ); } // Supprime le singleton static void kill () { if ( theSingleton != 0 ) { delete theSingleton; theSingleton = 0; } } protected: // Constructeur Singleton () { } // Destructeur ~Singleton () { } private: static T *theSingleton; // Instance unique statique }; template <typename T> T *Singleton<T>::theSingleton = 0; #endif // __SINGLETON_H__
[ [ [ 1, 45 ] ] ]
33c8fb97b970ecc15bd5d1682b2fe547ee70dae0
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/validators/datatype/DatatypeValidatorFactory.cpp
ffbe7a6656e41b5d42f24634c91ba74c549ad104
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
41,127
cpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DatatypeValidatorFactory.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/datatype/DatatypeValidatorFactory.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/validators/datatype/StringDatatypeValidator.hpp> #include <xercesc/validators/datatype/BooleanDatatypeValidator.hpp> #include <xercesc/validators/datatype/DecimalDatatypeValidator.hpp> #include <xercesc/validators/datatype/HexBinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/IDDatatypeValidator.hpp> #include <xercesc/validators/datatype/IDREFDatatypeValidator.hpp> #include <xercesc/validators/datatype/NOTATIONDatatypeValidator.hpp> #include <xercesc/validators/datatype/ENTITYDatatypeValidator.hpp> #include <xercesc/validators/datatype/QNameDatatypeValidator.hpp> #include <xercesc/validators/datatype/NameDatatypeValidator.hpp> #include <xercesc/validators/datatype/NCNameDatatypeValidator.hpp> #include <xercesc/validators/datatype/ListDatatypeValidator.hpp> #include <xercesc/validators/datatype/UnionDatatypeValidator.hpp> #include <xercesc/validators/datatype/DoubleDatatypeValidator.hpp> #include <xercesc/validators/datatype/FloatDatatypeValidator.hpp> #include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp> #include <xercesc/validators/datatype/AnySimpleTypeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DateTimeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DateDatatypeValidator.hpp> #include <xercesc/validators/datatype/TimeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DayDatatypeValidator.hpp> #include <xercesc/validators/datatype/MonthDatatypeValidator.hpp> #include <xercesc/validators/datatype/MonthDayDatatypeValidator.hpp> #include <xercesc/validators/datatype/YearDatatypeValidator.hpp> #include <xercesc/validators/datatype/YearMonthDatatypeValidator.hpp> #include <xercesc/validators/datatype/DurationDatatypeValidator.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLRegisterCleanup.hpp> #include <xercesc/util/XMLInitializer.hpp> #include <xercesc/internal/XTemplateSerializer.hpp> #include <xercesc/util/HashPtr.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Local const data // --------------------------------------------------------------------------- const XMLCh fgTokPattern[] = { chBackSlash, chLatin_c, chPlus, chNull }; //E2-43 //[+\-]?[0-9]+ const XMLCh fgIntegerPattern[] = { chOpenSquare, chPlus, chBackSlash, chDash, chCloseSquare, chQuestion, chOpenSquare, chDigit_0, chDash, chDigit_9, chCloseSquare, chPlus, chNull }; //"\\i\\c*" const XMLCh fgNamePattern[] = { chBackSlash, chLatin_i, chBackSlash, chLatin_c, chAsterisk, chNull }; //"[\\i-[:]][\\c-[:]]*" const XMLCh fgNCNamePattern[] = { chOpenSquare, chBackSlash, chLatin_i, chDash, chOpenSquare, chColon, chCloseSquare, chCloseSquare, chOpenSquare, chBackSlash, chLatin_c, chDash, chOpenSquare, chColon, chCloseSquare, chCloseSquare, chAsterisk, chNull }; const XMLCh fgP0Y[] = { chLatin_P, chDigit_0, chLatin_Y, chNull }; const XMLCh fgP1Y[] = { chLatin_P, chDigit_1, chLatin_Y, chNull }; const XMLCh fgP100Y[] = { chLatin_P, chDigit_1, chDigit_0, chDigit_0, chLatin_Y, chNull }; const XMLCh fgPT24H[] = { chLatin_P, chLatin_T, chDigit_2, chDigit_4, chLatin_H, chNull }; const XMLCh fgP1M[] = { chLatin_P, chDigit_1, chLatin_M, chNull }; // --------------------------------------------------------------------------- // Local static data // --------------------------------------------------------------------------- static bool sBuiltInRegistryMutexRegistered = false; static XMLMutex* sBuiltInRegistryMutex = 0; static XMLRegisterCleanup builtInRegistryCleanup; // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Static member data // --------------------------------------------------------------------------- RefHashTableOf<DatatypeValidator>* DatatypeValidatorFactory::fBuiltInRegistry = 0; RefHashTableOf<XMLCanRepGroup>* DatatypeValidatorFactory::fCanRepRegistry = 0; // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Constructors and Destructor // --------------------------------------------------------------------------- DatatypeValidatorFactory::DatatypeValidatorFactory(MemoryManager* const manager) : fUserDefinedRegistry(0) , fMemoryManager(manager) { } DatatypeValidatorFactory::~DatatypeValidatorFactory() { cleanUp(); } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Reset methods // --------------------------------------------------------------------------- void DatatypeValidatorFactory::resetRegistry() { if (fUserDefinedRegistry != 0) { fUserDefinedRegistry->removeAll(); } } // ----------------------------------------------------------------------- // Notification that lazy data has been deleted // ----------------------------------------------------------------------- void DatatypeValidatorFactory::reinitRegistry() { delete fBuiltInRegistry; fBuiltInRegistry = 0; delete fCanRepRegistry; fCanRepRegistry = 0; // delete local static data delete sBuiltInRegistryMutex; sBuiltInRegistryMutex = 0; sBuiltInRegistryMutexRegistered = false; } void XMLInitializer::initializeDVFactory() { DatatypeValidatorFactory *dvFactory = new DatatypeValidatorFactory(); if (dvFactory) { dvFactory->expandRegistryToFullSchemaSet(); delete dvFactory; } } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Registry initialization methods // --------------------------------------------------------------------------- void DatatypeValidatorFactory::expandRegistryToFullSchemaSet() { if (!sBuiltInRegistryMutexRegistered) { if (!sBuiltInRegistryMutex) { XMLMutexLock lock(XMLPlatformUtils::fgAtomicMutex); if (!sBuiltInRegistryMutex) sBuiltInRegistryMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager); } // Use a faux scope to synchronize while we do this { XMLMutexLock lock(sBuiltInRegistryMutex); // If we got here first, then register it and set the registered flag if (!sBuiltInRegistryMutexRegistered) { //Initialize common Schema/DTD Datatype validator set fBuiltInRegistry = new RefHashTableOf<DatatypeValidator>(29); DatatypeValidator *dv = new StringDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_STRING, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_STRING, dv); dv = new NOTATIONDatatypeValidator(); dv->setTypeName(XMLUni::fgNotationString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgNotationString, dv); dv = new AnySimpleTypeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_ANYSIMPLETYPE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_ANYSIMPLETYPE, dv); dv = new BooleanDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_BOOLEAN, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_BOOLEAN, dv); dv = new DecimalDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DECIMAL, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DECIMAL, dv); dv = new HexBinaryDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_HEXBINARY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_HEXBINARY, dv); dv = new Base64BinaryDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_BASE64BINARY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_BASE64BINARY, dv); dv = new DoubleDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DOUBLE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DOUBLE, dv); dv = new FloatDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_FLOAT, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_FLOAT, dv); dv = new AnyURIDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_ANYURI, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_ANYURI, dv); dv = new QNameDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_QNAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_QNAME, dv); dv = new DateTimeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DATETIME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DATETIME, dv); dv = new DateDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DATE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DATE, dv); dv = new TimeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_TIME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_TIME, dv); dv = new DayDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DAY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DAY, dv); dv = new MonthDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_MONTH, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_MONTH, dv); dv = new MonthDayDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_MONTHDAY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_MONTHDAY, dv); dv = new YearDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_YEAR, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_YEAR, dv); dv = new YearMonthDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_YEARMONTH, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_YEARMONTH, dv); dv = new DurationDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DURATION, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DURATION, dv); // REVISIT // We are creating a lot of Hashtables for the facets of the different // validators. It's better to have some kind of a memory pool and ask // the pool to give us a new instance of the hashtable. RefHashTableOf<KVStringPair>* facets = new RefHashTableOf<KVStringPair>(3); // Create 'normalizedString' datatype validator facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_REPLACE)); createDatatypeValidator(SchemaSymbols::fgDT_NORMALIZEDSTRING, getDatatypeValidator(SchemaSymbols::fgDT_STRING), facets, 0, false, 0, false); // Create 'token' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_COLLAPSE)); createDatatypeValidator(SchemaSymbols::fgDT_TOKEN, getDatatypeValidator(SchemaSymbols::fgDT_NORMALIZEDSTRING), facets, 0, false, 0, false); dv = new NameDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_TOKEN), 0, 0, 0); dv->setTypeName(SchemaSymbols::fgDT_NAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_NAME, dv); dv = new NCNameDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NAME), 0, 0, 0); dv->setTypeName(SchemaSymbols::fgDT_NCNAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_NCNAME, dv); // Create 'NMTOKEN' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_PATTERN , new KVStringPair(SchemaSymbols::fgELT_PATTERN,fgTokPattern)); facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_COLLAPSE)); createDatatypeValidator(XMLUni::fgNmTokenString, getDatatypeValidator(SchemaSymbols::fgDT_TOKEN),facets, 0, false, 0, false); // Create 'NMTOKENS' datatype validator createDatatypeValidator(XMLUni::fgNmTokensString, getDatatypeValidator(XMLUni::fgNmTokenString), 0, 0, true, 0, false); // Create 'language' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_PATTERN, new KVStringPair(SchemaSymbols::fgELT_PATTERN, XMLUni::fgLangPattern)); createDatatypeValidator(SchemaSymbols::fgDT_LANGUAGE, getDatatypeValidator(SchemaSymbols::fgDT_TOKEN), facets, 0, false, 0, false); // Create 'integer' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_FRACTIONDIGITS, new KVStringPair(SchemaSymbols::fgELT_FRACTIONDIGITS, XMLUni::fgValueZero)); facets->put((void*) SchemaSymbols::fgELT_PATTERN, new KVStringPair(SchemaSymbols::fgELT_PATTERN, fgIntegerPattern)); createDatatypeValidator(SchemaSymbols::fgDT_INTEGER, getDatatypeValidator(SchemaSymbols::fgDT_DECIMAL), facets, 0, false, 0, false); // Create 'nonPositiveInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgValueZero)); createDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'negativeInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgNegOne)); createDatatypeValidator(SchemaSymbols::fgDT_NEGATIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER), facets, 0, false, 0, false); // Create 'long' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgLongMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgLongMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_LONG, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'int' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgIntMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgIntMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_INT, getDatatypeValidator(SchemaSymbols::fgDT_LONG), facets, 0, false, 0, false); // Create 'short' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgShortMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgShortMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_SHORT, getDatatypeValidator(SchemaSymbols::fgDT_INT), facets, 0, false, 0 ,false); // Create 'byte' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgByteMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgByteMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_BYTE, getDatatypeValidator(SchemaSymbols::fgDT_SHORT), facets, 0, false, 0, false); // Create 'nonNegativeInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgValueZero)); createDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'unsignedLong' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgULongMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_ULONG, getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), facets, 0, false, 0, false); // Create 'unsignedInt' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUIntMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_UINT, getDatatypeValidator(SchemaSymbols::fgDT_ULONG), facets, 0, false, 0, false); // Create 'unsignedShort' datatypeValidator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUShortMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_USHORT, getDatatypeValidator(SchemaSymbols::fgDT_UINT), facets, 0, false, 0, false); // Create 'unsignedByte' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUByteMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_UBYTE, getDatatypeValidator(SchemaSymbols::fgDT_USHORT), facets, 0, false, 0, false); // Create 'positiveInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgValueOne)); createDatatypeValidator(SchemaSymbols::fgDT_POSITIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), facets, 0, false, 0, false); // Create 'ID', 'IDREF' and 'ENTITY' datatype validator dv = new IDDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgIDString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgIDString, dv); dv = new IDREFDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgIDRefString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgIDRefString, dv); dv = new ENTITYDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgEntityString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgEntityString, dv); // Create 'IDREFS' datatype validator createDatatypeValidator ( XMLUni::fgIDRefsString , getDatatypeValidator(XMLUni::fgIDRefString) , 0 , 0 , true , 0 , false ); // Create 'ENTITIES' datatype validator createDatatypeValidator ( XMLUni::fgEntitiesString , getDatatypeValidator(XMLUni::fgEntityString) , 0 , 0 , true , 0 , false ); initCanRepRegistory(); // register cleanup method builtInRegistryCleanup.registerCleanup(DatatypeValidatorFactory::reinitRegistry); sBuiltInRegistryMutexRegistered = true; } } } } /*** * * For Decimal-derivated, an instance of DecimalDatatypeValidator * can be used by the primitive datatype, decimal, or any one of * the derivated datatypes, such as int, long, unsighed short, just * name a few, or any user-defined datatypes, which may derivate from * either the primitive datatype, decimal, or from any one of those * decimal derivated datatypes, or other user-defined datatypes, which * in turn, indirectly derivate from decimal or decimal-derived. * * fCanRepRegisty captures deciaml dv and its derivatives. * ***/ void DatatypeValidatorFactory::initCanRepRegistory() { /*** * key: dv * data: XMLCanRepGroup ***/ fCanRepRegistry = new RefHashTableOf<XMLCanRepGroup>(29, true, new HashPtr() ); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_DECIMAL), new XMLCanRepGroup(XMLCanRepGroup::Decimal)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_LONG), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_INT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_SHORT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_BYTE), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_POSITIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NEGATIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_ULONG), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_UINT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_USHORT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_UBYTE), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derivated_npi)); } /*** * * For any dv other than Decimaldv, return String only. * Later on if support to dv other than Decimaldv arise, we may * add them fCanRepRegistry during DatatypeValidatorFactory::initCanRepRegistory() * ***/ XMLCanRepGroup::CanRepGroup DatatypeValidatorFactory::getCanRepGroup(const DatatypeValidator* const dv) { if (!dv) return XMLCanRepGroup::String; DatatypeValidator *curdv = (DatatypeValidator*) dv; while (curdv) { if (fCanRepRegistry->containsKey(curdv)) return fCanRepRegistry->get(curdv)->getGroup(); else curdv = curdv->getBaseValidator(); } return XMLCanRepGroup::String; } DatatypeValidator* DatatypeValidatorFactory::getBuiltInBaseValidator(const DatatypeValidator* const dv) { DatatypeValidator *curdv = (DatatypeValidator*)dv; while (curdv) { if (curdv == getBuiltInRegistry()->get(curdv->getTypeLocalName())) return curdv; else curdv = curdv->getBaseValidator(); } return 0; } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: factory methods // --------------------------------------------------------------------------- DatatypeValidator* DatatypeValidatorFactory::createDatatypeValidator ( const XMLCh* const typeName , DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const bool isDerivedByList , const int finalSet , const bool isUserDefined , MemoryManager* const userManager ) { if (baseValidator == 0) { if (facets) { Janitor<KVStringPairHashTable> janFacets(facets); } if (enums) { Janitor<XMLChRefVector> janEnums(enums); } return 0; } DatatypeValidator* datatypeValidator = 0; MemoryManager* const manager = (isUserDefined) ? userManager : XMLPlatformUtils::fgMemoryManager; if (isDerivedByList) { datatypeValidator = new (manager) ListDatatypeValidator(baseValidator, facets, enums, finalSet, manager); // Set PSVI information for Ordered, Numeric, Bounded & Finite datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_FALSE); datatypeValidator->setNumeric(false); if (facets && ((facets->get(SchemaSymbols::fgELT_LENGTH) || (facets->get(SchemaSymbols::fgELT_MINLENGTH) && facets->get(SchemaSymbols::fgELT_MAXLENGTH))))) { datatypeValidator->setBounded(true); datatypeValidator->setFinite(true); } else { datatypeValidator->setBounded(false); datatypeValidator->setFinite(false); } } else { if ((baseValidator->getType() != DatatypeValidator::String) && facets) { KVStringPair* value = facets->get(SchemaSymbols::fgELT_WHITESPACE); if (value != 0) { facets->removeKey(SchemaSymbols::fgELT_WHITESPACE); } } datatypeValidator = baseValidator->newInstance ( facets , enums , finalSet , manager ); // Set PSVI information for Ordered, Numeric, Bounded & Finite datatypeValidator->setOrdered(baseValidator->getOrdered()); datatypeValidator->setNumeric(baseValidator->getNumeric()); RefHashTableOf<KVStringPair>* baseFacets = baseValidator->getFacets(); if (facets && ((facets->get(SchemaSymbols::fgELT_MININCLUSIVE) || facets->get(SchemaSymbols::fgELT_MINEXCLUSIVE) || (baseFacets && (baseFacets->get(SchemaSymbols::fgELT_MININCLUSIVE) || baseFacets->get(SchemaSymbols::fgELT_MINEXCLUSIVE))))) && (facets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || facets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE) || (baseFacets && ((baseFacets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || baseFacets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE)))))) { datatypeValidator->setBounded(true); } else { datatypeValidator->setBounded(false); } if (baseValidator->getFinite()) { datatypeValidator->setFinite(true); } else if (!facets) { datatypeValidator->setFinite(false); } else if (facets->get(SchemaSymbols::fgELT_LENGTH) || facets->get(SchemaSymbols::fgELT_MAXLENGTH) || facets->get(SchemaSymbols::fgELT_TOTALDIGITS)) { datatypeValidator->setFinite(true); } //for efficiency use this instead of rechecking... //else if ((facets->get(SchemaSymbols::fgELT_MININCLUSIVE) || facets->get(SchemaSymbols::fgELT_MINEXCLUSIVE)) && // (facets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || facets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE))) else if (datatypeValidator->getBounded() || datatypeValidator->getType() == DatatypeValidator::Date || datatypeValidator->getType() == DatatypeValidator::YearMonth || datatypeValidator->getType() == DatatypeValidator::Year || datatypeValidator->getType() == DatatypeValidator::MonthDay || datatypeValidator->getType() == DatatypeValidator::Day || datatypeValidator->getType() == DatatypeValidator::Month) { if (facets->get(SchemaSymbols::fgELT_FRACTIONDIGITS)) { datatypeValidator->setFinite(true); } else { datatypeValidator->setFinite(false); } } else { datatypeValidator->setFinite(false); } } if (datatypeValidator != 0) { if (isUserDefined) { if (!fUserDefinedRegistry) { fUserDefinedRegistry = new (userManager) RefHashTableOf<DatatypeValidator>(29, userManager); } fUserDefinedRegistry->put((void *)typeName, datatypeValidator); } else { fBuiltInRegistry->put((void *)typeName, datatypeValidator); } datatypeValidator->setTypeName(typeName); } return datatypeValidator; } static DatatypeValidator::ValidatorType getPrimitiveDV(DatatypeValidator::ValidatorType validationDV) { if (validationDV == DatatypeValidator::ID || validationDV == DatatypeValidator::IDREF || validationDV == DatatypeValidator::ENTITY) { return DatatypeValidator::String; } return validationDV; } DatatypeValidator* DatatypeValidatorFactory::createDatatypeValidator ( const XMLCh* const typeName , RefVectorOf<DatatypeValidator>* const validators , const int finalSet , const bool userDefined , MemoryManager* const userManager ) { if (validators == 0) return 0; DatatypeValidator* datatypeValidator = 0; MemoryManager* const manager = (userDefined) ? userManager : XMLPlatformUtils::fgMemoryManager; datatypeValidator = new (manager) UnionDatatypeValidator(validators, finalSet, manager); if (datatypeValidator != 0) { if (userDefined) { if (!fUserDefinedRegistry) { fUserDefinedRegistry = new (userManager) RefHashTableOf<DatatypeValidator>(29, userManager); } fUserDefinedRegistry->put((void *)typeName, datatypeValidator); } else { fBuiltInRegistry->put((void *)typeName, datatypeValidator); } datatypeValidator->setTypeName(typeName); // Set PSVI information for Ordered, Numeric, Bounded & Finite unsigned int valSize = validators->size(); if (valSize) { DatatypeValidator::ValidatorType ancestorId = getPrimitiveDV(validators->elementAt(0)->getType()); // For a union the ORDERED {value} is partial unless one of the following: // 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet. // 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false. bool allOrderedFalse = true; bool commonAnc = ancestorId != DatatypeValidator::AnySimpleType; bool allNumeric = true; bool allBounded = true; bool allFinite = true; for(unsigned int i = 0 ; (i < valSize) && (commonAnc || allOrderedFalse || allNumeric || allBounded || allFinite); i++) { // for the other member types, check whether the value is false // and whether they have the same ancestor as the first one if (commonAnc) commonAnc = ancestorId == getPrimitiveDV(validators->elementAt(i)->getType()); if (allOrderedFalse) allOrderedFalse = validators->elementAt(i)->getOrdered() == XSSimpleTypeDefinition::ORDERED_FALSE; if (allNumeric && !validators->elementAt(i)->getNumeric()) { allNumeric = false; } if (allBounded && (!validators->elementAt(i)->getBounded() || ancestorId != getPrimitiveDV(validators->elementAt(i)->getType()))) { allBounded = false; } if (allFinite && !validators->elementAt(i)->getFinite()) { allFinite = false; } } if (commonAnc) { datatypeValidator->setOrdered(validators->elementAt(0)->getOrdered()); } else if (allOrderedFalse) { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_FALSE); } else { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL); } datatypeValidator->setNumeric(allNumeric); datatypeValidator->setBounded(allBounded); datatypeValidator->setFinite(allFinite); } else // size = 0 { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL); datatypeValidator->setNumeric(true); datatypeValidator->setBounded(true); datatypeValidator->setFinite(true); } } return datatypeValidator; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(DatatypeValidatorFactory) void DatatypeValidatorFactory::serialize(XSerializeEngine& serEng) { // Need not to serialize static data member, fBuiltInRegistry if (serEng.isStoring()) { /*** * Serialize RefHashTableOf<DatatypeValidator> ***/ XTemplateSerializer::storeObject(fUserDefinedRegistry, serEng); } else { /*** * DV in the UserDefinedRegistry rely on the fBuiltInRegistry * to resolve their built-in baseValidator ***/ expandRegistryToFullSchemaSet(); /*** * Deserialize RefHashTableOf<DatatypeValidator> ***/ XTemplateSerializer::loadObject(&fUserDefinedRegistry, 29, true, serEng); } } XERCES_CPP_NAMESPACE_END /** * End of file DatatypeValidatorFactory.cpp */
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 933 ] ] ]
8f1b0cc0515e54cb7b8590cb6267b5f1f99282cc
bc6049b0c707083955c1fab5774e850ca7b351b0
/stepmania/src/ScreenGameplaySyncMachine.h
63c97da823ba2a7abed738ba3b2ba2f53925527c
[]
no_license
Jousway/stepmania-old
9ceacb25bd88e3caae3f3f69c7d591c6a4ab12d8
51576d5942ead16d2205831677cea74630c1b598
refs/heads/master
2020-04-29T20:27:30.389623
2010-01-25T07:38:23
2010-01-25T07:38:23
176,383,881
5
0
null
null
null
null
UTF-8
C++
false
false
2,060
h
/* ScreenGameplaySyncMachine - */ #ifndef ScreenGameplaySyncMachine_H #define ScreenGameplaySyncMachine_H #include "ScreenGameplayNormal.h" #include "Song.h" class ScreenGameplaySyncMachine : public ScreenGameplayNormal { public: virtual void Init(); virtual void Update( float fDelta ); virtual void Input( const InputEventPlus &input ); virtual ScreenType GetScreenType() const { return system_menu; } void HandleScreenMessage( const ScreenMessage SM ); void ResetAndRestartCurrentSong(); protected: virtual bool UseSongBackgroundAndForeground() const { return false; } void RefreshText(); Song m_Song; const Steps *m_pSteps; BitmapText m_textSyncInfo; }; #endif /* * (c) 2001-2004 Chris Danford * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
[ [ [ 1, 56 ] ] ]
1e0cbe2cf11e8ee8f929e2abd53f02bc8c2f1878
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib-test/af2-test/tutorial/tutorial_6.cpp
b2af6fb14a36dae7b78732676fb7a8026e9bb55d
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,586
cpp
#include "mglaugust2.h" class CMyFrame : public CAugustWindowFrame2 { private: CAugustImage2 m_img; CAugustKeyboardInput m_kb; // 今回新たに追加 int m_moveX; int m_moveY; public: // 初期化時に呼ばれる bool OnGraphicInitEnded() { RegistControl(&m_img); RegistControl(&m_kb); m_img.Load("test.jpg"); // キーボードイベントハンドラ登録(左) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, AGH_KEYCODE_LEFT, (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveLeft, this); // キーボードイベントハンドラ登録(右) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, AGH_KEYCODE_RIGHT, (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveRight, this); // キーボードイベントハンドラ登録(上) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, AGH_KEYCODE_UP, (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveUp, this); // キーボードイベントハンドラ登録(下) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, AGH_KEYCODE_DOWN, (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveDown, this); // キーボードイベントハンドラ登録(スペースキー) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, ' ', (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveStop, this); // キーボードイベントハンドラ登録(Zキー) m_kb.RegistHandler( CAugustKeyboardInput::ON_PRESS, 'Z', (CAugustKeyboardInput::CALLBACK_TYPE_MI)&CMyFrame::MoveToInitial, this); // move変数の初期化 m_moveX = 0; m_moveY = 0; return true; } // 各ハンドラメソッド bool MoveLeft(){ m_moveX = -1; m_moveY = 0; return true; } bool MoveRight(){ m_moveX = 1; m_moveY = 0; return true; } bool MoveUp(){ m_moveX = 0; m_moveY = -1; return true; } bool MoveDown(){ m_moveX = 0; m_moveY = 1; return true; } // 今回は以下を追加 bool MoveStop(){ m_moveX = 0; m_moveY = 0; return true; } bool MoveToInitial(){ m_img.SetPos(0,0); MoveStop(); return true; } bool OnFrameDoUser(){ m_img.Move(m_moveX, m_moveY); return true; } }; // WinMain int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { CMyFrame frame; frame.Start(); return 0; }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 119 ] ] ]
a13ce1ec7e19e4d762f4b8af1a9e3d00ba734978
2920ac8b9d3f25edf9f48cb8231d2422dffb485c
/source/code/Module.h
71d9b727bb22a08f55d9a654bddfeb538c65c01a
[]
no_license
TheBuzzSaw/legacy-dejarix
0b2e028fc6a2eeb50ed733750b0f69dab7b80d6d
0a119a465c9097f918c19153e1056ba9eabc18e7
refs/heads/master
2021-01-10T20:19:40.595842
2011-01-23T22:18:16
2011-01-23T22:18:16
41,321,281
0
0
null
null
null
null
UTF-8
C++
false
false
3,056
h
/** * This file is part of Dejarix. * * Dejarix 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. * * Dejarix 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 Dejarix. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _MODULE_H_ #define _MODULE_H_ #include <SDL.h> #include <string> class Module { public: class Exception { public: Exception(const std::string& inReason) : reason(inReason) {} const std::string reason; }; Module(); virtual ~Module(); void onEvent(SDL_Event* inEvent); inline bool isRunning() { return mRunning; }; inline bool isDead() { return mDead; } inline Module* next() { return mNextModule; } /// module operation virtual void onLoad(); virtual void onOpen(); virtual void onLoop(); virtual void onFrame(); virtual void onClose(); virtual void onUnload(); protected: bool mRunning; bool mDead; Module* mNextModule; /// input events virtual void onInputFocus(); virtual void onInputBlur(); virtual void onKeyDown(SDLKey inSym, SDLMod inMod, Uint16 inUnicode); virtual void onKeyUp(SDLKey inSym, SDLMod inMod, Uint16 inUnicode); virtual void onMouseFocus(); virtual void onMouseBlur(); virtual void onMouseMove(int inX, int inY, int inRelX, int inRelY, bool inLeft, bool inRight, bool inMiddle); virtual void onMouseWheel(bool inUp, bool inDown); virtual void onLButtonDown(int inX, int inY); virtual void onLButtonUp(int inX, int inY); virtual void onRButtonDown(int inX, int inY); virtual void onRButtonUp(int inX, int inY); virtual void onMButtonDown(int inX, int inY); virtual void onMButtonUp(int inX, int inY); virtual void onJoyAxis(Uint8 inWhich, Uint8 inAxis, Sint16 inValue); virtual void onJoyButtonDown(Uint8 inWhich, Uint8 inButton); virtual void onJoyButtonUp(Uint8 inWhich, Uint8 inButton); virtual void onJoyHat(Uint8 inWhich, Uint8 inHat, Uint8 inValue); virtual void onJoyBall(Uint8 inWhich, Uint8 inBall, Sint16 inXRel, Sint16 inYRel); virtual void onMinimize(); virtual void onRestore(); virtual void onResize(int inWidth, int inHeight); virtual void onExpose(); virtual void onExit(); virtual void onUser(Uint8 inType, int inCode, void* inData1, void* inData2); }; #endif
[ "TheBuzzSaw@35cf13a5-3602-408e-9700-a7e2e4f0c3b8" ]
[ [ [ 1, 88 ] ] ]
1b55182c7542420256e00458c8baaffabb605a8c
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/uiTipsMenu.h
ba1d4032d00a9c20acad58d4b8f67950636235b3
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
#pragma once #include <MyGUI.h> #include "BaseLayout/BaseLayout.h" namespace Kylin { ATTRIBUTE_CLASS_LAYOUT(TipsMenu, "commontips.layout"); class TipsMenu : public wraps::BaseLayout { public: TipsMenu(); KVOID Show( const MyGUI::IntPoint & _point ); KVOID Hide(); KVOID SetTitle(KCSTR& sTitle); KVOID SetContent(KCSTR& sContent); protected: ATTRIBUTE_FIELD_WIDGET_NAME(TipsMenu, m_pTitle, "title"); MyGUI::StaticText* m_pTitle; ATTRIBUTE_FIELD_WIDGET_NAME(TipsMenu, m_pContent, "content"); MyGUI::Edit* m_pContent; int mOffsetHeight; }; }
[ [ [ 1, 29 ] ] ]
8a3d4d945f067e0786a99cc01a492ab7b67daa48
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/engine/hayat.h
1c2d92ec08cd0348b4d7f208d5ebb48c473b7ece
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,701
h
/* -*- coding: sjis-dos; -*- */ /* * copyright 2010 FUKUZAWA Tadashi. All rights reserved. */ #ifndef m_HAYAT_H_ #define m_HAYAT_H_ #include "hyThreadManager.h" #include "hyVM.h" #include "hyBytecode.h" #include "hyCodeManager.h" #include "hyVarTable.h" #include "hyStringBuffer.h" #include "hyValueArray.h" #include "hyException.h" #include "hyHash.h" #include "hyStringBuffer.h" #include "hySymbolTable.h" #include "hyDebug.h" namespace Hayat { namespace Engine { // メモリ、GC等初期化 void initMemory(void* pMemory, size_t memorySize); // stdlib初期化 // バイトコードは内部で管理されるので、最後のfinalizeも内部で行なわれる void initStdlib(const char* stdlibPath = "stdlib.hyb"); // ライブラリ類バイトコード読み込み、初期化 // 戻り値はバイトコードシンボル // バイトコードは内部で管理されるので、最後のfinalizeも内部で行なわれる SymbolID_t readLibrary(const char* filename); // バイトコードの先頭から、スレッドで開始 ThreadID_t startThread(Bytecode* bytecode); // スレッド強制終了 void terminateThread(ThreadID_t tid); // 後始末 void finalizeAll(void); // デバッグメモリ初期化 void initializeDebug(void* debugMemory = NULL, size_t debugMemorySize = 0); // デバッグ後始末 void finalizeDebug(void); } } #endif /* m_HAYAT_H_ */ /********** 使用例 ******* // メモリ確保 void* pMem = OS_ALLOCATE_MEMORY(memSize); // 初期化 Hayat::Engine::initMemory(pMem, memSize); // ===={ デバッグ用設定 (この部分は呼ばなくても良い) // デバッグ情報用メモリ確保 (しなければメインメモリgMemPoolに読む) void* pDebMem = OS_ALLOCATE_MEMORY(debMemSize); initializeDebug(pDebMem, debMemSize); // ↓バイトコードのデバッグ情報(*.hdb)読み込みをオフにする場合は以下を使う // Hayat::Engine::Bytecode::setFlagReadDebugInfo(false); // デバッグ用シンボル(symbols.sym)読み込み (無くても良い) Hayat::Engine::gSymbolTable.readFile("symbols.sym"); // エラーメッセージのShift-JISバージョンを読み込み (無くても良い) MMes::readTable("mm_sjis.mm"); // ====} デバッグ用設定終わり // stdlib初期化 Hayat::Engine::initStdlib(); // それぞれのプロジェクトで必要なバイトコード読み込み // 大元を読めばrequire先は芋蔓式に自動で読み込む Hayat::Engine::readLibrary("project_library_bytecode.hyb"); // 実行したいバイトコードを読み込む Hayat::Engine::Bytecode* pBytecode = Hayat::Engine::gCodeManager.readBytecode("target.hyb"); // それをスレッドで実行開始 Hayat::Engine::ThreadID_t tid; tid = Hayat::Engine::startThread(pBytecode); // 1フレーム毎にexec1tick()を呼ぶ // while (Hayat::Engine::gThreadManager.isThreadRunning()) // Hayat::Engine::gThreadManager.exec1tick(); // 後始末 Hayat::Engine::finalizeAll(); // デバッグ後始末 (デバッグ用設定をしたならば呼ぶ) Hayat::Engine::finalizeDebug(); // デバッグ用メモリ解放 (確保したならば) OS_FREE_MEMORY(pDebMem); // メモリ解放 OS_FREE_MEMORY(pMem); ********** **********/
[ [ [ 1, 110 ] ] ]
833cc95c3741c37c7ec463717722943ad11dd50a
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/node/nmeshipol_main.cc
36a014da433a71662f0648026a44c74dec19539e
[]
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
12,379
cc
#define N_IMPLEMENTS nMeshIpol //------------------------------------------------------------------------------ // nmeshipol_main.cc // (C) 2000 RadonLabs GmbH -- A.Weissflog //------------------------------------------------------------------------------ #include "node/nmeshipol.h" #include "node/nmeshnode.h" #include "gfx/nscenegraph2.h" #include "gfx/nvertexbuffer.h" #include "gfx/nindexbuffer.h" #include "gfx/nchannelcontext.h" #include "mathlib/bbox.h" nNebulaScriptClass(nMeshIpol, "nanimnode"); //------------------------------------------------------------------------------ /** */ nMeshIpol::nMeshIpol() : update_flags(0), num_keys(0), key_array(0), in_begin_keys(false), dyn_vb(kernelServer, this) { // make sure source meshes are saved before myself this->SetFlags(N_FLAG_SAVEUPSIDEDOWN); } //------------------------------------------------------------------------------ /** */ nMeshIpol::~nMeshIpol() { if (this->key_array) { delete[] this->key_array; this->key_array = NULL; } } //------------------------------------------------------------------------------ /** Interpolate between 2 source vertex buffer, render result to target vertex buffer. @param sceneGraph pointer to scene graph object @param l lerp value (between 0.0 and 1.0) @param vb0 first source vertex buffer @param vb1 second source vertex buffer */ void nMeshIpol::interpolate(nSceneGraph2* sceneGraph, float l, nVertexBuffer *vb0, nVertexBuffer *vb1) { n_assert(sceneGraph && vb0 && vb1); // get current index buffer (this is the index buffer from // one of the source meshes, all index buffer should be // identical anyway!) nIndexBuffer* indexBuffer = sceneGraph->GetIndexBuffer(); n_assert(indexBuffer); // get destination vertex buffer nVertexBuffer *vb2 = this->dyn_vb.Begin( indexBuffer, sceneGraph->GetPixelShader(), sceneGraph->GetTextureArray()); // lock source buffers to gain read access vb0->LockVertices(); vb1->LockVertices(); // get the required pointers float *coord[3]; float *norm[3]; ulong *color[3]; float *uv[N_MAXNUM_TEXCOORDS][3]; coord[0]=vb0->coord_ptr; coord[1]=vb1->coord_ptr; coord[2]=vb2->coord_ptr; norm[0] =vb0->norm_ptr; norm[1] =vb1->norm_ptr; norm[2] =vb2->norm_ptr; color[0]=vb0->color_ptr; color[1]=vb1->color_ptr; color[2]=vb2->color_ptr; int i; for (i=0; i<N_MAXNUM_TEXCOORDS; i++) { uv[i][0]=vb0->uv_ptr[i]; uv[i][1]=vb1->uv_ptr[i]; uv[i][2]=vb2->uv_ptr[i]; } bool do_coord = this->update_flags & N_UPDATE_COORD ? true : false; bool do_norm = this->update_flags & N_UPDATE_NORM ? true : false; bool do_color = this->update_flags & N_UPDATE_RGBA ? true : false; bool do_uv[N_MAXNUM_TEXCOORDS]; do_uv[0] = this->update_flags & N_UPDATE_UV0 ? true : false; do_uv[1] = this->update_flags & N_UPDATE_UV1 ? true : false; do_uv[2] = this->update_flags & N_UPDATE_UV2 ? true : false; do_uv[3] = this->update_flags & N_UPDATE_UV3 ? true : false; // get 16 bit fixed point lerp value for color lerping short uslerp = (short) (256.0f * l); // the destination buffer must be written continously, because // it may be placed in uncached memory (AGP or video mem) // it may actually be better to keep coords, norms, etc // in separate arrays -> DX8! int num_v = vb0->GetNumVertices(); for (i=0; i<num_v; i++) { int k; // interpolate 3d coordinates if (coord[0]) { if (do_coord) { coord[2][0] = coord[0][0] + ((coord[1][0]-coord[0][0])*l); coord[2][1] = coord[0][1] + ((coord[1][1]-coord[0][1])*l); coord[2][2] = coord[0][2] + ((coord[1][2]-coord[0][2])*l); } else { coord[2][0] = coord[0][0]; coord[2][1] = coord[0][1]; coord[2][2] = coord[0][2]; } coord[0] += vb0->stride4; coord[1] += vb1->stride4; coord[2] += vb2->stride4; } // interpolate normals if (norm[0]) { if (do_norm) { norm[2][0] = norm[0][0] + ((norm[1][0]-norm[0][0])*l); norm[2][1] = norm[0][1] + ((norm[1][1]-norm[0][1])*l); norm[2][2] = norm[0][2] + ((norm[1][2]-norm[0][2])*l); } else { norm[2][0] = norm[0][0]; norm[2][1] = norm[0][1]; norm[2][2] = norm[0][2]; } norm[0] += vb0->stride4; norm[1] += vb1->stride4; norm[2] += vb2->stride4; } // interpolate vertex colors if (color[0]) { if (do_color) { // FIXME!!! (optimize!) ulong c0 = color[0][0]; ulong c1 = color[1][0]; short r0 = short((c0>>24) & 0xff); short g0 = short((c0>>16) & 0xff); short b0 = short((c0>>8) & 0xff); short a0 = short(c0 & 0xff); short r1 = short((c1>>24) & 0xff); short g1 = short((c1>>16) & 0xff); short b1 = short((c1>>8) & 0xff); short a1 = short(c1 & 0xff); color[2][0] = (((r0 + (((r1-r0)*uslerp)>>8)) & 0xff)<<24) | (((g0 + (((g1-g0)*uslerp)>>8)) & 0xff)<<16) | (((b0 + (((b1-b0)*uslerp)>>8)) & 0xff)<<8) | (((a0 + (((a1-a0)*uslerp)>>8)) & 0xff)); } else { color[2][0] = color[0][0]; } color[0] += vb0->stride4; color[1] += vb1->stride4; color[2] += vb2->stride4; } // interpolate texture coords for (k=0; k<N_MAXNUM_TEXCOORDS; k++) { if (uv[k][0]) { if (do_uv[k]) { uv[k][2][0] = uv[k][0][0] + ((uv[k][1][0]-uv[k][0][0])*l); uv[k][2][1] = uv[k][0][1] + ((uv[k][1][1]-uv[k][0][1])*l); } else { uv[k][2][0] = uv[k][0][0]; uv[k][2][1] = uv[k][0][1]; } uv[k][0] += vb0->stride4; uv[k][1] += vb1->stride4; uv[k][2] += vb2->stride4; } } } // lerp bounding box const vector3& vb0_min = vb0->GetBBox().vmin; const vector3& vb0_max = vb0->GetBBox().vmax; const vector3& vb1_min = vb1->GetBBox().vmin; const vector3& vb1_max = vb1->GetBBox().vmax; vector3 vb2_min = vb0_min + (vb1_min-vb0_min) * l; vector3 vb2_max = vb0_max + (vb1_max-vb0_max) * l; bbox3 vb2_bbox(vb2_min, vb2_max); vb2->SetBBox(vb2_bbox); // unlock source vertex buffers, and render dynamic vertex buffer vb1->UnlockVertices(); vb0->UnlockVertices(); this->dyn_vb.End(num_v, indexBuffer->GetNumIndices()); // if we are readonly, attach vertex buffer to current scene graph node if (this->dyn_vb.GetReadOnly()) { sceneGraph->SetVertexBuffer(vb2); } else { sceneGraph->SetVertexBuffer(0); } } //------------------------------------------------------------------------------ /** Attach object to scene if a non-readonly object (a read only object will not be visible and only serves as input mesh for other mesh animators). @param sceneGraph pointer to scene graph object */ bool nMeshIpol::Attach(nSceneGraph2* sceneGraph) { n_assert(sceneGraph); if (nVisNode::Attach(sceneGraph)) { // don't attach to scene if we are a readonly mesh if (!this->dyn_vb.GetReadOnly()) { sceneGraph->AttachVisualNode(this); } return true; } return false; } //------------------------------------------------------------------------------ /** Update myself and render to dynamic mesh, or set as current vertex buffer in scene graph if I'm read only (see nMeshNode). @param sceneGraph pointer to scene graph object 24-Jul-01 floh + some corrections to prevent illegal array accesses */ void nMeshIpol::Compute(nSceneGraph2* sceneGraph) { n_assert(sceneGraph); // let my depend nodes update me nVisNode::Compute(sceneGraph); // find the 2 current keyframes float tscale = this->scale; float min_t = this->key_array[0].t * tscale; float max_t = this->key_array[this->num_keys-1].t * tscale; if (max_t > 0.0) { // get current anim channel value nChannelContext* chnContext = sceneGraph->GetChannelContext(); n_assert(chnContext); float t = this->ComputeTime(chnContext->GetChannel1f(this->localChannelIndex), min_t, max_t); // find the right keys int i = 0; if (n_neqz(this->key_array[0].t) && (this->repType != N_REPTYPE_ONESHOT)) { n_error("Object '%s' 1st keyframe > 0.0f!\n",this->GetFullName().c_str()); } while ((this->key_array[i].t*tscale) <= t) i++; n_assert((i > 0) && (i < this->num_keys)); nMeshIpolKey *k0 = &(this->key_array[i-1]); nMeshIpolKey *k1 = &(this->key_array[i]); nVertexBuffer *vb0 = NULL; nVertexBuffer *vb1 = NULL; // invoke Compute() on both candidates and get vertex buffer pointers k0->ref_source->Compute(sceneGraph); vb0 = sceneGraph->GetVertexBuffer(); n_assert(vb0); n_assert(vb0->GetVBufType() == N_VBTYPE_READONLY); k1->ref_source->Compute(sceneGraph); vb1 = sceneGraph->GetVertexBuffer(); n_assert(vb1); n_assert(vb1->GetVBufType() == N_VBTYPE_READONLY); // clear scene graph vertex buffer after child nodes wrote to it sceneGraph->SetVertexBuffer(0); // FIXME: make sure both vertex buffers have identical number of vertices /* if (vb0->GetNumVertices() != vb1->GetNumVertices()) { char buf0[N_MAXPATH]; char buf1[N_MAXPATH]; n_error("ERROR: nMeshIpol: num vertices differ '%s' and '%s'\n", k0->ref_source->GetFullName(buf0, sizeof(buf0)), k1->ref_source->GetFullName(buf1, sizeof(buf1))); } */ // make sure both vertex buffers have identical vertex formats if (vb0->GetVertexType() != vb1->GetVertexType()) { n_error("ERROR: nMeshIpol: vertex formats differ '%s' and '%s'\n", k0->ref_source->GetFullName().c_str(), k1->ref_source->GetFullName().c_str()); } // initialize dynamic vertex buffer if not happened yet if (!this->dyn_vb.IsValid()) { this->dyn_vb.Initialize(vb0->GetVertexType(), vb0->GetNumVertices()); // make sure that the vbuffers we get are bigger // then the source buffers, that's a compromise // we make to not make the code overly difficult if (vb0->GetNumVertices() > this->dyn_vb.GetNumVertices()) { n_error("ERROR: source vertex buffers are greater then target vertex buffer!\n"); } } // compute lerp position float l; float t0 = k0->t * tscale; float t1 = k1->t * tscale; if (t1 > t0) l = (float) ((t-t0)/(t1-t0)); else l = 1.0f; // generate and render interpolated vertex buffer this->interpolate(sceneGraph, l, vb0, vb1); } } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 353 ] ] ]
ed968aa88d79ade4b54b5f20f2d0d0933ae737fe
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/TSTranslatable.cpp
4dea06de09b99d0ad5983681620c9ff6504ba063
[]
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
UTF-8
C++
false
false
1,235
cpp
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, 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 GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #include "stdafx.h" #include "TSTranslatable.h" #include "PrgAPI.h" TSTranslatable::TSTranslatable() { PRGAPI()->GetTranslationManager()->RegisterTranslatable(*this); } TSTranslatable::~TSTranslatable() { PRGAPI()->GetTranslationManager()->UnRegisterTranslatable(*this); }
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 35 ] ] ]
1ac1e3a80ac533f4fad1b0a73573bccabd8fb354
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/sdk/src/wxScintilla/ScintillaWX.cpp
e02b2502abe50ead31986acbe3d0bd783db070d2
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,581
cpp
//////////////////////////////////////////////////////////////////////////// // Name: ScintillaWX.cxx // Purpose: A wxWidgets implementation of Scintilla. A class derived // from ScintillaBase that uses the "wx platform" defined in // PlatformWX.cxx This class is one end of a bridge between // the wx world and the Scintilla world. It needs a peer // object of type wxScintilla to function. // // Author: Robin Dunn // // Created: 13-Jan-2000 // RCS-ID: $Id: ScintillaWX.cpp 5368 2008-12-30 11:05:44Z jenslody $ // Copyright: (c) 2000 by Total Control Software // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// #include "ScintillaWX.h" //?#include "ExternalLexer.h" #include "PlatWX.h" #include "wx/wxscintilla.h" #include <wx/textbuf.h> #ifdef __WXMSW__ #include <wx/msw/private.h> // GetHwndOf() #endif //---------------------------------------------------------------------- // Helper classes class wxSCITimer : public wxTimer { public: wxSCITimer(ScintillaWX* swx) { this->swx = swx; } void Notify() { swx->DoTick(); } private: ScintillaWX* swx; }; #if wxUSE_DRAG_AND_DROP class wxStartDragTimer : public wxTimer { public: wxStartDragTimer(ScintillaWX* swx) { this->swx = swx; } void Notify() { swx->DoStartDrag(); } private: ScintillaWX* swx; }; bool wxSCIDropTarget::OnDropText(wxCoord x, wxCoord y, const wxString& data) { return swx->DoDropText(x, y, data); } wxDragResult wxSCIDropTarget::OnEnter(wxCoord x, wxCoord y, wxDragResult def) { return swx->DoDragEnter(x, y, def); } wxDragResult wxSCIDropTarget::OnDragOver(wxCoord x, wxCoord y, wxDragResult def) { return swx->DoDragOver(x, y, def); } void wxSCIDropTarget::OnLeave() { swx->DoDragLeave(); } #endif #if wxUSE_POPUPWIN && wxSCI_USE_POPUP #include <wx/popupwin.h> #define wxSCICallTipBase wxPopupWindow #define param2 wxBORDER_NONE // popup's 2nd param is flags #else #define wxSCICallTipBase wxWindow #define param2 -1 // wxWindow's 2nd param is ID #endif #include <wx/dcbuffer.h> class wxSCICallTip : public wxSCICallTipBase { public: wxSCICallTip(wxWindow* parent, CallTip* ct, ScintillaWX* swx) : wxSCICallTipBase(parent, param2), m_ct(ct), m_swx(swx), m_cx(-1), m_cy(-1) { } ~wxSCICallTip() { #if wxUSE_POPUPWIN && wxSCI_USE_POPUP && defined(__WXGTK__) wxRect rect = GetRect(); rect.x = m_cx; rect.y = m_cy; GetParent()->Refresh(false, &rect); #endif } bool AcceptsFocus() const { return false; } void OnPaint(wxPaintEvent& WXUNUSED(evt)) { wxBufferedPaintDC dc(this); Surface* surfaceWindow = Surface::Allocate(); surfaceWindow->Init(&dc, m_ct->wDraw.GetID()); m_ct->PaintCT(surfaceWindow); surfaceWindow->Release(); delete surfaceWindow; } void OnFocus(wxFocusEvent& event) { GetParent()->SetFocus(); event.Skip(); } void OnLeftDown(wxMouseEvent& event) { wxPoint pt = event.GetPosition(); Point p(pt.x, pt.y); m_ct->MouseClick(p); m_swx->CallTipClick(); } #if wxUSE_POPUPWIN && wxSCI_USE_POPUP virtual void DoSetSize(int x, int y, int width, int height, int sizeFlags = wxSIZE_AUTO) { if (x != -1) { m_cx = x; GetParent()->ClientToScreen(&x, NULL); } if (y != -1) { m_cy = y; GetParent()->ClientToScreen(NULL, &y); } wxSCICallTipBase::DoSetSize(x, y, width, height, sizeFlags); } #endif wxPoint GetMyPosition() { return wxPoint(m_cx, m_cy); } private: CallTip* m_ct; ScintillaWX* m_swx; int m_cx, m_cy; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxSCICallTip, wxSCICallTipBase) EVT_PAINT(wxSCICallTip::OnPaint) EVT_SET_FOCUS(wxSCICallTip::OnFocus) EVT_LEFT_DOWN(wxSCICallTip::OnLeftDown) END_EVENT_TABLE() //---------------------------------------------------------------------- #if wxUSE_DATAOBJ static wxTextFileType wxConvertEOLMode(int scintillaMode) { wxTextFileType type; switch (scintillaMode) { case wxSCI_EOL_CRLF: type = wxTextFileType_Dos; break; case wxSCI_EOL_CR: type = wxTextFileType_Mac; break; case wxSCI_EOL_LF: type = wxTextFileType_Unix; break; default: type = wxTextBuffer::typeDefault; break; } return type; } #endif // wxUSE_DATAOBJ static int wxCountLines(const char* text, int scintillaMode) { char eolchar; switch (scintillaMode) { case wxSCI_EOL_CRLF: case wxSCI_EOL_LF: eolchar = '\n'; break; case wxSCI_EOL_CR: eolchar = '\r'; break; default: return 0; } int count = 0; int i = 0; while (text[i] != 0) { if (text[i] == eolchar) { count++; } i++; } return count; } //---------------------------------------------------------------------- // Constructor/Destructor ScintillaWX::ScintillaWX(wxScintilla* win) { capturedMouse = false; focusEvent = false; wMain = win; sci = win; wheelRotation = 0; Initialise(); #ifdef __WXMSW__ #if wxCHECK_VERSION(2, 5, 0) sysCaretBitmap = 0; sysCaretWidth = 0; sysCaretHeight = 0; #endif #endif #if wxUSE_DRAG_AND_DROP startDragTimer = new wxStartDragTimer(this); #endif } ScintillaWX::~ScintillaWX() { #if wxUSE_DRAG_AND_DROP delete startDragTimer; #endif Finalise(); } //---------------------------------------------------------------------- // base class virtuals void ScintillaWX::Initialise() { //ScintillaBase::Initialise(); #if wxUSE_DRAG_AND_DROP dropTarget = new wxSCIDropTarget; dropTarget->SetScintilla(this); sci->SetDropTarget(dropTarget); dragRectangle = false; #endif #ifdef __WXMAC__ vs.extraFontFlag = false; // UseAntiAliasing #else vs.extraFontFlag = true; // UseAntiAliasing #endif } void ScintillaWX::Finalise() { ScintillaBase::Finalise(); SetTicking(false); SetIdle(false); DestroySystemCaret(); } void ScintillaWX::StartDrag() { #if wxUSE_DRAG_AND_DROP #if wxVERSION_NUMBER >= 2800 && defined(__WXGTK__) // For recent wxGTKs, DnD won't work if we delay with the timer, so go there direct DoStartDrag(); #else startDragTimer->Start (200, true); #endif // wxVERSION_NUMBER >= 2701 && defined(__WXGTK20__) #endif } void ScintillaWX::DoStartDrag() { #if wxUSE_DRAG_AND_DROP wxString dragText = sci2wx (drag.s, drag.len); // Send an event to allow the drag text to be changed wxScintillaEvent evt(wxEVT_SCI_START_DRAG, sci->GetId()); evt.SetEventObject (sci); evt.SetDragText (dragText); evt.SetDragAllowMove (true); evt.SetPosition (wxMin(sci->GetSelectionStart(), sci->GetSelectionEnd())); sci->GetEventHandler()->ProcessEvent (evt); pdoc->BeginUndoAction(); dragText = evt.GetDragText(); dragRectangle = drag.rectangular; if (dragText.Length()) { wxDropSource source(sci); wxTextDataObject data(dragText); source.SetData(data); inDragDrop = ddDragging; source.DoDragDrop(wxDrag_DefaultMove); inDragDrop = ddNone; SetDragPosition (invalidPosition); } pdoc->EndUndoAction(); #endif } bool ScintillaWX::SetIdle(bool on) { if (idler.state != on) { // connect or disconnect the EVT_IDLE handler if (on) sci->Connect(wxID_ANY, wxEVT_IDLE, (wxObjectEventFunction) (wxEventFunction) (wxIdleEventFunction) &wxScintilla::OnIdle); else sci->Disconnect(wxID_ANY, wxEVT_IDLE, (wxObjectEventFunction) (wxEventFunction) (wxIdleEventFunction) &wxScintilla::OnIdle); idler.state = on; } return idler.state; } void ScintillaWX::SetTicking(bool on) { wxSCITimer* stiTimer; if (timer.ticking != on) { timer.ticking = on; if (timer.ticking) { stiTimer = new wxSCITimer(this); stiTimer->Start(timer.tickSize); timer.tickerID = stiTimer; } else { stiTimer = (wxSCITimer*)timer.tickerID; stiTimer->Stop(); delete stiTimer; timer.tickerID = 0; } } timer.ticksToWait = caret.period; } void ScintillaWX::SetMouseCapture(bool on) { if (mouseDownCaptures) { if (on && !capturedMouse) sci->CaptureMouse(); else if (!on && capturedMouse && sci->HasCapture()) sci->ReleaseMouse(); capturedMouse = on; } } bool ScintillaWX::HaveMouseCapture() { return capturedMouse; } void ScintillaWX::ScrollText(int linesToMove) { int dy = vs.lineHeight * (linesToMove); sci->ScrollWindow(0, dy); sci->Update(); } void ScintillaWX::SetVerticalScrollPos() { if (sci->m_vScrollBar == NULL) { // Use built-in scrollbar sci->SetScrollPos(wxVERTICAL, topLine); } else { // otherwise use the one that's been given to us sci->m_vScrollBar->SetThumbPosition(topLine); } } void ScintillaWX::SetHorizontalScrollPos() { if (sci->m_hScrollBar == NULL) { // Use built-in scrollbar sci->SetScrollPos(wxHORIZONTAL, xOffset); } else { // otherwise use the one that's been given to us sci->m_hScrollBar->SetThumbPosition(xOffset); } } const int H_SCROLL_STEP = 20; bool ScintillaWX::ModifyScrollBars(int nMax, int nPage) { bool modified = false; int vertEnd = nMax; if (!verticalScrollBarVisible) vertEnd = 0; // Check the vertical scrollbar if (sci->m_vScrollBar == NULL) { // Use built-in scrollbar int sbMax = sci->GetScrollRange(wxVERTICAL); int sbThumb = sci->GetScrollThumb(wxVERTICAL); int sbPos = sci->GetScrollPos(wxVERTICAL); if (sbMax != vertEnd || sbThumb != nPage) { sci->SetScrollbar(wxVERTICAL, sbPos, nPage, vertEnd+1); modified = true; } } else { // otherwise use the one that's been given to us int sbMax = sci->m_vScrollBar->GetRange(); int sbPage = sci->m_vScrollBar->GetPageSize(); int sbPos = sci->m_vScrollBar->GetThumbPosition(); if (sbMax != vertEnd || sbPage != nPage) { sci->m_vScrollBar->SetScrollbar(sbPos, nPage, vertEnd+1, nPage); modified = true; } } // Check the horizontal scrollbar PRectangle rcText = GetTextRectangle(); int horizEnd = scrollWidth; if (horizEnd < 0) horizEnd = 0; if (!horizontalScrollBarVisible || (wrapState != eWrapNone)) horizEnd = 0; int pageWidth = rcText.Width(); if (sci->m_hScrollBar == NULL) { // Use built-in scrollbar int sbMax = sci->GetScrollRange(wxHORIZONTAL); int sbThumb = sci->GetScrollThumb(wxHORIZONTAL); int sbPos = sci->GetScrollPos(wxHORIZONTAL); if ((sbMax != horizEnd) || (sbThumb != pageWidth) || (sbPos != 0)) { sci->SetScrollbar(wxHORIZONTAL, sbPos, pageWidth, horizEnd); modified = true; if (scrollWidth < pageWidth) { HorizontalScrollTo(0); } } } else { // otherwise use the one that's been given to us int sbMax = sci->m_hScrollBar->GetRange(); int sbThumb = sci->m_hScrollBar->GetPageSize(); int sbPos = sci->m_hScrollBar->GetThumbPosition(); if ((sbMax != horizEnd) || (sbThumb != pageWidth) || (sbPos != 0)) { sci->m_hScrollBar->SetScrollbar(sbPos, pageWidth, horizEnd, pageWidth); modified = true; if (scrollWidth < pageWidth) { HorizontalScrollTo(0); } } } return modified; } void ScintillaWX::NotifyChange() { sci->NotifyChange(); } void ScintillaWX::NotifyParent(SCNotification scn) { sci->NotifyParent(&scn); } // This method is overloaded from ScintillaBase in order to prevent the // AutoComplete window from being destroyed when it gets the focus. There is // a side effect that the AutoComp will also not be destroyed when switching // to another window, but I think that is okay. void ScintillaWX::CancelModes() { if (! focusEvent) AutoCompleteCancel(); ct.CallTipCancel(); Editor::CancelModes(); } void ScintillaWX::Copy() { if (currentPos != anchor) { SelectionText st; CopySelectionRange(&st); #ifdef __WXGTK__ for(int i=0; i<5; i++) { //wxPrintf(wxT("Copying to clipboard %ld\n"), i); CopyToClipboard(st); } #else CopyToClipboard(st); #endif } } void ScintillaWX::Paste() { pdoc->BeginUndoAction(); ClearSelection(); #if wxUSE_DATAOBJ wxTextDataObject data; wxString textString; wxWX2MBbuf buf; int len = 0; bool rectangular = false; if (wxTheClipboard->Open()) { wxTheClipboard->UsePrimarySelection(false); wxCustomDataObject selData(wxDataFormat(wxString(wxT("application/x-cbrectdata")))); bool gotRectData = wxTheClipboard->GetData(selData); if (gotRectData && selData.GetSize()>1) { const char* rectBuf = (const char*)selData.GetData(); rectangular = rectBuf[0] == (char)1; len = selData.GetDataSize()-1; char* buffer = new char[len]; memcpy (buffer, rectBuf+1, len); textString = sci2wx(buffer, len); delete [] buffer; } else { bool gotData = wxTheClipboard->GetData(data); if (gotData) { textString = wxTextBuffer::Translate (data.GetText(), wxConvertEOLMode(pdoc->eolMode)); } } data.SetText(wxEmptyString); // free the data object content wxTheClipboard->Close(); } buf = (wxWX2MBbuf)wx2sci(textString); len = strlen(buf); int newPos = 0; if (rectangular) { int newLine = pdoc->LineFromPosition (currentPos) + wxCountLines (buf, pdoc->eolMode); int newCol = pdoc->GetColumn(currentPos); PasteRectangular (currentPos, buf, len); newPos = pdoc->FindColumn (newLine, newCol); } else { pdoc->InsertString (currentPos, buf, len); newPos = currentPos + len; } SetEmptySelection (newPos); #endif // wxUSE_DATAOBJ pdoc->EndUndoAction(); NotifyChange(); Redraw(); } void ScintillaWX::CopyToClipboard (const SelectionText& st) { #if wxUSE_CLIPBOARD if (wxTheClipboard->Open()) { wxTheClipboard->UsePrimarySelection (false); wxString text = wxTextBuffer::Translate (sci2wx(st.s, st.len-1)); // composite object will hold "plain text" for pasting in other programs and a custom // object for local use that remembers what kind of selection was made (stream or // rectangular). wxDataObjectComposite* obj = new wxDataObjectComposite(); wxCustomDataObject* rectData = new wxCustomDataObject (wxDataFormat(wxString(wxT("application/x-cbrectdata")))); char* buffer = new char[st.len+1]; buffer[0] = (st.rectangular)? (char)1 : (char)0; memcpy (buffer+1, st.s, st.len); rectData->SetData (st.len+1, buffer); delete [] buffer; obj->Add (rectData, true); obj->Add (new wxTextDataObject (text)); wxTheClipboard->SetData (obj); wxTheClipboard->Close(); } #else wxUnusedVar(st); #endif // wxUSE_CLIPBOARD } bool ScintillaWX::CanPaste() { #if wxUSE_CLIPBOARD bool canPaste = false; bool didOpen; if (Editor::CanPaste()) { didOpen = !wxTheClipboard->IsOpened(); if ( didOpen ) wxTheClipboard->Open(); if (wxTheClipboard->IsOpened()) { wxTheClipboard->UsePrimarySelection(false); canPaste = wxTheClipboard->IsSupported(wxUSE_UNICODE ? wxDF_UNICODETEXT : wxDF_TEXT); if (didOpen) wxTheClipboard->Close(); } } return canPaste; #else return false; #endif // wxUSE_CLIPBOARD } void ScintillaWX::CreateCallTipWindow(PRectangle) { if (! ct.wCallTip.Created() ) { ct.wCallTip = new wxSCICallTip(sci, &ct, this); ct.wDraw = ct.wCallTip; } } void ScintillaWX::AddToPopUp(const char *label, int cmd, bool enabled) { if (!label[0]) ((wxMenu*)popup.GetID())->AppendSeparator(); else ((wxMenu*)popup.GetID())->Append(cmd, wxGetTranslation(sci2wx(label))); if (!enabled) ((wxMenu*)popup.GetID())->Enable(cmd, enabled); } // This is called by the Editor base class whenever something is selected void ScintillaWX::ClaimSelection() { #if 0 // Until wxGTK is able to support using both the primary selection and the // clipboard at the same time I think it causes more problems than it is // worth to implement this method. Selecting text should not clear the // clipboard. --Robin #ifdef __WXGTK__ // Put the selected text in the PRIMARY selection if (currentPos != anchor) { SelectionText st; CopySelectionRange(&st); if (wxTheClipboard->Open()) { wxTheClipboard->UsePrimarySelection(true); wxString text = sci2wx(st.s, st.len); wxTheClipboard->SetData(new wxTextDataObject(text)); wxTheClipboard->UsePrimarySelection(false); wxTheClipboard->Close(); } } #endif #endif } void ScintillaWX::UpdateSystemCaret() { #ifdef __WXMSW__ if (hasFocus) { if (HasCaretSizeChanged()) { DestroySystemCaret(); CreateSystemCaret(); } Point pos = LocationFromPosition(currentPos); #if wxCHECK_VERSION(2, 5, 0) ::SetCaretPos(pos.x, pos.y); #endif } #endif } bool ScintillaWX::HasCaretSizeChanged() { #ifdef __WXMSW__ #if !wxCHECK_VERSION(2, 5, 0) return false; #else if (( (0 != vs.caretWidth) && (sysCaretWidth != vs.caretWidth) ) || (0 != vs.lineHeight) && (sysCaretHeight != vs.lineHeight)) { return true; } #endif #endif return false; } bool ScintillaWX::CreateSystemCaret() { return false; /* #ifdef __WXMSW__ #if !wxCHECK_VERSION(2, 5, 0) return false; #else sysCaretWidth = vs.caretWidth; if (0 == sysCaretWidth) { sysCaretWidth = 1; } sysCaretHeight = vs.lineHeight; int bitmapSize = (((sysCaretWidth + 15) & ~15) >> 3) * sysCaretHeight; char *bits = new char[bitmapSize]; memset(bits, 0, bitmapSize); sysCaretBitmap = ::CreateBitmap(sysCaretWidth, sysCaretHeight, 1, 1, reinterpret_cast<BYTE *>(bits)); delete [] bits; BOOL retval = ::CreateCaret(GetHwndOf(sci), sysCaretBitmap, sysCaretWidth, sysCaretHeight); ::ShowCaret(GetHwndOf(sci)); return retval != 0; #endif #else return false; #endif */ } bool ScintillaWX::DestroySystemCaret() { return false; /* #ifdef __WXMSW__ #if !wxCHECK_VERSION(2, 5, 0) return false; #else ::HideCaret(GetHwndOf(sci)); BOOL retval = ::DestroyCaret(); if (sysCaretBitmap) { ::DeleteObject(sysCaretBitmap); sysCaretBitmap = 0; } return retval != 0; #endif #else return false; #endif */ } //---------------------------------------------------------------------- long ScintillaWX::DefWndProc(unsigned int /*iMessage*/, unsigned long /*wParam*/, long /*lParam*/) { return 0; } long ScintillaWX::WndProc(unsigned int iMessage, unsigned long wParam, long lParam) { switch (iMessage) { case SCI_CALLTIPSHOW: { // NOTE: This is copied here from scintilla/src/ScintillaBase.cxx // because of the little tweak that needs done below for wxGTK. // When updating new versions double check that this is still // needed, and that any new code there is copied here too. Point pt = LocationFromPosition(wParam); char* defn = reinterpret_cast<char *>(lParam); AutoCompleteCancel(); pt.y += vs.lineHeight; PRectangle rc = ct.CallTipStart(currentPos, pt, defn, vs.styles[STYLE_DEFAULT].fontName, vs.styles[STYLE_DEFAULT].sizeZoomed, CodePage(), vs.styles[STYLE_DEFAULT].characterSet, wMain); // If the call-tip window would be out of the client // space, adjust so it displays above the text. PRectangle rcClient = GetClientRectangle(); if (rc.bottom > rcClient.bottom) { #ifdef __WXGTK__ int offset = int(vs.lineHeight * 1.25) + rc.Height(); #else int offset = vs.lineHeight + rc.Height(); #endif rc.top -= offset; rc.bottom -= offset; } // Now display the window. CreateCallTipWindow(rc); ct.wCallTip.SetPositionRelative(rc, wMain); ct.wCallTip.Show(); break; } /*? TODO #ifdef SCI_LEXER case SCI_LOADLEXERLIBRARY: LexerManager::GetInstance()->Load((const char*)lParam); break; #endif ?*/ default: return ScintillaBase::WndProc(iMessage, wParam, lParam); } return 0; } //---------------------------------------------------------------------- // Event delegates void ScintillaWX::DoPaint(wxDC* dc, wxRect rect) { paintState = painting; Surface* surfaceWindow = Surface::Allocate(); surfaceWindow->Init(dc, wMain.GetID()); rcPaint = PRectangleFromwxRect(rect); PRectangle rcClient = GetClientRectangle(); paintingAllText = rcPaint.Contains(rcClient); ClipChildren(*dc, rcPaint); Paint(surfaceWindow, rcPaint); delete surfaceWindow; if (paintState == paintAbandoned) { // Painting area was insufficient to cover new styling or brace // highlight positions FullPaint(); } paintState = notPainting; } void ScintillaWX::DoHScroll(int type, int pos) { int xPos = xOffset; PRectangle rcText = GetTextRectangle(); int pageWidth = rcText.Width() * 2 / 3; if (type == wxEVT_SCROLLWIN_LINEUP || type == wxEVT_SCROLL_LINEUP) xPos -= H_SCROLL_STEP; else if (type == wxEVT_SCROLLWIN_LINEDOWN || type == wxEVT_SCROLL_LINEDOWN) xPos += H_SCROLL_STEP; else if (type == wxEVT_SCROLLWIN_PAGEUP || type == wxEVT_SCROLL_PAGEUP) xPos -= pageWidth; else if (type == wxEVT_SCROLLWIN_PAGEDOWN || type == wxEVT_SCROLL_PAGEDOWN) { xPos += pageWidth; if (xPos > scrollWidth - rcText.Width()) { xPos = scrollWidth - rcText.Width(); } } else if (type == wxEVT_SCROLLWIN_TOP || type == wxEVT_SCROLL_TOP) xPos = 0; else if (type == wxEVT_SCROLLWIN_BOTTOM || type == wxEVT_SCROLL_BOTTOM) xPos = scrollWidth; else if (type == wxEVT_SCROLLWIN_THUMBTRACK || type == wxEVT_SCROLL_THUMBTRACK) xPos = pos; HorizontalScrollTo(xPos); } void ScintillaWX::DoVScroll(int type, int pos) { int topLineNew = topLine; if (type == wxEVT_SCROLLWIN_LINEUP || type == wxEVT_SCROLL_LINEUP) topLineNew -= 1; else if (type == wxEVT_SCROLLWIN_LINEDOWN || type == wxEVT_SCROLL_LINEDOWN) topLineNew += 1; else if (type == wxEVT_SCROLLWIN_PAGEUP || type == wxEVT_SCROLL_PAGEUP) topLineNew -= LinesToScroll(); else if (type == wxEVT_SCROLLWIN_PAGEDOWN || type == wxEVT_SCROLL_PAGEDOWN) topLineNew += LinesToScroll(); else if (type == wxEVT_SCROLLWIN_TOP || type == wxEVT_SCROLL_TOP) topLineNew = 0; else if (type == wxEVT_SCROLLWIN_BOTTOM || type == wxEVT_SCROLL_BOTTOM) topLineNew = MaxScrollPos(); else if (type == wxEVT_SCROLLWIN_THUMBTRACK || type == wxEVT_SCROLL_THUMBTRACK) topLineNew = pos; ScrollTo(topLineNew); } void ScintillaWX::DoMouseWheel(int rotation, int delta, int linesPerAction, int ctrlDown, bool isPageScroll ) { int topLineNew = topLine; int lines; if (ctrlDown) { // Zoom the fonts if Ctrl key down if (rotation < 0) { KeyCommand(SCI_ZOOMIN); } else { KeyCommand(SCI_ZOOMOUT); } } else { // otherwise just scroll the window if ( !delta ) delta = 120; wheelRotation += rotation; lines = wheelRotation / delta; wheelRotation -= lines * delta; if (lines != 0) { if (isPageScroll) lines = lines * LinesOnScreen(); // lines is either +1 or -1 else lines *= linesPerAction; topLineNew -= lines; ScrollTo(topLineNew); } } } void ScintillaWX::DoSize(int WXUNUSED(width), int WXUNUSED(height)) { ChangeSize(); } void ScintillaWX::DoLoseFocus(){ focusEvent = true; SetFocusState(false); focusEvent = false; DestroySystemCaret(); } void ScintillaWX::DoGainFocus(){ focusEvent = true; SetFocusState(true); focusEvent = false; DestroySystemCaret(); CreateSystemCaret(); } void ScintillaWX::DoSysColourChange() { InvalidateStyleData(); } void ScintillaWX::DoLeftButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) { ButtonDown(pt, curTime, shift, ctrl, alt); } void ScintillaWX::DoLeftButtonUp(Point pt, unsigned int curTime, bool ctrl) { ButtonUp(pt, curTime, ctrl); #if wxUSE_DRAG_AND_DROP if (startDragTimer->IsRunning()) { startDragTimer->Stop(); SetDragPosition(invalidPosition); SetEmptySelection(PositionFromLocation(pt)); ShowCaretAtCurrentPosition(); } #endif } void ScintillaWX::DoLeftButtonMove(Point pt) { ButtonMove(pt); } #ifdef __WXGTK__ void ScintillaWX::DoMiddleButtonUp(Point pt) { // Set the current position to the mouse click point and // then paste in the PRIMARY selection, if any. wxGTK only. int newPos = PositionFromLocation(pt); MovePositionTo(newPos, noSel, true); pdoc->BeginUndoAction(); wxTextDataObject data; bool gotData = false; if (wxTheClipboard->Open()) { wxTheClipboard->UsePrimarySelection(true); gotData = wxTheClipboard->GetData(data); wxTheClipboard->UsePrimarySelection(false); wxTheClipboard->Close(); } if (gotData) { wxString text = wxTextBuffer::Translate (data.GetText(), wxConvertEOLMode(pdoc->eolMode)); data.SetText(wxEmptyString); // free the data object content wxWX2MBbuf buf = (wxWX2MBbuf)wx2sci(text); int len = strlen(buf); pdoc->InsertString(currentPos, buf, len); SetEmptySelection(currentPos + len); } pdoc->EndUndoAction(); NotifyChange(); Redraw(); ShowCaretAtCurrentPosition(); EnsureCaretVisible(); } #else void ScintillaWX::DoMiddleButtonUp(Point WXUNUSED(pt)) { } #endif void ScintillaWX::DoAddChar(int key) { #if wxUSE_UNICODE wxChar wszChars[2]; wszChars[0] = (wxChar)key; wszChars[1] = 0; wxWX2MBbuf buf = (wxWX2MBbuf)wx2sci(wszChars); AddCharUTF((char*)buf.data(), strlen(buf)); #else AddChar((char)key); #endif } int ScintillaWX::DoKeyDown(const wxKeyEvent& evt, bool* consumed) { int key = evt.GetKeyCode(); bool shift = evt.ShiftDown(), ctrl = evt.ControlDown(), alt = evt.AltDown(); if (ctrl && key >= 1 && key <= 26 && key != WXK_BACK) key += 'A' - 1; switch (key) { case WXK_DOWN: // fall through case WXK_NUMPAD_DOWN: key = SCK_DOWN; break; case WXK_UP: // fall through case WXK_NUMPAD_UP: key = SCK_UP; break; case WXK_LEFT: // fall through case WXK_NUMPAD_LEFT: key = SCK_LEFT; break; case WXK_RIGHT: // fall through case WXK_NUMPAD_RIGHT: key = SCK_RIGHT; break; case WXK_HOME: // fall through case WXK_NUMPAD_HOME: key = SCK_HOME; break; case WXK_END: // fall through case WXK_NUMPAD_END: key = SCK_END; break; #if !wxCHECK_VERSION(2, 8, 0) case WXK_PRIOR: // fall through case WXK_NUMPAD_PRIOR: // fall through #endif case WXK_PAGEUP: // fall through case WXK_NUMPAD_PAGEUP: key = SCK_PRIOR; break; #if !wxCHECK_VERSION(2, 8, 0) case WXK_NEXT: // fall through case WXK_NUMPAD_NEXT: // fall through #endif case WXK_PAGEDOWN: // fall through case WXK_NUMPAD_PAGEDOWN: key = SCK_NEXT; break; case WXK_NUMPAD_DELETE: // fall through case WXK_DELETE: key = SCK_DELETE; break; case WXK_NUMPAD_INSERT: // fall through case WXK_INSERT: key = SCK_INSERT; break; case WXK_ESCAPE: key = SCK_ESCAPE; break; case WXK_BACK: key = SCK_BACK; break; case WXK_TAB: key = SCK_TAB; break; case WXK_RETURN: // fall through case WXK_NUMPAD_ENTER: key = SCK_RETURN; break; case WXK_ADD: // fall through case WXK_NUMPAD_ADD: key = SCK_ADD; break; case WXK_SUBTRACT: // fall through case WXK_NUMPAD_SUBTRACT: key = SCK_SUBTRACT; break; case WXK_DIVIDE: // fall through case WXK_NUMPAD_DIVIDE: key = SCK_DIVIDE; break; case WXK_CONTROL: key = 0; break; case WXK_ALT: key = 0; break; case WXK_SHIFT: key = 0; break; case WXK_MENU: key = 0; break; } #ifdef __WXMAC__ if ( evt.MetaDown() ) { // check for a few common Mac Meta-key combos and remap them to Ctrl // for Scintilla switch ( key ) { case 'Z': // Undo case 'X': // Cut case 'C': // Copy case 'V': // Paste case 'A': // Select All ctrl = true; break; } } #endif int rv = KeyDown(key, shift, ctrl, alt, consumed); if (key) return rv; else return 1; } void ScintillaWX::DoCommand(int ID) { Command(ID); } void ScintillaWX::DoContextMenu(Point pt) { if (displayPopupMenu) ContextMenu(pt); } void ScintillaWX::DoOnListBox() { AutoCompleteCompleted(); } void ScintillaWX::DoOnIdle(wxIdleEvent& evt) { if ( Idle() ) evt.RequestMore(); else SetIdle(false); } //---------------------------------------------------------------------- #if wxUSE_DRAG_AND_DROP bool ScintillaWX::DoDropText(long x, long y, const wxString& data) { SetDragPosition(invalidPosition); wxString text = wxTextBuffer::Translate (data, wxConvertEOLMode(pdoc->eolMode)); // Send an event to allow the drag details to be changed wxScintillaEvent evt(wxEVT_SCI_DO_DROP, sci->GetId()); evt.SetEventObject(sci); evt.SetDragResult(dragResult); evt.SetX(x); evt.SetY(y); evt.SetPosition(PositionFromLocation(Point(x,y))); evt.SetDragText(text); sci->GetEventHandler()->ProcessEvent(evt); dragResult = evt.GetDragResult(); if (dragResult == wxDragMove || dragResult == wxDragCopy) { DropAt(evt.GetPosition(), wx2sci(evt.GetDragText()), dragResult == wxDragMove, dragRectangle); return true; } return false; } wxDragResult ScintillaWX::DoDragEnter(wxCoord WXUNUSED(x), wxCoord WXUNUSED(y), wxDragResult def) { dragResult = def; return dragResult; } wxDragResult ScintillaWX::DoDragOver(wxCoord x, wxCoord y, wxDragResult def) { SetDragPosition(PositionFromLocation(Point(x, y))); // Send an event to allow the drag result to be changed wxScintillaEvent evt(wxEVT_SCI_DRAG_OVER, sci->GetId()); evt.SetEventObject(sci); evt.SetDragResult(def); evt.SetX(x); evt.SetY(y); evt.SetPosition(PositionFromLocation(Point(x,y))); sci->GetEventHandler()->ProcessEvent(evt); dragResult = evt.GetDragResult(); return dragResult; } void ScintillaWX::DoDragLeave() { SetDragPosition(invalidPosition); } #endif //---------------------------------------------------------------------- // Force the whole window to be repainted void ScintillaWX::FullPaint() { #ifndef __WXMAC__ sci->Refresh(false); #endif sci->Update(); } void ScintillaWX::DoScrollToLine(int line) { ScrollTo(line); } void ScintillaWX::DoScrollToColumn(int column) { HorizontalScrollTo(column * vs.spaceWidth); } #ifdef __WXGTK__ void ScintillaWX::ClipChildren(wxDC& dc, PRectangle rect) { // wxGTK > 2.5 doesn't appear to need this explicit clipping code any longer #if !wxCHECK_VERSION(2, 5, 0) wxRegion rgn(wxRectFromPRectangle(rect)); if (ac.Active()) { wxRect childRect = ((wxWindow*)ac.lb->GetID())->GetRect(); rgn.Subtract(childRect); } if (ct.inCallTipMode) { wxSCICallTip* tip = (wxSCICallTip*)ct.wCallTip.GetID(); wxRect childRect = tip->GetRect(); #if wxUSE_POPUPWIN && wxSCI_USE_POPUP childRect.SetPosition(tip->GetMyPosition()); #endif rgn.Subtract(childRect); } dc.SetClippingRegion(rgn); #endif } #else void ScintillaWX::ClipChildren(wxDC& WXUNUSED(dc), PRectangle WXUNUSED(rect)) { } #endif void ScintillaWX::SetUseAntiAliasing(bool useAA) { vs.extraFontFlag = useAA; InvalidateStyleRedraw(); } bool ScintillaWX::GetUseAntiAliasing() { return vs.extraFontFlag; } //---------------------------------------------------------------------- //----------------------------------------------------------------------
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 1205 ] ] ]
8b75b000c6d7c859cb2f0084935d5764758e07c2
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/same_as.hpp
a94f007f3982032b8549b1faea4c93f07d83e840
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
hpp
#ifndef BOOST_MPL_SAME_AS_HPP_INCLUDED #define BOOST_MPL_SAME_AS_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-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/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/same_as.hpp,v $ // $Date: 2006/04/17 23:49:40 $ // $Revision: 1.1 $ #include <boost/mpl/not.hpp> #include <boost/mpl/aux_/lambda_spec.hpp> #include <boost/mpl/aux_/config/forwarding.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace mpl { template< typename T1 > struct same_as { template< typename T2 > struct apply #if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING) : is_same<T1,T2> { #else { typedef typename is_same<T1,T2>::type type; #endif }; }; template< typename T1 > struct not_same_as { template< typename T2 > struct apply #if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING) : not_< is_same<T1,T2> > { #else { typedef typename not_< is_same<T1,T2> >::type type; #endif }; }; }} #endif // BOOST_MPL_SAME_AS_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 55 ] ] ]
4810d7f73dd9cf047e676c464aebc71ac53ae23f
110f8081090ba9591d295d617a55a674467d127e
/math/Geometry.hpp
cb9d5e0ec45a0c6da0d83015554b49046ef9093b
[]
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
8,681
hpp
#ifndef GEOMETRY_HPP_ #define GEOMETRY_HPP_ #include <stdexcept> #include <ostream> #include <math/ArithmeticException.hpp> namespace geometry { template <typename UnitType = int> class Point { friend class GeometryTest; public: typedef UnitType BaseType; private: UnitType x; UnitType y; public: Point(): x(0), y(0) {} Point(const UnitType& x_, const UnitType& y_): x(x_), y(y_) {} Point(const Point& source): x(source.x), y(source.y) {} bool operator==(const Point& source) const { if (this->x == source.x && this->y == source.y) return true; return false; } bool operator!=(const Point& source) const { return ! this->operator==(source); } Point& operator=(const Point& source) { if (this != &source) { this->x = source.x; this->y = source.y; } return *this; } Point& operator+=(const Point& source) { this->x += source.x; this->y += source.y; return *this; } Point operator+(const Point& source) const { return Point(this->x + source.x, this->y + source.y); } Point& operator-=(const Point& source) { this->x -= source.x; this->y -= source.y; return *this; } Point operator-(const Point& source) const { return Point(this->x - source.x, this->y - source.y); } Point& operator*=(const BaseType& multiply) { this->x *= multiply; this->y *= multiply; return *this; } Point operator*(const BaseType& source) const { return Point(this->x * source, this->y * source); } Point& operator/=(const BaseType& divisor) throw(ZeroDivideException) { if (divisor == BaseType(0)) throw ZeroDivideException(); this->x /= divisor; this->y /= divisor; return *this; } Point operator/(const BaseType& divisor) const throw(ZeroDivideException) { if (divisor == BaseType(0)) throw ZeroDivideException(); return Point(this->x / divisor, this->y / divisor); } ~Point() throw() {} UnitType getX() const { return x; } UnitType getY() const { return y; } void setX(const UnitType& newX) { x = newX; } void setY(const UnitType& newY) { y = newY; } }; template <typename UnitType = int> class Rectangle { friend class GeometryTest; public: typedef UnitType BaseType; private: Point<BaseType> leftTop; Point<BaseType> rightBottom; public: Rectangle() throw() : leftTop(), rightBottom() {} Rectangle(const BaseType& left, const BaseType& top, const BaseType& right, const BaseType& bottom) throw(std::invalid_argument): leftTop(left, top), rightBottom(right, bottom) { if (left > right || top > bottom) throw std::invalid_argument("argument invalid."); } Rectangle(const Point<BaseType>& leftTop_, const Point<BaseType>& rightBottom_) throw(std::invalid_argument): leftTop(leftTop_), rightBottom(rightBottom_) { if (leftTop.getX() > rightBottom.getX() || leftTop.getY() > rightBottom.getY()) throw std::invalid_argument("argument invalid."); } Rectangle(const Rectangle& source) throw(): leftTop(source.leftTop), rightBottom(source.rightBottom) {} Rectangle& operator=(const Rectangle& source) throw() { if (this != &source) { this->leftTop = source.leftTop; this->rightBottom = source.rightBottom; } return *this; } ~Rectangle() throw() {} UnitType getTop() const throw() { return this->leftTop.getY(); } UnitType getLeft() const throw() { return this->leftTop.getX(); } Point<UnitType> getLeftTop() const throw() { return this->leftTop; } UnitType getBottom() const throw() { return this->rightBottom.getY(); } UnitType getRight() const throw() { return this->rightBottom.getX(); } Point<UnitType> getRightBottom() const throw() { return this->rightBottom; } Rectangle& operator+=(const Rectangle& source) throw() { if (this->leftTop.getX() > source.leftTop.getX()) this->leftTop.getX(source.leftTop.getX()); if (this->leftTop.getY() > source.leftTop.getY()) this->leftTop.getY(source.leftTop.getY()); if (this->rightBottom.getX() > source.rightBottom.getX()) this->rightBottom.getX(source.rightBottom.getX()); if (this->rightBottom.getY() > source.rightBottom.getY()) this->rightBottom.setY(source.rightBottom.getY()); return *this; } Rectangle operator+(const Rectangle& source) const throw() { return Rectangle(*this) += source; } Rectangle& operator+=(const Point<UnitType>& source) throw() { this->leftTop.setX(this->leftTop.getX() + source.getX()); this->leftTop.setY(this->leftTop.getY() + source.getY()); this->rightBottom.setX(this->rightBottom.getX() + source.getX()); this->rightBottom.setY(this->rightBottom.getY() + source.getY()); return *this; } Rectangle operator+(const Point<UnitType>& source) const throw() { return Rectangle(*this) += source; } bool operator==(const Rectangle& source) const throw() { return (this->leftTop == source.leftTop && this->rightBottom == source.rightBottom); } bool operator!=(const Rectangle& source) const throw() { return !((*this) == source); } Rectangle& slide(const BaseType& xMove, const BaseType& yMove) throw() { this->leftTop += Point<BaseType>(xMove, yMove); this->rightBottom += Point<BaseType>(xMove, yMove); return *this; } Rectangle& slide(const Point<BaseType>& move) throw() { this->leftTop += move; this->rightBottom += move; return *this; } Rectangle slide(const BaseType& xMove, const BaseType& yMove) const throw() { return Rectangle(*this).slide(xMove, yMove); } Rectangle slide(const Point<BaseType>& move) const throw() { return this->slide(move.getX(), move.getY()); } // on the edge is inner. bool isCollision(const Point<BaseType>& position) const throw() { return (this->leftTop.getX() <= position.getX() && this->leftTop.getY() <= position.getY() && this->rightBottom.getX() >= position.getX() && this->rightBottom.getY() >= position.getY()); } bool isCollision(const Rectangle& source) const throw() { const BaseType left = this->getLeft() > source.getLeft() ? this->getLeft() : source.getLeft(); const BaseType top = this->getTop() > source.getTop() ? this->getTop() : source.getTop(); const BaseType right = this->getRight() < source.getRight() ? this->getRight() : source.getRight(); const BaseType bottom = this->getBottom() < source.getBottom() ? this->getBottom() : source.getBottom(); if (left > right || top > bottom) return false; return true; } Rectangle getProjection(const Rectangle& target) const { Rectangle conflictArea = this->getIntersection(target); conflictArea.slide(-1 * this->getLeft(), -1 * this->getTop()); return conflictArea; } Rectangle getUnion(const Rectangle& target) const { typedef UnitType number_t; return Rectangle( this->getLeft() < target.getLeft() ? this->getLeft() : target.getLeft(), this->getTop() < target.getTop() ? this->getTop() : target.getTop(), this->getRight() > target.getRight() ? this->getRight() : target.getRight(), this->getBottom() > target.getBottom() ? this->getBottom() : target.getBottom()); } Rectangle getIntersection(const Rectangle& target) const { typedef UnitType number_t; return Rectangle( this->getLeft() > target.getLeft() ? this->getLeft() : target.getLeft(), this->getTop() > target.getTop() ? this->getTop() : target.getTop(), this->getRight() < target.getRight() ? this->getRight() : target.getRight(), this->getBottom() < target.getBottom() ? this->getBottom() : target.getBottom()); } UnitType getWidth() const throw() { return this->getRight() - this->getLeft(); } UnitType getHeight() const throw() { return this->getBottom() - this->getTop(); } friend std::ostream& operator<<(std::ostream& out, const Rectangle<UnitType>& self) { return out << "(" << self.getLeft() << ", " << self.getTop() << ", " << self.getRight() << ", " << self.getBottom() << ")"; } }; } #endif /* GEOMETRY_HPP_ */
[ "bpokazakijr@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 389 ] ] ]
d54c160ff12cd3d63b8e701890de7aed69588399
d0cf8820b4ad21333e15f7cec1e4da54efe1fdc5
/DES_GOBSTG/DES_GOBSTG/Process/processResault.cpp
bdc9a3bff1a85d68d62b21baffac86c2e4e27a61
[]
no_license
CBE7F1F65/c1bf2614b1ec411ee7fe4eb8b5cfaee6
296b31d342e39d1d931094c3dfa887dbb2143e54
09ed689a34552e62316e0e6442c116bf88a5a88b
refs/heads/master
2020-05-30T14:47:27.645751
2010-10-12T16:06:11
2010-10-12T16:06:11
32,192,658
0
0
null
null
null
null
GB18030
C++
false
false
14,036
cpp
#include "Process.h" #include "Scripter.h" #include "BResource.h" #include "Data.h" #include "DataConnector.h" #include "InfoSelect.h" #include "Selector.h" #include "SE.h" #include "DataPrinter.h" int Process::processResult() { static char maxpage[7]; static int pageindex[7][10]; static char tnowpage; time++; if(time == 1) { Selector::Clear(); CINT(scr.d[SCR_RESERVEBEGIN].value) = 0; CINT(scr.d[SCR_RESERVEBEGIN+1].value) = - 0xf; CINT(scr.d[SCR_RESERVEBEGIN+2].value) = - 0xf; CINT(scr.d[SCR_RESERVEBEGIN+3].value) = - 0xf; CINT(scr.d[SCR_RESERVEBEGIN+4].value) = 0; int roller[7]; for(int i=0;i<7;i++) { roller[i] = 0; maxpage[i] = 0; } for(vector<rangeData>::iterator i=res.rdata.begin();i!=res.rdata.end();i++) { if(!i->isrange) continue; BYTE thisdiff = data.getDiff(i->sno); if(roller[thisdiff] == 0) { pageindex[thisdiff][maxpage[thisdiff]] = i->sno; maxpage[thisdiff]++; } if(roller[6] == 0) { pageindex[6][maxpage[6]] = i->sno; maxpage[6]++; } roller[thisdiff]++; if(roller[thisdiff] == 10) { roller[thisdiff] = 0; } roller[6]++; if(roller[6] == 10) { roller[6] = 0; } } } if(hge->Input_GetDIKey(KS_BOMB, DIKEY_DOWN)) { SE::push(SE_SYSTEM_CANCEL); infoselect.clear(); int d62 = CINT(scr.d[SCR_RESERVEBEGIN+3].value); int d61 = CINT(scr.d[SCR_RESERVEBEGIN+2].value); int d60 = CINT(scr.d[SCR_RESERVEBEGIN+1].value); if(d61 >= 0) { CINT(scr.d[SCR_RESERVEBEGIN+2].value) = d61 - 0xf; if(d62 >= 0) CINT(scr.d[SCR_RESERVEBEGIN+3].value) = d62 - 0xf; else CINT(scr.d[SCR_RESERVEBEGIN+3].value) = -0xf; } else if(d60 >= 0) { CINT(scr.d[SCR_RESERVEBEGIN+1].value) = d60 - 0xf; if(d61 >= 0) CINT(scr.d[SCR_RESERVEBEGIN+2].value) = d61 - 0xf; else CINT(scr.d[SCR_RESERVEBEGIN+2].value) = -0xf; if(d62 >= 0) CINT(scr.d[SCR_RESERVEBEGIN+3].value) = d62 - 0xf; else CINT(scr.d[SCR_RESERVEBEGIN+3].value) = -0xf; } else { time = 0; state = STATE_TITLE; return PTURN; } } else if (hge->Input_GetDIKey(DIK_D, DIKEY_DOWN)) { DataPrinter::PrintScore(); } scr.controlExecute(STATE_RESAULT, time); //-> pushtimer sec diffi chara nowpage if(retvalue == POK) { int tpushtimer = CINT(scr.d[SCR_RESERVEBEGIN].value); int tsec = CINT(scr.d[SCR_RESERVEBEGIN+1].value); int tdiff = CINT(scr.d[SCR_RESERVEBEGIN+2].value); int tchara = CINT(scr.d[SCR_RESERVEBEGIN+3].value); int tnowpage = CINT(scr.d[SCR_RESERVEBEGIN+4].value); bool update = false; hge->Input_SetDIKey(KS_FIRE, false); if(hge->Input_GetDIKey(KS_BOMB, DIKEY_DOWN)) { tchara = -1; update = true; } if(tsec != 2) { if(hge->Input_GetDIKey(KS_LEFT, DIKEY_DOWN)) { SE::push(SE_SYSTEM_SELECT); if(tchara) tchara--; else tchara = tsec + 3; update = true; } else if(hge->Input_GetDIKey(KS_RIGHT, DIKEY_DOWN)) { SE::push(SE_SYSTEM_SELECT); if(tchara < tsec + 3) tchara++; else tchara = 0; update = true; } if(tsec) { if(hge->Input_GetDIKey(KS_UP) || hge->Input_GetDIKey(KS_DOWN)) { tpushtimer++; if(tpushtimer == M_PUSH_FIRST) tpushtimer = M_PUSH_ROLLTO; if(tpushtimer == M_PUSH_ROLLTO) { hge->Input_SetDIKey(KS_UP, false); hge->Input_SetDIKey(KS_DOWN, false); } } else { tpushtimer = 0; } if(hge->Input_GetDIKey(KS_UP, DIKEY_DOWN)) { SE::push(SE_SYSTEM_SELECT); if(tnowpage) tnowpage--; else tnowpage = maxpage[tdiff]-1; update = true; } else if(hge->Input_GetDIKey(KS_DOWN, DIKEY_DOWN)) { SE::push(SE_SYSTEM_SELECT); if(tnowpage < maxpage[tdiff]-1) tnowpage++; else tnowpage = 0; update = true; } } } if(!infoselect.size()) { if(!tsec) { InfoSelect _ifs[11]; for(int i=0;i<10;i++) { DWORD sec; sec = data.sLinkType(DATAS_TOP); sec = data.sLinkDiff(sec, tdiff); sec = data.sLinkChara(sec, tchara); sec = data.sLinkNum(sec, i+1); strcpy(_ifs[i].info, ""); _ifs[i].linki("|10002", i+1); strcat(_ifs[i].info, ".|004"); strcat(_ifs[i].info, data.sRead(DATA_BINFILE, sec, data.nLinkType(DATAN_USERNAME), RESCONFIGDEFAULT_USERNAME)); _ifs[i].linkl("|11325", data.lRead(DATA_BINFILE, sec, data.nLinkType(DATAN_SCORE), 0)); BYTE tlaststage = data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_LASTSTAGE), 0); strcat(_ifs[i].info, "("); switch(tlaststage) { case 1: strcat(_ifs[i].info, M_LASTSTAGESTR_1); break; case 2: strcat(_ifs[i].info, M_LASTSTAGESTR_2); break; case 3: strcat(_ifs[i].info, M_LASTSTAGESTR_3A); break; case 4: strcat(_ifs[i].info, M_LASTSTAGESTR_3B); break; case 5: strcat(_ifs[i].info, M_LASTSTAGESTR_4); break; case 6: strcat(_ifs[i].info, M_LASTSTAGESTR_5); break; case 7: strcat(_ifs[i].info, M_LASTSTAGESTR_6A); break; case 8: strcat(_ifs[i].info, M_LASTSTAGESTR_6B); break; default: strcat(_ifs[i].info, M_LASTSTAGESTR_C); break; } strcat(_ifs[i].info, ")"); _ifs[i].linki("|13036", data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_ALIVENESS), 0)); _ifs[i].linki("|23840", data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_TIME_MONTH), 0)); strcat(_ifs[i].info, "/"); _ifs[i].linki("|24143", data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_TIME_DAY), 0)); _ifs[i].linkf("|24550", 2, data.fRead(DATA_BINFILE, sec, data.nLinkType(DATAN_LOST), 0)); strcat(_ifs[i].info, "%"); _ifs[i].valueSet(i, _ifs[i].info, 30, 150+20*i, INFO_GREEN, true); infoselect.push_back(_ifs[i]); } _ifs[10].valueSet(10, " 序 名号|016得分(结束关)|032生符 日期 处理落率", 30, 130, INFO_RED, true); infoselect.push_back(_ifs[10]); InfoSelect::nselect = 0; InfoSelect::select = 0; } else if(tsec == 1) { int sno[10]; int maxindex = 0; bool save = false; for(vector<rangeData>::iterator i=res.rdata.begin();i!=res.rdata.end();i++) { if(!i->isrange) continue; if(i->sno == pageindex[tdiff][tnowpage]) { save = true; } if(save && (tdiff == M_NDIFFI || data.getDiff(i->sno) == tdiff)) { sno[maxindex] = i->sno; maxindex++; if(maxindex == 10) break; } } InfoSelect _ifs[11]; for(int i=0;i<maxindex;i++) { int tnget = 0; int tnmeet = 0; LONGLONG tmaxbonus = 0; tnget = data.nGet(sno[i], true, tchara); tnmeet = data.nMeet(sno[i], true, tchara); tmaxbonus = data.nHighScore(sno[i], 0, true, false, tchara); strcpy(_ifs[i].info, "R-"); _ifs[i].linki("|20205", data.getRangeNumber(sno[i])); strcat(_ifs[i].info, "|005"); if(data.raGetIndi(sno[i])) { strcat(_ifs[i].info, data.getRangeName(sno[i])); if(tnget) _ifs[i].coltype = INFO_GREEN; else _ifs[i].coltype = INFO_YELLOW; } else { strcat(_ifs[i].info, DATA_DEFAULTSTR_WIDE); _ifs[i].coltype = INFO_GRAY; } _ifs[i].linki("|13135", tnget); strcat(_ifs[i].info, "/"); _ifs[i].linki("|13640", tnmeet); strcat(_ifs[i].info, "("); switch(data.getDiff(sno[i])) { case M_DIFFI_EASY: strcat(_ifs[i].info, "E"); break; case M_DIFFI_NORMAL: strcat(_ifs[i].info, "N"); break; case M_DIFFI_HARD: strcat(_ifs[i].info, "H"); break; case M_DIFFI_EXTRA: strcat(_ifs[i].info, "X"); break; case M_DIFFI_PHANTASM: strcat(_ifs[i].info, "P"); break; case M_DIFFI_DESTINY: strcat(_ifs[i].info, "D"); break; } strcat(_ifs[i].info, ")"); _ifs[i].linkl("|14252", tmaxbonus); _ifs[i].valueSet(i, _ifs[i].info, 30, i*20+150, _ifs[i].coltype, true); infoselect.push_back(_ifs[i]); } _ifs[10].valueSet(10, " 序|008领域界名|020取得数/挑战数(难易度)|044最高得点", 30, 130, INFO_RED, true); infoselect.push_back(_ifs[10]); InfoSelect::nselect = 0; InfoSelect::select = 0; } else { InfoSelect _ifs[9]; char buff[M_STRITOAMAX]; strcpy(_ifs[0].info, DATASTR_TOTAL_GAMETIME); LONGLONG tltotalplaytime = data.lRead(DATA_BINFILE, data.sLinkType(DATAS_TOTAL), data.nLinkType(DATAN_TOTALPLAYTIME), 0) / 10000000; int tplayhour = tltotalplaytime / 3600; int tplayminute = (tltotalplaytime / 60) % 60; int tplaysecond = tltotalplaytime % 60; _ifs[0].linki("|014", tplayhour); strcat(_ifs[0].info, ":"); if(tplayminute < 10) strcat(_ifs[0].info, "0"); strcat(_ifs[0].info, itoa(tplayminute, buff, 10)); strcat(_ifs[0].info, ":"); if(tplaysecond < 10) strcat(_ifs[0].info, "0"); strcat(_ifs[0].info, itoa(tplaysecond, buff, 10)); _ifs[0].valueSet(0, _ifs[0].info, 40, 120, INFO_BLUE, true); char buffer[M_STRMAX]; strcpy(buffer, DATASTR_TOTAL_PLAYTIME); strcat(buffer, "|017"); strcat(buffer, M_DIFFISTR_EASY); strcat(buffer, "|022"); strcat(buffer, M_DIFFISTR_NORMAL); strcat(buffer, "|027"); strcat(buffer, M_DIFFISTR_HARD); strcat(buffer, "|032"); strcat(buffer, M_DIFFISTR_EXTRA); strcat(buffer, "|037"); strcat(buffer, M_DIFFISTR_PHANTASM); strcat(buffer, "|042"); strcat(buffer, DATASTR_TOTAL_PLAYTIME_ALL); _ifs[1].valueSet(1, buffer, 40, 160, INFO_GREEN, true); int tplaytime[M_NCHARA+1][M_NSTAGEDIFFI+1]; int tcleartime[M_NSTAGEDIFFI+1]; int tpracticetime[M_NSTAGEDIFFI+1]; for(int i=0;i<M_NCHARA+1;i++) tplaytime[i][M_NSTAGEDIFFI] = 0; for(int i=0;i<M_NSTAGEDIFFI+1;i++) { tplaytime[M_NCHARA][i] = 0; tcleartime[i] = 0; tpracticetime[i] = 0; } for(int i=0;i<M_NCHARA;i++) { for(int j=0;j<M_NSTAGEDIFFI;j++) { DWORD sec; sec = data.sLinkType(DATAS_TOTAL); sec = data.sLinkDiff(sec, j); sec = data.sLinkChara(sec, i); tplaytime[i][j] = data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_PLAYTIME), 0); tplaytime[i][M_NSTAGEDIFFI] += tplaytime[i][j]; tplaytime[M_NCHARA][j] += tplaytime[i][j]; tcleartime[j] += data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_CLEARTIME), 0); tpracticetime[j] += data.iRead(DATA_BINFILE, sec, data.nLinkType(DATAN_PRACTICETIME), 0); } tplaytime[M_NCHARA][M_NSTAGEDIFFI] += tplaytime[i][M_NSTAGEDIFFI]; } for (int i=0; i<M_NSTAGEDIFFI; i++) { tcleartime[M_NSTAGEDIFFI] += tcleartime[i]; tpracticetime[M_NSTAGEDIFFI] += tpracticetime[i]; } strcpy(_ifs[2].info, M_CHARASTR_FULL_SPACED_SHI_LINGYE); strcpy(_ifs[3].info, M_CHARASTR_FULL_SPACED_NUSIKUIMA_GEJI); strcpy(_ifs[4].info, M_CHARASTR_FULL_SPACED_CILAN_ZANGYUE); strcpy(_ifs[5].info, M_CHARASTR_FULL_SPACED_WUSHUANG); strcpy(_ifs[6].info, DATASTR_TOTAL_SPACED_ALLCHARA); for(int i=0;i<M_NCHARA+1;i++) { _ifs[i+2].linki("|11419", tplaytime[i][0]); _ifs[i+2].linki("|11924", tplaytime[i][1]); _ifs[i+2].linki("|12429", tplaytime[i][2]); _ifs[i+2].linki("|12934", tplaytime[i][3]); _ifs[i+2].linki("|13439", tplaytime[i][4]); _ifs[i+2].linki("|13945", tplaytime[i][5]); _ifs[i+2].valueSet(i+2, _ifs[i+2].info, 40, i*25+192+i/4*12, INFO_BLUE, true); } strcpy(_ifs[7].info, DATASTR_TOTAL_SPACED_CLEARTIME); _ifs[7].linki("|11419", tcleartime[0]); _ifs[7].linki("|11924", tcleartime[1]); _ifs[7].linki("|12429", tcleartime[2]); _ifs[7].linki("|12934", tcleartime[3]); _ifs[7].linki("|13439", tcleartime[4]); _ifs[7].linki("|13945", tcleartime[5]); _ifs[7].valueSet(7, _ifs[7].info, 40, 340, INFO_YELLOW, true); strcpy(_ifs[8].info, DATASTR_TOTAL_SPACED_PRACTICETIME); _ifs[8].linki("|11419", tpracticetime[0]); _ifs[8].linki("|11924", tpracticetime[1]); _ifs[8].linki("|12429", tpracticetime[2]); _ifs[8].linki("|12934", tpracticetime[3]); _ifs[8].linki("|13439", tpracticetime[4]); _ifs[8].linki("|13945", tpracticetime[5]); _ifs[8].valueSet(8, _ifs[8].info, 40, 370, INFO_YELLOW, true); for(int i=0;i<9;i++) { infoselect.push_back(_ifs[i]); } InfoSelect::nselect = 0; InfoSelect::select = 0; } } if(tsec == 2) { if(infoselect.size() > 9) infoselect.pop_back(); InfoSelect _ifs; char buff[M_STRITOAMAX]; strcpy(_ifs.info, DATASTR_TOTAL_RUNTIME); LONGLONG tldiffruntime = data.getTotalRunTime(); int trunhour = tldiffruntime / 3600; int trunminute = (tldiffruntime / 60) % 60; int trunsecond = tldiffruntime % 60; _ifs.linki("|014", trunhour); strcat(_ifs.info, ":"); if(trunminute < 10) strcat(_ifs.info, "0"); strcat(_ifs.info, itoa(trunminute, buff, 10)); strcat(_ifs.info, ":"); if(trunsecond < 10) strcat(_ifs.info, "0"); strcat(_ifs.info, itoa(trunsecond, buff, 10)); _ifs.valueSet(9, _ifs.info, 40, 100, INFO_RED, true); infoselect.push_back(_ifs); } if(update) { CINT(scr.d[SCR_RESERVEBEGIN+1].value) = tsec; CINT(scr.d[SCR_RESERVEBEGIN+2].value) = tdiff; CINT(scr.d[SCR_RESERVEBEGIN+3].value) = tchara; CINT(scr.d[SCR_RESERVEBEGIN+4].value) = tnowpage; infoselect.clear(); } CINT(scr.d[SCR_RESERVEBEGIN].value) = tpushtimer; } retvalue = PGO; return PGO; }
[ "CBE7F1F65@e00939f0-95ee-11de-8df0-bd213fda01be" ]
[ [ [ 1, 490 ] ] ]
1be6772738f804c8ff420866b98d916b1e6387d3
4506e6ceb97714292c3250023b634c3a07b73d5b
/rpg2kLib/rpg2k/exclude/gamemode/Menu.cpp
33041f68bfc5691607e42456d325cef8bf70e3a8
[]
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
17,220
cpp
#include "../Audio2D.hpp" #include "../Graphics2D.hpp" #include "../KeyListener.hpp" #include "../Main.hpp" #include "../Project.hpp" namespace rpg2k { namespace gamemode { #define PP_upDown() \ switch( keyList.getCursor() ) { \ case Key::DOWN: if( incCursor() ) getOwner().getAudio2D().playSound(getOwner().getProject().getLDB()[22].getArray1D()[41]); break; \ case Key::UP : if( decCursor() ) getOwner().getAudio2D().playSound(getOwner().getProject().getLDB()[22].getArray1D()[41]); break; \ default: break; \ } Equip::Equip(rpg2k::Main& m) : GameMode(m) { structure::Array1D& voc = getOwner().getProject().getLDB()[21]; // status name for(int i = 0; i < EQ_PARAM_NUM; i++) status_.push_back( voc[0x84 + i] ); // equipment name for(int i = 0; i < rpg2k::Equip::END; i++) equip_.push_back( voc[0x88 + i] ); } void Equip::draw(Graphics2D& g) { model::Project& proj = getOwner().getProject(); model::SaveData const& lsd = proj.getLSD(); model::DataBase const& ldb = proj.getLDB(); structure::Array2D const& item = ldb[13]; int curCharID = lsd.member( cursor(0) ); structure::Array1D const& curChar = lsd[108].getArray2D()[curCharID]; std::vector< uint16_t > curCharEquip = curChar[61].getBinary(); // window g.drawWindow( Vector2D( 0, 0), Size2D(SCREEN_SIZE[0], 32) ); g.drawWindow( Vector2D( 0, 32), Size2D(124, 96) ); g.drawWindow( Vector2D(124, 32), Size2D(196, 96) ); g.drawWindow( Vector2D( 0, 128), Size2D(SCREEN_SIZE[0], 124) ); // cursor // comment switch( cursorNum() ) { case 2: g.drawCursor( Vector2D(128, cursor(1)*16+40) + cursorMove(8), Size2D(188, 16) ); if( curCharEquip[cursor(1)] ) g.drawString( item[ curCharEquip[cursor(1)] ][2], Vector2D(8, 10) ); break; case 3: g.drawCursorPassive( Vector2D(128, cursor(1)*16+40), Size2D(188, 16) ); g.drawString( item[ idList_[cursor(1)] ][2], Vector2D(8, 8) ); break; } // status g.drawString( proj.name(curCharID), Vector2D(8, 42) ); for(int i = 0; i < EQ_PARAM_NUM; i++) g.drawString(status_[i], Vector2D(8, 58 + CURSOR_H*i), font::FNT_STATUS); // equipment for(int i = 0; i < rpg2k::Equip::END; i++) { g.drawString(equip_[i], Vector2D(132, 42 + CURSOR_H*i), font::FNT_STATUS); if( curCharEquip[i] ) g.drawString( item[ curCharEquip[i] ][1] , Vector2D(132 + font::FULL_FONT_W*5, 42 + CURSOR_H*i) ); } // item list } void Equip::run(input::KeyListener& keyList) { if( cursorCountLeft() ) return; model::Project& proj = getOwner().getProject(); model::SaveData& lsd = proj.getLSD(); switch( cursorNum() ) { case 2: // select equip type if( keyList.cancel() ) removeLastCursor(); // skip return to source char select PP_upDown() switch( keyList.getCursor() ) { case Key::RIGHT: incCursor(0); break; case Key::LEFT : decCursor(0); break; default: break; } break; case 3: // select equiping item break; if( keyList.enter() ) { proj.unequip( lsd.member( cursor(0) ), rpg2k::Equip::Type( cursor(1) ) ); proj. equip( lsd.member( cursor(0) ), idList_[ cursor(2) ] ); removeLastCursor(); } switch( keyList.getCursor() ) { case Key::UP : decCursor(); cursor()--; break; case Key::RIGHT: incCursor(); break; case Key::LEFT : decCursor(); break; case Key::DOWN : incCursor(); cursor()++; break; default: break; } break; } if( keyList.cancel() ) { if( cursorNum() <= 2 ) getOwner().returnGameMode(); else removeLastCursor(); } } void Equip::reset() { clearCursor(); } void Equip::gameModeChanged() { } void Equip::pass(int val) { clearCursor(); addCursor( getOwner().getProject().getLSD().memberNum() ); cursor(0) = val; addCursor( rpg2k::Equip::END ); } Item::Item(rpg2k::Main& m) : GameMode(m) { } void Item::draw(Graphics2D& g) { model::Project& proj = getOwner().getProject(); model::SaveData& lsd = proj.getLSD(); model::DataBase& ldb = proj.getLDB(); std::ostringstream ss; switch( cursorNum() ) { case 1: { // select item std::map< uint16_t, model::SaveData::Item >& itemList = lsd.item(); structure::Array2D const& item = ldb[13]; g.drawWindow( Vector2D(0, 0), Size2D(SCREEN_SIZE[0], 32) ); g.drawWindow( Vector2D(0, 32), SCREEN_SIZE - Size2D(0, 32) ); g.drawCursor( Vector2D(4, 42) + Vector2D( cursor() % 2 * 160, cursor() / 2 * CURSOR_H ), Size2D(152, CURSOR_H) ); int index = 0; for(std::map< uint16_t, model::SaveData::Item >::const_iterator it = itemList.begin(); it != itemList.end(); ++it) { Vector2D base = Vector2D(8, 42) + Vector2D( index % 2 * 160, index / 2 * CURSOR_H ); if( cursor() == index ) { g.drawString( item[it->first][2], Vector2D(8, 10) ); } g.drawString(item[it->first][1], base); ss.str(""); ss << ":" << std::setw(2) << it->second.num; g.drawString( ss.str(), base + Vector2D( font::HALF_FONT_W*21, 0 ) ); index++; } } break; case 2: // select char break; } } void Item::run(input::KeyListener& keyList) { if( cursorCountLeft() ) return; switch( cursorNum() ) { // item case 1: // select item if( keyList.enter() ) addCursor( getOwner().getProject().getLSD().item().size() + 1 ); switch( keyList.getCursor() ) { case Key::UP : decCursor(); cursor()--; break; case Key::RIGHT: incCursor(); break; case Key::LEFT : decCursor(); break; case Key::DOWN : incCursor(); cursor()++; break; default: break; } break; case 2: // select char if( keyList.cancel() ) { cursorMax(0) = getOwner().getProject().getLSD().item().size() + 1; if( cursor(0) >= cursorMax(0) ) cursor(0) = cursorMax(0) - 1; } break; } if( keyList.cancel() ) { if( cursorNum() <= 1 ) getOwner().returnGameMode(); else removeLastCursor(); } } void Item::reset() { clearCursor(); } void Item::gameModeChanged() { clearCursor(); addCursor( getOwner().getProject().getLSD().item().size() + 1 ); } void Item::pass(int val) { } Skill::Skill(rpg2k::Main& m) : GameMode(m) { } void Skill::draw(Graphics2D& g) { model::Project& proj = getOwner().getProject(); // model::SaveData& lsd = proj.getLSD(); model::DataBase& ldb = proj.getLDB(); std::ostringstream ss; switch( cursorNum() ) { case 2: { // select skill structure::Array2D const& skill = ldb[12]; g.drawWindow( Vector2D(0, 32*0), Size2D(SCREEN_SIZE[0], 32) ); if( cursor() != (int)idList_.size() ) { g.drawString( skill[ idList_[ cursor() ] ][2], Vector2D(8, 10) ); } g.drawWindow( Vector2D(0, 32*1), Size2D(SCREEN_SIZE[0], 32) ); // name Vector2D base(8, 32 + 10); g.drawString( proj.name(curCharID_), base ); // level base += Vector2D( font::HALF_FONT_W*14, 0 ); g.drawString( ldb.vocabulary(128), base, font::FNT_STATUS ); base += Vector2D( font::FULL_FONT_W*1, 0 ); ss.str(""); ss << proj.level(curCharID_); g.drawString( ss.str(), base ); // condition base += Vector2D( font::HALF_FONT_W*5, 0 ); g.drawString( proj.condition(curCharID_), base, proj.conditionColor(curCharID_) ); // HP base += Vector2D( font::HALF_FONT_W*10, 0 ); g.drawString( ldb.vocabulary(129), base, font::FNT_STATUS ); base += Vector2D( font::FULL_FONT_W*1, 0 ); ss.str(""); ss << std::setw(3) << proj.hp(curCharID_) << "/" << std::setw(3) << proj.param(curCharID_, Param::HP); g.drawString( ss.str(), base ); // MP base += Vector2D( font::HALF_FONT_W*9, 0 ); g.drawString( ldb.vocabulary(130), base, font::FNT_STATUS ); base += Vector2D( font::FULL_FONT_W*1, 0 ); ss.str(""); ss << std::setw(3) << proj.mp(curCharID_) << "/" << std::setw(3) << proj.param(curCharID_, Param::MP); g.drawString( ss.str(), base ); g.drawWindow( Vector2D(0, 32*2), SCREEN_SIZE - Size2D(0, 32*2) ); g.drawCursor( Vector2D(4, 72) + Vector2D( cursor() % 2 * 160, cursor() / 2 * CURSOR_H ), Size2D(152, CURSOR_H) ); int index = 0; for(std::vector< uint16_t >::const_iterator it = idList_.begin(); it != idList_.end(); ++it) { if( *it == 0 ) break; base = Vector2D(8, 74) + Vector2D( index % 2 * 160, index / 2 * CURSOR_H ); g.drawString(skill[*it][1], base); ss.str(""); ss << "-" << std::setw(3) << skill[*it][11].get<int>(); g.drawString( ss.str(), base + Vector2D( font::HALF_FONT_W*20, 0 ) ); index++; } } break; case 3: // select char break; } } void Skill::run(input::KeyListener& keyList) { if( cursorCountLeft() ) return; switch( cursorNum() ) { case 2: // select skill if( keyList.cancel() ) removeLastCursor(); // skip return to source char select switch( keyList.getCursor() ) { case Key::UP : --cursor(); decCursor(); break; case Key::RIGHT: incCursor(); break; case Key::LEFT : decCursor(); break; case Key::DOWN : ++cursor(); incCursor(); break; default: break; } break; case 3: // select destination char break; } if( keyList.cancel() ) { if( cursorNum() <= 2 ) getOwner().returnGameMode(); else removeLastCursor(); } } void Skill::reset() { clearCursor(); } void Skill::gameModeChanged() { } void Skill::pass(int val) { model::SaveData& lsd = getOwner().getProject().getLSD(); clearCursor(); addCursor( lsd.memberNum() ); cursor(0) = val; curCharID_ = lsd.member(val); idList_ = lsd[108].getArray2D()[curCharID_][52].getBinary(); idList_.push_back(INVALID_ID); addCursor( idList_.size() + 1 ); } Menu::Menu(rpg2k::Main& m) : GameMode(m) { structure::Array1D& voc = getOwner().getProject().getLDB()[21]; // top command for(int i = 0; i < 3; i++) command_.push_back( voc[0x6a + i] ); // save command_.push_back( voc[0x6e] ); // quit game command_.push_back( voc[0x70] ); // quit things quitMessage_ = voc[0x97].get_string(); yes_ = voc[0x98].get_string(); no_ = voc[0x99].get_string(); quitMessageW_ = font::Font::width(quitMessage_); yesNoW_ = yes_.length() > no_.length() ? font::Font::width(yes_) : font::Font::width(no_); } void Menu::reset() { gameModeChanged(); } void Menu::draw(Graphics2D& g) { g.drawWallpaper( Vector2D(0, 0), SCREEN_SIZE ); // model::Project& proj = getOwner().getProject(); // model::DataBase& ldb = proj.getLDB(); // model::SaveData& lsd = proj.getLSD(); if( cursorNum() == 1 ) drawMainMenu(g); else switch( cursor(0) ) { case MENU_SKILL: case MENU_EQUIP: drawMainMenu(g, true); break; case MENU_QUIT: g.drawWindow( Vector2D( (SCREEN_SIZE[0]-quitMessageW_-16)/2, 72 ), Size2D(quitMessageW_+16, 32) ); g.drawString(quitMessage_, Vector2D( (SCREEN_SIZE[0]-quitMessageW_)/2, 82 ), font::FNT_NORMAL); g.drawWindow( Vector2D( (SCREEN_SIZE[0]-yesNoW_-16)/2, 120 ), Size2D(yesNoW_+16, 48) ); g.drawCursor( Vector2D( (SCREEN_SIZE[0]-yesNoW_-8)/2, cursor()*CURSOR_H + 128 ) + cursorMove(), Size2D(yesNoW_+8, 16) ); g.drawString(yes_, Vector2D( (SCREEN_SIZE[0]-yesNoW_)/2, 130 ), font::FNT_NORMAL); g.drawString(no_ , Vector2D( (SCREEN_SIZE[0]-yesNoW_)/2, 146 ), font::FNT_NORMAL); break; default: break; } } void Menu::run(input::KeyListener& keyList) { if( cursorCountLeft() ) return; model::Project& proj = getOwner().getProject(); model::SaveData& lsd = proj.getLSD(); if( cursorNum() == 1 ) PP_upDown() switch( cursor(0) ) { case 0: switch( cursorNum() ) { // item case 1: // to item select if( keyList.enter() ) getOwner().callGameMode( GameMode::Item ); break; } break; case 1: switch( cursorNum() ) { // skill case 1: // to source char select if( keyList.enter() ) addCursor( lsd.memberNum() ); break; case 2: // select source char if( keyList.enter() ) { getOwner().passToGameMode( GameMode::Skill, cursor() ); removeLastCursor(); getOwner().callGameMode( GameMode::Skill ); return; } PP_upDown() break; } break; case 2: switch( cursorNum() ) { // equip case 1: // to char select if( keyList.enter() ) addCursor( lsd.memberNum() ); break; case 2: // select char if( keyList.enter() ) { getOwner().passToGameMode( GameMode::Equip, cursor() ); removeLastCursor(); getOwner().callGameMode( GameMode::Equip ); return; } PP_upDown() break; } break; case 3: switch( cursorNum() ) { // save case 1: if( keyList.enter() && proj.canSave() ) { getOwner().passToGameMode( GameMode::SaveManager, SaveManager::SAVE ); getOwner().callGameMode(GameMode::SaveManager); return; } break; } break; case 4: switch( cursorNum() ) { // quit case 1: if( keyList.enter() ) addCursor(2); break; case 2: if( keyList.enter() ) getOwner().gotoTitle(); else PP_upDown() break; } break; } if( keyList.cancel() ) { if( cursorNum() <= 1 ) getOwner().returnGameMode(); else removeLastCursor(); } } void Menu::gameModeChanged() { if( (cursorNum() != 1) || (cursor() != 4) ) { clearCursor(); addCursor( command_.size() ); } } void Menu::drawMainMenu(Graphics2D& g, bool charSelect) { model::Project& proj = getOwner().getProject(); model::SaveData& lsd = proj.getLSD(); model::DataBase& ldb = proj.getLDB(); std::ostringstream ss; // main menu g.drawWindow( Vector2D(0, 0), Size2D(88, 96) ); // cursor if(charSelect) g.drawCursorPassive( Vector2D(4, cursor(0)*16 + 8), Size2D(80, CURSOR_H) ); else g.drawCursor( Vector2D(4, cursor(0)*16 + 8) + cursorMove(), Size2D(80, CURSOR_H) ); // command font::FontColor c = lsd.memberNum() != 0 ? font::FNT_ENABLE : font::FNT_DISABLE; g.drawString(command_[0], Vector2D(8, 10 + CURSOR_H*0), font::FNT_ENABLE); g.drawString(command_[1], Vector2D(8, 10 + CURSOR_H*1), c); g.drawString(command_[2], Vector2D(8, 10 + CURSOR_H*2), c); g.drawString(command_[3], Vector2D(8, 10 + CURSOR_H*3), proj.canSave() ? font::FNT_ENABLE : font::FNT_DISABLE); g.drawString(command_[4], Vector2D(8, 10 + CURSOR_H*4), font::FNT_ENABLE); // money g.drawMoneyWindow( Vector2D( 0, 208) ); // char info g.drawWindow( Vector2D(88, 0), Size2D(232, 240) ); // char cursor if(charSelect) g.drawCursor( Vector2D(92, cursor(1)*58 + 4) + cursorMove(), Size2D(224, 56) ); std::vector< uint16_t >& mem = lsd.member(); for(uint i = 0; i < mem.size(); i++) { uint charID = mem[i]; Vector2D base(88 + 8, 8 + (FACE_SIZE[1] + 10)*i); g.drawFaceSet( proj.faceSet(charID), proj.faceSetPos(mem[i]), base ); base += Vector2D(FACE_SIZE[0] + 8, 3); g.drawString( proj.name(charID), base); g.drawString( proj.title(charID), base + Vector2D(font::HALF_FONT_W*15, 0) ); base += Vector2D(0, font::FONT_H + 3); // level g.drawString(ldb.vocabulary(128), base, font::FNT_STATUS); ss.str(""); ss << std::setw(2) << proj.level(charID); g.drawString( ss.str(), base + Vector2D(font::FULL_FONT_W, 0) ); // condition g.drawString( proj.condition(charID), base + Vector2D(font::HALF_FONT_W*7, 0), proj.conditionColor(charID) ); // HP g.drawString( ldb.vocabulary(129), base + Vector2D(font::HALF_FONT_W*18, 0), font::FNT_STATUS ); ss.str(""); ss << std::setw(3) << proj.hp(charID) << "/" << std::setw(3) << proj.param(charID, Param::HP); g.drawString( ss.str(), base + Vector2D(font::HALF_FONT_W*20, 0) ); base += Vector2D(0, font::FONT_H + 3); // experience g.drawString(ldb.vocabulary(127), base, font::FNT_STATUS); ss.str(""); if( proj.level(charID) >= LV_MAX ) ss << RPG2kString(6, '-') << "/" << RPG2kString(6, '-'); else ss << std::setw(6) << proj.exp(charID) << "/" << std::setw(6) << proj.nextLevelExp(charID); g.drawString( ss.str(), base + Vector2D(font::FULL_FONT_W, 0) ); // MP g.drawString( ldb.vocabulary(130), base + Vector2D(font::HALF_FONT_W*18, 0), font::FNT_STATUS ); ss.str(""); ss << std::setw(3) << proj.mp(charID) << "/" << std::setw(3) << proj.param(charID, Param::MP); g.drawString( ss.str(), base + Vector2D(font::HALF_FONT_W*20, 0) ); } } void Menu::pass(int val) { } } // namespace gamemode } // namespace rpg2k
[ "takechi101010@07b74652-1305-11df-902e-ef6c94960d2c" ]
[ [ [ 1, 506 ] ] ]
d0ad27afa02642130818f6555070c1c09b4a4831
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HHVClientDemo/HHVClientDemo/HHVClient.cpp
1824ac2321518ade1f8f231bef62a1e852e6d6a9
[]
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
GB18030
C++
false
false
3,266
cpp
// HHVClient.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "HHVClient.h" #include "HHVClientDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CHHVClientApp BEGIN_MESSAGE_MAP(CHHVClientApp, CWinApp) //{{AFX_MSG_MAP(CHHVClientApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHHVClientApp construction CHHVClientApp::CHHVClientApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CHHVClientApp object CHHVClientApp theApp; ///////////////////////////////////////////////////////////////////////////// // CHHVClientApp initialization BOOL CHHVClientApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif //获取当前路径 GetModuleFileName(NULL,m_szCurPath.GetBuffer(MAX_PATH),MAX_PATH); m_szCurPath.ReleaseBuffer(); m_szCurPath = m_szCurPath.Left(m_szCurPath.ReverseFind('\\') + 1); //setting配置文件路径 CString szSettingPath; szSettingPath = m_szCurPath + "setting.ini"; //语言配置文件路径 CString szLang; szLang="English"; DWORD dwSize = 1000; GetPrivateProfileString("Setting","Language",_T("Chinese"),szLang.GetBuffer(dwSize),dwSize,szSettingPath); m_szLanguagePath=m_szCurPath + _T("Language\\")+szLang+_T(".ini"); CHHVClientDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } /********************************************************************* * 函数名称:m_LoadString * 说明: 根据标识 szID到选定的语言文件中加载字符串 *********************************************************************/ CString CHHVClientApp::m_LoadString(CString szID) { CString szValue; DWORD dwSize = 1000; GetPrivateProfileString(_T("String"),szID,_T("Not found"), szValue.GetBuffer(dwSize),dwSize,m_szLanguagePath); szValue.ReleaseBuffer(); szValue.Replace(_T("\\n"),_T("\n")); //替换回换行符号 return szValue; }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 108 ] ] ]
1313fd5804d1104edb6a0e7c5ac2fec96996714e
df5277b77ad258cc5d3da348b5986294b055a2be
/GameEngineV0.35/Source/CameraController.h
22e074b1fc4eea7f337f0ce8e51da3f0e57a6bf5
[]
no_license
beentaken/cs260-last2
147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22
61b2f84d565cc94a0283cc14c40fb52189ec1ba5
refs/heads/master
2021-03-20T16:27:10.552333
2010-04-26T00:47:13
2010-04-26T00:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
#pragma once #include "IController.h" #include "GameMessages.h" namespace Framework { class CameraController : public Controller { public: CameraController( void ) : Controller(CID_Camera) {;} virtual ~CameraController () {;} virtual void Serialize (ISerializer& stream); virtual void SendMessage (Message* message); private: virtual void OnInitialize ( void ); virtual void LogicalUpdate ( float dt ); virtual void DestroyCheck () { /* we dont want to be destroyed */ } void HandleUpdateMessage(UpdateMessage* mess); }; }
[ "westleyargentum@af704e40-745a-32bd-e5ce-d8b418a3b9ef" ]
[ [ [ 1, 26 ] ] ]
94d1d02071588697304d23ac509e737dd40eca38
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/vutil.cpp
29f6c6b0baa295e66f7c79a7f5d8bcb4e073cb7e
[]
no_license
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
UHC
C++
false
false
18,399
cpp
#include "stdafx.h" #include <wingdi.h> #include <tchar.h> #include <stdio.h> #include "D3DX9.h" #include "File.h" #include "Debug.h" #if !defined(__SERVER) #include "targa.h" #endif int GetCharLen( const CHAR* pStr ) { char* pNext = CharNext( pStr ); return (int) (pNext - pStr ); } // 외국어포함 문장의 길이를 잘라준다. int GetStrCut( const CHAR* pSrc, CHAR* pDest, int nCount ) { int nOffset = 0; int nLen; while( nCount ) { nLen = GetCharLen( &pSrc[ nOffset ] ); nOffset += nLen; nCount--; } memcpy( pDest, pSrc, sizeof(char)*nOffset); return 1; } // 외국어포함 문자 갯수를 알아냄 int GetStrLen( const CHAR* pSrc ) { int nCount = 0; int nOffset = 0; int nLen; while( pSrc[ nOffset ] != NULL ) { nLen = GetCharLen( &pSrc[ nOffset ] ); nOffset += nLen; nCount++; } return nCount; } int CopyChar( const char* pSrc, char* pDest ) { const char* pNext = CharNextEx(pSrc); memcpy(pDest, pSrc, pNext - pSrc); return pNext - pSrc; } BOOL IsMultiByte( const char* pSrc ) { return ( CharNextEx(pSrc) - pSrc ) > 1; } BOOL IsNative( LPCTSTR lpszStr ) { ASSERT( g_codePage != 0 ); LPCWSTR pwSrc = (LPCWSTR) lpszStr; if( g_codePage == 874 ) // 타이 { return (BYTE)*lpszStr >= 0xa1 && (BYTE)*lpszStr <= 0xfb; } else if( g_codePage == 949 ) // 한글 { return IsHangul( *pwSrc ); } else if( g_codePage == 932 ) // 일본 { return IsDBCSLeadByte( (BYTE)( *pwSrc ) ); } else if( g_codePage == 936 ) // 한자 : 중국 { return IsDBCSLeadByte( (BYTE)( *pwSrc ) ); } else if( g_codePage == 950 ) // 한자 : 대만 { // return IsDBCSLeadByte( *pwSrc ); if( ((BYTE)*lpszStr >= 0xCA && (BYTE)*lpszStr <= 0xFD) && ( (BYTE)*lpszStr+1 >= 0xA1 ) && ( (BYTE)*lpszStr+1 <= 0xFE) ) { return TRUE; } else if ( ( ( (BYTE)*lpszStr >= 0x41 ) && ( (BYTE)*lpszStr <= 0x5A ) ) || ( ( (BYTE)*lpszStr >= 0x61 ) && ( (BYTE)*lpszStr <= 0x7A) ) ) { return TRUE; } else if( isdigit2( (BYTE)*lpszStr ) ) return TRUE; } return FALSE; } BOOL IsHangul( WORD word ) { BYTE l = word & 0xff; BYTE h = word >> 8; // 특수 문자, 일어 기타 언어 FALSE if( h >= 0xa1 && h <= 0xac && l >= 0xa0 && l <= 0xff ) return FALSE; // 확장 완성형 if( h >= 0x81 && h <= 0xc6 && l >= 0x41 && l <= 0xfe ) return TRUE; // 완성형 코드 if( h >= 0xb0 && h <= 0xc8 && l >= 0xa1 && l <= 0xfe ) return TRUE; return FALSE; } void SetStrNull( TCHAR* lpStr, int nNullLength ) { int nLength = strlen( lpStr ); // 0을 넣을 포지션이 실제 스트링 길이보다 길면 실제 스트링 길이로 맞출 필요가 있음 if( nNullLength > nLength ) nNullLength = nLength; int i; for( i = 0; i < nNullLength; ) { #ifdef __CLIENT if( ::GetLanguage() == LANG_THA && g_codePage == 874 ) // 타이 i++; else if(::GetLanguage() == LANG_VTN && g_codePage == 1258) i++; else #endif//__CLIENT if( IsDBCSLeadByte( lpStr[ i ] ) ) i+=2; else i++; } // i가 nLength 보다 크다면 Word캐릭터일 것이고, 끝부분이 깨져서 오차가 생긴 것이다. if( i > nNullLength ) lpStr[ i - 2 ] = 0; else lpStr[ i ] = 0; } void SetStrNull( CString& string, int nNullLength ) { int nLength = string.GetLength(); // 0을 넣을 포지션이 실제 스트링 길이보다 길면 실제 스트링 길이로 맞출 필요가 있음 if( nNullLength > nLength ) nNullLength = nLength; int i; for( i = 0; i < nNullLength; ) { #ifdef __CLIENT if( ::GetLanguage() == LANG_THA && g_codePage == 874 ) // 타이 i++; else if(::GetLanguage() == LANG_VTN && g_codePage == 1258) i++; else #endif//__CLIENT if( IsDBCSLeadByte( string[ i ] ) ) i+=2; else i++; } // i가 nLength 보다 크다면 Word캐릭터일 것이고, 끝부분이 깨져서 오차가 생긴 것이다. if( i > nNullLength ) string = string.Left( i - 2 ); else string = string.Left( i ); } #if defined (__WORLDSERVER) || defined (__CLIENT) HRESULT LoadTextureFromRes( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR strTexture, LPDIRECT3DTEXTURE9* ppTexture, DWORD MipFilter, D3DFORMAT d3dFormat ) { return LoadTextureFromRes( pd3dDevice, strTexture, D3DX_DEFAULT, D3DX_DEFAULT, MipFilter, 0, d3dFormat, D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, 0, NULL, NULL, ppTexture ); } HRESULT LoadTextureFromRes( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pFileName, UINT Width, UINT Height, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DTEXTURE9 *ppTexture ) { HRESULT hr = E_FAIL; CResFile file; if( file.Open( pFileName, "rb" ) == FALSE ) { LPCTSTR szErr = Error( "::LoadTextureFromRes : %s not found", pFileName ); ADDERRORMSG( szErr ); return E_FAIL; } int nSrcDataSize = file.GetLength(); LPBYTE pSrcData = new BYTE[ nSrcDataSize ]; if( file.Read( pSrcData, nSrcDataSize ) >= 1 ) { hr = D3DXCreateTextureFromFileInMemoryEx( pDevice, pSrcData, nSrcDataSize, Width, Height, MipLevels, Usage, Format, Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); if( FAILED( hr ) ) { LPCTSTR szErr = Error( "D3DXCreateTextureFromFileInMemoryEx %s %s", pFileName, DXGetErrorString9( hr ) ); ADDERRORMSG( szErr ); } } SAFE_DELETE_ARRAY( pSrcData ); return hr; } char g_szCrashClient[1024]; void PaintTexture( LPVOID pDestData, LPIMAGE pImage, CPoint pt, CSize sizeSurface, D3DFORMAT d3dFormat ) { memset( g_szCrashClient, 0, sizeof(char) * 1024 ); strcat( g_szCrashClient, "\nPaintTexture - IN" ); SIZE sizeTexture = pImage->size; DWORD dwOffsetSrc = 0; DWORD dwOffsetDest = ( pt.y * sizeSurface.cx + pt.x ); DWORD dwLine = sizeSurface.cx - sizeTexture.cx; int nSizeSurface = sizeSurface.cx * sizeSurface.cy; static char szstrError[128]; sprintf( szstrError, "\nSurface %d %d, Pt %d %d IMG_BIT = %d, D3DFORMAT = %d", sizeSurface.cx, sizeSurface.cy, pt.x, pt.y, pImage->nImgBit, d3dFormat ); strcat( g_szCrashClient, szstrError ); if( d3dFormat == D3DFMT_A4R4G4B4 ) { LPWORD pDest = (LPWORD) pDestData; LPBYTE pSrc = pImage->lpData; if( pImage->nImgBit == IMGBIT_24 ) { for( int y = pt.y; y < pt.y + sizeTexture.cy; y++, dwOffsetDest += dwLine ) { for( int x = pt.x; x < pt.x + sizeTexture.cx; x++, dwOffsetSrc += 3, dwOffsetDest++ ) { if( dwOffsetDest >= 0 && (DWORD)dwOffsetDest < (DWORD)nSizeSurface ) { DWORD bitcount = pImage->nImgBit / 8; // if( dwOffsetSrc >= pImage->dwSize ) if( pImage->dwSize != pImage->dwSizeBak ) { char szFile[2048] = { 0 }; sprintf( szFile, "D3DFMT_A4R4G4B4 ERROR IMGBIT_24\n Current = %d Tex X = %d, Y = %d [%d,%d]\n LINE = %d\n Size = %d", dwOffsetSrc, sizeTexture.cx, sizeTexture.cy, sizeSurface.cx, sizeSurface.cy, dwLine, pImage->dwSize ); //if( byData4 ) // pDest[ dwOffsetDest ] = ( byData4 << 12 ) | ( byData3 << 8 ) | ( byData2 << 4 ) | byData1; AfxMessageBox(szFile, MB_OKCANCEL); // dwOffsetSrc = si break; } BYTE byData1 = pSrc[ dwOffsetSrc + 0 ] >> 4; BYTE byData2 = pSrc[ dwOffsetSrc + 1 ] >> 4; BYTE byData3 = pSrc[ dwOffsetSrc + 2 ] >> 4; // 원래 있던 배경을 보존하기 위해서 ff00ff면 찍지 않는다. if( byData1 != 0xf || byData2 != 0 || byData3 != 0xf ) pDest[ dwOffsetDest ] = 0xf000 | ( byData3 << 8 ) | ( byData2 << 4 ) | byData1; } } } } else if( pImage->nImgBit == IMGBIT_32 ) { for( int y = pt.y; y < pt.y + sizeTexture.cy; y++, dwOffsetDest += dwLine ) { for( int x = pt.x; x < pt.x + sizeTexture.cx; x++, dwOffsetSrc += 4, dwOffsetDest++ ) { if( dwOffsetDest >= 0 && (DWORD)dwOffsetDest < (DWORD)nSizeSurface ) { if( dwOffsetSrc >= (DWORD)( (sizeTexture.cx * sizeTexture.cy * 4) ) ) { //if( byData4 ) // pDest[ dwOffsetDest ] = ( byData4 << 12 ) | ( byData3 << 8 ) | ( byData2 << 4 ) | byData1; AfxMessageBox(" D3DFMT_A4R4G4B4 ERROR IMGBIT_32", MB_OK ); break; } BYTE byData1 = pSrc[ dwOffsetSrc + 0 ] >> 4; BYTE byData2 = pSrc[ dwOffsetSrc + 1 ] >> 4; BYTE byData3 = pSrc[ dwOffsetSrc + 2 ] >> 4; BYTE byData4 = pSrc[ dwOffsetSrc + 3 ] >> 4; // 원래 있던 배경을 보존하기 위해서 알파값이 전혀 없으면 찍지 않는다. if( byData4 ) pDest[ dwOffsetDest ] = ( byData4 << 12 ) | ( byData3 << 8 ) | ( byData2 << 4 ) | byData1; } } } } } else if( d3dFormat == D3DFMT_A8R8G8B8 ) { LPDWORD pDest = (LPDWORD) pDestData; if( pImage->nImgBit == IMGBIT_24 ) { LPBYTE pSrc = pImage->lpData; for( int y = pt.y; y < pt.y + sizeTexture.cy; y++, dwOffsetDest += dwLine ) { for( int x = pt.x; x < pt.x + sizeTexture.cx; x++, dwOffsetSrc += 3, dwOffsetDest++ ) { if( dwOffsetDest >= 0 && (DWORD)dwOffsetDest < (DWORD)nSizeSurface ) { if( dwOffsetSrc >= (DWORD)( (sizeTexture.cx * sizeTexture.cy * 2 ) ) ) { //if( byData4 ) // pDest[ dwOffsetDest ] = ( byData4 << 12 ) | ( byData3 << 8 ) | ( byData2 << 4 ) | byData1; AfxMessageBox(" D3DFMT_A8R8G8B8 ERROR IMGBIT_24", MB_OK ); break; } BYTE byData1 = pSrc[ dwOffsetSrc + 0 ]; BYTE byData2 = pSrc[ dwOffsetSrc + 1 ]; BYTE byData3 = pSrc[ dwOffsetSrc + 2 ]; // 원래 있던 배경을 보존하기 위해서 ff00ff면 찍지 않는다. if( byData1 != 0xff || byData2 != 0 || byData3 != 0xff ) pDest[ dwOffsetDest ] = 0xf000 | ( byData3 << 16 ) | ( byData2 << 8 ) | byData1; } } } } else if( pImage->nImgBit == IMGBIT_32 ) { LPDWORD pSrc = (LPDWORD)pImage->lpData; for( int y = pt.y; y < pt.y + sizeTexture.cy; y++, dwOffsetDest += dwLine ) { for( int x = pt.x; x < pt.x + sizeTexture.cx; x++, dwOffsetSrc++, dwOffsetDest++ ) { if( dwOffsetDest >= 0 && (DWORD)dwOffsetDest < (DWORD)nSizeSurface ) { // 원래 있던 배경을 보존하기 위해서 알파값이 전혀 없으면 찍지 않는다. if( pSrc[ dwOffsetSrc ] & 0xff000000 ) pDest[ dwOffsetDest ] = pSrc[ dwOffsetSrc ];//yData4 << 24 ) | ( byData3 << 16 ) | ( byData2 << 8 ) | byData1; } } } } } strcat( g_szCrashClient, "\nPaintTexture - OUT" ); } void AdjustSize( SIZE* pSize ) { // 사이즈를 2의 자승으로 바꾸기 WORD dwTemp = 0x8000; int i; for( i = 0; i < 16; i++ ) { if( pSize->cx & dwTemp ) { if( pSize->cx % dwTemp ) { dwTemp <<= 1; pSize->cx = dwTemp; } break; } dwTemp >>= 1; } dwTemp = 0x8000; for( i = 0; i < 16; i++ ) { if( pSize->cy & dwTemp ) { if( pSize->cy % dwTemp ) { dwTemp <<= 1; pSize->cy = dwTemp; } break; } dwTemp >>= 1; } //return size; } BOOL LoadImage( LPCTSTR lpszFileName, LPIMAGE lpImage ) //LPBYTE* lppData, SIZE* pSize, int* pnImgBit ) { TCHAR szFileName[ MAX_PATH ]; strcpy( szFileName, lpszFileName ); strlwr( szFileName ); if( strstr( szFileName, ".tga" ) ) { return LoadTGA( lpszFileName, lpImage ); } else if( strstr( szFileName, ".bmp" ) ) { return LoadBMP( lpszFileName, lpImage ); } return FALSE; } BOOL LoadTGA( LPCTSTR lpszFileName, LPIMAGE lpImage ) //LPBYTE* lppData, SIZE* pSize ) { #if !defined(__SERVER) lpImage->nImgBit = IMGBIT_32; CTarga targa; return targa.Load( lpszFileName, &lpImage->lpData, &lpImage->size ); #endif return FALSE; } BOOL LoadBMP( LPCTSTR lpszFileName, LPIMAGE lpImage ) //LPBYTE* lppData, SIZE* pSize ) { CResFile file; if( file.Open( lpszFileName, "rb" ) == FALSE ) { Error( "LoadBMP Failed = %s", lpszFileName ); return FALSE; } BITMAPINFOHEADER infoHeader; LPBYTE lpData = (LPBYTE)file.Read(); LPBYTE lpDataDelete = lpData; lpData += sizeof( BITMAPFILEHEADER ); memcpy( &infoHeader, lpData, sizeof( BITMAPINFOHEADER ) ); lpData += sizeof( BITMAPINFOHEADER ); int bitCount = 1; if( infoHeader.biBitCount < 8) { lpImage->size.cx = 0; lpImage->size.cy = 0; lpImage->lpData = NULL; lpImage->nImgBit = IMGBIT_24; safe_delete_array( lpDataDelete ); return FALSE; } if( infoHeader.biBitCount > 8) { bitCount = infoHeader.biBitCount / 8; } if( infoHeader.biCompression) { lpImage->size.cx = 0; lpImage->size.cy = 0; lpImage->lpData = NULL; lpImage->nImgBit = IMGBIT_24; safe_delete_array( lpDataDelete ); return FALSE; } int nLgHeight = infoHeader.biHeight; int nLgWidth = infoHeader.biWidth; lpImage->size.cx = nLgWidth; lpImage->size.cy = nLgHeight; if( bitCount == 1 ) { if( infoHeader.biClrUsed == 0 ) infoHeader.biClrUsed = 256; lpData += infoHeader.biClrUsed * 4; } LPBYTE lpNewData = new BYTE[ nLgWidth * nLgHeight * bitCount * 2 ]; // 버그 때문에 2 곱했음. 사이즈가 4의 배수가 아니어서 문제 생겨서 * 2 했음 lpImage->dwSizeBak = lpImage->dwSize = nLgWidth * nLgHeight * bitCount * 2; int nPgHeight = abs( infoHeader.biHeight ); int nPgWidth = infoHeader.biWidth; nPgWidth *= bitCount; nLgWidth *= bitCount; nLgWidth += ( ( nLgWidth % 4 ) ? ( 4 - nLgWidth % 4 ) : 0 ); LPBYTE pTempDst = lpNewData + ( nPgWidth * ( nPgHeight - 1 ) ); int i; for( i = 0; i < nPgHeight; i++ ) { memcpy( pTempDst, lpData, nLgWidth ); lpData += nLgWidth; pTempDst -= nPgWidth; } safe_delete_array( lpDataDelete ); lpImage->lpData = lpNewData; lpImage->nImgBit = IMGBIT_24; return TRUE; } BOOL SaveBMP( LPCTSTR lpszFileName, LPBYTE lpData, SIZE size ) { int i, j; BITMAPFILEHEADER BMPheader; BITMAPINFOHEADER header = { 40,640,-480,1,24,0,0,5904,5904,0,0 }; header.biBitCount = 24; header.biWidth = size.cx; header.biHeight = -abs(size.cy); LPBYTE pBMP = NULL; LPBYTE pp; LPBYTE pSurface = (LPBYTE) lpData; int nBit = 24 >> 3;//m_infoHeader.biBitCount >> 3; BMPheader.bfType = 'M'; BMPheader.bfType <<= 8; BMPheader.bfType += 'B'; BMPheader.bfReserved1 = 0; BMPheader.bfReserved2 = 0; // 16비트(nBit==2)라도 팔레트가 있는 것 처럼 안하면 그림이 밀려서 출력한다. 아케인 캡춰 관련 버그 if(nBit == 1 || nBit == 2) { BMPheader.bfSize = ( sizeof(BITMAPFILEHEADER ) + sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256 + header.biWidth * abs(header.biHeight) * nBit ); BMPheader.bfOffBits = sizeof(BITMAPFILEHEADER ) + sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256; } else { BMPheader.bfSize = ( sizeof(BITMAPFILEHEADER ) + sizeof(BITMAPINFOHEADER) + header.biWidth * abs(header.biHeight) * nBit ); BMPheader.bfOffBits = sizeof(BITMAPFILEHEADER ) + sizeof(BITMAPINFOHEADER); } pBMP = new BYTE[BMPheader.bfSize]; if( pBMP == NULL ) return FALSE; pp = pBMP; header.biHeight = abs( header.biHeight); memcpy( pp, &BMPheader, sizeof(BITMAPFILEHEADER) ); pp += sizeof(BITMAPFILEHEADER); memcpy( pp, &header, sizeof(BITMAPINFOHEADER) ); pp += sizeof(BITMAPINFOHEADER); if(nBit == 1 || nBit == 2) { } j = header.biWidth * abs(header.biHeight) * nBit; for( i = 0; i < abs(header.biHeight); i ++ ) { j -= header.biWidth * nBit; memcpy( pp, pSurface + j, header.biWidth * nBit ); pp += header.biWidth * nBit; } CFile file; if(file.Open(lpszFileName,CFile::modeWrite|CFile::modeCreate)) { file.Write(pBMP,(int)(pp - pBMP)); safe_delete_array( pBMP ); return TRUE; } safe_delete_array( pBMP ); return FALSE; } void GetPickRay(CRect rect,POINT ptCursor,D3DXMATRIX* pmatProj,D3DXMATRIX* pmatView,D3DXVECTOR3* pvPickRayOrig,D3DXVECTOR3* pvPickRayDir) { D3DXVECTOR3 v; v.x = ( ( ( 2.0f * ptCursor.x ) / rect.Width() ) - 1 ) / pmatProj->_11; v.y = -( ( ( 2.0f * ptCursor.y ) / rect.Height() ) - 1 ) / pmatProj->_22; v.z = 1.0f; // Get the inverse view matrix D3DXMATRIX m; D3DXMatrixInverse( &m, NULL, pmatView ); // Transform the screen space pick ray into 3D space pvPickRayDir->x = v.x*m._11 + v.y*m._21 + v.z*m._31; pvPickRayDir->y = v.x*m._12 + v.y*m._22 + v.z*m._32; pvPickRayDir->z = v.x*m._13 + v.y*m._23 + v.z*m._33; pvPickRayOrig->x = m._41; pvPickRayOrig->y = m._42; pvPickRayOrig->z = m._43; } void GetRayEnd(D3DXVECTOR3* pvPickRayOrig,D3DXVECTOR3* pvPickRayDir,D3DXVECTOR3* pvPickRayEnd) { FLOAT fyOrig = pvPickRayOrig->y; FLOAT fyDir = -pvPickRayDir->y; pvPickRayDir->x = fyOrig * pvPickRayDir->x / fyDir; // vecY : posY = vecX : posX pvPickRayDir->z = fyOrig * pvPickRayDir->z / fyDir; // vecY : posY = vecZ : posZ pvPickRayDir->y = -fyOrig; // 아래 *pvPickRayDir + *pvPickRayOrig에서 y가 0이 나오게 하려면 -fyOrig를 넣어야 한다. *pvPickRayEnd = *pvPickRayDir + *pvPickRayOrig; } BOOL IntersectTriangle( D3DXVECTOR3& v0, D3DXVECTOR3& v1, D3DXVECTOR3& v2, const D3DXVECTOR3& orig, const D3DXVECTOR3& dir, D3DXVECTOR3* pIntersect, FLOAT* pfDist ) { FLOAT fU,fV; if(D3DXIntersectTri( &v0, &v1, &v2, &orig, &dir, &fU, &fV, pfDist ) == TRUE ) { *pIntersect = orig + *pfDist * dir; return TRUE; } return FALSE; } #endif //defined (__WORLDSERVER) || defined (__CLIENT) #ifdef __CLIENT static int CALLBACK FontEnumProc(const LOGFONT*, const TEXTMETRIC*, DWORD, LPARAM lParam) { if (lParam != NULL) { *(BOOL*)lParam = TRUE; } return 0; } BOOL IsFontInstalled( LPCTSTR pszFace ) { BOOL bInstalled; HDC hDC; LOGFONT lf; memset(&lf, 0, sizeof(lf)); lstrcpy(lf.lfFaceName, pszFace); lf.lfCharSet = DEFAULT_CHARSET; bInstalled = FALSE; hDC = ::GetDC(NULL); if (hDC != NULL) { ::EnumFontFamiliesEx(hDC, &lf, FontEnumProc, (LPARAM)&bInstalled, 0); ::ReleaseDC(NULL, hDC); } return bInstalled; } #endif // __CLIENT
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 665 ] ] ]
10d729bb044656ff56fe1af182d8227de86d3b75
992d3f90ab0f41ca157000c4b18d071087d14d85
/WELCOME.CPP
c8e2cbcc3434d126bf2047726a14562436ca9b5f
[]
no_license
axemclion/visionizzer
cabc53c9be41c07c04436a4733697e4ca35104e3
5b0158f8a3614e519183055e50c27349328677e7
refs/heads/master
2020-12-25T19:04:17.853016
2009-05-22T14:44:53
2009-05-22T14:44:53
29,331,323
0
0
null
null
null
null
UTF-8
C++
false
false
575
cpp
# include <stdio.h> # include <string.h> int main(int argc,char *argv[]) { printf("Type SOFT at command line to launch this software"); if (argc <4 ) return 1; if (!(strcmp(argv[1],"to") == 0 && strcmp(argv[2],"this") == 0 && strcmp(argv[3],"software") == 0)) return 1; rename("d1.axe","phase1.zip"); rename("d2.axe","phase2.zip"); rename("d3.axe","phase3.zip"); rename("d4.axe","phase4.zip"); rename("d5.axe","phase5.zip"); rename("d6.axe","phase6.zip"); rename("d7.axe","phase0.zip"); rename("data","starting.exe"); return 0; }
[ [ [ 1, 23 ] ] ]
b0d407ea5fc31b72ac1879c00d44adc49c3f77e2
b1892b06513186f2d81560e666e84121421f1754
/foo_sdk/foobar2000/ATLHelpers/inplace_edit_v2.cpp
c7e4316b8203ae28989b22a760c4855686b7ad72
[ "MIT" ]
permissive
anders007/foo_input_amr
469c98d022d50d5020d74de9f24848088bd686ae
b95a758717e0680b97711c03207dead33befca83
refs/heads/master
2021-01-18T17:36:27.834218
2009-11-19T22:34:49
2009-11-19T22:34:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,835
cpp
#include "stdafx.h" namespace InPlaceEdit { t_size CTableEditHelperV2::ColumnToPosition(t_size col) const { PFC_ASSERT( TableEdit_IsColumnEditable(col) ); pfc::array_t<t_size> colOrder; GrabColumnOrder(colOrder); t_size skipped = 0; for(t_size walk = 0; walk < colOrder.get_size(); ++walk) { const t_size curCol = colOrder[walk]; if (TableEdit_IsColumnEditable(curCol)) { if (curCol == col) return skipped; ++skipped; } } PFC_ASSERT( !"Should not get here." ); return ~0; } t_size CTableEditHelperV2::PositionToColumn(t_size pos) const { pfc::array_t<t_size> colOrder; GrabColumnOrder(colOrder); t_size skipped = 0; for(t_size walk = 0; walk < colOrder.get_size(); ++walk) { const t_size curCol = colOrder[walk]; if (TableEdit_IsColumnEditable(curCol)) { if (skipped == pos) return curCol; ++skipped; } } PFC_ASSERT( !"Should not get here." ); return ~0; } t_size CTableEditHelperV2::EditableColumnCount() const { const t_size total = TableEdit_GetColumnCount(); t_size found = 0; for(t_size walk = 0; walk < total; ++walk) { if (TableEdit_IsColumnEditable(walk)) found++; } return found; } bool CTableEditHelperV2::TableEdit_Advance(t_size & item, t_size & subItem, t_uint32 whathappened) { //moo unsigned _item((unsigned)item), _subItem((unsigned)ColumnToPosition(subItem)); if (!InPlaceEdit::TableEditAdvance(_item,_subItem,(unsigned) TableEdit_GetItemCount(), (unsigned) EditableColumnCount(), whathappened)) return false; item = _item; subItem = PositionToColumn(_subItem); return true; } void CTableEditHelperV2::TableEdit_Abort(bool forwardContent) { if (this->have_task(KTaskID)) { this->orphan_task(KTaskID); if (forwardContent && (m_editFlags & KFlagReadOnly) == 0) { if (m_editData.is_valid()) { pfc::string8 temp(*m_editData); TableEdit_SetField(m_editItem,m_editSubItem, temp); } } m_editData.release(); SetFocus(NULL); TableEdit_Finished(); } } void CTableEditHelperV2::TableEdit_Start(t_size item, t_size subItem) { PFC_ASSERT( TableEdit_IsColumnEditable( subItem ) ); m_editItem = item; m_editSubItem = subItem; _ReStart(); } void CTableEditHelperV2::_ReStart() { PFC_ASSERT( m_editItem < TableEdit_GetItemCount() ); PFC_ASSERT( m_editSubItem < TableEdit_GetColumnCount() ); TableEdit_SetItemFocus(m_editItem,m_editSubItem); m_editData.new_t(); t_size lineCount = 1; TableEdit_GetField(m_editItem, m_editSubItem, *m_editData, lineCount); m_editFlags = TableEdit_GetEditFlags(m_editItem, m_editSubItem); RECT rc = TableEdit_GetItemRect(m_editItem, m_editSubItem); if (lineCount > 1) { rc.bottom = rc.top + (rc.bottom - rc.top) * lineCount; m_editFlags |= KFlagMultiLine; } InPlaceEdit::StartEx(TableEdit_GetParentWnd(), rc, m_editFlags, m_editData, create_task(KTaskID)); } void CTableEditHelperV2::on_task_completion(unsigned id, unsigned status) { if (id == KTaskID) { orphan_task(KTaskID); if (m_editData.is_valid()) { if (status & InPlaceEdit::KEditFlagContentChanged) { TableEdit_SetField(m_editItem,m_editSubItem,*m_editData); } m_editData.release(); } if (TableEdit_Advance(m_editItem,m_editSubItem,status)) { _ReStart(); } else { TableEdit_Finished(); } } } void CTableEditHelperV2_ListView::TableEdit_GetColumnOrder(t_size * out, t_size count) const { pfc::array_t<int> temp; temp.set_size(count); WIN32_OP_D( ListView_GetColumnOrderArray( TableEdit_GetParentWnd(), count, temp.get_ptr() ) ); for(t_size walk = 0; walk < count; ++walk) out[walk] = temp[walk]; } RECT CTableEditHelperV2_ListView::TableEdit_GetItemRect(t_size item, t_size subItem) const { RECT rc; WIN32_OP_D( ListView_GetSubItemRect(TableEdit_GetParentWnd(),item,subItem,LVIR_LABEL,&rc) ); return rc; } void CTableEditHelperV2_ListView::TableEdit_GetField(t_size item, t_size subItem, pfc::string_base & out, t_size & lineCount) { listview_helper::get_item_text( TableEdit_GetParentWnd(), item, subItem, out); lineCount = pfc::is_multiline(out) ? 5 : 1; } void CTableEditHelperV2_ListView::TableEdit_SetField(t_size item, t_size subItem, const char * value) { WIN32_OP_D( listview_helper::set_item_text( TableEdit_GetParentWnd(), item, subItem, value) ); } t_size CTableEditHelperV2_ListView::TableEdit_GetItemCount() const { LRESULT temp; WIN32_OP_D( ( temp = ListView_GetItemCount( TableEdit_GetParentWnd() ) ) >= 0 ); return (t_size) temp; } void CTableEditHelperV2_ListView::TableEdit_SetItemFocus(t_size item, t_size subItem) { WIN32_OP_D( listview_helper::select_single_item( TableEdit_GetParentWnd(), item ) ); } }
[ [ [ 1, 139 ] ] ]
4f08a7d9b41f3495ee3ffaf2c8ec27fe0d261c9a
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/qwt/qwt_plot_curve.cpp
c772e4a2ec104aea61d8d4a6a8e3459094192e59
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,272
cpp
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include <qpainter.h> #include <qpixmap.h> #include <qbitarray.h> #include "qwt_global.h" #include "qwt_legend.h" #include "qwt_legend_item.h" #include "qwt_data.h" #include "qwt_rect.h" #include "qwt_scale_map.h" #include "qwt_double_rect.h" #include "qwt_math.h" #include "qwt_painter.h" #include "qwt_plot.h" #include "qwt_plot_canvas.h" #include "qwt_spline.h" #include "qwt_symbol.h" #include "qwt_plot_curve.h" #if QT_VERSION >= 0x040000 #include <qevent.h> class QwtPlotCurvePaintHelper: public QObject { public: QwtPlotCurvePaintHelper(const QwtPlotCurve *curve, int from, int to): _curve(curve), _from(from), _to(to) { } virtual bool eventFilter(QObject *, QEvent *event) { if ( event->type() == QEvent::Paint ) { _curve->draw(_from, _to); return true; } return false; } private: const QwtPlotCurve *_curve; int _from; int _to; }; #endif // QT_VERSION >= 0x040000 #if QT_VERSION < 0x040000 #define QwtPointArray QPointArray #else #define QwtPointArray QPolygon #endif class QwtPlotCurve::PrivateData { public: class PixelMatrix: private QBitArray { public: PixelMatrix(const QRect& rect): QBitArray(rect.width() * rect.height()), _rect(rect) { fill(false); } inline bool testPixel(const QPoint& pos) { if ( !_rect.contains(pos) ) return false; const int idx = _rect.width() * (pos.y() - _rect.y()) + (pos.x() - _rect.x()); const bool marked = testBit(idx); if ( !marked ) setBit(idx, true); return !marked; } private: QRect _rect; }; PrivateData() { pen = QPen(Qt::black, 0); reference = 0.0; splineSize = 250; attributes = Auto; paintAttributes = 0; style = QwtPlotCurve::Lines; } QwtPlotCurve::CurveStyle style; double reference; QwtSymbol sym; QPen pen; QBrush brush; QwtText title; int attributes; int splineSize; int paintAttributes; }; static int qwtChkMono(const double *array, int size) { if (size < 2) return 0; int rv = qwtSign(array[1] - array[0]); for (int i = 1; i < size - 1; i++) { if ( qwtSign(array[i+1] - array[i]) != rv ) { rv = 0; break; } } return rv; } static void qwtTwistArray(double *array, int size) { const int s2 = size / 2; for (int i=0; i < s2; i++) { const int itmp = size - 1 - i; const double dtmp = array[i]; array[i] = array[itmp]; array[itmp] = dtmp; } } /*! \brief Ctor */ QwtPlotCurve::QwtPlotCurve() { init(QwtText()); } /*! \brief Ctor \param title title of the curve */ QwtPlotCurve::QwtPlotCurve(const QwtText &title) { init(title); } /*! \brief Ctor \param title title of the curve */ QwtPlotCurve::QwtPlotCurve(const QString &title) { init(title); } /*! \brief Copy Constructor */ QwtPlotCurve::QwtPlotCurve(const QwtPlotCurve &c): QwtPlotItem(c) { init(c.d_data->title); copy(c); } //! Dtor QwtPlotCurve::~QwtPlotCurve() { delete d_xy; delete d_data; } /*! \brief Initialize data members */ void QwtPlotCurve::init(const QwtText &title) { setItemAttribute(QwtPlotItem::Legend); setItemAttribute(QwtPlotItem::AutoScale); d_data = new PrivateData; d_data->title = title; d_xy = new QwtDoublePointData(QwtArray<QwtDoublePoint>()); setZ(20.0); } /*! \brief Copy the contents of a curve into another curve */ void QwtPlotCurve::copy(const QwtPlotCurve &c) { if (this != &c) { *d_data = *c.d_data; delete d_xy; d_xy = c.d_xy->copy(); itemChanged(); } } /*! \brief Copy Assignment */ const QwtPlotCurve& QwtPlotCurve::operator=(const QwtPlotCurve &c) { copy(c); return *this; } int QwtPlotCurve::rtti() const { return QwtPlotItem::Rtti_PlotCurve; } /*! \brief Specify an attribute how to draw the curve The attributes can be used to modify the drawing algorithm. The following attributes are defined:<dl> <dt>QwtPlotCurve::PaintFiltered</dt> <dd>Tries to reduce the data that has to be painted, by sorting out duplicates, or paintings outside the visible area. Might have a notable impact on curves with many close points. Only a couple of very basic filtering algos are implemented.</dd> <dt>QwtPlotCurve::ClipPolygons</dt> <dd>Clip polygons before painting them. </dl> The default is, that no paint attributes are enabled. \param attribute Paint attribute \param on On/Off /sa QwtPlotCurve::testPaintAttribute() */ void QwtPlotCurve::setPaintAttribute(PaintAttribute attribute, bool on) { if ( on ) d_data->paintAttributes |= attribute; else d_data->paintAttributes &= ~attribute; } /*! \brief Return the current paint attributes \sa QwtPlotCurve::setPaintAttribute */ bool QwtPlotCurve::testPaintAttribute(PaintAttribute attribute) const { return (d_data->paintAttributes & attribute); } /*! \brief Set the curve's drawing style Valid styles are: <dl> <dt>QwtPlotCurve::NoCurve</dt> <dd>Don't draw a curve. Note: This doesn't affect the symbol. </dd> <dt>QwtPlotCurve::Lines</dt> <dd>Connect the points with straight lines.</dd> <dt>QwtPlotCurve::Sticks</dt> <dd>Draw vertical sticks from a baseline which is defined by setBaseline().</dd> <dt>QwtPlotCurve::Steps</dt> <dd>Connect the points with a step function. The step function is drawn from the left to the right or vice versa, depending on the 'Inverted' option.</dd> <dt>QwtPlotCurves::Dots</dt> <dd>Draw dots at the locations of the data points. Note: This is different from a dotted line (see setPen()).</dd> <dt>QwtPlotCurve::Spline</dt> <dd>Interpolate the points with a spline. The spline type can be specified with setCurveAttribute(), the size of the spline (= number of interpolated points) can be specified with setSplineSize().</dd> <dt>QwtPlotCurve::UserCurve ...</dt> <dd>Styles >= QwtPlotCurve::UserCurve are reserved for derived classes of QwtPlotCurve that overload QwtPlotCurve::draw() with additional application specific curve types.</dd> </dl> \sa QwtPlotCurve::style() */ void QwtPlotCurve::setStyle(CurveStyle style) { if ( style != d_data->style ) { d_data->style = style; itemChanged(); } } /*! \fn CurveStyle QwtPlotCurve::style() const \brief Return the current style \sa QwtPlotCurve::setStyle */ QwtPlotCurve::CurveStyle QwtPlotCurve::style() const { return d_data->style; } /*! \brief Assign a symbol \param s symbol \sa QwtSymbol */ void QwtPlotCurve::setSymbol(const QwtSymbol &s ) { d_data->sym = s; itemChanged(); } /*! \brief Return the current symbol \sa QwtPlotCurve::setSymbol */ const QwtSymbol &QwtPlotCurve::symbol() const { return d_data->sym; } /*! \brief Assign a pen \param p New pen */ void QwtPlotCurve::setPen(const QPen &p) { if ( p != d_data->pen ) { d_data->pen = p; itemChanged(); } } /*! \brief Return the pen used to draw the lines \sa QwtPlotCurve::setPen */ const QPen& QwtPlotCurve::pen() const { return d_data->pen; } /*! \brief Assign a brush. In case of brush.style() != QBrush::NoBrush and style() != QwtPlotCurve::Sticks the area between the curve and the baseline will be filled. In case !brush.color().isValid() the area will be filled by pen.color(). The fill algorithm simply connects the first and the last curve point to the baseline. So the curve data has to be sorted (ascending or descending). \param brush New brush \sa QwtPlotCurve::brush, QwtPlotCurve::setBaseline, QwtPlotCurve::baseline */ void QwtPlotCurve::setBrush(const QBrush &brush) { if ( brush != d_data->brush ) { d_data->brush = brush; itemChanged(); } } /*! \brief Return the brush used to fill the area between lines and the baseline \sa QwtPlotCurve::setBrush, QwtPlotCurve::setBaseline, QwtPlotCurve::baseline */ const QBrush& QwtPlotCurve::brush() const { return d_data->brush; } /*! \brief Set data by copying x- and y-values from specified memory blocks Contrary to \b QwtPlot::setCurveRawData, this function makes a 'deep copy' of the data. \param xData pointer to x values \param yData pointer to y values \param size size of xData and yData \sa QwData::setData. */ void QwtPlotCurve::setData(const double *xData, const double *yData, int size) { delete d_xy; d_xy = new QwtArrayData(xData, yData, size); itemChanged(); } /*! \brief Initialize data with x- and y-arrays (explicitly shared) \param xData x data \param yData y data \sa QwtData::setData. */ void QwtPlotCurve::setData(const QwtArray<double> &xData, const QwtArray<double> &yData) { delete d_xy; d_xy = new QwtArrayData(xData, yData); itemChanged(); } /*! Initialize data with an array of points (explicitly shared). \param data Data \sa QwtDoublePointData::setData. */ void QwtPlotCurve::setData(const QwtArray<QwtDoublePoint> &data) { delete d_xy; d_xy = new QwtDoublePointData(data); itemChanged(); } /*! Initialize data with a pointer to QwtData. \param data Data \sa QwtData::copy. */ void QwtPlotCurve::setData(const QwtData &data) { delete d_xy; d_xy = data.copy(); itemChanged(); } /*! \brief Initialize the data by pointing to memory blocks which are not managed by QwtPlotCurve. setRawData is provided for efficiency. It is important to keep the pointers during the lifetime of the underlying QwtCPointerData class. \param xData pointer to x data \param yData pointer to y data \param size size of x and y \sa QwtCPointerData::setData. */ void QwtPlotCurve::setRawData(const double *xData, const double *yData, int size) { delete d_xy; d_xy = new QwtCPointerData(xData, yData, size); itemChanged(); } /*! \brief Assign a title to a curve \param title new title */ void QwtPlotCurve::setTitle(const QString &title) { setTitle(QwtText(title)); } /*! \brief Assign a title to a curve \param title new title */ void QwtPlotCurve::setTitle(const QwtText &title) { d_data->title = title; itemChanged(); } /*! \brief Return the title. \sa QwtPlotCurve::setTitle */ const QwtText &QwtPlotCurve::title() const { return d_data->title; } /*! Returns the bounding rectangle of the curve data. If there is no bounding rect, like for empty data the rectangle is invalid: QwtDoubleRect.isValid() == false */ QwtDoubleRect QwtPlotCurve::boundingRect() const { if ( d_xy == NULL ) return QwtDoubleRect(1.0, 1.0, -2.0, -2.0); // invalid return d_xy->boundingRect(); } /*! \brief Checks if a range of indices is valid and corrects it if necessary \param i1 Index 1 \param i2 Index 2 */ int QwtPlotCurve::verifyRange(int &i1, int &i2) const { int size = dataSize(); if (size < 1) return 0; i1 = qwtLim(i1, 0, size-1); i2 = qwtLim(i2, 0, size-1); if ( i1 > i2 ) qSwap(i1, i2); return (i2 - i1 + 1); } void QwtPlotCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const { draw(painter, xMap, yMap, 0, -1); } /*! \brief Draw a set of points of a curve. When observing an measurement while it is running, new points have to be added to an existing curve. drawCurve can be used to display them avoiding a complete redraw of the canvas. Setting plot()->canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true); will result in faster painting, if the paint engine of the canvas widget supports this feature. \param from Index of the first point to be painted \param to Index of the last point to be painted. If to < 0 the curve will be painted to its last point. \sa QwtCurve::draw */ void QwtPlotCurve::draw(int from, int to) const { if ( !plot() ) return; QwtPlotCanvas *canvas = plot()->canvas(); bool directPaint = true; #if QT_VERSION >= 0x040000 if ( !canvas->testAttribute(Qt::WA_WState_InPaintEvent) && !canvas->testAttribute(Qt::WA_PaintOutsidePaintEvent) ) { /* We save curve and range in helper and call repaint. The helper filters the Paint event, to repeat the QwtPlotCurve::draw, but now from inside the paint event. */ QwtPlotCurvePaintHelper helper(this, from, to); canvas->installEventFilter(&helper); canvas->repaint(); return; } #endif const QwtScaleMap xMap = plot()->canvasMap(xAxis()); const QwtScaleMap yMap = plot()->canvasMap(yAxis()); if ( canvas->testPaintAttribute(QwtPlotCanvas::PaintCached) && canvas->paintCache() && !canvas->paintCache()->isNull() ) { QPainter cachePainter((QPixmap *)canvas->paintCache()); cachePainter.translate(-canvas->contentsRect().x(), -canvas->contentsRect().y()); draw(&cachePainter, xMap, yMap, from, to); } if ( directPaint ) { QPainter painter(canvas); painter.setClipping(true); painter.setClipRect(canvas->contentsRect()); draw(&painter, xMap, yMap, from, to); return; } #if QT_VERSION >= 0x040000 if ( canvas->testPaintAttribute(QwtPlotCanvas::PaintCached) && canvas->paintCache() ) { /* The cache is up to date. We flush it via repaint to the canvas. This works flicker free but is much ( > 10x ) slower than direct painting. */ const bool noBG = canvas->testAttribute(Qt::WA_NoBackground); if ( !noBG ) canvas->setAttribute(Qt::WA_NoBackground, true); canvas->repaint(canvas->contentsRect()); if ( !noBG ) canvas->setAttribute(Qt::WA_NoBackground, false); return; } #endif // Ok, we give up canvas->repaint(canvas->contentsRect()); } /*! \brief Draw an interval of the curve \param painter Painter \param xMap maps x-values into pixel coordinates. \param yMap maps y-values into pixel coordinates. \param from index of the first point to be painted \param to index of the last point to be painted. If to < 0 the curve will be painted to its last point. \sa QwtPlotCurve::drawCurve, QwtPlotCurve::drawDots, QwtPlotCurve::drawLines, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSteps, QwtPlotCurve::drawSticks */ void QwtPlotCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { if ( !painter || dataSize() <= 0 ) return; if (to < 0) to = dataSize() - 1; if ( verifyRange(from, to) > 0 ) { painter->save(); painter->setPen(d_data->pen); /* Qt 4.0.0 is slow when drawing lines, but it´s even slower when the painter has a brush. So we don't set the brush before we need it. */ drawCurve(painter, d_data->style, xMap, yMap, from, to); painter->restore(); if (d_data->sym.style() != QwtSymbol::None) { painter->save(); drawSymbols(painter, d_data->sym, xMap, yMap, from, to); painter->restore(); } } } /*! \brief Draw the line part (without symbols) of a curve interval. \param painter Painter \param style curve style, see QwtPlotCurve::CurveStyle \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted \sa QwtPlotCurve::draw, QwtPlotCurve::drawDots, QwtPlotCurve::drawLines, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSteps, QwtPlotCurve::drawSticks */ void QwtPlotCurve::drawCurve(QPainter *painter, int style, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { switch (style) { case Lines: drawLines(painter, xMap, yMap, from, to); break; case Sticks: drawSticks(painter, xMap, yMap, from, to); break; case Steps: drawSteps(painter, xMap, yMap, from, to); break; case Spline: if ( from > 0 || to < dataSize() - 1 ) drawLines(painter, xMap, yMap, from, to); else drawSpline(painter, xMap, yMap); break; case Dots: drawDots(painter, xMap, yMap, from, to); break; case NoCurve: default: break; } } /*! \brief Draw lines \param painter Painter \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted \sa QwtPlotCurve::draw, QwtPlotCurve::drawLines, QwtPlotCurve::drawDots, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSteps, QwtPlotCurve::drawSticks */ void QwtPlotCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { const int size = to - from + 1; if ( size <= 0 ) return; QwtPointArray polyline(size); if ( d_data->paintAttributes & PaintFiltered ) { QPoint pp( xMap.transform(x(from)), yMap.transform(y(from)) ); polyline.setPoint(0, pp); int count = 1; for (int i = from + 1; i <= to; i++) { const QPoint pi(xMap.transform(x(i)), yMap.transform(y(i))); if ( pi != pp ) { polyline.setPoint(count, pi); count++; pp = pi; } } if ( count != size ) polyline.resize(count); } else { for (int i = from; i <= to; i++) { int xi = xMap.transform(x(i)); int yi = yMap.transform(y(i)); polyline.setPoint(i - from, xi, yi); } } if ( d_data->paintAttributes & ClipPolygons ) { QwtRect r = painter->window(); polyline = r.clip(polyline); } QwtPainter::drawPolyline(painter, polyline); if ( d_data->brush.style() != Qt::NoBrush ) fillCurve(painter, xMap, yMap, polyline); } /*! \brief Draw sticks \param painter Painter \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted \sa QwtPlotCurve::draw, QwtPlotCurve::drawCurve, QwtPlotCurve::drawDots, QwtPlotCurve::drawLines, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSteps */ void QwtPlotCurve::drawSticks(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { int x0 = xMap.transform(d_data->reference); int y0 = yMap.transform(d_data->reference); for (int i = from; i <= to; i++) { const int xi = xMap.transform(x(i)); const int yi = yMap.transform(y(i)); if (d_data->attributes & Xfy) QwtPainter::drawLine(painter, x0, yi, xi, yi); else QwtPainter::drawLine(painter, xi, y0, xi, yi); } } /*! \brief Draw dots \param painter Painter \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted \sa QwtPlotCurve::drawPolyline, QwtPlotCurve::drawLine, QwtPlotCurve::drawLines, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSteps QwtPlotCurve::drawPolyline, QwtPlotCurve::drawPolygon */ void QwtPlotCurve::drawDots(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { const QRect window = painter->window(); if ( window.isEmpty() ) return; const bool doFill = d_data->brush.style() != Qt::NoBrush; QwtPointArray polyline; if ( doFill ) polyline.resize(to - from + 1); if ( to > from && d_data->paintAttributes & PaintFiltered ) { int count = 0; if ( doFill ) { QPoint pp( xMap.transform(x(from)), yMap.transform(y(from)) ); polyline.setPoint(0, pp); int count = 1; for (int i = from + 1; i <= to; i++) { const QPoint pi(xMap.transform(x(i)), yMap.transform(y(i))); if ( pi != pp ) { polyline.setPoint(count, pi); count++; pp = pi; } } } else { // if we don't need to fill, we can sort out // duplicates independent from the order PrivateData::PixelMatrix pixelMatrix(window); for (int i = from; i <= to; i++) { const QPoint p( xMap.transform(x(i)), yMap.transform(y(i)) ); if ( pixelMatrix.testPixel(p) ) { polyline[count] = p; count++; } } } if ( int(polyline.size()) != count ) polyline.resize(count); } else { for (int i = from; i <= to; i++) { const int xi = xMap.transform(x(i)); const int yi = yMap.transform(y(i)); QwtPainter::drawPoint(painter, xi, yi); if ( doFill ) polyline.setPoint(i - from, xi, yi); } } if ( d_data->paintAttributes & ClipPolygons ) { const QwtRect r = painter->window(); polyline = r.clip(polyline); } if ( doFill ) fillCurve(painter, xMap, yMap, polyline); } /*! \brief Draw step function \param painter Painter \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted \sa QwtPlotCurve::draw, QwtPlotCurve::drawCurve, QwtPlotCurve::drawDots, QwtPlotCurve::drawLines, QwtPlotCurve::drawSpline, QwtPlotCurve::drawSticks */ void QwtPlotCurve::drawSteps(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { QwtPointArray polyline(2 * (to - from) + 1); bool inverted = d_data->attributes & Yfx; if ( d_data->attributes & Inverted ) inverted = !inverted; int i,ip; for (i = from, ip = 0; i <= to; i++, ip += 2) { const int xi = xMap.transform(x(i)); const int yi = yMap.transform(y(i)); if ( ip > 0 ) { if (inverted) polyline.setPoint(ip - 1, polyline[ip-2].x(), yi); else polyline.setPoint(ip - 1, xi, polyline[ip-2].y()); } polyline.setPoint(ip, xi, yi); } if ( d_data->paintAttributes & ClipPolygons ) { const QwtRect r = painter->window(); polyline = r.clip(polyline); } QwtPainter::drawPolyline(painter, polyline); if ( d_data->brush.style() != Qt::NoBrush ) fillCurve(painter, xMap, yMap, polyline); } /*! \brief Draw a spline \param painter Painter \param xMap x map \param yMap y map \sa QwtPlotCurve::draw, QwtPlotCurve::drawCurve, QwtPlotCurve::drawDots, QwtPlotCurve::drawLines, QwtPlotCurve::drawSteps, QwtPlotCurve::drawSticks */ void QwtPlotCurve::drawSpline(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const { int i; const int size = dataSize(); double *txval = new double[size]; double *tyval = new double[size]; // // Transform x and y values to window coordinates // to avoid a distinction between linear and // logarithmic scales. // for (i=0;i<size;i++) { txval[i] = xMap.xTransform(x(i)); tyval[i] = yMap.xTransform(y(i)); } int stype; if (! (d_data->attributes & (Yfx|Xfy|Parametric))) { if (qwtChkMono(txval, size)) { stype = Yfx; } else if(qwtChkMono(tyval, size)) { stype = Xfy; } else { stype = Parametric; if ( (d_data->attributes & Periodic) || ( (x(0) == x(size-1)) && (y(0) == y(size-1)))) { stype |= Periodic; } } } else { stype = d_data->attributes; } bool ok = false; QwtPointArray polyline(d_data->splineSize); if (stype & Parametric) { // // setup parameter vector // double *param = new double[size]; param[0] = 0.0; for (i=1; i<size; i++) { const double delta = sqrt( qwtSqr(txval[i] - txval[i-1]) + qwtSqr( tyval[i] - tyval[i-1])); param[i] = param[i-1] + qwtMax(delta, 1.0); } // // setup splines QwtSpline spx, spy; ok = spx.recalc(param, txval, size, stype & Periodic); if (ok) ok = spy.recalc(param, tyval, size, stype & Periodic); if ( ok ) { // fill point array const double delta = param[size - 1] / double(d_data->splineSize-1); for (i = 0; i < d_data->splineSize; i++) { const double dtmp = delta * double(i); polyline.setPoint(i, qRound(spx.value(dtmp)), qRound(spy.value(dtmp)) ); } } delete[] param; } else if (stype & Xfy) { if (tyval[size-1] < tyval[0]) { qwtTwistArray(txval, size); qwtTwistArray(tyval, size); } // 1. Calculate spline coefficients QwtSpline spx; ok = spx.recalc(tyval, txval, size, stype & Periodic); if ( ok ) { const double ymin = qwtGetMin(tyval, size); const double ymax = qwtGetMax(tyval, size); const double delta = (ymax - ymin) / double(d_data->splineSize - 1); for (i = 0; i < d_data->splineSize; i++) { const double dtmp = ymin + delta * double(i); polyline.setPoint(i, qRound(spx.value(dtmp)), qRound(dtmp + 0.5)); } } } else { if (txval[size-1] < txval[0]) { qwtTwistArray(tyval, size); qwtTwistArray(txval, size); } // 1. Calculate spline coefficients QwtSpline spy; ok = spy.recalc(txval, tyval, size, stype & Periodic); if ( ok ) { const double xmin = qwtGetMin(txval, size); const double xmax = qwtGetMax(txval, size); const double delta = (xmax - xmin) / double(d_data->splineSize - 1); for (i = 0; i < d_data->splineSize; i++) { double dtmp = xmin + delta * double(i); polyline.setPoint(i, qRound(dtmp), qRound(spy.value(dtmp))); } } } delete[] txval; delete[] tyval; if ( ok ) { if ( d_data->paintAttributes & ClipPolygons ) { const QwtRect r = painter->window(); polyline = r.clip(polyline); } QwtPainter::drawPolyline(painter, polyline); if ( d_data->brush.style() != Qt::NoBrush ) fillCurve(painter, xMap, yMap, polyline); } else drawLines(painter, xMap, yMap, 0, size - 1); } /*! \brief Specify an attribute for the drawing style The attributes can be used to modify the drawing style. The following attributes are defined:<dl> <dt>QwtPlotCurve::Auto</dt> <dd>The default setting. For QwtPlotCurve::spline, this means that the type of the spline is determined automatically, depending on the data. For all other styles, this means that y is regarded as a function of x.</dd> <dt>QwtPlotCurve::Yfx</dt> <dd>Draws y as a function of x (the default). The baseline is interpreted as a horizontal line with y = baseline().</dd> <dt>QwtPlotCurve::Xfy</dt> <dd>Draws x as a function of y. The baseline is interpreted as a vertical line with x = baseline().</dd> <dt>QwtPlotCurve::Parametric</dt> <dd>For QwtPlotCurve::Spline only. Draws a parametric spline.</dd> <dt>QwtPlotCurve::Periodic</dt> <dd>For QwtPlotCurve::Spline only. Draws a periodic spline.</dd> <dt>QwtPlotCurve::Inverted</dt> <dd>For QwtPlotCurve::Steps only. Draws a step function from the right to the left.</dd></dl> \param attribute Curve attribute \param on On/Off /sa QwtPlotCurve::testCurveAttribute() */ void QwtPlotCurve::setCurveAttribute(CurveAttribute attribute, bool on) { if ( bool(d_data->attributes & attribute) == on ) return; if ( on ) d_data->attributes |= attribute; else d_data->attributes &= ~attribute; itemChanged(); } /*! \brief Return the current curve attributes \sa QwtPlotCurve::setCurveAttribute */ bool QwtPlotCurve::testCurveAttribute(CurveAttribute attribute) const { return d_data->attributes & attribute; } /*! \brief Change the number of interpolated points \param s new size \warning The default is 250 points. */ void QwtPlotCurve::setSplineSize(int s) { d_data->splineSize = qwtMax(s, 10); itemChanged(); } /*! \fn int QwtPlotCurve::splineSize() const \brief Return the spline size \sa QwtPlotCurve::setSplineSize */ int QwtPlotCurve::splineSize() const { return d_data->splineSize; } /*! Fill the area between the polygon and the baseline with the curve brush \param painter Painter \param xMap x map \param yMap y map \param pa Polygon \sa QwtPlotCurve::setBrush() */ void QwtPlotCurve::fillCurve(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, QwtPointArray &pa) const { if ( d_data->brush.style() == Qt::NoBrush ) return; closePolyline(xMap, yMap, pa); if ( pa.count() <= 2 ) // a line can't be filled return; QBrush b = d_data->brush; if ( !b.color().isValid() ) b.setColor(d_data->pen.color()); painter->save(); painter->setPen(QPen(Qt::NoPen)); painter->setBrush(b); QwtPainter::drawPolygon(painter, pa); painter->restore(); } /*! \brief Complete a polygon to be a closed polygon including the area between the original polygon and the baseline. \param xMap X map \param yMap Y map \param pa Polygon to be completed */ void QwtPlotCurve::closePolyline( const QwtScaleMap &xMap, const QwtScaleMap &yMap, QwtPointArray &pa) const { const int sz = pa.size(); if ( sz < 2 ) return; pa.resize(sz + 2); if ( d_data->attributes & QwtPlotCurve::Xfy ) { pa.setPoint(sz, xMap.transform(d_data->reference), pa.point(sz - 1).y()); pa.setPoint(sz + 1, xMap.transform(d_data->reference), pa.point(0).y()); } else { pa.setPoint(sz, pa.point(sz - 1).x(), yMap.transform(d_data->reference)); pa.setPoint(pa.size() - 1, pa.point(0).x(), yMap.transform(d_data->reference)); } } /*! \brief Draw symbols \param painter Painter \param symbol Curve symbol \param xMap x map \param yMap y map \param from index of the first point to be painted \param to index of the last point to be painted */ void QwtPlotCurve::drawSymbols(QPainter *painter, const QwtSymbol &symbol, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { painter->setBrush(symbol.brush()); painter->setPen(symbol.pen()); QRect rect; rect.setSize(QwtPainter::metricsMap().screenToLayout(symbol.size())); if ( to > from && d_data->paintAttributes & PaintFiltered ) { const QRect window = painter->window(); if ( window.isEmpty() ) return; PrivateData::PixelMatrix pixelMatrix(window); for (int i = from; i <= to; i++) { const QPoint pi( xMap.transform(x(i)), yMap.transform(y(i)) ); if ( pixelMatrix.testPixel(pi) ) { rect.moveCenter(pi); symbol.draw(painter, rect); } } } else { for (int i = from; i <= to; i++) { const int xi = xMap.transform(x(i)); const int yi = yMap.transform(y(i)); rect.moveCenter(QPoint(xi, yi)); symbol.draw(painter, rect); } } } /*! \brief Set the value of the baseline The baseline is needed for filling the curve with a brush or the QwtPlotCurve::Sticks drawing style. The default value is 0.0. The interpretation of the baseline depends on the style options. With QwtPlotCurve::Yfx, the baseline is interpreted as a horizontal line at y = baseline(), with QwtPlotCurve::Yfy, it is interpreted as a vertical line at x = baseline(). \param reference baseline \sa QwtPlotCurve::setBrush(), QwtPlotCurve::setStyle(), QwtPlotCurve::setCurveAttribute() */ void QwtPlotCurve::setBaseline(double reference) { if ( d_data->reference != reference ) { d_data->reference = reference; itemChanged(); } } /*! \brief Return the value of the baseline \sa QwtPlotCurve::setBaseline */ double QwtPlotCurve::baseline() const { return d_data->reference; } /*! Return the size of the data arrays */ int QwtPlotCurve::dataSize() const { return d_xy->size(); } int QwtPlotCurve::closestPoint(const QPoint &pos, double *dist) const { if ( plot() == NULL || dataSize() <= 0 ) return -1; const QwtScaleMap xMap = plot()->canvasMap(xAxis()); const QwtScaleMap yMap = plot()->canvasMap(yAxis()); int index = -1; double dmin = 1.0e10; for (int i=0; i < dataSize(); i++) { const double cx = xMap.xTransform(x(i)) - pos.x(); const double cy = yMap.xTransform(y(i)) - pos.y(); const double f = qwtSqr(cx) + qwtSqr(cy); if (f < dmin) { index = i; dmin = f; } } if ( dist ) *dist = sqrt(dmin); return index; } void QwtPlotCurve::updateLegend(QwtLegend *legend) const { if ( !legend ) return; QwtPlotItem::updateLegend(legend); QWidget *widget = legend->find(this); if ( !widget || !widget->inherits("QwtLegendItem") ) return; QwtLegendItem *legendItem = (QwtLegendItem *)widget; #if QT_VERSION < 0x040000 const bool doUpdate = legendItem->isUpdatesEnabled(); #else const bool doUpdate = legendItem->updatesEnabled(); #endif legendItem->setUpdatesEnabled(false); const int policy = legend->displayPolicy(); if (policy == QwtLegend::Fixed) { int mode = legend->identifierMode(); if (mode & QwtLegendItem::ShowLine) legendItem->setCurvePen(pen()); if (mode & QwtLegendItem::ShowSymbol) legendItem->setSymbol(symbol()); if (mode & QwtLegendItem::ShowText) legendItem->setText(title()); else legendItem->setText(QwtText()); legendItem->setIdentifierMode(mode); } else if (policy == QwtLegend::Auto) { int mode = 0; if (QwtPlotCurve::NoCurve != style()) { legendItem->setCurvePen(pen()); mode |= QwtLegendItem::ShowLine; } if (QwtSymbol::None != symbol().style()) { legendItem->setSymbol(symbol()); mode |= QwtLegendItem::ShowSymbol; } if ( !title().isEmpty() ) { legendItem->setText(title()); mode |= QwtLegendItem::ShowText; } else { legendItem->setText(QwtText()); } legendItem->setIdentifierMode(mode); } legendItem->setUpdatesEnabled(doUpdate); legendItem->update(); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 1469 ] ] ]
620691be2b89f13dd8a4db281dffe24c9c83efe0
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ShareModule/CommonModule/ServiceThread.cpp
8fa71f6fa9dc411cc9602bd4e603cd5e3250228e
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
4,608
cpp
#include "StdAfx.h" #include <Process.h> #include "ServiceThread.h" ////////////////////////////////////////////////////////////////////////// //结构定义 //启动参数 struct tagThreadParameter { bool bSuccess; //是否错误 HANDLE hEventFinish; //事件句柄 CServiceThread * m_pServiceThread; //线程指针 }; ////////////////////////////////////////////////////////////////////////// //构造函数 CThreadLockHandle::CThreadLockHandle(IThreadLock * pIThreadLock, bool bAutoLock) { ASSERT(pIThreadLock!=NULL); m_nLockCount=0; m_pIThreadLock=pIThreadLock; if (bAutoLock) Lock(); return; } //析构函数 CThreadLockHandle::~CThreadLockHandle() { while (m_nLockCount>0) UnLock(); } //锁定函数 void CThreadLockHandle::Lock() { //效验状态 ASSERT(m_nLockCount>=0); ASSERT(m_pIThreadLock!=NULL); //锁定对象 m_nLockCount++; m_pIThreadLock->Lock(); } //解锁函数 void CThreadLockHandle::UnLock() { //效验状态 ASSERT(m_nLockCount>0); ASSERT(m_pIThreadLock!=NULL); //解除锁定 m_nLockCount--; m_pIThreadLock->UnLock(); } ////////////////////////////////////////////////////////////////////////// //构造函数 CServiceThread::CServiceThread(void) { m_bRun=false; m_uThreadID=0; m_hThreadHandle=NULL; } //析构函数 CServiceThread::~CServiceThread(void) { StopThread(INFINITE); } //状态判断 bool CServiceThread::IsRuning() { if (m_hThreadHandle!=NULL) { DWORD dwRetCode=WaitForSingleObject(m_hThreadHandle,0); if (dwRetCode==WAIT_TIMEOUT) return true; } return false; } //启动线程 bool CServiceThread::StartThead() { //效验状态 if (IsRuning()) return false; //清理变量 if (m_hThreadHandle!=NULL) { CloseHandle(m_hThreadHandle); m_hThreadHandle=NULL; m_uThreadID=0; } //构造参数 tagThreadParameter ThreadParameter; ThreadParameter.bSuccess=false; ThreadParameter.m_pServiceThread=this; ThreadParameter.hEventFinish=CreateEvent(NULL,FALSE,FALSE,NULL); if (ThreadParameter.hEventFinish==NULL) return false; //启动线程 m_bRun=true; m_hThreadHandle=(HANDLE)::_beginthreadex(NULL,0,ThreadFunction,&ThreadParameter,0,&m_uThreadID); //等待事件 WaitForSingleObject(ThreadParameter.hEventFinish,INFINITE); //关闭事件 CloseHandle(ThreadParameter.hEventFinish); //判断错误 if (ThreadParameter.bSuccess==false) { StopThread(); return false; } return true; } //停止线程 bool CServiceThread::StopThread(DWORD dwWaitSeconds) { //停止线程 if (IsRuning()==true) { m_bRun=false; DWORD dwRetCode=WaitForSingleObject(m_hThreadHandle,dwWaitSeconds); if (dwRetCode==WAIT_TIMEOUT) return false; } //设置变量 if (m_hThreadHandle!=NULL) { CloseHandle(m_hThreadHandle); m_hThreadHandle=NULL; m_uThreadID=0; } return true; } //中止线程 bool CServiceThread::TerminateThread(DWORD dwExitCode) { //停止线程 if (IsRuning()==true) { ::TerminateThread(m_hThreadHandle,dwExitCode); } //设置变量 if (m_hThreadHandle!=NULL) { CloseHandle(m_hThreadHandle); m_hThreadHandle=NULL; m_uThreadID=0; } return true; } //投递消息 bool CServiceThread::PostThreadMessage(UINT uMessage, WPARAM wParam, LPARAM lParam) { //状态效验 if (m_uThreadID==0) return false; //投递消息 BOOL bSuccess=::PostThreadMessage(m_uThreadID,uMessage,wParam,lParam); return bSuccess?true:false; } //线程函数 unsigned __stdcall CServiceThread::ThreadFunction(LPVOID pThreadData) { //获取参数 ASSERT(pThreadData!=NULL); tagThreadParameter * pThreadParameter=(tagThreadParameter *)pThreadData; CServiceThread * pThread=pThreadParameter->m_pServiceThread; //随机事件 srand((DWORD)time(NULL)); //启动事件 try { pThreadParameter->bSuccess=pThread->OnThreadStratEvent(); } catch (...) { pThreadParameter->bSuccess=false; } //设置事件 bool bSuccess=pThreadParameter->bSuccess; ASSERT(pThreadParameter->hEventFinish!=NULL); SetEvent(pThreadParameter->hEventFinish); //Run线程 if (bSuccess==true) { while (pThread->m_bRun) { try { if (pThread->RepetitionRun()==false) break; } catch (...) {} } } //停止事件 try { pThread->OnThreadStopEvent(); } catch (...) { } //中止线程 _endthreadex(0); return 0; } //////////////////////////////////////////////////////////////////////////
[ [ [ 1, 233 ] ] ]
fccbaa52fdc45dde357eb14dc08fe4c25bf17c86
6581dacb25182f7f5d7afb39975dc622914defc7
/ZTable/collectionhelper.h
381a45c2edc3e31ca7dce310ad00a56093ba358e
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,339
h
#pragma warning( disable : 4018 ) //signed/unsigned mismatch #include <vector> //////////////////////////////////////////////////////////////////////// ///// // CComCollect // // icontainer: The interface for the container // container_iid: The IID for the container interface // libid: The GUID for the library // container: The implementation class for the container // icontained: The interface for the contained interface // contained_iid: The IID for the contained interface // // Usage: // Derive your collection class from this and CComObjectRootEx. Since this template class // inherits from CComCoClass, IDispatchImpl, and ISupportErrorInfo, you should not inherit // from those in your concrete class. Here's an example declaration: // // class ATL_NO_VTABLE CSomeCollection : // public CComObjectRoot, // public CComCollect<IContainer, &IID_IContainer,&LIBID_DINGES2Lib, // Container,&CLSID_Container,IContained,&IID_IContained> // // If all you need are the standard Add, Remove, Item, get_Count, and get__NewEnum methods, // then you do not need to provide any other implementation. Just make sure you declare // the interface for your collection class in an IDL file. Here's the example for the // above declaration: // /* interface IDataCollection : IDispatch { [propget, id(1)] HRESULT Count([out, retval] long *pVal); [id(2)] HRESULT Add([in] IContained * inItem); [id(3)] HRESULT Remove([in] long inIndex); [propget, id(DISPID_VALUE)] HRESULT Item([in] long inIndex,[out, retval] IContained** outChart); [propget, id(DISPID_NEWENUM)] HRESULT _NewEnum([out, retval]LPUNKNOWN *pVal); }; */ // // You are free to add additional accessor/builder methods (note that the collection // implementation is exposed. Just declare it in your header and the IDL and provide an // implementation. // #ifndef __COLLECTIONHELPER_H_ #define __COLLECTIONHELPER_H_ #include "persistvarxml/IPersistVarXML.h" #include "Log4cxxHelper.h" template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> class ATL_NO_VTABLE CComCollect : public CComCoClass<container, container_clsid>, public IDispatchImpl<icontainer, container_iid, libid> { public: CComCollect() {} ~CComCollect() {RemoveAll();} // ISPCChartSpecs public: STDMETHOD(RemoveAll)(); STDMETHOD(Add)(/*[in]*/ icontained* inItem); STDMETHOD(Insert)(long index, /*[in]*/ icontained* inItem); STDMETHOD(get__NewEnum)(/*[out, retval]*/ LPUNKNOWN *pVal); STDMETHOD(get_Item)(/*[in]*/ long inIndex, /*[out, retval]*/icontained** outChart); STDMETHOD(get_Count)(/*[out, retval]*/ long *pVal); STDMETHOD(Remove)(/*[in]*/ long inIndex); STDMETHOD(Reserve)(/*[in]*/ long lngSize); STDMETHOD(Shrink)(); // ISupportsErrorInfo //STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // Helper functions typedef std::vector<CComVariant> collection; typedef collection::iterator iterator; iterator begin(); iterator end(); protected: collection mCollect; bool m_bDirty; }; /* template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid> ::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { container_iid, }; for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } */ template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> std::vector<CComVariant>::iterator CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::begin() { return mCollect.begin(); } template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> std::vector<CComVariant>::iterator CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::end() { return mCollect.end(); } // Returns the number of elements in the collection template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::get_Count(long * pVal) { // Make sure we didn't get a null pointer passed in if (!pVal) return E_POINTER; // Get the size from the collection *pVal = static_cast<long>(mCollect.size()); return S_OK; } // Returns a single item corresponding to the index template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::get_Item(long inIndex, icontained** outContained) { // Make sure we didn't get a null pointer passed in if (!outContained) return E_POINTER; // Make sure the index is within range (index is 1-based) if (inIndex < 1 || inIndex > mCollect.size()) return E_INVALIDARG; // Get the variant out of the collection CComVariant& var = mCollect[inIndex-1]; // Make sure we've got an element HRESULT hr = var.pdispVal->QueryInterface(*contained_iid, (void**)outContained); if (FAILED(hr)) return E_UNEXPECTED; return S_OK; } template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::get__NewEnum(LPUNKNOWN * pVal) { // Make sure we didn't get a null pointer passed in if (!pVal) return E_POINTER; *pVal = 0; // Create the enumeration object typedef CComObject<CComEnum<IEnumVARIANT, &IID_IEnumVARIANT, VARIANT, _Copy<VARIANT> > > enumVar; enumVar* pEnum = new enumVar; if (!pEnum) return E_OUTOFMEMORY; // Initialize with the chart collection iterators HRESULT hr = pEnum->Init(&*mCollect.begin(), &*mCollect.end(), NULL,AtlFlagCopy); if (SUCCEEDED(hr)) hr = pEnum->QueryInterface(IID_IEnumVARIANT, (void**)pVal); if (FAILED(hr)) delete pEnum; return hr; } template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::Add(icontained* inItem) { HRESULT hr = S_OK; icontained* pContained; // Make sure we've got an element hr = inItem->QueryInterface(*contained_iid, (void **)&pContained); if (FAILED(hr)) return E_UNEXPECTED; // Add the variant (dispatch) to the collection m_bDirty = TRUE; mCollect.push_back(CComVariant(inItem)); pContained->Release(); return hr; } // Inserts an item at an integer index template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::Insert(long inIndex, icontained* inItem) { HRESULT hr = S_OK; icontained* pContained; // Make sure we've got an element hr = inItem->QueryInterface(*contained_iid, (void **)&pContained); if (FAILED(hr)) return E_UNEXPECTED; pContained->Release(); // Make sure the index is within range (index is 1-based) if(inIndex < 1 || inIndex > mCollect.size() + 1) return E_INVALIDARG; // Add the variant (dispatch) to the collection m_bDirty = TRUE; if(inIndex == mCollect.size() + 1) return Add(inItem); iterator iter = mCollect.begin(); for(long i = 1; i < inIndex; ++i) ++iter; if(iter != mCollect.end() || mCollect.size() == 0) mCollect.insert(iter, CComVariant(inItem)); return hr; } // Removes an item at an integer index template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::Remove(long inIndex) { HRESULT hr = S_OK; // Make sure the index is within range (index is 1-based) if (inIndex < 1 || inIndex > mCollect.size()) return E_INVALIDARG; m_bDirty = TRUE; mCollect.erase(mCollect.begin() + inIndex - 1); return hr; } ///////////////////////////////////////////////////////////// // // Remove all elements from the collection // template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::RemoveAll() { mCollect.erase(mCollect.begin(), mCollect.end()); return S_OK; } template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::Reserve(long lngSize) { mCollect.reserve(lngSize); return S_OK; } template <class icontainer, const IID* container_iid, const GUID* libid, class container, const CLSID* container_clsid, class icontained, const IID* contained_iid> STDMETHODIMP CComCollect<icontainer, container_iid, libid, container, container_clsid, icontained, contained_iid>::Shrink() { collection(mCollect).swap(mCollect); return S_OK; } template <class T> HRESULT SaveXML_COMMON(T *pObj, BSTR *pbstrXml) { HRESULT hRes(S_OK); CComQIPtr<IPersistVarXML> pPersistXML(pObj); if(pPersistXML) { CComVariant vOutput; VARIANT vXml; vXml.vt = VT_EMPTY; vOutput.vt = VT_BYREF|VT_VARIANT; vOutput.pvarVal = &vXml; hRes = pPersistXML->SaveXML(vOutput); if(SUCCEEDED(hRes)) { // if(!IsBadWritePtr(*pbstrXml,1)) // ::SysFreeString(*pbstrXml); *pbstrXml = vXml.bstrVal; } } return hRes; } template <class T> HRESULT LoadXML_COMMON(T *pObj, BSTR xml) { // TODO: Add your implementation code here HRESULT hRes(S_OK); //get interface what we need try { CComQIPtr<IPersistVarXML> pPersistXML(pObj); if(pPersistXML) { //save string to Variant BY REF (we asked for this! -> VT_VARIANT|VT_BYREF) hRes = pPersistXML->LoadXML((CComVariant)xml); } } catch (...) { hRes=S_FALSE; } return hRes; } template <class I,class I2,class T_THIS> HRESULT SaveXMLContent_T(I2 *pX, T_THIS *pThis) { long i, count; pThis->get_Count(&count); for (i=1; i<=count;i++){ I *lpTemp=NULL; pThis->get_Item(i,&lpTemp); if(lpTemp){ CComQIPtr<IPersistVarXML> pPersistXML(lpTemp); if(pPersistXML) pPersistXML->SaveXML(CComVariant(pX)); lpTemp->Release(); } } return S_OK; } #endif
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 359 ] ] ]
3973201632b611b26c5e5b82a09a4496dc36488d
3cad09dde08a7f9f4fe4acbcb2ffd4643a642957
/Recognition/Recognition/EyeTracker/track.cpp
0b21c9e063dbb9c7894e4fa66a2870bfcb479a3b
[]
no_license
gmarcotte/cos436-eye-tracker
420ad9c37cf1819a238c0379662dee71f6fd9b0f
05d0b010bae8dcf06add2ae93534851668d4eff4
refs/heads/master
2021-01-23T13:47:38.533817
2009-01-15T02:40:43
2009-01-15T02:40:43
32,219,880
0
0
null
null
null
null
UTF-8
C++
false
false
17,170
cpp
#include <stdio.h> #include <cv.h> #include <highgui.h> #include <math.h> #include "..\Recognizer.h" #include "..\Eye.h" #include "CaptureHandler.h" #include "config.h" #include "GUI.h" #ifndef PI #define PI 3.1415926 #endif void calibration_mouse_handler( int event, int x, int y, int flags, void* param); class Pupil { public: int x; int y; int radius; }; void draw_box(IplImage* img, CvRect rect, CvScalar color) { cvRectangle( img, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height), color, 2); } double dist(CvPoint a, CvPoint b) { return sqrt( (double)((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)) ); } double dist(CvPoint2D32f a, CvPoint2D32f b) { return sqrt( (double)((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)) ); } double heron(double a, double b, double c) { double s = (a + b + c) / 2; return sqrt(s * (s - a) * (s - b) * (s - c)); } bool boxContainsCircle(CvPoint2D32f* box, CvPoint2D32f center, double radius) { double a, b; double alt; double width = dist(box[0], box[1]); double height = dist(box[1], box[2]); a = dist(box[0], center); b = dist(box[1], center); // Check that the center is contained in the box if (acos( (width*width + b*b - a*a) / (2 * width * b) ) > PI/2) return false; if (acos( (width*width + a*a - b*b) / (2 * width * a) ) > PI/2) return false; // Now check the distance from the center to the width side alt = 2 * heron(a, b, width) / width; if (alt < radius || (height - alt) < radius) return false; // Check that the center is contained in the box a = dist(box[2], center); if (acos( (height*height + b*b - a*a) / (2 * height * b) ) > PI/2) return false; if (acos( (height*height + a*a - b*b) / (2 * height * a) ) > PI/2) return false; // Now check the distance from the center to the height side alt = 2 * heron(a, b, height) / height; if (alt < radius || (width - alt) < radius) return false; return true; } bool boxContainsCircle(CvRect box, CvPoint center, int radius) { return ( ((center.x - radius) >= box.x) && ((center.y - radius) >= box.y) && ((center.x + radius) <= box.x + box.width) && ((center.y + radius) <= box.y + box.height) ); } void updatePupil(IplImage* inputImg, Pupil* update_pup) { CvMemStorage* storage = cvCreateMemStorage(1000); CvSeq* firstContour; int headerSize = sizeof(CvContour); int count; CvPoint* pointArray; CvPoint2D32f* pointArray32f; int i; CvBox2D* myBox = (CvBox2D*)malloc(sizeof(CvBox2D)); CvPoint myCenter; int height, width; update_pup->radius = 0; // ** Contours are found cvFindContours(inputImg, storage, &firstContour, headerSize, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_TC89_L1 ); //cvNamedWindow("draw", 0); // ** Search for valid contours int max = 0; while (firstContour != NULL) { //cvDrawContours(inputImg, firstContour,RGB(0,0,255),CV_FILLED,0); //cvShowImage("draw", inputImg); //cvWaitKey(0); // not a point? if ( CV_IS_SEQ_CURVE(firstContour) ) { count = firstContour->total; pointArray = (CvPoint*) malloc(count*sizeof(CvPoint)); pointArray32f = (CvPoint2D32f*) malloc((count+1)*sizeof(CvPoint2D32f)); // ** Get contour points cvCvtSeqToArray(firstContour, pointArray, CV_WHOLE_SEQ); // ** Convert to 32f points for (i=0; i<count; i++) { pointArray32f[i].x = (float)pointArray[i].x; pointArray32f[i].y = (float)pointArray[i].y; } pointArray32f[i].x = pointArray[0].x; pointArray32f[i].y = pointArray[0].y; if (count>=6) { // ** Fit Ellipse to the points cvFitEllipse(pointArray32f, count, myBox); myCenter.x = (int)myBox->center.x; myCenter.y = (int)myBox->center.y; height = (int)myBox->size.height; width = (int)myBox->size.width; //cvCircle(inputImg,myCenter, (int)length/2 ,RGB(0,0,255)); //float myAngle= myBox->angle; //cvEllipse(inputImg, myCenter, cvSize ((int)width/2,(int)height/2), -myBox->angle, 0,360,RGB(0,255,0),1); // ** Check whether it is a valid connected component or not? if ( (myCenter.x > 0) && (myCenter.y > 0) && ((height+width) > max) && ((height-width) <= width) && ((width-height) <= height) && (width <= (int)inputImg->width/2) && (height <= (int)inputImg->height/2)) { max = height + width; update_pup->x = myCenter.x; update_pup->y = myCenter.y; height>width ? update_pup->radius=(int)height/2 : update_pup->radius=(int)width/2; } } free(pointArray); free(pointArray32f); } //cvShowImage("draw", inputImg); cvWaitKey(0); firstContour = firstContour->h_next; } free(myBox); cvReleaseMemStorage(&storage); //cvDestroyWindow("draw"); } void updateEyebrow(IplImage* img, CvBox2D* eyebrow, Pupil* pupil) { CvSeq* contours; IplImage* scratch = cvCloneImage(img); CvMemStorage* storage = cvCreateMemStorage(0); cvFindContours(scratch, storage, &contours); CvSeq* curr_contour = contours; int run_once = 0; CvBox2D best_eyebrow; best_eyebrow.center.x = -1; while (curr_contour != NULL) { CvBox2D box = cvMinAreaRect2(curr_contour); if ( cvContourPerimeter(curr_contour) >= MIN_EB_PERIM && (pupil->radius == 0 || (abs(box.center.x - pupil->x) < 200 && (pupil->y - box.center.y) > 10) )) { if (run_once == 0) { best_eyebrow = box; run_once = 1; } else if (best_eyebrow.center.y > box.center.y) best_eyebrow = box; } curr_contour = curr_contour->h_next; } *(eyebrow) = best_eyebrow; cvReleaseMemStorage(&storage); cvReleaseImage(&scratch); } CvRect box; bool drawing_box = false; bool need_update = false; bool drawn = false; int main(int argc, char* argv[]) { int i; char c; bool from_camera = false; CaptureHandler* capture = NULL; if (1 < argc) { // The user supplied a command line path for video analysis try { capture = new CaptureHandler(argv[1]); } catch(CaptureHandler::FileReadError) { printf("Read Error: skipping file %s\n", argv[1]); delete capture; } printf("Tracking from %s:\n", argv[1]); capture->printFullState(); printf("\n\n"); } while (!capture) { // No command-line argument was given, so try to load a camera try { capture = new CaptureHandler(); } catch(CaptureHandler::CameraReadError) { printf("ERROR: Please connect a camera, and then press enter.\n"); getchar(); continue; } printf("Tracking from camera:\n"); from_camera = true; capture->printFullState(); } char* original_name = "Direct Camera Feed"; cvNamedWindow(original_name); IplImage* original_img = cvCreateImage(cvSize(capture->getWidth(), capture->getHeight()), IPL_DEPTH_8U, 3); printf("\n\n******** ENTERING CALIBRATION **************\n\n"); printf("Please position the camera so that both eye regions (including eyebrows and forehead) are clearly visible.\n"); printf("Press SPACEBAR to continue...\n"); long numFrames = 0; while( (c = cvWaitKey(1)) != 32) { numFrames++; capture->advance(); capture->getCurrentFrame(original_img, CV_CVTIMG_FLIP); cvFlip(original_img, 0, 1); cvShowImage(original_name, original_img); } printf("Watched for %d frames.\n", numFrames); IplImage* shown_img = cvCloneImage(original_img); CvRect regions[NUM_INPUTS]; cvSetMouseCallback(original_name, calibration_mouse_handler); printf("Please select the full eye regions, one at a time. Be sure to include the full eyebrow and forehead.\n"); printf("Press SPACEBAR after each selection...\n"); box = cvRect(-1, -1, 0, 0); CvScalar colors[] = {CV_RGB(255, 0, 0), CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), CV_RGB(255, 255, 0), CV_RGB(255, 0, 255), CV_RGB(0, 255, 255)}; for (i=0; i<NUM_INPUTS; i++) { printf("Please select REGION %d!\n", i); while ( ((c = cvWaitKey(15)) != 32) || !drawn) { cvCopyImage(original_img, shown_img); if (drawing_box || drawn) draw_box(shown_img, box, colors[i%6]); cvShowImage(original_name, shown_img); } regions[i] = box; draw_box(original_img, box, colors[i%6]); drawn = false; drawing_box = false; } printf("Thank you. Please check the windows to ensure regions were chosen properly.\n\n"); // Set up the eye trackers, image memory and display windows for each input IplImage* original_eyes[NUM_INPUTS]; IplImage* modified_eyes[NUM_INPUTS]; IplImage* threshold_eyes[NUM_INPUTS]; char modified_names[NUM_INPUTS][MAX_STRING]; char eyebrow_names[NUM_INPUTS][MAX_STRING]; char pupil_names[NUM_INPUTS][MAX_STRING]; for (i=0; i<NUM_INPUTS; i++) { sprintf_s(modified_names[i], MAX_STRING, "Input %d: Tracking Results", i); sprintf_s(eyebrow_names[i], MAX_STRING, "Input %d: Thresholded Eyebrow", i); sprintf_s(pupil_names[i], MAX_STRING, "Input %d: Thresholded Pupil", i); cvNamedWindow(modified_names[i]); cvNamedWindow(eyebrow_names[i]); cvNamedWindow(pupil_names[i]); original_eyes[i] = cvCreateImage(cvSize(regions[i].width, regions[i].height), IPL_DEPTH_8U, 3); modified_eyes[i] = cvCreateImage(cvSize(regions[i].width, regions[i].height), IPL_DEPTH_8U, 1); threshold_eyes[i] = cvCreateImage(cvSize(regions[i].width, regions[i].height), IPL_DEPTH_8U, 1); } // Set up the config GUI char* config_name = "EyeTracker Configuration"; cvNamedWindow(config_name, 0); ConfigTrackbar* pupil_thresholds[NUM_INPUTS]; ConfigTrackbar* eyebrow_thresholds[NUM_INPUTS]; for (i=0; i<NUM_INPUTS; i++) { char pupil_name[MAX_STRING]; sprintf_s(pupil_name, MAX_STRING, "P Thresh %d", i); pupil_thresholds[i] = new ConfigTrackbar( pupil_name, config_name, 20, 0, 255, 255); char eyebrow_name[MAX_STRING]; sprintf_s(eyebrow_name, MAX_STRING, "EB Thresh %d", i); eyebrow_thresholds[i] = new ConfigTrackbar( eyebrow_name, config_name, 85, 0, 255, 255); } Recognizer* recog = new Recognizer(); Eye* eye_trackers[NUM_INPUTS]; Pupil pupils[NUM_INPUTS]; CvBox2D eyebrows[NUM_INPUTS]; for (i = 0; i < NUM_INPUTS; i++) { eye_trackers[i] = new Eye(); pupils[i].x = 0; pupils[i].y = 0; pupils[i].radius = 0; eyebrows[i].angle = 0; eyebrows[i].center = cvPoint2D32f(0, 0); eyebrows[i].size = cvSize2D32f(0, 0); } bool calibrating = true; int calibration_stage = -1; int calibration_timer = -1; bool send_data = false; printf("Please adjust the sliders at left until the pupil and eyebrow are stably tracked.\n"); printf("Press SPACEBAR when you are ready to continue.\n\n"); // Quit with Escape long frameCount = 0; while ( (c = cvWaitKey(33)) != 27) { frameCount++; // Start and stop recognition with Spacebar if (c == 32 && !calibrating) send_data = !send_data; if (c == 'c') { printf("\n\n****** Entering Recalibration ****\n\n"); printf("Please press SPACEBAR to continue with calibration.\n"); send_data = false; calibrating = true; Eye e; recog->updateLeftCalibration(e, 0, true); recog->updateRightCalibration(e, 0, true); } cvResetImageROI(original_img); capture->advance(); capture->getCurrentFrame(original_img, CV_CVTIMG_FLIP); cvFlip(original_img, 0, 1); for (i = 0; i < NUM_INPUTS; i++) { cvSetImageROI(original_img, regions[i]); cvCopy(original_img, original_eyes[i]); cvZero(modified_eyes[i]); cvCvtPixToPlane(original_img, NULL, NULL, modified_eyes[i], NULL ); cvSmooth(modified_eyes[i], modified_eyes[i], CV_GAUSSIAN, 5, 5); // Pupil detection cvThreshold(modified_eyes[i], threshold_eyes[i], pupil_thresholds[i]->getValue(), 255, CV_THRESH_BINARY_INV); cvCanny(threshold_eyes[i], threshold_eyes[i], CANNY_LOW, CANNY_HIGH, 3); cvShowImage(pupil_names[i], threshold_eyes[i]); updatePupil(threshold_eyes[i], &pupils[i]); //printf("Found pupil %d: (%d, %d) - %d\n", i, pupils[i].x, pupils[i].y, pupils[i].radius); if (pupils[i].radius > MIN_PUPIL_RADIUS) cvDrawCircle(original_eyes[i], cvPoint(pupils[i].x, pupils[i].y), pupils[i].radius, CV_RGB(255, 0, 0), 2); // Eyebrow Detection cvThreshold(modified_eyes[i], threshold_eyes[i], eyebrow_thresholds[i]->getValue(), 255, CV_THRESH_BINARY_INV); cvShowImage(eyebrow_names[i], threshold_eyes[i]); updateEyebrow(threshold_eyes[i], &eyebrows[i], &pupils[i]); if ( (eyebrows[i].center.x >= 0 && eyebrows[i].center.x <= capture->getWidth()) && (eyebrows[i].center.y >= 0 && eyebrows[i].center.y <= capture->getHeight()) ) { //printf("Found Eyebrow: \n\tPos: %6.2f, %6.2f, \n\tSize: %6.2f, %6.2f, \n\tAngle: %6.2f\n", // eyebrows[i].center.x, eyebrows[i].center.y, // eyebrows[i].size.width, eyebrows[i].size.height, // eyebrows[i].angle); cvDrawEllipse(original_eyes[i], cvPoint(eyebrows[i].center.x, eyebrows[i].center.y), cvSize(eyebrows[i].size.height / 2, eyebrows[i].size.width / 2), eyebrows[i].angle, 0.0, 360.0, CV_RGB(0, 255, 0), 2); } //else //{ // printf("No eyebrow detected.\n"); //} cvShowImage(modified_names[i], original_eyes[i]); eye_trackers[i]->noPupilDetected = (pupils[i].radius <= MIN_PUPIL_RADIUS); eye_trackers[i]->pupilPositionX = pupils[i].x; eye_trackers[i]->pupilPositionY = pupils[i].y; eye_trackers[i]->pupilRadius = pupils[i].radius; eye_trackers[i]->browPositionY = eyebrows[i].center.y; eye_trackers[i]->browHeight = min(eyebrows[i].size.height, eyebrows[i].size.width); } if (send_data) recog->updateState(*eye_trackers[0], *eye_trackers[1]); if (calibrating) { if (calibration_stage < 0 && c == 32) { calibration_stage++; printf("Without moving your head, please look to the LEFT.\n"); printf("Press SPACEBAR and continue to look LEFT for a few moments\n"); printf("before looking back at the screen.\n\n"); } else if (calibration_stage >= NUM_TO_CALIBRATE) { printf("Thank you for calibrating!\n"); printf("********** END OF CALIBRATION ***************\n\n"); printf("Please press SPACEBAR to begin recognition\n\n"); calibrating = false; calibration_stage = -1; calibration_timer = -1; } else if (c == 32 && calibration_timer < 0) { calibration_timer++; } else if (calibration_timer >= 0) { recog->updateLeftCalibration(*eye_trackers[0], calibration_stage, false); recog->updateRightCalibration(*eye_trackers[1], calibration_stage, false); calibration_timer++; } if (calibration_timer >= CALIBRATION_FRAMES) { calibration_timer = -1; calibration_stage++; switch(calibration_stage) { case 1: { printf("Without moving your head, please look to the RIGHT.\n"); printf("Press SPACEBAR and continue to look RIGHT for a few moments\n"); printf("before looking back at the screen.\n\n"); } break; case 2: { printf("Without moving your head, please look UP.\n"); printf("Press SPACEBAR and continue to look UP for a few moments\n"); printf("before looking back at the screen.\n\n"); } break; case 3: { printf("Without moving your head, please look DOWN.\n"); printf("Press SPACEBAR and continue to look DOWN for a few moments\n"); printf("before looking back at the screen.\n\n"); } break; case 4: { printf("Without moving your head, please RAISE YOUR EYEBROWS."); printf("Press SPACEBAR and continue RAISING YOUR EYEBROWS for a\n"); printf("few moments before returning them to a rest position.\n\n"); } break; } } } } // Free memory allocated for input captures for (i=0; i<NUM_INPUTS; i++) { cvReleaseImage(&modified_eyes[i]); cvReleaseImage(&threshold_eyes[i]); cvDestroyWindow(modified_names[i]); cvDestroyWindow(eyebrow_names[i]); cvDestroyWindow(pupil_names[i]); delete eye_trackers[i]; delete pupil_thresholds[i]; delete eyebrow_thresholds[i]; } delete recog; delete capture; cvDestroyWindow(config_name); printf("Tracked for %d frames.\n", frameCount); return 1; } void calibration_mouse_handler(int event, int x, int y, int flas, void* param) { switch(event) { case CV_EVENT_MOUSEMOVE: { if(drawing_box) { box.width = x - box.x; box.height = y - box.y; } } break; case CV_EVENT_LBUTTONDOWN: { drawing_box = true; drawn = false; box = cvRect(x, y, 0, 0); } break; case CV_EVENT_LBUTTONUP: { drawing_box = false; drawn = true; if (box.width < 0) { box.x += box.width; box.width *= -1; } if (box.height < 0) { box.y += box.height; box.height *= -1; } } break; } }
[ "garrett.marcotte@45935db4-cf16-11dd-8ca8-e3ff79f713b6" ]
[ [ [ 1, 578 ] ] ]
50d67ac6d27f032e6dbd500ae86544071b2f32f7
fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68
/combat.cpp
69703bbe8afed68e2ad7789a383cc9a835136fe0
[]
no_license
divinity76/ancient-divinity-ots
d29efe620cea3fe8d61ffd66480cf20c8f77af13
0c7b5bfd5b9277c97d28de598f781dbb198f473d
refs/heads/master
2020-05-16T21:01:29.130756
2010-10-11T22:58:07
2010-10-11T22:58:07
29,501,722
0
0
null
null
null
null
UTF-8
C++
false
false
37,206
cpp
////////////////////////////////////////////////////////////////////// // OpenTibia - an opensource roleplaying game ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // 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 "otpch.h" #include "combat.h" #include "configmanager.h" #include "game.h" #include "creature.h" #include "player.h" #include "const76.h" #include "tools.h" #include "weapons.h" #include "spells.h" #include <sstream> extern Game g_game; extern Weapons* g_weapons; extern ConfigManager g_config; extern Spells* g_spells; Combat::Combat() { params.condition = NULL; params.valueCallback = NULL; params.tileCallback = NULL; params.targetCallback = NULL; area = NULL; formulaType = FORMULA_UNDEFINED; mina = 0.0; minb = 0.0; maxa = 0.0; maxb = 0.0; } Combat::~Combat() { delete params.condition; delete params.valueCallback; delete params.tileCallback; delete params.targetCallback; delete area; } bool Combat::getMinMaxValues(Creature* creature, Creature* target, int32_t& min, int32_t& max) const { if(!creature){ return false; } if(creature->getCombatValues(min, max)){ return true; } else if(Player* player = creature->getPlayer()){ if(params.valueCallback){ params.valueCallback->getMinMaxValues(player, min, max, params.useCharges); return true; } else{ switch(formulaType){ case FORMULA_LEVELMAGIC: { max = (int32_t)((player->getLevel() * 2 + player->getMagicLevel() * 3) * 1. * mina + minb); min = (int32_t)((player->getLevel() * 2 + player->getMagicLevel() * 3) * 1. * maxa + maxb); return true; break; } case FORMULA_SKILL: { Item* tool = player->getWeapon(); const Weapon* weapon = g_weapons->getWeapon(tool); min = (int32_t)minb; if(weapon){ max = (int32_t)(weapon->getWeaponDamage(player, target, tool, true) * maxa + maxb); if(params.useCharges && tool->hasCharges() && g_config.getNumber(ConfigManager::REMOVE_WEAPON_CHARGES)){ int32_t newCharge = std::max((int32_t)0, ((int32_t)tool->getCharges()) - 1); g_game.transformItem(tool, tool->getID(), newCharge); } } else{ max = (int32_t)maxb; } return true; break; } case FORMULA_VALUE: { min = (int32_t)mina; max = (int32_t)maxa; return true; break; } default: min = 0; max = 0; return false; break; } //std::cout << "No callback set for combat" << std::endl; } } else if(formulaType == FORMULA_VALUE){ min = (int32_t)mina; max = (int32_t)maxa; return true; } return false; } void Combat::getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area, std::list<Tile*>& list) { if(area){ area->getList(centerPos, targetPos, list); } else if(targetPos.x >= 0 && targetPos.y >= 0 && targetPos.z >= 0 && targetPos.x <= 0xFFFF && targetPos.y <= 0xFFFF && targetPos.z < MAP_MAX_LAYERS) { Tile* tile = g_game.getTile(targetPos.x, targetPos.y, targetPos.z); if(!tile) { tile = new Tile(targetPos.x, targetPos.y, targetPos.z); g_game.setTile(tile); } list.push_back(tile); } } CombatType_t Combat::ConditionToDamageType(ConditionType_t type) { switch(type){ case CONDITION_FIRE: return COMBAT_FIREDAMAGE; break; case CONDITION_ENERGY: return COMBAT_ENERGYDAMAGE; break; case CONDITION_POISON: return COMBAT_POISONDAMAGE; break; default: break; } return COMBAT_NONE; } ConditionType_t Combat::DamageToConditionType(CombatType_t type) { switch(type){ case COMBAT_FIREDAMAGE: return CONDITION_FIRE; break; case COMBAT_ENERGYDAMAGE: return CONDITION_ENERGY; break; case COMBAT_POISONDAMAGE: return CONDITION_POISON; break; default: break; } return CONDITION_NONE; } bool Combat::isPlayerCombat(const Creature* target) { if(target->getPlayer()){ return true; } if(target->isSummon() && target->getMaster()->getPlayer()){ return true; } return false; } ReturnValue Combat::canTargetCreature(const Player* player, const Creature* target) { if(player == target){ return RET_YOUMAYNOTATTACKTHISPLAYER; } if(!player->hasFlag(PlayerFlag_IgnoreProtectionZone)){ //pz-zone if(player->getZone() == ZONE_PROTECTION){ return RET_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE; } if(target->getZone() == ZONE_PROTECTION){ return RET_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE; } //nopvp-zone if(isPlayerCombat(target)){ if(player->getZone() == ZONE_NOPVP){ return RET_ACTIONNOTPERMITTEDINANOPVPZONE; } if(target->getZone() == ZONE_NOPVP){ return RET_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE; } } } if(player->hasFlag(PlayerFlag_CannotUseCombat) || !target->isAttackable()){ if(target->getPlayer()){ return RET_YOUMAYNOTATTACKTHISPLAYER; } else{ return RET_YOUMAYNOTATTACKTHISCREATURE; } } #ifdef __SKULLSYSTEM__ if(player->hasSafeMode() && target->getPlayer()) { if(player->getParty()) { if(player->getParty()->isPlayerMember(target->getPlayer()) || player->getParty()->getLeader() == target) { return Combat::canDoCombat(player, target); } } if(target->getPlayer()->getSkull() == SKULL_NONE) { if(!Combat::isInPvpZone(player, target)) { return RET_TURNSECUREMODETOATTACKUNMARKEDPLAYERS; } } } #endif return Combat::canDoCombat(player, target); } ReturnValue Combat::canDoCombat(const Creature* caster, const Tile* tile, bool isAggressive) { if(tile->hasProperty(BLOCKPROJECTILE)){ return RET_NOTENOUGHROOM; } //if(!tile->ground){ // return RET_NOTPOSSIBLE; //} if(tile->floorChange()){ return RET_NOTENOUGHROOM; } if(tile->getTeleportItem()){ return RET_NOTENOUGHROOM; } if(caster){ if(caster->getPosition().z < tile->getPosition().z){ return RET_FIRSTGODOWNSTAIRS; } if(caster->getPosition().z > tile->getPosition().z){ return RET_FIRSTGOUPSTAIRS; } if(const Player* player = caster->getPlayer()){ if(player->hasFlag(PlayerFlag_IgnoreProtectionZone)){ return RET_NOERROR; } } } //pz-zone if(isAggressive && tile->hasFlag(TILESTATE_PROTECTIONZONE)){ return RET_ACTIONNOTPERMITTEDINPROTECTIONZONE; } return RET_NOERROR; } bool Combat::isInPvpZone(const Creature* attacker, const Creature* target) { if(attacker->getZone() != ZONE_PVP){ return false; } if(target->getZone() != ZONE_PVP){ return false; } return true; } ReturnValue Combat::canDoCombat(const Creature* attacker, const Creature* target) { if(attacker){ if(const Player* targetPlayer = target->getPlayer()){ if(targetPlayer->hasFlag(PlayerFlag_CannotBeAttacked)){ return RET_YOUMAYNOTATTACKTHISPLAYER; } if(const Player* attackerPlayer = attacker->getPlayer()){ if(attackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)){ return RET_YOUMAYNOTATTACKTHISPLAYER; } } if(attacker->isSummon()){ if(const Player* masterAttackerPlayer = attacker->getMaster()->getPlayer()){ if(masterAttackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)){ return RET_YOUMAYNOTATTACKTHISPLAYER; } } } } else if(target->getMonster()){ if(const Player* attackerPlayer = attacker->getPlayer()){ if(attackerPlayer->hasFlag(PlayerFlag_CannotAttackMonster)){ return RET_YOUMAYNOTATTACKTHISCREATURE; } } } if(attacker->getPlayer() || (attacker->isSummon() && attacker->getMaster()->getPlayer()) ){ //nopvp-zone if(target->getPlayer() && target->getTile()->hasFlag(TILESTATE_NOPVPZONE)){ return RET_ACTIONNOTPERMITTEDINANOPVPZONE; } if(g_game.getWorldType() == WORLD_TYPE_NO_PVP){ if(target->getPlayer()){ if(!isInPvpZone(attacker, target)){ return RET_YOUMAYNOTATTACKTHISPLAYER; } } if(target->isSummon() && target->getMaster()->getPlayer()){ if(!isInPvpZone(attacker, target)){ return RET_YOUMAYNOTATTACKTHISCREATURE; } } } } } return RET_NOERROR; } void Combat::setPlayerCombatValues(formulaType_t _type, double _mina, double _minb, double _maxa, double _maxb) { formulaType = _type; mina = _mina; minb = _minb; maxa = _maxa; maxb = _maxb; } bool Combat::setParam(CombatParam_t param, uint32_t value) { switch(param){ case COMBATPARAM_COMBATTYPE: { params.combatType = (CombatType_t)value; return true; } case COMBATPARAM_EFFECT: { params.impactEffect = value; return true; } case COMBATPARAM_DISTANCEEFFECT: { params.distanceEffect = value; return true; } case COMBATPARAM_BLOCKEDBYARMOR: { params.blockedByArmor = (value != 0); return true; } case COMBATPARAM_BLOCKEDBYSHIELD: { params.blockedByShield = (value != 0); return true; } case COMBATPARAM_TARGETCASTERORTOPMOST: { params.targetCasterOrTopMost = (value != 0); return true; } case COMBATPARAM_CREATEITEM: { params.itemId = value; return true; } case COMBATPARAM_AGGRESSIVE: { params.isAggressive = (value != 0); return true; } case COMBATPARAM_DISPEL: { params.dispelType = (ConditionType_t)value; return true; } case COMBATPARAM_USECHARGES: { params.useCharges = (value != 0); return true; } case COMBATPARAM_HITEFFECT: { params.hitEffect = (MagicEffectClasses)value; return true; } case COMBATPARAM_HITTEXTCOLOR: { params.hitTextColor = (TextColor_t)value; return true; } default: { break; } } return false; } bool Combat::setCallback(CallBackParam_t key) { switch(key){ case CALLBACKPARAM_LEVELMAGICVALUE: { delete params.valueCallback; params.valueCallback = new ValueCallback(FORMULA_LEVELMAGIC); return true; } case CALLBACKPARAM_SKILLVALUE: { delete params.valueCallback; params.valueCallback = new ValueCallback(FORMULA_SKILL); return true; } case CALLBACKPARAM_TARGETTILECALLBACK: { delete params.tileCallback; params.tileCallback = new TileCallback(); break; } case CALLBACKPARAM_TARGETCREATURECALLBACK: { delete params.targetCallback; params.targetCallback = new TargetCallback(); break; } default: { std::cout << "Combat::setCallback - Unknown callback type: " << (uint32_t)key << std::endl; break; } } return false; } CallBack* Combat::getCallback(CallBackParam_t key) { switch(key){ case CALLBACKPARAM_LEVELMAGICVALUE: case CALLBACKPARAM_SKILLVALUE: { return params.valueCallback; } case CALLBACKPARAM_TARGETTILECALLBACK: { return params.tileCallback; } case CALLBACKPARAM_TARGETCREATURECALLBACK: { return params.targetCallback; } } return NULL; } bool Combat::CombatHealthFunc(Creature* caster, Creature* target, const CombatParams& params, void* data) { Combat2Var* var = (Combat2Var*)data; int32_t healthChange = random_range(var->minChange, var->maxChange, DISTRO_NORMAL); if(g_game.combatBlockHit(params.combatType, caster, target, healthChange, params.blockedByShield, params.blockedByArmor)){ return false; } if(healthChange < 0){ if(caster && caster->getPlayer() && target->getPlayer()){ healthChange = healthChange/2; } } bool result = g_game.combatChangeHealth(params.combatType, params.hitEffect, params.hitTextColor, caster, target, healthChange); if(result){ CombatConditionFunc(caster, target, params, NULL); CombatDispelFunc(caster, target, params, NULL); } return result; } bool Combat::CombatManaFunc(Creature* caster, Creature* target, const CombatParams& params, void* data) { Combat2Var* var = (Combat2Var*)data; int32_t manaChange = random_range(var->minChange, var->maxChange, DISTRO_NORMAL); if(manaChange < 0){ if(caster && caster->getPlayer() && target->getPlayer()){ manaChange = manaChange/2; } } bool result = g_game.combatChangeMana(caster, target, manaChange); if(result){ CombatConditionFunc(caster, target, params, NULL); CombatDispelFunc(caster, target, params, NULL); } return result; } bool Combat::CombatConditionFunc(Creature* caster, Creature* target, const CombatParams& params, void* data) { bool result = false; if(params.condition){ if(caster == target || !target->isImmune(params.condition->getType())){ Condition* conditionCopy = params.condition->clone(); if(caster){ conditionCopy->setParam(CONDITIONPARAM_OWNER, caster->getID()); } //TODO: infight condition until all aggressive conditions has ended result = target->addCombatCondition(conditionCopy); } } return result; } bool Combat::CombatDispelFunc(Creature* caster, Creature* target, const CombatParams& params, void* data) { if(target->hasCondition(params.dispelType)){ target->removeCondition(caster, params.dispelType); return true; } return false; } bool Combat::CombatNullFunc(Creature* caster, Creature* target, const CombatParams& params, void* data) { CombatConditionFunc(caster, target, params, NULL); CombatDispelFunc(caster, target, params, NULL); return true; } void Combat::combatTileEffects(const SpectatorVec& list, Creature* caster, Tile* tile, const CombatParams& params) { if(params.itemId != 0){ uint32_t itemId = params.itemId; Player* p_caster = NULL; if(caster){ if(caster->getPlayer()){ p_caster = caster->getPlayer(); } else if(caster->isSummon()){ p_caster = caster->getMaster()->getPlayer(); } } if(p_caster){ if(g_game.getWorldType() == WORLD_TYPE_NO_PVP || tile->hasFlag(TILESTATE_NOPVPZONE)){ if(itemId == ITEM_FIREFIELD_PVP){ itemId = ITEM_FIREFIELD_NOPVP; } else if(itemId == ITEM_POISONFIELD_PVP){ itemId = ITEM_POISONFIELD_NOPVP; } else if(itemId == ITEM_ENERGYFIELD_PVP){ itemId = ITEM_ENERGYFIELD_NOPVP; } } else if(params.isAggressive){ const ItemType& it = Item::items[itemId]; if(!it.blockSolid){ p_caster->addInFightTicks(true); } else{ p_caster->addInFightTicks(); } } } Item* item = Item::CreateItem(itemId); if(caster){ item->setOwner(caster->getID()); } ReturnValue ret = g_game.internalAddItem(tile, item); if(ret == RET_NOERROR){ g_game.startDecay(item); } else{ delete item; } } if(params.tileCallback){ params.tileCallback->onTileCombat(caster, tile); } if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(list, tile->getPosition(), params.impactEffect); } } void Combat::postCombatEffects(Creature* caster, const Position& pos, const CombatParams& params) { if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), pos, params.distanceEffect); } } void Combat::addDistanceEffect(Creature* caster, const Position& fromPos, const Position& toPos, uint8_t effect) { uint8_t distanceEffect = effect; if(caster && distanceEffect != NM_ME_NONE){ g_game.addDistanceEffect(fromPos, toPos, distanceEffect); } } void Combat::CombatFunc(Creature* caster, const Position& pos, const AreaCombat* area, const CombatParams& params, COMBATFUNC func, void* data) { std::list<Tile*> tileList; if(caster){ getCombatArea(caster->getPosition(), pos, area, tileList); } else{ getCombatArea(pos, pos, area, tileList); } SpectatorVec list; uint32_t maxX = 0; uint32_t maxY = 0; uint32_t diff; //calculate the max viewable range for(std::list<Tile*>::iterator it = tileList.begin(); it != tileList.end(); ++it){ diff = std::abs((*it)->getPosition().x - pos.x); if(diff > maxX){ maxX = diff; } diff = std::abs((*it)->getPosition().y - pos.y); if(diff > maxY){ maxY = diff; } } g_game.getSpectators(list, pos, false, true, maxX + Map::maxViewportX, maxX + Map::maxViewportX, maxY + Map::maxViewportY, maxY + Map::maxViewportY); for(std::list<Tile*>::iterator it = tileList.begin(); it != tileList.end(); ++it){ bool bContinue = true; if(canDoCombat(caster, *it, params.isAggressive) == RET_NOERROR){ for(CreatureVector::iterator cit = (*it)->creatures.begin(); bContinue && cit != (*it)->creatures.end(); ++cit){ if(params.targetCasterOrTopMost){ if(caster && caster->getTile() == (*it)){ if(*cit == caster){ bContinue = false; } } else if(*cit == (*it)->getTopCreature()){ bContinue = false; } if(bContinue){ continue; } } if(!params.isAggressive || (caster != *cit && Combat::canDoCombat(caster, *cit) == RET_NOERROR)){ func(caster, *cit, params, data); if(params.targetCallback){ params.targetCallback->onTargetCombat(caster, *cit); } } } combatTileEffects(list, caster, *it, params); } } postCombatEffects(caster, pos, params); } void Combat::doCombat(Creature* caster, Creature* target) const { //target combat callback function if(params.combatType != COMBAT_NONE){ int32_t minChange = 0; int32_t maxChange = 0; getMinMaxValues(caster, target, minChange, maxChange); if(params.combatType != COMBAT_MANADRAIN){ doCombatHealth(caster, target, minChange, maxChange, params); } else{ doCombatMana(caster, target, minChange, maxChange, params); } } else{ doCombatDefault(caster, target, params); } } void Combat::doCombat(Creature* caster, const Position& pos) const { //area combat callback function if(params.combatType != COMBAT_NONE){ int32_t minChange = 0; int32_t maxChange = 0; getMinMaxValues(caster, NULL, minChange, maxChange); if(params.combatType != COMBAT_MANADRAIN){ doCombatHealth(caster, pos, area, minChange, maxChange, params); } else{ doCombatMana(caster, pos, area, minChange, maxChange, params); } } else{ CombatFunc(caster, pos, area, params, CombatNullFunc, NULL); } } void Combat::doCombatHealth(Creature* caster, Creature* target, int32_t minChange, int32_t maxChange, const CombatParams& params) { if(!params.isAggressive || (caster != target && Combat::canDoCombat(caster, target) == RET_NOERROR)){ Combat2Var var; var.minChange = minChange; var.maxChange = maxChange; CombatHealthFunc(caster, target, params, (void*)&var); if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(target->getPosition(), params.impactEffect); } if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect); } } } void Combat::doCombatHealth(Creature* caster, const Position& pos, const AreaCombat* area, int32_t minChange, int32_t maxChange, const CombatParams& params) { Combat2Var var; var.minChange = minChange; var.maxChange = maxChange; CombatFunc(caster, pos, area, params, CombatHealthFunc, (void*)&var); } void Combat::doCombatMana(Creature* caster, Creature* target, int32_t minChange, int32_t maxChange, const CombatParams& params) { if(!params.isAggressive || (caster != target && Combat::canDoCombat(caster, target) == RET_NOERROR)){ Combat2Var var; var.minChange = minChange; var.maxChange = maxChange; CombatManaFunc(caster, target, params, (void*)&var); if(params.targetCallback){ params.targetCallback->onTargetCombat(caster, target); } if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(target->getPosition(), params.impactEffect); } if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect); } } } void Combat::doCombatMana(Creature* caster, const Position& pos, const AreaCombat* area, int32_t minChange, int32_t maxChange, const CombatParams& params) { Combat2Var var; var.minChange = minChange; var.maxChange = maxChange; CombatFunc(caster, pos, area, params, CombatManaFunc, (void*)&var); } void Combat::doCombatCondition(Creature* caster, const Position& pos, const AreaCombat* area, const CombatParams& params) { CombatFunc(caster, pos, area, params, CombatConditionFunc, NULL); } void Combat::doCombatCondition(Creature* caster, Creature* target, const CombatParams& params) { if(!params.isAggressive || (caster != target && Combat::canDoCombat(caster, target) == RET_NOERROR)){ CombatConditionFunc(caster, target, params, NULL); if(params.targetCallback){ params.targetCallback->onTargetCombat(caster, target); } if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(target->getPosition(), params.impactEffect); } if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect); } } } void Combat::doCombatDispel(Creature* caster, const Position& pos, const AreaCombat* area, const CombatParams& params) { CombatFunc(caster, pos, area, params, CombatDispelFunc, NULL); } void Combat::doCombatDispel(Creature* caster, Creature* target, const CombatParams& params) { if(!params.isAggressive || (caster != target && Combat::canDoCombat(caster, target) == RET_NOERROR)){ CombatDispelFunc(caster, target, params, NULL); if(params.targetCallback){ params.targetCallback->onTargetCombat(caster, target); } if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(target->getPosition(), params.impactEffect); } if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect); } } } void Combat::doCombatDefault(Creature* caster, Creature* target, const CombatParams& params) { if(!params.isAggressive || (caster != target && Combat::canDoCombat(caster, target) == RET_NOERROR)){ const SpectatorVec& list = g_game.getSpectators(target->getTile()->getPosition()); CombatNullFunc(caster, target, params, NULL); combatTileEffects(list, caster, target->getTile(), params); if(params.targetCallback){ params.targetCallback->onTargetCombat(caster, target); } if(params.impactEffect != NM_ME_NONE){ g_game.addMagicEffect(target->getPosition(), params.impactEffect); } if(caster && params.distanceEffect != NM_ME_NONE){ addDistanceEffect(caster, caster->getPosition(), target->getPosition(), params.distanceEffect); } } } //********************************************************** void ValueCallback::getMinMaxValues(Player* player, int32_t& min, int32_t& max, bool useCharges) const { //"onGetPlayerMinMaxValues"(...) if(m_scriptInterface->reserveScriptEnv()){ ScriptEnviroment* env = m_scriptInterface->getScriptEnv(); lua_State* L = m_scriptInterface->getLuaState(); if(!env->setCallbackId(m_scriptId, m_scriptInterface)) return; uint32_t cid = env->addThing(player); m_scriptInterface->pushFunction(m_scriptId); lua_pushnumber(L, cid); int32_t parameters = 1; switch(type){ case FORMULA_LEVELMAGIC: { //"onGetPlayerMinMaxValues"(cid, level, maglevel) lua_pushnumber(L, player->getLevel()); lua_pushnumber(L, player->getMagicLevel()); parameters += 2; break; } case FORMULA_SKILL: { //"onGetPlayerMinMaxValues"(cid, attackSkill, attackValue, attackFactor) Item* tool = player->getWeapon(); int32_t attackSkill = player->getWeaponSkill(tool); int32_t attackValue = 7; if(tool){ attackValue = tool->getAttack(); if(useCharges && tool->hasCharges() && g_config.getNumber(ConfigManager::REMOVE_WEAPON_CHARGES)){ int32_t newCharge = std::max(0, tool->getCharges() - 1); g_game.transformItem(tool, tool->getID(), newCharge); } } float attackFactor = player->getAttackFactor(); lua_pushnumber(L, attackSkill); lua_pushnumber(L, attackValue); lua_pushnumber(L, attackFactor); parameters += 3; break; } default: std::cout << "ValueCallback::getMinMaxValues - unknown callback type" << std::endl; return; break; } int size0 = lua_gettop(L); if(lua_pcall(L, parameters, 2 /*nReturnValues*/, 0) != 0){ LuaScriptInterface::reportError(NULL, std::string(LuaScriptInterface::popString(L))); } else{ max = LuaScriptInterface::popNumber(L); min = LuaScriptInterface::popNumber(L); } if((lua_gettop(L) + parameters /*nParams*/ + 1) != size0){ LuaScriptInterface::reportError(NULL, "Stack size changed!"); } env->resetCallback(); m_scriptInterface->releaseScriptEnv(); } else{ std::cout << "[Error] Call stack overflow. ValueCallback::getMinMaxValues" << std::endl; return; } } //********************************************************** void TileCallback::onTileCombat(Creature* creature, Tile* tile) const { //"onTileCombat"(cid, pos) if(m_scriptInterface->reserveScriptEnv()){ ScriptEnviroment* env = m_scriptInterface->getScriptEnv(); lua_State* L = m_scriptInterface->getLuaState(); if(!env->setCallbackId(m_scriptId, m_scriptInterface)) return; uint32_t cid = 0; if(creature){ cid = env->addThing(creature); } m_scriptInterface->pushFunction(m_scriptId); lua_pushnumber(L, cid); m_scriptInterface->pushPosition(L, tile->getPosition(), 0); m_scriptInterface->callFunction(2); env->resetCallback(); m_scriptInterface->releaseScriptEnv(); } else{ std::cout << "[Error] Call stack overflow. TileCallback::onTileCombat" << std::endl; return; } } //********************************************************** void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const { //"onTargetCombat"(cid, target) if(m_scriptInterface->reserveScriptEnv()){ ScriptEnviroment* env = m_scriptInterface->getScriptEnv(); lua_State* L = m_scriptInterface->getLuaState(); if(!env->setCallbackId(m_scriptId, m_scriptInterface)) return; uint32_t cid = 0; if(creature){ cid = env->addThing(creature); } uint32_t targetCid = env->addThing(target); m_scriptInterface->pushFunction(m_scriptId); lua_pushnumber(L, cid); lua_pushnumber(L, targetCid); int size0 = lua_gettop(L); if(lua_pcall(L, 2, 0 /*nReturnValues*/, 0) != 0){ LuaScriptInterface::reportError(NULL, std::string(LuaScriptInterface::popString(L))); } if((lua_gettop(L) + 2 /*nParams*/ + 1) != size0){ LuaScriptInterface::reportError(NULL, "Stack size changed!"); } env->resetCallback(); m_scriptInterface->releaseScriptEnv(); } else{ std::cout << "[Error] Call stack overflow. TargetCallback::onTargetCombat" << std::endl; return; } } //********************************************************** void AreaCombat::clear() { for(AreaCombatMap::iterator it = areas.begin(); it != areas.end(); ++it){ delete it->second; } areas.clear(); } AreaCombat::AreaCombat(const AreaCombat& rhs) { hasExtArea = rhs.hasExtArea; for(AreaCombatMap::const_iterator it = rhs.areas.begin(); it != rhs.areas.end(); ++it){ areas[it->first] = new MatrixArea(*it->second); } } bool AreaCombat::getList(const Position& centerPos, const Position& targetPos, std::list<Tile*>& list) const { Tile* tile = g_game.getTile(targetPos.x, targetPos.y, targetPos.z); const MatrixArea* area = getArea(centerPos, targetPos); if(!area){ return false; } Position tmpPos = targetPos; size_t cols = area->getCols(); size_t rows = area->getRows(); uint32_t centerY, centerX; area->getCenter(centerY, centerX); tmpPos.x -= centerX; tmpPos.y -= centerY; for(size_t y = 0; y < rows; ++y){ for(size_t x = 0; x < cols; ++x){ if(area->getValue(y, x) != 0){ if(tmpPos.x >= 0 && tmpPos.y >= 0 && tmpPos.z >= 0 && tmpPos.x <= 0xFFFF && tmpPos.y <= 0xFFFF && tmpPos.z < MAP_MAX_LAYERS) { if(g_game.isSightClear(targetPos, tmpPos, true)){ tile = g_game.getTile(tmpPos.x, tmpPos.y, tmpPos.z); if(!tile){ tile = new Tile(tmpPos.x, tmpPos.y, tmpPos.z); g_game.setTile(tile); } list.push_back(tile); } } } tmpPos.x += 1; } tmpPos.x -= cols; tmpPos.y += 1; } return true; } int32_t round(float v) { int32_t t = (int32_t)std::floor(v); if((v - t) > 0.5){ return t + 1; } else{ return t; } } void AreaCombat::copyArea(const MatrixArea* input, MatrixArea* output, MatrixOperation_t op) const { uint32_t centerY, centerX; input->getCenter(centerY, centerX); if(op == MATRIXOPERATION_COPY){ for(unsigned int y = 0; y < input->getRows(); ++y){ for(unsigned int x = 0; x < input->getCols(); ++x){ (*output)[y][x] = (*input)[y][x]; } } output->setCenter(centerY, centerX); } else if(op == MATRIXOPERATION_MIRROR){ for(unsigned int y = 0; y < input->getRows(); ++y){ int rx = 0; for(int x = input->getCols() - 1; x >= 0; --x){ (*output)[y][rx++] = (*input)[y][x]; } } output->setCenter(centerY, (input->getRows() - 1) - centerX); } else if(op == MATRIXOPERATION_FLIP){ for(unsigned int x = 0; x < input->getCols(); ++x){ int ry = 0; for(int y = input->getRows() - 1; y >= 0; --y){ (*output)[ry++][x] = (*input)[y][x]; } } output->setCenter((input->getCols() - 1) - centerY, centerX); } //rotation else{ uint32_t centerX, centerY; input->getCenter(centerY, centerX); int32_t rotateCenterX = (output->getCols() / 2) - 1; int32_t rotateCenterY = (output->getRows() / 2) - 1; int32_t angle = 0; switch(op){ case MATRIXOPERATION_ROTATE90: angle = 90; break; case MATRIXOPERATION_ROTATE180: angle = 180; break; case MATRIXOPERATION_ROTATE270: angle = 270; break; default: angle = 0; break; } double angleRad = 3.1416 * angle / 180.0; float a = std::cos(angleRad); float b = -std::sin(angleRad); float c = std::sin(angleRad); float d = std::cos(angleRad); for(int32_t x = 0; x < (int32_t)input->getCols(); ++x){ for(int32_t y = 0; y < (int32_t)input->getRows(); ++y){ //calculate new coordinates using rotation center int32_t newX = x - centerX; int32_t newY = y - centerY; //perform rotation int32_t rotatedX = round(newX * a + newY * b); int32_t rotatedY = round(newX * c + newY * d); //write in the output matrix using rotated coordinates (*output)[rotatedY + rotateCenterY][rotatedX + rotateCenterX] = (*input)[y][x]; } } output->setCenter(rotateCenterY, rotateCenterX); } } MatrixArea* AreaCombat::createArea(const std::list<uint32_t>& list, uint32_t rows) { unsigned int cols = list.size() / rows; MatrixArea* area = new MatrixArea(rows, cols); uint32_t x = 0; uint32_t y = 0; for(std::list<uint32_t>::const_iterator it = list.begin(); it != list.end(); ++it){ if(*it == 1 || *it == 3){ area->setValue(y, x, true); } if(*it == 2 || *it == 3){ area->setCenter(y, x); } ++x; if(cols == x){ x = 0; ++y; } } return area; } void AreaCombat::setupArea(const std::list<uint32_t>& list, uint32_t rows) { MatrixArea* area = createArea(list, rows); //NORTH areas[NORTH] = area; uint32_t maxOutput = std::max(area->getCols(), area->getRows()) * 2; //SOUTH MatrixArea* southArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, southArea, MATRIXOPERATION_ROTATE180); areas[SOUTH] = southArea; //EAST MatrixArea* eastArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, eastArea, MATRIXOPERATION_ROTATE90); areas[EAST] = eastArea; //WEST MatrixArea* westArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, westArea, MATRIXOPERATION_ROTATE270); areas[WEST] = westArea; } void AreaCombat::setupArea(int32_t length, int32_t spread) { std::list<uint32_t> list; uint32_t rows = length; int32_t cols = 1; if(spread != 0){ cols = ((length - length % spread) / spread) * 2 + 1; } int32_t colSpread = cols; for(uint32_t y = 1; y <= rows; ++y){ int32_t mincol = cols - colSpread + 1; int32_t maxcol = cols - (cols - colSpread); for(int32_t x = 1; x <= cols; ++x){ if(y == rows && x == ((cols - cols % 2) / 2) + 1){ list.push_back(3); } else if(x >= mincol && x <= maxcol){ list.push_back(1); } else{ list.push_back(0); } } if(spread > 0 && y % spread == 0){ --colSpread; } } setupArea(list, rows); } void AreaCombat::setupArea(int32_t radius) { int32_t area[13][13] = { {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0}, {0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0}, {0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0}, {0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0}, {0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0}, {8, 7, 6, 5, 4, 2, 1, 2, 4, 5, 6, 7, 8}, {0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0}, {0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0}, {0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0}, {0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0}, {0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0} }; std::list<uint32_t> list; for(int32_t y = 0; y < 13; ++y){ for(int32_t x = 0; x < 13; ++x){ if(area[y][x] == 1){ list.push_back(3); } else if(area[y][x] > 0 && area[y][x] <= radius){ list.push_back(1); } else{ list.push_back(0); } } } setupArea(list, 13); } void AreaCombat::setupExtArea(const std::list<uint32_t>& list, uint32_t rows) { if(list.empty()){ return; } hasExtArea = true; MatrixArea* area = createArea(list, rows); //NORTH-WEST areas[NORTHWEST] = area; uint32_t maxOutput = std::max(area->getCols(), area->getRows()) * 2; //NORTH-EAST MatrixArea* neArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, neArea, MATRIXOPERATION_MIRROR); areas[NORTHEAST] = neArea; //SOUTH-WEST MatrixArea* swArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, swArea, MATRIXOPERATION_FLIP); areas[SOUTHWEST] = swArea; //SOUTH-EAST MatrixArea* seArea = new MatrixArea(maxOutput, maxOutput); copyArea(swArea, seArea, MATRIXOPERATION_MIRROR); areas[SOUTHEAST] = seArea; } //********************************************************** void MagicField::onStepInField(Creature* creature, bool purposeful/*= true*/) { //remove magic walls/wild growth if(isBlocking()){ g_game.internalRemoveItem(this, 1); } else{ const ItemType& it = items[getID()]; if(it.condition){ Condition* conditionCopy = it.condition->clone(); uint32_t owner = getOwner(); if(owner != 0 && purposeful){ bool harmfulField = true; if(g_game.getWorldType() == WORLD_TYPE_NO_PVP || getTile()->hasFlag(TILESTATE_NOPVPZONE) ){ Creature* creature = g_game.getCreatureByID(owner); if(creature){ if(creature->getPlayer() || (creature->isSummon() && creature->getMaster()->getPlayer())){ harmfulField = false; } } } if( !harmfulField || (OTSYS_TIME() - createTime <= g_config.getNumber(ConfigManager::FIELD_OWNERSHIP_DURATION)) || creature->hasBeenAttacked(owner)) { conditionCopy->setParam(CONDITIONPARAM_OWNER, owner); } } creature->addCondition(conditionCopy); } } }
[ "[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e" ]
[ [ [ 1, 1449 ] ] ]
b473ca6e75fbedb5e17fcdbc4ce9c7e94ec6df92
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/gxlib/gxl.dib.cpp
49630374bc42393786d137fafebeba718e4f3447
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
24,086
cpp
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gxl.inc.h" #include "gxl.memory.h" #include "gxl.file.h" #include "gxl.dib.h" /* * */ const uint32 BWPAL[32] = { 0x0000,0x0841,0x1082,0x18C3,0x2104,0x2945,0x3186,0x39C7, 0x4208,0x4A49,0x528A,0x5ACB,0x630C,0x6B4D,0x738E,0x7BCF, 0x8410,0x8C51,0x9492,0x9CD3,0xA514,0xAD55,0xB596,0xBDD7, 0xC618,0xCE59,0xD69A,0xDEDB,0xE71C,0xEF5D,0xF79E,0xFFDF }; /* * */ const uint16 RED_MASK[iDib::TypeCount] = { 0x1F<<11, 0xF<<12, 0x1F<<11 }; const uint16 GREEN_MASK[iDib::TypeCount] = { 0x3F<<5, 0xF<<8, 0x1F<<6 }; const uint16 BLUE_MASK[iDib::TypeCount] = { 0x1F, 0xF<<4, 0x1F<<1 }; const uint16 COLOR_MASK[iDib::TypeCount] = { 0xFFFF, 0xFFF<<4, 0x7FFF<<1 }; const uint16 ALPHA_MASK[iDib::TypeCount] = { 0, 0xF, 0x1 }; /* * Blit functions */ inline void BlitDibBlock_RGB(iDib::pixel *dst, const iDib::pixel *src, uint32 size) { memcpy(dst,src,size*sizeof(iDib::pixel)); } inline void BlitDibBlock_RGBA(iDib::pixel *dst, const iDib::pixel *src, uint32 size) { uint16* dpix = dst; const uint16* spix = src; for (uint32 xx=0; xx<size; ++xx) { if ((*spix & ALPHA_MASK[iDib::RGBA]) == 0xF) { *dpix = (*spix & RED_MASK[iDib::RGBA]) | (*spix & GREEN_MASK[iDib::RGBA])>>1 | (*spix & BLUE_MASK[iDib::RGBA])>>3; } else if ((*spix & ALPHA_MASK[iDib::RGBA]) > 0) { uint16 aa = (*spix & ALPHA_MASK[iDib::RGBA])<<2; uint16 RB1 = *dpix & (RED_MASK[iDib::RGB] | BLUE_MASK[iDib::RGB]); uint16 G1 = *dpix & (GREEN_MASK[iDib::RGB] ); uint16 RB2 = (*spix & RED_MASK[iDib::RGBA]) | (*spix & BLUE_MASK[iDib::RGBA])>>3; uint16 G2 = (*spix & (GREEN_MASK[iDib::RGBA] ) ) >> 1; uint16 RB = RB1 + (((RB2-RB1) * (aa)) >> 6); uint16 G = G1 + (((G2-G1)*(aa))>>6); RB &= (RED_MASK[iDib::RGB] | BLUE_MASK[iDib::RGB]); G &= (GREEN_MASK[iDib::RGB]); *dpix = RB | G; } spix++; dpix++; } } inline void BlitDibBlock_RGBCK(iDib::pixel *dst, const iDib::pixel *src, uint32 size) { uint16* dpix = dst; const uint16* spix = src; for (uint32 xx=0; xx<size; ++xx) { if ((*spix & ALPHA_MASK[iDib::RGBCK]) > 0) *dpix = (*spix & RED_MASK[iDib::RGBCK]) | (*spix & GREEN_MASK[iDib::RGBCK]) | (*spix & BLUE_MASK[iDib::RGBCK]) >> 1; dpix++; spix++; } } inline void BlitDibBlockAlpha(iDib::pixel *dst, const iDib::pixel *src, uint8 a, uint32 size) { const uint32 alpha = a; #if 1 for (uint32 xx=0; xx<size; ++xx, ++dst, ++src) { const uint32 a = *src; const uint32 b = *dst; uint32 sb = a & 0x1f; uint32 sg = (a >> 5) & 0x3f; uint32 sr = (a >> 11) & 0x1f; uint32 db = b & 0x1f; uint32 dg = (b >> 5) & 0x3f; uint32 dr = (b >> 11) & 0x1f; *dst = (iDib::pixel)((((alpha * (sb-db)) >> 8) + db) | (((alpha * (sg-dg)) >> 8) + dg) << 5 | (((alpha * (sr-dr)) >> 8) + dr) << 11); } #else uint8 inv_a = 256-a; for (uint32 xx=0; xx<size; ++xx, ++dst, ++src) { uint16 sr = a * ((*src & RED_MASK[iDib::RGB]) >> 11); uint16 sg = a * ((*src & GREEN_MASK[iDib::RGB]) >> 5); uint16 sb = a * ((*src & BLUE_MASK[iDib::RGB])); uint16 dr = inv_a * ((*dst & RED_MASK[iDib::RGB]) >> 11); uint16 dg = inv_a * ((*dst & GREEN_MASK[iDib::RGB]) >> 5); uint16 db = inv_a * ((*dst & BLUE_MASK[iDib::RGB])); *dst = (((sr+dr)>>8)<<11 | ((sg+dg)>>8)<<5 | ((sb+db)>>8)); } #endif } inline void FillDibBlock(iDib::pixel *dst, const iDib::pixel src, uint32 size) { for (uint32 xx=0; xx<size; ++xx, ++dst) *dst = src; } inline void FillDibBlockAlpha(iDib::pixel *dst, const iDib::pixel src, uint8 a, uint32 size) { #if 1 const uint32 alpha = a; const uint32 sb = src & 0x1f; const uint32 sg = (src >> 5) & 0x3f; const uint32 sr = (src >> 11) & 0x1f; for (uint32 xx=0; xx<size; ++xx, ++dst) { const uint32 b = *dst; uint32 db = b & 0x1f; uint32 dg = (b >> 5) & 0x3f; uint32 dr = (b >> 11) & 0x1f; *dst = (iDib::pixel)((((alpha * (sb-db)) >> 8) + db) | (((alpha * (sg-dg)) >> 8) + dg) << 5 | (((alpha * (sr-dr)) >> 8) + dr) << 11); } #else uint8 inv_a = 255-a; uint16 sr = a * ((src & RED_MASK[iDib::RGB]) >> 11); uint16 sg = a * ((src & GREEN_MASK[iDib::RGB]) >> 5); uint16 sb = a * ((src & BLUE_MASK[iDib::RGB])); for (uint32 xx=0; xx<size; ++xx, ++dst) { uint16 dr = inv_a * ((*dst & RED_MASK[iDib::RGB]) >> 11); uint16 dg = inv_a * ((*dst & GREEN_MASK[iDib::RGB]) >> 5); uint16 db = inv_a * ((*dst & BLUE_MASK[iDib::RGB])); *dst = (((sr+dr)>>8)<<11 | ((sg+dg)>>8)<<5 | ((sb+db)>>8)); } #endif } inline void SetDibPixelAlpha(iDib::pixel *dst, const iDib::pixel src, uint8 a) { uint8 inv_a = 255-a; uint16 sr = a * ((src & RED_MASK[iDib::RGB]) >> 11); uint16 sg = a * ((src & GREEN_MASK[iDib::RGB]) >> 5); uint16 sb = a * ((src & BLUE_MASK[iDib::RGB])); uint16 dr = inv_a * ((*dst & RED_MASK[iDib::RGB]) >> 11); uint16 dg = inv_a * ((*dst & GREEN_MASK[iDib::RGB]) >> 5); uint16 db = inv_a * ((*dst & BLUE_MASK[iDib::RGB])); *dst = (((sr+dr)>>8)<<11 | ((sg+dg)>>8)<<5 | ((sb+db)>>8)); } /* * iDib */ iDib::iDib() : m_dibType(RGB) {} iDib::iDib(const iDib& dib) { Init(dib); } iDib::iDib(const iSize& siz, Type dType) { Init(siz,dType); } iDib::iDib(const iDib& dib, const iRect& rect) { Init(dib, rect); } iDib::~iDib() { Cleanup(); } void iDib::Init(const iDib& dib) { m_dibType = dib.GetType(); Allocate(dib); } void iDib::Init(const iDib& dib, const iRect& rect) { Allocate(rect); m_dibType = dib.m_dibType; const pixel *src_ptr = dib.m_RGB + dib.m_Siz.w*rect.y + rect.x; pixel *dst_ptr = m_RGB; for (uint32 yy=0; yy<rect.h; ++yy){ memcpy(dst_ptr,src_ptr,rect.w*sizeof(pixel)); dst_ptr+=rect.w; src_ptr+=dib.m_Siz.w; } } void iDib::Init(const iSize& siz, Type dType) { m_dibType = dType; Allocate(siz); } void iDib::Resize(const iSize& siz) { Cleanup(); Allocate(siz); } void iDib::Allocate(const iSize& siz) { check(m_RGB.IsClean()); m_Siz = siz; m_RGB.Allocate(siz.w*siz.h); } void iDib::Allocate(const iDib& dib) { check(m_RGB.IsClean()); m_Siz = dib.GetSize(); m_RGB.Allocate(dib.m_RGB, dib.m_Siz.w*dib.m_Siz.h); } void iDib::Cleanup() { m_RGB.Clean(); m_Siz.Zero(); m_dibType = RGB; } void iDib::Swap(iDib& other) { iBuff<pixel> tmp_buff(m_RGB); m_RGB.Allocate(other.m_RGB); other.m_RGB.Allocate(tmp_buff); iSwap(m_Siz,other.m_Siz); iSwap(m_dibType,other.m_dibType); } iDib& iDib::operator = ( const iDib& other ) { iDib clone( other ); Swap( clone ); return *this; } /* * iPaletteDib */ iPaletteDib::iPaletteDib() {} iPaletteDib::~iPaletteDib() { Cleanup(); } iPaletteDib::iPaletteDib(const iSize& siz) { Init(siz); } void iPaletteDib::Init(const iSize& siz) { Allocate(siz); } void iPaletteDib::Allocate(const iSize& siz) { check(m_RGB.IsClean()); m_Siz = siz; m_RGB.Allocate(siz.w*siz.h); } void iPaletteDib::Cleanup() { m_RGB.Clean(); m_Siz.Zero(); } void iPaletteDib::CopyToDibXY(iDib& dib, const iPoint& pos, const iPalette& pal, uint8 alpha) const { if ( (pos.x + (sint32)m_Siz.w) <= 0 || (pos.y + (sint32)m_Siz.w) <= 0) return; iRect src_rect(GetSize()); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,iRect(0,0,dib.GetWidth(),dib.GetHeight()),src_rect,GetSize())) return; const uint8* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; for (uint32 yy=0; yy<dst_rect.h; yy++) { for (uint32 xx=0; xx<dst_rect.w; ++xx) { if (src_clr[xx]) { if (alpha == 255) dst_clr[xx] = pal[src_clr[xx]]; else SetDibPixelAlpha(&dst_clr[xx], pal[src_clr[xx]],alpha); } } src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } void iPaletteDib::CopyRectToDibXY(iDib& dib, const iRect& srect, const iPoint& pos, const iPalette& pal, uint8 alpha) const { iRect src_rect(srect); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,dib.GetSize(),src_rect,GetSize())) return; const uint8* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; for (uint32 yy=0; yy<dst_rect.h; yy++) { for (uint32 xx=0; xx<dst_rect.w; ++xx) { if (src_clr[xx] && pal[src_clr[xx]] != RGB16(0xF0,0,0xF0)) { if (alpha == 255) dst_clr[xx] = pal[src_clr[xx]]; else SetDibPixelAlpha(&dst_clr[xx], pal[src_clr[xx]],alpha); } } src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } /* * Primitives */ void iDib::Fill(pixel clr, uint8 a) { if (a==255) FillDibBlock(m_RGB,clr,m_Siz.w*m_Siz.h); else FillDibBlockAlpha(m_RGB,clr,a,m_Siz.w*m_Siz.h); } void iDib::FillRect(const iRect& rc, pixel clr, uint8 a) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; uint32 h = drect.h; while (h--) { if (a==255) FillDibBlock(dstPtr,clr,drect.w); else FillDibBlockAlpha(dstPtr,clr,a,drect.w); dstPtr += m_Siz.w; } } const uint32 tintGradient[32] = { 0x4101, 0x4101, 0x4921, 0x4942, 0x5142, 0x5162, 0x5983, 0x61a3, 0x61e3, 0x6a04, 0x7224, 0x7a65, 0x8285, 0x8ac6, 0x8ae6, 0x9327, 0xa368, 0xa389, 0xabc9, 0xb40a, 0xbc4b, 0xc48c, 0xcccd, 0xd4ed, 0xdd2e, 0xe54f, 0xed90, 0xedd0, 0xf5f1, 0xf611, 0xf632, 0xf652 }; const uint32 hcbwGradient[32] = { 0x4101, 0x4101, 0x4921, 0x4942, 0x5142, 0x5162, 0x5983, 0x61a3, 0x61e3, 0x6a04, 0x7224, 0x7a65, 0x8285, 0x8ac6, 0x8ae6, 0x9327, 0xa368, 0xa389, 0xabc9, 0xb40a, 0xbc4b, 0xc48c, 0xcccd, 0xd4ed, 0xdd2e, 0xe54f, 0xed90, 0xedd0, 0xf5f1, 0xf611, 0xf632, 0xf652 }; always_inline uint32 TintedShadow( uint32 pixel) { //static uint8 rpt = 31; uint32 chnl = (pixel >> 6) & 0x1f; return ( (BWPAL[chnl] & 0xf7de) >> 1 ) + ((0x39e7 & 0xf7de) >> 1); } void iDib::Fade(uint8 a) { if (!a){ Fill(cColor_Black); } else if (a != 255) { Fill(cColor_Black, 255 - a); } } void iDib::DarkenBWRect(const iRect& rc) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; uint32 h = drect.h; while (h--) { pixel* pptr = dstPtr; for (uint32 xx=0; xx<drect.w; ++xx, ++pptr){ *pptr = (pixel)TintedShadow(*pptr); } dstPtr += m_Siz.w; } } void iDib::Darken25Rect(const iRect& rc) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; uint32 h = drect.h; while (h--) { pixel* pptr = dstPtr; for (uint32 xx=0; xx<drect.w; ++xx, ++pptr){ *pptr = (pixel)Darken25(*pptr); } dstPtr += m_Siz.w; } } void iDib::Darken50Rect(const iRect& rc) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; uint32 h = drect.h; while (h--) { pixel* pptr = dstPtr; for (uint32 xx=0; xx<drect.w; ++xx, ++pptr){ *pptr = (pixel)Darken50(*pptr); } dstPtr += m_Siz.w; } } void iDib::HGradientRect(const iRect& rc, pixel c1, pixel c2) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; sint32 tw = rc.w-1; if (!tw){ return; } pixel gr[320]; pixel* pgr = gr; sint32 tp = drect.x-rc.x; uint32 cnt = iMIN<uint32>(drect.w,320); uint32 w = cnt; while (w--) { sint32 dr = ((c2&0xF800)>>11) - ((c1&0xF800)>>11); sint32 nr = iCLAMP<sint32>(0,0x1F, ((c1&0xF800)>>11) + ((dr*tp)/tw)); sint32 dg = ((c2&0x7E0)>>5) - ((c1&0x7E0)>>5); sint32 ng = iCLAMP<sint32>(0,0x3F, ((c1&0x7E0)>>5) + ((dg*tp)/tw)); sint32 db = (c2&0x1F) - (c1&0x1F); sint32 nb = iCLAMP<sint32>(0,0x1F, (c1&0x1F) + ((db*tp)/tw)); *pgr = (pixel)((nr<<11)|(ng<<5)|nb); pgr++; tp++; } uint32 h = drect.h; while (h--) { memcpy(dstPtr, gr, cnt * sizeof(pixel)); dstPtr += m_Siz.w; } } void iDib::VGradientRect(const iRect& rc, pixel c1, pixel c2) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; pixel* dstPtr = m_RGB + drect.y*m_Siz.w+drect.x; sint32 th = rc.h-1; if (!th){ FillDibBlock(dstPtr,c1,drect.w); return; } sint32 tp = drect.y-rc.y; uint32 h = drect.h; while (h--) { sint32 dr = ((c2&0xF800)>>11) - ((c1&0xF800)>>11); sint32 nr = iCLAMP<sint32>(0,0x1F, ((c1&0xF800)>>11) + ((dr*tp)/th)); sint32 dg = ((c2&0x7E0)>>5) - ((c1&0x7E0)>>5); sint32 ng = iCLAMP<sint32>(0,0x3F, ((c1&0x7E0)>>5) + ((dg*tp)/th)); sint32 db = (c2&0x1F) - (c1&0x1F); sint32 nb = iCLAMP<sint32>(0,0x1F, (c1&0x1F) + ((db*tp)/th)); FillDibBlock(dstPtr,(pixel)((nr<<11)|(ng<<5)|nb),drect.w); dstPtr += m_Siz.w; tp++; } } void iDib::FrameRect(const iRect& rc, pixel clr, uint8 a) { iRect drect(rc); if (!iClipper::ClipRect(drect,m_Siz)) return; HLine(rc.TopLeft(),rc.x2(),clr,a); HLine(rc.BottomLeft(),rc.x2(),clr,a); VLine(rc.TopLeft(),rc.y2(),clr,a); VLine(rc.TopRight(),rc.y2(),clr,a); } void iDib::HLine(const iPoint& pos, sint32 x2, pixel clr, uint8 a) { iPoint dpos1 = iPoint(iMIN(pos.x,x2),pos.y); sint32 dx2 = iMAX(pos.x,x2); if (!iClipper::ClipHLine(dpos1,dx2,m_Siz)) return; uint32 len = dx2-dpos1.x+1; pixel* dstPtr = m_RGB + dpos1.y*m_Siz.w+dpos1.x; if (a==255) FillDibBlock(dstPtr,clr,len); else FillDibBlockAlpha(dstPtr,clr,a,len); } void iDib::VLine(const iPoint& pos, sint32 y2, pixel clr, uint8 a) { iPoint dpos1 = iPoint(pos.x,iMIN(pos.y,y2)); sint32 dy2 = iMAX(pos.y,y2); if (!iClipper::ClipVLine(dpos1,dy2,m_Siz)) return; uint32 len = dy2-dpos1.y+1; pixel* dstPtr = m_RGB + dpos1.y*m_Siz.w+dpos1.x; uint32 h = dy2 - dpos1.y; while (h--) { if (a==255) *dstPtr = clr; else SetDibPixelAlpha(dstPtr,clr,a); dstPtr += m_Siz.w; } } void iDib::Line(const iPoint& p1, const iPoint& p2, pixel clr, uint8 a) { iPoint p( p1 ); iPoint d( iABS( p2.x - p1.x ), iABS( p2.y - p1.y ) ); iPoint s( iSIGN( p2.x - p1.x ), iSIGN( p2.y - p1.y ) ); sint32 d_, d1, d2; if ( d.y <= d.x ) { d_ = d.y * 2 - d.x; d1 = d.y * 2; d2 = ( d.y - d.x ) * 2; PutPixel(p, clr); p = iPoint( p1.x + s.x, p1.y ); for( sint32 i = 0; i < d.x; i++ ) { if ( d_ > 0 ){ d_ += d2; p.y += s.y; } else { d_ += d1; } PutPixel(p, clr); p.x += s.x; } } else { d_ = d.x * 2 - d.y; d1 = d.x * 2; d2 = ( d.x - d.y ) * 2; PutPixel(p, clr); p = iPoint( p1.x, p1.y + s.y ); for( sint32 i = 0; i < d.y; i++ ) { if ( d_ > 0 ) { d_ += d2; p.x += s.x; } else { d_ += d1; } PutPixel(p, clr); p.y += s.y; } } } void iDib::Triangle(const iPoint& p1, const iPoint& p2, const iPoint& p3, pixel clr) { iPoint s, e; sint32 dx1, dx2, dx3; if (p2.y-p1.y > 0) dx1=(p2.x-p1.x)/(p2.y-p1.y); else dx1=0; if (p3.y-p1.y > 0) dx2=(p3.x-p1.x)/(p2.y-p1.y); else dx2=0; if (p3.y-p2.y > 0) dx3=(p3.x-p2.x)/(p3.y-p2.y); else dx3=0; s=e=p1; if(dx1 > dx2) { for(;s.y<=p2.y;s.y++,e.y++,s.x+=dx2,e.x+=dx1) HLine(iPoint(s.x,s.y), e.x, clr); e=p2; for(;s.y<=p3.y;s.y++,e.y++,s.x+=dx2,e.x+=dx3) HLine(iPoint(s.x,s.y), e.x, clr); } else { for(;s.y<=p2.y;s.y++,e.y++,s.x+=dx1,e.x+=dx2) HLine(iPoint(s.x,s.y), e.x, clr); s=p2; for(;s.y<=p3.y;s.y++,e.y++,s.x+=dx3,e.x+=dx2) HLine(iPoint(s.x,s.y), e.x, clr); } } /* * */ void iDib::CopyToDibXY(iDib& dib, const iPoint& pos, uint8 a) const { if ( (pos.x + (sint32)m_Siz.w) <= 0 || (pos.y + (sint32)m_Siz.w) <= 0) return; check(m_dibType == RGB); iRect src_rect(GetSize()); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,iRect(0,0,dib.GetWidth(),dib.GetHeight()),src_rect,GetSize())) return; const uint16* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; for (uint32 yy=0; yy<dst_rect.h; yy++) { BlitDibBlockAlpha(dst_clr,src_clr,a,dst_rect.w); src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } void iDib::CopyToDibXY( iDib& dib, const iPoint& pos) const { if ( (pos.x + (sint32)m_Siz.w) <= 0 || (pos.y + (sint32)m_Siz.w) <= 0) return; iRect src_rect(GetSize()); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,iRect(0,0,dib.GetWidth(),dib.GetHeight()),src_rect,GetSize())) return; const uint16* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; for (uint32 yy=0; yy<dst_rect.h; yy++) { if (m_dibType == RGB) BlitDibBlock_RGB(dst_clr,src_clr,dst_rect.w); else if (m_dibType == RGBA) BlitDibBlock_RGBA(dst_clr,src_clr,dst_rect.w); else if (m_dibType == RGBCK) BlitDibBlock_RGBCK(dst_clr,src_clr,dst_rect.w); src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } // void iDib::CopyRectToDibXY(iDib& dib, const iRect& srect, const iPoint& pos, uint8 a) const { iRect src_rect(srect); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,dib.GetSize(),src_rect,GetSize())) return; const uint16* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; if ( a == 255 ) { for (uint32 yy=0; yy<dst_rect.h; yy++) { if (m_dibType == RGB) BlitDibBlock_RGB(dst_clr,src_clr,dst_rect.w); else if (m_dibType == RGBA) BlitDibBlock_RGBA(dst_clr,src_clr,dst_rect.w); else if (m_dibType == RGBCK) BlitDibBlock_RGBCK(dst_clr,src_clr,dst_rect.w); src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } else { for (uint32 yy=0; yy<dst_rect.h; yy++) { BlitDibBlockAlpha(dst_clr,src_clr,a,dst_rect.w); src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } } void iDib::BlendToDibXY(iDib& dib, const iPoint& pos, pixel ck, uint8 bval) const { if ( (pos.x + (sint32)m_Siz.w) <= 0 || (pos.y + (sint32)m_Siz.w) <= 0) return; iRect src_rect(GetSize()); iSize siz = iSize(dib.GetWidth() - pos.x, dib.GetHeight() - pos.y); iRect dst_rect(pos,siz); if (!iClipper::iClipRectRect(dst_rect,iRect(0,0,dib.GetWidth(),dib.GetHeight()),src_rect,GetSize())) return; const uint16* src_clr = m_RGB+src_rect.y*m_Siz.w+src_rect.x; uint16* dst_clr=dib.GetPtr()+dst_rect.y*dib.GetWidth()+dst_rect.x; for (uint32 yy=0; yy<dst_rect.h; ++yy) { const uint16* scl = src_clr; uint16* dcl = dst_clr; for (uint32 xx=0; xx<dst_rect.w; ++xx) { if (*scl != ck) { uint8 inv_a = 255-bval; uint16 sr = bval * ((*scl & RED_MASK[iDib::RGB]) >> 11); uint16 sg = bval * ((*scl & GREEN_MASK[iDib::RGB]) >> 5); uint16 sb = bval * ((*scl & BLUE_MASK[iDib::RGB])); uint16 dr = inv_a * ((*dcl & RED_MASK[iDib::RGB]) >> 11); uint16 dg = inv_a * ((*dcl & GREEN_MASK[iDib::RGB]) >> 5); uint16 db = inv_a * ((*dcl & BLUE_MASK[iDib::RGB])); *dcl = (((sr+dr)>>8)<<11 | ((sg+dg)>>8)<<5 | ((sb+db)>>8)); } scl++; dcl++; } //if (m_dibType == RGB) BlitDibBlock_RGB(dst_clr,src_clr,dst_rect.w); //else if (m_dibType == RGBA) BlitDibBlock_RGBA(dst_clr,src_clr,dst_rect.w); //else if (m_dibType == RGBCK) BlitDibBlock_RGBCK(dst_clr,src_clr,dst_rect.w); src_clr+=m_Siz.w; dst_clr+=dib.GetWidth(); } } #ifndef UNDER_CE void iDib::BlitToDCXY(HDC hdc, const iPoint& pos, bool bDoubleSize) const { uint32 bi_siz = sizeof ( BITMAPINFOHEADER ) + 3*sizeof(DWORD); BITMAPINFO bi; memset(&bi,0,sizeof(BITMAPINFOHEADER)); DWORD* bmask = (DWORD*)bi.bmiColors; bmask[0] = 0x1F<<11; bmask[1] = 0x3F<<5; bmask[2] = 0x1F; bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = m_Siz.w; bi.bmiHeader.biHeight = -(sint32)m_Siz.h; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 16; bi.bmiHeader.biCompression = BI_BITFIELDS; bi.bmiHeader.biSizeImage = m_Siz.w * m_Siz.h * 2; if (bDoubleSize) { StretchDIBits(hdc,pos.x,pos.y,m_Siz.w*2,m_Siz.h*2,0,0,m_Siz.w,m_Siz.h,m_RGB,&bi,DIB_RGB_COLORS,SRCCOPY); } else { SetDIBitsToDevice(hdc,pos.x,pos.y,m_Siz.w,m_Siz.h,0,0,0,m_Siz.h,m_RGB,&bi,DIB_RGB_COLORS); } } #endif /* * Save bitmap */ bool SaveDibBitmap32(const iDib& dib, const iStringT& fname) { iFilePtr pFile = CreateWin32File(fname); if (!pFile) return false; uint32 pix_siz = dib.GetWidth()*dib.GetHeight(); check(pix_siz); const iDib::pixel* buff = dib.GetPtr(); // Prepare BITMAPFILEHEADER BITMAPFILEHEADER bmfHeader; bmfHeader.bfType = ((WORD) ('M' << 8) | 'B'); bmfHeader.bfReserved1 = 0; bmfHeader.bfReserved2 = 0; bmfHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (dib.GetWidth() * dib.GetHeight() * 4); bmfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // Prepare BITMAPINFOHEADER BITMAPINFOHEADER bmihdr; bmihdr.biSize = sizeof(BITMAPINFOHEADER); bmihdr.biWidth = dib.GetWidth(); bmihdr.biHeight = -((sint32)dib.GetHeight()); bmihdr.biPlanes = 1; bmihdr.biBitCount = 32; bmihdr.biCompression = BI_RGB; bmihdr.biSizeImage = 0; bmihdr.biXPelsPerMeter = 600; bmihdr.biYPelsPerMeter = 600; bmihdr.biClrUsed = 0; bmihdr.biClrImportant = 0; pFile->Write(&bmfHeader,sizeof(BITMAPFILEHEADER)); pFile->Write(&bmihdr,sizeof(BITMAPINFOHEADER)); for (uint32 yy=0; yy<dib.GetHeight(); ++yy) { for (uint32 xx=0; xx<dib.GetWidth(); ++xx) { uint32 clr = ((*buff)>>11)<<19 | (((*buff)>>5) & 0x3f)<<10 | ((*buff)&0x1f)<<3; pFile->Write(&clr,sizeof(clr)); buff++; } } return true; } bool SaveDibBitmap16(const iDib& dib, const iStringT& fname) { iFilePtr pFile = CreateWin32File(fname); if (!pFile) return false; uint32 pix_siz = dib.GetWidth()*dib.GetHeight(); check(pix_siz); const iDib::pixel* buff = dib.GetPtr(); // Prepare BITMAPFILEHEADER BITMAPFILEHEADER bmfHeader; bmfHeader.bfType = ((WORD) ('M' << 8) | 'B'); bmfHeader.bfReserved1 = 0; bmfHeader.bfReserved2 = 0; bmfHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (dib.GetWidth() * dib.GetHeight() * 2); bmfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // Prepare BITMAPINFOHEADER BITMAPINFOHEADER bmihdr; bmihdr.biSize = sizeof(BITMAPINFOHEADER); bmihdr.biWidth = dib.GetWidth(); bmihdr.biHeight = -((sint32)dib.GetHeight()); bmihdr.biPlanes = 1; bmihdr.biBitCount = 16; bmihdr.biCompression = BI_RGB; bmihdr.biSizeImage = 0; bmihdr.biXPelsPerMeter = 600; bmihdr.biYPelsPerMeter = 600; bmihdr.biClrUsed = 0; bmihdr.biClrImportant = 0; pFile->Write(&bmfHeader,sizeof(BITMAPFILEHEADER)); pFile->Write(&bmihdr,sizeof(BITMAPINFOHEADER)); uint16* obuff = new uint16[dib.GetWidth()]; for (uint32 yy=0; yy<dib.GetHeight(); ++yy) { for (uint32 xx=0; xx<dib.GetWidth(); ++xx) { obuff[xx] = (*buff & 0x1F) | ((*buff & 0xFFC0)>>1); buff++; } pFile->Write(obuff,dib.GetWidth() * sizeof(uint16)); } delete[] obuff; return true; }
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 828 ] ] ]
c225946eaa38e5945170e1dc87c3607e9794e7d4
2431a77a6b3f005eacd7161170e185d7002492ee
/stdafx.h
cd8113a17b34cd67b201d1a1a7e96930fd13d6d7
[]
no_license
autch/kpinwa2.kpi
3ea46292dcd31c44461566f61e4f529ab074cfe8
e89b9b74df44eb0b018c9dab9f2572033b8f3c47
refs/heads/master
2016-09-10T12:00:12.854244
2010-12-16T05:07:01
2010-12-16T05:07:01
1,173,270
6
1
null
null
null
null
SHIFT_JIS
C++
false
false
602
h
// stdafx.h : 標準のシステム インクルード ファイルのインクルード ファイル、または // 参照回数が多く、かつあまり変更されない、プロジェクト専用のインクルード ファイル // を記述します。 // #pragma once #define WIN32_LEAN_AND_MEAN // Windows ヘッダーから使用されていない部分を除外します。 // Windows ヘッダー ファイル : #include <windows.h> // TODO: プログラムに必要な追加ヘッダーをここで参照してください。 #include <string> #include "kmp_pi.h"
[ "autch@88ae5fc5-0d13-0410-8ce9-a1c778df29b8" ]
[ [ [ 1, 17 ] ] ]
9377388294432bd5cb3b1f197b83b3f094097dd8
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Intersection/WmlIntrSph3Con3.cpp
b61f4c17aa5ae702b8b0f5bac9107cc3e0222c4a
[]
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
4,819
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 "WmlIntrSph3Con3.h" using namespace Wml; //---------------------------------------------------------------------------- template <class Real> bool Wml::TestIntersection (const Sphere3<Real>& rkSphere, const Cone3<Real>& rkCone) { // TO DO. Add these as members of Cone3 to avoid recomputing on each // intersection call. Real fInvSin = ((Real)1.0)/rkCone.SinAngle(); Real fCosSqr = rkCone.CosAngle()*rkCone.CosAngle(); Vector3<Real> kCmV = rkSphere.Center() - rkCone.Vertex(); Vector3<Real> kD = kCmV + (rkSphere.Radius()*fInvSin)*rkCone.Axis(); Real fDSqrLen = kD.SquaredLength(); Real fE = kD.Dot(rkCone.Axis()); if ( fE > (Real)0.0 && fE*fE >= fDSqrLen*fCosSqr ) { // TO DO. Add this as member of Cone3 to avoid recomputing on each // intersection call. Real fSinSqr = rkCone.SinAngle()*rkCone.SinAngle(); fDSqrLen = kCmV.SquaredLength(); fE = -kCmV.Dot(rkCone.Axis()); if ( fE > (Real)0.0 && fE*fE >= fDSqrLen*fSinSqr ) { // TO DO. Add this as member of Sphere to avoid recomputing on // each intersection call. (Useful for other functions using // squared radius.) Real fRSqr = rkSphere.Radius()*rkSphere.Radius(); return fDSqrLen <= fRSqr; } return true; } return false; } //---------------------------------------------------------------------------- template <class Real> bool Wml::FindIntersection (const Sphere3<Real>& rkSphere, const Cone3<Real>& rkCone, Vector3<Real>& rkClosest) { // test if cone vertex is in sphere Vector3<Real> kDiff = rkSphere.Center() - rkCone.Vertex(); Real fRSqr = rkSphere.Radius()*rkSphere.Radius(); Real fLSqr = kDiff.SquaredLength(); if ( fLSqr <= fRSqr) return true; // test if sphere center is in cone Real fDot = kDiff.Dot(rkCone.Axis()); Real fDotSqr = fDot*fDot; Real fCosSqr = rkCone.CosAngle()*rkCone.CosAngle(); if ( fDotSqr >= fLSqr*fCosSqr && fDot > (Real)0.0 ) { // sphere center is inside cone, so sphere and cone intersect return true; } // Sphere center is outside cone. Problem now reduces to looking for // an intersection between circle and ray in the plane containing // cone vertex and spanned by cone axis and vector from vertex to // sphere center. // Ray is t*D+V (t >= 0) where |D| = 1 and dot(A,D) = cos(angle). // Also, D = e*A+f*(C-V). Plugging ray equation into sphere equation // yields R^2 = |t*D+V-C|^2, so the quadratic for intersections is // t^2 - 2*dot(D,C-V)*t + |C-V|^2 - R^2 = 0. An intersection occurs // if and only if the discriminant is nonnegative. This test becomes // // dot(D,C-V)^2 >= dot(C-V,C-V) - R^2 // // Note that if the right-hand side is nonpositive, then the inequality // is true (the sphere contains V). I have already ruled this out in // the first block of code in this function. Real fULen = Math<Real>::Sqrt(Math<Real>::FAbs(fLSqr-fDotSqr)); Real fTest = rkCone.CosAngle()*fDot + rkCone.SinAngle()*fULen; Real fDiscr = fTest*fTest - fLSqr + fRSqr; // compute point of intersection closest to vertex V Real fT = fTest - Math<Real>::Sqrt(fDiscr); Vector3<Real> kB = kDiff - fDot*rkCone.Axis(); Real fTmp = rkCone.SinAngle()/fULen; rkClosest = fT*(rkCone.CosAngle()*rkCone.Axis() + fTmp*kB); return fDiscr >= (Real)0.0 && fTest >= (Real)0.0; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template WML_ITEM bool TestIntersection<float> (const Sphere3<float>&, const Cone3<float>&); template WML_ITEM bool FindIntersection<float> (const Sphere3<float>&, const Cone3<float>&, Vector3<float>&); template WML_ITEM bool TestIntersection<double> (const Sphere3<double>&, const Cone3<double>&); template WML_ITEM bool FindIntersection<double> (const Sphere3<double>&, const Cone3<double>&, Vector3<double>&); } //----------------------------------------------------------------------------
[ [ [ 1, 116 ] ] ]
ef8bc6f9a65a020d92762c838348d4e3aec5aa28
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/TO2PlayerStats.h
b5ef6529a0ab44fffe36b67f4dfe820b667fb02f
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
7,260
h
// ----------------------------------------------------------------------- // // // MODULE : TO2PlayerStats.h // // PURPOSE : Definition of PlayerStats class // // CREATED : 10/9/97 // // (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __TO2PLAYERSTATS_H #define __TO2PLAYERSTATS_H #include "ltbasedefs.h" #include "weaponmgr.h" #include "overlays.h" #include "IDList.h" #include "IntelItemList.h" #include "SkillsButeMgr.h" #include "PlayerStats.h" #include "SharedMission.h" class CTO2PlayerStats : public CPlayerStats { public: CTO2PlayerStats(); ~CTO2PlayerStats(); IDList* GetObjectives() { return &m_Objectives; } IDList* GetOptionalObjectives() { return &m_OptionalObjectives; } IDList* GetCompletedObjectives() { return &m_CompletedObjectives; } IDList* GetParameters() { return &m_Parameters; } IDList* GetKeys() { return &m_Keys; } CIntelItemList* GetIntelList() { return &m_IntelList; } LTBOOL Init(); void Term(); void Update(); void OnEnterWorld(LTBOOL bRestoringGame=LTFALSE); void OnExitWorld(); void UpdatePlayerWeapon(uint8 nWeaponId, uint8 nAmmoId, LTBOOL bForce=LTFALSE); void ResetStats(); void Clear(); void UpdateHealth(uint32 nHealth); void UpdateArmor(uint32 nArmor); void UpdateMaxHealth(uint32 nHealth); void UpdateMaxArmor(uint32 nArmor); void UpdateEnergy(uint32 nEnergy) {} void UpdateMaxEnergy(uint32 nEnergy) {} void UpdateProgress(uint32 nProgress) { m_dwProgress = (nProgress >= m_dwMaxProgress ? m_dwMaxProgress : nProgress); } void UpdateMaxProgress(uint32 nMaxProgress) { m_dwMaxProgress = nMaxProgress; } void UpdateAmmo(uint8 nWeaponId, uint8 nAmmoId, uint32 nAmmo, LTBOOL bPickedup=LTFALSE, LTBOOL bDisplayMsg=LTTRUE); void UpdateGear(uint8 nGearId); void UpdateMod(uint8 nModId); void UpdateAir(LTFLOAT nPercent); void UpdateObjectives(uint8 nThing, uint8 nType, uint32 dwId); void UpdateKeys(uint8 nType, uint16 dwId); void UpdateIntel(uint32 nTextId, uint8 nPopupId, LTBOOL bIsIntel); void UpdateHiding(LTBOOL bIsHiding, LTBOOL bIsHidden, LTBOOL bCantHide, float fHideDuration); void UpdateSkills(ILTMessage_Read *pMsg); void GainSkills(uint8 nRewardId, uint8 nBonusId, uint16 nAmount); void UpdateMissionStats(ILTMessage_Read *pMsg); void ResetSkills(); //clears all skill data void ResetObjectives(); //clears all objective data void ResetMissionStats(); void ResetInventory(); //clears all inventory data void DropInventory(LTBOOL bResetGear=LTTRUE); //drops are currently carried weapons and ammo // also drops gear and mods if bResetGear is set void OnObjectivesDataMessage(ILTMessage_Read *pMsg); void ClearMissionInfo(); int GetMissionDamage() {return m_nDamage;} void SetObjectivesSeen(); const MissionStats* GetMissionStats() const {return &m_MissionStats;} void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); uint8 GetCurWeapon() const { return m_nCurrentWeapon; } // [KLS - 02/13/02] Updated to support checking for mods on weapons other than // the current weapon... uint8 GetMod(ModType eType, const WEAPON* pW=LTNULL); inline uint8 GetSilencer(const WEAPON* pW=LTNULL) { return GetMod(SILENCER, pW); } inline uint8 GetScope(const WEAPON* pW=LTNULL) { return GetMod(SCOPE, pW); } inline LTBOOL CanBeSilenced() { return (GetSilencer() != WMGR_INVALID_ID); } inline LTBOOL CanHaveScope() { return (GetScope() != WMGR_INVALID_ID); } uint32 GetAmmoCount(uint8 nAmmoId) const; LTBOOL HaveWeapon(uint8 nWeaponId) const; LTBOOL HaveMod(uint8 nModId) const; LTBOOL HaveGear(uint8 nGearId) const; LTBOOL CanUseWeapon(uint8 nWeaponId) const; LTBOOL CanUseAmmo(uint8 nAmmoId) const; LTBOOL CanUseMod(uint8 nModId) const; LTBOOL CanUseGear(uint8 nGearId) const; void Setup( ); LTBOOL HaveAirSupply(); uint32 GetHealth() { return m_nHealth;} // current health uint32 GetMaxHealth() { return m_nMaxHealth;} // current maximum health uint32 GetArmor() { return m_nArmor;} // current armor uint32 GetMaxArmor() { return m_nMaxArmor;} // current maximum armor uint32 GetEnergy() { return 0; } uint32 GetMaxEnergy() { return 0; } LTFLOAT GetAirPercent() { return m_fAirPercent;} uint32 GetProgress() { return m_dwProgress; } uint32 GetMaxProgress(){ return m_dwMaxProgress; } uint8 GetCurrentWeapon() { return m_nCurrentWeapon;} // current weapon uint8 GetCurrentAmmo() { return m_nCurrentAmmo;} // current ammo uint32 GetCurrentAmmoCount(); LTBOOL IsHiding() {return m_bHiding;} LTBOOL IsHidden() {return m_bHidden;} LTBOOL CanHide() {return !m_bCantHide; } float GetHideDuration() { return m_fHideDuration; } uint32 GetTotalSkillPoints() {return m_nTotalSkillPoints;} uint32 GetAvailSkillPoints() {return m_nAvailSkillPoints;} uint8 GetSkillLevel(eSkill skill) {return m_nSkills[skill]; } const RANK* GetRank(); uint32 GetCostToUpgrade(eSkill skill); float GetSkillModifier(eSkill skl, uint8 nMod); protected: void AddCanUseWeapon(uint8 nWeaponId); void AddCanUseAmmo(uint8 nAmmoId); void AddCanUseMod(uint8 nModId); void AddCanUseGear(uint8 nGearId); protected: uint32 m_nHealth; // current health uint32 m_nArmor; // current armor uint32 m_nMaxHealth; // current maximum health uint32 m_nMaxArmor; // current maximum armor LTFLOAT m_fAirPercent; uint32* m_pnAmmo; // All ammo values LTBOOL* m_pbHaveAmmo; // ammos that player had during mission LTBOOL* m_pbHaveWeapon; // Weapon status uint8 m_nCurrentWeapon; // current weapon uint8 m_nCurrentAmmo; // current ammo LTBOOL* m_pbHaveMod; // Mod status LTBOOL* m_pbHaveGear; // Gear status uint32 m_nTotalSkillPoints; uint32 m_nAvailSkillPoints; uint8 m_nSkills[kNumSkills]; LTBOOL* m_pbCanUseAmmo; // Can we use this ammo LTBOOL* m_pbCanUseWeapon; // Can we carry this Weapon LTBOOL* m_pbCanUseMod; // Can we carry this Mod LTBOOL* m_pbCanUseGear; // Can we carry this Gear int m_nDamage; // Damage taken during this mission LTBOOL m_bHidden; //player is hidden LTBOOL m_bHiding; //player is trying to hide LTBOOL m_bCantHide; //player is unable to hide float m_fHideDuration; // how long it takes player to become hidden IDList m_Objectives; IDList m_OptionalObjectives; IDList m_CompletedObjectives; IDList m_Parameters; IDList m_Keys; CIntelItemList m_IntelList; LTBOOL m_bObjAdded; LTBOOL m_bObjRemoved; LTBOOL m_bObjCompleted; MissionStats m_MissionStats; uint32 m_dwProgress; uint32 m_dwMaxProgress; }; #endif // __TO2PLAYERSTATS_H
[ [ [ 1, 208 ] ] ]
daf4c248f8b488cc8be8e6604139f8ef489d1436
138a353006eb1376668037fcdfbafc05450aa413
/source/ArenaLevel.h
2e7131241db7414b6010df7450408d94b4e6c897
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,789
h
#ifndef ARENALEVEL_H #define ARENALEVEL_H #include <Ogre.h> #include <OgreNewt.h> #include "Level.h" class GameServices; class InputManager; class PlayerEntity; class ModelEntity; class CollisionManager; class GameEvent; class TriggerEntity; class RigidModelEntity; class CollisionHandler; class LevelParser; class PlatformCamera; class OneTimeTrigger; class MovingBlock; class EnemyManager; class ArenaCamera; class ArenaLevel : public Level { public: ArenaLevel(GameServices *gs, const Ogre::String &filePath, const Ogre::String &name); ~ArenaLevel(); LevelState update(); void loadLevel(); void unloadLevel(); void getPlayers(PlayerEntity* p1, PlayerEntity* p2){p1 = mPlayer1; p2 = mPlayer2;} protected: void initModels(); void initCamera(); void initLighting(); void initScene(); void addEntity( ModelEntity *entity, bool needUpdate); int removeEntity( ModelEntity *entity, bool needUpdate ); std::map<std::string,ModelEntity*> mStaticEnts; //hold all entities in the level std::list<ModelEntity*> mDynamicEnts; //hold only entities that get updated GameServices *mGameServices; InputManager *mInputManager; Ogre::SceneManager *mSceneMgr; CollisionManager *mCollisionMgr; Ogre::String mFilePath; Ogre::String mName; Ogre::SceneNode *mRootNode; Ogre::SceneNode *mLevelObjectsNode; Ogre::SceneNode *mPlayersNode; PlayerEntity *mPlayer1; PlayerEntity *mPlayer2; ModelEntity *mArena; Ogre::Camera *mCam; Ogre::SceneNode *mCamNode; //Newton physics world OgreNewt::World *mCollisionWorld; OgreNewt::BasicFrameListener *mNewtonListener; //Newton Materials OgreNewt::MaterialPair *mMaterialPair; CollisionHandler *mCollisionCallback; ArenaCamera *mFollowCam; }; #endif
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 74 ] ] ]
2bd9f0935501f575d3817d1f320685f1a4fef018
34afed2cb0f90f863c864c872ce1195ac2979d70
/test.cpp
eb3f5a628cf7cb086db624e65aa0a065847b5085
[]
no_license
hex108/regexp
51d222e822edee5e2b5e38226d148d6166771b7e
4e8fbba1ef7a61c5b4af447e926fd01f2820b8db
refs/heads/master
2020-05-29T17:01:47.021704
2010-06-18T12:57:00
2010-06-18T12:57:00
33,920,525
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include <iostream> #include <string> #include "regexp.h" using namespace std; int main() { string str; //while(1){ // cin >> str; bool ret; ret = reg_exp_match( "aaabbctd","(a|b)*abb" ); if( ret ) cout << "matched" << endl; else cout << "unmatched" << endl; ret = reg_exp_match( "aaabbctd","a*c" ); if( ret ) cout << "matched" << endl; else cout << "unmatched" << endl; //} //system("pause"); return 0; }
[ "heixia108@0f5113ed-b8ba-8753-5270-db2f1710a095" ]
[ [ [ 1, 31 ] ] ]
060dc208a6b7becf86eee31a4f1c5703bf10a52f
8fa4334746f35b9103750bb23ec2b8d38e93cbe9
/coding/qt/forum/forum/japplication.cpp
3e30b7a8ff4b77348bdb1fafb8ce6ee78fe167a1
[]
no_license
zhzengj/testrepo
620b22b2cf1e8ff10274a9d0c6491816cecaec3b
daf8bd55fd347220f07bfd7d15b02b01a516479b
refs/heads/master
2016-09-11T00:50:57.846600
2011-10-16T07:59:48
2011-10-16T07:59:48
2,365,453
0
0
null
null
null
null
GB18030
C++
false
false
2,042
cpp
/******************************************************************** created: 12:6:2011 22:46 file base: japplication.cpp author: zhzengj *********************************************************************/ #include "stdafx.h" #include "japplication.h" #include "accountsvr.h" JApplication::JApplication(int &argc, char **argv) :QApplication(argc, argv) { QTextCodec *codec = QTextCodec::codecForName("GB2312"); QTextCodec::setCodecForCStrings(codec); m_pAccountSrv = new JAccountSvr(this); } void JApplication::loadInfo(const QString & file) { m_vtImport.clear(); QDomDocument doc; if (!ZJ::openXml(doc, applicationDirPath() + "/" + file)) { QString str = "加载配置文件 " + applicationDirPath() + "/" + file + " 失败!"; QMessageBox::critical(NULL, "错误", str); ::exit(-1); } QDomElement root = doc.documentElement(); QDomElement e = root.firstChildElement("import"); for (; !e.isNull(); e = e.nextSiblingElement()) { if (e.hasAttribute("id") && e.hasAttribute("file")) m_vtImport.push_back(QPair<QString, QString>(e.attribute("id"), applicationDirPath() + "/" + e.attribute("file"))); } loadInfo(); } void JApplication::loadInfo() { try { //load xml m_pAccountSrv->loadInfo(getFileById(QString::fromUtf16(ZJ::XmlAccountId))); } catch (QString err) { qCritical() << "loadInfo error : " << err << endl; } catch (...) { qCritical() << "loadInfo error\n"; } } void JApplication::saveInfo() { QStringList lst = getFileById(QString::fromUtf16(ZJ::XmlAccountId)); if (!lst.isEmpty()) m_pAccountSrv->SaveInfo(lst[0]); } QStringList JApplication::getFileById(const QString & id) const {//加载时,一个id可以有多个xml,但保存时,仅有一个。。 QStringList strList; for (int i = 0; i < m_vtImport.count(); ++i) { if (m_vtImport[i].first == id) strList << m_vtImport[i].second; } return strList; } JAccountSvr * JApplication::accountSvr() { return m_pAccountSrv; }
[ [ [ 1, 79 ] ] ]
0f5ff26eb17e19a7803fa0aeb3779b854ecec401
61e4e71a9ad4ac3fdce3c1595c627b9c79a68c29
/src/ui/LViewSubCategory.h
8ff2a45ba7f1901e4a12d6708e1c6800176ebacd
[]
no_license
oot/signpost
c2ff81bdb3ab75a5511eedd18798d637cd080526
8a8e5c6c693217daf56398e6bb59f89563f9689b
refs/heads/master
2016-09-05T19:52:41.876837
2010-11-19T08:07:48
2010-11-19T08:07:48
32,301,199
0
0
null
null
null
null
UTF-8
C++
false
false
164
h
#pragma once #include <gtkmm.h> class LViewSubCategory : public Gtk::ListViewText { public: LViewSubCategory(void); ~LViewSubCategory(void); };
[ "[email protected]@067241ac-f43e-11dd-9d1a-b59b2e1864b6" ]
[ [ [ 1, 13 ] ] ]
28e3e3d0698b5baba83ed7d5e85a56e9c247bc0c
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/framework/src/nlevel/nlevel_cmds.cc
43964bcc1daedef2029a409f2837964fd13ac2aa
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,610
cc
#include "precompiled/pchframework.h" //------------------------------------------------------------------------------ // nlevel_cmds.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "nlevel/nlevel.h" #include "kernel/npersistserver.h" #include "entity/nentityobjectserver.h" #include "nspatial/nspatialserver.h" #include "nspatial/ncspatialquadtree.h" #include "nspatial/ncspatialindoor.h" #ifndef NGAME #include "nlayermanager/nlayermanager.h" #endif NSCRIPT_INITCMDS_BEGIN(nLevel) NSCRIPT_ADDCMD('SSPE', void, SetSpaceEntity, 1, (nEntityObjectId), 0, ()); NSCRIPT_ADDCMD('SGLE', void, SetGlobalEntity, 1, (nEntityObjectId), 0, ()); NSCRIPT_ADDCMD('ISGE', bool, IsGlobalEntity, 1, (nEntityObjectId), 0, ()); NSCRIPT_ADDCMD('SENN', void, SetEntityName, 2, (nEntityObjectId, const char *), 0, ()); NSCRIPT_ADDCMD('GENN', const char *, GetEntityName, 1, (nEntityObjectId), 0, ()); NSCRIPT_ADDCMD('FINE', nEntityObjectId, FindEntity, 1, (const char *), 0, ()); NSCRIPT_ADDCMD('RENN', void, RemoveEntityName, 1, (const char *), 0, ()); NSCRIPT_ADDCMD('APEN', void, AddEntity, 1, (nObject*), 0, ()); NSCRIPT_ADDCMD('SWZK', void, SetWizardKey, 1, (int), 0, ()); NSCRIPT_ADDCMD('AELY', void, AddEntityLayer, 4, (int, const char *, bool, const char *), 0, ()); #ifndef NGAME NSCRIPT_ADDCMD('GELM', nRoot*, GetEntityLayerManager, 0, (), 0, ()); #endif NGAME NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ /** */ int __cdecl nLevel::EntityIdSorter(const void* elm0, const void* elm1) { nEntityObjectId i0 = *(nEntityObjectId*)elm0; nEntityObjectId i1 = *(nEntityObjectId*)elm1; if (i0 < i1) { return -1; } else if (i0 > i1) { return 1; } else { return 0; } } //------------------------------------------------------------------------------ /** */ int __cdecl nLevel::EntityNameSorter(const void* elm0, const void* elm1) { EntityNameNode* node0 = *(EntityNameNode**)elm0; EntityNameNode* node1 = *(EntityNameNode**)elm1; if (node0->entityId < node1->entityId) { return -1; } else if (node0->entityId > node1->entityId) { return 1; } else { return 0; } } #ifndef NGAME //------------------------------------------------------------------------------ /** */ int __cdecl nLevel::EntityLayerSorter(const void* elm0, const void* elm1) { nLayer* layer0 = *(nLayer**)elm0; nLayer* layer1 = *(nLayer**)elm1; if (layer0->GetLayerKey() < layer1->GetLayerKey()) { return -1; } else if (layer0->GetLayerKey() > layer1->GetLayerKey()) { return 1; } else { return 0; } } #endif //------------------------------------------------------------------------------ /** */ void nLevel::SortKeyGroup(KeyGroup& keyGroup) { // sort globals by entity id qsort(keyGroup.keyGlobals.Begin(), keyGroup.keyGlobals.Size(), sizeof(nEntityObjectId), EntityIdSorter); // sort spaces by entity id qsort(keyGroup.keySpaces.Begin(), keyGroup.keySpaces.Size(), sizeof(nEntityObjectId), EntityIdSorter); // sort names by entity id qsort(keyGroup.keyNames.Begin(), keyGroup.keyNames.Size(), sizeof(EntityNameNode*), EntityNameSorter); #ifndef NGAME // sort layer by wizard id qsort(keyGroup.keyLayers.Begin(), keyGroup.keyLayers.Size(), sizeof(nLayer*), EntityLayerSorter); #endif } //------------------------------------------------------------------------------ /** */ bool nLevel::SaveCmds(nPersistServer *ps) { if (nRoot::SaveCmds(ps)) { nArray<KeyGroup> keyGroups; keyGroups.SetFixedSize(0x100); // persist all space entities currently in the spatial server // (their names should have been added to the level explicitly) nArray<nEntityObject*> objects; nSpatialServer *spatialServer = nSpatialServer::Instance(); if (spatialServer->HasQuadtreeSpace()) { nEntityObjectId entityId = spatialServer->GetOutdoorEntity()->GetId(); int index = (entityId & nEntityObjectServer::IDHIGHMASK) >> nEntityObjectServer::IDLOWBITS; keyGroups[index].keySpaces.Append(entityId); } nArray<ncSpatialIndoor*>& indoors = spatialServer->GetIndoorSpaces(); for (int i = 0; i < indoors.Size(); ++i) { nEntityObjectId entityId = indoors[i]->GetEntityObject()->GetId(); int index = (entityId & nEntityObjectServer::IDHIGHMASK) >> nEntityObjectServer::IDLOWBITS; keyGroups[index].keySpaces.Append(entityId); } // persist global entities using wizards nArray<nEntityObject*> globals; nSpatialServer::Instance()->GetCommonGlobalEntities(globals); for (int i = 0; i < globals.Size(); ++i) { // persist only user-created global entities (eg. not cameras) if (globals.At(i)->GetEntityClass()->IsUserCreated() && nEntityObjectServer::Instance()->GetEntityObjectType(globals.At(i)->GetId()) == nEntityObjectServer::Normal) { nEntityObjectId entityId = globals.At(i)->GetId(); int index = (entityId & nEntityObjectServer::IDHIGHMASK) >> nEntityObjectServer::IDLOWBITS; keyGroups[index].keyGlobals.Append(entityId); } } // group entity names by wizard id EntityNameNode* curNode; for (curNode = (EntityNameNode*) this->entityNameList.GetHead(); curNode; curNode = (EntityNameNode*) curNode->GetSucc()) { int index = (curNode->entityId & nEntityObjectServer::IDHIGHMASK) >> nEntityObjectServer::IDLOWBITS; // avoid persisting local entities! if (index > 0) { keyGroups[index].keyNames.Append(curNode); } } #ifndef NGAME // group entity layers by wizard id int numLayers = this->refEntityLayerManager->GetNumLayers(); for (int i = 0; i < numLayers; ++i) { int layerKey; nLayer *curLayer = this->refEntityLayerManager->GetLayerAt(i); if (curLayer->GetLayerKey() == -1) { layerKey = nEntityObjectServer::Instance()->GetHighId(); } else { layerKey = curLayer->GetLayerKey(); } int index = (layerKey & nEntityObjectServer::IDHIGHMASK) >> nEntityObjectServer::IDLOWBITS; keyGroups[index].keyLayers.Append(curLayer); } #endif // persist globals, entities and layers using wizards for (int i = 0; i < keyGroups.Size(); ++i) { // sort keys, to keep same persistence order this->SortKeyGroup(keyGroups[i]); #ifndef NGAME // --- setwizardkey --- ps->Put(this, 'SWZK', (i << nEntityObjectServer::IDLOWBITS)); #endif int j; for (j = 0; j < keyGroups[i].keyGlobals.Size() ; ++j) { // --- addglobalentity --- nEntityObjectId entityId = keyGroups[i].keyGlobals[j]; ps->Put(this, 'SGLE', entityId); } for (j = 0; j < keyGroups[i].keySpaces.Size() ; ++j) { // --- setspaceentity --- nEntityObjectId entityId = keyGroups[i].keySpaces[j]; ps->Put(this, 'SSPE', entityId); } for (j = 0; j < keyGroups[i].keyNames.Size() ; ++j) { // --- setentityname --- EntityNameNode* curNode = keyGroups[i].keyNames[j]; ps->Put(this, 'SENN', curNode->entityId, curNode->GetName()); } #ifndef NGAME for (j = 0; j < keyGroups[i].keyLayers.Size() ; ++j) { // --- addentitylayer --- nLayer *curLayer = keyGroups[i].keyLayers[j]; ps->Put(this, 'AELY', curLayer->GetId(), curLayer->GetLayerName(), curLayer->IsLocked(), curLayer->GetPassword() ); } #endif } return true; } return false; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 252 ] ] ]
8721681274faae88a2702f5c67369f6c152b4e4c
5d8070c3ad1d3ef09cc350f210fcd5be994171b9
/include/ship.h
ec72f219c3c7e94d24c98e58c057b53fd49d45d3
[]
no_license
python50/Space-Shooter-Demo
08a5db204dd1db99ccf6c9d4c1a924e5caaa285d
77715e7837fb2c485dee226a9e74f57de13a9675
refs/heads/master
2021-01-01T15:24:58.884177
2011-09-19T10:58:42
2011-09-19T10:58:42
2,037,477
1
0
null
null
null
null
UTF-8
C++
false
false
1,364
h
/** ** Code Copyright (C) 2011 Jason White <[email protected]> ** White Waters Software - wwsoft.co.cc ** ** Copying and distributing this source is prohibited without ** explicit authorization by the copyright holder: Jason White **/ #ifndef SHIP_H #define SHIP_H #include "SDL.h" #include "SDL_mixer.h" #include "SDL_image.h" #include "SDL_ttf.h" #include "SDL_net.h" #include "game_engine.h" #include "error.h" #include <vector> #include <SDL.h> class ship : public controller { public: ship(game_engine * gm_engine,float x, float y); void init(); void reset(); virtual void call(std::string item, void * value_1, void * value_2); virtual void get(std::string item, void * return_value); virtual void set(std::string item, void * value); void update(); void physics(); virtual ~ship(); protected: private: float x; float y; float direction; float image_angle; float speed; float friction; float image_offset; float start_x; float start_y; float start_direction; std::vector<SDL_Surface *> sprites; game_engine * gm_engine; int shot_counter; int reset_counter; bool god; }; #endif // SHIP_H
[ "jason@jason-master-desktop.(none)", "[email protected]" ]
[ [ [ 1, 26 ], [ 33, 44 ], [ 48, 49 ], [ 53, 55 ] ], [ [ 27, 32 ], [ 45, 47 ], [ 50, 52 ] ] ]
f249a95e6dd255eda46cce24c6105b5a7558ac43
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/v104/ok/10482/c.cpp
f6f3cbbce63bd6d6493697eca8e3d3b42ab9545a
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
#include <iostream> using namespace std; int inst= 0; int n,c[40]; #define MM (650) char mat[MM+100][MM+100]; int diff(int a,int b,int c) { int maior, menor; if(a>b && a>c) maior = a; else maior = (b>c) ? b : c; if(a<b && a<c) menor = a; else menor = (b<c) ? b : c; return maior-menor; } int bad,tot; void st() { bad = 0; cin >> n; int i,j,k,v; int m1=0,m2=0; for(i=0;i!=n;i++) { cin >> c[i]; bad += c[i]; } tot = bad; for(i=0;i!=MM;i++) for(j=0;j!=MM;j++) mat[i][j]=0; mat[0][0]=1; for(i=0;i!=n;i++) { v = c[i]; for(j=m1;j>=0;j--) { for(k=m2;k>=0;k--) { if(mat[j][k]) { // coloca em um ou no outro mat[j+v][k] = mat[j][k+v] = 1; if(j+v>m1 && j+v<=MM) m1 = j+v; if(k+v>m2 && k+v<=MM) m2 = k+v; } } } } int dif; for(j=m1;j>=0;j--) { for(k=m2;k>=0;k--) { if(mat[j][k]) { dif = diff(j,k,tot-j-k); if(dif<bad) bad = dif; } } } cout << "Case " << ++inst << ": " << bad << endl; } int main() { int t; cin >> t; while(t--) st(); return 0; }
[ [ [ 1, 72 ] ] ]
d2df112695e8f3439a80e7ce1912e92bbd2c207b
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/com/XMLDOMElement.cpp
0f2975042cf84a278dda0e80d6506511f565ccd6
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
6,857
cpp
/* * Copyright 1999-2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XMLDOMElement.cpp,v 1.3 2004/09/08 13:55:35 peiyongz Exp $ */ #include "stdafx.h" #include "xml4com.h" #include "XMLDOMElement.h" #include "XMLDOMAttribute.h" #include "XMLDOMNodeList.h" // IXMLDOMElement methods STDMETHODIMP CXMLDOMElement::get_tagName(BSTR *pVal) { ATLTRACE(_T("CXMLDOMElement::get_tagName\n")); if (NULL == pVal) return E_POINTER; *pVal = NULL; try { *pVal = SysAllocString(element->getTagName()); } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return S_OK; } STDMETHODIMP CXMLDOMElement::getAttribute(BSTR name, VARIANT *pVal) { ATLTRACE(_T("CXMLDOMElement::getAttribute\n")); if (NULL == pVal) return E_POINTER; ::VariantInit(pVal); V_VT(pVal) = VT_EMPTY; try { V_VT(pVal) = VT_BSTR; V_BSTR(pVal) = SysAllocString(element->getAttribute(name)); } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return S_OK; } STDMETHODIMP CXMLDOMElement::setAttribute(BSTR name, VARIANT value) { ATLTRACE(_T("CXMLDOMElement::setAttribute\n")); try { if (V_VT(&value) == VT_BSTR) { element->setAttribute(name, value.bstrVal); } else { element->setAttribute(name,(BSTR) (_bstr_t) value); } } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return S_OK; } STDMETHODIMP CXMLDOMElement::removeAttribute(BSTR name) { ATLTRACE(_T("CXMLDOMElement::removeAttribute\n")); try { element->removeAttribute(name); } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return S_OK; } STDMETHODIMP CXMLDOMElement::getAttributeNode(BSTR name, IXMLDOMAttribute **attr) { ATLTRACE(_T("CXMLDOMElement::getAttributeNode\n")); if (NULL == attr) return E_POINTER; *attr = NULL; DOMAttr* attrNode=element->getAttributeNode(name); if(attrNode==NULL) return S_OK; CXMLDOMAttributeObj *pObj = NULL; HRESULT hr = CXMLDOMAttributeObj::CreateInstance(&pObj); if (S_OK != hr) return hr; pObj->AddRef(); pObj->SetOwnerDoc(m_pIXMLDOMDocument); try { pObj->attr = attrNode; } catch(DOMException& ex) { pObj->Release(); return MakeHRESULT(ex); } catch(...) { pObj->Release(); return E_FAIL; } hr = pObj->QueryInterface(IID_IXMLDOMAttribute, reinterpret_cast<LPVOID*> (attr)); if (S_OK != hr) *attr = NULL; pObj->Release(); return hr; } STDMETHODIMP CXMLDOMElement::setAttributeNode(IXMLDOMAttribute *attr, IXMLDOMAttribute **attributeNode) { ATLTRACE(_T("CXMLDOMElement::setAttributeNode\n")); if (NULL == attr || NULL == attributeNode) return E_POINTER; *attributeNode = NULL; DOMAttr* newAttr = NULL; IIBMXMLDOMNodeIdentity* nodeID = NULL; HRESULT sc = attr->QueryInterface(IID_IIBMXMLDOMNodeIdentity,(void**) &nodeID); if(SUCCEEDED(sc)) { long id = 0; sc = nodeID->get_NodeId(&id); nodeID->Release(); if(SUCCEEDED(sc)) { // // any subsequent failure will be reported as an invalid arg // sc = E_INVALIDARG; try { DOMNode* newNode = (DOMNode*) id; if(newNode->getNodeType() == DOMNode::ATTRIBUTE_NODE) { newAttr = (DOMAttr*) newNode; } } catch(...) { } } } // // if we couldn't extract an attribute out of the // argument, then return with a failure code if(newAttr == NULL) return sc; sc = S_OK; try { DOMAttr* oldAttr = element->setAttributeNode(newAttr); if(oldAttr!=NULL) { CXMLDOMAttributeObj *pObj = NULL; sc = CXMLDOMAttributeObj::CreateInstance(&pObj); if (SUCCEEDED(sc)) { pObj->attr = oldAttr; pObj->AddRef(); pObj->SetOwnerDoc(m_pIXMLDOMDocument); sc = pObj->QueryInterface(IID_IXMLDOMAttribute, reinterpret_cast<LPVOID*> (attributeNode)); pObj->Release(); } } } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return sc; } STDMETHODIMP CXMLDOMElement::removeAttributeNode(IXMLDOMAttribute *attr, IXMLDOMAttribute * *attributeNode) { ATLTRACE(_T("CXMLDOMElement::removeAttributeNode\n")); if (NULL == attr || NULL == attributeNode) return E_POINTER; *attributeNode = NULL; CXMLDOMAttributeObj *pObj = NULL; HRESULT hr = CXMLDOMAttributeObj::CreateInstance(&pObj); if (S_OK != hr) return hr; pObj->AddRef(); pObj->SetOwnerDoc(m_pIXMLDOMDocument); try { long id = 0; IIBMXMLDOMNodeIdentity* nodeID = NULL; if(SUCCEEDED(attr->QueryInterface(IID_IIBMXMLDOMNodeIdentity,(void**) &nodeID))) { nodeID->get_NodeId(&id); nodeID->Release(); } pObj->attr = element->removeAttributeNode((DOMAttr*) id); } catch(DOMException& ex) { pObj->Release(); return MakeHRESULT(ex); } catch(...) { pObj->Release(); return E_FAIL; } hr = pObj->QueryInterface(IID_IXMLDOMAttribute, reinterpret_cast<LPVOID*> (attributeNode)); if (S_OK != hr) *attributeNode = NULL; pObj->Release(); return hr; } STDMETHODIMP CXMLDOMElement::getElementsByTagName(BSTR tagName, IXMLDOMNodeList **pVal) { ATLTRACE(_T("CXMLDOMElement::getElementsByTagName\n")); if (NULL == pVal) return E_POINTER; *pVal = NULL; CXMLDOMNodeListObj *pObj = NULL; HRESULT hr = CXMLDOMNodeListObj::CreateInstance(&pObj); if (S_OK != hr) return hr; pObj->AddRef(); pObj->SetOwnerDoc(m_pIXMLDOMDocument); try { pObj->m_container = element->getElementsByTagName(tagName); } catch(DOMException& ex) { pObj->Release(); return MakeHRESULT(ex); } catch(...) { pObj->Release(); return E_FAIL; } hr = pObj->QueryInterface(IID_IXMLDOMNodeList, reinterpret_cast<LPVOID*> (pVal)); if (S_OK != hr) *pVal = NULL; pObj->Release(); return hr; } STDMETHODIMP CXMLDOMElement::normalize(void) { ATLTRACE(_T("CXMLDOMElement::normalize\n")); try { element->normalize(); } catch(DOMException& ex) { return MakeHRESULT(ex); } catch(...) { return E_FAIL; } return S_OK; }
[ [ [ 1, 340 ] ] ]
fef599e30106e92509758f912a2cd9a92401d670
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/MyGUIEngine/src/MyGUI_ControllerManager.cpp
959f71a215c20a683ba42b279e5e493a70ea0198
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,041
cpp
/*! @file @author Albert Semenov @date 01/2008 @module */ #include "MyGUI_Gui.h" #include "MyGUI_ControllerManager.h" #include "MyGUI_WidgetManager.h" #include "MyGUI_Common.h" namespace MyGUI { INSTANCE_IMPLEMENT(ControllerManager); void ControllerManager::initialise() { MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice"); MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME); WidgetManager::getInstance().registerUnlinker(this); MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized"); mIsInitialise = true; } void ControllerManager::shutdown() { if (false == mIsInitialise) return; MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME); WidgetManager::getInstance().unregisterUnlinker(this); clear(); MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown"); mIsInitialise = false; } void ControllerManager::clear() { for (ListControllerItem::iterator iter=mListItem.begin(); iter!=mListItem.end(); ++iter) { delete (*iter).second; } mListItem.clear(); } void ControllerManager::addItem(WidgetPtr _widget, ControllerItem * _item) { // если виджет первый, то подписываемся на кадры if (0 == mListItem.size()) Gui::getInstance().addFrameListener(this); // подготавливаем _item->prepareItem(_widget); for (ListControllerItem::iterator iter=mListItem.begin(); iter!=mListItem.end(); ++iter) { // такой уже в списке есть if ((*iter).first == _widget) { if ((*iter).second->getType() == _item->getType()) { (*iter).second->replaseItem((*iter).first, _item); delete _item; return; } } } // вставляем в самый конец mListItem.push_back(PairControllerItem(_widget, _item)); } void ControllerManager::removeItem(WidgetPtr _widget) { // не удаляем из списка, а обнуляем, в цикле он будет удален for (ListControllerItem::iterator iter=mListItem.begin(); iter!=mListItem.end(); ++iter) { if ((*iter).first == _widget) (*iter).first = null; } } void ControllerManager::_unlinkWidget(WidgetPtr _widget) { removeItem(_widget); } void ControllerManager::_frameEntered(float _time) { for (ListControllerItem::iterator iter=mListItem.begin(); iter!=mListItem.end(); /*added in body*/) { if (null == (*iter).first) { delete (*iter).second; // удаляем из списка, итератор не увеличиваем и на новый круг iter = mListItem.erase(iter); continue; } if ((*iter).second->addTime((*iter).first, _time)) { ++iter; continue; } // на следующей итерации виджет вылетит из списка (*iter).first = null; } if (0 == mListItem.size()) Gui::getInstance().removeFrameListener(this); } } // namespace MyGUI
[ [ [ 1, 6 ], [ 8, 9 ], [ 11, 18 ], [ 20, 108 ] ], [ [ 7, 7 ], [ 10, 10 ], [ 19, 19 ] ] ]
a9742e18ff4b722a35908917249bcf0e5484cc5c
bd8d12db21c3533bb082c15e973119aeeaeedc84
/MathProblems.h
0ad97d1ea6c341def19a39da9d6451860b09e001
[]
no_license
jbreslin33/visomathtxtgame
0280cf7a045bb8df82c80beddba985e3128b9e7d
7ab2a608e91468603b2900e7a213b61df1ba2e49
refs/heads/master
2016-08-07T22:31:23.238476
2010-10-10T00:33:51
2010-10-10T00:33:51
37,391,318
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
/* * MathProblems.h * * Author: Jim Breslin * Email: [email protected] * Website: http://www.roacheopen.com */ #ifndef MATHPROBLEMS_H_ #define MATHPROBLEMS_H_ #include <vector> #include <string> class MathProblems { public: MathProblems(); ~MathProblems(); std::string getWelcomeString(); std::vector<int> mVectorOfInts; std::string welcomeString; }; #endif
[ "jbreslin33@localhost" ]
[ [ [ 1, 28 ] ] ]
b96b61d029b85043c07bbd12c3e4f49740cabb97
a230afa027a8a672c3d3581df13439127c795a55
/Rendrer/Physics/Helpers/cooking.h
5bb8717d4ab80c13845b5498da5693f4248c98a4
[]
no_license
ASDen/CGsp
fbecb2463d975412f85fa343e87fda9707b7801a
2657b72269566c59cc0127239e3827f359197f9e
refs/heads/master
2021-01-25T12:02:10.331018
2010-09-22T12:43:19
2010-09-22T12:43:19
503,933
1
0
null
null
null
null
UTF-8
C++
false
false
886
h
#ifndef COOKING_H #define COOKING_H #include "NxCooking.h" class NxPMap; class NxTriangleMesh; class NxUserOutputStream; //#pragma message(CGSP_CC) CGSP_CC bool hasCookingLibrary(); // check to see if the cooking library is available or not! CGSP_CC bool InitCooking(NxUserAllocator* allocator = NULL, NxUserOutputStream* outputStream = NULL); CGSP_CC void CloseCooking(); CGSP_CC bool CookConvexMesh(const NxConvexMeshDesc& desc, NxStream& stream); CGSP_CC bool CookClothMesh(const NxClothMeshDesc& desc, NxStream& stream); CGSP_CC bool CookTriangleMesh(const NxTriangleMeshDesc& desc, NxStream& stream); CGSP_CC bool CookSoftBodyMesh(const NxSoftBodyMeshDesc& desc, NxStream& stream); CGSP_CC bool CreatePMap(NxPMap& pmap, const NxTriangleMesh& mesh, NxU32 density, NxUserOutputStream* outputStream = NULL); CGSP_CC bool ReleasePMap(NxPMap& pmap); #endif
[ [ [ 1, 23 ] ] ]
42b43beb8687db6e339ec44232731811392b4e5c
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
/itl/libs/itl_xt/example/toytime.h
2c8f6820944a4584ef37f01bc600bae08a13518f
[ "BSL-1.0" ]
permissive
WolfgangSt/itl
e43ed68933f554c952ddfadefef0e466612f542c
6609324171a96565cabcf755154ed81943f07d36
refs/heads/master
2016-09-05T20:35:36.628316
2008-11-04T11:44:44
2008-11-04T11:44:44
327,076
0
1
null
null
null
null
UTF-8
C++
false
false
3,360
h
/*----------------------------------------------------------------------------+ Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin +-----------------------------------------------------------------------------+ Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +----------------------------------------------------------------------------*/ namespace boost{namespace itl { /** Time is a toy-class to demonstrate a class that conforms the requirements of a template parameter for class IntervalT. In real world applications you may want to use the integer representation of a time variable. That way intervals and their containers are working most efficiently. */ enum {sunday=0, monday, tuesday, wednesday, thursday, friday, saturday}; static const char* daynames[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}; class Time { public: Time(): m_time(0) {} Time(int hours, int minutes): m_time(60*hours+minutes) {} Time(int day, int hours, int minutes): m_time((24*60)*day+60*hours+minutes) {} int getDay()const { return m_time/(24*60); } int getHours()const { return (m_time%(24*60))/60; } int getMinutes()const { return (m_time%(24*60))%60; } int asInt()const { return m_time; } std::string getDayString()const { return daynames[getDay()]; } std::string as_string()const { const int MAX_TIMESTING_LEN = 256; char repr[MAX_TIMESTING_LEN]; sprintf(repr, "%3s:%02d:%02d", getDayString().c_str(), getHours(), getMinutes()); return std::string(repr); } Time& operator ++ () { m_time++; return *this; } Time& operator -- () { m_time--; return *this; } private: int m_time; }; bool operator < (const Time& x1, const Time& x2) { return x1.asInt() < x2.asInt(); } bool operator == (const Time& x1, const Time& x2) { return x1.asInt() == x2.asInt(); } bool operator <= (const Time& x1, const Time& x2) { return x1.asInt() <= x2.asInt(); } }} // namespace itl boost
[ "jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a" ]
[ [ [ 1, 75 ] ] ]
6e5d9e5be8fe2f41c4b22607f3240a59d5bc7b54
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/072.cpp
b0e989d20011c650fcd6f326542901d92584788e
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
///////////////////////////////////////////////////////////////////// // Mapper 72 (Created by rinao) void NES_mapper72_Init() { g_NESmapper.Reset = NES_mapper72_Reset; g_NESmapper.MemoryWrite = NES_mapper72_MemoryWrite; } void NES_mapper72_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } } void NES_mapper72_MemoryWrite(uint32 addr, uint8 data) { uint8 bank = data & 0x0f; if (data & 0x80) { g_NESmapper.set_CPU_banks4(bank*2, bank*2+1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } if (data & 0x40) { g_NESmapper.set_PPU_banks8(bank*8, bank*8+1,bank*8+2,bank*8+3,bank*8+4,bank*8+5,bank*8+6,bank*8+7); } } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 35 ] ] ]
e15d519547113577a9e4a1d93992e7923853d0d7
e07af5d5401cec17dc0bbf6dea61f6c048f07787
/field.cpp
efc1b63cbddb42c3d1df9c34199a097c814b14de
[]
no_license
Mosesofmason/nineo
4189c378026f46441498a021d8571f75579ce55e
c7f774d83a7a1f59fde1ac089fde9aa0b0182d83
refs/heads/master
2016-08-04T16:33:00.101017
2009-12-26T15:25:54
2009-12-26T15:25:54
32,200,899
0
0
null
null
null
null
UTF-8
C++
false
false
3,030
cpp
//////////////////////////////////////////////////////////////////////////////// ////////// Author: newblue <[email protected]> ////////// Copyright by newblue, 2008. //////////////////////////////////////////////////////////////////////////////// #include "field.hpp" #include <wx/regex.h> #include "decode.hpp" namespace NiField { Field::Field () {} Field::~Field () {} bool Field::operator () ( const wxString& data ) { return Parser (data); } bool Field::Parser ( const wxString& data ) { m_rawdata = data; m_data.Clear (); m_data.Alloc (data.size ()); m_charset = wxT("Raw"); wxRegEx re (wxT("=\\?([^\\?]*)\\?(.)\\?([^\\?]*)\\?=")); unsigned int start = 0, len = 0; wxString tdata; const wxChar *bp, *ep, *dp; dp = bp = m_rawdata.c_str(); ep = bp + m_rawdata.Len (); while ( dp < ep ) { if ( *dp == wxT('=') && re.Matches (dp) && re.GetMatchCount() == 4 ) { if ( re.GetMatch ( &start, &len, 1 ) ) { m_charset = wxString ( (dp + start), len ).Upper(); } if ( re.GetMatch ( &start, &len, 2 ) ) { m_encodetype = *(dp+start); } if ( re.GetMatch ( &start, &len, 3 ) ) { tdata = wxString ((dp + start), len); if ( m_encodetype == wxT('q') || m_encodetype == wxT('Q') ) { m_data += NiDecode::QPDecode(tdata); } else if ( m_encodetype == wxT('B') || m_encodetype == wxT('b') ) { m_data += NiDecode::Base64Decode (tdata); } } if ( re.GetMatch ( &start, &len, 0 ) ) { dp += len; } } else { m_data += *dp; } ++dp; } return true; } wxString Field::Data () const { return m_data; } wxString Field::DataStripRe () const { const wxChar *bp, *ep, *dp; unsigned int start, len; dp = bp = m_data.c_str(); ep = bp + m_data.Len (); wxRegEx re (wxT("^([rR]e|[Rr]e \\[\\d+\\]): "), wxRE_DEFAULT|wxRE_ICASE); while ( dp < ep && re.Matches (dp) ) { if ( re.GetMatch ( &start, &len, 0 ) ) { dp += len; } } return wxString ( dp ); } NiUtils::HASH Field::DataStripReHash () const { return NiUtils::NiHash (DataStripRe()); } wxString Field::Charset () const { return m_charset; } }
[ [ [ 1, 103 ] ] ]
904be019a7094863531aa9015c7fb3d09323a293
5a39be53de11cddb52af7d0b70b56ef94cc52d35
/doc/ICTCLAS/Codes and Application/Utility/Dictionary.cpp
e760ea011d9d1667e5f252495c5a27b2710b392a
[]
no_license
zchn/jsepku
2b76eb5d118f86a5c942a9f4ec25a5adae24f802
8290fef5ff8abaf62cf050cead489dc7d44efa5f
refs/heads/master
2016-09-10T19:44:23.882210
2008-01-01T07:32:13
2008-01-01T07:32:13
33,052,475
0
0
null
null
null
null
GB18030
C++
false
false
34,170
cpp
////////////////////////////////////////////////////////////////////// //ICTCLAS简介:计算所汉语词法分析系统ICTCLAS(Institute of Computing Technology, Chinese Lexical Analysis System), // 功能有:中文分词;词性标注;未登录词识别。 // 分词正确率高达97.58%(973专家评测结果), // 未登录词识别召回率均高于90%,其中中国人名的识别召回率接近98%; // 处理速度为31.5Kbytes/s。 //著作权: Copyright?2002-2005中科院计算所 职务著作权人:张华平 刘群 //遵循协议:自然语言处理开放资源许可证1.0 //Email: [email protected] //Homepage:www.nlp.org.cn;mtgroup.ict.ac.cn /**************************************************************************** * * Copyright (c) 2000, 2001 * Machine Group * Software Research Lab. * Institute of Computing Tech. * Chinese Academy of Sciences * All rights reserved. * * This file is the confidential and proprietary property of * Institute of Computing Tech. and the posession or use of this file requires * a written license from the author. * Filename: Dictionary.cpp * Abstract: * implementation of the CDictionary class. * Author: Kevin Zhang * ([email protected]) * Date: 2002-1-8 * * Notes: * ****************************************************************************/ #include "stdafx.h" #include "Dictionary.h" #include "Utility.h" #include <string.h> #include <stdlib.h> #include <malloc.h> #include <stdio.h> #include <fstream> using namespace std; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDictionary::CDictionary() { //initilization memset(m_IndexTable,0,sizeof(m_IndexTable)); m_pModifyTable=NULL; } CDictionary::~CDictionary() { for(int i=0;i<CC_NUM;i++) {//delete the memory of word item array in the dictionary for(int j=0;j<m_IndexTable[i].nCount;j++) delete m_IndexTable[i].pWordItemHead[j].sWord; delete [] m_IndexTable[i].pWordItemHead; } DelModified(); } /********************************************************************* * * Func Name : Load * * Description: Load the dictionary from the file .dct * * * Parameters : sFilename: the file name * * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::Load(char *sFilename,bool bReset) { FILE *fp; int i,j,nBuffer[3]; if((fp=fopen(sFilename,"rb"))==NULL) return false;//fail while opening the file //Release the memory for new files for( i=0;i<CC_NUM;i++) {//delete the memory of word item array in the dictionary for( j=0;j<m_IndexTable[i].nCount;j++) delete m_IndexTable[i].pWordItemHead[j].sWord; delete [] m_IndexTable[i].pWordItemHead; } DelModified(); for(i=0;i<CC_NUM;i++) { fread(&(m_IndexTable[i].nCount),sizeof(int),1,fp); if(m_IndexTable[i].nCount>0) m_IndexTable[i].pWordItemHead=new WORD_ITEM[m_IndexTable[i].nCount]; else { m_IndexTable[i].pWordItemHead=0; continue; } j=0; while(j<m_IndexTable[i].nCount) { fread(nBuffer,sizeof(int),3,fp); m_IndexTable[i].pWordItemHead[j].sWord=new char[nBuffer[1]+1]; if(nBuffer[1])//String length is more than 0 { fread(m_IndexTable[i].pWordItemHead[j].sWord,sizeof(char),nBuffer[1],fp); } m_IndexTable[i].pWordItemHead[j].sWord[nBuffer[1]]=0; if(bReset)//Reset the frequency m_IndexTable[i].pWordItemHead[j].nFrequency=0; else m_IndexTable[i].pWordItemHead[j].nFrequency=nBuffer[0]; m_IndexTable[i].pWordItemHead[j].nWordLen=nBuffer[1]; m_IndexTable[i].pWordItemHead[j].nHandle=nBuffer[2]; j+=1;//Get next item in the original table. } } fclose(fp); return true; } /********************************************************************* * * Func Name : Save * * Description: Save the dictionary as the file .dct * * * Parameters : sFilename: the file name * * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::Save(char *sFilename) { FILE *fp; int i,j,nCount,nBuffer[3]; PWORD_CHAIN pCur; if((fp=fopen(sFilename,"wb"))==NULL) return false;//fail while opening the file for(i=0;i<CC_NUM;i++) { pCur=NULL; if(m_pModifyTable) {//Modification made nCount=m_IndexTable[i].nCount+m_pModifyTable[i].nCount-m_pModifyTable[i].nDelete; fwrite(&nCount,sizeof(int),1,fp); pCur=m_pModifyTable[i].pWordItemHead; j=0; while(pCur!=NULL&&j<m_IndexTable[i].nCount) {//Output to the file after comparision if(strcmp(pCur->data.sWord,m_IndexTable[i].pWordItemHead[j].sWord)<0||(strcmp(pCur->data.sWord,m_IndexTable[i].pWordItemHead[j].sWord)==0&&pCur->data.nHandle<m_IndexTable[i].pWordItemHead[j].nHandle)) {//Output the modified data to the file nBuffer[0]=pCur->data.nFrequency; nBuffer[1]=pCur->data.nWordLen; nBuffer[2]=pCur->data.nHandle; fwrite(nBuffer,sizeof(int),3,fp); if(nBuffer[1])//String length is more than 0 fwrite(pCur->data.sWord,sizeof(char),nBuffer[1],fp); pCur=pCur->next;//Get next item in the modify table. } else if(m_IndexTable[i].pWordItemHead[j].nFrequency==-1) {//The item has been removed,so skip it j+=1; } else if(strcmp(pCur->data.sWord,m_IndexTable[i].pWordItemHead[j].sWord)>0||(strcmp(pCur->data.sWord,m_IndexTable[i].pWordItemHead[j].sWord)==0&&pCur->data.nHandle>m_IndexTable[i].pWordItemHead[j].nHandle)) {//Output the index table data to the file nBuffer[0]=m_IndexTable[i].pWordItemHead[j].nFrequency; nBuffer[1]=m_IndexTable[i].pWordItemHead[j].nWordLen; nBuffer[2]=m_IndexTable[i].pWordItemHead[j].nHandle; fwrite(nBuffer,sizeof(int),3,fp); if(nBuffer[1])//String length is more than 0 fwrite(m_IndexTable[i].pWordItemHead[j].sWord,sizeof(char),nBuffer[1],fp); j+=1;//Get next item in the original table. } } if(j<m_IndexTable[i].nCount) { while(j<m_IndexTable[i].nCount) { if(m_IndexTable[i].pWordItemHead[j].nFrequency!=-1) {//Has been deleted nBuffer[0]=m_IndexTable[i].pWordItemHead[j].nFrequency; nBuffer[1]=m_IndexTable[i].pWordItemHead[j].nWordLen; nBuffer[2]=m_IndexTable[i].pWordItemHead[j].nHandle; fwrite(nBuffer,sizeof(int),3,fp); if(nBuffer[1])//String length is more than 0 fwrite(m_IndexTable[i].pWordItemHead[j].sWord,sizeof(char),nBuffer[1],fp); } j+=1;//Get next item in the original table. } } else////No Modification while(pCur!=NULL)//Add the rest data to the file. { nBuffer[0]=pCur->data.nFrequency; nBuffer[1]=pCur->data.nWordLen; nBuffer[2]=pCur->data.nHandle; fwrite(nBuffer,sizeof(int),3,fp); if(nBuffer[1])//String length is more than 0 fwrite(pCur->data.sWord,sizeof(char),nBuffer[1],fp); pCur=pCur->next;//Get next item in the modify table. } } else { fwrite(&m_IndexTable[i].nCount,sizeof(int),1,fp); //write to the file j=0; while(j<m_IndexTable[i].nCount) { nBuffer[0]=m_IndexTable[i].pWordItemHead[j].nFrequency; nBuffer[1]=m_IndexTable[i].pWordItemHead[j].nWordLen; nBuffer[2]=m_IndexTable[i].pWordItemHead[j].nHandle; fwrite(nBuffer,sizeof(int),3,fp); if(nBuffer[1])//String length is more than 0 fwrite(m_IndexTable[i].pWordItemHead[j].sWord,sizeof(char),nBuffer[1],fp); j+=1;//Get next item in the original table. } } } fclose(fp); return true; } /********************************************************************* * * Func Name : AddItem * * Description: Add a word item to the dictionary * * * Parameters : sWord: the word * nHandle:the handle number * nFrequency: the frequency * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::AddItem(char *sWord, int nHandle,int nFrequency) { char sWordAdd[WORD_MAXLENGTH-2]; int nPos,nFoundPos; PWORD_CHAIN pRet,pTemp,pNext; int i=0; if(!PreProcessing(sWord, &nPos,sWordAdd,true)) return false; if(FindInOriginalTable(nPos,sWordAdd,nHandle,&nFoundPos)) {//The word exists in the original table, so add the frequency //Operation in the index table and its items if(m_IndexTable[nPos].pWordItemHead[nFoundPos].nFrequency==-1) {//The word item has been removed m_IndexTable[nPos].pWordItemHead[nFoundPos].nFrequency=nFrequency; if(!m_pModifyTable)//Not prepare the buffer { m_pModifyTable=new MODIFY_TABLE[CC_NUM]; memset(m_pModifyTable,0,CC_NUM*sizeof(MODIFY_TABLE)); } m_pModifyTable[nPos].nDelete-=1; } else m_IndexTable[nPos].pWordItemHead[nFoundPos].nFrequency+=nFrequency; return true; } //The items not exists in the index table. //As following, we have to find the item whether exists in the modify data region //If exists, change the frequency .or else add a item if(!m_pModifyTable)//Not prepare the buffer { m_pModifyTable=new MODIFY_TABLE[CC_NUM]; memset(m_pModifyTable,0,CC_NUM*sizeof(MODIFY_TABLE)); } if(FindInModifyTable(nPos,sWordAdd,nHandle,&pRet)) { if(pRet!=NULL) pRet=pRet->next; else pRet=m_pModifyTable[nPos].pWordItemHead; pRet->data.nFrequency+=nFrequency; return true; } //find the proper position to add the word to the modify data table and link pTemp=new WORD_CHAIN;//Allocate the word chain node if(pTemp==NULL)//Allocate memory failure return false; memset(pTemp,0,sizeof(WORD_CHAIN));//init it with 0 pTemp->data.nHandle=nHandle;//store the handle pTemp->data.nWordLen=strlen(sWordAdd); pTemp->data.sWord=new char[1+pTemp->data.nWordLen]; strcpy(pTemp->data.sWord,sWordAdd); pTemp->data.nFrequency=nFrequency; pTemp->next=NULL; if(pRet!=NULL) { pNext=pRet->next;//Get the next item before the current item pRet->next=pTemp;//link the node to the chain } else { pNext=m_pModifyTable[nPos].pWordItemHead; m_pModifyTable[nPos].pWordItemHead=pTemp;//Set the pAdd as the head node } pTemp->next=pNext;//Very important!!!! or else it will lose some node //Modify in 2001-10-29 m_pModifyTable[nPos].nCount++;//the number increase by one return true; } bool CDictionary::DelItem(char *sWord,int nHandle) { char sWordDel[WORD_MAXLENGTH-2]; int nPos,nFoundPos,nTemp; PWORD_CHAIN pPre,pTemp,pCur; if(!PreProcessing(sWord, &nPos,sWordDel)) return false; if(FindInOriginalTable(nPos,sWordDel,nHandle,&nFoundPos)) { if(!m_pModifyTable)//Not prepare the buffer { m_pModifyTable=new MODIFY_TABLE[CC_NUM]; memset(m_pModifyTable,0,CC_NUM*sizeof(MODIFY_TABLE)); } m_IndexTable[nPos].pWordItemHead[nFoundPos].nFrequency=-1; m_pModifyTable[nPos].nDelete+=1; if(nHandle==-1)//Remove all items which word is sWordDel,ignoring the handle { /* nTemp=nFoundPos-1;//Check its previous position while(nTemp>0&&strcmp(m_IndexTable[nPos].pWordItemHead[nFoundPos].sWord,sWordDel)==0) { m_IndexTable[nPos].pWordItemHead[nTemp].nFrequency=-1; m_pModifyTable[nPos].nDelete+=1; nTemp-=1; } */ nTemp=nFoundPos+1;//Check its previous position while(nTemp<m_IndexTable[nPos].nCount&&strcmp(m_IndexTable[nPos].pWordItemHead[nFoundPos].sWord,sWordDel)==0) { m_IndexTable[nPos].pWordItemHead[nTemp].nFrequency=-1; m_pModifyTable[nPos].nDelete+=1; nTemp+=1; } } return true; } //Operation in the modify table and its items if(FindInModifyTable(nPos,sWordDel,nHandle,&pPre)) { pCur=m_pModifyTable[nPos].pWordItemHead; if(pPre!=NULL) pCur=pPre->next; while(pCur!=NULL && _stricmp(pCur->data.sWord,sWordDel)==0&&(pCur->data.nHandle==nHandle||nHandle<0)) { pTemp=pCur; if(pPre!=NULL)//pCur is the first item pPre->next=pCur->next; else m_pModifyTable[nPos].pWordItemHead=pCur->next; pCur=pCur->next; delete pTemp->data.sWord;//Delete the word delete pTemp; } return true; } return false; } bool CDictionary::DelModified() { PWORD_CHAIN pTemp,pCur; if(!m_pModifyTable) return true; for(int i=0;i<CC_NUM;i++) { pCur=m_pModifyTable[i].pWordItemHead; while(pCur!=NULL) { pTemp=pCur; pCur=pCur->next; delete pTemp->data.sWord; delete pTemp; } } delete [] m_pModifyTable; m_pModifyTable=NULL; return true; } bool CDictionary::IsExist(char *sWord, int nHandle) { char sWordFind[WORD_MAXLENGTH-2]; int nPos; if(!PreProcessing(sWord, &nPos,sWordFind)) return false; return(FindInOriginalTable(nPos,sWordFind,nHandle)||FindInModifyTable(nPos,sWordFind,nHandle)); } bool CDictionary::GetHandle(char *sWord,int *pnCount,int *pnHandle,int *pnFrequency) { char sWordGet[WORD_MAXLENGTH-2]; int nPos,nFoundPos,nTemp; PWORD_CHAIN pPre,pCur; *pnCount=0; if(!PreProcessing(sWord, &nPos,sWordGet)) return false; if(FindInOriginalTable(nPos,sWordGet,-1,&nFoundPos)) { pnHandle[*pnCount]=m_IndexTable[nPos].pWordItemHead[nFoundPos].nHandle; pnFrequency[*pnCount]=m_IndexTable[nPos].pWordItemHead[nFoundPos].nFrequency; *pnCount+=1; /* nTemp=nFoundPos-1;//Check its previous position while(nTemp>0&&strcmp(m_IndexTable[nPos].pWordItemHead[nTemp].sWord,sWordGet)==0) { pnHandle[*pnCount]=m_IndexTable[nPos].pWordItemHead[nTemp].nHandle; pnFrequency[*pnCount]=m_IndexTable[nPos].pWordItemHead[nTemp].nFrequency; *pnCount+=1; nTemp-=1; } */ nTemp=nFoundPos+1;//Check its previous position while(nTemp<m_IndexTable[nPos].nCount&&strcmp(m_IndexTable[nPos].pWordItemHead[nTemp].sWord,sWordGet)==0) { pnHandle[*pnCount]=m_IndexTable[nPos].pWordItemHead[nTemp].nHandle; pnFrequency[*pnCount]=m_IndexTable[nPos].pWordItemHead[nTemp].nFrequency; *pnCount+=1; nTemp+=1; } return true; } //Operation in the index table and its items if(FindInModifyTable(nPos,sWordGet,-1,&pPre)) { pCur=m_pModifyTable[nPos].pWordItemHead; if(pPre!=NULL) pCur=pPre->next; while(pCur!=NULL && _stricmp(pCur->data.sWord,sWordGet)==0) { pnHandle[*pnCount]=pCur->data.nHandle; pnFrequency[*pnCount]=pCur->data.nFrequency; *pnCount+=1; pCur=pCur->next; } return true; } return false; } /********************************************************************* * * Func Name : FindInOriginalTable * * Description: judge the word and handle exist in the inner table and its items * * * Parameters : nInnerCode: the inner code of the first CHines char * sWord: the word * nHandle:the handle number * *nPosRet:the position which node is matched * * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::FindInOriginalTable(int nInnerCode,char *sWord,int nHandle,int *nPosRet) { PWORD_ITEM pItems=m_IndexTable[nInnerCode].pWordItemHead; int nStart=0,nEnd=m_IndexTable[nInnerCode].nCount-1,nMid=(nStart+nEnd)/2,nCount=0,nCmpValue; while(nStart<=nEnd)//Binary search { nCmpValue=strcmp(pItems[nMid].sWord,sWord); if(nCmpValue==0&&(pItems[nMid].nHandle==nHandle||nHandle==-1)) { if(nPosRet) { if(nHandle==-1)//Not very strict match {//Add in 2002-1-28 nMid-=1; while(nMid>=0&&strcmp(pItems[nMid].sWord,sWord)==0) //Get the first item which match the current word nMid--; if(nMid<0||strcmp(pItems[nMid].sWord,sWord)!=0) nMid++; } *nPosRet=nMid; return true; } if(nPosRet) *nPosRet=nMid; return true;//find it } else if(nCmpValue<0||(nCmpValue==0&&pItems[nMid].nHandle<nHandle&&nHandle!=-1)) { nStart=nMid+1; } else if(nCmpValue>0||(nCmpValue==0&&pItems[nMid].nHandle>nHandle&&nHandle!=-1)) { nEnd=nMid-1; } nMid=(nStart+nEnd)/2; } if(nPosRet) { //Get the previous position *nPosRet=nMid-1; } return false; } /********************************************************************* * * Func Name : FindInModifyTable * * Description: judge the word and handle exist in the modified table and its items * * * Parameters : nInnerCode: the inner code of the first CHines char * sWord: the word * nHandle:the handle number * *pFindRet: the node found * * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::FindInModifyTable(int nInnerCode,char *sWord,int nHandle,PWORD_CHAIN *pFindRet) { PWORD_CHAIN pCur,pPre; if(m_pModifyTable==NULL)//empty return false; pCur=m_pModifyTable[nInnerCode].pWordItemHead; pPre=NULL; while(pCur!=NULL&&(_stricmp(pCur->data.sWord,sWord)<0||(_stricmp(pCur->data.sWord,sWord)==0&&pCur->data.nHandle<nHandle))) //sort the link chain as alphabet { pPre=pCur; pCur=pCur->next; } if(pFindRet) *pFindRet=pPre; if(pCur!=NULL && _stricmp(pCur->data.sWord,sWord)==0&&(pCur->data.nHandle==nHandle||nHandle<0)) {//The node exists, delete the node and return return true; } return false; } /********************************************************************* * * Func Name : GetWordType * * Description: Get the type of word * * * Parameters : sWord: the word * Returns : the type * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ int CDictionary::GetWordType(char *sWord) { int nType=charType((unsigned char *)sWord),nLen=strlen(sWord); if(nLen>0&&nType==CT_CHINESE&&IsAllChinese((unsigned char *)sWord)) return WT_CHINESE;//Chinese word else if(nLen>0&&nType==CT_DELIMITER) return WT_DELIMITER;//Delimiter else return WT_OTHER;//other invalid } /********************************************************************* * * Func Name : PreProcessing * * Description: Get the type of word * * * Parameters : sWord: the word * Returns : the type * Author : Kevin Zhang * History : * 1.create 2002-1-9 *********************************************************************/ bool CDictionary::PreProcessing(char *sWord, int *nId, char *sWordRet,bool bAdd) { //Position for the delimeters int nType=charType((unsigned char *)sWord),nLen=strlen(sWord); int nEnd=nLen-1,nBegin=0; if(nLen==0) return false; while(nEnd>=0&&sWord[nEnd]==' ') nEnd-=1; while(nBegin<=nEnd&&sWord[nBegin]==' ') nBegin+=1; if(nBegin>nEnd) return false; if(nEnd!=nLen-1||nBegin!=0) { strncpy(sWord,sWord+nBegin,nEnd-nBegin+1); sWord[nEnd-nBegin+1]=0; } /* if((bAdd||strlen(sWord)>4)&&IsAllChineseNum(sWord)) { //Only convert the Chinese Num to 3755 while //Get the inner code of the first Chinese Char strcpy(sWord,"五十八"); } */ if(nType==CT_CHINESE)//&&IsAllChinese((unsigned char *)sWord) {//Chinese word *nId=CC_ID(sWord[0],sWord[1]); //Get the inner code of the first Chinese Char strcpy(sWordRet,&sWord[2]);//store the word,not store the first Chinese Char return true; } /* if(nType==CT_NUM&&IsAllNum((unsigned char *)sWord)) { *nId=3756; //Get the inner code of the first Chinese Char sWordRet[0]=0;//store the word,not store the first Chinese Char return true; } */ if(nType==CT_DELIMITER) {//Delimiter *nId=3755; //Get the inner code of the first Chinese Char strcpy(sWordRet,sWord);//store the word,not store the first Chinese Char return true; } /* if(nType==CT_LETTER&&IsAllLetter((unsigned char *)sWord)) { *nId=3757; //Get the inner code of the first Chinese Char sWordRet[0]=0;//store the word,not store the first Chinese Char return true; } if(nType==CT_SINGLE&&IsAllSingleByte((unsigned char *)sWord)) { *nId=3758; //Get the inner code of the first Chinese Char sWordRet[0]=0;//store the word,not store the first Chinese Char return true; } if(nType==CT_INDEX&&IsAllIndex((unsigned char *)sWord)) { *nId=3759; //Get the inner code of the first Chinese Char sWordRet[0]=0;//store the word,not store the first Chinese Char return true; } */ return false;//other invalid } /********************************************************************* * * Func Name : MergePOS * * Description: Merge all the POS into nHandle, * just get the word in the dictionary and set its Handle as nHandle * * * Parameters : nHandle: the only handle which will be attached to the word * Returns : the type * Author : Kevin Zhang * History : * 1.create 2002-1-21 *********************************************************************/ bool CDictionary::MergePOS(int nHandle) { int i,j,nCompare; char sWordPrev[WORD_MAXLENGTH]; PWORD_CHAIN pPre,pCur,pTemp; if(!m_pModifyTable)//Not prepare the buffer { m_pModifyTable=new MODIFY_TABLE[CC_NUM]; memset(m_pModifyTable,0,CC_NUM*sizeof(MODIFY_TABLE)); } for( i=0;i<CC_NUM;i++)//Operation in the index table {//delete the memory of word item array in the dictionary sWordPrev[0]=0;//Set empty for(j=0;j<m_IndexTable[i].nCount;j++) { nCompare=_stricmp(sWordPrev,m_IndexTable[i].pWordItemHead[j].sWord); if((j==0||nCompare<0)&&m_IndexTable[i].pWordItemHead[j].nFrequency!=-1) {//Need to modify its handle m_IndexTable[i].pWordItemHead[j].nHandle=nHandle;//Change its handle strcpy(sWordPrev,m_IndexTable[i].pWordItemHead[j].sWord);//Refresh previous Word } else if(nCompare==0&&m_IndexTable[i].pWordItemHead[j].nFrequency!=-1) {//Need to delete when not delete and same as previous word m_IndexTable[i].pWordItemHead[j].nFrequency=-1;//Set delete flag m_pModifyTable[i].nDelete+=1;//Add the number of being deleted } } } for( i=0;i<CC_NUM;i++)//Operation in the modify table { pPre=NULL; pCur=m_pModifyTable[i].pWordItemHead; sWordPrev[0]=0;//Set empty while(pCur!=NULL) { if(_stricmp(pCur->data.sWord,sWordPrev)>0) {//The new word pCur->data.nHandle=nHandle;//Chang its handle strcpy(sWordPrev,pCur->data.sWord);//Set new previous word pPre=pCur;//New previous pointer pCur=pCur->next; } else {//The same word as previous,delete it. pTemp=pCur; if(pPre!=NULL)//pCur is the first item pPre->next=pCur->next; else m_pModifyTable[i].pWordItemHead=pCur->next; pCur=pCur->next; delete pTemp->data.sWord;//Delete the word delete pTemp;//Delete the item } } } return true; } /********************************************************************* * * Func Name : GetMaxMatch * * Description: Get the max match to the word * * * Parameters : nHandle: the only handle which will be attached to the word * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-21 *********************************************************************/ bool CDictionary::GetMaxMatch(char *sWord, char *sWordRet,int *npHandleRet) { char sWordGet[WORD_MAXLENGTH-2],sFirstChar[3]; int nPos,nFoundPos,nTemp; PWORD_CHAIN pCur; *npHandleRet=-1; if(!PreProcessing(sWord, &nPos,sWordGet)) return false; sWordRet[0]=0; strncpy(sFirstChar,sWord,strlen(sWord)-strlen(sWordGet));//Get the first char sFirstChar[strlen(sWord)-strlen(sWordGet)]=0;//Set the end flag FindInOriginalTable(nPos,sWordGet,-1,&nFoundPos); nTemp=nFoundPos;//Check its previous position if(nFoundPos==-1) nTemp=0; while(nTemp<m_IndexTable[nPos].nCount&&CC_Find(m_IndexTable[nPos].pWordItemHead[nTemp].sWord,sWordGet)!=m_IndexTable[nPos].pWordItemHead[nTemp].sWord) {//Get the next nTemp+=1; } if(nTemp<m_IndexTable[nPos].nCount&&CC_Find(m_IndexTable[nPos].pWordItemHead[nTemp].sWord,sWordGet)==m_IndexTable[nPos].pWordItemHead[nTemp].sWord) { strcpy(sWordRet,sFirstChar); strcat(sWordRet,m_IndexTable[nPos].pWordItemHead[nTemp].sWord); *npHandleRet=m_IndexTable[nPos].pWordItemHead[nTemp].nHandle; return true; }//Cannot get the item and retrieve the modified data if exists //Operation in the index table and its items if(m_pModifyTable&&m_pModifyTable[nPos].pWordItemHead)//Exists pCur=m_pModifyTable[nPos].pWordItemHead; else pCur=NULL; while(pCur!=NULL&&strcmp(pCur->data.sWord,sWordGet)<=0&&CC_Find(pCur->data.sWord,sWordGet)!=pCur->data.sWord)// { pCur=pCur->next; } if(pCur!=NULL&&CC_Find(pCur->data.sWord,sWordGet)!=pCur->data.sWord) {//Get it strcpy(sWordRet,sFirstChar); strcat(sWordRet,pCur->data.sWord); *npHandleRet=pCur->data.nHandle; return true; } return false; } /********************************************************************* * * Func Name : GetPOSValue * * Description: Get the POS value according the POS string * * * Parameters : * Returns : the value * Author : Kevin Zhang * History : * 1.create 2002-1-29 *********************************************************************/ int CDictionary::GetPOSValue(char *sPOS) { int nPOS; char *sPlusPos,sTemp[4]; if(strlen(sPOS)<3) { nPOS=sPOS[0]*256+sPOS[1]; } else { sPlusPos=strchr(sPOS,'+'); strncpy(sTemp,sPOS,sPlusPos-sPOS); sTemp[sPlusPos-sPOS]=0; nPOS=100*GetPOSValue(sTemp); strncpy(sTemp,sPlusPos+1,4); nPOS+=atoi(sTemp); } return nPOS; } /********************************************************************* * * Func Name : GetPOSString * * Description: Get the POS string according the POS value * * * Parameters : * Returns : success or fail * Author : Kevin Zhang * History : * 1.create 2002-1-29 *********************************************************************/ bool CDictionary::GetPOSString(int nPOS, char *sPOSRet) { if(nPOS>'a'*25600) { if((nPOS/100)%256!=0) sprintf(sPOSRet,"%c%c+%d",nPOS/25600,(nPOS/100)%256,nPOS%100); else sprintf(sPOSRet,"%c+%d",nPOS/25600,nPOS%100); } else { if(nPOS>256) sprintf(sPOSRet,"%c%c",nPOS/256,nPOS%256); else sprintf(sPOSRet,"%c",nPOS%256); } return true; } int CDictionary::GetFrequency(char *sWord, int nHandle) { char sWordFind[WORD_MAXLENGTH-2]; int nPos,nIndex; PWORD_CHAIN pFound; if(!PreProcessing(sWord, &nPos,sWordFind)) return 0; if(FindInOriginalTable(nPos,sWordFind,nHandle,&nIndex)) { return m_IndexTable[nPos].pWordItemHead[nIndex].nFrequency; } if(FindInModifyTable(nPos,sWordFind,nHandle,&pFound)) { return pFound->data.nFrequency; } return 0; } bool CDictionary::Output(char *sFilename) { FILE *fp; int i,j; PWORD_CHAIN pCur; char sPrevWord[WORD_MAXLENGTH]="", sCurWord[WORD_MAXLENGTH],sPOS[10]; if((fp=fopen(sFilename,"wb"))==NULL) return false;//fail while opening the file if(m_pModifyTable) {//Modification made, not to output when modify table exists. return false; } for(i=0;i<CC_NUM;i++) { pCur=NULL; j=0; while(j<m_IndexTable[i].nCount) { GetPOSString(m_IndexTable[i].pWordItemHead[j].nHandle,sPOS); //Get the POS string sprintf(sCurWord,"%c%c%s",CC_CHAR1(i),CC_CHAR2(i),m_IndexTable[i].pWordItemHead[j].sWord); if(strcmp(sPrevWord,sCurWord)!=0) fprintf(fp,"\n%s %s",sCurWord,sPOS); else fprintf(fp," %s",sPOS); strcpy(sPrevWord,sCurWord); j+=1;//Get next item in the original table. } } fclose(fp); return true; } bool CDictionary::OutputChars(char *sFilename) { FILE *fp; int i,j; char sPrevWord[WORD_MAXLENGTH]="", sCurWord[WORD_MAXLENGTH]; if((fp=fopen(sFilename,"wb"))==NULL) return false;//fail while opening the file if(m_pModifyTable) {//Modification made, not to output when modify table exists. return false; } for(i=0;i<CC_NUM;i++) { j=0; while(j<m_IndexTable[i].nCount) { sprintf(sCurWord,"%c%c%s",CC_CHAR1(i),CC_CHAR2(i),m_IndexTable[i].pWordItemHead[j].sWord); if(strcmp(sPrevWord,sCurWord)!=0&&m_IndexTable[i].pWordItemHead[j].nFrequency>50)// fprintf(fp,"%s",sCurWord); strcpy(sPrevWord,sCurWord); j+=1;//Get next item in the original table. } } fclose(fp); return true; } bool CDictionary::Merge(CDictionary dict2, int nRatio) //Merge dict2 into current dictionary and the frequency ratio from dict2 and current dict is nRatio { int i,j,k,nCmpValue; char sWord[WORD_MAXLENGTH]; if(m_pModifyTable||dict2.m_pModifyTable) {//Modification made, not to output when modify table exists. return false; } for(i=0;i<CC_NUM;i++) { j=0; k=0; while(j<m_IndexTable[i].nCount&&k<dict2.m_IndexTable[i].nCount) { nCmpValue=strcmp(m_IndexTable[i].pWordItemHead[j].sWord,dict2.m_IndexTable[i].pWordItemHead[k].sWord); if(nCmpValue==0)//Same Words and determine the different handle { if(m_IndexTable[i].pWordItemHead[j].nHandle<dict2.m_IndexTable[i].pWordItemHead[k].nHandle) nCmpValue=-1; else if(m_IndexTable[i].pWordItemHead[j].nHandle>dict2.m_IndexTable[i].pWordItemHead[k].nHandle) nCmpValue=1; } if(nCmpValue==0) { m_IndexTable[i].pWordItemHead[j].nFrequency=(nRatio*m_IndexTable[i].pWordItemHead[j].nFrequency+dict2.m_IndexTable[i].pWordItemHead[k].nFrequency)/(nRatio+1); j+=1; k+=1; } else if(nCmpValue<0)//Get next word in the current dictionary { m_IndexTable[i].pWordItemHead[j].nFrequency=(nRatio*m_IndexTable[i].pWordItemHead[j].nFrequency)/(nRatio+1); j+=1; } else//Get next word in the second dictionary { if(dict2.m_IndexTable[i].pWordItemHead[k].nFrequency>(nRatio+1)/10) { sprintf(sWord,"%c%c%s",CC_CHAR1(i),CC_CHAR2(i),dict2.m_IndexTable[i].pWordItemHead[k].sWord); AddItem(sWord,dict2.m_IndexTable[i].pWordItemHead[k].nHandle,dict2.m_IndexTable[i].pWordItemHead[k].nFrequency/(nRatio+1)); } k+=1; } } while(j<m_IndexTable[i].nCount)//words in current dictionary are left { m_IndexTable[i].pWordItemHead[j].nFrequency=(nRatio*m_IndexTable[i].pWordItemHead[j].nFrequency)/(nRatio+1); j+=1; } while(k<dict2.m_IndexTable[i].nCount)//words in Dict2 are left { if(dict2.m_IndexTable[i].pWordItemHead[k].nFrequency>(nRatio+1)/10) { sprintf(sWord,"%c%c%s",CC_CHAR1(i),CC_CHAR2(i),dict2.m_IndexTable[i].pWordItemHead[k].sWord); AddItem(sWord,dict2.m_IndexTable[i].pWordItemHead[k].nHandle,dict2.m_IndexTable[i].pWordItemHead[k].nFrequency/(nRatio+1)); } k+=1; } } return true; } //Delete word item which //(1)frequency is 0 //(2)word is same as following but the POS value is parent set of the following //for example "江泽民/n/0" will deleted, because "江泽民/nr/0" is more detail and correct bool CDictionary::Optimum() { int nPrevPOS,i,j,nPrevFreq; char sPrevWord[WORD_MAXLENGTH],sCurWord[WORD_MAXLENGTH]; for(i=0;i<CC_NUM;i++) { j=0; sPrevWord[0]=0; nPrevPOS=0; nPrevFreq=-1; while(j<m_IndexTable[i].nCount) { sprintf(sCurWord,"%c%c%s",CC_CHAR1(i),CC_CHAR2(i),m_IndexTable[i].pWordItemHead[j].sWord); if(nPrevPOS==30720||nPrevPOS==26368||nPrevPOS==29031||(strcmp(sPrevWord,sCurWord)==0&&nPrevFreq==0&&m_IndexTable[i].pWordItemHead[j].nHandle/256*256==nPrevPOS)) {//Delete Previous word item //Delete word with POS 'x','g' 'qg' DelItem(sPrevWord,nPrevPOS); } strcpy(sPrevWord,sCurWord); nPrevPOS=m_IndexTable[i].pWordItemHead[j].nHandle; nPrevFreq=m_IndexTable[i].pWordItemHead[j].nFrequency; j+=1;//Get next item in the original table. } } return true; }
[ "joyanlj@702d1322-cd41-0410-9eed-0fefee27d168" ]
[ [ [ 1, 1024 ] ] ]
67ec0f149ff1adc90a32cd9dc6f3adcce8f89e71
f4b649f3f48ad288550762f4439fcfffddc08d0e
/eRacer/Source/Graphics/SkyBox.cpp
62ccc5872932f250d906d5f099d5017306d67142
[]
no_license
Knio/eRacer
0fa27c8f7d1430952a98ac2896ab8b8ee87116e7
65941230b8bed458548a920a6eac84ad23c561b8
refs/heads/master
2023-09-01T16:02:58.232341
2010-04-26T23:58:20
2010-04-26T23:58:20
506,897
1
0
null
null
null
null
UTF-8
C++
false
false
759
cpp
/** * @file SkyBox.cpp * @brief Implementation of the SkyBox class * * @date 07.02.2010 * @author: Ole Rehmsen */ #include "SkyBox.h" #include "GraphicsLayer.h" #include <iostream> using namespace std; namespace Graphics{ void SkyBox::Draw(IDirect3DDevice9* device) const { if (!initialized) return; Camera& cam = *GraphicsLayer::GetInstance().GetCamera(); //should be far/sqrt(2), but not enough for some reason Matrix transform = CreateMatrix(cam.GetPosition(), cam.GetFar()*0.5f); device->SetTransform( D3DTS_WORLDMATRIX(0), &transform ); mesh_->Draw(device); } SkyBox::SkyBox() : initialized(false), mesh_(NULL) { } void SkyBox::Init(Mesh* mesh){ mesh_ = mesh; initialized = true; } }
[ [ [ 1, 7 ], [ 10, 10 ], [ 13, 17 ], [ 19, 21 ], [ 23, 23 ], [ 25, 27 ], [ 29, 41 ] ], [ [ 8, 9 ], [ 11, 12 ], [ 18, 18 ], [ 22, 22 ], [ 24, 24 ], [ 28, 28 ] ] ]
0e8cc5706c2971dc0a759772ac0819b8f73b9e28
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/serialization/src/basic_iarchive.cpp
b4355e3ce625ce0ff17f2c65232574902afda600
[ "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
19,382
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // basic_archive.cpp: // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <boost/config.hpp> // msvc 6.0 needs this to suppress warnings #include <cassert> #include <set> #include <list> #include <vector> #include <cstddef> // size_t #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::size_t; } // namespace std #endif #define BOOST_ARCHIVE_SOURCE #include <boost/archive/detail/auto_link_archive.hpp> #include <boost/limits.hpp> #include <boost/state_saver.hpp> #include <boost/throw_exception.hpp> #include <boost/archive/detail/basic_iserializer.hpp> #include <boost/archive/detail/basic_pointer_iserializer.hpp> #include <boost/archive/detail/basic_iarchive.hpp> #include <boost/archive/detail/basic_archive_impl.hpp> #include <boost/archive/archive_exception.hpp> #include <boost/serialization/tracking.hpp> #include <boost/serialization/extended_type_info.hpp> using namespace boost::serialization; namespace boost { namespace archive { namespace detail { class basic_iserializer; class basic_pointer_iserializer; class basic_iarchive_impl : public basic_archive_impl { friend class basic_iarchive; version_type m_archive_library_version; unsigned int m_flags; ////////////////////////////////////////////////////////////////////// // information about each serialized object loaded // indexed on object_id struct aobject { void * address; class_id_type class_id; aobject( void *a, class_id_type class_id_ ) : address(a), class_id(class_id_) {} aobject() : address(NULL), class_id(-2) {} }; typedef std::vector<aobject> object_id_vector_type; object_id_vector_type object_id_vector; ////////////////////////////////////////////////////////////////////// // used to implement the reset_object_address operation. // list of objects which might be moved. We use a vector for implemenation // in the hope the the truncation operation will be faster than either // with a list or stack adaptor object_id_type moveable_objects_start; object_id_type moveable_objects_end; object_id_type moveable_objects_recent; void reset_object_address( const void * new_address, const void *old_address ); ////////////////////////////////////////////////////////////////////// // used by load object to look up class id given basic_serializer struct cobject_type { const basic_iserializer * bis; const class_id_type class_id; cobject_type( class_id_type class_id_, const basic_iserializer & bis_ ) : bis(& bis_), class_id(class_id_) {} cobject_type(const cobject_type & rhs) : bis(rhs.bis), class_id(rhs.class_id) {} // the following cannot be defined because of the const // member. This will generate a link error if an attempt // is made to assign. This should never be necessary cobject_type & operator=(const cobject_type & rhs); bool operator<(const cobject_type &rhs) const { return *bis < *(rhs.bis); } }; typedef std::set<cobject_type> cobject_info_set_type; cobject_info_set_type cobject_info_set; ////////////////////////////////////////////////////////////////////// // information about each serialized class indexed on class_id class cobject_id { public: cobject_id & operator=(const cobject_id & rhs){ bis_ptr = rhs.bis_ptr; bpis_ptr = rhs.bpis_ptr; file_version = rhs.file_version; tracking_level = rhs.tracking_level; initialized = rhs.initialized; return *this; } const basic_iserializer * bis_ptr; const basic_pointer_iserializer * bpis_ptr; version_type file_version; tracking_type tracking_level; bool initialized; cobject_id(const basic_iserializer & bis_) : bis_ptr(& bis_), bpis_ptr(NULL), file_version(0), tracking_level(track_never), initialized(false) {} cobject_id(const cobject_id &rhs): bis_ptr(rhs.bis_ptr), bpis_ptr(rhs.bpis_ptr), file_version(rhs.file_version), tracking_level(rhs.tracking_level), initialized(rhs.initialized) {} }; typedef std::vector<cobject_id> cobject_id_vector_type; cobject_id_vector_type cobject_id_vector; ////////////////////////////////////////////////////////////////////// // list of objects created by de-serialization. Used to implement // clean up after exceptions. class created_pointer_type { public: created_pointer_type( class_id_type class_id_, void * address_ ) : class_id(class_id_), address(address_) {} created_pointer_type(const created_pointer_type &rhs) : class_id(rhs.class_id), address(rhs.address) {} created_pointer_type & operator=(const created_pointer_type &){ assert(false); return *this; } void * get_address() const { return address; } // object to which this item refers const class_id_type class_id; private: void * address; }; std::list<created_pointer_type> created_pointers; ////////////////////////////////////////////////////////////////////// // address of the most recent object serialized as a poiner // whose data itself is now pending serialization void * pending_object; const basic_iserializer * pending_bis; version_type pending_version; basic_iarchive_impl(unsigned int flags) : m_archive_library_version(ARCHIVE_VERSION()), m_flags(flags), moveable_objects_start(0), moveable_objects_end(0), pending_object(NULL), pending_bis(NULL), pending_version(0) {} ~basic_iarchive_impl(){} void set_library_version(unsigned int archive_library_version){ m_archive_library_version = archive_library_version; } bool track( basic_iarchive & ar, void * & t ); void load_preamble( basic_iarchive & ar, cobject_id & co ); class_id_type register_type( const basic_iserializer & bis ); // redirect through virtual functions to load functions for this archive template<class T> void load(basic_iarchive & ar, T & t){ ar.vload(t); } //public: void next_object_pointer(void * t){ pending_object = t; } void delete_created_pointers(); class_id_type register_type( const basic_pointer_iserializer & bpis ); void load_object( basic_iarchive & ar, void * t, const basic_iserializer & bis ); const basic_pointer_iserializer * load_pointer( basic_iarchive & ar, void * & t, const basic_pointer_iserializer * bpis, const basic_pointer_iserializer * (*finder)( const boost::serialization::extended_type_info & type ) ); }; inline void basic_iarchive_impl::reset_object_address( const void * new_address, const void *old_address ){ object_id_type i; // this code handles a couple of situations. // a) where reset_object_address is applied to an untracked object. // In such a case the call is really superfluous and its really an // an error. But we don't have access to the types here so we can't // know that. However, this code will effectively turn this situation // into a no-op and every thing will work fine - albeat with a small // execution time penalty. // b) where the call to reset_object_address doesn't immediatly follow // the << operator to which it corresponds. This would be a bad idea // but the code may work anyway. Naturally, a bad practice on the part // of the programmer but we can't detect it - as above. So maybe we // can save a few more people from themselves as above. for(i = moveable_objects_recent; i < moveable_objects_end; ++i){ if(old_address == object_id_vector[i].address) break; } for(; i < moveable_objects_end; ++i){ // calculate displacement from this level // warning - pointer arithmetic on void * is in herently non-portable // but expected to work on all platforms in current usage if(object_id_vector[i].address > old_address){ std::size_t member_displacement = reinterpret_cast<std::size_t>(object_id_vector[i].address) - reinterpret_cast<std::size_t>(old_address); object_id_vector[i].address = reinterpret_cast<void *>( reinterpret_cast<std::size_t>(new_address) + member_displacement ); } else{ std::size_t member_displacement = reinterpret_cast<std::size_t>(old_address) - reinterpret_cast<std::size_t>(object_id_vector[i].address); object_id_vector[i].address = reinterpret_cast<void *>( reinterpret_cast<std::size_t>(new_address) - member_displacement ); } ++i; } } inline void basic_iarchive_impl::delete_created_pointers() { while(! created_pointers.empty()){ const created_pointer_type & cp = created_pointers.front(); // figure out the class of the object to be deleted // note: extra line used to evade borland issue const int id = cp.class_id; const cobject_id & co = cobject_id_vector[id]; // with the appropriate input serializer, // delete the indicated object co.bis_ptr->destroy(cp.get_address()); created_pointers.pop_front(); } } inline class_id_type basic_iarchive_impl::register_type( const basic_iserializer & bis ){ class_id_type id(static_cast<int>(cobject_info_set.size())); cobject_type co(id, bis); std::pair<cobject_info_set_type::const_iterator, bool> result = cobject_info_set.insert(co); if(result.second){ cobject_id_vector.push_back(cobject_id(bis)); assert(cobject_info_set.size() == cobject_id_vector.size()); } id = result.first->class_id; // borland complains without this minor hack const int tid = id; cobject_id & coid = cobject_id_vector[tid]; coid.bpis_ptr = bis.get_bpis_ptr(); return id; } void basic_iarchive_impl::load_preamble( basic_iarchive & ar, cobject_id & co ){ if(! co.initialized){ if(co.bis_ptr->class_info()){ class_id_optional_type cid; load(ar, cid); // to be thrown away load(ar, co.tracking_level); load(ar, co.file_version); } else{ // override tracking with indicator from class information co.tracking_level = co.bis_ptr->tracking(m_flags); co.file_version = version_type( co.bis_ptr->version() ); } co.initialized = true; } } bool basic_iarchive_impl::track( basic_iarchive & ar, void * & t ){ object_id_type oid; load(ar, oid); // if its a reference to a old object if(object_id_type(object_id_vector.size()) > oid){ // we're done t = object_id_vector[oid].address; return false; } return true; } inline void basic_iarchive_impl::load_object( basic_iarchive & ar, void * t, const basic_iserializer & bis ){ // if its been serialized through a pointer and the preamble's been done if(t == pending_object && & bis == pending_bis){ // read data (bis.load_object_data)(ar, t, pending_version); return; } const class_id_type cid = register_type(bis); // note: extra line used to evade borland issue const int id = cid; cobject_id & co = cobject_id_vector[id]; load_preamble(ar, co); // save the current move stack position in case we want to truncate it boost::state_saver<object_id_type> w(moveable_objects_start); // note: extra line used to evade borland issue const bool tracking = co.tracking_level; object_id_type this_id; moveable_objects_start = this_id = object_id_vector.size(); // if we tracked this object when the archive was saved if(tracking){ // if it was already read if(!track(ar, t)) // we're done return; // add a new enty into the tracking list object_id_vector.push_back(aobject(t, cid)); // and add an entry for this object moveable_objects_end = object_id_vector.size(); } // read data (bis.load_object_data)(ar, t, co.file_version); moveable_objects_recent = this_id; } inline const basic_pointer_iserializer * basic_iarchive_impl::load_pointer( basic_iarchive &ar, void * & t, const basic_pointer_iserializer * bpis_ptr, const basic_pointer_iserializer * (*finder)( const boost::serialization::extended_type_info & type_ ) ){ class_id_type cid; load(ar, cid); if(NULL_POINTER_TAG == cid){ t = NULL; return bpis_ptr; } // if its a new class type - i.e. never been registered if(class_id_type(cobject_info_set.size()) <= cid){ // if its either abstract if(NULL == bpis_ptr // or polymorphic || bpis_ptr->get_basic_serializer().is_polymorphic()){ // is must have been exported char key[BOOST_SERIALIZATION_MAX_KEY_SIZE]; class_name_type class_name(key); load(ar, class_name); // if it has a class name const serialization::extended_type_info *eti = NULL; if(0 != key[0]) eti = serialization::extended_type_info::find(key); if(NULL == eti) boost::throw_exception( archive_exception(archive_exception::unregistered_class) ); bpis_ptr = (*finder)(*eti); } assert(NULL != bpis_ptr); class_id_type new_cid = register_type(bpis_ptr->get_basic_serializer()); int i = cid; cobject_id_vector[i].bpis_ptr = bpis_ptr; assert(new_cid == cid); } int i = cid; cobject_id & co = cobject_id_vector[i]; bpis_ptr = co.bpis_ptr; load_preamble(ar, co); // extra line to evade borland issue const bool tracking = co.tracking_level; // if we're tracking and the pointer has already been read if(tracking && ! track(ar, t)) // we're done return bpis_ptr; // save state state_saver<object_id_type> w_start(moveable_objects_start); if(! tracking){ bpis_ptr->load_object_ptr(ar, t, co.file_version); } else{ state_saver<void *> x(pending_object); state_saver<const basic_iserializer *> y(pending_bis); state_saver<version_type> z(pending_version); pending_bis = & bpis_ptr->get_basic_serializer(); pending_version = co.file_version; // predict next object id to be created const unsigned int ui = object_id_vector.size(); state_saver<object_id_type> w_end(moveable_objects_end); // because the following operation could move the items // don't use co after this // add to list of serialized objects so that we can properly handle // cyclic strucures object_id_vector.push_back(aobject(t, cid)); bpis_ptr->load_object_ptr( ar, object_id_vector[ui].address, co.file_version ); t = object_id_vector[ui].address; assert(NULL != t); // and add to list of created pointers created_pointers.push_back(created_pointer_type(cid, t)); } return bpis_ptr; } ////////////////////////////////////////////////////////////////////// // implementation of basic_iarchive functions BOOST_ARCHIVE_DECL(void) basic_iarchive::next_object_pointer(void *t){ pimpl->next_object_pointer(t); } BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive::basic_iarchive(unsigned int flags) : pimpl(new basic_iarchive_impl(flags)) {} BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive::~basic_iarchive() { delete pimpl; } BOOST_ARCHIVE_DECL(void) basic_iarchive::set_library_version(unsigned int archive_library_version){ pimpl->set_library_version(archive_library_version); } BOOST_ARCHIVE_DECL(void) basic_iarchive::reset_object_address( const void * new_address, const void * old_address ){ pimpl->reset_object_address(new_address, old_address); } BOOST_ARCHIVE_DECL(void) basic_iarchive::load_object( void *t, const basic_iserializer & bis ){ pimpl->load_object(*this, t, bis); } // load a pointer object BOOST_ARCHIVE_DECL(const basic_pointer_iserializer *) basic_iarchive::load_pointer( void * &t, const basic_pointer_iserializer * bpis_ptr, const basic_pointer_iserializer * (*finder)( const boost::serialization::extended_type_info & type_ ) ){ return pimpl->load_pointer(*this, t, bpis_ptr, finder); } BOOST_ARCHIVE_DECL(void) basic_iarchive::register_basic_serializer(const basic_iserializer & bis){ pimpl->register_type(bis); } BOOST_ARCHIVE_DECL(void) basic_iarchive::lookup_basic_helper( const boost::serialization::extended_type_info * const eti, shared_ptr<void> & sph ){ pimpl->lookup_helper(eti, sph); } BOOST_ARCHIVE_DECL(void) basic_iarchive::insert_basic_helper( const boost::serialization::extended_type_info * const eti, shared_ptr<void> & sph ){ pimpl->insert_helper(eti, sph); } BOOST_ARCHIVE_DECL(void) basic_iarchive::delete_created_pointers() { pimpl->delete_created_pointers(); } BOOST_ARCHIVE_DECL(unsigned int) basic_iarchive::get_library_version() const{ return pimpl->m_archive_library_version; } BOOST_ARCHIVE_DECL(unsigned int) basic_iarchive::get_flags() const{ return pimpl->m_flags; } } // namespace detail } // namespace archive } // namespace boost
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 612 ] ] ]