blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
3da80434de0ef212175c12e2449c98153d430bfe
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/QtApp/QtExecute/src/OrzWindow.cpp
2b4272408403a8a4988d89eceb6cead8dc98406a
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,937
cpp
#include "OrzWindow.h" #include "QtExecute.h" #include "QtInputManager.h" #include "QTimer.h" #include <orz/View_OGRE3D/OgreGraphicsManager.h> #include <orz/Toolkit_Base/EventSystem/EventWorldUpdate.h> #include <orz/Toolkit_Base/DynLibManager.h> #include <orz/Toolkit_Base/LogManager.h> #include <orz/View_OGRE3D/OgreGraphicsManager.h> #include <orz/View_CEGUI/CEGUIManager.h> #include <orz/View_OIS/OISInputManager.h> #include <orz/View_Fmod/FmodSoundManager.h> //#include <orz/View_AomiUI/AomiUIManager.h> #include <orz/View_SingleChip/SingleChipManager.h> namespace Orz { class TheWindow:public WindowInterface { public: TheWindow(OrzWindow * window):_window(window) { } /** 得到窗口句柄 */ virtual size_t getHandle() { return (size_t)(HWND)_window->winId(); } /** 得到窗口宽度 */ virtual size_t getWidth() { return static_cast<size_t>(_window->width()); } /** 得到窗口高度 */ virtual size_t getHeight() { return static_cast<size_t>(_window->height()); } void resize(int width, int height) { _width = width; _height = height; _sizeChange(width, height); } private: int _width; int _height; OrzWindow * _window; }; } OrzWindow::OrzWindow(QWidget *parent, Qt::WFlags flags):QWidget(parent, flags | Qt::MSWindowsOwnDC),_init(false) { QPalette colourPalette = palette(); colourPalette.setColor(QPalette::Active, QPalette::WindowText, Qt::black); colourPalette.setColor(QPalette::Active, QPalette::Window, Qt::black); setPalette(colourPalette); _clock.restart(); _now =_clock.elapsed(); } OrzWindow::~OrzWindow() { } void OrzWindow::mousePressEvent(QMouseEvent* evt) { QtInputManager::getSingleton().mousePressEvent(evt); } void OrzWindow::mouseReleaseEvent(QMouseEvent* evt) { QtInputManager::getSingleton().mouseReleaseEvent(evt); } void OrzWindow::mouseMoveEvent(QMouseEvent* evt) { QtInputManager::getSingleton().mouseMoveEvent(evt); } void OrzWindow::wheelEvent(QWheelEvent* evt) { QtInputManager::getSingleton().wheelEvent(evt); } //void OrzWindow::resizeEvent(QResizeEvent* evt) //{ // //QtExecute::getSingleton().orzWindowResizeEvent(); //} //void OrzWindow::initializeGL(void) //{ // if(!_init) // { // _init = true; // _logic->load(); // // } //} QPaintEngine *OrzWindow:: paintEngine() const { return 0; } void OrzWindow::paintEvent(QPaintEvent* evt) { if(_init) { Orz::TimeType temp = _clock.elapsed(); if(_now > temp) { _now -= _clock.elapsed_max(); } Orz::TimeType interval = temp - _now; _now = temp; _system->update(interval); } } bool OrzWindow::init(void) { if(!_init) { //These attributes are the same as those use in a QGLWidget setAttribute(Qt::WA_PaintOnScreen); setAttribute(Qt::WA_NoSystemBackground); using namespace Orz; _system.reset(new SystemList<boost::mpl::list<SimpleTimerManager,OgreGraphicsManager, QtInputManager, /*PluginsManager,*/CEGUIManager, FmodSoundManager, SingleChipManager, EventWorldUpdate> >()); _system->setParame("w32_mouse",Orz::Variant(true)); _logic.reset(new LogicConfiger::LogicFacade()); LogicConfiger::ManualBuilder builder; // //增加两个个动态插件 builder.addPlugin("SanController"); builder.addPlugin("Model_Base"); builder.addPlugin("NetWheelDirector"); //builder.addPlugin("WheelAnimal2Model"); builder.addPlugin("SanModel"); builder.addPlugin("NewGameComponents"); builder.addPlugin("NewGameSceneComponent"); builder.addPlugin("GameNeedleComponent"); builder.addPlugin("GameDiamondComponent"); builder.addPlugin("VedioUIComponent"); //builder.addPlugin("CodingComponent"); //builder.addPlugin("MyJobComponent"); //设置大厅 builder.setTheater("TheaterBase","main"); builder.addDirector("WheelDirector","wheel"); builder.setActiveDirector("wheel"); _logic->building(builder); setMouseTracking(true); _window.reset(new Orz::TheWindow(this)); Orz::WeakWindowPtr win = Orz::WindowPtr(_window); _system->setParame<Orz::WeakWindowPtr>("WINDOW", win); _system->init(); _autoUpdateTimer = new QTimer; QObject::connect(_autoUpdateTimer, SIGNAL(timeout()), this, SLOT(update())); _autoUpdateTimer->setInterval(1); _init = true; bool ret = _logic->load(EventWorld::Parameter()); _autoUpdateTimer->start(); _clock.restart(); _now =_clock.elapsed(); return ret; return true; } return false; } void OrzWindow::shutdown(void) { _logic->unload(); _autoUpdateTimer->stop(); _system->shutdown(); } void OrzWindow::resizeEvent(QResizeEvent* evt) { if(_init) { if(width() == 0 || height() == 0) return; this->setVisible(false); _window->resize(width(), height()); this->setVisible(true); } }
[ [ [ 1, 218 ] ] ]
7f343b2c184321da89a511248b5286634fc0d48f
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch08/Fig08_07/fig08_07.cpp
3f097bd6648a42cc83402d4c3a1f866a613086b2
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
WINDOWS-1258
C++
false
false
1,787
cpp
// Fig. 8.7: fig08_07.cpp // Pass-by-reference with a pointer argument used to cube a // variable’s value. #include <iostream> using std::cout; using std::endl; void cubeByReference( int * ); // prototype int main() { int number = 5; cout << "The original value of number is " << number; cubeByReference( &number ); // pass number address to cubeByReference cout << "\nThe new value of number is " << number << endl; return 0; // indicates successful termination } // end main // calculate cube of *nPtr; modifies variable number in main void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr } // end function cubeByReference /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 41 ] ] ]
e3cf4aada5d4400b65a0b6b8bedfce70217e2b17
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Windows/include/WinBitmap.h
90941769e956e574923cfe76ba5a953cf38d3b9a
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,067
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WINBITMAP_H #define WINBITMAP_H #include <windows.h> #include <vector> #include "MapPlotter.h" namespace isab { /* header for a TGA (TARGA) File */ typedef struct { uint8 numCharsID; uint8 colorMapType; uint8 imageType; uint8 colorMapSpec[5]; uint16 xOrig; uint16 yOrig; uint16 imageWidth; uint16 imageHeight; uint8 bitsPerPixel; uint8 imageDesc; } TGAHEADER; typedef struct { uint8 red; uint8 green; uint8 blue; } PIXEL; class WinBitmap : public BitMap { /** data **/ private: /* the bitmap */ HBITMAP m_bmp; /* the mask */ HBITMAP m_mask; /* the old bitmap from the DC */ HBITMAP m_oldBmp; /* it's DC */ HDC m_dc; /* dimensions of bitmap */ int32 m_width, m_height; /* flag which indicates whether the BMP is maked or not */ bool m_isMasked; /// The color map. vector<PIXEL> m_colorMap; /** methods **/ private: /* private constructor */ WinBitmap(); /* second-phase constrcutor */ bool construct(const byte* dataBuf, uint32 nbrBytes); /** * Help method. * Reads the color map data if any is present. * @param tgaHeader The tga header. * @param colorData Pointer to the color map data. * @return How much colormap data that has been read, i.e. * how much the colorData should be increased in order * to point at the color data instead of at the color * map. */ int readColorMapData( const TGAHEADER& tgaHeader, const byte* colorData ); public: /* allocator */ static WinBitmap* allocate(const byte* dataBuf, uint32 nbrBytes); /* destructor */ ~WinBitmap(); /* gets width of bitmap */ int32 width() const { return(m_width); } /* gets height of bitmap */ int32 height() const { return(m_height); } /* gets the handle to the DC */ HDC getDC() const { return(m_dc); } /* gets the mask bitmap */ HBITMAP getMask() const { return(m_mask); } /* returns true, if the image is masked, false otherwise */ bool isMasked() const { return(m_isMasked); } }; }; #endif
[ [ [ 1, 130 ] ] ]
7cfca33debd6a372b77349117aeb722e23376f1a
96a48df2a03d542068be2cbe140500bc99f52725
/matchingmodule.cpp
6371c0afe39a616d48dd7355f0a885429220190f
[]
no_license
noahkong/stereocam
d0bbffafba8815ac3531dd59c5f270b67b52a11d
19749024834ed11767c114370fc55aeb41f75e2c
refs/heads/master
2020-05-30T14:50:32.032286
2011-03-26T18:51:33
2011-03-26T18:51:33
32,440,548
0
0
null
null
null
null
UTF-8
C++
false
false
5,162
cpp
#include "matchingmodule.hpp" #include "property.hpp" #include <opencv2/highgui/highgui.hpp> #include <QVBoxLayout> #include <QRadioButton> #include <QLabel> #include <QCheckBox> #include <QSpinBox> #include <QComboBox> #include <QPushButton> using namespace std; using namespace cv; MatchingModule::MatchingModule(QObject *parent) : QObject(parent){ chosenAlgorithm = -1; } MatchingModule::~MatchingModule(){ for(int i = 0; i < algorithms.size(); ++i){ delete algorithms[i]; } delete buttonGroup; } void MatchingModule::init(Settings * sets, QDialog * dialog){ settings = sets; chooseDialog = new QDialog(dialog); chooseDialog->setWindowTitle("Stereo dopasowanie"); initAlgorithms(); initChooseWindow(); initWindows(); } void MatchingModule::initAlgorithms(){ StereoMatching * bm = new StereoMatchingBM(); bm->id = 0; StereoMatching * sgbm = new StereoMatchingSGBM(); sgbm->id = 1; StereoMatching * gc = new StereoMatchingGC(); gc->id = 2; algorithms.push_back(bm); algorithms.push_back(sgbm); algorithms.push_back(gc); chosenAlgorithm = 0; } void MatchingModule::initChooseWindow(){ QVBoxLayout *layout = new QVBoxLayout; buttonGroup = new QButtonGroup; for(int i = 0; i < algorithms.size(); ++i){ QRadioButton * button = new QRadioButton(QString(algorithms[i]->getName()), chooseDialog); layout->addWidget(button); buttonGroup->addButton(button); if(chosenAlgorithm == i){ button->setChecked(true); } buttonGroup->setId(button, i); } connect ( buttonGroup, SIGNAL(buttonClicked (int)), this, SLOT(algorithmChanged (int))); chooseDialog->setLayout(layout); chooseDialog->setMinimumWidth(200); chooseDialog->adjustSize(); chooseDialog->move(10,20); } void MatchingModule::initWindows(){ for(int i = 0; i < algorithms.size(); ++i){ QDialog * setsDialog = new QDialog(chooseDialog); QVBoxLayout *layout = new QVBoxLayout; QPushButton * buttonApply = new QPushButton("Zastosuj", chooseDialog); connect(buttonApply, SIGNAL(clicked()), this, SLOT(applyValues())); int propsCounter = algorithms[i]->properties.size(); for(int j = 0; j < propsCounter; ++j){ Property * prop = algorithms[i]->properties[j]; addGuiForProperty(setsDialog, layout, prop, buttonApply); } buttonApply->setEnabled(false); layout->addWidget(buttonApply); applyButtons.push_back(buttonApply); setsDialog->setWindowTitle(algorithms[i]->getName()); setsDialog->setLayout(layout); setsDialog->setMinimumWidth(200); setsDialog->adjustSize(); setsDialog->move(10,150); setsDialogs.push_back(setsDialog); } } void MatchingModule::addGuiForProperty(QDialog * parent, QLayout * layout, Property * prop, QPushButton * button){ Property::TYPE theType = prop->getType(); switch(theType){ case Property::INT:{ QLabel * label = new QLabel(prop->getName(), parent); layout->addWidget(label); QSpinBox * spin = new QSpinBox(parent); spin->setRange(prop->minValue, prop->maxValue); spin->setValue(prop->getValue()); spin->setSingleStep(prop->step); layout->addWidget(spin); connect(spin, SIGNAL(valueChanged(int)), prop, SLOT(setValueToChange(int))); connect(spin, SIGNAL(valueChanged(int)), this, SLOT(enableButton(int))); break; } case Property::BOOL:{ QCheckBox * checkBox = new QCheckBox(prop->getName(), parent); checkBox->setChecked((bool)prop->getValue()); layout->addWidget(checkBox); connect(checkBox, SIGNAL(stateChanged(int)), prop, SLOT(setValueToChange(int))); connect(checkBox, SIGNAL(stateChanged(int)), this, SLOT(enableButton(int))); break; } case Property::DISCRETE:{ QLabel * label = new QLabel(prop->getName(), parent); layout->addWidget(label); QComboBox * combo = new QComboBox(parent); int * values = prop->tableValues; for(int i = 0; i < prop->maxValue; ++i){ combo->addItem(QString().setNum(values[i])); } combo->setCurrentIndex(prop->getValue()); connect(combo, SIGNAL(currentIndexChanged(int)), prop, SLOT(setValueToChange(int))); connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(enableButton(int))); layout->addWidget(combo); break; } } } IplImage * MatchingModule::match(IplImage * frame1, IplImage * frame2){ Mat retImage; algorithms[chosenAlgorithm]->exec(Mat(frame1), Mat(frame2), retImage); return NULL; } /*********** obsluga zdarzen *************/ void MatchingModule::algorithmChanged(int id){ if(id == chosenAlgorithm){ return; } setsDialogs[chosenAlgorithm]->hide(); chosenAlgorithm = id; setsDialogs[chosenAlgorithm]->show(); } void MatchingModule::applyValues(){ algorithms[chosenAlgorithm]->setPropertiesWereChanged(); Mat a, b, c; algorithms[chosenAlgorithm]->exec(a,b,c); applyButtons[chosenAlgorithm]->setEnabled(false); } void MatchingModule::enableButton(int){ applyButtons[chosenAlgorithm]->setEnabled(true); }
[ "[email protected]@e744e3f1-1be2-aab4-d40b-2ba3014caec9" ]
[ [ [ 1, 209 ] ] ]
8204c6d615d9efedd108c9a2648a8b1407e44863
906e87b1936397339734770be45317f06fe66e6e
/include/TGRenderer.h
1fe9275ddbb794eb71aee88d4628ef53ff8fb671
[]
no_license
kcmohanprasad/tgui
03c1ab47e9058bc763b7e6ffc21a37b4358369bf
9f9cf391fa86b99c7d606c4d196e512a7b06be95
refs/heads/master
2021-01-10T08:52:18.629088
2007-05-17T04:42:58
2007-05-17T04:42:58
52,069,498
0
0
null
null
null
null
UTF-8
C++
false
false
9,414
h
//----------------------------------------------------------------------------- // This source file is part of TGUI (Tiny GUI) // // Copyright (c) 2006-2007 Tubras Software, Ltd // Also see acknowledgements in Readme.html // // 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 __TGRENDERER_H__ #define __TGRENDERER_H__ namespace TGUI { class TGTexture; class TGRenderer; class TGBrush; typedef Ogre::SharedPtr<TGBrush> TGSBrush; struct TGQuadVertex { TGReal x, y, z; // The position for the vertex. Ogre::RGBA diffuse; // colour of the vertex TGReal tu1, tv1; // texture coordinates }; struct TGQuadInfo { bool isClipped; Ogre::TexturePtr texture; TGRect position; TGQuadVertex lpos[6]; TGReal z; TGRect texPosition; uint32 topLeftCol; uint32 topRightCol; uint32 bottomLeftCol; uint32 bottomRightCol; TGQuadInfo(); TGQuadInfo(const TGQuadInfo& rhs); TGQuadInfo& TGQuadInfo::operator= (const TGQuadInfo& rhs); bool operator<(const TGQuadInfo& other) const { // this is intentionally reversed. return z > other.z; } }; typedef std::vector<TGQuadInfo> TGQuadList; class _TGUIExport TGRQListener : public Ogre::RenderQueueListener { public: TGRQListener(TGRenderer* renderer, Ogre::uint8 queueID, bool postQueue) { m_renderer = renderer; m_queueID = queueID; m_postQueue = postQueue; } virtual ~TGRQListener() {} virtual void renderQueueStarted(Ogre::uint8 id, const Ogre::String& invocation, bool& skipThisQueue); virtual void renderQueueEnded(Ogre::uint8 id, const Ogre::String& invocation, bool& repeatThisQueue); void setTargetRenderQueue(Ogre::uint8 queueID) {m_queueID = queueID;} void setPostRenderQueue(bool postQueue) {m_postQueue = postQueue;} private: TGRenderer* m_renderer; // TGUI renderer object for Ogre. Ogre::uint8 m_queueID; // ID of the queue that we are hooked into bool m_postQueue; // true if we render after everything else in our queue. }; struct TGClipArea { int x1; int y1; int x2; int y2; }; typedef std::vector<TGClipArea*> TGClipList; class _TGUIExport TGRenderer { unsigned int texture; void* rendererListEntry; bool enabled; TGClipList m_clipList; TGQuadInfo quad; public: TGRenderer(Ogre::RenderWindow* window, Ogre::uint8 queue_id = Ogre::RENDER_QUEUE_OVERLAY, bool post_queue = false); TGRenderer(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, Ogre::SceneManager* scene_manager); virtual ~TGRenderer(); void openClipArea(int x1, int y1, int x2, int y2); void closeClipArea(); void resetClipping(); virtual TGQuadInfo addQuad(const TGRect& dest_rect, TGReal z, const TGSBrush brush); virtual TGQuadInfo addLine(const TGRect& dest_rect, TGReal z, const TGSBrush brush, int thickness); virtual TGQuadInfo addTri(const TGRect& dest_rect, TGReal z, const TGSBrush brush, int pointDir); void renderQuadDirect(const TGRect& dest_rect, TGReal z, TGSBrush brush); virtual void doRender(TGQuadList& quadList); virtual TGTexture* createTexture(void); virtual TGTexture* createTexture(const TGString& filename, const TGString& resourceGroup = "General"); virtual TGTexture* createTexture(TGReal size); virtual void destroyTexture(TGTexture* texture); virtual void destroyAllTextures(void); virtual bool isQueueingEnabled(void) const {return m_queueing;} virtual TGReal getWidth(void) const {return m_displayArea.getWidth();} virtual TGReal getHeight(void) const {return m_displayArea.getHeight();} virtual TGSize getSize(void) const {return m_displayArea.getSize();} virtual TGRect getRect(void) const {return m_displayArea;} virtual uint getMaxTextureSize(void) const {return 2048;} virtual uint getHorzScreenDPI(void) const {return 96;} virtual uint getVertScreenDPI(void) const {return 96;} void setTargetSceneManager(Ogre::SceneManager* scene_manager); void setTargetRenderQueue(Ogre::uint8 queue_id, bool post_queue); TGTexture* createTexture(Ogre::TexturePtr& texture); void setDisplaySize(const TGSize& sz); void resetZValue(void) {d_current_z = GuiZInitialValue;} void advanceZValue(void) {d_current_z -= GuiZElementStep;} TGReal getCurrentZ(void) const {return d_current_z;} TGReal getZLayer(uint layer) const {return d_current_z - ((TGReal)layer * GuiZLayerStep);} private: static const TGReal GuiZInitialValue; // Initial value to use for 'z' each frame. static const TGReal GuiZElementStep; // Value to step 'z' for each GUI element. static const TGReal GuiZLayerStep; // Value to step 'z' for each GUI layer. TGReal d_current_z; //!< The current z co-ordinate value. static const size_t VERTEX_PER_QUAD; // number of vertices per quad static const size_t VERTEX_PER_TRIANGLE; // number of vertices for a triangle static const size_t VERTEXBUFFER_INITIAL_CAPACITY; // initial capacity of the allocated vertex buffer static const size_t UNDERUSED_FRAME_THRESHOLD; // number of frames to wait before shrinking buffer void initRenderStates(void); bool clipQuad(TGClipArea* clip, TGRect& drect, TGRect& tRect, TGColourRect colours); uint32 colourToOgre(const TGColour& col) const; void constructor_impl(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue); TGRect m_displayArea; bool m_queueing; // setting for queueing control. // Ogre specific bits. Ogre::Root* m_ogreRoot; // pointer to the Ogre root object that we attach to Ogre::RenderSystem* m_renderSys; // Pointer to the render system for Ogre. Ogre::uint8 m_queue_id; // ID of the queue that we are hooked into Ogre::TexturePtr m_currTexture; // currently set texture; Ogre::RenderOperation m_render_op; // Ogre render operation we use to do our stuff. Ogre::HardwareVertexBufferSharedPtr m_buffer; // vertex buffer to queue sprite rendering size_t m_underused_framecount; //!< Number of frames elapsed since buffer utilization was above half the capacity Ogre::RenderOperation m_direct_render_op; // Renderop for cursor Ogre::HardwareVertexBufferSharedPtr m_direct_buffer; //!< Renderop for cursor Ogre::SceneManager* m_sceneMgr; // The scene manager we are hooked into. Ogre::LayerBlendModeEx m_colourBlendMode; // Controls colour blending mode used. Ogre::LayerBlendModeEx m_alphaBlendMode; // Controls alpha blending mode used. Ogre::TextureUnitState::UVWAddressingMode m_uvwAddressMode; TGRQListener* m_ourlistener; bool m_post_queue; // true if we render after everything else in our queue. size_t m_bufferPos; // index into buffer where next vertex should be put. bool m_modified; // true when data in quad list is modified. TGPoint m_texelOffset; // Offset required for proper texel mapping. std::list<TGTexture*> m_texturelist; // List used to track textures. }; } #endif
[ "pc0der@a5263bde-0223-0410-8bbb-1954fdd97a2f" ]
[ [ [ 1, 206 ] ] ]
de5b29430d3a30df86250247fe4accc4384733c6
c3db5e9c2778ed2e37edb5483f9d86a9b6d95aca
/PSGamepad/PSGamepad.h
2929b357eee45b83e1dd68bb0c8615e5e62d482f
[]
no_license
marciopocebon/InputDevices
e859bda8c70571fe1d91df73d17428c39240d220
50363fe7359f921bb0b39e87548a7dc759a07230
refs/heads/master
2020-06-23T15:07:44.829866
2010-11-04T03:17:04
2010-11-04T03:17:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
h
// -*- C++ -*- /*! * @file PSGamepad.h * @brief Playstation Gamepad class * @date $Date$ * * $Id$ */ #ifndef PSGAMEPAD_H #define PSGAMEPAD_H #include <iostream> #define DIRECTINPUT_VERSION 0x0800 //#define _CRT_SECURE_NO_DEPRECATE #ifndef _WIN32_DCOM #define _WIN32_DCOM #endif #include <windows.h> #pragma warning( disable : 4996 ) // disable deprecated warning #include <strsafe.h> #pragma warning( default : 4996 ) // #include "resource.h" // include for Direct X #include <dinput.h> #include <dinputd.h> #include <vector> using namespace std; class PSGamepad { public: PSGamepad(); ~PSGamepad(); HRESULT InitDirectInput(int max, int min, int threshold); HRESULT UpdateInputState(std::vector<float>& data, const std::vector<float>& rate); VOID FreeDirectInput(); struct DI_ENUM_CONTEXT { DIJOYCONFIG* pPreferredJoyCfg; bool bPreferredJoyCfgValid; }; private: }; extern "C" { BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext ); }; #endif // PSGAMEPAD_H
[ "kurihara@49ca9add-c54f-4622-9f17-f1590135c5e3" ]
[ [ [ 1, 61 ] ] ]
fa7a6c70a68dc982a09fd38f269bcf5f32f97870
906e87b1936397339734770be45317f06fe66e6e
/src/TGImage.cpp
096a46dfcc353873632f51552852fb3e91ab2961
[]
no_license
kcmohanprasad/tgui
03c1ab47e9058bc763b7e6ffc21a37b4358369bf
9f9cf391fa86b99c7d606c4d196e512a7b06be95
refs/heads/master
2021-01-10T08:52:18.629088
2007-05-17T04:42:58
2007-05-17T04:42:58
52,069,498
0
0
null
null
null
null
UTF-8
C++
false
false
5,470
cpp
//----------------------------------------------------------------------------- // This source file is part of TGUI (Tiny GUI) // // Copyright (c) 2006-2007 Tubras Software, Ltd // Also see acknowledgements in Readme.html // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //----------------------------------------------------------------------------- #include <tgui.h> #include "bitmaps/new.c" #include "bitmaps/open.c" #include "bitmaps/save.c" #include "bitmaps/saveas.c" #include "bitmaps/quit.c" #include "bitmaps/win.c" namespace TGUI { extern TGColour gColor; //----------------------------------------------------------------------- // T G I m a g e //----------------------------------------------------------------------- TGImage::TGImage(TGControl *parent, TGString name, TGString fname, TGString resourceGroup) : TGControl(parent, name) { int x1 = 0, y1 = 0, x2, y2; m_width = 0; m_height = 0; if (!fname.empty()) { if(resourceGroup.empty()) { resourceGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str(); } texture = getRenderer()->createTexture(fname,resourceGroup); m_width = texture->getWidth(); m_height = texture->getHeight(); x2 = x1 + (int)m_width - 1; y2 = y1 + (int)m_height - 1; } else { texture = NULL; x2 = x1 + 9; y2 = y1 + 9; } m_brush.bind(new TGBrush(texture)); setBounds(x1, y1, x2, y2); } //----------------------------------------------------------------------- // T G I m a g e //----------------------------------------------------------------------- TGImage::TGImage(TGControl *parent, TGString name, TGTexture* texture) : TGControl(parent, name) { this->texture = texture; m_width = texture->getWidth(); m_height = texture->getHeight(); x2 = x1 + (int)m_width - 1; y2 = y1 + (int)m_height - 1; setBounds(x1,y1,x2,y2); m_brush.bind(new TGBrush(texture)); } //----------------------------------------------------------------------- // ~ T G I m a g e //----------------------------------------------------------------------- TGImage::~TGImage() { //getRenderer()->destroyTexture(texture); } //----------------------------------------------------------------------- // s e t T e x t u r e //----------------------------------------------------------------------- void TGImage::setTexture(TGTexture *newTexture, bool resize) { texture = newTexture; m_width = texture->getWidth(); m_height = texture->getHeight(); if (resize) this->resize((int)m_width, (int)m_height); } //----------------------------------------------------------------------- // s e t T e x t u r e //----------------------------------------------------------------------- void TGImage::setTexture(TGString fname, TGString resourceGroup, bool resize) { if(resourceGroup.empty()) { resourceGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str(); } texture = getRenderer()->createTexture(fname,resourceGroup); m_width = texture->getWidth(); m_height = texture->getHeight(); if(resize) this->resize((int)m_width,(int)m_height); } //----------------------------------------------------------------------- // s e t A l p h a //----------------------------------------------------------------------- void TGImage::setAlpha(float value) { m_brush->setAlpha(value); redraw(); } //----------------------------------------------------------------------- // r e n d e r //----------------------------------------------------------------------- void TGImage::render() { if(isRenderCached()) return; int x1, y1, x2, y2; getBounds(x1, y1, x2, y2); fillRect(x1, y1, x2, y2, m_brush); TGControl::render(); } }
[ "pc0der@a5263bde-0223-0410-8bbb-1954fdd97a2f" ]
[ [ [ 1, 144 ] ] ]
9846fd5fef60b886b927f088d663d2f4606010fa
d826e0dcc5b51f57101f2579d65ce8e010f084ec
/transcad/PmeStdSolidFilletConstantFeatureAPI.cpp
db2d00c3a331f56abeeb8f4d9c7cf4e34ecb521a
[]
no_license
crazyhedgehog/macro-parametric
308d9253b96978537a26ade55c9c235e0442d2c4
9c98d25e148f894b45f69094a4031b8ad938bcc9
refs/heads/master
2020-05-18T06:01:30.426388
2009-06-26T15:00:02
2009-06-26T15:00:02
38,305,994
0
0
null
null
null
null
UTF-8
C++
false
false
4,420
cpp
#include "stdafx.h" #include ".\PmeStdSolidFilletConstantFeatureAPI.h" #include ".\PmeReferences.h" #include ".\PmeHandleMacro.h" #include ".\PmePart.h" #include ".\PmeStdSolidFilletConstantFeature.h" #include ".\PmeFeatures.h" #include ".\PmeSolid.h" #include ".\PmePartAPI.h" #include ".\PmeUpdateInfoAPI.h" #include ".\PmeExceptionTest.h" #include ".\PmeArgumentTypeException.h" #include ".\PmeArgumentNullException.h" #include ".\PmeReference.h" #include ".\PmeUtility.h" void PmeStdSolidFilletConstantFeatureAPI::Create ( PmeHPart hPart, const CString & name, PmeHReferences hFilletEdges, double radius, PmePropagationType propagation, PmeHFeature & hFeature ) { PmeThrowExceptionIf<PmeArgumentNullException>(!hPart); PmePart * pPart = PME_HANDLE2PART(hPart); PmeThrowExceptionIf<PmeArgumentNullException>(!hFilletEdges); PmeReferences * pFilletEdges = PME_HANDLE2REFERENCES(hFilletEdges); PmeFeatures * pFeatures = pPart->GetFeatures(); PmeStdSolidFilletConstantFeature * pFeature = new PmeStdSolidFilletConstantFeature(pPart, pFilletEdges, radius, propagation); if(name.IsEmpty()) pFeature->GiveDefaultName(); else pFeature->SetName(name); pFeatures->Add(pFeature); pPart->UpdateLast(); hFeature = PME_FEATURE2HANDLE(pFeature); if(hFeature) { PME_UPDATE_FEATURE(hPart, hFeature, PmeUpdateState_Add); } PmeHExplicitModelObject hSolid = PME_EXPLICITMODELOBJECT2HANDLE(pFeature->GetSolid()); if(hSolid) { PME_UPDATE_EXPLICITMODELOBJECT(hPart, hSolid, PmeUpdateState_Update); } } void PmeStdSolidFilletConstantFeatureAPI::GetFilletEdges(PmeHFeature hFeature, PmeHReferences & hFilletEdges) { PmeThrowExceptionIf<PmeArgumentNullException>(!hFeature); PmeFeature * pFeature = PME_HANDLE2FEATURE(hFeature); PmeThrowExceptionIf<PmeArgumentTypeException>(!pFeature->IsInstanceOf(PME_RUNTIME_TYPE(PmeStdSolidFilletConstantFeature))); PmeStdSolidFilletConstantFeature * pStdSolidFilletConstantFeature = static_cast<PmeStdSolidFilletConstantFeature *>(pFeature); PmeReferences * pFilletEdges = pStdSolidFilletConstantFeature->GetFilletEdges(); hFilletEdges = PME_REFERENCES2HANDLE(pFilletEdges); } void PmeStdSolidFilletConstantFeatureAPI::GetRadius(PmeHFeature hFeature, double & radius) { PmeThrowExceptionIf<PmeArgumentNullException>(!hFeature); PmeFeature * pFeature = PME_HANDLE2FEATURE(hFeature); PmeThrowExceptionIf<PmeArgumentTypeException>(!pFeature->IsInstanceOf(PME_RUNTIME_TYPE(PmeStdSolidFilletConstantFeature))); PmeStdSolidFilletConstantFeature * pStdSolidFilletConstantFeature = static_cast<PmeStdSolidFilletConstantFeature *>(pFeature); radius = pStdSolidFilletConstantFeature->GetRadius(); } void PmeStdSolidFilletConstantFeatureAPI::GetStartPoint(PmeHFeature hFeature, SPAposition & position) { PmeThrowExceptionIf<PmeArgumentNullException>(!hFeature); PmeFeature * pFeature = PME_HANDLE2FEATURE(hFeature); PmeThrowExceptionIf<PmeArgumentTypeException>(!pFeature->IsInstanceOf(PME_RUNTIME_TYPE(PmeStdSolidFilletConstantFeature))); PmeStdSolidFilletConstantFeature * pStdSolidFilletConstantFeature = static_cast<PmeStdSolidFilletConstantFeature *>(pFeature); position = pStdSolidFilletConstantFeature->GetStartPoint(); } void PmeStdSolidFilletConstantFeatureAPI::GetEndPoint(PmeHFeature hFeature, SPAposition & position) { PmeThrowExceptionIf<PmeArgumentNullException>(!hFeature); PmeFeature * pFeature = PME_HANDLE2FEATURE(hFeature); PmeThrowExceptionIf<PmeArgumentTypeException>(!pFeature->IsInstanceOf(PME_RUNTIME_TYPE(PmeStdSolidFilletConstantFeature))); PmeStdSolidFilletConstantFeature * pStdSolidFilletConstantFeature = static_cast<PmeStdSolidFilletConstantFeature *>(pFeature); position = pStdSolidFilletConstantFeature->GetEndPoint(); } void PmeStdSolidFilletConstantFeatureAPI::GetPropagationType(PmeHFeature hFeature, PmePropagationType & propagation) { PmeThrowExceptionIf<PmeArgumentNullException>(!hFeature); PmeFeature * pFeature = PME_HANDLE2FEATURE(hFeature); PmeThrowExceptionIf<PmeArgumentTypeException>(!pFeature->IsInstanceOf(PME_RUNTIME_TYPE(PmeStdSolidFilletConstantFeature))); PmeStdSolidFilletConstantFeature * pStdSolidFilletConstantFeature = static_cast<PmeStdSolidFilletConstantFeature *>(pFeature); propagation = pStdSolidFilletConstantFeature->GetPropagation(); }
[ "surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e" ]
[ [ [ 1, 106 ] ] ]
fa9d390333940d20efe72b962dfb245c48270571
b8abaaf2f7a1f94efe3bbc0d14ca49228471b43f
/libs/Box2D/Dynamics/b2Fixture.h
ed65bbe3ccfe847249e82547e9592b95def05e6d
[ "Zlib" ]
permissive
julsam/Momoko-Engine
e8cf8a2ad4de6b3925c8c85dc66272e7602e7e73
7503a2a81d53bf569eb760c890158d4f38d9baf9
refs/heads/master
2021-01-22T12:08:41.642354
2011-04-12T11:12:21
2011-04-12T11:12:21
1,494,202
2
0
null
null
null
null
UTF-8
C++
false
false
8,894
h
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_FIXTURE_H #define B2_FIXTURE_H #include "b2Body.h" #include "../Collision/b2Collision.h" #include "../Collision/Shapes/b2Shape.h" class b2BlockAllocator; class b2Body; class b2BroadPhase; /// This holds contact filtering data. struct b2Filter { /// The collision category bits. Normally you would just set one bit. uint16 categoryBits; /// The collision mask bits. This states the categories that this /// shape would accept for collision. uint16 maskBits; /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). Zero means no collision group. Non-zero group /// filtering always wins against the mask bits. int16 groupIndex; }; /// A fixture definition is used to create a fixture. This class defines an /// abstract fixture definition. You can reuse fixture definitions safely. struct b2FixtureDef { /// The constructor sets the default fixture definition values. b2FixtureDef() { shape = NULL; userData = NULL; friction = 0.2f; restitution = 0.0f; density = 0.0f; filter.categoryBits = 0x0001; filter.maskBits = 0xFFFF; filter.groupIndex = 0; isSensor = false; } virtual ~b2FixtureDef() {} /// The shape, this must be set. The shape will be cloned, so you /// can create the shape on the stack. const b2Shape* shape; /// Use this to store application specific fixture data. void* userData; /// The friction coefficient, usually in the range [0,1]. float32 friction; /// The restitution (elasticity) usually in the range [0,1]. float32 restitution; /// The density, usually in kg/m^2. float32 density; /// A sensor shape collects contact information but never generates a collision /// response. bool isSensor; /// Contact filtering data. b2Filter filter; }; /// A fixture is used to attach a shape to a body for collision detection. A fixture /// inherits its transform from its parent. Fixtures hold additional non-geometric data /// such as friction, collision filters, etc. /// Fixtures are created via b2Body::CreateFixture. /// @warning you cannot reuse fixtures. class b2Fixture { public: /// Get the type of the child shape. You can use this to down cast to the concrete shape. /// @return the shape type. b2Shape::Type GetType() const; /// Get the child shape. You can modify the child shape, however you should not change the /// number of vertices because this will crash some collision caching mechanisms. /// Manipulating the shape may lead to non-physical behavior. b2Shape* GetShape(); const b2Shape* GetShape() const; /// Set if this fixture is a sensor. void SetSensor(bool sensor); /// Is this fixture a sensor (non-solid)? /// @return the true if the shape is a sensor. bool IsSensor() const; /// Set the contact filtering data. This will not update contacts until the next time /// step when either parent body is active and awake. void SetFilterData(const b2Filter& filter); /// Get the contact filtering data. const b2Filter& GetFilterData() const; /// Get the parent body of this fixture. This is NULL if the fixture is not attached. /// @return the parent body. b2Body* GetBody(); const b2Body* GetBody() const; /// Get the next fixture in the parent body's fixture list. /// @return the next shape. b2Fixture* GetNext(); const b2Fixture* GetNext() const; /// Get the user data that was assigned in the fixture definition. Use this to /// store your application specific data. void* GetUserData() const; /// Set the user data. Use this to store your application specific data. void SetUserData(void* data); /// Test a point for containment in this fixture. /// @param xf the shape world transform. /// @param p a point in world coordinates. bool TestPoint(const b2Vec2& p) const; /// Cast a ray against this shape. /// @param output the ray-cast results. /// @param input the ray-cast input parameters. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; /// Get the mass data for this fixture. The mass data is based on the density and /// the shape. The rotational inertia is about the shape's origin. This operation /// may be expensive. void GetMassData(b2MassData* massData) const; /// Set the density of this fixture. This will _not_ automatically adjust the mass /// of the body. You must call b2Body::ResetMassData to update the body's mass. void SetDensity(float32 density); /// Get the density of this fixture. float32 GetDensity() const; /// Get the coefficient of friction. float32 GetFriction() const; /// Set the coefficient of friction. void SetFriction(float32 friction); /// Get the coefficient of restitution. float32 GetRestitution() const; /// Set the coefficient of restitution. void SetRestitution(float32 restitution); /// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// If you need a more accurate AABB, compute it using the shape and /// the body transform. const b2AABB& GetAABB() const; protected: friend class b2Body; friend class b2World; friend class b2Contact; friend class b2ContactManager; b2Fixture(); ~b2Fixture(); // We need separation create/destroy functions from the constructor/destructor because // the destructor cannot access the allocator (no destructor arguments allowed by C++). void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); void Destroy(b2BlockAllocator* allocator); // These support body activation/deactivation. void CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf); void DestroyProxy(b2BroadPhase* broadPhase); void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); b2AABB m_aabb; float32 m_density; b2Fixture* m_next; b2Body* m_body; b2Shape* m_shape; float32 m_friction; float32 m_restitution; int32 m_proxyId; b2Filter m_filter; bool m_isSensor; void* m_userData; }; inline b2Shape::Type b2Fixture::GetType() const { return m_shape->GetType(); } inline b2Shape* b2Fixture::GetShape() { return m_shape; } inline const b2Shape* b2Fixture::GetShape() const { return m_shape; } inline bool b2Fixture::IsSensor() const { return m_isSensor; } inline const b2Filter& b2Fixture::GetFilterData() const { return m_filter; } inline void* b2Fixture::GetUserData() const { return m_userData; } inline void b2Fixture::SetUserData(void* data) { m_userData = data; } inline b2Body* b2Fixture::GetBody() { return m_body; } inline const b2Body* b2Fixture::GetBody() const { return m_body; } inline b2Fixture* b2Fixture::GetNext() { return m_next; } inline const b2Fixture* b2Fixture::GetNext() const { return m_next; } inline void b2Fixture::SetDensity(float32 density) { b2Assert(b2IsValid(density) && density >= 0.0f); m_density = density; } inline float32 b2Fixture::GetDensity() const { return m_density; } inline float32 b2Fixture::GetFriction() const { return m_friction; } inline void b2Fixture::SetFriction(float32 friction) { m_friction = friction; } inline float32 b2Fixture::GetRestitution() const { return m_restitution; } inline void b2Fixture::SetRestitution(float32 restitution) { m_restitution = restitution; } inline bool b2Fixture::TestPoint(const b2Vec2& p) const { return m_shape->TestPoint(m_body->GetTransform(), p); } inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const { return m_shape->RayCast(output, input, m_body->GetTransform()); } inline void b2Fixture::GetMassData(b2MassData* massData) const { m_shape->ComputeMass(massData, m_density); } inline const b2AABB& b2Fixture::GetAABB() const { return m_aabb; } #endif
[ [ [ 1, 326 ] ] ]
cb4753558fab513fdbfc00a9aeaedac3d0e860a3
ee279e11dfed8540dc55bb6be48e8534942d0029
/Fiew/Cacher.h
f4421fe9696cdfcc6048faa211759ebd37f0ae3f
[]
no_license
xuxiandi/fiew-image-viewer
c5fc61ff6db3dc1571b5b97b5e5eb96c46cbf2c9
a1bc9ca1ed63afb33418df4f9032454ad8805fad
refs/heads/master
2021-01-18T09:24:43.933788
2009-02-11T17:07:31
2009-02-11T17:07:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,467
h
class FwCHAR; class Catalog; class File; using namespace Gdiplus; class Cell { private: File *file; Bitmap *thumb; IStream *stream; public: Cell(File *file, byte *data); Cell(File *file); ~Cell(); File *getFile(); Image *getImage(); Bitmap *getImageThumb(); Bitmap *getImageThumb(int width, int height); IStream *getStream(); bool isLoaded(); Cell *loadThumb(int load); private: bool loadStream(byte *data, DWORD len); }; class Cacher { private: List<Cell> *cache; Catalog *source; Core *core; int full; protected: HANDLE mut_cache, mut_bool; HANDLE mut_initloop, mut_initterminator; HANDLE mut_nextloop, mut_nextstep, mut_nextterminator; HANDLE mut_prevloop, mut_prevstep, mut_prevterminator; HANDLE thrd_init, thrd_next, thrd_prev; HANDLE sem_nexts, sem_prevs, sem_nextlock, sem_prevlock; public: Cacher(Core *core); ~Cacher(); void init(); Catalog *getSource(); List<Cell> *getCache(); void setFull(bool val, bool thumbs = true); int isFull(); bool isRunning(); bool next(); bool prev(); Cell *getThat(); Image *getThatImage(); Image *getThatThumb(int width, int height); void unlockNext(); void unlockPrev(); void lockCache(); void unlockCache(); void gotoCell(Cell *cell); static DWORD WINAPI initAlloc(LPVOID param); static DWORD WINAPI nextAlloc(LPVOID param); static DWORD WINAPI prevAlloc(LPVOID param); };
[ [ [ 1, 84 ] ] ]
9c040ff26c5a634c1d7323122009db211a1fa3b7
ee065463a247fda9a1927e978143186204fefa23
/Src/Depends/ClanLib/ClanLib2.0/Sources/Core/Zip/zip_local_file_header.h
0e9cc9bb9d5be5fd9c58907a6eb02029212b5b9c
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
2,049
h
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #pragma once #include "API/Core/IOData/datatypes.h" #include "API/Core/System/databuffer.h" class CL_IODevice; class CL_ZipLocalFileHeader { /// \name Construction /// \{ public: CL_ZipLocalFileHeader(); ~CL_ZipLocalFileHeader(); /// \} /// \name Attributes /// \{ public: cl_int32 signature; // 0x04034b50 cl_int16 version_needed_to_extract; cl_int16 general_purpose_bit_flag; cl_int16 compression_method; cl_int16 last_mod_file_time; cl_int16 last_mod_file_date; cl_uint32 crc32; cl_int32 compressed_size; cl_int32 uncompressed_size; cl_int16 file_name_length; cl_int16 extra_field_length; CL_String filename; CL_DataBuffer extra_field; /// \} /// \name Operations /// \{ public: void load(CL_IODevice &input); void save(CL_IODevice &output); /// \} /// \name Implementation /// \{ private: /// \} };
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 97 ] ] ]
53d6f8f2a13aa3d7827c2f79eff15e3ffcb3f5b5
0e25e68e96c9883edcc85cbee6d24fdfd49cf8e5
/source/Background.cpp
31650e2fddbc1007e56cfc0c4284ff36aa5e6b49
[]
no_license
dpembo/tetwiis
ff334a52ce2b41e79790c37fbe6630d26b1eb2b7
207692026d767b1a3aa9909ba9c6297cfd78fae0
refs/heads/master
2021-08-17T10:36:38.264831
2011-08-03T11:25:21
2011-08-03T11:25:21
32,199,080
1
1
null
null
null
null
UTF-8
C++
false
false
2,490
cpp
/** * * Tetwiis * (C)2009 http://www.pembo.co.uk * **/ //------------------------------------------------------------------------------ // Headers //------------------------------------------------------------------------------ # include "Background.h" //------------------------------------------------------------------------------ // Externals //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Globals //------------------------------------------------------------------------------ static GRRLIB_texImg *tex_bg1; static GRRLIB_texImg *tex_bg2; static GRRLIB_texImg *tex_bg3; //static GRRLIB_texImg *tex_bg4; //static GRRLIB_texImg *tex_bg5; static int onImage; static int lastOnImage; static int lastOnLevel; //_______________________________________________________________________________ /** * constructor */ Background::Background() { } //_______________________________________________________________________________ /** * destructor */ Background::~Background() { free(tex_bg1); free(tex_bg2); free(tex_bg3); //free(tex_bg4); //free(tex_bg5); } void Background::initialise() { tex_bg1=GRRLIB_LoadTexturePNG(bg1); tex_bg2=GRRLIB_LoadTexturePNG(bg2); tex_bg3=GRRLIB_LoadTexturePNG(bg3); //tex_bg4=GRRLIB_LoadTexturePNG(bg4); //tex_bg5=GRRLIB_LoadTexturePNG(bg5); onImage=1; lastOnImage=1; lastOnLevel = 1; } void Background::reset() { onImage=1; lastOnImage=1; lastOnLevel = 1; } void Background::drawBackGround(int level) { if(lastOnLevel!=level && level%5==0)onImage++; if(onImage>3)onImage=1; /*if(onImage!=lastOnImage) { if(onImage==1)tex_bg1=GRRLIB_LoadTexturePNG(bg1); if(onImage==2)tex_bg1=GRRLIB_LoadTexturePNG(bg2); if(onImage==3)tex_bg1=GRRLIB_LoadTexturePNG(bg3); if(onImage==4)tex_bg1=GRRLIB_LoadTexturePNG(bg4); if(onImage==5)tex_bg1=GRRLIB_LoadTexturePNG(bg5); }*/ if(onImage==1)GRRLIB_DrawImg(0,0,tex_bg1,0,1,1,0xFFFFFFFF); else if(onImage==2)GRRLIB_DrawImg(0,0,tex_bg2,0,1,1,0xFFFFFFFF); else if(onImage==3)GRRLIB_DrawImg(0,0,tex_bg3,0,1,1,0xFFFFFFFF); //else if(onImage==4)GRRLIB_DrawImg(0,0,tex_bg4,0,1,1,0xFFFFFFFF); //if(onImage==5)GRRLIB_DrawImg(0,0,tex_bg5,0,1,1,0xFFFFFFFF); //GRRLIB_DrawImg(0,0,tex_bg1,0,1,1,0xFFFFFFFF); //lastOnImage = onImage; lastOnLevel = level; }
[ "[email protected]@d3020fdf-8559-019b-6164-6b32d0407fe0" ]
[ [ [ 1, 99 ] ] ]
1df2a63bc7d44710df54b997738d02d685d65445
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Game/MinimapView.h
86cd599116bb5c670d2318819aeb2513b1e56c8a
[ "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
2,443
h
/* 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. */ #ifndef _HMM_MINIMAP_VIEW_H_ #define _HMM_MINIMAP_VIEW_H_ const sint32 ZOOM_MIN = 1; const sint32 ZOOM_MAX = 4; class iMinimapView : public iChildGameView { public: iMinimapView(); void OnMouseDown(const iPoint& pos); void OnMouseUp(const iPoint& pos); void OnMouseTrack(const iPoint& pos); void PrepareSurface(); void SetCenterCell(const iPoint& pos); iPoint GetCenterCell() const { return m_CenterCell; } void OnZoomChanged(); sint32 GetScale() const { return m_Scale; } inline void SetZoom(sint32 nScale) { m_Scale = iCLAMP<sint32>(ZOOM_MIN, ZOOM_MAX, nScale); } inline void ZoomIn() { m_Scale = iMIN<sint32>(m_Scale+1,ZOOM_MAX); OnZoomChanged(); } inline void ZoomOut() { m_Scale = iMAX<sint32>(m_Scale-1,ZOOM_MIN); OnZoomChanged(); } inline iPoint Screen2Map(const iPoint& pos) const { sint32 mx = ((pos.x-(sint32)(m_Rect.w/2))/m_Scale+pos.y/m_Scale)/2; sint32 my = pos.y/m_Scale-mx; return iPoint(mx,my); } inline iPoint Map2Screen(const iPoint& pos) const { return iPoint((-pos.y+pos.x)*m_Scale+m_Rect.w/2,(pos.x+pos.y)*m_Scale); } inline iPoint GetOffset() const { return iPoint(m_Rect.w/2,m_Rect.h/2) - Map2Screen(m_CenterCell); } void OnCompose(); private: void iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param); private: sint32 m_Scale; iBuff<uint16> m_Surf; iPoint m_CenterCell; iPoint m_TrackCell; }; /* * Minimap Toolbar */ class iMinimapToolBar : public iView { public: iMinimapToolBar(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect); void OnCompose(); }; #endif //_HMM_MINIMAP_VIEW_H_
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 83 ] ] ]
307c366595166da3849d707c257ee73897894cf5
6f7850c90ed97967998033df615d06eacfabd5fa
/common/my_time.cpp
72500915b316a8b28e3c0897c5aa1e86e5919d29
[]
no_license
vi-k/whoisalive
1145b0af6a2a18e951533b00a2103b000abd570a
ae86c1982c1e97eeebc50ba54bf53b9b694078b6
refs/heads/master
2021-01-10T02:00:28.585126
2010-08-23T01:58:45
2010-08-23T01:58:45
44,526,120
0
0
null
null
null
null
UTF-8
C++
false
false
2,839
cpp
#include "my_time.h" #include "my_exception.h" using namespace std; #include <boost/date_time/time_parsing.hpp> #include <boost/date_time/c_local_time_adjustor.hpp> namespace boost { std::size_t hash_value(const posix_time::ptime &t) { int size = sizeof(t) / sizeof(size_t); size_t seed = 0; size_t *ptr = (size_t*)&t; while (size--) boost::hash_combine(seed, *ptr); return seed; } } namespace my { namespace time { posix_time::ptime utc_now() { return posix_time::microsec_clock::universal_time(); } posix_time::ptime local_now() { return posix_time::microsec_clock::local_time(); } double div( const posix_time::time_duration &time1, const posix_time::time_duration &time2) { return (double)time1.ticks() / (double)time2.ticks(); } posix_time::time_duration div( const posix_time::time_duration &time, double divisor) { return posix_time::time_duration(0, 0, 0, posix_time::time_duration::fractional_seconds_type( (double)time.ticks() / divisor + 0.5)); } posix_time::time_duration mul( const posix_time::time_duration &time, double rhs) { return posix_time::time_duration(0, 0, 0, posix_time::time_duration::fractional_seconds_type( (double)time.ticks() * rhs + 0.5)); } posix_time::ptime utc_to_local(const posix_time::ptime &utc_time) { return boost::date_time::c_local_adjustor<posix_time::ptime> ::utc_to_local(utc_time); } posix_time::ptime local_to_utc(const posix_time::ptime &local_time) { /* Прямой функции для c_local_adjustor почему-то нет */ posix_time::time_duration td = utc_to_local(local_time) - local_time; return local_time - td; } posix_time::ptime floor(const posix_time::ptime &time, const posix_time::time_duration &prec) { return posix_time::ptime(time.date(), my::time::floor(time.time_of_day(), prec)); } posix_time::time_duration floor(const posix_time::time_duration &dur, const posix_time::time_duration &prec) { return prec * (int)( my::time::div(dur, prec) ); } posix_time::ptime ceil(const posix_time::ptime &time, const posix_time::time_duration &prec) { return posix_time::ptime(time.date(), my::time::ceil(time.time_of_day(), prec)); } posix_time::time_duration ceil(const posix_time::time_duration &dur, const posix_time::time_duration &prec) { posix_time::time_duration fl = my::time::floor(dur, prec); return fl == dur ? fl : fl + prec; } posix_time::ptime round(const posix_time::ptime &time, const posix_time::time_duration &prec) { return posix_time::ptime(time.date(), my::time::round(time.time_of_day(), prec)); } posix_time::time_duration round(const posix_time::time_duration &dur, const posix_time::time_duration &prec) { return my::time::floor(dur + prec / 2, prec); } }}
[ "victor dunaev ([email protected])" ]
[ [ [ 1, 114 ] ] ]
b37f9b4df72bcb3cdd4c74cb0eebb32a452eaf5e
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/vertexshader.cpp
4eaafa946d2d68b20344548d90c4e09ebb47a77a
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
5,890
cpp
#include"vertexshader.h" namespace Maid { #if 0 VertexShader::CACHE::INFOMAP VertexShader::CACHE::s_InfoMap; //! シェーダーを作成する /*! 作成しますが文字列が"0100" - "0199" までの場合、デフォルトのシェーダーを作成する必要があります。 @param ShaderCode [i ] コンパイルするシェーダー */ void VertexShader::Create( const String& ShaderCode ) { IVertexShader::Clear(); if( ShaderCode.empty() ) { return ; } m_Compiler.Compile( ShaderCode, ShaderCompiler::CODETYPE_VERTEXSHADER, GlobalPointer<GraphicsCore>::Get()->GetDevice() ); } bool VertexShader::IsCompiling()const { // ポインタが存在してるならすでに作ってる if( IVertexShader::Get().get()!=NULL ) { return false; } // 処理が終わるまでは忙しい if( m_Compiler.IsCompiling() ) { return true; } // ここまできたらコンパイルが終わっている const std::vector<unt08>& code = m_Compiler.GetByteCode(); if( code.empty() ) { return false; } // 次はシェーダー作成処理 if( m_Cache.IsEmpty() ) { // m_Cache が動いてない==まだ作ってないなので、作成する const String& key = m_Compiler.GetShaderLanguage(); const std::vector<unt08>& byte = m_Compiler.GetByteCode(); const_cast<VertexShader*>(this)->m_Cache.Start( KEEPOUT::vsInput(key, byte, GlobalPointer<GraphicsCore>::Get()->GetDevice() ) ); } if( m_Cache.IsExecuting() ) { return true; } const_cast<VertexShader*>(this)->IVertexShader::Set( m_Cache.GetOutput().pShader ); return false; } #endif #if 0 VertexShader::SHAREDDATA VertexShader::s_SharedData; VertexShader::~VertexShader() { Delete(); } void VertexShader::Create( const String& ShaderCode ) { Delete(); if( ShaderCode.empty() ) { return ; } SHAREDDATA::iterator ite = s_SharedData.find( ShaderCode ); if( ite!=s_SharedData.end() ) { m_pShaderInfo = ite->second; IVertexShader::Set( m_pShaderInfo->pShader ); } else { m_Compiler.Compile( ShaderCode, ShaderCompiler::CODETYPE_VERTEXSHADER, GlobalPointer<GraphicsCore>::Get()->GetDevice() ); } m_ShaderCode = ShaderCode; } bool VertexShader::IsCompiling()const { // ポインタが存在してるならすでに作ってる if( IVertexShader::Get().get()!=NULL ) { return false; } // 処理が終わるまでは忙しい if( m_Compiler.IsCompiling() ) { return true; } // ここまできたらコンパイルが終わっている const std::vector<unt08>& code = m_Compiler.GetByteCode(); if( code.empty() ) { return false; } VertexShader* pThis = const_cast<VertexShader*>(this); SPSHADERINFO pInfo; SHAREDDATA::iterator ite = s_SharedData.find( m_ShaderCode ); if( ite==s_SharedData.end() ) { // 次はシェーダー作成処理 GraphicsCore* pCore = GlobalPointer<GraphicsCore>::Get(); Graphics::SPVERTEXSHADER pShader = pCore->GetDevice()->CreateVertexShader(&(code[0]),code.size()); if( pShader.get()==NULL ) { return false; } { SPSHADERINFO p( new SHADERINFO ); p->pShader = pShader; pInfo = p; s_SharedData[m_ShaderCode] = p; } }else { pInfo = ite->second; } pThis->m_pShaderInfo = pInfo; pThis->IVertexShader::Set( m_pShaderInfo->pShader ); return false; } void VertexShader::Delete() { if( m_ShaderCode.empty() ) { return ; } const String tmp = m_ShaderCode; { IVertexShader::Clear(); m_pShaderInfo = SPSHADERINFO(); m_Compiler = ShaderCompiler(); m_ShaderCode = String(); } SHAREDDATA::iterator ite = s_SharedData.find( tmp ); if( ite!=s_SharedData.end() ) { if( ite->second.unique() ) { s_SharedData.erase(ite); } } } #endif VertexShader::~VertexShader() { Delete(); } void VertexShader::Create( const String& ShaderCode ) { Delete(); if( ShaderCode.empty() ) { return ; } if( m_Table.IsExist(ShaderCode) ) { m_Table.Load( ShaderCode ); IVertexShader::Set( m_Table.GetValue().pShader ); }else { m_Compiler.Compile( ShaderCode, ShaderCompiler::CODETYPE_VERTEXSHADER, GlobalPointer<GraphicsCore>::Get()->GetDevice() ); } } bool VertexShader::IsCompiling()const { // ポインタが存在してるならすでに作ってる if( IVertexShader::Get().get()!=NULL ) { return false; } const String& shader_code = m_Compiler.GetShaderLanguage(); if( shader_code.empty() ) { return false; } // 処理が終わるまでは忙しい if( m_Compiler.IsCompiling() ) { return true; } // ここまできたらコンパイルが終わっている const std::vector<unt08>& code = m_Compiler.GetByteCode(); if( code.empty() ) { return false; } VertexShader* pThis = const_cast<VertexShader*>(this); if( m_Table.IsExist(shader_code) ) { pThis->m_Table.Load( shader_code ); }else { GraphicsCore* pCore = GlobalPointer<GraphicsCore>::Get(); Graphics::SPVERTEXSHADER pShader = pCore->GetDevice()->CreateVertexShader(&(code[0]),code.size()); if( pShader.get()==NULL ) { return false; } SHADERINFO info; info.pShader = pShader; pThis->m_Table.Create( shader_code, info ); } pThis->IVertexShader::Set( m_Table.GetValue().pShader ); return false; } void VertexShader::Delete() { IVertexShader::Clear(); m_Compiler = ShaderCompiler(); } }
[ "[email protected]", "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 5 ], [ 9, 51 ], [ 123, 123 ], [ 210, 211 ] ], [ [ 6, 8 ], [ 52, 122 ], [ 124, 209 ] ] ]
07b52bbbe004609d6f1f2637a65fc0cfbd3de8bd
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/opengl/drawcommandexecuteopengl_3.cpp
db123eb6ea6feac68d0f367f6f6573fe2c7583e1
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
6,054
cpp
#include"drawcommandexecuteopengl.h" #include"deviceopengl.h" #include"bufferopengl.h" #include"texture2dopengl.h" /* #include"rendertargetd3d11.h" #include"depthstencild3d11.h" */ #include"materialopengl.h" #include"inputlayoutopengl.h" /* #include"rasterizerstated3d11.h" #include"samplerstated3d11.h" #include"blendstated3d11.h" #include"vertexshaderd3d11.h" #include"pixelshaderd3d11.h" #include"debug.h" */ // ここは各種Drawを書く namespace Maid { namespace Graphics { enum DECLUSAGE { DECLUSAGE_NONE, DECLUSAGE_POSITION, DECLUSAGE_NORMAL, DECLUSAGE_COLOR, DECLUSAGE_TEXCOORD, }; inline DECLUSAGE INPUT_ELEMENTSemanticNametoDECLUSAGE( const char* p ) { DECLUSAGE ret = DECLUSAGE_NONE ; std::string str = p; std::transform(str.begin(), str.end(), str.begin(), tolower ); if( str=="position" ) { ret = DECLUSAGE_POSITION; } else if( str=="normal" ) { ret = DECLUSAGE_NORMAL; } else if( str=="color" ) { ret = DECLUSAGE_COLOR; } else if( str=="texcoord" ) { ret = DECLUSAGE_TEXCOORD; } /* else if( str=="blendweight" ) { ret = D3DDECLUSAGE_BLENDWEIGHT; } else if( str=="blendindices" ) { ret = D3DDECLUSAGE_BLENDINDICES; } else if( str=="psize" ) { ret = D3DDECLUSAGE_PSIZE; } else if( str=="tangent" ) { ret = D3DDECLUSAGE_TANGENT; } else if( str=="binormal" ) { ret = D3DDECLUSAGE_BINORMAL; } else if( str=="tessfactor" ) { ret = D3DDECLUSAGE_TESSFACTOR; } else if( str=="positiont" ) { ret = D3DDECLUSAGE_POSITIONT; } else if( str=="fog" ) { ret = D3DDECLUSAGE_FOG; } else if( str=="depth" ) { ret = D3DDECLUSAGE_DEPTH; } else if( str=="sample" ) { ret = D3DDECLUSAGE_SAMPLE; } */ return ret; } inline GLint CoordinatePerVertex( INPUT_ELEMENT::TYPE t ) { GLint ret = 4; switch( t ) { case INPUT_ELEMENT::TYPE_FLOAT1: { ret=1; }break; case INPUT_ELEMENT::TYPE_FLOAT2: { ret=2; }break; case INPUT_ELEMENT::TYPE_FLOAT3: { ret=3; }break; case INPUT_ELEMENT::TYPE_FLOAT4: { ret=4; }break; case INPUT_ELEMENT::TYPE_COLOR: { ret=1; }break; } return ret; } inline GLenum CoordinateType( INPUT_ELEMENT::TYPE t ) { GLint ret = GL_FLOAT; switch( t ) { case INPUT_ELEMENT::TYPE_FLOAT1: { ret=GL_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT2: { ret=GL_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT3: { ret=GL_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT4: { ret=GL_FLOAT; }break; case INPUT_ELEMENT::TYPE_COLOR: { ret=GL_4_BYTES; }break; // 通るかな? } return ret; } void DrawCommandExecuteOpenGL::Draw( size_t UseVertexCount, size_t StartVertex ) { { const GLuint prog = m_ShaderProgramID; m_Ext.glLinkProgram( prog ); m_Ext.glUseProgram( prog ); } const std::vector<INPUT_ELEMENT>& InputElement = static_cast<InputLayoutOpenGL*>(m_pInputLayout.get())->Element; std::vector<GLenum> EnableList; for( int i=0; i<(int)InputElement.size(); ++i ) { const INPUT_ELEMENT& ele = InputElement[i]; const DECLUSAGE decl = INPUT_ELEMENTSemanticNametoDECLUSAGE( ele.SemanticName.c_str() ); const VERTEXBUFFER& v = m_VertexBuffer[ele.SlotNo]; const GLint cpv = CoordinatePerVertex( ele.Type ); const GLenum type = CoordinateType( ele.Type ); const GLsizei stride = v.Stride; const int offset = ele.Offset; m_Ext.glBindBuffer( GL_ARRAY_BUFFER, v.pBuffer->GetID() ); switch( decl ) { case DECLUSAGE_POSITION: { EnableList.push_back( GL_VERTEX_ARRAY ); m_Ext.glVertexPointer( cpv, type, stride, (const GLvoid*)(offset) ); }break; case DECLUSAGE_NORMAL: { }break; case DECLUSAGE_COLOR: { EnableList.push_back( GL_COLOR_ARRAY ); m_Ext.glColorPointer( cpv, type, stride, (const GLvoid*)(offset) ); }break; case DECLUSAGE_TEXCOORD: { EnableList.push_back( GL_TEXTURE_COORD_ARRAY ); m_Ext.glTexCoordPointer( cpv, type, stride, (const GLvoid*)(offset) ); const int idx = ele.SemanticIndex; { char buf[256]; sprintf( buf, "texture%0d", idx ); const GLint tex_pos = m_Ext.glGetUniformLocation(m_ShaderProgramID, buf); m_Ext.glUniform1i(tex_pos,idx); } }break; } } for( int i=0; i<(int)EnableList.size(); ++i ) { m_Dll.glEnableClientState( EnableList[i] ); } m_Ext.glActiveTexture( GL_TEXTURE0 ); m_Ext.glDrawArrays( m_PrimitiveTopology, 0, UseVertexCount ); for( int i=0; i<(int)EnableList.size(); ++i ) { m_Dll.glDisableClientState( EnableList[i] ); } } void DrawCommandExecuteOpenGL::DrawIndexed( size_t UseIndexCount, size_t StartIndex, size_t OffsetVertex ) { // m_pDevice->DrawIndexed( UseIndexCount, StartIndex, OffsetVertex ); } /* ID3D11Resource* DrawCommandExecuteOpenGL::GetResource( const SPRESOURCE& pResource ) { ID3D11Resource* pRet = NULL; switch( pResource->GetType() ) { case IResource::TYPE_BUFFER: { BufferD3D11* pBuffer = static_cast<BufferD3D11*>( pResource.get() ); pRet = pBuffer->pBuffer.get(); }break; case IResource::TYPE_TEXTURE2D: { Texture2DD3D11* pBuffer = static_cast<Texture2DD3D11*>( pResource.get() ); pRet = pBuffer->pTexture.get(); }break; } return pRet; return NULL; } */ void DrawCommandExecuteOpenGL::CopyResource( const SPRESOURCE& pDstResource, const SPRESOURCE& pSrcResource ) { // ID3D11Resource* pDst = GetResource(pDstResource); // ID3D11Resource* pSrc = GetResource(pSrcResource); // m_pDevice->CopyResource( pDst, pSrc ); } void DrawCommandExecuteOpenGL::GenerateMips( const SPMATERIAL& pMaterial ) { // ID3D11ShaderResourceView* pView = static_cast<MaterialD3D11*>(pMaterial.get())->pView.get(); // m_pDevice->GenerateMips( pView ); } }}
[ "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 210 ] ] ]
010c75ae0cb689067c3d853c0705ada3eb8f6e8b
8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076
/code/Kernel/fxTimer.h
5d3dc9c1c8822d8539591d030fc6b1eda3797aa6
[]
no_license
BackupTheBerlios/insane
fb4c5c6a933164630352295692bcb3e5163fc4bc
7dc07a4eb873d39917da61e0a21e6c4c843b2105
refs/heads/master
2016-09-05T11:28:43.517158
2001-01-31T20:46:38
2001-01-31T20:46:38
40,043,333
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
//--------------------------------------------------------------------------- #ifndef fxTimerH #define fxTimerH //--------------------------------------------------------------------------- #include "../kernel/fxClass.h" #include "../insanefx.h" class INSANEFX_API fxTimer : public fxClass { private: double frequency; double lasttime; double starttime; int lowshift; bool firstframe; float GetTime(void); // returns the number of seconds that have passed since the last call float GetTimeDelta(void); public: fxTimer(); void Refresh(void); float timedelta; float time; void RestartTimer(void); }; #endif
[ "josef" ]
[ [ [ 1, 34 ] ] ]
7e99914ffbef7c9e27540c377aeb81a659a94843
96f796a966025265020459ca2a38346c3c292b1e
/TestAnsoply/ansoplyinterface1.h
0e6c2ee27d4273c9be89efe6d50452405b96e93b
[]
no_license
shanewfx/ansoply
222979843662ddb98fb444ce735d607e3033dd5e
99e91008048d0c1afbf80152d0dc173a15e068ee
refs/heads/master
2020-05-18T15:53:46.618329
2009-06-17T01:04:47
2009-06-17T01:04:47
32,243,359
1
0
null
null
null
null
UTF-8
C++
false
false
23,064
h
#pragma once // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. ///////////////////////////////////////////////////////////////////////////// // CAnsoplyinterface1 wrapper class class CAnsoplyinterface1 : public CWnd { protected: DECLARE_DYNCREATE(CAnsoplyinterface1) public: CLSID const& GetClsid() { static CLSID const clsid = { 0xD1EBA581, 0x3B3, 0x42EA, { 0xB0, 0x97, 0x7F, 0x97, 0xF0, 0xAD, 0xB8, 0x7B } }; return clsid; } virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL) { return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); } BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CFile* pPersist = NULL, BOOL bStorage = FALSE, BSTR bstrLicKey = NULL) { return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID, pPersist, bStorage, bstrLicKey); } // Attributes public: // Operations public: // IAnsoplyInterface // Functions // void CreateVideoGroup(unsigned long * uNewGroupID) { static BYTE parms[] = VTS_PUI4 ; InvokeHelper(0x1, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uNewGroupID); } void DelVideoGroup(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x2, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void AddVideoFile(unsigned long uGroupID, LPCTSTR sFilePathName, unsigned long * uFileObjectID) { static BYTE parms[] = VTS_UI4 VTS_BSTR VTS_PUI4 ; InvokeHelper(0x3, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, sFilePathName, uFileObjectID); } void DelVideoFile(unsigned long uGroupID, unsigned long uFileID) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x4, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID); } void GetVideoObjectCount(unsigned long uGroupID, unsigned long * uFileCount) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x5, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileCount); } void GetFirstVideoObjectID(unsigned long uGroupID, unsigned long * uFileID) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x6, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID); } void GetNextVideoObjectID(unsigned long uGroupID, unsigned long * uFileID) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x7, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID); } void GetVideoObjectFileName(unsigned long uGroupID, unsigned long uFileID, BSTR * ch) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_PBSTR ; InvokeHelper(0x8, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID, ch); } void SetObjectLevel(unsigned long uObjectID, unsigned long uLevel) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID, uLevel); } void GetObjectLevel(unsigned long uObjectID, unsigned long * uLevel) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0xa, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID, uLevel); } void Play(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0xb, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Pause(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0xc, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Stop(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0xd, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Next(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0xe, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Previous(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0xf, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Seek(unsigned long GroupID, unsigned long uPosition) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x10, DISPATCH_METHOD, VT_EMPTY, NULL, parms, GroupID, uPosition); } void SavePlayList(LPCTSTR sFilePathName) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x11, DISPATCH_METHOD, VT_EMPTY, NULL, parms, sFilePathName); } void LoadPlayList(LPCTSTR sFilePathName) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x12, DISPATCH_METHOD, VT_EMPTY, NULL, parms, sFilePathName); } void SetVideoPosition(unsigned long uGroupID, unsigned long uX, unsigned long uY) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x13, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY); } void GetVideoPosition(unsigned long uGroupID, unsigned long * uX, unsigned long * uY) { static BYTE parms[] = VTS_UI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x14, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY); } void SetVideoPosAndSize(unsigned long uGroupID, unsigned long uX, unsigned long uY, unsigned long uWeight, unsigned long uHeight) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x15, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY, uWeight, uHeight); } void GetVideoPositionAndSize(unsigned long uGroupID, unsigned long * uX, unsigned long * uY, unsigned long * uWeight, unsigned long * uHeight) { static BYTE parms[] = VTS_UI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x16, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY, uWeight, uHeight); } void SetVideoAlpha(unsigned long GroupID, unsigned long uAlpha) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x17, DISPATCH_METHOD, VT_EMPTY, NULL, parms, GroupID, uAlpha); } void GetVideoAlpha(unsigned long uGroupID, unsigned long * uAlpha) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x18, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uAlpha); } void SetBitmap(unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize) { static BYTE parms[] = VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x19, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize); } void GetBitmap(unsigned long uBitmapID, BSTR * sBitmapFilePath, unsigned long * uAlpha, unsigned long * uTransparentColor, unsigned long * uX, unsigned long * uY, unsigned long * uWidth, unsigned long * uHeight, unsigned long * uOriginalSize, unsigned long * uDrawStyle, unsigned long * uDelay) { static BYTE parms[] = VTS_UI4 VTS_PBSTR VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x1a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, uDrawStyle, uDelay); } void DelBitmap(unsigned long uBitmapID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x1b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID); } void SetDynamicBitmap(unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize, unsigned long uMilliSec) { static BYTE parms[] = VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x1c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, uMilliSec); } void GetDynamicBitmap(unsigned long uBitmapID, BSTR * sBitmapFilePath, unsigned long * uAlpha, unsigned long * uTransparentColor, unsigned long * uX, unsigned long * uY, unsigned long * uMilliSec) { static BYTE parms[] = VTS_UI4 VTS_PBSTR VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x1d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uMilliSec); } void SetText(unsigned long uX, unsigned long uY, LPCTSTR sOutputText, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long * uObjectID) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_BSTR VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_PUI4 ; InvokeHelper(0x1e, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uObjectID); } void GetText(unsigned long uObjectID, unsigned long * uX, unsigned long * uY, BSTR * sOutputText, BSTR * sFaceName, unsigned long * uItalic, unsigned long * uBold, unsigned long * uUnderLine, unsigned long * uWidth, unsigned long * uHeight, unsigned long * uColor, unsigned long * uAlpha, unsigned long * uTransparentColor, unsigned long * uDrawStyle, unsigned long * uDelay) { static BYTE parms[] = VTS_UI4 VTS_PUI4 VTS_PUI4 VTS_PBSTR VTS_PBSTR VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x1f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uAlpha, uTransparentColor, uDrawStyle, uDelay); } void DelText(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x20, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void GetLastError() { InvokeHelper(0x21, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Init(long hWnd, unsigned long uWidth, unsigned long uHeight) { static BYTE parms[] = VTS_I4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x22, DISPATCH_METHOD, VT_EMPTY, NULL, parms, hWnd, uWidth, uHeight); } void SetPlayRate(unsigned long uGroupID, double dRate) { static BYTE parms[] = VTS_UI4 VTS_R8 ; InvokeHelper(0x23, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, dRate); } void SelectObjectByCoordinate(unsigned long * uGroupID, unsigned long * uObjectType, unsigned long cX, unsigned long cY, unsigned long uFrameColor) { static BYTE parms[] = VTS_PUI4 VTS_PUI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x24, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uObjectType, cX, cY, uFrameColor); } void SelectObject(unsigned long uGroupID, unsigned long uFrameColor) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x25, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFrameColor); } void BringToFront(unsigned long uObjectID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x26, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID); } void SendToBack(unsigned long uObjectID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x27, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID); } void BringUp(unsigned long uObjectID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x28, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID); } void SendBack(unsigned long uObjectID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x29, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID); } void SetPlayMode(unsigned long uGroupID, unsigned long uPlayMode) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x2a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uPlayMode); } void GetVideoLength(unsigned long uGroupID, unsigned long uFileID, double * uLength) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_PR8 ; InvokeHelper(0x2b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID, uLength); } void GetVideoGroupZOrder(unsigned long uGroupID, unsigned long * uZOrder) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x2c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uZOrder); } void UnSelectVideoGroup() { InvokeHelper(0x2d, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void SetMediaFilePath(LPCTSTR sFilePathName) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x2e, DISPATCH_METHOD, VT_EMPTY, NULL, parms, sFilePathName); } void SetDefaultVideoSize(unsigned long uGroupID, unsigned long uX, unsigned long uY) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x2f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY); } void GetVideoGroupCount(unsigned long * uGroupCount) { static BYTE parms[] = VTS_PUI4 ; InvokeHelper(0x30, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupCount); } void GetFirstVideoGroupID(long * uGroupID) { static BYTE parms[] = VTS_PI4 ; InvokeHelper(0x31, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void GetNextVideoGroupID(long * uGroupID) { static BYTE parms[] = VTS_PI4 ; InvokeHelper(0x32, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void Close() { InvokeHelper(0x33, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Refresh() { InvokeHelper(0x34, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void GetCurrentFileID(unsigned long uGroupID, long * uFileID) { static BYTE parms[] = VTS_UI4 VTS_PI4 ; InvokeHelper(0x35, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uFileID); } void GetCurrentPlayingPos(unsigned long uGroupID, unsigned long * uCurPos) { static BYTE parms[] = VTS_UI4 VTS_PUI4 ; InvokeHelper(0x36, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uCurPos); } void SetTextInRegion(unsigned long uX, unsigned long uY, LPCTSTR sOutputText, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long * uObjectID, unsigned long uRegionWidth, unsigned long uRegionHeight) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_BSTR VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_PUI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x37, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uObjectID, uRegionWidth, uRegionHeight); } void SetVideoFile(unsigned long uGroupID, LPCTSTR sFileName, unsigned long uOldFileID, unsigned long * uNewFileID) { static BYTE parms[] = VTS_UI4 VTS_BSTR VTS_UI4 VTS_PUI4 ; InvokeHelper(0x38, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, sFileName, uOldFileID, uNewFileID); } void SetVisibility(unsigned long uObjectID, unsigned long bVisibility) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x39, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uObjectID, bVisibility); } void SetPlayTimes(unsigned long uGroupID, unsigned long uPlayTimes) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x3a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uPlayTimes); } void SetPlayTimeout(unsigned long uGroupID, unsigned long uTimeout_s) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x3b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uTimeout_s); } void SetEffectBitmap(unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize, unsigned long DrawStyle, unsigned long uDelay) { static BYTE parms[] = VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x3c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, DrawStyle, uDelay); } void SetEffectBitmapStyle(unsigned long uID, unsigned long uStyle) { static BYTE parms[] = VTS_UI4 VTS_UI4 ; InvokeHelper(0x3d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uID, uStyle); } void SetEffectTextInRegion(unsigned long uX, unsigned long uY, LPCTSTR sOutputText, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long * uObjectID, unsigned long uRegionWidth, unsigned long uRegionHeight, unsigned long uDrawStyle, unsigned long uDelay) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_BSTR VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_PUI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x3e, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uObjectID, uRegionWidth, uRegionHeight, uDrawStyle, uDelay); } void SetEffectPlayRange(unsigned long uID, unsigned long uPlayMode, unsigned long uRangeStart, unsigned long uRangeEnd) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x3f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uID, uPlayMode, uRangeStart, uRangeEnd); } void SetEffectEndTime(unsigned long uID, long EndTime) { static BYTE parms[] = VTS_UI4 VTS_I4 ; InvokeHelper(0x40, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uID, EndTime); } void SetDynamicEffectBitmap(unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize, unsigned long uDrawStyle) { static BYTE parms[] = VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x41, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, uDrawStyle); } void CreateBitmapGroup(unsigned long * uGroupID) { static BYTE parms[] = VTS_PUI4 ; InvokeHelper(0x42, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void AddBitmap(unsigned long uGroupID, unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize, unsigned long uDrawStyle, unsigned long uDelay) { static BYTE parms[] = VTS_UI4 VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x43, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, uDrawStyle, uDelay); } void DelBitmapGroup(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x44, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void InsertBitmap(unsigned long uGroupID, unsigned long uWhere, unsigned long * uBitmapID, LPCTSTR sBitmapFilePath, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize, unsigned long uDrawStyle, unsigned long uDelay) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_PUI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x45, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uWhere, uBitmapID, sBitmapFilePath, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize, uDrawStyle, uDelay); } void CreateTextGroup(unsigned long * uGroupID) { static BYTE parms[] = VTS_PUI4 ; InvokeHelper(0x46, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void AddText(unsigned long uGroupID, unsigned long uX, unsigned long uY, LPCTSTR sOutputText, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long * uObjectID, unsigned long uRegionWidth, unsigned long uRegionHeight, unsigned long uDrawStyle, unsigned long uDelay, unsigned long uAlpha, unsigned long uTransparentColor) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_BSTR VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_PUI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x47, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uObjectID, uRegionWidth, uRegionHeight, uDrawStyle, uDelay, uAlpha, uTransparentColor); } void DelTextGroup(unsigned long uGroupID) { static BYTE parms[] = VTS_UI4 ; InvokeHelper(0x48, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID); } void InsertText(unsigned long uGroupID, unsigned long uWhere, unsigned long uX, unsigned long uY, LPCTSTR sOutputText, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long * uObjectID, unsigned long uRegionWidth, unsigned long uRegionHeight, unsigned long uDrawStyle, long uDelay) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_BSTR VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_PUI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_I4 ; InvokeHelper(0x49, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uWhere, uX, uY, sOutputText, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uObjectID, uRegionWidth, uRegionHeight, uDrawStyle, uDelay); } void SetBitmapParam(unsigned long uBitmapID, unsigned long uAlpha, unsigned long uTransparentColor, unsigned long uX, unsigned long uY, unsigned long uWidth, unsigned long uHeight, unsigned long uOriginalSize) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x4a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uBitmapID, uAlpha, uTransparentColor, uX, uY, uWidth, uHeight, uOriginalSize); } void SetTextParam(unsigned long uTextID, unsigned long uX, unsigned long uY, LPCTSTR sFaceName, unsigned long uItalic, unsigned long uBold, unsigned long uUnderLine, unsigned long uWidth, unsigned long uHeight, unsigned long uColor, unsigned long uAlpha, unsigned long uTransparentColor) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 VTS_BSTR VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x4b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uTextID, uX, uY, sFaceName, uItalic, uBold, uUnderLine, uWidth, uHeight, uColor, uAlpha, uTransparentColor); } void SetPlayParam(unsigned long uGroupID, unsigned long uID, unsigned long uDrawStyle) { static BYTE parms[] = VTS_UI4 VTS_UI4 VTS_UI4 ; InvokeHelper(0x4c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uID, uDrawStyle); } void GetPlayParam(unsigned long uGroupID, unsigned long * uID, unsigned long * uDrawStyle) { static BYTE parms[] = VTS_UI4 VTS_PUI4 VTS_PUI4 ; InvokeHelper(0x4d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, uGroupID, uID, uDrawStyle); } // Properties // };
[ "Gmagic10@26f92a05-6149-0410-981d-7deb1f891687", "gmagic10@26f92a05-6149-0410-981d-7deb1f891687" ]
[ [ [ 1, 83 ], [ 85, 85 ], [ 87, 173 ], [ 175, 175 ], [ 178, 183 ], [ 185, 185 ], [ 188, 198 ], [ 200, 200 ], [ 203, 222 ], [ 224, 224 ], [ 227, 227 ], [ 229, 232 ], [ 234, 235 ], [ 237, 237 ], [ 239, 240 ], [ 242, 242 ], [ 244, 245 ], [ 247, 247 ], [ 249, 250 ], [ 252, 286 ], [ 288, 288 ], [ 290, 291 ], [ 293, 293 ], [ 295, 296 ], [ 430, 436 ] ], [ [ 84, 84 ], [ 86, 86 ], [ 174, 174 ], [ 176, 177 ], [ 184, 184 ], [ 186, 187 ], [ 199, 199 ], [ 201, 202 ], [ 223, 223 ], [ 225, 226 ], [ 228, 228 ], [ 233, 233 ], [ 236, 236 ], [ 238, 238 ], [ 241, 241 ], [ 243, 243 ], [ 246, 246 ], [ 248, 248 ], [ 251, 251 ], [ 287, 287 ], [ 289, 289 ], [ 292, 292 ], [ 294, 294 ], [ 297, 429 ] ] ]
246420d8d532f2a4783ae50449baccf2ad9b9f74
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/CameraFirstPerson.h
b4cb49b94c44f481edd7a0f588096afbce89c43d
[]
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
1,850
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: CameraFirstPerson.h Version: 0.08 --------------------------------------------------------------------------- */ #ifndef __INC_CAMERAFIRSTPERSON_H_ #define __INC_CAMERAFIRSTPERSON_H_ #include "Camera3D.h" #include "TypeInfo.h" namespace nGENE { /** Presents view from the first person perspective. @remarks It is especially useful in FPS games. @par Although position of the camera is influenced by the position of parental node, rotation is not. It is due to the fact FPS camera is quite independent and rarely fixed, so there is no such need. */ class nGENEDLL CameraFirstPerson: public Camera3D { EXPOSE_TYPE protected: virtual void updateAxes(); public: CameraFirstPerson(); virtual ~CameraFirstPerson(); virtual void init(); virtual void cleanup(); /** Moves the camera in the z-direction. @param _direction pass 1 to make camera go forward and -1, to go backwards. */ virtual void move(Real _direction); /** Moves the camera in the x-direction. @param _direction pass 1 to make camera go right and -1, to go left. */ virtual void strafe(Real _direction); virtual void serialize(ISerializer* _serializer, bool _serializeType, bool _serializeChildren); virtual void deserialize(ISerializer* _serializer); }; /** Camera factory to be used for creating CameraFirstPerson type objects. */ class nGENEDLL FPPCameraFactory: public CameraFactory { public: FPPCameraFactory(); virtual ~FPPCameraFactory(); Camera* createCamera() {return new CameraFirstPerson();} }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 79 ] ] ]
6823e484213e250160699c2b8fbcbe65dc386328
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/Level.cpp
4051d232d0bb2709be952cc5af1ff786f578b544
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,288
cpp
/*** * hesperus: Level.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include "Level.h" #include <source/level/nav/NavDataset.h> #include <source/level/nav/NavMesh.h> #include <source/level/trees/BSPTree.h> #include <source/level/trees/TreeUtil.h> namespace hesp { //#################### CONSTRUCTORS #################### Level::Level(const GeometryRenderer_Ptr& geomRenderer, const BSPTree_Ptr& tree, const PortalVector& portals, const LeafVisTable_Ptr& leafVis, const ColPolyVector& onionPolygons, const OnionTree_Ptr& onionTree, const OnionPortalVector& onionPortals, const NavManager_Ptr& navManager, const ObjectManager_Ptr& objectManager) : m_geomRenderer(geomRenderer), m_tree(tree), m_portals(portals), m_leafVis(leafVis), m_onionPolygons(onionPolygons), m_onionTree(onionTree), m_onionPortals(onionPortals), m_navManager(navManager), m_objectManager(objectManager) {} //#################### PUBLIC METHODS #################### BSPTree_CPtr Level::bsp_tree() const { return m_tree; } /** Determine which leaves are potentially visible from the specified eye position. */ std::vector<int> Level::find_visible_leaves(const Vector3d& eye) const { bool allVisible = false; int curLeaf = TreeUtil::find_leaf_index(eye, m_tree); if(curLeaf >= m_tree->empty_leaf_count()) { // If we're erroneously in a solid leaf, we assume all leaves are visible (the best we can do when rendering in this case is render the entire level). allVisible = true; } std::vector<int> visibleLeaves; for(int i=0, size=m_leafVis->size(); i<size; ++i) { // TODO: View frustum culling. if(allVisible || (*m_leafVis)(curLeaf,i)) visibleLeaves.push_back(i); } return visibleLeaves; } GeometryRenderer_CPtr Level::geom_renderer() const { return m_geomRenderer; } NavManager_CPtr Level::nav_manager() const { return m_navManager; } const ObjectManager_Ptr& Level::object_manager() { return m_objectManager; } const std::vector<CollisionPolygon_Ptr>& Level::onion_polygons() const { return m_onionPolygons; } OnionTree_CPtr Level::onion_tree() const { return m_onionTree; } const std::vector<Portal_Ptr>& Level::portals() const { return m_portals; } }
[ [ [ 1, 85 ] ] ]
ae3c725737ec35994201c5345bbbbe9cf9edeab8
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnSystem/Source/GnPath.h
e00c92c8afdaba29b8694cc34136f75c4e1b4021
[]
no_license
mujige77/WebGame
c0a218ee7d23609076859e634e10e29c92bb595b
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
refs/heads/master
2021-01-01T15:51:20.045414
2011-10-03T01:02:59
2011-10-03T01:02:59
455,950
3
1
null
null
null
null
UTF-8
C++
false
false
1,019
h
#ifndef GNPATH_H #define GNPATH_H #include "GnSystemDefine.h" #if defined(_MAX_PATH) #define GN_MAX_PATH _MAX_PATH #else //#if defined(_MAX_PATH) #define GN_MAX_PATH 260 #endif //#if defined(_MAX_PATH) class GNSYSTEM_ENTRY GnPath { protected: gtchar* mFullFilePath; gtchar* mFileName; gtchar* mFileExtension; public: static size_t ConvertToAbsolute( gchar* pcAbsolutePath, size_t stBytes, const gchar* pcRelativePath, const gchar* pcRelativeToHere); static bool GetFileName(const gwchar* pcFilePath, gwchar* pcOutName, gsize maxPathLength, bool hasExtension = false); static bool GetFullPath(const gwchar* pcFilePath, gwchar* pcOutPath, gsize maxPathLength); static bool GetFileNameA(const gchar* pcFilePath, gchar* pcOutName, gsize maxPathLength, bool hasExtension = false); static bool GetFullPathA(const gchar* pcFilePath, gchar* pcOutPath, gsize maxPathLength); static bool CheckSamePathA(const gchar* pcPath1, const gchar* pcPath2); }; #endif // GNPATH_H
[ [ [ 1, 32 ] ] ]
1ee566ad73028ba5f749ce3d096cf865dcd20150
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/svn/main.cpp
1ec7ef88994d5a42d15c85fffd92d143a0bf8fdd
[ "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
386
cpp
#include <cbear.berlios.de/svn/client/main.hpp> #include <cbear.berlios.de/windows/cout.hpp> #include <iostream> namespace Svn = cbear_berlios_de::svn; namespace Client = cbear_berlios_de::svn::client; namespace Windows = cbear_berlios_de::windows; int main() { const Svn::version_t &V = Client::version(); Windows::cout() << V << "\n"; std::cin.get(); return 0; }
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 15 ] ] ]
b5362855a1f134b4afc7f39d33954beafbb6dedc
7956f4ceddbbcbabd3dd0ae211899cfa5934fc7a
/metaballs3d/trunk/OgreMetaballs/DynamicMesh.cpp
14636b476dd5dc2d8a3e30d4f545e6723183039e
[]
no_license
pranavsureshpn/gpusphsim
8d77cde45f5951aee65a13d1ea7edcb5837c6caa
723d950efbd0d2643edb4b99845bcc658ce38f20
refs/heads/master
2021-01-10T05:18:21.705120
2011-09-08T01:58:38
2011-09-08T01:58:38
50,779,129
0
0
null
null
null
null
UTF-8
C++
false
false
1,312
cpp
#include "DynamicMesh.h" //----------------------------------- // DynamicMesh //----------------------------------- DynamicMesh::DynamicMesh(const String& name) : ManualObject(name), m_initialized(false), m_vertexCount(0) { ManualObject::setDynamic(true); } DynamicMesh::~DynamicMesh() { } void DynamicMesh::BeginMesh() { //Update or begin the object if needed if(m_initialized) { ManualObject::beginUpdate(0); } else { m_initialized = true; ManualObject::begin(""); } m_vertexCount = 0; } void DynamicMesh::EndMesh() { //Finalize the mesh ManualObject::end(); } int DynamicMesh::AddVertex(const Vertex& vertex) { return AddVertex(vertex.Position, vertex.Normal, vertex.Color); } int DynamicMesh::AddVertex(const Vector3& position, const Vector3& normal, const ColourValue& color) { //Declare a new vertex in the vertex buffer ManualObject::position(position); ManualObject::normal(normal); ManualObject::colour(color); return m_vertexCount++; } void DynamicMesh::AddTriangle(int idx1, int idx2, int idx3) { //Add a triangle to the index buffer triangle(idx1, idx2, idx3); } void DynamicMesh::EstimateSize(int size) { //Allocate memory for future needs estimateIndexCount(size); estimateVertexCount(size); }
[ "yaoyansi@cd07e373-eec6-1eb2-8c47-9a5824a9cb26" ]
[ [ [ 1, 64 ] ] ]
015ec3f421dd99430155f81688c4361d50082af1
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleEmitters/ParticleUniverseMeshSurfaceEmitterFactory.h
1a80e17fc144775935d78074111f57d77eb8fd92
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,882
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_MESH_SURFACE_EMITTER_FACTORY_H__ #define __PU_MESH_SURFACE_EMITTER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseEmitterFactory.h" #include "ParticleUniverseMeshSurfaceEmitterTokens.h" #include "ParticleUniverseMeshSurfaceEmitter.h" namespace ParticleUniverse { /** This is the factory class that is responsible for creating a MeshSurfaceEmitter. */ class _ParticleUniverseExport MeshSurfaceEmitterFactory : public ParticleEmitterFactory { protected: MeshSurfaceEmitterTokens mMeshSurfaceEmitterTokens; public: MeshSurfaceEmitterFactory(void) {}; virtual ~MeshSurfaceEmitterFactory(void) {}; /** See ParticleEmitterFactory */ Ogre::String getEmitterType() const { return "MeshSurface"; } /** See ParticleEmitterFactory */ ParticleEmitter* createEmitter(void) { return _createEmitter<MeshSurfaceEmitter>(); } /** See ParticleEmitterFactory */ virtual void setupTokenDefinitions(ITokenRegister* tokenRegister) { // Delegate to mMeshSurfaceEmitterTokens mMeshSurfaceEmitterTokens.setupTokenDefinitions(tokenRegister); } }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 59 ] ] ]
f8648a17d15c82e0276970955ede70692b3f4bc5
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Nuclex/Storage/Stream.h
2a11836cc9d64d4e8235d5b46e617348a96a8065
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
4,639
h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Stream.h - Data source & sink  // // ### # # ###  // // # ### # ### Binary data stream for input and output  // // # ## # # ## ##  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_STORAGE_STREAM_H #define NUCLEX_STORAGE_STREAM_H #include "Nuclex/Nuclex.h" #include "Nuclex/Support/Exception.h" #include "Nuclex/Support/Cacheable.h" namespace Nuclex { namespace Storage { //  // //  Nuclex::Storage::Stream  // //  // /// Nuclex stream base class /** A stream is both a data source and a data sink, meaning you can retrieve data from it or store data into it. Where the data will end up depends on the stream class, it could provide direct access to a file on disk or it could store the stream in memory amongst other possibilities. */ class Stream : public Cacheable { public: /// Wrong access mode NUCLEX_DECLAREEXCEPTION(FailedException, WrongAccessModeException); /// Stream access modes enum AccessMode { AM_NONE = 0, ///< No access (query only) AM_READ, ///< Read access AM_WRITE, ///< Write access AM_APPEND ///< Append write access }; /// Destructor /** Destroys an instance of Stream */ NUCLEX_API virtual ~Stream() {} // // Stream implementation // public: /// Templated read method template<typename VarType> inline void read(VarType &Value) { readData(reinterpret_cast<void *>(&Value), sizeof(VarType)); } /// Templated read method template<typename VarType> inline VarType read() { VarType Var; read(Var); return Var; } /// Templated write method template<typename VarType> inline void write(const VarType &Value) { writeData(reinterpret_cast<const void *>(&Value), sizeof(VarType)); } /// Get stream name /** Retrieves the name of the stream (for debugging purposes only) @return The stream's name */ NUCLEX_API virtual string getName() const = 0; /// Get stream size /** Retrieves the size of the stream @return The stream's size */ NUCLEX_API virtual size_t getSize() const = 0; /// Seek to position /** Changes the current position in the stream @param Pos New seek position */ NUCLEX_API virtual void seekTo(size_t Pos) = 0; /// Current location /** Retrieves the current position in the stream @return The current location */ NUCLEX_API virtual size_t getLocation() const = 0; /// Read data /** Read data from the stream @param pDest Destination address @param nBytes Number of bytes to read @return The number of bytes actually read */ NUCLEX_API virtual size_t readData(void *pDest, size_t nBytes) = 0; /// Write data /** Write data to the stream @param pSource Source address @param nBytes Number of bytes to write @return The number of bytes actually written */ NUCLEX_API virtual size_t writeData(const void *pSource, size_t nBytes) = 0; /// Retrieve access mode /** Retrieves the stream's access mode @return The stream's access mode */ NUCLEX_API virtual AccessMode getAccessMode() const = 0; /// Flush stream cache /** Ensures the data sent to the stream is processed (eg. written to disc) */ NUCLEX_API virtual void flush() = 0; }; }} // namespace Nuclex::Storage #endif // NUCLEX_STORAGE_STREAM_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 130 ] ] ]
95ac77a0af92b3990a32cb9598248012cf01e169
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyJava/JRex/src/native/JRexWebProgressListenerImpl.cpp
ed5929384221cfbb4a75dd2f7213a15be34c2d66
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
7,983
cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * C.N Medappa <[email protected]><> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the NPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the NPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "JRexWindow.h" #include "JRex_JNI_ProgressEvent.h" using namespace JRex_JNI_ProgressEvent; /* void onStateChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aStateFlags, in nsresult aStatus); */ NS_IMETHODIMP JRexWindow::OnStateChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRUint32 aStateFlags, nsresult aStatus) { JREX_LOGLN("OnStateChange()--> aStateFlags<"<<aStateFlags<<"> mProgListenerAdded <"<<mProgListenerAdded<<">") if((aStateFlags & STATE_IS_NETWORK) && (mChromeFlag & nsIWebBrowserChrome::CHROME_OPENAS_CHROME)){ JREX_LOGLN("OnStateChange()--> Doing SizeToContent ") nsCOMPtr<nsIDOMWindow> contentWin; nsresult rv=mWebBrowser->GetContentDOMWindow(getter_AddRefs(contentWin)); if (contentWin) rv= contentWin->SizeToContent(); JREX_LOGLN("OnStateChange()--> SizeToContent rv<"<<rv<<">") } if(!mProgListenerAdded)return NS_OK; nsresult rv=NS_OK; StateChangeProgressEventParam *sParm=new StateChangeProgressEventParam; if(IS_NULL(sParm))return NS_ERROR_OUT_OF_MEMORY; sParm->target=NS_PTR_TO_INT32(this); sParm->progEventType=PROG_STATE_CHANGE; SetCommonParam(sParm,aWebProgress,aRequest); sParm->stateFlags=aStateFlags; sParm->status=aStatus; sParm->request=aRequest; rv=fireEvent(sParm,PR_FALSE,nsnull); JREX_LOGLN("OnStateChange()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress); */ NS_IMETHODIMP JRexWindow::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress) { JREX_LOGLN("OnProgressChange()--> aCurSelfProgress<"<<aCurSelfProgress <<"> aMaxSelfProgress<"<<aMaxSelfProgress <<"> aCurTotalProgress<"<<aCurTotalProgress <<"> aMaxTotalProgress<"<<aMaxTotalProgress <<"> mProgListenerAdded <"<<mProgListenerAdded<<">") if(!mProgListenerAdded)return NS_OK; nsresult rv=NS_OK; ProgressChangeProgressEventParam *sParm=new ProgressChangeProgressEventParam; if(IS_NULL(sParm))return NS_ERROR_OUT_OF_MEMORY; sParm->target=NS_PTR_TO_INT32(this); sParm->progEventType=PROG_PROGRESS_CHANGE; SetCommonParam(sParm,aWebProgress,aRequest); sParm->curSelfProgress=aCurSelfProgress; sParm->maxSelfProgress=aMaxSelfProgress; sParm->curTotalProgress=aCurTotalProgress; sParm->maxTotalProgress=aMaxTotalProgress; rv=fireEvent(sParm,PR_FALSE,nsnull); JREX_LOGLN("OnProgressChange()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */ NS_IMETHODIMP JRexWindow::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location) { JREX_LOGLN("OnLocationChange()--> *** location <"<<location<<"> mProgListenerAdded <"<<mProgListenerAdded<<"> ***") if(!mProgListenerAdded)return NS_OK; if (NOT_NULL(aWebProgress)) { nsCOMPtr<nsIDOMWindow> domWindow; nsCOMPtr<nsIDOMWindow> topDomWindow; aWebProgress->GetDOMWindow(getter_AddRefs(domWindow)); if (NOT_NULL(domWindow)){ domWindow->GetTop(getter_AddRefs(topDomWindow)); if (domWindow != topDomWindow){ nsresult rv=NS_OK; LocationChangeProgressEventParam *sParm=new LocationChangeProgressEventParam; if(IS_NULL(sParm))return NS_ERROR_OUT_OF_MEMORY; sParm->target=NS_PTR_TO_INT32(this); sParm->progEventType=PROG_LOC_CHANGE; SetCommonParam(sParm,aWebProgress,aRequest); if(NOT_NULL(location)){ JREX_LOGLN("OnLocationChange()--> *** NOT_NULL location ***") nsEmbedCString spec; rv=location->GetSpec(spec); if(NS_SUCCEEDED(rv)) sParm->loc =ToNewCString(spec); else sParm->loc=nsnull; }else{ JREX_LOGLN("OnLocationChange()--> *** NULL location ***") sParm->loc=nsnull; } rv=fireEvent(sParm,PR_FALSE,nsnull); JREX_LOGLN("OnLocationChange()--> *** fireEvent rv<"<<rv<<"> ***") } } } return NS_OK; } /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */ NS_IMETHODIMP JRexWindow::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage) { JREX_LOGLN("OnStatusChange()--> *** aStatus <"<<aStatus<<"> mProgListenerAdded <"<<mProgListenerAdded<<"> ***") if(!mProgListenerAdded)return NS_OK; nsresult rv=NS_OK; StatusChangeProgressEventParam *sParm=new StatusChangeProgressEventParam; if(IS_NULL(sParm))return NS_ERROR_OUT_OF_MEMORY; sParm->target=NS_PTR_TO_INT32(this); sParm->progEventType=PROG_STATUS_CHANGE; SetCommonParam(sParm,aWebProgress,aRequest); sParm->status=aStatus; if(NOT_NULL(aMessage)){ nsEmbedString statusStr(aMessage); char* temp=ToNewUTF8String(statusStr); JREX_LOGLN("OnStatusChange()--> *** status<"<<aStatus<<"> statusMessage<"<<temp<<"> ***") sParm->statusMessage=temp; }else sParm->statusMessage=nsnull; rv=fireEvent(sParm,PR_FALSE,nsnull); JREX_LOGLN("OnStatusChange()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* void onSecurityChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long state); */ NS_IMETHODIMP JRexWindow::OnSecurityChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRUint32 state) { JREX_LOGLN("OnSecurityChange()--> *** state <"<<state<<"> mProgListenerAdded <"<<mProgListenerAdded<<"> ***") if(!mProgListenerAdded)return NS_OK; nsresult rv=NS_OK; StateChangeProgressEventParam *sParm=new StateChangeProgressEventParam; if(IS_NULL(sParm))return NS_ERROR_OUT_OF_MEMORY; sParm->target=NS_PTR_TO_INT32(this); sParm->progEventType=PROG_SECURITY_CHANGE; SetCommonParam(sParm,aWebProgress,aRequest); sParm->stateFlags=state; sParm->status=rv; rv=fireEvent(sParm,PR_FALSE,nsnull); JREX_LOGLN("OnSecurityChange()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; }
[ [ [ 1, 178 ] ] ]
b29452e2369ccce05c66e1abfbfb471999c4bc55
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/gui/nguiskyeditor_main.cc
49968bd7fa9eb554c6b061e9d6c22e06f56ef17c
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
80,598
cc
//------------------------------------------------------------------------------ // nguiskyeditor_main.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gui/nguihorislidergroup.h" #include "scene/ntransformnode.h" #include "scene/nlightnode.h" #include "gui/nguitextlabel.h" #include "gui/nguicolorslidergroup.h" #include "scene/nskinanimator.h" #include "gui/nguitextlabel.h" #include "gui/nguitextview.h" #include "anim2/nanimstateinfo.h" #include "variable/nvariable.h" #include "variable/nvariableserver.h" #include "gui/nguiskyeditor.h" #include "scene/nskynode.h" #include "scene/nshapenode.h" #include "gui/nguicheckbutton.h" #include "kernel/ntimeserver.h" nNebulaClass(nGuiSkyEditor, "nguiformlayout"); //------------------------------------------------------------------------------ /** */ nGuiSkyEditor::nGuiSkyEditor(): sliderChanged(false), // ??? skyPath("/usr/scene"), refSky("/usr/scene"), layoutChanged(false), elementReady(true), activeElement(-1), oldElement(-1), activeState(-1), stateReady(true), refresh(false), saveSky(false), updateSkyTime(true), activeType(nSkyNode::InvalidElement) { this->FindSkyNode(refSky); } //------------------------------------------------------------------------------ /** */ nGuiSkyEditor::~nGuiSkyEditor() { // empty } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::OnShow() { // call parent class nGuiFormLayout::OnShow(); this->ShowSky(); // update all layouts this->UpdateLayout(this->rect); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::OnHide() { this->HideSky(); nGuiFormLayout::OnHide(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::OnEvent(const nGuiEvent& event) { this->EventSky(event); nGuiFormLayout::OnEvent(event); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ShowSky() { const float leftWidth = 0.3f; const float rightWidth = 0.15f; const float maxAngle = 360.0f; const float minHeight = -90.0f; const float maxHeight = 90.0f; const float border = 0.005f; const float sliderOffset = 0.025f; kernelServer->PushCwd(this); nGuiHoriSliderGroup* slider; if (this->refSky.isvalid()) { vector2 buttonSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("button_n"); nGuiTextButton* button = (nGuiTextButton*) kernelServer->New("nguitextbutton", "refreshButton"); n_assert(button); button->SetText("Refresh"); button->SetFont("GuiSmall"); button->SetAlignment(nGuiTextButton::Center); button->SetDefaultBrush("button_n"); button->SetPressedBrush("button_p"); button->SetHighlightBrush("button_h"); button->SetMinSize(buttonSize); button->SetMaxSize(buttonSize); button->SetColor(vector4(0,0,0,1)); this->AttachForm(button, nGuiFormLayout::Top, 3 * border); this->AttachForm(button, nGuiFormLayout::Right, 0.005f); button->OnShow(); this->refRefreshButton = button; button = (nGuiTextButton*) kernelServer->New("nguitextbutton", "saveButton"); n_assert(button); button->SetText("Save"); button->SetFont("GuiSmall"); button->SetAlignment(nGuiTextButton::Center); button->SetDefaultBrush("button_n"); button->SetPressedBrush("button_p"); button->SetHighlightBrush("button_h"); button->SetMinSize(buttonSize); button->SetMaxSize(buttonSize); button->SetColor(vector4(0,0,0,1)); this->AttachWidget(button, nGuiFormLayout::Right, this->refRefreshButton, 0.005f); this->AttachForm(button, nGuiFormLayout::Top, 3 * border); button->OnShow(); this->refSaveButton = button; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyStartTimeSlider"); slider->SetLeftText("Skytime start"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(this->refSky->GetTimePeriod()); slider->SetValue(this->refSky->GetSkyTime()); slider->SetKnobSize(this->refSky->GetTimePeriod()/10); slider->SetIncrement(1.0f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refSaveButton, 3 * border); // Animation pr?en this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); slider->OnShow(); this->refSkyTimeSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyTimeFactorSlider"); slider->SetLeftText("Skytime Factor"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(-1000.0f); slider->SetMaxValue(1000.0f); slider->SetValue(this->refSky->GetTimeFactor()); slider->SetKnobSize(200); slider->SetKnobSize(100.0f); slider->SetIncrement(1.0f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refSkyTimeSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); slider->OnShow(); this->refTimeFactorSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyElementSlider"); slider->SetLeftText("Sky Element"); slider->SetRightText("%d"); slider->SetMinValue(0); slider->SetMaxValue((float)this->refSky->GetNumElements()); slider->SetValue(0); slider->SetKnobSize(1); slider->SetIncrement(1); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refTimeFactorSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); slider->OnShow(); this->refElementSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyStateSlider"); slider->SetLeftText("Sky States"); slider->SetRightText("%d"); slider->SetMinValue(0); slider->SetMaxValue(0); slider->SetValue(0); slider->SetKnobSize(1); slider->SetIncrement(1); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refElementSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); slider->OnShow(); this->refStateSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyStateTimeSlider"); slider->SetLeftText("StateTime"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0); slider->SetMaxValue(0); slider->SetValue(1); slider->SetKnobSize(1); slider->SetIncrement(1); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refStateSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); slider->OnShow(); this->refStateTimeSlider = slider; nGuiTextLabel* textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "nSkyElementLabel"); n_assert(textLabel); textLabel->SetText("Element"); textLabel->SetFont("GuiSmall"); textLabel->SetAlignment(nGuiTextLabel::Right); vector2 textSize = textLabel->GetTextExtent(); vector2 textMinSize(0.0f, textSize.y); vector2 textMaxSize(1.0f, textSize.y); textLabel->SetColor(vector4(1.0f, 1.0f, 0.0f, 1.0f)); textLabel->SetMinSize(textMinSize); textLabel->SetMaxSize(textMaxSize); this->AttachWidget(textLabel, nGuiFormLayout::Top, this->refStateTimeSlider, border); this->AttachForm(textLabel, nGuiFormLayout::Left, border); this->AttachPos(textLabel, nGuiFormLayout::Right, 0.45f); textLabel->OnShow(); this->refElementLabel = textLabel; this->CreateCloud(); this->CreateSkycolor(); this->CreateSun(); this->CreateSunlight(); } kernelServer->PopCwd(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::HideSky() { if (this->refSky.isvalid()) { // FIXME: Check each slider this->refSkyTimeSlider->Release(); this->refTimeFactorSlider->Release(); this->refElementSlider->Release(); this->refStateSlider->Release(); this->refElementLabel->Release(); this->refRefreshButton->Release(); this->refSaveButton->Release(); this->refStateTimeSlider->Release(); } this->ReleaseCloud(); this->ReleaseSkycolor(); this->ReleaseSun(); this->ReleaseSunlight(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::EventSky(const nGuiEvent& event) { if (this->refSky.isvalid() && this->refSkyTimeSlider.isvalid() && this->refTimeFactorSlider.isvalid() && this->refElementSlider.isvalid() && this->refStateSlider.isvalid() && this->refRefreshButton.isvalid() && this->refSaveButton.isvalid() && this->refStateTimeSlider.isvalid()) { if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refRefreshButton)) { this->refresh = true; } else if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refSaveButton)) { this->saveSky = true; } if (event.GetWidget() == this->refSkyTimeSlider) { if (this->refSkyTimeSlider->Inside(nGuiServer::Instance()->GetMousePos())) { this->refSky->SetStartTime(this->refSky->GetStartTime() + (this->refSkyTimeSlider->GetValue() - this->refSky->GetSkyTime())); this->updateSkyTime = false; } } if (event.GetWidget() == this->refTimeFactorSlider) { this->refSky->SetTimeFactor(this->refTimeFactorSlider->GetValue()); } if (event.GetWidget() == this->refElementSlider) { int actualElement = (int)floor(this->refElementSlider->GetValue() - 1); if (actualElement != this->activeElement) { this->oldElement = this->activeElement; this->activeElement = actualElement; this->elementReady = false; this->layoutChanged = true; } } if (event.GetWidget() == this->refStateSlider) { int actualState = (int)floor(this->refStateSlider->GetValue() - 1); if (actualState != this->activeState) { this->activeState = actualState; this->stateReady = false; this->layoutChanged = true; } } if (event.GetWidget() == this->refStateTimeSlider) { if ((this->activeState > -1) && (this->activeElement > -1)) { int actualState = this->refSky->SetStateTime(this->activeElement, this->activeState, this->refStateTimeSlider->GetValue()); this->refStateSlider->SetValue((float)actualState + 1); } } } this->EventCloud(event); this->EventSkycolor(event); this->EventSun(event); this->EventSunlight(event); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::CreateCloud() { const float leftWidth = 0.3f; const float rightWidth = 0.15f; const float maxAngle = 360; const float minHeight = -90; const float maxHeight = 90; const float border = 0.005f; const float sliderOffset = 0.025f; kernelServer->PushCwd(this); nGuiHoriSliderGroup* slider; nGuiColorSliderGroup* colorSlider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudAddSlider"); slider->SetLeftText("Cloud Add"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(-3.0f); slider->SetMaxValue(3.0f); slider->SetValue(0); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refElementLabel, 2*border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudAddSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudMulSlider"); slider->SetLeftText("Cloud Mul"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(10.0f); slider->SetValue(1); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudAddSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudMulSlider = slider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "CloudColSlider"); colorSlider->SetLabelText("Cloud Col"); colorSlider->SetMaxIntensity(2.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refCloudMulSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refCloudColSlider = colorSlider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudGlowSlider"); slider->SetLeftText("Cloud Glow"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(3.0f); slider->SetValue(0.5f); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudColSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudGlowSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudRangeSlider"); slider->SetLeftText("Cloud Range"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(10.0f); slider->SetValue(1); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudGlowSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudRangeSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudDensSlider"); slider->SetLeftText("Cloud Dens"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(1.0f); slider->SetValue(0); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudRangeSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudDensSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudMapResSlider"); slider->SetLeftText("Cloud MapRes"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(5.0f); slider->SetValue(1); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudDensSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudMapResSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudStrucResSlider"); slider->SetLeftText("Cloud StrucRes"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(5.0f); slider->SetValue(1.0f); slider->SetKnobSize(0.5f); slider->SetIncrement(0.001f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudMapResSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudStrucResSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudMapDirSlider"); slider->SetLeftText("Cloud Dir"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(360.0f); slider->SetValue(0); slider->SetKnobSize(10.0f); slider->SetIncrement(0.1f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudStrucResSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudMapDirSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudMapSpeedSlider"); slider->SetLeftText("Cloud MapSpeed"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.000001f); slider->SetMaxValue(10.0f); slider->SetValue(1); slider->SetKnobSize(1.0f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudMapDirSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudMapSpeedSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudStrucSpeedSlider"); slider->SetLeftText("Cloud StrucSpeed"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.000001f); slider->SetMaxValue(10.0f); slider->SetValue(1); slider->SetKnobSize(1.0f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudMapSpeedSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudStrucSpeedSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "CloudWeightSlider"); slider->SetLeftText("Cloud Bumpweight"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(1.0f); slider->SetValue(0.7f); slider->SetKnobSize(0.1f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refCloudStrucSpeedSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refCloudWeightSlider = slider; kernelServer->PopCwd(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ShowCloud() { if (this->refElement.isvalid()) { if (this->refCloudAddSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudAddSlider, nShaderState::CloudMod, -3, 3, 1); this->refCloudAddSlider->Show(); } if (this->refCloudMulSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudMulSlider, nShaderState::CloudMod, 0, 10, 2); this->refCloudMulSlider->Show(); } if (this->refCloudColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refCloudColSlider, nShaderState::MatDiffuse, 2); this->refCloudColSlider->Show(); } if (this->refCloudGlowSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudGlowSlider, nShaderState::Glow, 0, 3); this->refCloudGlowSlider->Show(); } if (this->refCloudRangeSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudRangeSlider, nShaderState::SunRange, 0, 10); this->refCloudRangeSlider->Show(); } if (this->refCloudDensSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudDensSlider, nShaderState::Density, 0, 1); this->refCloudDensSlider->Show(); } if (this->refCloudMapResSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudMapResSlider, nShaderState::Map0uvRes, 0, 5); this->refCloudMapResSlider->Show(); } if (this->refCloudStrucResSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudStrucResSlider, nShaderState::Map1uvRes, 0, 5); this->refCloudStrucResSlider->Show(); } if (this->refCloudMapDirSlider.isvalid()) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); vector2 dirvec = vector2(vec.x,vec.y); if (dirvec.x == 0) dirvec.x = 0.0001f; float dir =(float)(90-((atan(fabs(dirvec.y)/fabs(dirvec.x))*180)/N_PI)); if ((dirvec.x > 0)&&(dirvec.y < 0)) dir += 90; else if ((dirvec.x < 0)&&(dirvec.y < 0)) dir += 180; else if ((dirvec.x < 0)&&(dirvec.y > 0)) dir += 270; float min = 0; float max = 360; this->refCloudMapDirSlider->SetMinValue(min); this->refCloudMapDirSlider->SetMaxValue(max); this->refCloudMapDirSlider->SetKnobSize((float)(fabs(min)+max)/10); this->refCloudMapDirSlider->SetValue(dir); } else { this->refCloudMapDirSlider->SetMinValue(0); this->refCloudMapDirSlider->SetMaxValue(0); this->refCloudMapDirSlider->SetKnobSize(1); this->refCloudMapDirSlider->SetValue(0); } this->refCloudMapDirSlider->Show(); } if (this->refCloudMapSpeedSlider.isvalid()) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); vector2 dirvec = vector2(vec.x,vec.y); float min = 0; float max = 10; this->refCloudMapSpeedSlider->SetMinValue(min); this->refCloudMapSpeedSlider->SetMaxValue(max); this->refCloudMapSpeedSlider->SetKnobSize((float)(fabs(min)+max)/10); this->refCloudMapSpeedSlider->SetValue(dirvec.len()); } else { this->refCloudMapSpeedSlider->SetMinValue(0); this->refCloudMapSpeedSlider->SetMaxValue(0); this->refCloudMapSpeedSlider->SetKnobSize(1); this->refCloudMapSpeedSlider->SetValue(0); } this->refCloudMapSpeedSlider->Show(); } if (this->refCloudStrucSpeedSlider.isvalid()) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); vector2 dirvec = vector2(vec.z,vec.w); float min = 0; float max = 10; this->refCloudStrucSpeedSlider->SetMinValue(min); this->refCloudStrucSpeedSlider->SetMaxValue(max); this->refCloudStrucSpeedSlider->SetKnobSize((float)(fabs(min)+max)/10); this->refCloudStrucSpeedSlider->SetValue(dirvec.len()); } else { this->refCloudStrucSpeedSlider->SetMinValue(0); this->refCloudStrucSpeedSlider->SetMaxValue(0); this->refCloudStrucSpeedSlider->SetKnobSize(1); this->refCloudStrucSpeedSlider->SetValue(0); } this->refCloudStrucSpeedSlider->Show(); } if (this->refCloudWeightSlider.isvalid()) { this->UpdateSliderFromElement(this->refCloudWeightSlider, nShaderState::Weight, 0, 1); this->refCloudWeightSlider->Show(); } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::EventCloud(const nGuiEvent& event) { if (this->elementReady && (this->activeType == nSkyNode::CloudElement) && this->refSky.isvalid() && this->refElement.isvalid() && this->refCloudAddSlider.isvalid() && this->refCloudColSlider.isvalid() && this->refCloudGlowSlider.isvalid() && this->refCloudRangeSlider.isvalid() && this->refCloudDensSlider.isvalid() && this->refCloudMapResSlider.isvalid() && this->refCloudStrucResSlider.isvalid() && this->refCloudMapDirSlider.isvalid() && this->refCloudMapSpeedSlider.isvalid() && this->refCloudStrucSpeedSlider.isvalid() && this->refCloudMulSlider.isvalid()) { if (event.GetWidget() == this->refCloudAddSlider) { if (this->refElement.isvalid() && (this->refCloudAddSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::CloudMod)) { vector4 vec = this->refElement->GetVector(nShaderState::CloudMod); vec.x = this->refCloudAddSlider->GetValue(); this->refElement->SetVector(nShaderState::CloudMod, vec); } else { vector4 vec(0,1,0,0); vec.x = this->refCloudAddSlider->GetValue(); this->refElement->SetVector(nShaderState::CloudMod, vec); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudMulSlider) { if (this->refElement.isvalid() && (this->refCloudMulSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::CloudMod)) { vector4 vec = this->refElement->GetVector(nShaderState::CloudMod); vec.y = this->refCloudMulSlider->GetValue(); this->refElement->SetVector(nShaderState::CloudMod, vec); } else { vector4 vec(0,1,0,0); vec.y = this->refCloudMulSlider->GetValue(); this->refElement->SetVector(nShaderState::CloudMod, vec); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudColSlider) { if (this->refElement.isvalid() && (this->refCloudColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::MatDiffuse)) { this->refElement->SetVector(nShaderState::MatDiffuse, this->refCloudColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::MatDiffuse, this->refCloudColSlider->GetColor()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudGlowSlider) { if (this->refElement.isvalid() && (this->refCloudGlowSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Glow)) { this->refElement->SetFloat(nShaderState::Glow, this->refCloudGlowSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Glow, this->refCloudGlowSlider->GetValue()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudRangeSlider) { if (this->refElement.isvalid() && (this->refCloudRangeSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::SunRange)) { this->refElement->SetFloat(nShaderState::SunRange, this->refCloudRangeSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::SunRange, this->refCloudRangeSlider->GetValue()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudDensSlider) { if (this->refElement.isvalid() && (this->refCloudDensSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Density)) { this->refElement->SetFloat(nShaderState::Density, this->refCloudDensSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Density, this->refCloudDensSlider->GetValue()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudMapResSlider) { if (this->refElement.isvalid() && (this->refCloudMapResSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Map0uvRes)) { this->refElement->SetFloat(nShaderState::Map0uvRes, this->refCloudMapResSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Map0uvRes, this->refCloudMapResSlider->GetValue()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudStrucResSlider) { if (this->refElement.isvalid() && (this->refCloudStrucResSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Map1uvRes)) { this->refElement->SetFloat(nShaderState::Map1uvRes, this->refCloudStrucResSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Map1uvRes, this->refCloudStrucResSlider->GetValue()); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudMapDirSlider) { if (this->refElement.isvalid() && (this->refCloudMapDirSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); float dir = this->refCloudMapDirSlider->GetValue(); dir = (dir*N_PI)/180; vector2 dirvec(vec.x,vec.y); vector2 dirvec2(vec.w,vec.z); float len = dirvec.len(); float len2 = dirvec2.len(); dirvec = vector2(0,1); dirvec.rotate(dir); vec.x = dirvec.x * len; vec.y = dirvec.y * len; vec.z = dirvec.x * len2; // Zusammengeschaltet vec.w = dirvec.y * len2; this->refElement->SetVector(nShaderState::Move, vec); } else { vector4 vec(0.0f,0.1f,0.0f,0.1f); float dir = this->refCloudMapDirSlider->GetValue(); dir = (dir*N_PI)/180; vector2 dirvec(vec.x,vec.y); vector2 dirvec2(vec.w,vec.z); float len = dirvec.len(); float len2 = dirvec2.len(); dirvec = vector2(0,1); dirvec.rotate(dir); vec.x = dirvec.x * len; vec.y = dirvec.y * len; vec.z = dirvec.x * len2; // Zusammengeschaltet vec.w = dirvec.y * len2; this->refElement->SetVector(nShaderState::Move, vec); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudMapSpeedSlider) { if (this->refElement.isvalid() && (this->refCloudMapSpeedSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); vector2 dirvec(vec.x,vec.y); dirvec.norm(); float len = this->refCloudMapSpeedSlider->GetValue(); vec.x = dirvec.x * len; vec.y = dirvec.y * len; this->refElement->SetVector(nShaderState::Move, vec); } else { vector4 vec(0.0f,0.1f,0.0f,0.1f); vector2 dirvec(vec.x,vec.y); dirvec.norm(); float len = this->refCloudMapSpeedSlider->GetValue(); vec.x = dirvec.x * len; vec.y = dirvec.y * len; this->refElement->SetVector(nShaderState::Move, vec); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudStrucSpeedSlider) { if (this->refElement.isvalid() && (this->refCloudStrucSpeedSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Move)) { vector4 vec = this->refElement->GetVector(nShaderState::Move); vector2 dirvec(vec.x,vec.y); dirvec.norm(); float len = this->refCloudStrucSpeedSlider->GetValue(); vec.z = dirvec.x * len; vec.w = dirvec.y * len; this->refElement->SetVector(nShaderState::Move, vec); } else { vector4 vec(0.0f,0.1f,0.0f,0.1f); vector2 dirvec(vec.x,vec.y); dirvec.norm(); float len = this->refCloudStrucSpeedSlider->GetValue(); vec.z = dirvec.x * len; vec.w = dirvec.y * len; this->refElement->SetVector(nShaderState::Move, vec); this->ShowCloud(); } } } if (event.GetWidget() == this->refCloudWeightSlider) { if (this->refElement.isvalid() && (this->refCloudWeightSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Weight)) { this->refElement->SetFloat(nShaderState::Weight, this->refCloudWeightSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Weight, this->refCloudWeightSlider->GetValue()); this->ShowCloud(); } } } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::HideCloud() { if (this->refElement.isvalid()) { if (this->refCloudAddSlider.isvalid()) this->refCloudAddSlider->Hide(); if (this->refCloudMulSlider.isvalid()) this->refCloudMulSlider->Hide(); if (this->refCloudColSlider.isvalid()) this->refCloudColSlider->Hide(); if (this->refCloudGlowSlider.isvalid()) this->refCloudGlowSlider->Hide(); if (this->refCloudRangeSlider.isvalid()) this->refCloudRangeSlider->Hide(); if (this->refCloudDensSlider.isvalid()) this->refCloudDensSlider->Hide(); if (this->refCloudMapResSlider.isvalid()) this->refCloudMapResSlider->Hide(); if (this->refCloudStrucResSlider.isvalid()) this->refCloudStrucResSlider->Hide(); if (this->refCloudMapDirSlider.isvalid()) this->refCloudMapDirSlider->Hide(); if (this->refCloudMapSpeedSlider.isvalid()) this->refCloudMapSpeedSlider->Hide(); if (this->refCloudStrucSpeedSlider.isvalid()) this->refCloudStrucSpeedSlider->Hide(); if (this->refCloudWeightSlider.isvalid()) this->refCloudWeightSlider->Hide(); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ReleaseCloud() { if (this->refElement.isvalid()) { // FIXME: check each one this->refCloudAddSlider->Release(); this->refCloudMulSlider->Release(); this->refCloudColSlider->Release(); this->refCloudGlowSlider->Release(); this->refCloudRangeSlider->Release(); this->refCloudDensSlider->Release(); this->refCloudMapResSlider->Release(); this->refCloudStrucResSlider->Release(); this->refCloudMapDirSlider->Release(); this->refCloudMapSpeedSlider->Release(); this->refCloudStrucSpeedSlider->Release(); this->refCloudWeightSlider->Release(); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::CreateSkycolor() { const float leftWidth = 0.3f; const float rightWidth = 0.15f; const float border = 0.005f; const float sliderOffset = 0.025f; kernelServer->PushCwd(this); nGuiHoriSliderGroup* slider; nGuiColorSliderGroup* colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SkyTopColSlider"); colorSlider->SetLabelText("Sky TopCol"); colorSlider->SetMaxIntensity(1.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(0.3f,0.3f,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refElementLabel, 2*border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSkyTopColSlider = colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SkyBotColSlider"); colorSlider->SetLabelText("Sky BotCol"); colorSlider->SetMaxIntensity(1.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(0.6f,0.6f,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSkyTopColSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSkyBotColSlider = colorSlider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyBottomSlider"); slider->SetLeftText("Sky Bottom"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(-1.0f); slider->SetMaxValue(1.0f); slider->SetValue(0); slider->SetKnobSize(0.4f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refSkyBotColSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkyBottomSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkyBrightSlider"); slider->SetLeftText("Sky Brightness"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(1.0f); slider->SetValue(1); slider->SetKnobSize(0.2f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refSkyBottomSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkyBrightSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkySatSlider"); slider->SetLeftText("Sky Saturation"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(1.0f); slider->SetValue(1); slider->SetKnobSize(0.2f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top, this->refSkyBrightSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkySatSlider = slider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SkySunColSlider"); colorSlider->SetLabelText("Sky SunCol"); colorSlider->SetMaxIntensity(1.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSkySatSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSkySunColSlider = colorSlider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkySunRangeSlider"); slider->SetLeftText("Sky Sunrange"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(2.0f); slider->SetValue(1); slider->SetKnobSize(0.4f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top, this->refSkySunColSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkySunRangeSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkySunIntensSlider"); slider->SetLeftText("Sky Sunintensity"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(2.0f); slider->SetValue(1); slider->SetKnobSize(0.4f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top, this->refSkySunRangeSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkySunIntensSlider = slider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SkySunFlatSlider"); slider->SetLeftText("Sky Sunflatness"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(5.0f); slider->SetValue(0); slider->SetKnobSize(0.4f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top, this->refSkySunIntensSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSkySunFlatSlider = slider; kernelServer->PopCwd(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ShowSkycolor() { if (this->refElement.isvalid()) { if (this->refSkyTopColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSkyTopColSlider,nShaderState::TopColor, 1); this->refSkyTopColSlider->Show(); } if (this->refSkyBotColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSkyBotColSlider,nShaderState::BottomColor, 1); this->refSkyBotColSlider->Show(); } if (this->refSkyBottomSlider.isvalid()) { UpdateSliderFromElement(refSkyBottomSlider,nShaderState::SkyBottom, -2, 1); this->refSkyBottomSlider->Show(); } if (this->refSkyBrightSlider.isvalid()) { UpdateSliderFromElement(refSkyBrightSlider,nShaderState::Brightness, 0, 1, 4); this->refSkyBrightSlider->Show(); } if (this->refSkySatSlider.isvalid()) { UpdateSliderFromElement(refSkySatSlider,nShaderState::Saturation, 0, 1, 4); this->refSkySatSlider->Show(); } if (this->refSkySunColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSkySunColSlider,nShaderState::SunColor, 1); this->refSkySunColSlider->Show(); } if (this->refSkySunRangeSlider.isvalid()) { UpdateSliderFromElement(refSkySunRangeSlider,nShaderState::SunRange, 0, 2); this->refSkySunRangeSlider->Show(); } if (this->refSkySunIntensSlider.isvalid()) { UpdateSliderFromElement(refSkySunIntensSlider,nShaderState::Intensity0, 0, 2); this->refSkySunIntensSlider->Show(); } if (this->refSkySunFlatSlider.isvalid()) { UpdateSliderFromElement(refSkySunFlatSlider,nShaderState::SunFlat, 0, 8); this->refSkySunFlatSlider->Show(); } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::EventSkycolor(const nGuiEvent& event) { if (this->elementReady && (this->activeType == nSkyNode::SkyElement) && this->refSky.isvalid() && this->refElement.isvalid() && this->refSkyTopColSlider.isvalid() && this->refSkyBotColSlider.isvalid() && this->refSkySunColSlider.isvalid() && this->refSkyBrightSlider.isvalid() && this->refSkySatSlider.isvalid()&& this->refSkyBottomSlider.isvalid()&& this->refSkySunRangeSlider.isvalid()&& this->refSkySunIntensSlider.isvalid()&& this->refSkySunFlatSlider.isvalid()) { if (event.GetWidget() == this->refSkyTopColSlider) { if (this->refElement.isvalid() && (this->refSkyTopColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::TopColor)) { this->refElement->SetVector(nShaderState::TopColor, this->refSkyTopColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::TopColor, this->refSkyTopColSlider->GetColor()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkyBotColSlider) { if (this->refElement.isvalid() && (this->refSkyBotColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::BottomColor)) { this->refElement->SetVector(nShaderState::BottomColor, this->refSkyBotColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::BottomColor, this->refSkyBotColSlider->GetColor()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkyBottomSlider) { if (this->refElement.isvalid() && (this->refSkyBottomSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::SkyBottom)) { this->refElement->SetFloat(nShaderState::SkyBottom, this->refSkyBottomSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::SkyBottom, this->refSkyBottomSlider->GetValue()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkyBrightSlider) { if (this->refElement.isvalid() && (this->refSkyBrightSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Brightness)) { this->refElement->SetVector(nShaderState::Brightness, vector4(1,1,1,this->refSkyBrightSlider->GetValue())); } else { this->refElement->SetVector(nShaderState::Brightness, vector4(1,1,1,this->refSkyBrightSlider->GetValue())); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkySatSlider) { if (this->refElement.isvalid() && (this->refSkySatSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Saturation)) { this->refElement->SetVector(nShaderState::Saturation, vector4(1,1,1,this->refSkySatSlider->GetValue())); } else { this->refElement->SetVector(nShaderState::Saturation, vector4(1,1,1,this->refSkySatSlider->GetValue())); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkySunColSlider) { if (this->refElement.isvalid() && (this->refSkySunColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::SunColor)) { this->refElement->SetVector(nShaderState::SunColor, this->refSkySunColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::SunColor, this->refSkySunColSlider->GetColor()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkySunRangeSlider) { if (this->refElement.isvalid() && (this->refSkySunRangeSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::SunRange)) { this->refElement->SetFloat(nShaderState::SunRange, this->refSkySunRangeSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::SunRange, this->refSkySunRangeSlider->GetValue()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkySunIntensSlider) { if (this->refElement.isvalid() && (this->refSkySunIntensSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::Intensity0)) { this->refElement->SetFloat(nShaderState::Intensity0, this->refSkySunIntensSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::Intensity0, this->refSkySunIntensSlider->GetValue()); this->ShowSkycolor(); } } } if (event.GetWidget() == this->refSkySunFlatSlider) { if (this->refElement.isvalid() && (this->refSkySunFlatSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::SunFlat)) { this->refElement->SetFloat(nShaderState::SunFlat, this->refSkySunFlatSlider->GetValue()); } else { this->refElement->SetFloat(nShaderState::SunFlat, this->refSkySunFlatSlider->GetValue()); this->ShowSkycolor(); } } } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::HideSkycolor() { if (this->refSkyTopColSlider.isvalid()) this->refSkyTopColSlider->Hide(); if (this->refSkyBotColSlider.isvalid()) this->refSkyBotColSlider->Hide(); if (this->refSkySunColSlider.isvalid()) this->refSkySunColSlider->Hide(); if (this->refSkyBrightSlider.isvalid()) this->refSkyBrightSlider->Hide(); if (this->refSkySatSlider.isvalid()) this->refSkySatSlider->Hide(); if (this->refSkyBottomSlider.isvalid()) this->refSkyBottomSlider->Hide(); if (this->refSkySunRangeSlider.isvalid()) this->refSkySunRangeSlider->Hide(); if (this->refSkySunIntensSlider.isvalid()) this->refSkySunIntensSlider->Hide(); if (this->refSkySunFlatSlider.isvalid()) this->refSkySunFlatSlider->Hide(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ReleaseSkycolor() { if (this->refElement.isvalid()) { // FIXME: check each one this->refSkyTopColSlider->Release(); this->refSkyBotColSlider->Release(); this->refSkySunColSlider->Release(); this->refSkyBrightSlider->Release(); this->refSkySatSlider->Release(); this->refSkyBottomSlider->Release(); this->refSkySunRangeSlider->Release(); this->refSkySunIntensSlider->Release(); this->refSkySunFlatSlider->Release(); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::CreateSun() { const float leftWidth = 0.3f; const float rightWidth = 0.15f; const float border = 0.005f; const float sliderOffset = 0.025f; kernelServer->PushCwd(this); nGuiHoriSliderGroup* slider; nGuiColorSliderGroup* colorSlider; colorSlider = (nGuiColorSliderGroup*)kernelServer->New("nguicolorslidergroup", "SunColSlider"); colorSlider->SetLabelText("Sun Color"); colorSlider->SetMaxIntensity(10.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1.0f, 1.0f, 1.0f, 1.0f)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refElementLabel, 2*border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSunColSlider = colorSlider; slider = (nGuiHoriSliderGroup*) kernelServer->New("nguihorislidergroup", "SunScaleSlider"); slider->SetLeftText("Sun Scale"); slider->SetRightText("%f"); slider->SetDisplayFormat(nGuiHoriSliderGroup::Float); slider->SetMinValue(0.0f); slider->SetMaxValue(5.0f); slider->SetValue(0.0f); slider->SetKnobSize(0.05f); slider->SetIncrement(0.01f); slider->SetLeftWidth(leftWidth); slider->SetRightWidth(rightWidth); this->AttachWidget(slider, nGuiFormLayout::Top,this->refSunColSlider, border); this->AttachForm(slider, nGuiFormLayout::Left, border); this->AttachForm(slider, nGuiFormLayout::Right, border); this->refSunScaleSlider = slider; kernelServer->PopCwd(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ShowSun() { if (this->refElement.isvalid()) { if (this->refSunColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSunColSlider,nShaderState::MatDiffuse, 10); this->refSunColSlider->Show(); } if (this->refSunScaleSlider.isvalid()) { UpdateSliderFromElement(refSunScaleSlider,nShaderState::ScaleVector, 0, 5, 4); this->refSunScaleSlider->Show(); } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::EventSun(const nGuiEvent& event) { if (this->elementReady && (this->activeType == nSkyNode::SunElement) && this->refSky.isvalid() && this->refElement.isvalid() && this->refSunColSlider.isvalid() && this->refSunScaleSlider.isvalid()) { if (event.GetWidget() == this->refSunColSlider) { if (this->refElement.isvalid() && (this->refSunColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::MatDiffuse)) { this->refElement->SetVector(nShaderState::MatDiffuse, this->refSunColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::MatDiffuse, this->refSunColSlider->GetColor()); this->ShowSun(); } } } if (event.GetWidget() == this->refSunScaleSlider) { if (this->refElement.isvalid() && (this->refSunScaleSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::ScaleVector)) { this->refElement->SetVector(nShaderState::ScaleVector, vector4(1,1,1,this->refSunScaleSlider->GetValue())); } else { this->refElement->SetVector(nShaderState::ScaleVector, vector4(1,1,1,this->refSunScaleSlider->GetValue())); this->ShowSun(); } } } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::HideSun() { if (this->refSunColSlider.isvalid()) this->refSunColSlider->Hide(); if (this->refSunScaleSlider.isvalid()) this->refSunScaleSlider->Hide(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ReleaseSun() { if (this->refElement.isvalid()) { // FIXME: check each one this->refSunColSlider->Release(); this->refSunScaleSlider->Release(); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::CreateSunlight() { const float leftWidth = 0.3f; const float rightWidth = 0.15f; const float maxAngle = 360.0f; const float minHeight = -90.0f; const float maxHeight = 90.0f; const float border = 0.005f; const float sliderOffset = 0.025f; kernelServer->PushCwd(this); nGuiColorSliderGroup* colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SunlightDiffColSlider"); colorSlider->SetLabelText("Sunlight Diffuse"); colorSlider->SetMaxIntensity(3.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refElementLabel, 2*border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSunLightDiffuseColSlider = colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SunlightDiff1ColSlider"); colorSlider->SetLabelText("Sunlight Diffuse1"); colorSlider->SetMaxIntensity(3.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSunLightDiffuseColSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSunLightDiffuse1ColSlider = colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SunlightAmbiColSlider"); colorSlider->SetLabelText("Sunlight Ambient"); colorSlider->SetMaxIntensity(3.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSunLightDiffuse1ColSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSunLightAmbientColSlider = colorSlider; colorSlider = (nGuiColorSliderGroup*) kernelServer->New("nguicolorslidergroup", "SunlightSpecColSlider"); colorSlider->SetLabelText("Sunlight Specular"); colorSlider->SetMaxIntensity(3.0f); colorSlider->SetTextLabelWidth(leftWidth); colorSlider->SetColor(vector4(1,1,1,1)); this->AttachWidget(colorSlider, nGuiFormLayout::Top, this->refSunLightAmbientColSlider, border); this->AttachForm(colorSlider, nGuiFormLayout::Left, border); this->AttachForm(colorSlider, nGuiFormLayout::Right, border); this->refSunLightSpecularColSlider = colorSlider; kernelServer->PopCwd(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ShowSunlight() { if (this->refElement.isvalid()) { if (this->refSunLightDiffuseColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSunLightDiffuseColSlider,nShaderState::LightDiffuse, 10); this->refSunLightDiffuseColSlider->Show(); } if (this->refSunLightDiffuse1ColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSunLightDiffuse1ColSlider,nShaderState::LightDiffuse1, 10); this->refSunLightDiffuse1ColSlider->Show(); } if (this->refSunLightAmbientColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSunLightAmbientColSlider,nShaderState::LightAmbient, 10); this->refSunLightAmbientColSlider->Show(); } if (this->refSunLightSpecularColSlider.isvalid()) { this->UpdateColorSliderFromElement(this->refSunLightSpecularColSlider,nShaderState::LightSpecular, 10); this->refSunLightSpecularColSlider->Show(); } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::EventSunlight(const nGuiEvent& event) { if (this->elementReady && (this->activeType == nSkyNode::LightElement) && this->refSky.isvalid() && this->refElement.isvalid() && this->refSunLightDiffuseColSlider.isvalid() && this->refSunLightDiffuse1ColSlider.isvalid() && this->refSunLightAmbientColSlider.isvalid() && this->refSunLightSpecularColSlider.isvalid()) { if (event.GetWidget() == this->refSunLightDiffuseColSlider) { if (this->refElement.isvalid() && (this->refSunLightDiffuseColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::LightDiffuse)) { this->refElement->SetVector(nShaderState::LightDiffuse, this->refSunLightDiffuseColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::LightDiffuse, this->refSunLightDiffuseColSlider->GetColor()); this->ShowSunlight(); } } } if (event.GetWidget() == this->refSunLightDiffuse1ColSlider) { if (this->refElement.isvalid() && (this->refSunLightDiffuse1ColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::LightDiffuse1)) { this->refElement->SetVector(nShaderState::LightDiffuse1, this->refSunLightDiffuse1ColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::LightDiffuse1, this->refSunLightDiffuse1ColSlider->GetColor()); this->ShowSunlight(); } } } if (event.GetWidget() == this->refSunLightAmbientColSlider) { if (this->refElement.isvalid() && (this->refSunLightAmbientColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::LightAmbient)) { this->refElement->SetVector(nShaderState::LightAmbient, this->refSunLightAmbientColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::LightAmbient, this->refSunLightAmbientColSlider->GetColor()); this->ShowSunlight(); } } } if (event.GetWidget() == this->refSunLightSpecularColSlider) { if (this->refElement.isvalid() && (this->refSunLightSpecularColSlider->Inside(nGuiServer::Instance()->GetMousePos()))) { if (this->refElement->HasParam(nShaderState::LightSpecular)) { this->refElement->SetVector(nShaderState::LightSpecular, this->refSunLightSpecularColSlider->GetColor()); } else { this->refElement->SetVector(nShaderState::LightSpecular, this->refSunLightSpecularColSlider->GetColor()); this->ShowSunlight(); } } } } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::HideSunlight() { if (this->refSunLightDiffuseColSlider.isvalid()) this->refSunLightDiffuseColSlider->Hide(); if (this->refSunLightDiffuse1ColSlider.isvalid()) this->refSunLightDiffuse1ColSlider->Hide(); if (this->refSunLightAmbientColSlider.isvalid()) this->refSunLightAmbientColSlider->Hide(); if (this->refSunLightSpecularColSlider.isvalid()) this->refSunLightSpecularColSlider->Hide(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::ReleaseSunlight() { if (this->refElement.isvalid()) { // FIXME: Check each one this->refSunLightDiffuseColSlider->Release(); this->refSunLightDiffuse1ColSlider->Release(); this->refSunLightAmbientColSlider->Release(); this->refSunLightSpecularColSlider->Release(); } } //------------------------------------------------------------------------------ /** called per frame when parent widget is visible */ void nGuiSkyEditor::OnFrame() { nSkyNode::ElementType type; if (this->layoutChanged) { // Element if (!this->elementReady) { if (this->oldElement > -1) { type = this->refSky->GetElementType(this->oldElement); switch (type) { case nSkyNode::CloudElement: this->HideCloud(); break; case nSkyNode::SkyElement: this->HideSkycolor(); break; case nSkyNode::SunElement: this->HideSun(); break; case nSkyNode::LightElement: this->HideSunlight(); break; } this->activeType = nSkyNode::InvalidElement; } if (this->activeElement > -1) { this->refElement = this->refSky->GetElement(this->activeElement); type = this->refSky->GetElementType(this->activeElement); switch (type) { case nSkyNode::CloudElement: this->ShowCloud(); break; case nSkyNode::SkyElement: this->ShowSkycolor(); break; case nSkyNode::SunElement: this->ShowSun(); break; case nSkyNode::LightElement: this->ShowSunlight(); break; } this->activeType = type; this->refStateSlider->SetValue(0); this->refStateSlider->SetMaxValue((float)this->refSky->GetNumStates(this->activeElement)); this->refStateSlider->OnShow(); this->refElementLabel->SetText(this->refElement->GetName()); this->refStateTimeSlider->SetValue(0); this->refStateTimeSlider->SetKnobSize(1); this->refStateTimeSlider->SetMaxValue(0); this->refStateTimeSlider->OnShow(); } else if (this->activeElement == -1) { this->refStateSlider->SetValue(0); this->refStateSlider->SetMaxValue(0); this->refStateSlider->OnShow(); this->refElementLabel->SetText("nSkyNode"); this->refStateTimeSlider->SetValue(0); this->refStateTimeSlider->SetKnobSize(1); this->refStateTimeSlider->SetMaxValue(0); this->refStateTimeSlider->OnShow(); } this->elementReady = true; } //State if (!this->stateReady) { if (this->activeElement > -1) { type = this->refSky->GetElementType(this->activeElement); switch (type) { case nSkyNode::CloudElement: this->HideCloud(); break; case nSkyNode::SkyElement: this->HideSkycolor(); break; case nSkyNode::SunElement: this->HideSun(); break; case nSkyNode::LightElement: this->HideSunlight(); break; } this->activeType = nSkyNode::InvalidElement; } if ((this->activeState > -1) && (this->activeElement > -1)) { this->refElement = this->refSky->GetState(this->activeElement, this->activeState); type = this->refSky->GetElementType(this->activeElement); switch (type) { case nSkyNode::CloudElement: this->ShowCloud(); break; case nSkyNode::SkyElement: this->ShowSkycolor(); break; case nSkyNode::SunElement: this->ShowSun(); break; case nSkyNode::LightElement: this->ShowSunlight(); break; } this->activeType = type; this->refElementLabel->SetText(this->refElement->GetName()); this->refStateTimeSlider->SetMaxValue(this->refSky->GetTimePeriod()); this->refStateTimeSlider->SetValue(this->refSky->GetStateTime(this->activeElement, this->activeState)); this->refStateTimeSlider->SetKnobSize(this->refSky->GetTimePeriod()/10); this->refStateTimeSlider->OnShow(); } else if ((this->activeState == -1) && (this->activeElement > -1)) { this->refElement = this->refSky->GetElement(this->activeElement); type = this->refSky->GetElementType(this->activeElement); switch (type) { case nSkyNode::CloudElement: this->ShowCloud(); break; case nSkyNode::SkyElement: this->ShowSkycolor(); break; case nSkyNode::SunElement: this->ShowSun(); break; case nSkyNode::LightElement: this->ShowSunlight(); break; } this->activeType = type; this->refStateSlider->SetValue(0); this->refStateSlider->SetMaxValue((float)this->refSky->GetNumStates(this->activeElement)); this->refStateSlider->OnShow(); this->refElementLabel->SetText(this->refElement->GetName()); this->refStateTimeSlider->SetValue(0); this->refStateTimeSlider->SetKnobSize(1); this->refStateTimeSlider->SetMaxValue(0); this->refStateTimeSlider->OnShow(); } this->stateReady = true; } this->layoutChanged = false; this->UpdateLayout(this->GetRect()); } // Refresh Button was pressed if (this->refresh && (this->activeElement > -1) && (this->refSky.isvalid())) { type = this->refSky->GetElementType(this->activeElement); switch (type) { case nSkyNode::CloudElement: this->ShowCloud(); break; case nSkyNode::SkyElement: this->ShowSkycolor(); break; case nSkyNode::SunElement: this->ShowSun(); break; case nSkyNode::LightElement: this->ShowSunlight(); break; } this->refStateTimeSlider->OnShow(); this->refresh = false; } // Don't update skytime slider, if it was moved if (this->updateSkyTime && this->refSkyTimeSlider.isvalid() && this->refSky.isvalid()) { this->refSkyTimeSlider->SetValue(this->refSky->GetSkyTime()); } else { this->updateSkyTime = true; } // Save Button was pressed if (this->saveSky) { // FIXME: Hardcoded... nDynAutoRef<nRoot> refPath(this->skyPath.ExtractToLastSlash().Get()); refPath->SaveAs("proj:export/gfxlib/examples/SkySave.n2"); this->saveSky = false; } nGuiFormLayout::OnFrame(); } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::UpdateSliderFromElement(nGuiHoriSliderGroup* slider, nShaderState::Param param, float min, float max, int vectornr) { if (this->refElement->HasParam(param)) { slider->SetMinValue(min); slider->SetMaxValue(max); slider->SetKnobSize((float)(fabs(min) + max)/10); if (vectornr == 0) { slider->SetValue(this->refElement->GetFloat(param)); } else if (vectornr > 0 && vectornr <= 4) { switch (vectornr) { case 1: slider->SetValue(this->refElement->GetVector(param).x); break; case 2: slider->SetValue(this->refElement->GetVector(param).y); break; case 3: slider->SetValue(this->refElement->GetVector(param).z); break; case 4: slider->SetValue(this->refElement->GetVector(param).w); break; } } else n_assert(false); } else { slider->SetMinValue(0); slider->SetMaxValue(0); slider->SetKnobSize(1); slider->SetValue(0); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::UpdateColorSliderFromElement(nGuiColorSliderGroup* slider, nShaderState::Param param, float max) { if (this->refElement->HasParam(param)) { slider->SetMaxIntensity(max); slider->SetColor(this->refElement->GetVector(param)); } else { slider->SetMaxIntensity(max); slider->SetColor(vector4(1.0f, 1.0f, 1.0f, 0.0f)); } } //------------------------------------------------------------------------------ /** */ void nGuiSkyEditor::FindSkyNode(nRoot* node) { if (node->IsInstanceOf("nskynode")) { this->skyPath = node->GetFullName(); this->refSky.set(this->skyPath.Get()); } else { nRoot* child = node->GetHead(); while (child) { this->FindSkyNode(child); child = child->GetSucc(); } } }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 2023 ] ] ]
3d0501f418cb1f5e192bb2896d33a830413b96f6
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/back_reference_fwd.hpp
e3c840d67e84d145fa95f1a3d60bcc5c6f9ecfec
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,500
hpp
// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_BACK_REFERENCE_FWD_040510_HPP #define LUABIND_BACK_REFERENCE_FWD_040510_HPP namespace luabind { template<class T> bool get_back_reference( lua_State* L, T const& x ); template<class T> bool move_back_reference( lua_State* L, T const& x ); } // namespace luabind #endif // LUABIND_BACK_REFERENCE_FWD_040510_HPP
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 38 ] ] ]
0d18904c151ad0011a5ca0b180b87bff8ccd4a17
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/06112002/src/VirtualFS/VFSPlugin_Q3BSP.cpp
973e5a244b86d774cd3b886aa7d7deb49cc31c4a
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,088
cpp
#include <VirtualFS/VFSPlugin_Q3BSP.h> #include <Fusion.h> #include <fstream> using namespace std; ofstream logfile("bsp.log"); VFSPlugin_Q3BSP::VFSPlugin_Q3BSP() { m_type = "bsp;"; m_offset = 0; m_fileinfo = NULL; } VFSPlugin_Q3BSP::~VFSPlugin_Q3BSP() { } FileInfo * VFSPlugin_Q3BSP::Read(unsigned char *buffer, unsigned int length) { m_offset = 0; m_buffer = buffer; m_fileinfo = new MeshFileInfo(); m_fileinfo->filelength = length; m_fileinfo->mesh = fusion->Mesh->CreateMesh(); Read_Header(); Read_Entities(); Read_Shaders(); Read_Planes(); Read_Nodes(); Read_Leaves(); Read_Leaf_Face(); Read_Leaf_Brushes(); Read_Models(); Read_Brushes(); Read_Brush_Sides(); Read_Vertex(); Read_MeshVerts(); Read_Effects(); Read_Faces(); Read_Lightmaps(); Read_LightVols(); Read_Visibility(); ProcessMesh(); return m_fileinfo; } char * VFSPlugin_Q3BSP::Write(FileInfo *data, unsigned int &length) { // Not Implemented return NULL; } char * VFSPlugin_Q3BSP::Type(void) { return m_type; } char * VFSPlugin_Q3BSP::ReadData(int length) { char *data = new char[length]; memcpy(data,&m_buffer[m_offset],length); m_offset+=length; return data; } void VFSPlugin_Q3BSP::Read_Header(void) { m_header = reinterpret_cast<BSPHeader *>(ReadData(sizeof(BSPHeader))); } void VFSPlugin_Q3BSP::Read_Entities(void) { BSPLump *lump = &m_header->lump[BSP_ENTITIES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Shaders(void) { BSPLump *lump = &m_header->lump[BSP_SHADERS]; m_offset = lump->offset; m_shader = reinterpret_cast<BSPShader *>(ReadData(lump->length)); m_numshaders = lump->length/sizeof(BSPShader); for(int a=0;a<m_numshaders;a++){ logfile << "Shader["<<a<<"] = {" << std::endl; logfile << "\t name = " << m_shader[a].name << std::endl; logfile << "};" << std::endl << std::endl; } } void VFSPlugin_Q3BSP::Read_Planes(void) { BSPLump *lump = &m_header->lump[BSP_PLANES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Nodes(void) { BSPLump *lump = &m_header->lump[BSP_NODES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Leaves(void) { BSPLump *lump = &m_header->lump[BSP_LEAVES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Leaf_Face(void) { BSPLump *lump = &m_header->lump[BSP_LEAF_FACES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Leaf_Brushes(void) { BSPLump *lump = &m_header->lump[BSP_LEAF_BRUSHES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Models(void) { BSPLump *lump = &m_header->lump[7]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Brushes(void) { BSPLump *lump = &m_header->lump[BSP_BRUSH]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Brush_Sides(void) { BSPLump *lump = &m_header->lump[BSP_BRUSHSIDES]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Vertex(void) { BSPLump *lump = &m_header->lump[BSP_VERTEX]; m_offset = lump->offset; m_numvertex = lump->length/sizeof(BSPVertex); BSPVertex *v = reinterpret_cast<BSPVertex *>(ReadData(lump->length)); Vertex3f *p = new Vertex3f[m_numvertex]; Vertex3f *n = new Vertex3f[m_numvertex]; Vertex2f *t = new Vertex2f[m_numvertex]; logfile << "Position Data: " << std::endl; for(int a=0;a<m_numvertex;a++){ std::swap(v[a].point.y,v[a].point.z); memcpy(&p[a],&v[a].point, sizeof(Vertex3f)); memcpy(&n[a],&v[a].normal, sizeof(Vertex3f)); memcpy(&t[a],&v[a].texture, sizeof(Vertex2f)); //logfile << "Position["<<a<<"] = {" << p[a].x << ", " << p[a].y << ", " << p[a].z << "};"<< std::endl; } delete[] v; m_fileinfo->mesh->Initialise(m_numvertex); m_fileinfo->mesh->SetPosition(p); m_fileinfo->mesh->SetNormal(n); m_fileinfo->mesh->SetTexcoord(t); } void VFSPlugin_Q3BSP::Read_MeshVerts(void) { BSPLump *lump = &m_header->lump[BSP_MESHVERTS]; m_offset = lump->offset; m_nummeshverts = lump->length/sizeof(int); m_meshverts = reinterpret_cast<int *>(ReadData(lump->length)); } void VFSPlugin_Q3BSP::Read_Effects(void) { BSPLump *lump = &m_header->lump[BSP_EFFECTS]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Faces(void) { BSPLump *lump = &m_header->lump[BSP_FACES]; m_offset = lump->offset; m_numfaces = lump->length/sizeof(BSPFace); m_face = reinterpret_cast<BSPFace *>(ReadData(lump->length)); } void VFSPlugin_Q3BSP::Read_Lightmaps(void) { BSPLump *lump = &m_header->lump[BSP_LIGHTMAPS]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_LightVols(void) { BSPLump *lump = &m_header->lump[BSP_LIGHTVOLS]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::Read_Visibility(void) { BSPLump *lump = &m_header->lump[BSP_VIS]; m_offset = lump->offset; } void VFSPlugin_Q3BSP::ProcessMesh(void) { Mesh *m = m_fileinfo->mesh; CentreMesh(); for(int a=0;a<m_numshaders;a++){ CreateVertexBuffer(a); BuildVertexBuffer(a); } } void VFSPlugin_Q3BSP::CentreMesh(void) { int a; Maths::Vector centre,min,max; Mesh *m = m_fileinfo->mesh; Vertex3f *vertex = m->GetPosition(); // Sets up the bounding box with extreme values min.Set(16000,16000,16000); max.Set(-16000,-16000,-16000); // Calculate the bounding box of the Surface for(a=0;a<m_numvertex;a++){ if(vertex[a].x < min.x) min.x = vertex[a].x; if(vertex[a].y < min.y) min.y = vertex[a].y; if(vertex[a].z < min.z) min.z = vertex[a].z; if(vertex[a].x > max.x) max.x = vertex[a].x; if(vertex[a].y > max.y) max.y = vertex[a].y; if(vertex[a].z > max.z) max.z = vertex[a].z; } // Calculate the centre of the box centre = (max - min)/2; for(a=0;a<m_numvertex;a++){ // Move the Surface to centre around (0,0,0) vertex[a].x -= centre.x; vertex[a].y -= centre.y; vertex[a].z -= centre.z; // Invert the x axis, so the Surface displays the correct way vertex[a].x = -vertex[a].x; } } void VFSPlugin_Q3BSP::CreateVertexBuffer(int shader) { IVertexBuffer *vb = m_fileinfo->mesh->AddVertexBuffer(); Material *m = vb->GetMaterial(); m->colour.r = 1; m->colour.g = 1; m->colour.b = 1; m->colour.a = 1; // Load texture vb->SetTextureLayer(0,vb->GetTexcoord(),FindTexture(m_shader[shader].name)); } ITexture * VFSPlugin_Q3BSP::FindTexture(char *name) { VFSHandle *h = NULL; char *filename = new char[256]; ITexture *t = NULL; // look for tga if(t == NULL){ memset(filename,0,256); sprintf(filename,"file://%s.tga",name); t = fusion->Graphics->CreateTexture(filename); } // look for jpg if(t == NULL){ memset(filename,0,256); sprintf(filename,"file://%s.jpg",name); t = fusion->Graphics->CreateTexture(filename); } // look for jpeg if(t == NULL){ memset(filename,0,256); sprintf(filename,"file://%s.jpeg",name); t = fusion->Graphics->CreateTexture(filename); } // look for shader (return null) if(t == NULL){ memset(filename,0,256); sprintf(filename,"file://%s.shader",name); t = NULL; } if(t == NULL){ logfile << "FindTexture: Couldnt find texture \"" << name << "\"" << std::endl; } return t; } void VFSPlugin_Q3BSP::BuildVertexBuffer(int shader) { CountPolygons(shader); Mesh *m = m_fileinfo->mesh; IVertexBuffer *vb = m->GetVertexBuffer(shader); int ctr = 0; int *i = vb->GetIndex(); for(int a=0;a<m_numfaces;a++){ if(m_face[a].shader == shader){ if(m_face[a].type == 1){ TempPolygon *p = new TempPolygon; p->numvertex = m_face[a].vert_count; p->index = new int[p->numvertex]; for(int b=0;b<p->numvertex;b++) p->index[b] = m_face[a].vert_start+b; // Process the list of vertices into triangles for(int c=1;c<p->numvertex-1;c++){ i[ctr++] = p->index[0]; i[ctr++] = p->index[c+0]; i[ctr++] = p->index[c+1]; } } if(m_face[a].type == 3){ TempPolygon *p = new TempPolygon; p->numvertex = m_face[a].vert_count; p->index = new int[p->numvertex]; for(int b=0;b<p->numvertex;b++) p->index[b] = m_face[a].vert_start+b; // Process the list of vertices into triangles for(int c=1;c<p->numvertex-1;c++){ i[ctr++] = p->index[0]; i[ctr++] = p->index[c+0]; i[ctr++] = p->index[c+1]; } } } } vb->SetPosition ((float *)m->GetPosition()); vb->SetNormal ((float *)m->GetNormal()); vb->SetTextureLayer(0,(float *)m->GetTexcoord(),vb->GetTexture()); } void VFSPlugin_Q3BSP::CountPolygons(int shader) { int a,ctr = 0; for(a=0;a<m_numfaces;a++){ if(m_face[a].shader == shader){ if(m_face[a].type == 1){ ctr += (m_face[a].vert_count-2); } if(m_face[a].type == 3){ ctr += (m_face[a].vert_count-2); } } } IVertexBuffer *vb = m_fileinfo->mesh->GetVertexBuffer(shader); vb->Initialise(m_fileinfo->mesh->GetNumVertex(),ctr*3,3,2); }
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 393 ] ] ]
9152c889780834d9cf1481ddfcd9c61da22e6e23
1eb441701fc977785b13ea70bc590234f4a45705
/nukak3d/include/nkNukak3D.h
4873fe3c56de50820d4e868d773f5f6572b02e05
[]
no_license
svn2github/Nukak3D
942947dc37c56fc54245bbc489e61923c7623933
ec461c40431c6f2a04d112b265e184d260f929b8
refs/heads/master
2021-01-10T03:13:54.715360
2011-01-18T22:16:52
2011-01-18T22:16:52
47,416,318
1
2
null
null
null
null
ISO-8859-2
C++
false
false
14,042
h
/** * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group. * Bogota - Colombia * All rights reserved. * * Author(s): Alexander Pinzón Fernández. * * ***** END GPL LICENSE BLOCK ***** */ /** * @file nkNukak3D.h * @brief Main window. * @details Gui implementation * @author Alexander Pinzón Fernandez, Byron Pérez * @version 0.2 * @date 27/12/2007 03:37 p.m. */ #ifndef _NKNUKAK3D_H_ #define _NKNUKAK3D_H_ #include "vtkINRIA3DConfigure.h" #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif /** wx */ #include <wx/aui/aui.h> #include <wx/aui/auibook.h> #include <wx/config.h> #include <wx/imaglist.h> #include <wx/intl.h> #include <wx/joystick.h> #include <wx/treectrl.h> #ifndef __WXMSW__ #include "mondrian.xpm" #endif #include "main.xpm" /** vtk*/ #include <vtkBMPWriter.h> #include <vtkJPEGWriter.h> #include "vtkLookupTableManager.h" #include <vtkOutputWindow.h> #include <vtkTIFFWriter.h> #include <vtkWindowToImageFilter.h> /** nk*/ #include "nkObj3DViewer.h" #include "nkVolViewer.h" #include "nkIODialog.h" #include "nkAcercaDe.h" #include "nkKernel.h" #include "nkAdminPluginGui.h" //#ifdef __WXMAC__ #ifdef __WIN32__ #include "nkToolBar.h" #else // mac or unix #include "nkToolBarMac.h" #endif //__WIN32__ #define mensajes 1 /** * @brief Main window. * @details Gui implementation */ class nkNukak3D: public wxFrame{ public: /** * Event identifier. */ enum{ ID_OPEN_FILE = wxID_HIGHEST + 1500, /**< Open file. */ ID_OPEN_FILE_DICOM, /**< Open stack of image Dicom. */ ID_OPEN_FILE_MESH3D, /**< Open object 3D. */ ID_OPEN_FILE_VOL, /**< Open file vol. */ ID_ABOUT, /**< Show Dialog About Nukak3d. */ ID_ABOUT_MAC, /**< Show Dialog About Nukak3d (Only for Mac ) . */ ID_ADMIN_PLUGIN_PATH, /**< Admin plugin's paths. */ ID_TREE, /**< Event launch by nkToolBarMac. */ ID_AREA, /**< Calc area . */ ID_prBoundingBox, /**< Show/hide bounding box. */ ID_BOXWIDGET, /**< Show/hide box widget. */ ID_CAMERAPOS, /**< Show position of camera. */ ID_CAMPLANES, /**< Update planes with position of camera. */ ID_CLOSE, /**< Close application. */ ID_CLOSE_ALL, /**< Close application. */ ID_COLDET, /**< Collision detection. */ ID_DICOMFIND, /**< Dicom C-FIND. */ ID_DICOMSERVER, /**< Dicom listener SCP. */ ID_ENDOCAMOBB, /**< Enable virtual endoscopy. */ ID_ENDOCAM, /**< Enable Virtual endoscopy. */ ID_FILPOLYDECIMATE, /**< To reduce numbers of polygon. */ ID_FILPOLYDEFORM, /**< Deform Mesh. */ ID_FILPOLYNORMALS, /**< Recalc normals of faces. */ ID_FILPOLYSMOOTH, /**< Smooth mesh. */ ID_FILPOLYTRIANGLE, /**< Triangle mesh. */ ID_FILVOLGAUSSIAN, /**< Gaussian filter. */ ID_FILVOLGRADIENT, /**< Gradient filter. */ ID_FILVOLMEDIAN, /**< Median filter. */ ID_FILVOLTHRESHOLD, /**< Threshold filter. */ ID_SAVE_MESH3D, /**< Save object 3D. */ ID_SAVE_VOL, /**< Save vol. */ ID_JOYSTICK, /**< Input device to Joystick. */ ID_LSLEVELSETSCOMPLETO, /**< Level sets. */ ID_MARCHING_CUBES, /**< Surface reconstruction with Marching Cubes. */ ID_NAVENDOSCOPE, /**< Mode of navigation camera endoscopy. */ ID_NAVFLIGHT, /**< Flight Camera. */ ID_NAVJOYSTICK, /**< Joystick Camera. */ ID_NAVRESET, /**< Reset camera position and orientation. */ ID_NAVTRACKBALL, /**< Trackball Camera. */ ID_NAVUNICAM, /**< Unicam Camera. */ ID_LOOKUP_TABLE, /**< lookup table. */ ID_INFORMATION_IMAGE, /**< Image information. */ ID_INFORMATION_POLYGON, /**< Object 3D information. */ ID_INFORMATION_VIDEO_CARD, /**< VideoCard information. */ ID_RESET_LOOKUP_TABLE, /**< Reset window and level. */ ID_EXIT, /**< Close application. */ ID_SETLANGUAGE, /**< Change user language. */ ID_SNAPSHOT3D, /**< Snapshot canvas 3D. */ ID_SNAPSHOTAXIAL, /**< Snapshot axial view. */ ID_SNAPSHOTCORONAL, /**< Snapshot coronal view. */ ID_SNAPSHOTSAGITAL, /**< Snapshot sagital view. */ ID_STEREO_ACTIVE, /**< Enable stereoscopic vision. */ ID_STEREO_MORE_SEPARATION, /**< Stereoscopic vision more separation. */ ID_STEREO_LESS_SEPARATION, /**< Stereoscopic vision less separation. */ ID_STEREO_PASSIVE, /**< Active stereoscopy vision. */ ID_VOLVIEWER_RENDERING_ESCALAR, /**< Ortogonal planes view. */ ID_VOLVIEWER_RENDERING_MRC_MIP, /**< Ray Tracing MIP. */ ID_VOLVIEWER_RENDERING_MRC_COMP,/**< Ray Tracing COMPOSITE. */ ID_VOLVIEWER_RENDERING_MRC_ISO, /**< Ray Tracing ISOSURFACE. */ ID_VOLVIEWER_RENDERING_TEXTURE, /**< Texture mpping rendering. */ ID_FPS, /**< Frames per second. */ ID_LAST_LOOKUP_TABLE = wxID_HIGHEST+3000, /**< Event's for lookup table. */ ID_NK_ITK_PLUGIN_FILTER = wxID_HIGHEST+3200 }; /** * @brief Class constructor. * @details Main window. */ nkNukak3D(wxWindow* parent, int id=-1, const wxString& title="Nukak3D", const wxPoint& pos=wxDefaultPosition, const wxSize& size=wxDefaultSize, long style=wxDEFAULT_FRAME_STYLE ); /** * @brief Class destructor. */ virtual ~nkNukak3D(); /** * @brief Insert Toolbar Botton. * @param window nkToolbar to insert. * @param a_name nkToolbar title. * @param a_label Label for this control. */ void prInsertToolBar(wxWindow* window, wxString a_name, wxString a_label); /** * @brief Open volume of images store in unique file. */ void prEventOpenVolumen(wxCommandEvent& WXUNUSED(event)); /** * @brief Open Dicom directories. */ void prEventOpenVolumenDicom(wxCommandEvent& WXUNUSED(event)); /** * @brief Open Dicom directories. */ void prOpenVolumenDicom(wxString pathDicom); /** * @brief Open object 3D (vtk structured grid). */ void prEventOpenMesh3D(wxCommandEvent& WXUNUSED(event)); /** * @brief Open about nkNukak3D. */ void prEventAbout(wxCommandEvent& WXUNUSED(event)); /** * @brief Open about nkNukak3D for Mac. */ void prEventAboutMAC(wxCommandEvent& WXUNUSED(event)); /** * @brief .nkToolbar event's for Mac and unix systems. */ void prEventTree(wxTreeEvent& event); /** * @brief Save volume. */ void prEventSaveVol(wxCommandEvent& WXUNUSED(event)); /** * @brief Save object 3D in vtk structured grid file. */ void prEventSaveMesh3D(wxCommandEvent& WXUNUSED(event)); /** * @brief Show/hide bounding box */ void prEventprBoundingBox(wxCommandEvent& WXUNUSED(event)); /** * @brief Show/hide box widget */ void prEventBoxWidget(wxCommandEvent& WXUNUSED(event)); /** * @brief Change lookup table for rendering volume. */ void prEventLookupTable(wxCommandEvent& event); /** * @brief Reset window and level. */ void prEventResetLookupTable(wxCommandEvent& WXUNUSED(event)); /** * @brief Close application mene. */ void prEventExit(wxCommandEvent& WXUNUSED(event)); /** * @brief Close application. */ void prOnClose(wxCloseEvent & event); /** * @brief View ortogonal planes rendering. */ void prEventVolViewerRenderingEscalar(wxCommandEvent& WXUNUSED(event)); /** * @brief Texture maping rendering. */ void prEventVolViewerRenderingTextura(wxCommandEvent& WXUNUSED(event)); /** * @brief Visualiza el volumen 3D usando el algoritmo ray casting * MIP - Maximum Intensity Projection. * La opacidad se cambia variando la ventana (width and level) de la imagen */ void prEventVolViewerRenderingMRCmip(wxCommandEvent& WXUNUSED(event)); /** * @brief Visualiza el volumen 3D usando el algoritmo ray casting. * COMPOSITE * La opacidad se cambia variando la ventana (width and level) de la imagen */ void prEventVolViewerRenderingMRCcomp(wxCommandEvent& WXUNUSED(event)); /** * @brief Visualiza el volumen 3D usando el algoritmo ray casting. * ISOSURFACE * La opacidad se cambia variando la ventana (width and level) de la imagen */ void prEventVolViewerRenderingMRCiso(wxCommandEvent& WXUNUSED(event)); /** * @brief Marching cubes event. */ void prEventMarchingCubes(wxCommandEvent& WXUNUSED(event)); /** * @brief Segmentation with levelsets */ void prEventLevelSets(wxCommandEvent& WXUNUSED(event)); /** * @brief Event for calc area. */ void prEventCalcArea(wxCommandEvent& WXUNUSED(event)); /** * @brief Reset position and orientatio camera. */ void prEventprNavResetCamara(wxCommandEvent& WXUNUSED(event)); /** * @brief Trackball camera. * @details Navigation by default. */ void prEventprNavTrackball(wxCommandEvent& WXUNUSED(event)); /** * @brief Joystick camera. */ void prEventprNavJoystick(wxCommandEvent& WXUNUSED(event)); /** * @brief Flight camera. */ void prEventprNavFlight(wxCommandEvent& WXUNUSED(event)); /** * @brief Unicam camera. */ void prEventprNavUnicam(wxCommandEvent& WXUNUSED(event)); /** * @brief Enable/Disable stereoscopic vision. */ void prEventprActiveStereo(wxCommandEvent& WXUNUSED(event)); /** * @brief Enable/Disable passive stereo. */ void prEventprStereoPassive(wxCommandEvent& WXUNUSED(event)); /** * @brief More separation for images in stereoscopic vision. */ void prEventStMoreSeparation(wxCommandEvent& WXUNUSED(event)); /** * @brief Less separation for images in stereoscopic vision. */ void prEventStLessSeparation(wxCommandEvent& WXUNUSED(event)); /** * @brief Gaussian filter. */ void prEventFilVolGaussian(wxCommandEvent& WXUNUSED(event)); /** * @brief Median filter. */ void prEventFilVolMedian(wxCommandEvent& WXUNUSED(event)); /** * @brief Gradient filter. */ void prEventFilVolGradient(wxCommandEvent& WXUNUSED(event)); /** * @brief Threshold filter. */ void prEventFilVolThreshold(wxCommandEvent& WXUNUSED(event)); /** * @brief Triangle mesh. */ void prEventFilprPolyTriangle(wxCommandEvent& WXUNUSED(event)); /** * @brief Decimate mesh. */ void prEventFilprPolyDecimate(wxCommandEvent& WXUNUSED(event)); /** * @brief Smooth mesh. */ void prEventFilprPolySmooth(wxCommandEvent& WXUNUSED(event)); /** * @brief Recalc normals. */ void prEventFilprPolyNormals(wxCommandEvent& WXUNUSED(event)); /** * @brief Deform mesh. */ void prEventFilprPolyDeform(wxCommandEvent& WXUNUSED(event)); /** * @brief Snapshot 3d view. */ void prEventSnapshot3D(wxCommandEvent& WXUNUSED(event)); /** * @brief Snapshot axial view. */ void prEventSnapshotAxial(wxCommandEvent& WXUNUSED(event)); /** * @brief Snapshot axial sagital. */ void prEventSnapshotSagital(wxCommandEvent& WXUNUSED(event)); /** * @brief Snapshot axial coronal. */ void prEventSnapshotCoronal(wxCommandEvent& WXUNUSED(event)); /** * @brief Show information of volume. */ void prEventInformationImage(wxCommandEvent& WXUNUSED(event)); /** * @brief Show information of mesh. */ void prEventInformationPolygon(wxCommandEvent& WXUNUSED(event)); /** * @brief Show information of video card. */ void prEventInformationVideoCard(wxCommandEvent& WXUNUSED(event)); /** * @brief Change the user preferences, language. */ void prEventChangeLanguage(wxCommandEvent& WXUNUSED(event)); /** * @brief Get notebok to make other pages. * @return wxAuiNotebook * */ wxAuiNotebook * getWxAuiNotebook(void); /** * @brief Active a joystick/gamepad for navigation */ void prEventActiveJoystick(wxCommandEvent& WXUNUSED(event)); /** * @brief Show/save camera's position */ void prEventPositionCamera(wxCommandEvent& WXUNUSED(event)); /** * @brief Navigation type endoscopy * @details Mode of navigation type endoscopy */ void prEventNavEndoscope(wxCommandEvent& WXUNUSED(event)); /** * @brief Frames per second * @details Show frames per second of this render */ void prEventFPS(wxCommandEvent& WXUNUSED(event)); /** * @brief Dicom SCP Listener * @details Dicom SCP Listener, bassed on OFFIS DICOM storescp server. */ void prEventDicomListener(wxCommandEvent& WXUNUSED(event)); /** * @brief Dicom C-FIND * @details Dialog for search in Dicom server with C-Find option. */ void prEventDicomFind(wxCommandEvent& WXUNUSED(event)); /** * @brief Admin Plugin's paths * @details Dialog for admin plugin's paths. */ void prEventAdminPluginsPaths(wxCommandEvent& WXUNUSED(event)); nukak3d::nkKernel & getNukakKernel(void); private: wxAuiNotebook * prv_wxAuiNotebook; //! notebook for manage pages. wxAuiManager prv_auiManager; //! Administrator for Aui. nkToolBar * prv_nkToolBarTools; //! nkToolBar for tools. nkToolBar * prv_nkToolBarImageViewer; //! nkToolBar for image tools. nukak3d::nkKernel prv_nkKernel; DECLARE_EVENT_TABLE() //! Call macro for declaration of events. }; #endif //_NKNUKAK3D_H_
[ "apinzonf@4b68e429-1748-0410-913f-c2fc311d3372" ]
[ [ [ 1, 498 ] ] ]
14722598f454f6832e3c4ce815152374196ef5a7
3a79a741fe799d531f363834255d1ce15a520258
/artigos/arquiteturaDeJogos/programacao/animacao/math/Box.cpp
b1fe4aa2e4b5c76a52dc39eda5dbea265066c9d7
[]
no_license
ViniGodoy/pontov
a8bd3485c53d5fc79312f175610a2962c420c40d
01f8f82209ba10a57d9d220d838cbf00aede4cee
refs/heads/master
2020-04-24T19:33:24.288796
2011-06-20T21:44:03
2011-06-20T21:44:03
32,488,089
0
0
null
null
null
null
UTF-8
C++
false
false
2,294
cpp
#include "Box.h" #include <stdexcept> using math::Box; using math::Vector3D; Box::Box() : min(0,0,0), max(1,1,1) { } Box::Box(const Vector3D& _min, const Vector3D& _max) { set(_min, _max); } Box::Box(float x1, float y1, float z1, float x2, float y2, float z2) { set(x1, y1, z1, x2, y2, z2); } const Vector3D& Box::getMin() const { return min; } const Vector3D& Box::getMax() const { return max; } Vector3D Box::getCenter() const { return (min + max) * 0.5f; } bool Box::intersects(const Box& other, Box* boxIntersect) const { // Check for no overlap if (min.getZ() > other.getMax().getZ()) return false; if (max.getZ() < other.getMin().getZ()) return false; if (min.getX() > other.getMax().getX()) return false; if (max.getX() < other.getMin().getX()) return false; if (min.getY() > other.getMax().getY()) return false; if (max.getY() < other.getMin().getY()) return false; if (boxIntersect == NULL) return true; boxIntersect->set( std::max(getMin().getX(), other.getMin().getX()), std::max(getMin().getY(), other.getMin().getY()), std::max(getMin().getZ(), other.getMin().getZ()), std::min(getMax().getX(), other.getMax().getX()), std::min(getMax().getY(), other.getMax().getY()), std::min(getMax().getZ(), other.getMax().getZ())); return true; } bool Box::contains(const Vector3D point) const { return (point.getX() >= min.getX()) && (point.getX() <= max.getX()) && (point.getY() >= min.getY()) && (point.getY() <= max.getY()) && (point.getZ() >= min.getZ()) && (point.getZ() <= max.getZ()); } void Box::set(float x1, float y1, float z1, float x2, float y2, float z2) { if (x1 > x2 || y1 > y2 || z1 > z2) throw std::invalid_argument("Invalid box points!"); min.set(x1, y1, z1); max.set(x2, y2, z2); } void Box::set(const Vector3D& _min, const Vector3D& _max) { set(_min.getX(), _min.getY(), _min.getZ(), _max.getX(), _max.getY(), _max.getZ()); } void Box::move(const Vector3D& position) { min += position; max += position; } Box Box::moved(const Vector3D& position) const { return Box(min + position, max + position); }
[ "bcsanches@7ec48984-19c3-11df-a513-1fc609e2573f" ]
[ [ [ 1, 97 ] ] ]
296db10ba32eb2f56f31b78f86a1d2321c76395e
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/python/src/converter/from_python.cpp
fef9281f82a8dd407a1e5230460b4a45fb0f9ea1
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
8,837
cpp
// Copyright David Abrahams 2002. // 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) #include <boost/python/converter/from_python.hpp> #include <boost/python/converter/registrations.hpp> #include <boost/python/converter/rvalue_from_python_data.hpp> #include <boost/python/object/find_instance.hpp> #include <boost/python/handle.hpp> #include <boost/python/detail/raw_pyobject.hpp> #include <boost/python/cast.hpp> #include <vector> #include <algorithm> namespace boost { namespace python { namespace converter { // rvalue_from_python_stage1 -- do the first stage of a conversion // from a Python object to a C++ rvalue. // // source - the Python object to be converted // converters - the registry entry for the target type T // // Postcondition: where x is the result, one of: // // 1. x.convertible == 0, indicating failure // // 2. x.construct == 0, x.convertible is the address of an object of // type T. Indicates a successful lvalue conversion // // 3. where y is of type rvalue_from_python_data<T>, // x.construct(source, y) constructs an object of type T // in y.storage.bytes and then sets y.convertible == y.storage.bytes, // or else throws an exception and has no effect. BOOST_PYTHON_DECL rvalue_from_python_stage1_data rvalue_from_python_stage1( PyObject* source , registration const& converters) { rvalue_from_python_stage1_data data; // First check to see if it's embedded in an extension class // instance, as a special case. data.convertible = objects::find_instance_impl(source, converters.target_type); if (data.convertible) { data.construct = 0; } else { for (rvalue_from_python_chain const* chain = converters.rvalue_chain; chain != 0; chain = chain->next) { void* r = chain->convertible(source); if (r != 0) { data.convertible = r; data.construct = chain->construct; break; } } } return data; } // rvalue_result_from_python -- return the address of a C++ object which // can be used as the result of calling a Python function. // // src - the Python object to be converted // // data - a reference to the base part of a // rvalue_from_python_data<T> object, where T is the // target type of the conversion. // // Requires: data.convertible == &registered<T>::converters // BOOST_PYTHON_DECL void* rvalue_result_from_python( PyObject* src, rvalue_from_python_stage1_data& data) { // Retrieve the registration // Cast in two steps for less-capable compilers void const* converters_ = data.convertible; registration const& converters = *static_cast<registration const*>(converters_); // Look for an eligible converter data = rvalue_from_python_stage1(src, converters); return rvalue_from_python_stage2(src, data, converters); } BOOST_PYTHON_DECL void* rvalue_from_python_stage2( PyObject* source, rvalue_from_python_stage1_data& data, registration const& converters) { if (!data.convertible) { handle<> msg( ::PyString_FromFormat( "No registered converter was able to produce a C++ rvalue of type %s from this Python object of type %s" , converters.target_type.name() , source->ob_type->tp_name )); PyErr_SetObject(PyExc_TypeError, msg.get()); throw_error_already_set(); } // If a construct function was registered (i.e. we found an // rvalue conversion), call it now. if (data.construct != 0) data.construct(source, &data); // Return the address of the resulting C++ object return data.convertible; } BOOST_PYTHON_DECL void* get_lvalue_from_python( PyObject* source , registration const& converters) { // Check to see if it's embedded in a class instance void* x = objects::find_instance_impl(source, converters.target_type); if (x) return x; lvalue_from_python_chain const* chain = converters.lvalue_chain; for (;chain != 0; chain = chain->next) { void* r = chain->convert(source); if (r != 0) return r; } return 0; } namespace { // Prevent looping in implicit conversions. This could/should be // much more efficient, but will work for now. typedef std::vector<rvalue_from_python_chain const*> visited_t; static visited_t visited; inline bool visit(rvalue_from_python_chain const* chain) { visited_t::iterator const p = std::lower_bound(visited.begin(), visited.end(), chain); if (p != visited.end() && *p == chain) return false; visited.insert(p, chain); return true; } // RAII class for managing global visited marks. struct unvisit { unvisit(rvalue_from_python_chain const* chain) : chain(chain) {} ~unvisit() { visited_t::iterator const p = std::lower_bound(visited.begin(), visited.end(), chain); assert(p != visited.end()); visited.erase(p); } private: rvalue_from_python_chain const* chain; }; } BOOST_PYTHON_DECL bool implicit_rvalue_convertible_from_python( PyObject* source , registration const& converters) { if (objects::find_instance_impl(source, converters.target_type)) return true; rvalue_from_python_chain const* chain = converters.rvalue_chain; if (!visit(chain)) return false; unvisit protect(chain); for (;chain != 0; chain = chain->next) { if (chain->convertible(source)) return true; } return false; } namespace { void throw_no_lvalue_from_python(PyObject* source, registration const& converters, char const* ref_type) { handle<> msg( ::PyString_FromFormat( "No registered converter was able to extract a C++ %s to type %s" " from this Python object of type %s" , ref_type , converters.target_type.name() , source->ob_type->tp_name )); PyErr_SetObject(PyExc_TypeError, msg.get()); throw_error_already_set(); } void* lvalue_result_from_python( PyObject* source , registration const& converters , char const* ref_type) { handle<> holder(source); if (source->ob_refcnt <= 1) { handle<> msg( ::PyString_FromFormat( "Attempt to return dangling %s to object of type: %s" , ref_type , converters.target_type.name())); PyErr_SetObject(PyExc_ReferenceError, msg.get()); throw_error_already_set(); } void* result = get_lvalue_from_python(source, converters); if (!result) (throw_no_lvalue_from_python)(source, converters, ref_type); return result; } } BOOST_PYTHON_DECL void throw_no_pointer_from_python(PyObject* source, registration const& converters) { (throw_no_lvalue_from_python)(source, converters, "pointer"); } BOOST_PYTHON_DECL void throw_no_reference_from_python(PyObject* source, registration const& converters) { (throw_no_lvalue_from_python)(source, converters, "reference"); } BOOST_PYTHON_DECL void* reference_result_from_python( PyObject* source , registration const& converters) { return (lvalue_result_from_python)(source, converters, "reference"); } BOOST_PYTHON_DECL void* pointer_result_from_python( PyObject* source , registration const& converters) { if (source == Py_None) { Py_DECREF(source); return 0; } return (lvalue_result_from_python)(source, converters, "pointer"); } BOOST_PYTHON_DECL void void_result_from_python(PyObject* o) { Py_DECREF(expect_non_null(o)); } } // namespace boost::python::converter BOOST_PYTHON_DECL PyObject* pytype_check(PyTypeObject* type_, PyObject* source) { if (!PyObject_IsInstance(source, python::upcast<PyObject>(type_))) { ::PyErr_Format( PyExc_TypeError , "Expecting an object of type %s; got an object of type %s instead" , type_->tp_name , source->ob_type->tp_name ); throw_error_already_set(); } return source; } }} // namespace boost::python
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 291 ] ] ]
08605086499d93400b94521baa7ef85a28a41656
c85f27488ce1a1d93a2a3eb0a1ca160100c6d3ad
/RayTracer.h
8e684b892577c8844a264ff01dee06f0c51ecf3b
[]
no_license
cheokwan/cs184-ds-dw-raytracer
ce57e682338afdd5ecdef9cbaba09f32bcf9e2be
f84d21eb9d39ee1316acea857dc36e1ef51070ac
refs/heads/master
2021-01-19T08:26:39.715985
2010-04-27T22:48:39
2010-04-27T22:48:39
32,121,050
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#include "algebra3.h" #include "Color.h" #include "Light.h" #include "Primitive.h" #include "Sphere.h" #include "Triangle.h" #include <math.h> #include <vector> using namespace std; #ifndef _Raytracer_h_ #define _Raytracer_h_ class Raytracer { public: vector<Primitive*> primitives; vector<Light*> lights; void trace(int reflects, vec4 p0, vec4 p1, double depth, Color *color); bool visible(vec4 p, Light *l); Raytracer(); ~Raytracer(); }; #endif
[ "samwong99@0be72354-b10b-e666-8ac9-db255acbfd61" ]
[ [ [ 1, 25 ] ] ]
d1a76782a407f08465f40cb6e206ae76699f9483
62bc2e657a042a7755595859ba9aa63283332a32
/cpp/RayTracer/fractals/Menger3D.cpp
9d34f03019d5dd54c7adac12eb182cab75eb536e
[]
no_license
nyanpasu64/makc
e1728cd903f2db596565b7c8a8c557f7a8ee12d9
b05773e2693f1aa9724ec247886f600a2dadd508
refs/heads/master
2021-05-31T23:26:22.384255
2011-11-03T00:30:07
2011-11-03T00:30:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,082
cpp
#include <math.h> #define MENGER3D_ORDER 5 bool hitTestMenger3D (double x, double y, double z) { // Menger sponge by Daniel White: // http://www.fractalforums.com/3d-fractal-generation/revenge-of-the-half-eaten-menger-sponge/ x += 0.5; y += 0.5; z += 0.5; if ((x<0)||(x>1)||(y<0)||(y>1)||(z<0)||(z>1)) return false; double p = 3; for (int m = 1; m < MENGER3D_ORDER; m++) { double xa = fmod (x*p, 3); double ya = fmod (y*p, 3); double za = fmod (z*p, 3); if (/* any two coordinates */ ((xa > 1.0) && (xa < 2.0) && (ya > 1.0) && (ya < 2.0)) || ((ya > 1.0) && (ya < 2.0) && (za > 1.0) && (za < 2.0)) || ((xa > 1.0) && (xa < 2.0) && (za > 1.0) && (za < 2.0)) ) return false; p *= 3; } return true; } double appDistMenger3D (double x, double y, double z) { x += 0.5; y += 0.5; z += 0.5; double d = -1; if (x < 0) if ((d < 0)||(-x < d)) d = -x; if (x > 1) if ((d < 0)||(x-1 < d)) d = x-1; if (y < 0) if ((d < 0)||(-y < d)) d = -y; if (y > 1) if ((d < 0)||(y-1 < d)) d = y-1; if (z < 0) if ((d < 0)||(-z < d)) d = -z; if (z > 1) if ((d < 0)||(z-1 < d)) d = z-1; if (d > 0) return d; double p = 3; for (int m = 1; m < MENGER3D_ORDER; m++) { double xa = fmod (x*p, 3); double ya = fmod (y*p, 3); double za = fmod (z*p, 3); d = -1; if ((xa > 1.0) && (xa < 2.0) && (ya > 1.0) && (ya < 2.0)) { if ((d < 0)||(xa-1 < d)) d = xa-1; if ((d < 0)||(2-xa < d)) d = 2-xa; if ((d < 0)||(ya-1 < d)) d = ya-1; if ((d < 0)||(2-ya < d)) d = 2-ya; } if ((za > 1.0) && (za < 2.0) && (ya > 1.0) && (ya < 2.0)) { if ((d < 0)||(za-1 < d)) d = za-1; if ((d < 0)||(2-za < d)) d = 2-za; if ((d < 0)||(ya-1 < d)) d = ya-1; if ((d < 0)||(2-ya < d)) d = 2-ya; } if ((xa > 1.0) && (xa < 2.0) && (za > 1.0) && (za < 2.0)) { if ((d < 0)||(xa-1 < d)) d = xa-1; if ((d < 0)||(2-xa < d)) d = 2-xa; if ((d < 0)||(za-1 < d)) d = za-1; if ((d < 0)||(2-za < d)) d = 2-za; } if (d > 0) return d / p; p *= 3; } return 0; }
[ "makc.the.great@1eff5426-bb48-0410-838f-eba945681aae" ]
[ [ [ 1, 70 ] ] ]
a53abd5a4fe70648b125f2437f427f0e49ff2fef
8eee4b8f879a829a01b7859538129828f6e1f9a4
/src/Application/Application.h
5914d82a10289960619428211e7a276f6fb8827f
[]
no_license
mperepelkin/GameTest
32d53220a1c66dafa5253036cc021c1f5dba0da9
9b91bb455f45d9ba5d69551436923d45712166f1
refs/heads/master
2016-09-05T10:52:31.770611
2011-05-01T18:50:58
2011-05-01T18:50:58
1,688,707
0
0
null
null
null
null
UTF-8
C++
false
false
617
h
/** * Application declaration. */ #ifndef __APPLICATION_H__ #define __APPLICATION_H__ #include "windows.h" namespace GameTest { // The main application ticking class. class Application { public: // Creates the new application instance, asserts if called more than once. static Application* createInstance(); // Initializes the application and all subsystems. void init(int argc, char *argv[]); // Updates the application and all subsystems. void update(); protected: // Ctor. Application(); // Dtor. ~Application(); }; } #endif
[ "mperepelkin@.(none)" ]
[ [ [ 1, 37 ] ] ]
18f566a47e3e243bceff8b4239fd12301b6b7a01
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/config/test/has_tr1_complex_over_pass.cpp
17c6f5a1d2a0ecd12bb3d9eb0ffb77d5e6bec0a7
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,091
cpp
// This file was automatically generated on Sat Apr 02 11:49:11 2005 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_HAS_TR1_COMPLEX_OVERLOADS // This file should compile, if it does not then // BOOST_HAS_TR1_COMPLEX_OVERLOADS should not be defined. // See file boost_has_tr1_complex_over.ipp for details // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifdef BOOST_HAS_TR1_COMPLEX_OVERLOADS #include "boost_has_tr1_complex_over.ipp" #else namespace boost_has_tr1_complex_overloads = empty_boost; #endif int main( int, char *[] ) { return boost_has_tr1_complex_overloads::test(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 34 ] ] ]
8dc73db6aa0095dc69b5d68490d0a4ae190376e4
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleUniverseTechnique.h
0f70411b517abf1db499d889dcc73983d167013a
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
ISO-8859-1
C++
false
false
36,723
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_TECHNIQUE_H__ #define __PU_TECHNIQUE_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseRenderer.h" #include "ParticleUniverseParticle.h" #include "ParticleUniverseEmitter.h" #include "ParticleUniverseAffector.h" #include "ParticleUniverseObserver.h" #include "ParticleUniverseEventHandler.h" #include "ParticleUniverseBehaviour.h" #include "ParticleUniverseIAlias.h" #include "ParticleUniverseParticlePool.h" #include "ParticleUniverseIElement.h" #include "ParticleUniverseHook.h" #include "ParticleUniverseSpatialHashTable.h" #include "ParticleUniverseCameraDependency.h" #include "ParticleUniverseCameraDependencyFactory.h" #include "ParticleUniverseTechniqueListener.h" namespace ParticleUniverse { static const Ogre::Vector3 HALFSCALE = Ogre::Vector3::UNIT_SCALE * 0.5; /** In analogy of Ogre´s material system, the ParticleTechnique is introduced. It forms an extra layer between particle emitters, affectors, etc. on one side, and the particle system and the other side. A ParticleTechnique has a few benefits. For example, with the use of a ParticleTechnique it is possible to implement Particle LOD (Level Of Detail). Also combining multiple renderers and material within one ParticleSystem is possible. */ class _ParticleUniverseExport ParticleTechnique : public Particle, public IAlias, public IElement { public: typedef std::vector<ParticleEmitter*>::iterator ParticleEmitterIterator; typedef std::vector<ParticleEmitter*> ParticleEmitterList; typedef std::vector<ParticleAffector*>::iterator ParticleAffectorIterator; typedef std::vector<ParticleAffector*> ParticleAffectorList; typedef std::vector<ParticleObserver*>::iterator ParticleObserverIterator; typedef std::vector<ParticleObserver*> ParticleObserverList; typedef std::vector<ParticleBehaviour*>::iterator ParticleBehaviourIterator; typedef std::vector<ParticleBehaviour*> ParticleBehaviourList; typedef std::vector<Extern*>::iterator ExternIterator; typedef std::vector<Extern*> ExternList; typedef std::vector<TechniqueListener*>::iterator TechniqueListenerIterator; typedef std::vector<TechniqueListener*> TechniqueListenerList; ParticleTechnique(void); virtual ~ParticleTechnique(void); /** */ ParticleSystem* getParentSystem(void) const {return mParentSystem;}; void setParentSystem(ParticleSystem* parentSystem) {mParentSystem = parentSystem;}; /** */ const Ogre::String& getName(void) const {return mName;}; void setName(const Ogre::String& name) {mName = name;}; /** */ size_t getVisualParticleQuota(void) const; void setVisualParticleQuota(size_t quota); /** */ size_t getEmittedEmitterQuota(void) const; void setEmittedEmitterQuota(size_t quota); /** */ size_t getEmittedTechniqueQuota(void) const; void setEmittedTechniqueQuota(size_t quota); /** */ size_t getEmittedAffectorQuota(void) const; void setEmittedAffectorQuota(size_t quota); /** */ size_t getEmittedSystemQuota(void) const; void setEmittedSystemQuota(size_t quota); /** */ const Ogre::Real getDefaultWidth(void) const; void setDefaultWidth(const Ogre::Real width); /** */ const Ogre::Real getDefaultHeight(void) const; void setDefaultHeight(const Ogre::Real height); /** */ const Ogre::Real getDefaultDepth(void) const; void setDefaultDepth(const Ogre::Real depth); /** Returns the derived position of the technique. @remarks Note, that in script, the position is set into localspace, while if the technique is emitted, its position is automatically transformed. This function always returns the derived position. */ const Ogre::Vector3& getDerivedPosition(void); /** Get/Set the squared distance between camera and ParticleTechnique. */ Ogre::Real getCameraSquareDistance(void) const {return mCameraSquareDistance;}; void setCameraSquareDistance(Ogre::Real cameraSquareDistance){mCameraSquareDistance = cameraSquareDistance;}; /** Function to suppress notification of an emission change. @see ParticleTechnique */ void suppressNotifyEmissionChange(bool suppress); /** Set the name of the material used by the renderer. */ const Ogre::String& getMaterialName(void) const; /** Set the name of the material used by the renderer. */ void setMaterialName(const Ogre::String& materialName); //-------------------------------------- Emitter -------------------------------------- /** Create a ParticleEmitter and add it to this ParticleTechnique. */ ParticleEmitter* createEmitter (const Ogre::String& emitterType); /** Add a ParticleEmitter to this ParticleTechnique. @remarks It must be possible to add a previously created emitter to the list. This is the case with emitters that were created outside the technique. An example is the creation of emitters by means of a script. The emitter will be placed under control of the technique. The Emitter Factory however, deletes the emitters (since they are also created by the factory). @param emitter Pointer to a previously created emitter. */ void addEmitter (ParticleEmitter* emitter); /** Get a ParticleEmitter. Search by index. */ ParticleEmitter* getEmitter (size_t index) const; /** Get a ParticleEmitter. Search by name. */ ParticleEmitter* getEmitter (const Ogre::String& emitterName) const; /** Get the number of ParticleEmitters added to this ParticleTechnique. */ size_t getNumEmitters (void) const; /** Delete a ParticleEmitter that is part of this ParticleTechnique. Search by index. */ void destroyEmitter (size_t index); /** Delete a ParticleEmitter that is part of this ParticleTechnique. */ void destroyEmitter (ParticleEmitter* emitter); /** Delete all ParticleEmitters of this ParticleTechnique. */ void destroyAllEmitters (void); /** Get the number of emitted ParticleEmitters. @remarks This doesn't return the real number of emitted emitters, but the number of emitters that are marked for emission. */ size_t getNumEmittedEmitters (void) const; //-------------------------------------- Affector -------------------------------------- /** Create a ParticleAffector and add it to this ParticleTechnique. */ ParticleAffector* createAffector (const Ogre::String& affectorType); /** Add a ParticleAffector to this ParticleTechnique. @param Pointer to a previously created affector. */ void addAffector (ParticleAffector* affector); /** Get a ParticleAffector. Search by index. */ ParticleAffector* getAffector (size_t index) const; /** Get a ParticleAffector. Search by name. */ ParticleAffector* getAffector (const Ogre::String& affectorName) const; /** Get the number of ParticleAffectors added to this ParticleTechnique. */ size_t getNumAffectors (void) const; /** Delete a ParticleAffector that is part of this ParticleTechnique. Search by index. */ void destroyAffector (size_t index); /** Delete a ParticleAffector that is part of this ParticleTechnique. */ void destroyAffector (ParticleAffector* affector); /** Delete all ParticleAffectors of this ParticleTechnique. */ void destroyAllAffectors (void); /** Get the number of emitted ParticleAffectors. @remarks This doesn't return the real number of emitted affectors, but the number of affectors that are marked for emission. */ size_t getNumEmittedAffectors (void) const; //-------------------------------------- Observer -------------------------------------- /** Create a ParticleObserver and add it to this ParticleTechnique. */ ParticleObserver* createObserver (const Ogre::String& observerType); /** Add a ParticleObserver to this ParticleTechnique. @param Pointer to a previously created observer. */ void addObserver (ParticleObserver* observer); /** Get a ParticleObserver. Search by index. */ ParticleObserver* getObserver (size_t index) const; /** Get a ParticleObserver. Search by name. */ ParticleObserver* getObserver (const Ogre::String& observerName) const; /** Get the number of ParticleObservers added to this ParticleTechnique. */ size_t getNumObservers (void) const; /** Delete a ParticleObserver that is part of this ParticleTechnique. Search by index. */ void destroyObserver (size_t index); /** Delete a ParticleObserver that is part of this ParticleTechnique. */ void destroyObserver (ParticleObserver* observer); /** Delete all ParticleObservers of this ParticleTechnique. */ void destroyAllObservers (void); //-------------------------------------- Renderer -------------------------------------- /** Returns the pointer to the renderer. */ ParticleRenderer* getRenderer(void) const; /** Set a renderer by means of the type of renderer. */ void setRenderer(const Ogre::String& rendererType); /** Set a renderer. */ void setRenderer(ParticleRenderer* renderer); /** Delete the renderer of this ParticleTechnique. */ void destroyRenderer(void); //-------------------------------------- Behaviour -------------------------------------- /** Add a ParticleBehaviour template to this ParticleTechnique. @remarks The ParticleBehaviour only serves as a blueprint for other ParticleBehaviour objects that are attached to a Particle, so the method should only be used internally. @param Pointer to a previously created Behaviour object. */ void _addBehaviourTemplate (ParticleBehaviour* behaviourTemplate); /** Get a ParticleBehaviour template. Search by index. */ ParticleBehaviour* _getBehaviourTemplate (size_t index) const; /** Get a ParticleBehaviour template. Search by type. */ ParticleBehaviour* _getBehaviourTemplate (const Ogre::String& behaviourType) const; /** Get the number of ParticleBehaviour templates added to this ParticleTechnique. */ size_t _getNumBehaviourTemplate (void) const; /** Delete a ParticleBehaviour template that is part of this ParticleTechnique. */ void _destroyBehaviourTemplate (ParticleBehaviour* behaviourTemplate); /** Delete all ParticleBehaviour templates of this ParticleTechnique. */ void _destroyAllBehaviourTemplates (void); //-------------------------------------- Extern -------------------------------------- /** Create an Extern and add it to this ParticleTechnique. */ Extern* createExtern (const Ogre::String& externType); /** Add an Extern to this ParticleTechnique. @param Pointer to a previously created Extern object. */ void addExtern (Extern* externObject); /** Get an Extern. Search by index. */ Extern* getExtern (size_t index) const; /** Get an Extern. Search by name. */ Extern* getExtern (const Ogre::String& externName) const; /** Get an Extern. Search by type. */ Extern* getExternType (const Ogre::String& externType) const; /** Get the number of Externs added to this ParticleTechnique. */ size_t getNumExterns (void) const; /** Delete an Extern that is part of this ParticleTechnique. Search by index. */ void destroyExtern (size_t index); /** Delete an Extern that is part of this ParticleTechnique. */ void destroyExtern (Extern* externObject); /** Delete all Externs of this ParticleTechnique. */ void destroyAllExterns (void); //-------------------------------------- Rest -------------------------------------- /** Update the renderqueue. @remarks This function invokes the renderer and updates the renderqueue of that renderer. This is not only performed for this ParticleTechnique, but also for the pooled ParticleTechniques if available. Updating the renderqueue causes the particles to be actually rendered. */ void _updateRenderQueue(Ogre::RenderQueue* queue); /** Perform some initialisation activities. @remarks To reduce initialisation activities as soon as the particle system is started, these activities can also be performed in front. */ void _prepare(void); /** Update this ParticleTechnique. @remarks Updating the ParticleTechnique actually sets all particles in motion. The ParticleTechnique is only updated if the ParticleSystem to which the ParticleTechnique belongs is started. */ void _update(Ogre::Real timeElapsed); /** Is called as soon as a new emitter is added or deleted, which leads to a re-evaluation of the emitted objects. @remarks Emitters are able to emit other objects (emitters, techniques, affectors) besides visual particles, and removing or adding an emitter could lead to a broken chain of references. This means that 1). Emitters that were emitted by a deleted emitter, aren't emitted anymore. 2). An added emitter could emit another emitter (or affector); the other emitter has to know that it will be emitted. 3). Another emitter could emit the emitter that is added; the added emitter has to know that. 4). If an already existing emitter sets its emitsName the chain is broken. @par This method runs through the whole chain of emitters each time a new emitter is added or an emitter is deleted. This has a performance penalty, but since the number of emitters is usually not very large we can get away with it. @par If an emitter is deleted and this emitter is also emitted itself, the effect of deletion is not always instantly noticable. Emitted emitters are part of the particle pool and are NOT deleted if the base emitter (from which the pooled emitters are cloned) is deleted. */ void _notifyEmissionChange(void); /** Implementation of the _notifyAttached, needed for each technique that is part of a particle system. @remarks Delegates to the renderer. */ void _notifyAttached(Ogre::Node* parent, bool isTagPoint = false); /** Implementation of the _notifyCurrentCamera, needed for each technique that is part of a particle system. @remarks Delegates to the renderer. */ void _notifyCurrentCamera(Ogre::Camera* camera); /** Notify the pooled techniques with the current camera. @remarks This is done for emitted ParticleTechniques. */ void _notifyCurrentCameraPooledTechniques(Ogre::Camera* camera); /** Implementation of the _notifyParticleResized, needed for each technique that is part of a particle system. @remarks Delegates to the renderer. */ void _notifyParticleResized(void); /** Perform activities when a ParticleTechnique is started. @remarks This is only used to set some attributes to their default value, so a re-start can be performed. Note, that one cannot assume that the _prepare() function has been called, so don´t perform initialisation activities on objects that are not created yet (for instance the renderer). */ void _notifyStart (void); /** Perform activities when a ParticleTechnique is stopped. */ void _notifyStop (void); /** Perform activities when a ParticleTechnique is paused. */ void _notifyPause (void); /** Perform activities when a ParticleTechnique is resumed. */ void _notifyResume (void); /** Validate whether a particle is expired. */ bool _isExpired(Particle* particle, Ogre::Real timeElapsed); /** Forces emission of particles. @remarks The number of requested particles are the exact number that are emitted. No down-scalling is applied. */ void forceEmission(ParticleEmitter* emitter, unsigned requested); /** Emits particles of the first emitter it encounters in this technique. */ void forceEmission(const Particle::ParticleType particleType, unsigned requested); /** Copy the attributes of this ParticleTechnique to another ParticleTechnique. */ virtual void copyAttributesTo (ParticleTechnique* technique); /** Get the Lod index. @remarks The Lod index determines at which distance this ParticleTechnique is active. This has only effect if the Lod distances of the ParticleSystem to which this ParticleTechnique belongs have been defined. */ unsigned short getLodIndex(void) const {return mLodIndex;}; /** Set the Lod index. */ void setLodIndex(unsigned short lodIndex) {mLodIndex = lodIndex;}; /** Determine which techniques, affectors, emitters will be emitted. @remarks All objects that are able to be emitted will get an indication when they are emitted. This function runs through all ParticleEmitters and if the ParticleEmitter emits objects other than visual particles, these objects are marked. */ void _markForEmission(void); /** Notify updating the axis aligned bounding box. @remarks The Particle System calls this function to make the ParticleTechnique calculating its mWorldAABB. */ void _notifyUpdateBounds(); /** Reset the bounds. */ void _resetBounds(); /** Notify that the Particle System is rescaled. */ void _notifyRescaled(const Ogre::Vector3& scale); /** Notify that the velocity is rescaled. */ void _notifyVelocityRescaled(const Ogre::Real& scaleVelocity); /** Returns the world aabb. */ const Ogre::AxisAlignedBox& getWorldBoundingBox(void) const {return mWorldAABB;} /** Sort the visual particles. @remarks Only the visual particles are sorted, because sorting non-visual particles doesn't make sense. */ void _sortVisualParticles(Ogre::Camera* camera); /** */ void setWidthCameraDependency(CameraDependency* cameraDependency); void setWidthCameraDependency(Ogre::Real squareDistance, bool inc); /** */ CameraDependency* getWidthCameraDependency(void); /** */ void setHeightCameraDependency(CameraDependency* cameraDependency); void setHeightCameraDependency(Ogre::Real squareDistance, bool inc); /** */ CameraDependency* getHeightCameraDependency(void); /** */ void setDepthCameraDependency(CameraDependency* cameraDependency); void setDepthCameraDependency(Ogre::Real squareDistance, bool inc); /** */ CameraDependency* getDepthCameraDependency(void); /** */ size_t getNumberOfEmittedParticles(void); /** */ size_t getNumberOfEmittedParticles(Particle::ParticleType particleType); /** Clears all active (emitted) particles. In other words, all particles are put back into the pool. */ void clearAllParticles(void); /** Reset the visual data in the pool. @remarks Visual particles may keep some additional visual data that needs to be reset in some cases. This function puts all particles back into the pool. */ void initVisualDataInPool(void); /** */ bool isKeepLocal(void) const; /** If this attribute is set to 'true', the particles are emitted relative to the technique */ void setKeepLocal(bool keepLocal); /** Transforms the particle position in a local position relative to the technique */ bool makeParticleLocal(Particle* particle); /** Returns the Spatial Hashtable. */ SpatialHashTable<Particle*>* getSpatialHashTable(void) const; /** Defines whether spatial hashing is used. */ void setSpatialHashing(bool spatialHashingUsed); /** Returns the celsize used in spatial hashing. */ unsigned short getSpatialHashingCellDimension(void) const; /** Set the celsize used in spatial hashing. A cel represents a small part of the 3d space in which particles may exist. The size of the cel is the same for both x, y and z dimension. */ void setSpatialHashingCellDimension(unsigned short spatialHashingCellDimension); /** Return the size of the overlap. */ unsigned short getSpatialHashingCellOverlap(void) const; /** Set the size of the overlap. @remarks The cell overlap is used to put a particle in multiple cells if needed. This is a better way to determine nearby particles. A particle in one cell is not considered nearby in relation to a particle in another cel, although they can be nearby in terms of their world position. If you want to inspect all particles positioned in a radius around a central particle, and that particle is close to the border of a cel, you miss a few particles in the neighbouring cell that are nearby. By defining an overlap you duplicate particles in multiple cells, but you are able to determine all nearby particles. @par Because particle are duplicated in multiple cells, you have to consider that validations between 2 particles in one cell are also performed in another cell. Set a flag to a particle, indicating that it has been validated. */ void setSpatialHashingCellOverlap(unsigned short spatialHashingCellOverlap); /** Returns the size of the hashtable used in spatial hashing. */ unsigned int getSpatialHashTableSize(void) const; /** Sets the size of the hashtable used in spatial hashing. */ void setSpatialHashTableSize(unsigned int spatialHashTableSize); /** Return the interval when the spatial hashtable is updated. */ Ogre::Real getSpatialHashingInterval(void) const; /** Set the interval when the spatial hashtable is updated. */ void setSpatialHashingInterval(Ogre::Real spatialHashingInterval); /** Return the indication whether to use only the particle position (false) or take the particle size into account (true). */ bool isSpatialHashingParticleSizeUsed(void) const; /** Set the indication whether to use only the particle position (false) or take the particle size into account (true). */ void setSpatialHashingParticleSizeUsed(bool spatialHashingParticleSizeUsed); /** Todo */ Ogre::Real getMaxVelocity(void) const; /** Todo */ void setMaxVelocity(Ogre::Real maxVelocity); /** Todo */ void addTechniqueListener (TechniqueListener* techniqueListener); /** Todo */ void removeTechniqueListener (TechniqueListener* techniqueListener); protected: /** Functor to sort by direction. */ struct DirectionSorter { Ogre::Vector3 sortDirection; DirectionSorter(const Ogre::Vector3& dir); float operator()(Particle* p) const; }; /** Functor to sort by distance. */ struct DistanceSorter { Ogre::Vector3 sortPosition; DistanceSorter(const Ogre::Vector3& pos); float operator()(Particle* p) const; }; static Ogre::RadixSort<std::list<VisualParticle*>, Particle*, float> mRadixSorter; /** Initialises a particle by another object (if available). */ void _initParticleForEmission(Particle* particle); /** Initialise the ParticleTechnique before it is emitted itself. */ virtual void _initForEmission(void); /** Initialise the ParticleTechnique before it is expired itself. */ virtual void _initForExpiration(ParticleTechnique* technique, Ogre::Real timeElapsed); /** Updates the renderqueue of pooled ParticleTechniques. @remarks It is possible to emit ParticleTechniques, where these ParticleTechniques are created by and stored in the particle pool. Since they aren't the responsibility of the ParticleSystem itself, they also aren't updated by the ParticleSystem. This means that the ParticleTechnique that emits the pooled ParticleTechniques, must update them. */ void _updateRenderQueuePooledTechniques(Ogre::RenderQueue* queue); /** Determines which techniques, affectors, emitters will be emitted by the given emitter. */ void _markForEmission(ParticleEmitter* emitter); /** Reset all MarkForEmission values (to false) for all techniques, affectors and emitters. */ void _resetMarkForEmission(void); /** Apply actions on the emitted particles (expire, affect, observe, ...). */ void _processParticles(Ogre::Real timeElapsed); /** Determine the dependencies and process them. */ void _processDependencies(void); /** Copies the pooled affectors from the pool to a separate list. @remarks Unfortunately, the particle pool can only be iterated once at a time. This prevents simultanious iteration of both particles and affectors, so the pooled affectors are stored in a temporary list. The benefit of a separate affector list is that it allows fast traversing once it has been created. */ void _extractPooledAffectors(void); /** If spatial hashing is required, the particle will be put in a hashtable. */ void _processSpatialHashing(Particle* particle, Ogre::Real timeElapsed); /** Function that affects a particle by the affectors that are part of this particle technique. */ void _processAffectors(Particle* particle, Ogre::Real timeElapsed, bool firstParticle); /** Perform some activities before all individual particles are processed. */ void _preProcessParticles(Ogre::Real timeElapsed); /** Perform some activities after all individual particles are processed. */ void _postProcessParticles(Ogre::Real timeElapsed); /** Todo. */ void _postProcessSpatialHashing(void); /** Function that uses an external source - outside the partice technique - to affect the particle. */ void _processExternals(Particle* particle, Ogre::Real timeElapsed, bool firstParticle); /** Perform actions on a single particle after each update. @remarks Besides affecting particles by affectors (which apply a global effect on a particle), particles can also affect themselves. */ void _processParticleSelf(Particle* particle, Ogre::Real timeElapsed, bool firstParticle); /** Perform actions if a particle gets expired. */ void _initParticleForExpiration(Particle* particle, Ogre::Real timeElapsed); /** Observers are classes that ´watch´ at a particle and perform an action as soon as a certain threshold is exceeded. This function calls all observers. */ void _processObservers(Particle* particle, Ogre::Real timeElapsed, bool firstParticle); /** Call the emitters to emit particles. */ void _emitParticles(Ogre::Real timeElapsed); /** Actually executes emission of particles. */ void _executeEmitParticles(ParticleEmitter* emitter, unsigned requested, Ogre::Real timeElapsed); /** Apply motion to a particle. */ void _processMotion(Particle* particle, Ogre::Real timeElapsed, bool firstParticle); /** Parent Particle System of this technique. */ ParticleSystem* mParentSystem; /** Name of the technique (optional). */ Ogre::String mName; /** Indication whether elements of the the particle pool are initialized. */ bool mVisualParticlePoolIncreased; bool mParticleEmitterPoolIncreased; bool mParticleTechniquePoolIncreased; bool mParticleAffectorPoolIncreased; bool mParticleSystemPoolIncreased; /** The maximum number of visual particles that can be emitted. */ size_t mVisualParticleQuota; /** The maximum number of emitter particles that can be emitted. */ size_t mEmittedEmitterQuota; /** The maximum number of technique particles that can be emitted. */ size_t mEmittedTechniqueQuota; /** The maximum number of affector particles that can be emitted. */ size_t mEmittedAffectorQuota; /** The maximum number of particle system particles that can be emitted. */ size_t mEmittedSystemQuota; /** List containing registered ParticleEmitters. */ ParticleEmitterList mEmitters; /** List containing registered ParticleAffectors. */ ParticleAffectorList mAffectors; /** List containing registered ParticleObservers. */ ParticleObserverList mObservers; /** List containing registered Behaviour templates. @remarks Note, that the ParticleBehaviours are only used as a blueprint. The actual ParticleBehaviour objects that are used in the ParticleUniverse plugin are attached to a Particle. */ ParticleBehaviourList mBehaviourTemplates; /** List containing registered Externs. */ ExternList mExterns; /** Particle pool. @remarks The particle pool contains precreated particles. In most cases these particles are visual particles, but the pool can also contain ParticleEmitters, ParticleAffectors and ParticleTechniques that are emitted. */ ParticlePool mPool; /** Because the particle pool is not capable to iterate multiple times at once, an extraction of the pooled ParticleAffectors is made. */ ParticleAffectorList mCopyOfPooledAffectors; /** Particle Renderer. */ ParticleRenderer* mRenderer; /** Indication whether _notifyEmissionChange() must be suppressed or not. @remarks Default is true */ bool mSuppressNotifyEmissionChange; /** Name of the material used in the renderer. */ Ogre::String mMaterialName; /** Default width of each visual particle. */ Ogre::Real mDefaultWidth; /** Default height of each visual particle. */ Ogre::Real mDefaultHeight; /** Default depth of each visual particle. */ Ogre::Real mDefaultDepth; /** Lod level. @remarks The mLodIndex corresponds to one of the lod distances set by the ParticleSystem. If the distance between the ParticleTechnique and the camera corresponds with the index of the ParticleTechnique, the ParticleTechnique will be enabled, otherwise the ParticleTechnique is disabled. @par Note, that mLodIndex only has a meaning if the lod distances are set by the ParticleSystem, otherwise it is ignored (which enables all ParticleTechniques). */ unsigned short mLodIndex; /** Distance between the latest camera that updated the renderqueue and the particle system. @remarks This is really only usable with a 1 camera set-up, because it always calculates the square distance between the technique and the latest camera update and you´ll never know which camera it was. The reason to have this attribute is to be able to apply LOD to a Particle System and Particle System LOD is only effective with 1 camera (otherwise, with more camera´s there is a risk that more than 1 Particle Technique is emitting) */ Ogre::Real mCameraSquareDistance; /** CameraDependency that causes a decrease (or increase if needed) of the particle width. */ CameraDependency* mWidthCameraDependency; /** CameraDependency that causes a decrease (or increase if needed) of the particle height. */ CameraDependency* mHeightCameraDependency; /** CameraDependency that causes a decrease (or increase if needed) of the particle depth. */ CameraDependency* mDepthCameraDependency; /** Helper Factory to create a CameraDependency. */ CameraDependencyFactory mCameraDependencyFactory; /** Indication used to determine whether the Extern objects must be prepared. */ bool mPrepareExtern; /** Indication used to determine whether the Behaviour objects must be prepared. */ bool mPrepareBehaviour; /** Indication used to determine whether the Affector objects must be prepared. */ bool mPrepareAffector; /** Indication used to determine whether the Emitter objects must be prepared. */ bool mPrepareEmitter; /** World AABB. @remarks Because all positions are in worldspace, the ParticleTechnique's worldspace bounding box is calculated. */ Ogre::AxisAlignedBox mWorldAABB; /** Determines whether the Particle Technique should update their bounds. */ bool mUpdateWorldAABB; /** Min/max extends of the WorldAABB. */ Ogre::Vector3 mMinWorldExtend; Ogre::Vector3 mMaxWorldExtend; bool mHasExtents; /** Determines whether particle positions should be kept local in relation to the technique. */ bool mKeepLocal; /** Similar as _notifyStart(), but now for the pooled components. */ void _notifyStartPooledComponents(void); /** Similar as _notifyStop(), but now for the pooled components. */ void _notifyStopPooledComponents(void); /** Similar as _notifyPause(), but now for the pooled components. */ void _notifyPausePooledComponents(void); /** Similar as _notifyResume(), but now for the pooled components. */ void _notifyResumePooledComponents(void); /** Although the scale is on a Particle System level, it is stored here also, because this value is often used. It is a derived value, so it has not get a get and set function. */ Ogre::Vector3 _mParticleSystemScale; /** Although the velocity scale is on a Particle System level, it is stored here also, because this value is often used. It is a derived value, so it has not get a get and set function. */ Ogre::Real _mParticleSystemScaleVelocity; /** If needed, the particles can be structured in a spatial hashtable. This is a fast way to store particles that are near each other in 3d space. The hashtable can be used for inter-particle collision or nearest neighbour search. @remarks We are using 2 hashtables. One table is filled during frame 1 and used in frame 2, while the other table is used in frame 1 and filled in frame 2. By swapping the tables after each frame we have the possibility to compare each particle in the processParticles loop with the particles in the currently used hashtable. */ bool mIsSpatialHashingUsed; bool mIsSpatialHashingInitialised; unsigned short mSpatialHashingCellDimension; // Cell size unsigned short mSpatialHashingCellOverlap; // Amount of overlap between each cell unsigned int mSpatialHashTableSize; SpatialHashTable<Particle*>* mSpatialHashTableA; SpatialHashTable<Particle*>* mSpatialHashTableB; SpatialHashTable<Particle*>* mCurrentSpatialHashTable; /** Attributes that determine that the spatial hashtable is the updated after every interval. */ Ogre::Real mSpatialHashingInterval; Ogre::Real mSpatialHashingIntervalRemainder; bool mSpatialHashingIntervalSet; /** Attributes that limit the velocity of the particles in this technique. */ Ogre::Real mMaxVelocity; bool mMaxVelocitySet; /** List of TechniqueListeners */ TechniqueListenerList mTechniqueListenerList; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 1004 ] ] ]
7b9da7f6407187b92ef6724b5b03e22db4a4397f
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/gfx/RenderableOrderedBillboards.h
0e2f1ffa029cc56d22ce09f66c7dc39a5b53df11
[ "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,099
h
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #ifndef __RENDER_ORDERED_BILLBOARDS_H #define __RENDER_ORDERED_BILLBOARDS_H #include "../kernel/Proxies.h" #include "../renderer/Renderable.h" #include "geometry/BufferChunk.h" #include "geometry/VBManagerSource.h" namespace dingus { struct SVertexXyzDiffuseTex1; struct SMatrix4x4; struct SOBillboard { public: void setWholeTexture() { tu1=tv1=0; tu2=tv2=1; } public: float x1, y1, x2, y2; float tu1, tv1, tu2, tv2; D3DCOLOR color; CD3DTexture* texture; }; /** * Billboard renderer with order-preserving. * * Renders billboards (aka sprites, or screen-aligned textured * quads). Preserves billboard submitting order - this may be not very * efficient if billboards use different textures. Use CRenderableBillboards * if order doesn't matter. */ class CRenderableOrderedBillboards : public CRenderable, public IRenderListener { public: CRenderableOrderedBillboards( CD3DIndexBuffer& ib, CEffectParams::TParamName texParamName ); virtual ~CRenderableOrderedBillboards(); SOBillboard& addBill() { mBills.push_back(SOBillboard()); return mBills.back(); }; void clear() { mBills.clear(); } // IRenderListener virtual void beforeRender( CRenderable& r, CRenderContext& ctx ); virtual void afterRender( CRenderable& r, CRenderContext& ctx ); virtual void render( const CRenderContext& ctx ); virtual const CD3DVertexBuffer* getUsedVB() const { return CDynamicVBManager::getInstance().getBuffer(); }; virtual const CD3DIndexBuffer* getUsedIB() const { return mIB; }; private: typedef SVertexXyzDiffuseTex1 TVertex; typedef std::vector<SOBillboard> TBillVector; private: CD3DIndexBuffer* mIB; CVBManagerSource mVBSource; CEffectParams::TParamName mTexParamName; TBillVector mBills; TVBChunk::TSharedPtr mChunk; }; }; // namespace #endif
[ [ [ 1, 74 ] ] ]
7617e19fcd81c83b2e2e2a4f9507fdffcefb3c17
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/gameobjects/structures/cSpiceSilo.cpp
944206522ae2bbf6d80b01e8f6ac86501cc432ca
[]
no_license
dmitrygerasimuk/dune2themaker-fossfriendly
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
89a6920b216f3964241eeab7cf1a631e1e63f110
refs/heads/master
2020-03-12T03:23:40.821001
2011-02-19T12:01:30
2011-02-19T12:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include "../../include/d2tmh.h" // Constructor cSpiceSilo::cSpiceSilo() { // other variables (class specific) } int cSpiceSilo::getType() { return SILO; } cSpiceSilo::~cSpiceSilo() { } void cSpiceSilo::think() { // think like base class cAbstractStructure::think(); } // Specific Animation thinking (flag animation OR its deploy animation) void cSpiceSilo::think_animation() { cAbstractStructure::think_animation(); cAbstractStructure::think_flag(); } void cSpiceSilo::think_guard() { } /* STRUCTURE SPECIFIC FUNCTIONS */ int cSpiceSilo::getSpiceSiloCapacity() { cHitpointCalculator hitpointCalculator; float percentage = ((float)getHitPoints() / (float)structures[getType()].hp); return hitpointCalculator.getByPercent(1000, percentage); }
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 43 ] ] ]
9f22c45ed6d95889b6445a73c4a8847c39063c22
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/graphics/texture/gtextureatlas.h
22938849fbe811f99620b4bdbd3cf8b11d084a7e
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
824
h
/* * gtextureatlas.h * * Created on: 25.7.2011 * Author: akin */ #ifndef GTEXTUREATLAS_H_ #define GTEXTUREATLAS_H_ #include <glm/glm> #include "gtexture.h" #include <atlas/atlas.h> namespace ice { class GTextureAtlas { protected: Atlas atlas; GTexture texture; bool initialized; public: GTextureAtlas(); virtual ~GTextureAtlas(); bool initialize( const glm::ivec2& dimensions , const int padding , ColorMode mode = RGBA ); bool resize( const glm::ivec2& val ); bool request( const glm::ivec2& dimensions , glm::ivec2& position ); bool release( const glm::ivec2& dimensions , const glm::ivec2& position ); unsigned int getPadding(); glm::ivec2 getDimension(); GTexture& getTexture(); }; } /* namespace ice */ #endif /* GTEXTUREATLAS_H_ */
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 26 ], [ 28, 39 ] ], [ [ 27, 27 ] ] ]
b2ea0d126b2b80da0b358e67bd7515123465fe83
43626054205d6048ec98c76db5641ce8e42b8237
/Tile Engine/CTileManager.h
26a94aa832288d1672af73a85c9614cc27fc059c
[]
no_license
Wazoobi/whitewings
b700da98b855a64442ad7b7c4b0be23427b0ee23
a53fdb832cfb1ce8605209c9af47f36b01c44727
refs/heads/master
2021-01-10T19:33:22.924792
2009-08-05T18:30:07
2009-08-05T18:30:07
32,119,981
0
0
null
null
null
null
UTF-8
C++
false
false
5,158
h
////////////////////////////////////////////////////////////////////////// // Filename: TileManager.h // // Author: David Seabolt // // Purpose: To encapsulate all level data and interactions thereof ////////////////////////////////////////////////////////////////////////// #ifndef CTILEMANAGER_H_ #define CTILEMANAGER_H_ //---------------------------------- // #include's #include "CLevel.h" #include "CCamera.h" class CTileManager { //---------------------------------------------- //Encapsulation of TOE CTileManager() {;} CTileManager(const CTileManager&) {;} CTileManager& operator=(const CTileManager&) {;} //---------------------------------------------- //--------------------------------------------------------------------------------------------------------- // Level Variables short m_shCurrentLevel; char** m_szFilenames; CLevel** m_pLevels; //---------------------------------------------------------------------------------------------------------- //------------------------------------ // Camera Variables CCamera* m_pCamera; CPlayer* m_pPlayer; //------------------------------------ protected: public: ////////////////////////////////////////////////////////////////////////// // Function: GetInstance // // Parameters: None // // Purpose: To return the current instance of the TileManager ////////////////////////////////////////////////////////////////////////// static CTileManager* GetInstance() { static CTileManager* m_pInstance = new CTileManager(); return m_pInstance; } ////////////////////////////////////////////////////////////////////////// // Function: ReleaseManager // // Parameters: None // // Purpose: To clean up any memory allocated by the manager ////////////////////////////////////////////////////////////////////////// void ReleaseManager(); ////////////////////////////////////////////////////////////////////////// // Function: GetCurrentLevel() // // Parameters: None // // Purpose: To return the current Level ////////////////////////////////////////////////////////////////////////// short GetCurrentLevel() {return m_shCurrentLevel;} ////////////////////////////////////////////////////////////////////////// // Function: SetCurrentLevel() // // Parameters: short level - the current level, must be <= max amount of levels // // Purpose: To set the current level being played ////////////////////////////////////////////////////////////////////////// void SetCurrentLevel(short level) {m_shCurrentLevel = level;} ////////////////////////////////////////////////////////////////////////// // Function: GetCurrentLevelFilePath() // // Parameters: short currentLevel - the current level being played // // Purpose: To get the current level's filepath to load from ////////////////////////////////////////////////////////////////////////// char* GetCurrentLevelFilePath(short currentLevel) {return m_szFilenames[currentLevel - 1];} ////////////////////////////////////////////////////////////////////////// // Function: SetCurrentLevelFilePath() // // Parameters: short currentLevel - the current level being played // // Purpose: To set the current level's filepath that the level will load from ////////////////////////////////////////////////////////////////////////// void SetCurrentLevelFilePath(short currentLevel); ////////////////////////////////////////////////////////////////////////// // Function: Update() // // Parameters: CPlayer* pPlayer - a pointer to the avatar // // Purpose: Update any level specific information ////////////////////////////////////////////////////////////////////////// void Update(CPlayer* pPlayer); ////////////////////////////////////////////////////////////////////////// // Function: Render() // // Parameters: None // // Purpose: To render the level ////////////////////////////////////////////////////////////////////////// void Render(); ////////////////////////////////////////////////////////////////////////// // Function: InitManager() // // Parameters: None // // Purpose: To instantiate information pertaining to the manager ////////////////////////////////////////////////////////////////////////// void InitManager(); ////////////////////////////////////////////////////////////////////////// // Function: CCamera* GetCamera() // // Parameters: None // // Purpose: To return the current instance of the camera ////////////////////////////////////////////////////////////////////////// CCamera* GetCamera() {return m_pCamera;} ////////////////////////////////////////////////////////////////////////// // Function: CheckLevelCollisions // // Parameters: CBase* pObject, CCamera* pCamera // // Purpose: To check to see if the object has collided with the level and send messages accordingly ////////////////////////////////////////////////////////////////////////// void CheckLevelCollisions(CBase* pObject, CCamera* pCamera); }; #endif
[ "dSeabolt66@1cfc0206-7002-11de-8585-3f51e31374b7" ]
[ [ [ 1, 170 ] ] ]
5aeee2f654ce533eb93c4f762a17975db635f7a3
718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1
/soft micros/Codigo/codigo portable/Propiedades/PropiedadIncrementable/PropiedadHora.hpp
681f75a641e7292ec70b4d196ec13c6fea6edbd2
[]
no_license
jonyMarino/microsdhacel
affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca
66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3
refs/heads/master
2020-05-18T19:53:51.301695
2011-05-30T20:40:24
2011-05-30T20:40:24
34,532,512
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
hpp
#ifndef _PROPIEDAD_HORA_HPP #define _PROPIEDAD_HORA_HPP #include <stdtypes.h> #include "PropiedadIncrementable.hpp" #pragma DATA_SEG PROPIEDAD_HORA_DATA #pragma CODE_SEG PROPIEDAD_HORA_CODE #pragma CONST_SEG DEFAULT class PropiedadHora:public PropiedadIncrementable{ public: PropiedadHora(void*obj,const struct ArgumentosPropiedadIncrementable* args,uchar numObjeto); virtual void incrementar(); virtual void decrementar(); virtual void setValor(int valor); virtual void print(OutputStream&os); }; struct PropiedadHoraFactory:public PropGetterVisualFactory{ virtual PropiedadGetter& getPropiedad(void*obj,const struct ArgumentosPropiedadGetter* args,uchar numObjeto)const; }; struct ConstructorPropiedadHora{ const struct PropGetterVisualFactory * factory; struct ArgumentosPropiedadIncrementable args; }; #pragma DATA_SEG DEFAULT #pragma CODE_SEG DEFAULT #endif
[ "jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549" ]
[ [ [ 1, 34 ] ] ]
f318ad30ac4cf30b78d69aa59bfdaeb9ba68a997
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nnavmesh/src/ndelaunay/ndelaunay.cc
b1c2fd1d7db50c5790813e5c85c3955c79997215
[]
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,870
cc
#include "precompiled/pchnnavmesh.h" //------------------------------------------------------------------------------ // ndelaunay.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "ndelaunay/ndelaunay.h" #include <stdlib.h> #include "mathlib/nmath.h" #include "kernel/ntypes.h" // for n_realloc #include "kernel/nlogclass.h" /* qsort(p,nv,sizeof(dXYZ),XYZCompare); : int XYZCompare(void *v1,void *v2) { dXYZ *p1,*p2; p1 = v1; p2 = v2; if (p1->x < p2->x) return(-1); else if (p1->x > p2->x) return(1); else return(0); } */ #define EPSILON 0.005f //------------------------------------------------------------------------------ /** Triangulate @brief Triangulation subroutine Takes as input NV vertices in array pxyz Returned is a list of ntri triangular faces in the array v These triangles are arranged in a consistent clockwise order. The triangle array 'v' should be malloced to 3 * nv The vertex array pxyz must be big enough to hold 3 more points The vertex array must be sorted in increasing x values say */ int nDelaunay::Triangulate (int nv, vector3 *pxyz, ITRIANGLE *v, int *ntri) { int *complete = 0; IEDGE *edges = 0; int nedge = 0; int trimax,emax = 200; int status = 0; int inside; int i,j,k; float xp,yp,x1,y1,x2,y2,x3,y3,xc,yc,r; float xmin,xmax,ymin,ymax,xmid,ymid; float dx,dy,dmax; /* Allocate memory for the completeness list, flag for each triangle */ trimax = 4 * nv; if ((complete = (int*)n_new_array (int, trimax)) == 0) { status = 1; goto skip; } /* Allocate memory for the edge list */ if ((edges = (IEDGE*)n_new_array (IEDGE, emax)) == 0) { status = 2; goto skip; } /* Find the maximum and minimum vertex bounds. This is to allow calculation of the bounding triangle */ xmin = pxyz[0].x; ymin = pxyz[0].z; xmax = xmin; ymax = ymin; for (i=1;i<nv;i++) { if (pxyz[i].x < xmin) xmin = pxyz[i].x; if (pxyz[i].x > xmax) xmax = pxyz[i].x; if (pxyz[i].z < ymin) ymin = pxyz[i].z; if (pxyz[i].z > ymax) ymax = pxyz[i].z; } dx = xmax - xmin; dy = ymax - ymin; dmax = (dx > dy) ? dx : dy; xmid = (xmax + xmin) / 2.0f; ymid = (ymax + ymin) / 2.0f; /* Set up the supertriangle This is a triangle which encompasses all the sample points. The supertriangle coordinates are added to the end of the vertex list. The supertriangle is the first triangle in the triangle list. */ pxyz[nv+0].x = xmid - 20 * dmax; pxyz[nv+0].y = 0.0; pxyz[nv+0].z = ymid - dmax; pxyz[nv+1].x = xmid; pxyz[nv+1].y = 0.0; pxyz[nv+1].z = ymid + 20 * dmax; pxyz[nv+2].x = xmid + 20 * dmax; pxyz[nv+2].y = 0.0; pxyz[nv+2].z = ymid - dmax; v[0].p1 = nv; v[0].p2 = nv+1; v[0].p3 = nv+2; complete[0] = false; *ntri = 1; /* Include each point one at a time into the existing mesh */ nTime startTime( nTimeServer::Instance()->GetTime() ); for (i=0;i<nv;i++) { if ( nTimeServer::Instance()->GetTime() - startTime > 10 ) { startTime = nTimeServer::Instance()->GetTime(); NLOG_REL( navbuild, (NLOGUSER | 1, "[2/4] Delaunay triangulation...%d/%d", i+1, nv) ); } xp = pxyz[i].x; yp = pxyz[i].z; nedge = 0; /* Set up the edge buffer. If the point (xp,yp) lies inside the circumcircle then the three edges of that triangle are added to the edge buffer and that triangle is removed. */ for (j=0;j<(*ntri);j++) { if (complete[j]) { continue; } x1 = pxyz[v[j].p1].x; y1 = pxyz[v[j].p1].z; x2 = pxyz[v[j].p2].x; y2 = pxyz[v[j].p2].z; x3 = pxyz[v[j].p3].x; y3 = pxyz[v[j].p3].z; inside = this->CircumCircle(xp,yp,x1,y1,x2,y2,x3,y3,&xc,&yc,&r); if (xc + r < xp) { complete[j] = true; } if (inside) { /* Check that we haven't exceeded the edge list size */ if (nedge+3 >= emax) { emax += 100; if ((edges = (IEDGE*)n_realloc(edges,emax*(long)sizeof(IEDGE))) == 0) { status = 3; goto skip; } } edges[nedge+0].p1 = v[j].p1; edges[nedge+0].p2 = v[j].p2; edges[nedge+1].p1 = v[j].p2; edges[nedge+1].p2 = v[j].p3; edges[nedge+2].p1 = v[j].p3; edges[nedge+2].p2 = v[j].p1; nedge += 3; v[j] = v[(*ntri)-1]; complete[j] = complete[(*ntri)-1]; (*ntri)--; j--; } } /* Tag multiple edges Note: if all triangles are specified anticlockwise then all interior edges are opposite pointing in direction. */ for ( j=0; j<nedge-1; j++ ) { for ( k=j+1; k<nedge; k++ ) { if ( (edges[j].p1 == edges[k].p2) && (edges[j].p2 == edges[k].p1) ) { edges[j].p1 = -1; edges[j].p2 = -1; edges[k].p1 = -1; edges[k].p2 = -1; } /* Shouldn't need the following, see note above */ if ( (edges[j].p1 == edges[k].p1) && (edges[j].p2 == edges[k].p2) ) { edges[j].p1 = -1; edges[j].p2 = -1; edges[k].p1 = -1; edges[k].p2 = -1; } } } /* Form new triangles for the current point Skipping over any tagged edges. All edges are arranged in clockwise order. */ for (j=0;j<nedge;j++) { if (edges[j].p1 < 0 || edges[j].p2 < 0) { continue; } if ((*ntri) >= trimax) { status = 4; goto skip; } v[*ntri].p1 = edges[j].p1; v[*ntri].p2 = edges[j].p2; v[*ntri].p3 = i; complete[*ntri] = false; (*ntri)++; } } /* Remove triangles with supertriangle vertices These are triangles which have a vertex number greater than nv */ /* for (i=0;i<(*ntri);i++) { if (v[i].p1 >= nv || v[i].p2 >= nv || v[i].p3 >= nv) { v[i] = v[(*ntri)-1]; (*ntri)--; i--; } }*/ skip: n_delete_array (edges); n_delete_array (complete); return(status); } //------------------------------------------------------------------------------ /** CircumCircle @return TRUE if a point (xp,yp) is inside the circumcircle made up of the points (x1,y1), (x2,y2), (x3,y3) The circumcircle centre is returned in (xc,yc) and the radius r NOTE: A point on the edge is inside the circumcircle */ int nDelaunay::CircumCircle (float xp,float yp, float x1, float y1, float x2, float y2, float x3, float y3, float *xc, float *yc, float *r) { double m1,m2,mx1,mx2,my1,my2; double dx,dy,rsqr,drsqr; double xxc, yyc; /* Check for coincident points */ if (n_abs(y1-y2) < EPSILON && n_abs(y2-y3) < EPSILON) { return(false); } if (n_abs(y2-y1) < EPSILON) { m2 = - (x3-x2) / (y3-y2); mx2 = (x2 + x3) / 2.0f; my2 = (y2 + y3) / 2.0f; xxc = (x2 + x1) / 2.0f; yyc = m2 * (xxc - mx2) + my2; } else if (n_abs(y3-y2) < EPSILON) { m1 = - (x2-x1) / (y2-y1); mx1 = (x1 + x2) / 2.0f; my1 = (y1 + y2) / 2.0f; xxc = (x3 + x2) / 2.0f; yyc = m1 * (xxc - mx1) + my1; } else { m1 = - (x2-x1) / (y2-y1); m2 = - (x3-x2) / (y3-y2); mx1 = (x1 + x2) / 2.0f; mx2 = (x2 + x3) / 2.0f; my1 = (y1 + y2) / 2.0f; my2 = (y2 + y3) / 2.0f; xxc = (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2); yyc = m1 * (xxc - mx1) + my1; } dx = x1 - xxc; dy = y1 - yyc; rsqr = dx*dx + dy*dy; *xc = float(xxc); *yc = float(yyc); *r = n_sqrt(float(rsqr)); dx = xp - xxc; dy = yp - yyc; drsqr = dx*dx + dy*dy; return drsqr < rsqr; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 324 ] ] ]
24cee7b5ee555ef0a56c525f276aca0b1382b128
485c5413e1a4769516c549ed7f5cd4e835751187
/Source/Engine/grass.cpp
40859cda69e50feb405fe212e1b2692dcffce56e
[]
no_license
FranckLetellier/rvstereogram
44d0a78c47288ec0d9fc88efac5c34088af88d41
c494b87ee8ebb00cf806214bc547ecbec9ad0ca0
refs/heads/master
2021-05-29T12:00:15.042441
2010-03-25T13:06:10
2010-03-25T13:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
#include "grass.h" #include "meshManager.h" #include "objMesh.h" grass::grass(int iType, int iTurn): m_iType(iType), m_iTurn(iTurn){ } void grass::draw()const{ glDisable(GL_CULL_FACE); glPushMatrix(); MeshManager::getInstance().getMesh("grass.obj")->Draw(); glPopMatrix(); glEnable(GL_CULL_FACE); }
[ [ [ 1, 23 ] ] ]
a4a5a71324fbb20723f6c90fce14852d6d3f18bb
51574a600a87ecfaaec8ea0e46b3809884859680
/Utils/ObjectIdPool.inl
2fba4ac5539e104adc1b12f757ee93985f9e0868
[]
no_license
suilevap/motion-plan
b5ad60a8448b118c3742c8c9c42b29fd5e41ef3e
d9f5693938287f2179ca2cb4eb75bda51b97bbb0
refs/heads/master
2021-01-10T03:29:50.373970
2011-12-20T22:39:55
2011-12-20T22:39:55
49,495,165
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
inl
#ifndef UTILS_OBJECTIDPOOL_H_ #error "Include from ObjectIdPoll.h only." #else #pragma warning( disable : 4018 ) template<class T> ObjectIdPool<T>::ObjectIdPool(void) { } template<class T> ObjectIdPool<T>::~ObjectIdPool(void) { for (int i = 0; i < _items.size(); ++i) { Free(i); } } template<class T> int ObjectIdPool<T>::New() { T* obj = new T(); int index = Add(obj); return index; } template<class T> int ObjectIdPool<T>::Add(T* obj) { int index; if (!_freeIds.empty()) { index = _freeIds.top(); _freeIds.pop(); _items[index] = obj; } else { _items.push_back(obj); index = _items.size()-1; } return index; } template<class T> T* ObjectIdPool<T>::Get(int id) { T* result = NULL; if ((id>=0) &&(id<_items.size())) { result=_items[id]; } return result; } template<class T> bool ObjectIdPool<T>::Free(int id) { bool isSucceed = false; if ((id>=0) &&(id<_items.size())) { if (_items[id] != NULL) { delete _items[id]; _items[id] = NULL; _freeIds.push(id); isSucceed = true; } } return isSucceed; } #pragma warning( default : 4018 ) #endif
[ "suilevap@localhost" ]
[ [ [ 1, 77 ] ] ]
d2092fda6cf41d0f5c6ad764b3669921a970508b
c5a289ffd550cc9f66e60f7fd1c547c167499a90
/planetrender/geoclipmap/src/GeoClipmapCube.cpp
9f2c86c142551bb6e398c4d1959edf2439eda32b
[]
no_license
ylyking/planetrender
c1a351389f8b0eb15ad13d3bc449ba7d8a10e3a1
56a30e51459d9368d07c10935c9e68fd99f87f39
refs/heads/master
2019-01-02T04:18:07.031438
2009-04-18T15:06:30
2009-04-18T15:06:30
35,853,741
0
0
null
null
null
null
UTF-8
C++
false
false
23,811
cpp
#include <OgreSceneManager.h> #include <OgreManualObject.h> #include <OgreMesh.h> #include <OgreMeshManager.h> #include <OgreCamera.h> #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> #include <OgreMaterialManager.h> #include <vector> #include "GeoClipmapCube.h" #include "Clipmap.h" using namespace Ogre; GeoClipmapCube::GeoClipmapCube(float radius, float maxHeight, SceneManager* sceneMgr, Camera* camera, unsigned int detailGridSize, String opticalDepthTexName, Light* light) : m_SceneMgr(sceneMgr), m_Camera(camera), m_Radius(radius), m_MaxHeight(maxHeight + radius), m_SemiEdgeLen(radius * Math::Cos(Degree(45))), //m_AABB(Vector3(-(radius + maxHeight) * Math::Cos(Degree(45))), Vector3((radius + maxHeight) * Math::Cos(Degree(45)))) m_AABB(Vector3(-(radius + maxHeight)), Vector3(radius + maxHeight)), m_OpticalDepthTexName(opticalDepthTexName), m_light(light) { // m_ClipmapSize = cm->getLayerSize(0) - 1;//1 * (m_N - 1) ; // 64;//this is wrong, just a replacement value for debug m_ClipmapSize = 129 - 1; assert(m_ClipmapSize % 2 == 0); m_N = detailGridSize; // correct value of m_ClipmapSize is a even integer > N m_ResNamePrefix = StringConverter::toString(reinterpret_cast<unsigned long>(this)) + "_"; // create the patches memset(m_Patches, 0, sizeof(GeoClipmapPatch*) * 6); for(int i = 0; i < 6; i++) { m_Clipmaps[i] = new Clipmap(5, m_ClipmapSize + 1, detailGridSize); for(int lod = 0; lod < 5; lod++) { m_Clipmaps[i]->addTexture("marsheightm" + StringConverter::toString(i) + "_" + StringConverter::toString(lod) + ".bmp"); } m_Patches[i] = new GeoClipmapPatch(*this, i); } // creates meshes createGrids(); } GeoClipmapCube::~GeoClipmapCube(void) { for(int i = 0; i < 6; i++) { delete m_Patches[i]; delete m_Clipmaps[i]; } removeBlockMeshes(); } const String& GeoClipmapCube::getMovableType(void) const { static String movType = "GeoClipmapCube"; return movType; } const AxisAlignedBox& GeoClipmapCube::getBoundingBox(void) const { return m_AABB; } Real GeoClipmapCube::getBoundingRadius(void) const { return m_Radius + m_MaxHeight; } void GeoClipmapCube::_updateRenderQueue(RenderQueue* queue) { computePatchViewpoints(); for(int i = 0; i < 6; i++) if (m_FaceVisible[i]) m_Patches[i]->_updateRenderQueue(queue); } void GeoClipmapCube::computeFaceTxMat(Node* parent) { // init the transformation matrix Matrix3 rot[6]; Vector3 trans[6] = { Vector3( 1, 0, 0), Vector3(-1, 0, 0), Vector3( 0, 1, 0), Vector3( 0,-1, 0), Vector3( 0, 0, 1), Vector3( 0, 0,-1) }; //float clipmapSize = (m_N - 1); // this is wrong, just a replacement value for debug float scaleGeoToClipmap = m_SemiEdgeLen / ((m_ClipmapSize) / 2.0); rot[0].FromAxes(Vector3( 0, 0,-1), Vector3( 0, 1, 0), Vector3( 1, 0, 0)); rot[1].FromAxes(Vector3( 0, 0, 1), Vector3( 0, 1, 0), Vector3(-1, 0, 0)); rot[2].FromAxes(Vector3( 1, 0, 0), Vector3( 0, 0,-1), Vector3( 0, 1, 0)); rot[3].FromAxes(Vector3( 1, 0, 0), Vector3( 0, 0, 1), Vector3( 0,-1, 0)); rot[4].FromAxes(Vector3( 1, 0, 0), Vector3( 0, 1, 0), Vector3( 0, 0, 1)); rot[5].FromAxes(Vector3(-1, 0, 0), Vector3( 0, 1, 0), Vector3( 0, 0,-1)); // computes.... for (int i = 0; i < 6; i++) { m_xForm[i] = Matrix4::IDENTITY; // rot m_xForm[i] = rot[i] * scaleGeoToClipmap; // scale // trans m_xForm[i].setTrans(m_SemiEdgeLen * trans[i]); } // finally, update the clip planes, since it is in world space... /*Plane clipPlanes[4] = { // old code for rect plane Plane( 1, 0, 0, m_ClipmapSize / 2.0), Plane(-1, 0, 0, m_ClipmapSize / 2.0), Plane( 0, 1, 0, m_ClipmapSize / 2.0), Plane( 0,-1, 0, m_ClipmapSize / 2.0), };*/ float cp_nelm = Math::InvSqrt(2); float cp_d = (m_ClipmapSize) / 2.0 * Math::Sin(Degree(45)); Plane clipPlanes[4] = { Plane( cp_nelm, 0, cp_nelm, cp_d), Plane(-cp_nelm, 0, cp_nelm, cp_d), Plane( 0, cp_nelm, cp_nelm, cp_d), Plane( 0,-cp_nelm, cp_nelm, cp_d), }; for(int i = 0; i < 6; i++) { for(int j = 0; j < 4; j++) { m_Patches[i]->setClipPlanes(j, _getParentNodeFullTransform() * m_xForm[i] * clipPlanes[j]); } } } void GeoClipmapCube::_notifyAttached(Node* parent, bool isTagPoint) { if (parent != NULL) computeFaceTxMat(parent); MovableObject::_notifyAttached(parent, isTagPoint); } void GeoClipmapCube::_notifyMoved(void) { computeFaceTxMat(getParentNode()); MovableObject::_notifyMoved(); } void GeoClipmapCube::getFaceTransformMatrix(int faceID, Matrix4* mat) const { // place the patches in correct location, scale and orientation assert(faceID >= 0 && faceID < 6); *mat = m_xForm[faceID]; } void GeoClipmapCube::createGrids() { int m = (m_N + 1) / 4; int l = 2 * (m - 1) + 3; createGrid(GCM_MESH_BASE, m_ClipmapSize+1, m_ClipmapSize+1); createGrid(GCM_MESH_MXM, m, m); createGrid(GCM_MESH_MX3, m, 3); createGrid(GCM_MESH_3XM, 3, m); createGrid(GCM_MESH_2XL, 2, l); createGrid(GCM_MESH_LX2, l, 2); createTFillingGrid(GCM_MESH_TFillH, 2 * m, false); createTFillingGrid(GCM_MESH_TFillV, 2 * m, true); } void GeoClipmapCube::createGrid(MeshType meshType, int vertexCountX, int vertexCountY) { ManualObject* manual = m_SceneMgr->createManualObject("Geoclipmap"); // Use identity view/projection matrices manual->setUseIdentityProjection(true); manual->setUseIdentityView(true); // calc how many vertex and idx are needed int SegX = vertexCountX - 1, SegY = vertexCountY - 1; int BlkMeshWidth = SegX, BlkMeshHeight = SegY; // let them be equal, this saves lots of crazy maths int VertexCount = vertexCountX * vertexCountY; int RectCount = SegX * SegY; int IdxCount = RectCount * 2 * 3; manual->estimateVertexCount(VertexCount); manual->estimateIndexCount(IdxCount); manual->begin(m_ResNamePrefix + "TempObj", RenderOperation::OT_TRIANGLE_LIST); // gen vertex Vector3 vStart(-BlkMeshWidth / 2.0, BlkMeshHeight / 2.0, 0); m_MeshAABBs[getMeshName(meshType)].setMinimum(-BlkMeshWidth / 2.0, -BlkMeshHeight / 2.0, -m_MaxHeight); m_MeshAABBs[getMeshName(meshType)].setMaximum(BlkMeshWidth / 2.0, BlkMeshHeight / 2.0, m_MaxHeight); Vector3 vDeltaX((Real)BlkMeshWidth / SegX, 0, 0); Vector3 vDeltaY(0, -(Real)BlkMeshHeight / SegY, 0); Vector3 v(vStart); for(int y = 0; y < vertexCountY; y++) { for(int x = 0; x < vertexCountX; x++) { manual->position(v); v += vDeltaX; } v.x = vStart.x; v += vDeltaY; } // gen idx for(int y = 0; y < SegY; y++) { for(int x = y * vertexCountX; x < y * vertexCountX + SegX; x++) { manual->index(x); manual->index(x + vertexCountX); manual->index(x + vertexCountX + 1); manual->index(x); manual->index(x + vertexCountX + 1); manual->index(x + 1); } } manual->end(); manual->convertToMesh(getMeshName(meshType)); m_SceneMgr->destroyManualObject(manual); } void GeoClipmapCube::createTFillingGrid(MeshType meshType, int coarserVertexCount, bool transpose) { ManualObject* manual = m_SceneMgr->createManualObject("Geoclipmap"); // Use identity view/projection matrices manual->setUseIdentityProjection(true); manual->setUseIdentityView(true); // calc how many vertex and idx are needed int SegX = coarserVertexCount - 1; int BlkMeshWidth = SegX * 2, BlkMeshHeight = 0; // let them be equal, this saves lots of crazy maths int VertexCount = coarserVertexCount + 2 * coarserVertexCount - 1; int RectCount = (coarserVertexCount - 1) * 3; int IdxCount = RectCount * 3; manual->estimateVertexCount(VertexCount); manual->estimateIndexCount(IdxCount); manual->begin("Geoclipmap", RenderOperation::OT_TRIANGLE_LIST); // Set aabb Real eps = 1; if (transpose) { m_MeshAABBs[getMeshName(meshType)].setMinimum(-eps, -BlkMeshWidth / 2.0, -m_MaxHeight); m_MeshAABBs[getMeshName(meshType)].setMaximum(eps, BlkMeshWidth / 2.0, m_MaxHeight); } else { m_MeshAABBs[getMeshName(meshType)].setMinimum(-BlkMeshWidth / 2.0, -eps, -m_MaxHeight); m_MeshAABBs[getMeshName(meshType)].setMaximum(BlkMeshWidth / 2.0, eps, m_MaxHeight); } // gen vertex Vector3 vStart(-BlkMeshWidth / 2.0, 0, 0); Vector3 vDeltaX((Real)BlkMeshWidth / SegX, 0, 0); Vector3 v(vStart); // gen the coarser vertex first for(int x = 0; x < coarserVertexCount; x++) { if (transpose) manual->position(v.z, v.x, v.y); else manual->position(v); v += vDeltaX; } v = vStart; //v.z = 10; vDeltaX = Vector3((Real)BlkMeshWidth / SegX / 2, 0, 0); // gen the finer vertex for(int x = 0; x < 2 * coarserVertexCount - 1; x++) { if (transpose) manual->position(v.z, v.x, v.y); else manual->position(v); v += vDeltaX; } // gen idx for(int x = 0; x < coarserVertexCount - 1; x++) { int finerIdx = x * 2 + coarserVertexCount; manual->index(x); manual->index(finerIdx); manual->index(finerIdx + 1); manual->index(x); manual->index(finerIdx + 1); manual->index(x + 1); manual->index(x + 1); manual->index(finerIdx + 1); manual->index(finerIdx + 2); } manual->end(); manual->convertToMesh(getMeshName(meshType)); m_SceneMgr->destroyManualObject(manual); } const String& GeoClipmapCube::getMeshName(MeshType meshType) const { static const String meshMxMSuffix = "MxM"; static const String meshMx3Suffix = "Mx3"; static const String mesh3xMSuffix = "3xM"; static const String mesh2xLSuffix = "2xL"; static const String meshLx2Suffix = "Lx2"; static const String meshTFillHSuffix = "TFillH"; static const String meshTFillVSuffix = "TFillV"; static const String meshBaseSuffix = "Base"; static String names[GCM_MESH_COUNT] = { m_ResNamePrefix + meshMxMSuffix, m_ResNamePrefix + meshMx3Suffix, m_ResNamePrefix + mesh3xMSuffix, m_ResNamePrefix + mesh2xLSuffix, m_ResNamePrefix + meshLx2Suffix, m_ResNamePrefix + meshTFillHSuffix, m_ResNamePrefix + meshTFillVSuffix, m_ResNamePrefix + meshBaseSuffix }; return names[meshType]; } const AxisAlignedBox& GeoClipmapCube::getMeshAABB(String meshName) const { return m_MeshAABBs.find(meshName)->second; } void GeoClipmapCube::removeBlockMeshes() const { for(int i = 0; i < GCM_MESH_COUNT; i++) MeshManager::getSingleton().remove(getMeshName((MeshType)i)); } inline int roundup(float n) { if (n >= 0) return (n + 0.5); else return (n - 0.5); } inline int sign(float n) { if (n >= 0) return 1; else return -1; } void Ogre::GeoClipmapCube::computePatchViewpoints() { Matrix4 matLocalInv = _getParentNodeFullTransform().inverse(); Vector3 camPosLocal = matLocalInv * m_Camera->getPosition(); //Vector3(0, 0, 300); // find out the lod level int maxLodLvl; // self exclusive float camHeight = camPosLocal.length() - (m_Radius * 1.1); if (camHeight < 0) camHeight = 0; maxLodLvl = getClipmapDepth() - camHeight / 70; if (maxLodLvl < 1) maxLodLvl = 1; // scale it from geo space to clipmap space camPosLocal = camPosLocal / m_SemiEdgeLen * (m_ClipmapSize / 2.0); m_CamPosLocal = camPosLocal; m_LightDirLocal = matLocalInv.transpose() * -m_light->getDirection(); int activeFaceID = -1; // mark all faces visible memset(m_FaceVisible, 1, sizeof(m_FaceVisible)); // first part, find the active face if (Math::Abs(camPosLocal.x) > Math::Abs(camPosLocal.y)) { if (Math::Abs(camPosLocal.x) > Math::Abs(camPosLocal.z)) { if (camPosLocal.x >= 0) { activeFaceID = 0; m_FaceVisible[1] = false; } else { activeFaceID = 1; m_FaceVisible[0] = false; } } else { if (camPosLocal.z >= 0) { activeFaceID = 4; m_FaceVisible[5] = false; } else { activeFaceID = 5; m_FaceVisible[4] = false; } } } else { if (Math::Abs(camPosLocal.y) > Math::Abs(camPosLocal.z)) { if (camPosLocal.y >= 0) { activeFaceID = 2; m_FaceVisible[3] = false; } else { activeFaceID = 3; m_FaceVisible[2] = false; } } else { if (camPosLocal.z >= 0) { activeFaceID = 4; m_FaceVisible[5] = false; } else { activeFaceID = 5; m_FaceVisible[4] = false; } } } static int adjacentFaceTable[6][4] = { {5, 4, 2, 3}, {4, 5, 2, 3}, {0, 1, 5, 4}, {0, 1, 4, 5}, {0, 1, 2, 3}, {1, 0, 2, 3} }; std::vector<Vector2> viewPosLists[6]; // resize the view post lists for (int i = 0; i < 6; i++) { viewPosLists[i].resize(maxLodLvl); } Vector2 camPosOfFaces[6]; // init the view pos of every faces switch (activeFaceID) { case 0: camPosOfFaces[0].x = -camPosLocal.z * m_ClipmapSize / 2.0 / camPosLocal.x; camPosOfFaces[0].y = camPosLocal.y * m_ClipmapSize / 2.0 / camPosLocal.x; break; case 1: camPosOfFaces[0].x = camPosLocal.z * m_ClipmapSize / 2.0 / -camPosLocal.x; camPosOfFaces[0].y = camPosLocal.y * m_ClipmapSize / 2.0 / -camPosLocal.x; break; case 2: camPosOfFaces[0].x = camPosLocal.x * m_ClipmapSize / 2.0 / camPosLocal.y; camPosOfFaces[0].y = -camPosLocal.z * m_ClipmapSize / 2.0 / camPosLocal.y; break; case 3: camPosOfFaces[0].x = camPosLocal.x * m_ClipmapSize / 2.0 / -camPosLocal.y; camPosOfFaces[0].y = camPosLocal.z * m_ClipmapSize / 2.0 / -camPosLocal.y; break; case 4: camPosOfFaces[0].x = camPosLocal.x * m_ClipmapSize / 2.0 / camPosLocal.z; camPosOfFaces[0].y = camPosLocal.y * m_ClipmapSize / 2.0 / camPosLocal.z; break; case 5: camPosOfFaces[0].x = -camPosLocal.x * m_ClipmapSize / 2.0 / -camPosLocal.z; camPosOfFaces[0].y = camPosLocal.y * m_ClipmapSize / 2.0 / -camPosLocal.z; break; } for (int i = 1; i < 6; i++) { camPosOfFaces[i] = camPosOfFaces[0]; } int maxLodLvlAdjacent[6]; memset(maxLodLvlAdjacent, 0, sizeof(maxLodLvlAdjacent)); maxLodLvlAdjacent[activeFaceID] = maxLodLvl - 1; bool updated = false; // now calculate the view pos at every lod level of active face first // also calculate the offset of the adjacent faces for (int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { if (lodLvl == 0) { viewPosLists[activeFaceID][lodLvl].x = roundup(camPosOfFaces[activeFaceID].x * (1 << lodLvl) ) / (1 << lodLvl); viewPosLists[activeFaceID][lodLvl].y = roundup(camPosOfFaces[activeFaceID].y * (1 << lodLvl) ) / (1 << lodLvl); } else { Vector2 offsetSign = camPosOfFaces[activeFaceID] - viewPosLists[activeFaceID][lodLvl - 1]; offsetSign.x = sign(offsetSign.x); offsetSign.y = sign(offsetSign.y); Vector2 offsetMag = Vector2(Math::Pow(2, -lodLvl)); Vector2 offset = offsetSign * offsetMag; viewPosLists[activeFaceID][lodLvl] = viewPosLists[activeFaceID][lodLvl - 1] + offset; // Ensure continuous lod level int nl = m_N - 1; float lodLvlPow = Math::Pow(2, -lodLvl); float half_nl = nl / 2; float half_nl_lod = half_nl * lodLvlPow; float eps = 1e-3; float halfClipmapSize = m_ClipmapSize / 2.0; float xp, xn, yp, yn; xp = halfClipmapSize - viewPosLists[activeFaceID][lodLvl].x - half_nl_lod; xn = halfClipmapSize - -viewPosLists[activeFaceID][lodLvl].x - half_nl_lod; yp = halfClipmapSize - viewPosLists[activeFaceID][lodLvl].y - half_nl_lod; yn = halfClipmapSize - -viewPosLists[activeFaceID][lodLvl].y - half_nl_lod; if (Math::Abs(xp) <= eps) camPosOfFaces[adjacentFaceTable[activeFaceID][0]].x += 2 * lodLvlPow; if (Math::Abs(xn) <= eps) camPosOfFaces[adjacentFaceTable[activeFaceID][1]].x -= 2 * lodLvlPow; if (Math::Abs(yp) <= eps) camPosOfFaces[adjacentFaceTable[activeFaceID][2]].y += 2 * lodLvlPow; if (Math::Abs(yn) <= eps) camPosOfFaces[adjacentFaceTable[activeFaceID][3]].y -= 2 * lodLvlPow; if (xp <= eps) maxLodLvlAdjacent[adjacentFaceTable[activeFaceID][0]] = lodLvl; if (xn <= eps) maxLodLvlAdjacent[adjacentFaceTable[activeFaceID][1]] = lodLvl; if (yp <= eps) maxLodLvlAdjacent[adjacentFaceTable[activeFaceID][2]] = lodLvl; if (yn <= eps) maxLodLvlAdjacent[adjacentFaceTable[activeFaceID][3]] = lodLvl; } // check that if last frame has less details than the new frame const std::vector<Vector2>& oldViewPosList = m_Patches[activeFaceID]->getViewPosList(); if (oldViewPosList.size() <= lodLvl) { updated = true; continue; } // check that is the position of last frame is the same as the new frame Vector2 oldViewPos = oldViewPosList[lodLvl]; if ((oldViewPos - viewPosLists[activeFaceID][lodLvl]).length() > 1) updated = true; } // if the last frame has more details than the new frame... if (m_Patches[activeFaceID]->getViewPosList().size() > maxLodLvl) updated = true; // update is not needed, return if (!updated) return; // now, calculate the view position of adjacent faces for(int i = 0; i < 6; i++) { if (i == activeFaceID) continue; for (int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { if (lodLvl == 0) { viewPosLists[i][lodLvl].x = roundup(camPosOfFaces[i].x * Math::Pow(2, lodLvl)) / Math::Pow(2, lodLvl); viewPosLists[i][lodLvl].y = roundup(camPosOfFaces[i].y * Math::Pow(2, lodLvl)) / Math::Pow(2, lodLvl); } else { Vector2 offsetSign = camPosOfFaces[i] - viewPosLists[i][lodLvl - 1]; offsetSign.x = sign(offsetSign.x); offsetSign.y = sign(offsetSign.y); Vector2 offsetMag = Vector2(Math::Pow(2, -lodLvl)); Vector2 offset = offsetSign * offsetMag; viewPosLists[i][lodLvl] = viewPosLists[i][lodLvl - 1] + offset; } } } // remove cracks between adjacent faces if (maxLodLvl > 1) { int xpFaceIdx, xnFaceIdx, ypFaceIdx, ynFaceIdx; xpFaceIdx = adjacentFaceTable[activeFaceID][0]; xnFaceIdx = adjacentFaceTable[activeFaceID][1]; ypFaceIdx = adjacentFaceTable[activeFaceID][2]; ynFaceIdx = adjacentFaceTable[activeFaceID][3]; int nl = m_N - 1; float lodLvlPow = 1;//Math::Pow(2, -lodLvl); float half_nl = nl / 2; float half_nl_lod = half_nl * lodLvlPow; float eps = 0.5 + 1e-3; //why 0.5??? float halfClipmapSize = m_ClipmapSize / 2.0; float xp, xn, yp, yn; xp = halfClipmapSize - viewPosLists[activeFaceID][0].x - half_nl_lod; xn = halfClipmapSize - -viewPosLists[activeFaceID][0].x - half_nl_lod; yp = halfClipmapSize - viewPosLists[activeFaceID][0].y - half_nl_lod; yn = halfClipmapSize - -viewPosLists[activeFaceID][0].y - half_nl_lod; if (xp <= eps && yp <= eps) { if (viewPosLists[ypFaceIdx][0].y > viewPosLists[xpFaceIdx][0].x) for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[xpFaceIdx][lodLvl].x = viewPosLists[ypFaceIdx][lodLvl].y; } else for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[ypFaceIdx][lodLvl].y = viewPosLists[xpFaceIdx][lodLvl].x; }; } if (xp <= eps && yn <= eps) { if (-viewPosLists[ynFaceIdx][0].y > viewPosLists[xpFaceIdx][0].x) for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[xpFaceIdx][lodLvl].x = -viewPosLists[ynFaceIdx][lodLvl].y; } else for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[ynFaceIdx][lodLvl].y = -viewPosLists[xpFaceIdx][lodLvl].x; }; } if (xn <= eps && yp <= eps) { if (viewPosLists[ypFaceIdx][0].y > -viewPosLists[xnFaceIdx][0].x) for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[xnFaceIdx][lodLvl].x = -viewPosLists[ypFaceIdx][lodLvl].y; } else for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[ypFaceIdx][lodLvl].y = -viewPosLists[xnFaceIdx][lodLvl].x; }; } if (xn <= eps && yn <= eps) { if (-viewPosLists[ynFaceIdx][0].y > -viewPosLists[xnFaceIdx][0].x) for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[xnFaceIdx][lodLvl].x = viewPosLists[ynFaceIdx][lodLvl].y; } else for(int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { viewPosLists[ynFaceIdx][lodLvl].y = viewPosLists[xnFaceIdx][lodLvl].x; }; } } // transform the coord into correct face spaces for (int lodLvl = 0; lodLvl < maxLodLvl; lodLvl++) { Vector2 st[6]; switch (activeFaceID) { case 0: st[0].x = viewPosLists[0][lodLvl].x; st[0].y = viewPosLists[0][lodLvl].y; st[1].x = 0; st[1].y = 0; st[2].x = m_ClipmapSize - viewPosLists[2][lodLvl].y; st[2].y = viewPosLists[2][lodLvl].x; st[3].x = viewPosLists[3][lodLvl].y + m_ClipmapSize; st[3].y = -viewPosLists[3][lodLvl].x; st[4].x = viewPosLists[4][lodLvl].x + m_ClipmapSize; st[4].y = viewPosLists[4][lodLvl].y; st[5].x = viewPosLists[5][lodLvl].x - m_ClipmapSize; st[5].y = viewPosLists[5][lodLvl].y; break; case 1: st[0].x = 0; st[0].y = 0; st[1].x = viewPosLists[1][lodLvl].x; st[1].y = viewPosLists[1][lodLvl].y; st[2].x = viewPosLists[2][lodLvl].y - m_ClipmapSize; st[2].y = -viewPosLists[2][lodLvl].x; st[3].x = -m_ClipmapSize - viewPosLists[3][lodLvl].y; st[3].y = viewPosLists[3][lodLvl].x; st[4].x = viewPosLists[4][lodLvl].x - m_ClipmapSize; st[4].y = viewPosLists[4][lodLvl].y; st[5].x = viewPosLists[5][lodLvl].x + m_ClipmapSize; st[5].y = viewPosLists[5][lodLvl].y; break; case 2: st[0].x = viewPosLists[0][lodLvl].y; st[0].y = m_ClipmapSize - viewPosLists[0][lodLvl].x; st[1].x = -viewPosLists[1][lodLvl].y; st[1].y = viewPosLists[1][lodLvl].x + m_ClipmapSize; st[2].x = viewPosLists[2][lodLvl].x; st[2].y = viewPosLists[2][lodLvl].y; st[3].x = 0; st[3].y = 0; st[4].x = viewPosLists[4][lodLvl].x; st[4].y = viewPosLists[4][lodLvl].y + m_ClipmapSize; st[5].x = -viewPosLists[5][lodLvl].x; st[5].y = m_ClipmapSize - viewPosLists[5][lodLvl].y; break; case 3: st[0].x = -viewPosLists[0][lodLvl].y; st[0].y = viewPosLists[0][lodLvl].x - m_ClipmapSize; st[1].x = viewPosLists[1][lodLvl].y; st[1].y = -m_ClipmapSize - viewPosLists[1][lodLvl].x; st[2].x = 0; st[2].y = 0; st[3].x = viewPosLists[3][lodLvl].x; st[3].y = viewPosLists[3][lodLvl].y; st[4].x = viewPosLists[4][lodLvl].x; st[4].y = viewPosLists[4][lodLvl].y - m_ClipmapSize; st[5].x = -viewPosLists[5][lodLvl].x; st[5].y = -m_ClipmapSize - viewPosLists[5][lodLvl].y; break; case 4: st[0].x = viewPosLists[0][lodLvl].x - m_ClipmapSize; st[0].y = viewPosLists[0][lodLvl].y; st[1].x = viewPosLists[1][lodLvl].x + m_ClipmapSize; st[1].y = viewPosLists[1][lodLvl].y; st[2].x = viewPosLists[2][lodLvl].x; st[2].y = viewPosLists[2][lodLvl].y - m_ClipmapSize; st[3].x = viewPosLists[3][lodLvl].x; st[3].y = viewPosLists[3][lodLvl].y + m_ClipmapSize; st[4].x = viewPosLists[4][lodLvl].x; st[4].y = viewPosLists[4][lodLvl].y; st[5].x = 0; st[5].y = 0; break; case 5: st[0].x = viewPosLists[0][lodLvl].x + m_ClipmapSize; st[0].y = viewPosLists[0][lodLvl].y; st[1].x = viewPosLists[1][lodLvl].x - m_ClipmapSize; st[1].y = viewPosLists[1][lodLvl].y; st[2].x = -viewPosLists[2][lodLvl].x; st[2].y = m_ClipmapSize - viewPosLists[2][lodLvl].y; st[3].x = -viewPosLists[3][lodLvl].x; st[3].y = -m_ClipmapSize - viewPosLists[3][lodLvl].y; st[4].x = 0; st[4].y = 0; st[5].x = viewPosLists[5][lodLvl].x; st[5].y = viewPosLists[5][lodLvl].y; break; } for(int i = 0; i < 6; i++) { viewPosLists[i][lodLvl] = st[i]; } } for(int i = 0; i < 6; i++) { viewPosLists[i].resize(maxLodLvlAdjacent[i] + 1); m_Patches[i]->setViewPosList(viewPosLists[i]); } } unsigned int Ogre::GeoClipmapCube::getClipmapDepth() const { return m_Clipmaps[0]->getDepth(); }
[ "tc0312@8bc37eee-a4f6-11dd-9fb0-994c145e5ff7", "mclam07@8bc37eee-a4f6-11dd-9fb0-994c145e5ff7" ]
[ [ [ 1, 5 ], [ 9, 14 ], [ 16, 21 ], [ 26, 40 ], [ 42, 365 ], [ 367, 369 ], [ 379, 381 ], [ 385, 534 ], [ 536, 541 ], [ 543, 547 ], [ 552, 748 ] ], [ [ 6, 8 ], [ 15, 15 ], [ 22, 25 ], [ 41, 41 ], [ 366, 366 ], [ 370, 378 ], [ 382, 384 ], [ 535, 535 ], [ 542, 542 ], [ 548, 551 ] ] ]
0394012f7e4da647134673a88791fcedaf1a7d92
55196303f36aa20da255031a8f115b6af83e7d11
/include/bikini/system/shader.hpp
38cf940d1d0328e6119e826edacc46aa69fa34cf
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
644
hpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008-2010 Viktor Reutskyy [email protected] *//*---------------------------------------------------------------------------------------------*/ #pragma once #define make_a_string(_ARG) #_ARG #if defined _XBOX # define compiled_shader(_NAME) make_a_string(_NAME.xbox 360.h) #elif defined _WIN64 # define compiled_shader(_NAME) make_a_string(_NAME.x64.h) #elif defined _WIN32 # define compiled_shader(_NAME) make_a_string(_NAME.win32.h) #endif
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 20 ] ] ]
30aa9f5d82a6224ea1dbfe1a9060cf13b70b7a31
d42ea2e76370d29f0e4057e97ea490ac4bd76937
/src/Type/Bomberman.cpp
2cb9876c6fe9b391f571e3f27b0276d443875b5e
[]
no_license
polycraft/Bomberman-like-reseau-serveur
ab71827c0f3e8f410474efb29d625ab354b171d2
6e03cc1705b45a502cb4e8025a283569348cd0a1
refs/heads/master
2021-01-01T19:24:43.389020
2011-06-09T07:37:44
2011-06-09T07:37:44
1,780,376
0
0
null
null
null
null
UTF-8
C++
false
false
2,993
cpp
#include "Bomberman.h" #include "../Engine/util/Timer.h" #include "Paquet.h" #include "../GameType/GameType.h" using namespace Engine; Bomberman::Bomberman(Socket *sock, GameType *gameType,map<EPropertyBomberman,Property*>& property):socket(sock),stop(false),gameType(gameType),connected(false) { this->property=property; socket->addObserverRecv(this); thread = sock->run(&stop); } Bomberman::Bomberman(Socket *sock,GameType *gameType,int id):socket(sock),stop(false),gameType(gameType) { this->property[PB_id]=new Property(id); thread = sock->run(&stop); socket->addObserverRecv(this); } Bomberman::~Bomberman() { //destruction des bonus set<Bonus*>::iterator it2; for(it2 = this->bonusList.begin() ; it2 != this->bonusList.end() ; it2++) { //delete (*it); } map<EPropertyBomberman,Property*>::iterator it; for ( it=property.begin() ; it != property.end(); it++ ) { delete (*it).second; } stop=true; //Threadable::join(thread); delete socket; } EType Bomberman::getType() { return T_Bomberman; } void Bomberman::updateTimer(unsigned int delay) { if(delay==this->getProperty<int>(PB_timeInvincible)) { this->setProperty<bool>(PB_invincible,false); Timer::getTimer()->removeListener(this,100); } else if(delay==100) { this->setVisible(!this->getVisible()); } else { this->setProperty<bool>(PB_canPutBomb,true); } } void Bomberman::setInvinsible(int time) { if(this->getProperty<bool>(PB_invincible)) { Timer::getTimer()->removeListenerOnce(this,this->getProperty<int>(PB_timeInvincible)); } Timer::getTimer()->addListenerOnce(this,time); this->setProperty<int>(PB_timeInvincible,time); this->setProperty<int>(PB_invincible,true); Timer::getTimer()->addListener(this,100); } void Bomberman::lostLife(int nb) { setProperty<int>(PB_life,getProperty<int>(PB_life)-nb); } void Bomberman::updateRecv(Socket *sock,Paquet& paquet) { gameType->updateRecvBomberman(this,sock,paquet); char type=(paquet.getData())[0]; switch(type) { case 'n': { PaquetName *paquetName=paquet.getData<PaquetName*>(); this->setName(string(paquetName->name)); } break; default: break; } } void Bomberman::sendData(Paquet &paquet) { socket->sendData(paquet); } bool Bomberman::isConnected() { return connected; } void Bomberman::setConnected(bool c) { connected=c; } string& Bomberman::getName() { return name; } void Bomberman::setName(string name) { this->name=name; } Socket* Bomberman::getSocket() { return socket; } void Bomberman::addBonus(Bonus *bonus) { this->bonusList.insert(bonus); } void Bomberman::remove(Bonus *bonus) { set<Bonus*>::iterator it; for(it = this->bonusList.begin() ; it != this->bonusList.end() ; it++) { if((*it) == bonus) { //suppression a voir si besoin } } }
[ [ [ 1, 149 ] ] ]
e73db3d121558cfe076916bbbf298f41377fecbe
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseBoxCollider.h
07fa9d497f979e1c7d1222dafba4e252aef844b6
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
2,996
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_BOX_COLLIDER_H__ #define __PU_BOX_COLLIDER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseCollider.h" namespace ParticleUniverse { /** The BoxCollider is a box shape that collides with the particles. The BoxCollider can only collide with particles that are created within the same ParticleTechnique as where the BoxCollider is registered. */ class _ParticleUniverseExport BoxCollider : public Collider { public: BoxCollider(void) : Collider(), mWidth(0.0f), mHeight(0.0f), mDepth(0.0f), mXmin(0.0f), mXmax(0.0f), mYmin(0.0f), mYmax(0.0f), mZmin(0.0f), mZmax(0.0f), mPredictedPosition(Ogre::Vector3::ZERO) { mAffectorType = "BoxCollider"; }; virtual ~BoxCollider(void){}; /** Returns the width of the box */ const Ogre::Real getWidth(void) const; /** Sets the width of the box */ void setWidth(const Ogre::Real width); /** Returns the height of the box */ const Ogre::Real getHeight(void) const; /** Sets the height of the box */ void setHeight(const Ogre::Real height); /** Returns the depth of the box */ const Ogre::Real getDepth(void) const; /** Sets the depth of the box */ void setDepth(const Ogre::Real depth); /** */ void calculateDirectionAfterCollision(Particle* particle); /** @copydoc ParticleAffector::_preProcessParticles */ virtual void _preProcessParticles(ParticleTechnique* particleTechnique, Ogre::Real timeElapsed); /** @copydoc ParticleAffector::_affect */ virtual void _affect(ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed); /** @copydoc ParticleAffector::copyAttributesTo */ virtual void copyAttributesTo (ParticleAffector* affector); protected: Ogre::Real mWidth; Ogre::Real mHeight; Ogre::Real mDepth; Ogre::Real mXmin; Ogre::Real mXmax; Ogre::Real mYmin; Ogre::Real mYmax; Ogre::Real mZmin; Ogre::Real mZmax; Ogre::AxisAlignedBox mBox; Ogre::Vector3 mPredictedPosition; /** */ void _calculateBounds (void); /** */ bool _isSmallestValue(Ogre::Real value, const Ogre::Vector3& particlePosition); }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 108 ] ] ]
c0cbcb14481d4686b56445f565d8461b4de39bb4
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/bignum.cpp
33938ad858a960ec278b0cfa51b427d68316abd2
[]
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,557
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; class StrArray { public: char **s; int tot; StrArray(int i){ s = (char **) malloc(sizeof(char *)*i); clear(); } void clear() { tot = 0; } void add(char *c) { s[tot++] = c; } void split(char *st, char c) { clear(); bool b = false; char *start = st; while((*st)!='\0') { if((*st)!=c) { if(!b) { start = st; b = true; } } else { (*st) = '\0'; if(b) { b = false; add(start); } } st++; } if(b) add(start); } int *toInt() { int *z = (int *) malloc(sizeof(int) * tot); for(int i=0;i!=tot;i++) { if(s[i][0]=='-') z[i] = -atoi(s[i]+1); else z[i] = atoi(s[i]); } return z; } long *toLong() { long *z = (long *) malloc(sizeof(long) * tot); for(int i=0;i!=tot;i++) { if(s[i][0]=='-') z[i] = -atol(s[i]+1); else z[i] = atol(s[i]); } return z; } }; bool isCharacter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } bool isVocal(char c) { return c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U'; }
[ [ [ 1, 74 ] ] ]
57b43e866b1ee69de5bbd49c39cb5352f1553daf
f7d5fcb47d370751163d253ac0d705d52bd3c5d5
/tags/trunk/Sources/source/hapticgraphclasses/GraphScene.h
b9c2625f15936d1a1241fe0a325d767eb48b6a62
[]
no_license
BackupTheBerlios/phantom-graphs-svn
b830eadf54c49ccecf2653e798e3a82af7e0e78d
6a585ecde8432394c732a72e4860e136d68cc4b4
refs/heads/master
2021-01-02T09:21:18.231965
2006-02-06T08:44:57
2006-02-06T08:44:57
40,820,960
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,696
h
//******************************************************************************* /// @file GraphScene.h /// @author Katharina Greiner, Matr.-Nr. 943471 /// @date Erstellt am 26.12.2005 /// @date Letzte Änderung 04.02.2006 //******************************************************************************* // Änderungen: // 30.12.05 - Konstruktor, Destruktor, renderSceneGraphics(), renderSceneHaptics() // hinzugefügt // - Doku zu den implementierten Methoden geschrieben. // 24.01.06 - Methode getGraphPlaneZ() hinzugefügt. // 26.01.06 - initScene() hat neue Parameter bekommen. // - GraphScene hat jetzt eine Camera zur Steuerung der Ansicht. // - Dafür Methode getView() hinzugefügt. // 28.01.06 - Membervariable m_rUnitInfo zur Einheitenkonvertierung hinzugefügt, // Konstruktor entsprechend angepasst. // 04.02.06 - Doku vervollständigt, Code aufgeräumt. #ifndef _GRAPHSCENE_H_ #define _GRAPHSCENE_H_ // STL includes #include <vector> using namespace std; // eigene includes #include "HapticObject.h" #include "Camera.h" #include "Node.h" #include "Grid.h" #include "Utilities.h" #include "HapticAction.h" #include "../businesslogic/IBusinessAdapter.h" //............................................................................... /// @author Katharina Greiner, Matr.-Nr. 943471 /// /// @brief Klasse, die alle haptischen Objekte der Scene verwaltet. /// /// Sie ist sowohl für die Erzeugung der Objekte verantwortlich, als auch /// dafür, dass sie sich zur richtigen Zeit rendern. //............................................................................... class GraphScene { protected: //....................................................................... /// @brief Liste aller haptischen Objekte der Scene. /// Alle Elemente der Szene werden auch von ihr freigegeben. //....................................................................... vector<HapticObject*> m_SceneElements; //....................................................................... /// @brief Camera-Objekt, von dem aus die Szene beobachtet wird. Wird von /// der GraphScene erzeugt und freigegeben. //....................................................................... Camera * m_pCamera; //....................................................................... /// @brief Referenz auf das Einheitenobjekt auf dessen Basis die Szene /// dargestellt werden soll. Wird NICHT von der GraphScene freigegeben! //....................................................................... UnitConversionInfo & m_rUnitInfo; //....................................................................... /// @brief Eventhandlerobjekt, dass für das Bewegen der Szene mit dem /// Phantom zuständig ist. Wird von der GraphScene erzeugt und freigegeben. //....................................................................... IHapticAction * m_pDragSceneHandler; //....................................................................... /// @brief Fordert alle Objekte auf, ihre haptische Beschaffenheit zu rendern. /// @param bHapticsEnabled Gibt an, ob die Haptik gerendert werden kann. //....................................................................... void renderSceneHaptics(bool bHapticsEnabled); //....................................................................... /// @brief Fordert alle Objekte auf, ihre graphische Beschaffenheit zu rendern. //....................................................................... void renderSceneGraphics(); //....................................................................... /// @brief Erzeugt aus einem Graphen, der durch IBusinessAdapter-Objekte /// beschrieben wird rekursiv die zugehörigen Darstellungsobjekte /// und fügt diese der Liste von Szenenelementen hinzu. /// @param businessObj Knoten, für den ein Darstellungsobjekt erzeugt /// werden soll. Auch für dessen Nachfolger wird /// createObjects aufgerufen. Die Knoten werden mit /// Kanten verbunden. /// @param pGrid Nötiger Parameter um die Darstellungsobjekte mit /// dem Grid zu verknüpfen. /// @return Das Darstellungsobjekt, das das businessObj repräsentiert. /// @todo Bisher kann mit dieser Methode nur ein Baum erzeugt werden, /// nicht jeder beliebige Graph. //....................................................................... Node * createObjects( IBusinessAdapter * businessObj, Grid * pGrid ); public: //....................................................................... /// @brief Konstruktor: Initialisiert das Objekt. /// @param unitInfo Referenz auf das Einheitenobjekt auf dessen Basis /// die Szene dargestellt werden soll. /// Wird NICHT von der GraphScene freigegeben! //....................................................................... GraphScene( UnitConversionInfo & unitInfo ); //....................................................................... /// @brief Destruktor: Gibt die Resourcen des Objektes frei. //....................................................................... virtual ~GraphScene(); //....................................................................... /// @brief Rendert die Haptik und Graphik der Szene. /// @param bHapticsEnabled Gibt an, ob die Haptik gerendert werden kann. //....................................................................... void renderScene( bool bHapticsEnabled ); //....................................................................... /// @brief Initialisiert die graphische/haptische Szene. /// @param viewportWidth Fensterbreite. /// @param viewportHeight Fensterhöhe. /// @param pHd Pointer auf das HapticDevice, das sich dem Sichtvolumen /// der Kamera anpassen soll. /// @param gridColumns Anzahl der Spalten, die das Grid haben soll, auf dem /// der Graph dargestellt wird. /// @param gridRows Anzahl der Zeilen, die das Grid haben soll, auf dem /// der Graph dargestellt wird. /// @param rootNode Wurzelknoten eines Graphen, der durch IBusinessAdapter-Objekte /// beschrieben wird. //....................................................................... virtual void initScene( int viewportWidth, int viewportHeight, HapticDevice * pHd, int gridColumns, int gridRows, IBusinessAdapter * rootNode ); //....................................................................... /// @brief Fügt der Szene ein neues Objekt hinzu. /// @param obj Pointer auf das Objekt, das hinzugefügt werden soll. //....................................................................... void addObject( HapticObject * obj ); //....................................................................... /// @brief Gibt die z-Koordinate der Ebene parallel zur x-y-Ebene auf /// der der Graph dargestellt wird zurück. /// @return z-Koordinate der Ebene parallel zur x-y-Ebene auf der der /// Graph dargestellt wird. //....................................................................... static float getGraphPlaneZ(); //....................................................................... /// @brief Gibt das Camera-Objekt zurück, mit dem die Szene betrachtet wird. /// @return Zeiger auf das Camera-Objekt, mit dem die Szene betrachtet wird. //....................................................................... Camera * getView(); }; #endif // _GRAPHSCENE_H_
[ "frosch@a1b688d3-ce07-0410-8a3f-c797401f78de" ]
[ [ [ 1, 161 ] ] ]
7ab77074b2b6d380f5ece18766a1ab198821d68a
6520b2b1c45e5a9e5996a9205142de6e2e2cb7ea
/AHL/wolfilair/src/lib/graphic/GL2D.cpp
c7e8daa7539c5abc59f4bc039d166e2eaef9840a
[]
no_license
xpierro/ahl
6207bc2c309a7f2e4bf659e86fcbf4d889250d82
8efd98a6ecc32d794a1e957b0b91eb017546fdf1
refs/heads/master
2020-06-04T00:59:13.590942
2010-10-21T04:09:48
2010-10-21T04:09:48
41,411,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,969
cpp
/* * GL.h * * Created on: 19 oct. 2010 * Author: Slynk */ #include <psgl/psgl.h> #include <psgl/psglu.h> #include "GL2D.h" namespace PS3{ GL2D::GL2D() { } GL2D::~GL2D() { } float GL2D::leftBound, GL2D::rightBound, GL2D::bottomBound, GL2D::topBound; void GL2D::preDraw(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2Df( leftBound, rightBound, bottomBound, topBound ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void GL2D::drawSprite(Sprite &sprite) { glBindTexture(GL_TEXTURE_2D, sprite.getImage()->getTextureId()); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, sprite.getCoord()); glTexCoordPointer(2, GL_FLOAT, 0, allImage); glDrawArrays(GL_QUADS, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } void GL2D::scrollX(float amount) { leftBound += amount; rightBound += amount; } void GL2D::scrollY(float amount) { bottomBound += amount; topBound += amount; } void GL2D::setBoundaries(void) { leftBound = 0; rightBound = width; bottomBound = 0; topBound = height; } void GL2D::setBoundaries(float l, float r, float b, float t) { leftBound = l; rightBound = r; bottomBound = b; topBound = t; } float GL2D::getLeftBound(void) { return leftBound; } float GL2D::getRightBound(void) { return rightBound; } float GL2D::getBottomBound(void) { return bottomBound; } float GL2D::getTopBound(void) { return topBound; } }
[ [ [ 1, 77 ] ] ]
99636aa6f797576e5f094b428543addd7160107b
428b5f476e013d4699416629ce5fa155e724849f
/webcontent_dummy.h
d5e7fc69e6d36766b1155f6747eb4853827bca23
[]
no_license
vitorboschi/kpws
afab7f2eb97f25c0eb7bcab2404d308edc0e3297
e51dd08e5f8e00149f407c259030855b82ae5f38
refs/heads/master
2021-01-16T19:35:50.269368
2010-02-02T23:59:33
2010-02-02T23:59:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,222
h
/* KDE Personal Web Server - Allow you to easily share files over http Copyright (C) 2010 by Vitor Boschi da Silva ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef WEBCONTENT_DUMMY_H #define WEBCONTENT_DUMMY_H #include <QString> #include <QByteArray> #include "webcontent.h" class WebContent_Dummy : public WebContent { public: WebContent_Dummy(QString identifier); int getChunk(QString url, QByteArray* buffer, qint64 start=0, int len=-1); QString getMime(QString url); qint64 getSize(QString url); bool validUrl(QString url); private: QByteArray content; }; #endif
[ [ [ 1, 41 ] ] ]
d86bfc569bfb029bbc73ce6a28695a56823393ab
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ServerModule/KernelModule/SocketEngine.cpp
30a5c3518b139d0084c5b4c0bdc6283dd4ab9660
[]
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
44,618
cpp
#include "StdAfx.h" #include "EventService.h" #include "SocketEngine.h" ////////////////////////////////////////////////////////////////////////// //宏定义 #define TIME_BREAK_READY 45000L //中断时间 #define TIME_BREAK_CONNECT 45000L //中断时间 #define TIME_DETECT_SOCKET 20000L //监测时间 const char* POLICYFILEREQUESET = TEXT("<policy-file-request/>"); const char* POLICYFILERESPONSE = TEXT("<?xml version=\"1.0\"?><cross-domain-policy> <allow-access-from domain=\"*\" to-ports=\"*\" /> </cross-domain-policy> "); static bool bInitHookSpecialCMD = false; static BYTE cbHookSpecialCMD_PolicyfileRequset[32]; static BYTE cbHookSpecialCMD_PolicyfileResponse[256]; static WORD wHookSpecialCMD_PolicyfileRequset_Size; static WORD wHookSpecialCMD_PolicyfileResponse_Size; ////////////////////////////////////////////////////////////////////////// //动作定义 #define QUEUE_SEND_REQUEST 1 //发送标识 #define QUEUE_SAFE_CLOSE 2 //安全关闭 #define QUEUE_ALLOW_BATCH 3 //允许群发 #define QUEUE_DETECT_SOCKET 4 //检测连接 //发送请求结构 struct tagSendDataRequest { WORD wMainCmdID; //主命令码 WORD wSubCmdID; //子命令码 WORD wIndex; //连接索引 WORD wRountID; //循环索引 WORD wDataSize; //数据大小 BYTE cbSendBuf[SOCKET_PACKAGE]; //发送缓冲 }; //设置群发 struct tagAllowBatchSend { WORD wIndex; //连接索引 WORD wRountID; //循环索引 BYTE cbAllow; //允许标志 }; //安全关闭 struct tagSafeCloseSocket { WORD wIndex; //连接索引 WORD wRountID; //循环索引 }; ////////////////////////////////////////////////////////////////////////// //发送字节映射表 const BYTE g_SendByteMap[256]= { 0x70,0x2F,0x40,0x5F,0x44,0x8E,0x6E,0x45,0x7E,0xAB,0x2C,0x1F,0xB4,0xAC,0x9D,0x91, 0x0D,0x36,0x9B,0x0B,0xD4,0xC4,0x39,0x74,0xBF,0x23,0x16,0x14,0x06,0xEB,0x04,0x3E, 0x12,0x5C,0x8B,0xBC,0x61,0x63,0xF6,0xA5,0xE1,0x65,0xD8,0xF5,0x5A,0x07,0xF0,0x13, 0xF2,0x20,0x6B,0x4A,0x24,0x59,0x89,0x64,0xD7,0x42,0x6A,0x5E,0x3D,0x0A,0x77,0xE0, 0x80,0x27,0xB8,0xC5,0x8C,0x0E,0xFA,0x8A,0xD5,0x29,0x56,0x57,0x6C,0x53,0x67,0x41, 0xE8,0x00,0x1A,0xCE,0x86,0x83,0xB0,0x22,0x28,0x4D,0x3F,0x26,0x46,0x4F,0x6F,0x2B, 0x72,0x3A,0xF1,0x8D,0x97,0x95,0x49,0x84,0xE5,0xE3,0x79,0x8F,0x51,0x10,0xA8,0x82, 0xC6,0xDD,0xFF,0xFC,0xE4,0xCF,0xB3,0x09,0x5D,0xEA,0x9C,0x34,0xF9,0x17,0x9F,0xDA, 0x87,0xF8,0x15,0x05,0x3C,0xD3,0xA4,0x85,0x2E,0xFB,0xEE,0x47,0x3B,0xEF,0x37,0x7F, 0x93,0xAF,0x69,0x0C,0x71,0x31,0xDE,0x21,0x75,0xA0,0xAA,0xBA,0x7C,0x38,0x02,0xB7, 0x81,0x01,0xFD,0xE7,0x1D,0xCC,0xCD,0xBD,0x1B,0x7A,0x2A,0xAD,0x66,0xBE,0x55,0x33, 0x03,0xDB,0x88,0xB2,0x1E,0x4E,0xB9,0xE6,0xC2,0xF7,0xCB,0x7D,0xC9,0x62,0xC3,0xA6, 0xDC,0xA7,0x50,0xB5,0x4B,0x94,0xC0,0x92,0x4C,0x11,0x5B,0x78,0xD9,0xB1,0xED,0x19, 0xE9,0xA1,0x1C,0xB6,0x32,0x99,0xA3,0x76,0x9E,0x7B,0x6D,0x9A,0x30,0xD6,0xA9,0x25, 0xC7,0xAE,0x96,0x35,0xD0,0xBB,0xD2,0xC8,0xA2,0x08,0xF3,0xD1,0x73,0xF4,0x48,0x2D, 0x90,0xCA,0xE2,0x58,0xC1,0x18,0x52,0xFE,0xDF,0x68,0x98,0x54,0xEC,0x60,0x43,0x0F }; //接收字节映射表 const BYTE g_RecvByteMap[256]= { 0x51,0xA1,0x9E,0xB0,0x1E,0x83,0x1C,0x2D,0xE9,0x77,0x3D,0x13,0x93,0x10,0x45,0xFF, 0x6D,0xC9,0x20,0x2F,0x1B,0x82,0x1A,0x7D,0xF5,0xCF,0x52,0xA8,0xD2,0xA4,0xB4,0x0B, 0x31,0x97,0x57,0x19,0x34,0xDF,0x5B,0x41,0x58,0x49,0xAA,0x5F,0x0A,0xEF,0x88,0x01, 0xDC,0x95,0xD4,0xAF,0x7B,0xE3,0x11,0x8E,0x9D,0x16,0x61,0x8C,0x84,0x3C,0x1F,0x5A, 0x02,0x4F,0x39,0xFE,0x04,0x07,0x5C,0x8B,0xEE,0x66,0x33,0xC4,0xC8,0x59,0xB5,0x5D, 0xC2,0x6C,0xF6,0x4D,0xFB,0xAE,0x4A,0x4B,0xF3,0x35,0x2C,0xCA,0x21,0x78,0x3B,0x03, 0xFD,0x24,0xBD,0x25,0x37,0x29,0xAC,0x4E,0xF9,0x92,0x3A,0x32,0x4C,0xDA,0x06,0x5E, 0x00,0x94,0x60,0xEC,0x17,0x98,0xD7,0x3E,0xCB,0x6A,0xA9,0xD9,0x9C,0xBB,0x08,0x8F, 0x40,0xA0,0x6F,0x55,0x67,0x87,0x54,0x80,0xB2,0x36,0x47,0x22,0x44,0x63,0x05,0x6B, 0xF0,0x0F,0xC7,0x90,0xC5,0x65,0xE2,0x64,0xFA,0xD5,0xDB,0x12,0x7A,0x0E,0xD8,0x7E, 0x99,0xD1,0xE8,0xD6,0x86,0x27,0xBF,0xC1,0x6E,0xDE,0x9A,0x09,0x0D,0xAB,0xE1,0x91, 0x56,0xCD,0xB3,0x76,0x0C,0xC3,0xD3,0x9F,0x42,0xB6,0x9B,0xE5,0x23,0xA7,0xAD,0x18, 0xC6,0xF4,0xB8,0xBE,0x15,0x43,0x70,0xE0,0xE7,0xBC,0xF1,0xBA,0xA5,0xA6,0x53,0x75, 0xE4,0xEB,0xE6,0x85,0x14,0x48,0xDD,0x38,0x2A,0xCC,0x7F,0xB1,0xC0,0x71,0x96,0xF8, 0x3F,0x28,0xF2,0x69,0x74,0x68,0xB7,0xA3,0x50,0xD0,0x79,0x1D,0xFC,0xCE,0x8A,0x8D, 0x2E,0x62,0x30,0xEA,0xED,0x2B,0x26,0xB9,0x81,0x7C,0x46,0x89,0x73,0xA2,0xF7,0x72 }; //数据加密密钥 const static DWORD g_dwPacketKey=0xA55AA55A; ////////////////////////////////////////////////////////////////////////// //构造函数 COverLapped::COverLapped(enOperationType OperationType) : m_OperationType(OperationType) { memset(&m_WSABuffer,0,sizeof(m_WSABuffer)); memset(&m_OverLapped,0,sizeof(m_OverLapped)); } //析构函数 COverLapped::~COverLapped() { } ////////////////////////////////////////////////////////////////////////// //构造函数 COverLappedSend::COverLappedSend() : COverLapped(OperationType_Send) { m_WSABuffer.len=0; m_WSABuffer.buf=(char *)m_cbBuffer; } //析构函数 COverLappedSend::~COverLappedSend() { } ////////////////////////////////////////////////////////////////////////// //构造函数 CServerSocketItem::CServerSocketItem(WORD wIndex, IServerSocketItemSink * pIServerSocketItemSink) : m_wIndex(wIndex), m_pIServerSocketItemSink(pIServerSocketItemSink) { m_wRountID=0; m_wRecvSize=0; m_cbSendRound=0; m_cbRecvRound=0; m_bNotify=true; m_bRecvIng=false; m_bCloseIng=false; m_bAllowBatch=false; m_dwSendXorKey=0; m_dwRecvXorKey=0; m_dwClientAddr=0; m_dwConnectTime=0; m_dwSendTickCount=0; m_dwRecvTickCount=0; m_dwSendPacketCount=0; m_dwRecvPacketCount=0; m_hSocket=INVALID_SOCKET; if(bInitHookSpecialCMD == false) { memset(cbHookSpecialCMD_PolicyfileRequset, 0, sizeof(cbHookSpecialCMD_PolicyfileRequset)); memcpy(cbHookSpecialCMD_PolicyfileRequset, POLICYFILEREQUESET, _tcslen(POLICYFILEREQUESET)); wHookSpecialCMD_PolicyfileRequset_Size = _tcslen(POLICYFILEREQUESET) + 1; memset(cbHookSpecialCMD_PolicyfileResponse, 0, sizeof(cbHookSpecialCMD_PolicyfileResponse)); memcpy(cbHookSpecialCMD_PolicyfileResponse, POLICYFILERESPONSE, _tcslen(POLICYFILERESPONSE)); wHookSpecialCMD_PolicyfileResponse_Size = _tcslen(POLICYFILERESPONSE) + 1; bInitHookSpecialCMD = true; } } //析够函数 CServerSocketItem::~CServerSocketItem(void) { //删除空闲重叠 IO INT_PTR iCount=m_OverLappedSendFree.GetCount(); for (INT_PTR i=0;i<iCount;i++) delete m_OverLappedSendFree[i]; m_OverLappedSendFree.RemoveAll(); //删除活动重叠 IO iCount=m_OverLappedSendActive.GetCount(); for (INT_PTR i=0;i<iCount;i++) delete m_OverLappedSendActive[i]; m_OverLappedSendActive.RemoveAll(); return; } //随机映射 WORD CServerSocketItem::SeedRandMap(WORD wSeed) { DWORD dwHold=wSeed; return (WORD)((dwHold=dwHold*241103L+2533101L)>>16); } //映射发送数据 BYTE CServerSocketItem::MapSendByte(BYTE const cbData) { //BYTE cbMap=g_SendByteMap[(BYTE)(cbData+m_cbSendRound)]; //m_cbSendRound+=3; BYTE cbMap=g_SendByteMap[(BYTE)(cbData)]; return cbMap; } //映射接收数据 BYTE CServerSocketItem::MapRecvByte(BYTE const cbData) { //BYTE cbMap=g_RecvByteMap[cbData]-m_cbRecvRound; //m_cbRecvRound+=3; BYTE cbMap=g_RecvByteMap[cbData]; return cbMap; } //获取发送结构 COverLappedSend * CServerSocketItem::GetSendOverLapped() { //寻找空闲结构 COverLappedSend * pOverLappedSend=NULL; INT_PTR nFreeCount=m_OverLappedSendFree.GetCount(); if (nFreeCount>0) { pOverLappedSend=m_OverLappedSendFree[nFreeCount-1]; GT_ASSERT(pOverLappedSend!=NULL); m_OverLappedSendFree.RemoveAt(nFreeCount-1); m_OverLappedSendActive.Add(pOverLappedSend); return pOverLappedSend; } //新建发送结构 _BEGIN_TRY { pOverLappedSend=new COverLappedSend; GT_ASSERT(pOverLappedSend!=NULL); m_OverLappedSendActive.Add(pOverLappedSend); return pOverLappedSend; } CATCH_COMMON_EXCEPTION(;)CATCH_UNKNOWN_EXCEPTION(;)_END_CATCH return NULL; } bool CServerSocketItem::HookSpecialCMD(BYTE* pcbDataBuffer, WORD wDataSize) { if(wDataSize == wHookSpecialCMD_PolicyfileRequset_Size) { if(_tcsicmp((char*)pcbDataBuffer, POLICYFILEREQUESET) == 0) { return SendRawData((void*)cbHookSpecialCMD_PolicyfileResponse, wHookSpecialCMD_PolicyfileResponse_Size, GetRountID()); } } return false; } //绑定对象 DWORD CServerSocketItem::Attach(SOCKET hSocket, DWORD dwClientAddr) { //效验数据 GT_ASSERT(dwClientAddr!=0); GT_ASSERT(m_bRecvIng==false); GT_ASSERT(IsValidSocket()==false); GT_ASSERT(hSocket!=INVALID_SOCKET); //设置变量 m_bNotify=false; m_bRecvIng=false; m_bCloseIng=false; m_hSocket=hSocket; m_dwClientAddr=dwClientAddr; m_dwRecvTickCount=GetTickCount(); m_dwConnectTime=(DWORD)time(NULL); //发送通知 m_pIServerSocketItemSink->OnSocketAcceptEvent(this); return GetIdentifierID(); } //发送函数 bool CServerSocketItem::SendData(WORD wMainCmdID, WORD wSubCmdID, WORD wRountID) { //效验状态 if (m_bCloseIng==true) return false; if (m_wRountID!=wRountID) return false; if (m_dwRecvPacketCount==0) return false; if (IsValidSocket()==false) return false; //寻找发送结构 COverLappedSend * pOverLappedSend=GetSendOverLapped(); GT_ASSERT(pOverLappedSend!=NULL); if (pOverLappedSend==NULL) return false; //构造数据 CMD_Head * pHead=(CMD_Head *)pOverLappedSend->m_cbBuffer; pHead->CommandInfo.wMainCmdID=wMainCmdID; pHead->CommandInfo.wSubCmdID=wSubCmdID; WORD wSendSize=EncryptBuffer(pOverLappedSend->m_cbBuffer,sizeof(CMD_Head),sizeof(pOverLappedSend->m_cbBuffer)); pOverLappedSend->m_WSABuffer.len=wSendSize; //发送数据 if (m_OverLappedSendActive.GetCount()==1) { DWORD dwThancferred=0; int iRetCode=WSASend(m_hSocket,&pOverLappedSend->m_WSABuffer,1,&dwThancferred,0,&pOverLappedSend->m_OverLapped,NULL); if ((iRetCode==SOCKET_ERROR)&&(WSAGetLastError()!=WSA_IO_PENDING)) { OnSendCompleted(pOverLappedSend,0L); return false; } } return true; } //发送函数 bool CServerSocketItem::SendData(void * pData, WORD wDataSize, WORD wMainCmdID, WORD wSubCmdID, WORD wRountID) { //效验参数 GT_ASSERT(wDataSize<=SOCKET_PACKAGE); //效验状态 if (m_bCloseIng==true) return false; if (m_wRountID!=wRountID) return false; if (m_dwRecvPacketCount==0) return false; if (IsValidSocket()==false) return false; if (wDataSize>SOCKET_PACKAGE) return false; //寻找发送结构 COverLappedSend * pOverLappedSend=GetSendOverLapped(); GT_ASSERT(pOverLappedSend!=NULL); if (pOverLappedSend==NULL) return false; //构造数据 CMD_Head * pHead=(CMD_Head *)pOverLappedSend->m_cbBuffer; pHead->CommandInfo.wMainCmdID=wMainCmdID; pHead->CommandInfo.wSubCmdID=wSubCmdID; if (wDataSize>0) { GT_ASSERT(pData!=NULL); memcpy(pHead+1,pData,wDataSize); } WORD wSendSize=EncryptBuffer(pOverLappedSend->m_cbBuffer,sizeof(CMD_Head)+wDataSize,sizeof(pOverLappedSend->m_cbBuffer)); pOverLappedSend->m_WSABuffer.len=wSendSize; //发送数据 if (m_OverLappedSendActive.GetCount()==1) { DWORD dwThancferred=0; int iRetCode=WSASend(m_hSocket,&pOverLappedSend->m_WSABuffer,1,&dwThancferred,0,&pOverLappedSend->m_OverLapped,NULL); if ((iRetCode==SOCKET_ERROR)&&(WSAGetLastError()!=WSA_IO_PENDING)) { OnSendCompleted(pOverLappedSend,0L); return false; } } return true; } //发送函数 bool CServerSocketItem::SendRawData(void * pData, WORD wDataSize, WORD wRountID) { //效验参数 GT_ASSERT(wDataSize<=SOCKET_PACKAGE); //效验状态 if (m_bCloseIng==true) return false; if (m_wRountID!=wRountID) return false; if (IsValidSocket()==false) return false; if (wDataSize>SOCKET_PACKAGE) return false; //寻找发送结构 COverLappedSend * pOverLappedSend=GetSendOverLapped(); GT_ASSERT(pOverLappedSend!=NULL); if (pOverLappedSend==NULL) return false; //构造数据 memcpy(pOverLappedSend->m_cbBuffer, pData, wDataSize); pOverLappedSend->m_WSABuffer.len=wDataSize; //发送数据 if (m_OverLappedSendActive.GetCount()==1) { DWORD dwThancferred=0; int iRetCode=WSASend(m_hSocket,&pOverLappedSend->m_WSABuffer,1,&dwThancferred,0,&pOverLappedSend->m_OverLapped,NULL); if ((iRetCode==SOCKET_ERROR)&&(WSAGetLastError()!=WSA_IO_PENDING)) { OnSendCompleted(pOverLappedSend,0L); return false; } } return true; } //投递接收 bool CServerSocketItem::RecvData() { //效验变量 GT_ASSERT(m_bRecvIng==false); GT_ASSERT(m_hSocket!=INVALID_SOCKET); //判断关闭 if (m_bCloseIng==true) { if (m_OverLappedSendActive.GetCount()==0) CloseSocket(m_wRountID); return false; } //接收数据 m_bRecvIng=true; DWORD dwThancferred=0,dwFlags=0; int iRetCode=WSARecv(m_hSocket,&m_OverLappedRecv.m_WSABuffer,1,&dwThancferred,&dwFlags,&m_OverLappedRecv.m_OverLapped,NULL); if ((iRetCode==SOCKET_ERROR)&&(WSAGetLastError()!=WSA_IO_PENDING)) { m_bRecvIng=false; CloseSocket(m_wRountID); return false; } return true; } //关闭连接 bool CServerSocketItem::CloseSocket(WORD wRountID) { //状态判断 if (m_wRountID!=wRountID) return false; //关闭连接 if (m_hSocket!=INVALID_SOCKET) { closesocket(m_hSocket); m_hSocket=INVALID_SOCKET; } //判断关闭 if ((m_bRecvIng==false)&&(m_OverLappedSendActive.GetCount()==0)) OnCloseCompleted(); return true; } //设置关闭 bool CServerSocketItem::ShutDownSocket(WORD wRountID) { return true; //状态判断 if (m_wRountID!=wRountID) return false; if (m_hSocket==INVALID_SOCKET) return false; //设置变量 if (m_bCloseIng==false) { m_bCloseIng=true; if (m_OverLappedSendActive.GetCount()==0) CloseSocket(wRountID); } return true; } //允许群发 bool CServerSocketItem::AllowBatchSend(WORD wRountID, bool bAllowBatch) { //状态判断 if (m_wRountID!=wRountID) return false; if (m_hSocket==INVALID_SOCKET) return false; //设置变量 m_bAllowBatch=bAllowBatch; return true; } //重置变量 void CServerSocketItem::ResetSocketData() { //效验状态 GT_ASSERT(m_hSocket==INVALID_SOCKET); //重置数据 m_wRountID++; m_wRecvSize=0; m_cbSendRound=0; m_cbRecvRound=0; m_dwSendXorKey=0; m_dwRecvXorKey=0; m_dwClientAddr=0; m_dwConnectTime=0; m_dwSendTickCount=0; m_dwRecvTickCount=0; m_dwSendPacketCount=0; m_dwRecvPacketCount=0; //状态变量 m_bNotify=true; m_bRecvIng=false; m_bCloseIng=false; m_bAllowBatch=false; m_OverLappedSendFree.Append(m_OverLappedSendActive); m_OverLappedSendActive.RemoveAll(); return; } //发送完成函数 bool CServerSocketItem::OnSendCompleted(COverLappedSend * pOverLappedSend, DWORD dwThancferred) { //效验变量 GT_ASSERT(pOverLappedSend!=NULL); GT_ASSERT(m_OverLappedSendActive.GetCount()>0); GT_ASSERT(pOverLappedSend==m_OverLappedSendActive[0]); //释放发送结构 m_OverLappedSendActive.RemoveAt(0); m_OverLappedSendFree.Add(pOverLappedSend); //设置变量 if (dwThancferred!=0) m_dwSendTickCount=GetTickCount(); //判断关闭 if (m_hSocket==INVALID_SOCKET) { m_OverLappedSendFree.Append(m_OverLappedSendActive); m_OverLappedSendActive.RemoveAll(); CloseSocket(m_wRountID); return true; } //继续发送数据 if (m_OverLappedSendActive.GetCount()>0) { DWORD dwThancferred=0; pOverLappedSend=m_OverLappedSendActive[0]; GT_ASSERT(pOverLappedSend!=NULL); int iRetCode=WSASend(m_hSocket,&pOverLappedSend->m_WSABuffer,1,&dwThancferred,0,&pOverLappedSend->m_OverLapped,NULL); if ((iRetCode==SOCKET_ERROR)&&(WSAGetLastError()!=WSA_IO_PENDING)) { m_OverLappedSendFree.Append(m_OverLappedSendActive); m_OverLappedSendActive.RemoveAll(); CloseSocket(m_wRountID); return false; } return true; } //判断关闭 if (m_bCloseIng==true) CloseSocket(m_wRountID); return true; } //接收完成函数 bool CServerSocketItem::OnRecvCompleted(COverLappedRecv * pOverLappedRecv, DWORD dwThancferred) { //效验数据 GT_ASSERT(m_bRecvIng==true); //设置变量 m_bRecvIng=false; m_dwRecvTickCount=GetTickCount(); //判断关闭 if (m_hSocket==INVALID_SOCKET) { CloseSocket(m_wRountID); return true; } //接收数据 int iRetCode=recv(m_hSocket,(char *)m_cbRecvBuf+m_wRecvSize,sizeof(m_cbRecvBuf)-m_wRecvSize,0); if (iRetCode<=0) { CloseSocket(m_wRountID); return true; } //客户端特殊命令处理 if(HookSpecialCMD(m_cbRecvBuf+m_wRecvSize, iRetCode)) { return true; } //接收完成 m_wRecvSize+=iRetCode; BYTE cbBuffer[SOCKET_BUFFER]; CMD_Head * pHead=(CMD_Head *)m_cbRecvBuf; //处理数据 _BEGIN_TRY { while (m_wRecvSize>=sizeof(CMD_Head)) { //效验数据 WORD wPacketSize=pHead->CmdInfo.wDataSize; if (wPacketSize>SOCKET_BUFFER) throw TEXT("数据包超长"); if (wPacketSize<sizeof(CMD_Head)) throw TEXT("数据包非法"); if (pHead->CmdInfo.cbMessageVer!=SOCKET_VER) throw TEXT("数据包版本错误"); if (m_wRecvSize<wPacketSize) break; //提取数据 CopyMemory(cbBuffer,m_cbRecvBuf,wPacketSize); WORD wRealySize=CrevasseBuffer(cbBuffer,wPacketSize); GT_ASSERT(wRealySize>=sizeof(CMD_Head)); m_dwRecvPacketCount++; //解释数据 WORD wDataSize=wRealySize-sizeof(CMD_Head); void * pDataBuffer=cbBuffer+sizeof(CMD_Head); CMD_Command Command=((CMD_Head *)cbBuffer)->CommandInfo; //内核命令 if (Command.wMainCmdID==MDM_KN_COMMAND) { switch (Command.wSubCmdID) { case SUB_KN_DETECT_SOCKET: //网络检测 { break; } default: throw TEXT("非法命令码"); } } else { //消息处理 m_pIServerSocketItemSink->OnSocketReadEvent(Command,pDataBuffer,wDataSize,this); } //删除缓存数据 m_wRecvSize-=wPacketSize; MoveMemory(m_cbRecvBuf,m_cbRecvBuf+wPacketSize,m_wRecvSize); } } CATCH_COMMON_EXCEPTION(CloseSocket(m_wRountID);return false;) CATCH_UNKNOWN_EXCEPTION(CloseSocket(m_wRountID);return false;) _END_CATCH return RecvData(); } //关闭完成通知 bool CServerSocketItem::OnCloseCompleted() { //效验状态 GT_ASSERT(m_hSocket==INVALID_SOCKET); GT_ASSERT(m_OverLappedSendActive.GetCount()==0); //关闭事件 GT_ASSERT(m_bNotify==false); if (m_bNotify==false) { m_bNotify=true; m_pIServerSocketItemSink->OnSocketCloseEvent(this); } //状态变量 ResetSocketData(); return true; } //加密数据 WORD CServerSocketItem::EncryptBuffer(BYTE pcbDataBuffer[], WORD wDataSize, WORD wBufferSize) { WORD i = 0; //效验参数 GT_ASSERT(wDataSize>=sizeof(CMD_Head)); GT_ASSERT(wDataSize<=(sizeof(CMD_Head)+SOCKET_PACKAGE)); GT_ASSERT(wBufferSize>=(wDataSize+2*sizeof(DWORD))); //调整长度 WORD wEncryptSize=wDataSize-sizeof(CMD_Info),wSnapCount=0; if ((wEncryptSize%sizeof(DWORD))!=0) { wSnapCount=sizeof(DWORD)-wEncryptSize%sizeof(DWORD); memset(pcbDataBuffer+sizeof(CMD_Info)+wEncryptSize,0,wSnapCount); } //效验码与字节映射 BYTE cbCheckCode=0; for (i=sizeof(CMD_Info);i<wDataSize;i++) { cbCheckCode+=pcbDataBuffer[i]; pcbDataBuffer[i]=MapSendByte(pcbDataBuffer[i]); } //填写信息头 CMD_Head * pHead=(CMD_Head *)pcbDataBuffer; pHead->CmdInfo.cbCheckCode=~cbCheckCode+1; pHead->CmdInfo.wDataSize=wDataSize; pHead->CmdInfo.cbMessageVer=SOCKET_VER; //设置变量 m_dwSendPacketCount++; //m_dwSendXorKey=dwXorKey; return wDataSize; } //解密数据 WORD CServerSocketItem::CrevasseBuffer(BYTE pcbDataBuffer[], WORD wDataSize) { WORD i = 0; //效验参数 GT_ASSERT(wDataSize>=sizeof(CMD_Head)); GT_ASSERT(((CMD_Head *)pcbDataBuffer)->CmdInfo.wDataSize==wDataSize); //调整长度 WORD wSnapCount=0; if ((wDataSize%sizeof(DWORD))!=0) { wSnapCount=sizeof(DWORD)-wDataSize%sizeof(DWORD); memset(pcbDataBuffer+wDataSize,0,wSnapCount); } //效验码与字节映射 CMD_Head * pHead=(CMD_Head *)pcbDataBuffer; BYTE cbCheckCode=pHead->CmdInfo.cbCheckCode;; for (i=sizeof(CMD_Info);i<wDataSize;i++) { pcbDataBuffer[i]=MapRecvByte(pcbDataBuffer[i]); cbCheckCode+=pcbDataBuffer[i]; } if (cbCheckCode!=0) throw TEXT("数据包效验码错误"); return wDataSize; } ////////////////////////////////////////////////////////////////////////// //构造函数 CServerSocketRSThread::CServerSocketRSThread(void) { m_hCompletionPort=NULL; } //析构函数 CServerSocketRSThread::~CServerSocketRSThread(void) { } //配置函数 bool CServerSocketRSThread::InitThread(HANDLE hCompletionPort) { GT_ASSERT(hCompletionPort!=NULL); m_hCompletionPort=hCompletionPort; return true; } //Run函数 bool CServerSocketRSThread::RepetitionRun() { //效验参数 GT_ASSERT(m_hCompletionPort!=NULL); //变量定义 DWORD dwThancferred=0; OVERLAPPED * pOverLapped=NULL; COverLapped * pSocketLapped=NULL; CServerSocketItem * pServerSocketItem=NULL; //等待完成端口 BOOL bSuccess=GetQueuedCompletionStatus(m_hCompletionPort,&dwThancferred,(PULONG_PTR)&pServerSocketItem,&pOverLapped,INFINITE); if ((bSuccess==FALSE)&&(GetLastError()!=ERROR_NETNAME_DELETED)) return false; if ((pServerSocketItem==NULL)&&(pOverLapped==NULL)) return false; //处理操作 GT_ASSERT(pOverLapped!=NULL); GT_ASSERT(pServerSocketItem!=NULL); pSocketLapped=CONTAINING_RECORD(pOverLapped,COverLapped,m_OverLapped); switch (pSocketLapped->GetOperationType()) { case OperationType_Recv: //SOCKET 数据读取 { COverLappedRecv * pOverLappedRecv=(COverLappedRecv *)pSocketLapped; CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->OnRecvCompleted(pOverLappedRecv,dwThancferred); break; } case OperationType_Send: //SOCKET 数据发送 { COverLappedSend * pOverLappedSend=(COverLappedSend *)pSocketLapped; CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->OnSendCompleted(pOverLappedSend,dwThancferred); break; } } return true; } ////////////////////////////////////////////////////////////////////////// //构造函数 CSocketAcceptThread::CSocketAcceptThread(void) { m_hCompletionPort=NULL; m_pTCPSocketManager=NULL; m_hListenSocket=INVALID_SOCKET; } //析构函数 CSocketAcceptThread::~CSocketAcceptThread(void) { } //配置函数 bool CSocketAcceptThread::InitThread(HANDLE hCompletionPort, SOCKET hListenSocket, CTCPSocketEngine * pTCPSocketManager) { GT_ASSERT(hCompletionPort!=NULL); GT_ASSERT(pTCPSocketManager!=NULL); GT_ASSERT(hListenSocket!=INVALID_SOCKET); m_hListenSocket=hListenSocket; m_hCompletionPort=hCompletionPort; m_pTCPSocketManager=pTCPSocketManager; return true; } //Run函数 bool CSocketAcceptThread::RepetitionRun() { //效验参数 GT_ASSERT(m_hCompletionPort!=NULL); GT_ASSERT(m_pTCPSocketManager!=NULL); //设置变量 SOCKADDR_IN SocketAddr; CServerSocketItem * pServerSocketItem=NULL; SOCKET hConnectSocket=INVALID_SOCKET; int nBufferSize=sizeof(SocketAddr); _BEGIN_TRY { //监听连接 hConnectSocket=WSAAccept(m_hListenSocket,(SOCKADDR *)&SocketAddr,&nBufferSize,NULL,NULL); if (hConnectSocket==INVALID_SOCKET) return false; //获取连接 pServerSocketItem=m_pTCPSocketManager->ActiveSocketItem(); if (pServerSocketItem==NULL) throw TEXT("申请连接对象失败"); //激活对象 CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->Attach(hConnectSocket,SocketAddr.sin_addr.S_un.S_addr); CreateIoCompletionPort((HANDLE)hConnectSocket,m_hCompletionPort,(ULONG_PTR)pServerSocketItem,0); pServerSocketItem->RecvData(); } CATCH_COMMON_EXCEPTION(if (hConnectSocket!=INVALID_SOCKET) closesocket(hConnectSocket);) CATCH_UNKNOWN_EXCEPTION(if (hConnectSocket!=INVALID_SOCKET) closesocket(hConnectSocket);) _END_CATCH return true; } ////////////////////////////////////////////////////////////////////////// //构造函数 CSocketDetectThread::CSocketDetectThread(void) { m_dwTickCount=0;; m_pTCPSocketManager=NULL; } //析构函数 CSocketDetectThread::~CSocketDetectThread(void) { } //配置函数 bool CSocketDetectThread::InitThread(CTCPSocketEngine * pTCPSocketManager) { //效验参数 GT_ASSERT(pTCPSocketManager!=NULL); //设置变量 m_dwTickCount=0L; m_pTCPSocketManager=pTCPSocketManager; return true; } //Run函数 bool CSocketDetectThread::RepetitionRun() { //效验参数 GT_ASSERT(m_pTCPSocketManager!=NULL); //设置间隔 Sleep(500); m_dwTickCount+=500L; //检测连接 if (m_dwTickCount>20000L) { m_dwTickCount=0L; m_pTCPSocketManager->DetectSocket(); } return true; } ////////////////////////////////////////////////////////////////////////// //构造函数 CTCPSocketEngine::CTCPSocketEngine(void) { m_bService=false; m_wListenPort=0; m_dwLastDetect=0; m_wMaxSocketItem=0; m_hCompletionPort=NULL; m_hServerSocket=INVALID_SOCKET; return; } //析构函数 CTCPSocketEngine::~CTCPSocketEngine(void) { //停止服务 StopService(); //释放存储连接 CServerSocketItem * pSocketItem=NULL; for (INT_PTR i=0;i<m_StorageSocketItem.GetCount();i++) { pSocketItem=m_StorageSocketItem[i]; GT_ASSERT(pSocketItem!=NULL); SafeDelete(pSocketItem); } m_StorageSocketItem.RemoveAll(); return; } //接口查询 void * __cdecl CTCPSocketEngine::QueryInterface(const IID & Guid, DWORD dwQueryVer) { QUERYINTERFACE(ITCPSocketEngine,Guid,dwQueryVer); QUERYINTERFACE(ITCPSocketEngineManager,Guid,dwQueryVer); QUERYINTERFACE(IQueueServiceSink,Guid,dwQueryVer); QUERYINTERFACE_IUNKNOWNEX(ITCPSocketEngine,Guid,dwQueryVer); return NULL; } //设置接口 bool __cdecl CTCPSocketEngine::SetSocketEngineSink(IUnknownEx * pIUnknownEx) { //状态判断 if (m_bService==true) { CEventTrace::ShowEventNotify(TEXT("网络引擎处于服务状态,绑定操作忽略"),Level_Exception); return false; } //设置接口 if (m_AttemperEvent.SetQueueService(pIUnknownEx)==false) { CEventTrace::ShowEventNotify(TEXT("网络引擎与触发服务绑定失败"),Level_Exception); return false; } return true; } //设置端口 bool __cdecl CTCPSocketEngine::SetServicePort(WORD wListenPort) { //效验状态 if (m_bService==true) { CEventTrace::ShowEventNotify(TEXT("网络引擎处于服务状态,端口绑定操作忽略"),Level_Exception); return false; } //判断参数 if (wListenPort==0) { CEventTrace::ShowEventNotify(TEXT("网络端口错误,端口绑定操作失败"),Level_Exception); return false; } //设置变量 m_wListenPort=wListenPort; return true; } //设置数目 bool __cdecl CTCPSocketEngine::SetMaxSocketItem(WORD wMaxSocketItem) { m_wMaxSocketItem=wMaxSocketItem; return true; } //启动服务 bool __cdecl CTCPSocketEngine::StartService() { DWORD i = 0; //效验状态 if (m_bService==true) { CEventTrace::ShowEventNotify(TEXT("网络引擎重复启动,启动操作忽略"),Level_Warning); return true; } //判断端口 if (m_wListenPort==0) { CEventTrace::ShowEventNotify(TEXT("网络引擎监听端口无效"),Level_Exception); return false; } //绑定对象 if (m_SendQueueService.SetQueueServiceSink(GET_MYSELF_INTERFACE(IUnknownEx))==false) { CEventTrace::ShowEventNotify(TEXT("网络引擎与触发服务绑定失败"),Level_Exception); return false; } try { //获取系统信息 SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); DWORD dwThreadCount=SystemInfo.dwNumberOfProcessors; //建立完成端口 m_hCompletionPort=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,NULL,SystemInfo.dwNumberOfProcessors); if (m_hCompletionPort==NULL) throw TEXT("网络引擎完成端口创建失败"); //建立监听SOCKET struct sockaddr_in SocketAddr; memset(&SocketAddr,0,sizeof(SocketAddr)); SocketAddr.sin_addr.s_addr=INADDR_ANY; SocketAddr.sin_family=AF_INET; SocketAddr.sin_port=htons(m_wListenPort); m_hServerSocket=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED); if (m_hServerSocket==INVALID_SOCKET) throw TEXT("网络引擎监听 SOCKET 创建失败"); int iErrorCode=bind(m_hServerSocket,(SOCKADDR*)&SocketAddr,sizeof(SocketAddr)); if (iErrorCode==SOCKET_ERROR) throw TEXT("网络引擎监听端口被占用,端口绑定失败"); iErrorCode=listen(m_hServerSocket,200); if (iErrorCode==SOCKET_ERROR) throw TEXT("网络引擎监听端口被占用,端口监听失败"); //启动发送队列 bool bSuccess=m_SendQueueService.StartService(1); if (bSuccess==false) throw TEXT("网络引擎发送队列服务启动失败"); //建立读写线程 for (i=0;i<dwThreadCount;i++) { CServerSocketRSThread * pServerSocketRSThread=new CServerSocketRSThread(); if (pServerSocketRSThread==NULL) throw TEXT("网络引擎读写线程服务创建失败"); bSuccess=pServerSocketRSThread->InitThread(m_hCompletionPort); if (bSuccess==false) throw TEXT("网络引擎读写线程服务配置失败"); m_SocketRSThreadArray.Add(pServerSocketRSThread); } //建立应答线程 bSuccess=m_SocketAcceptThread.InitThread(m_hCompletionPort,m_hServerSocket,this); if (bSuccess==false) throw TEXT("网络引擎网络监听线程服务配置"); //Run读写线程 for (i=0;i<dwThreadCount;i++) { CServerSocketRSThread * pServerSocketRSThread=m_SocketRSThreadArray[i]; GT_ASSERT(pServerSocketRSThread!=NULL); bSuccess=pServerSocketRSThread->StartThead(); if (bSuccess==false) throw TEXT("网络引擎读写线程服务启动失败"); } //网络检测线程 m_SocketDetectThread.InitThread(this); bSuccess=m_SocketDetectThread.StartThead(); if (bSuccess==false) throw TEXT("网络引检测线程服务启动失败"); //Run应答线程 bSuccess=m_SocketAcceptThread.StartThead(); if (bSuccess==false) throw TEXT("网络引擎监听线程服务启动失败"); //设置变量 m_bService=true; } catch (LPCTSTR pszError) { CEventTrace::ShowEventNotify(pszError,Level_Exception); return false; } return true; } //停止服务 bool __cdecl CTCPSocketEngine::StopService() { //设置变量 m_bService=false; m_dwLastDetect=0L; //停止检测线程 m_SocketDetectThread.StopThread(); //终止应答线程 if (m_hServerSocket!=INVALID_SOCKET) { closesocket(m_hServerSocket); m_hServerSocket=INVALID_SOCKET; } m_SocketAcceptThread.StopThread(); //停止发送队列 m_SendQueueService.StopService(); //释放读写线程 INT_PTR nCount=m_SocketRSThreadArray.GetCount(),i=0; if (m_hCompletionPort!=NULL) { for (i=0;i<nCount;i++) PostQueuedCompletionStatus(m_hCompletionPort,0,NULL,NULL); } for (i=0;i<nCount;i++) { CServerSocketRSThread * pSocketThread=m_SocketRSThreadArray[i]; GT_ASSERT(pSocketThread!=NULL); pSocketThread->StopThread(); SafeDelete(pSocketThread); } m_SocketRSThreadArray.RemoveAll(); //关闭完成端口 if (m_hCompletionPort!=NULL) { CloseHandle(m_hCompletionPort); m_hCompletionPort=NULL; } //关闭连接 CServerSocketItem * pServerSocketItem=NULL; for (i=0;i<m_ActiveSocketItem.GetCount();i++) { pServerSocketItem=m_ActiveSocketItem[i]; GT_ASSERT(pServerSocketItem!=NULL); pServerSocketItem->CloseSocket(pServerSocketItem->GetRountID()); pServerSocketItem->ResetSocketData(); } m_FreeSocketItem.Append(m_ActiveSocketItem); m_ActiveSocketItem.RemoveAll(); return true; } //应答消息 bool CTCPSocketEngine::OnSocketAcceptEvent(CServerSocketItem * pServerSocketItem) { //效验数据 GT_ASSERT(pServerSocketItem!=NULL); GT_ASSERT(m_AttemperEvent.IsValid()==true); //投递消息 if (m_bService==false) return false; m_AttemperEvent.PostSocketAcceptEvent(pServerSocketItem->GetIndex(),pServerSocketItem->GetRountID(),pServerSocketItem->GetClientAddr()); return true; } //网络读取消息 bool CTCPSocketEngine::OnSocketReadEvent(CMD_Command Command, void * pBuffer, WORD wDataSize, CServerSocketItem * pServerSocketItem) { //效验数据 GT_ASSERT(pServerSocketItem!=NULL); GT_ASSERT(m_AttemperEvent.IsValid()==true); //效验状态 if (m_bService==false) return false; m_AttemperEvent.PostSocketReadEvent(pServerSocketItem->GetIndex(),pServerSocketItem->GetRountID(),Command,pBuffer,wDataSize); return true; } //网络关闭消息 bool CTCPSocketEngine::OnSocketCloseEvent(CServerSocketItem * pServerSocketItem) { //效验参数 GT_ASSERT(pServerSocketItem!=NULL); GT_ASSERT(m_AttemperEvent.IsValid()==true); _BEGIN_TRY { //效验状态 if (m_bService==false) return false; //计算时间 WORD wIndex=pServerSocketItem->GetIndex(); WORD wRountID=pServerSocketItem->GetRountID(); DWORD dwClientAddr=pServerSocketItem->GetClientAddr(); DWORD dwConnectTime=pServerSocketItem->GetConnectTime(); m_AttemperEvent.PostSocketCloseEvent(wIndex,wRountID,dwClientAddr,dwConnectTime); //释放连接 FreeSocketItem(pServerSocketItem); } CATCH_COMMON_EXCEPTION(;) CATCH_UNKNOWN_EXCEPTION(;) _END_CATCH return true; } //通知回调函数(发送队列线程调用) void __cdecl CTCPSocketEngine::OnQueueServiceSink(BYTE cbThreadIndex,WORD wIdentifier, void * pBuffer, WORD wDataSize, DWORD dwInsertTime) { switch (wIdentifier) { case QUEUE_SEND_REQUEST: //发送请求 { //效验数据 tagSendDataRequest * pSendDataRequest=(tagSendDataRequest *)pBuffer; GT_ASSERT(wDataSize>=(sizeof(tagSendDataRequest)-sizeof(pSendDataRequest->cbSendBuf))); GT_ASSERT(wDataSize==(pSendDataRequest->wDataSize+sizeof(tagSendDataRequest)-sizeof(pSendDataRequest->cbSendBuf))); //发送数据 if (pSendDataRequest->wIndex==INDEX_ALL_SOCKET) { //获取活动项 CThreadLockHandle ItemLockedHandle(&m_ItemLocked); m_TempSocketItem.Copy(m_ActiveSocketItem); ItemLockedHandle.UnLock(); //循环发送数据 CServerSocketItem * pServerSocketItem=NULL; for (INT_PTR i=0;i<m_TempSocketItem.GetCount();i++) { pServerSocketItem=m_TempSocketItem[i]; GT_ASSERT(pServerSocketItem!=NULL); CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); if (pServerSocketItem->IsAllowBatch()) { pServerSocketItem->SendData(pSendDataRequest->cbSendBuf,pSendDataRequest->wDataSize,pSendDataRequest->wMainCmdID, pSendDataRequest->wSubCmdID,pServerSocketItem->GetRountID()); } } } else { //单项发送 CServerSocketItem * pServerSocketItem=EnumSocketItem(pSendDataRequest->wIndex); CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->SendData(pSendDataRequest->cbSendBuf,pSendDataRequest->wDataSize,pSendDataRequest->wMainCmdID, pSendDataRequest->wSubCmdID,pSendDataRequest->wRountID); } break; } case QUEUE_SAFE_CLOSE: //安全关闭 { //效验数据 GT_ASSERT(wDataSize==sizeof(tagSafeCloseSocket)); tagSafeCloseSocket * pSafeCloseSocket=(tagSafeCloseSocket *)pBuffer; //安全关闭 CServerSocketItem * pServerSocketItem=EnumSocketItem(pSafeCloseSocket->wIndex); CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->ShutDownSocket(pSafeCloseSocket->wRountID); break; } case QUEUE_ALLOW_BATCH: //允许群发 { //效验数据 GT_ASSERT(wDataSize==sizeof(tagAllowBatchSend)); tagAllowBatchSend * pAllowBatchSend=(tagAllowBatchSend *)pBuffer; //设置群发 CServerSocketItem * pServerSocketItem=EnumSocketItem(pAllowBatchSend->wIndex); CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); pServerSocketItem->AllowBatchSend(pAllowBatchSend->wRountID,pAllowBatchSend->cbAllow?true:false); break; } case QUEUE_DETECT_SOCKET: //检测连接 { //获取活动项 CThreadLockHandle ItemLockedHandle(&m_ItemLocked); m_TempSocketItem.Copy(m_ActiveSocketItem); ItemLockedHandle.UnLock(); //构造数据 CMD_KN_DetectSocket DetectSocket; ZeroMemory(&DetectSocket,sizeof(DetectSocket)); //变量定义 WORD wRountID=0; DWORD dwNowTickCount=GetTickCount(); DWORD dwBreakTickCount=__max(dwNowTickCount-m_dwLastDetect,TIME_BREAK_READY); //设置变量 m_dwLastDetect=GetTickCount(); //检测连接 for (INT_PTR i=0;i<m_TempSocketItem.GetCount();i++) { //变量定义 CServerSocketItem * pServerSocketItem=m_TempSocketItem[i]; DWORD dwRecvTickCount=pServerSocketItem->GetRecvTickCount(); CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); //间隔检查 if (dwRecvTickCount>=dwNowTickCount) continue; //检测连接 if (pServerSocketItem->IsReadySend()==true) { if ((dwNowTickCount-dwRecvTickCount)>dwBreakTickCount) { pServerSocketItem->CloseSocket(pServerSocketItem->GetRountID()); continue; } } else { if ((dwNowTickCount-dwRecvTickCount)>TIME_BREAK_CONNECT) { pServerSocketItem->CloseSocket(pServerSocketItem->GetRountID()); continue; } } //发送数据 if (pServerSocketItem->IsReadySend()==true) { wRountID=pServerSocketItem->GetRountID(); DetectSocket.dwSendTickCount=GetTickCount(); pServerSocketItem->SendData(&DetectSocket,sizeof(DetectSocket),MDM_KN_COMMAND,SUB_KN_DETECT_SOCKET,wRountID); } } break; } default: { GT_ASSERT(FALSE); } } return; } //获取空闲对象 CServerSocketItem * CTCPSocketEngine::ActiveSocketItem() { CThreadLockHandle ItemLockedHandle(&m_ItemLocked,true); //获取空闲对象 CServerSocketItem * pServerSocketItem=NULL; if (m_FreeSocketItem.GetCount()>0) { INT_PTR nItemPostion=m_FreeSocketItem.GetCount()-1; pServerSocketItem=m_FreeSocketItem[nItemPostion]; GT_ASSERT(pServerSocketItem!=NULL); m_FreeSocketItem.RemoveAt(nItemPostion); m_ActiveSocketItem.Add(pServerSocketItem); } //创建新对象 if (pServerSocketItem==NULL) { WORD wStorageCount=(WORD)m_StorageSocketItem.GetCount(); if (wStorageCount<m_wMaxSocketItem) { _BEGIN_TRY { pServerSocketItem=new CServerSocketItem(wStorageCount,this); if (pServerSocketItem==NULL) return NULL; m_StorageSocketItem.Add(pServerSocketItem); m_ActiveSocketItem.Add(pServerSocketItem); } CATCH_COMMON_EXCEPTION(return NULL;) CATCH_UNKNOWN_EXCEPTION(return NULL;) _END_CATCH } } return pServerSocketItem; } //获取连接对象 CServerSocketItem * CTCPSocketEngine::EnumSocketItem(WORD wIndex) { CThreadLockHandle ItemLockedHandle(&m_ItemLocked,true); if (wIndex<m_StorageSocketItem.GetCount()) { CServerSocketItem * pServerSocketItem=m_StorageSocketItem[wIndex]; GT_ASSERT(pServerSocketItem!=NULL); return pServerSocketItem; } return NULL; } //释放连接对象 bool CTCPSocketEngine::FreeSocketItem(CServerSocketItem * pServerSocketItem) { //效验参数 GT_ASSERT(pServerSocketItem!=NULL); //释放对象 CThreadLockHandle ItemLockedHandle(&m_ItemLocked,true); INT_PTR nActiveCount=m_ActiveSocketItem.GetCount(); for (int i=0;i<nActiveCount;i++) { if (pServerSocketItem==m_ActiveSocketItem[i]) { m_ActiveSocketItem.RemoveAt(i); m_FreeSocketItem.Add(pServerSocketItem); return true; } } //释放失败 GT_ASSERT(FALSE); return false; } //检测连接 bool __cdecl CTCPSocketEngine::DetectSocket() { return m_SendQueueService.AddToQueue(QUEUE_DETECT_SOCKET,NULL,0); } //发送函数 bool __cdecl CTCPSocketEngine::SendData(WORD wIndex, WORD wRountID, WORD wMainCmdID, WORD wSubCmdID) { //效益状态 GT_ASSERT(m_bService==true); if (m_bService==false) return false; //构造数据 tagSendDataRequest SendRequest; SendRequest.wMainCmdID=wMainCmdID; SendRequest.wSubCmdID=wSubCmdID; SendRequest.wIndex=wIndex; SendRequest.wRountID=wRountID; SendRequest.wDataSize=0; //加入发送队列 WORD wSendSize=sizeof(SendRequest)-sizeof(SendRequest.cbSendBuf); return m_SendQueueService.AddToQueue(QUEUE_SEND_REQUEST,&SendRequest,wSendSize); } //发送函数 bool __cdecl CTCPSocketEngine::SendData(WORD wIndex, WORD wRountID, WORD wMainCmdID, WORD wSubCmdID, void * pData, WORD wDataSize) { //效益状态 GT_ASSERT(m_bService==true); if (m_bService==false) return false; //效益数据 GT_ASSERT((wDataSize)<=SOCKET_PACKAGE); if ((wDataSize)>SOCKET_PACKAGE) return false; //构造数据 tagSendDataRequest SendRequest; SendRequest.wMainCmdID=wMainCmdID; SendRequest.wSubCmdID=wSubCmdID; SendRequest.wIndex=wIndex; SendRequest.wRountID=wRountID; SendRequest.wDataSize=wDataSize; if (wDataSize>0) { GT_ASSERT(pData!=NULL); CopyMemory(SendRequest.cbSendBuf,pData,wDataSize); } //加入发送队列 WORD wSendSize=sizeof(SendRequest)-sizeof(SendRequest.cbSendBuf)+wDataSize; return m_SendQueueService.AddToQueue(QUEUE_SEND_REQUEST,&SendRequest,wSendSize); } //批量发送 bool __cdecl CTCPSocketEngine::SendDataBatch(WORD wMainCmdID, WORD wSubCmdID, void * pData, WORD wDataSize) { //效益状态 if (m_bService==false) return false; //效益数据 GT_ASSERT((wDataSize)<=SOCKET_PACKAGE); if ((wDataSize)>SOCKET_PACKAGE) return false; //构造数据 tagSendDataRequest SendRequest; SendRequest.wMainCmdID=wMainCmdID; SendRequest.wSubCmdID=wSubCmdID; SendRequest.wIndex=INDEX_ALL_SOCKET; SendRequest.wRountID=0; SendRequest.wDataSize=wDataSize; if (wDataSize>0) { GT_ASSERT(pData!=NULL); CopyMemory(SendRequest.cbSendBuf,pData,wDataSize); } //加入发送队列 WORD wSendSize=sizeof(SendRequest)-sizeof(SendRequest.cbSendBuf)+wDataSize; return m_SendQueueService.AddToQueue(QUEUE_SEND_REQUEST,&SendRequest,wSendSize); } //关闭连接 bool __cdecl CTCPSocketEngine::CloseSocket(WORD wIndex, WORD wRountID) { CServerSocketItem * pServerSocketItem=EnumSocketItem(wIndex); if (pServerSocketItem==NULL) return false; CThreadLockHandle SocketLockHandle(pServerSocketItem->GetSignedLock()); return pServerSocketItem->CloseSocket(wRountID); } //设置关闭 bool __cdecl CTCPSocketEngine::ShutDownSocket(WORD wIndex, WORD wRountID) { tagSafeCloseSocket SafeCloseSocket; SafeCloseSocket.wIndex=wIndex; SafeCloseSocket.wRountID=wRountID; return m_SendQueueService.AddToQueue(QUEUE_SAFE_CLOSE,&SafeCloseSocket,sizeof(SafeCloseSocket)); } //允许群发 bool __cdecl CTCPSocketEngine::AllowBatchSend(WORD wIndex, WORD wRountID, bool bAllow) { tagAllowBatchSend AllowBatchSend; AllowBatchSend.wIndex=wIndex; AllowBatchSend.wRountID=wRountID; AllowBatchSend.cbAllow=bAllow; return m_SendQueueService.AddToQueue(QUEUE_ALLOW_BATCH,&AllowBatchSend,sizeof(AllowBatchSend)); } ////////////////////////////////////////////////////////////////////////// //建立对象函数 extern "C" __declspec(dllexport) void * __cdecl CreateTCPSocketEngine(const GUID & Guid, DWORD dwInterfaceVer) { //建立对象 CTCPSocketEngine * pTCPSocketEngine=NULL; _BEGIN_TRY { pTCPSocketEngine=new CTCPSocketEngine(); if (pTCPSocketEngine==NULL) throw TEXT("创建失败"); void * pObject=pTCPSocketEngine->QueryInterface(Guid,dwInterfaceVer); if (pObject==NULL) throw TEXT("接口查询失败"); return pObject; } CATCH_COMMON_EXCEPTION(;)CATCH_UNKNOWN_EXCEPTION(;)_END_CATCH //清理对象 SafeDelete(pTCPSocketEngine); return NULL; } //////////////////////////////////////////////////////////////////////////
[ [ [ 1, 1544 ] ] ]
25c6f9e7c412960173c6a1312f1462da0aca4f51
f065febc4f2b6104ef8e844b4fae53add2760d71
/Pow32/link32/Objfile.cpp
eb6fbcbeaff108746f57dd15ef37ad56450e0f4b
[]
no_license
Spirit-of-Oberon/POW
370bcceb2c93ffef941fd8bcb2f1ed5da4926846
eaf5d9b1817ba4f51e2b3de4adbfe8d726ea3e9f
refs/heads/master
2021-01-25T07:40:30.160481
2011-12-19T13:52:46
2011-12-19T13:52:46
3,012,201
7
6
null
null
null
null
ISO-8859-1
C++
false
false
18,891
cpp
/**************************************************************************************************/ /*** Die Datei ObjFile.cpp beinhaltet die Implementierung folgender Klassen: ***/ /*** CCObjFile ***/ /**************************************************************************************************/ #ifndef __STDLIB_H__ #include <stdlib.h> #endif #ifndef __STRING_H__ #include <string.h> #endif #ifndef __OBJFILE_HPP__ #include "ObjFile.hpp" #endif #ifndef __LINKER_HPP__ #include "Linker.hpp" #endif #ifndef __SECTION_HPP__ #include "Section.hpp" #endif #ifndef __PUBLIBEN_HPP__ #include "PubLibEn.hpp" #endif extern FILE *logFil; extern char *logFilNam; extern int logOn; extern void WriteMessageToPow(WORD msgNr, char *str1, char *str2); extern void FreeCObjFileSection(CObjFileSection *aCObjFileSection); extern void FreeCSymbolEntry(CSymbolEntry *aCSymbolEntry); extern void FreeCDllExportEntry(CDllExportEntry *aCDllExportEntry); extern void FreeCMapStringToOb(CMapStringToOb *aCMapStringToOb); extern void FreeCObList(CObList *aCObList); extern void FreeCObArray(CObArray *aCObArray); extern void FreeCMemFile(CMemFile *aCMemFile); extern void FreeCMyMemFile(CMyMemFile *aCMyMemFile); extern void FreeCMyPtrList(CMyPtrList *aCMyPtrList); IMPLEMENT_DYNAMIC(CObjFile, CObject) /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ /*-------------------*/ /*-- Konstruktoren --*/ /*-------------------*/ CObjFile::CObjFile() { objFilBuf= NULL; srcFilNam= NULL; objFilNam= NULL; libFilNam= NULL; incDllFun= FALSE; libObjFil= TRUE; insSstFilInd= TRUE; linNmbInc= FALSE; incExpEnt= NULL; secLstLst= NULL; secLst= NULL; newSymLst= NULL; ftrExeFil= NULL; objMemFil= NULL; dbgTSec= NULL; freSymNamLst= NULL; gloPubSymLst= NULL; symEntBuf= NULL; sstGloTypRawDat= NULL; libFilInd= 0; cvModInd= 0xFFFF; } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ /*------------------*/ /*-- Destruktoren --*/ /*------------------*/ CObjFile::~CObjFile() { FreeUsedMemory(); } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ void CObjFile::FreeUsedMemory() { CObjFileSection *delSecEnt; char *symNam; int entInLst; int i; if (objFilBuf) { free(objFilBuf); objFilBuf= NULL; } if (srcFilNam) { free(srcFilNam); srcFilNam= NULL; } if (objFilNam) { free(objFilNam); objFilNam= NULL; } if (secLstLst) { FreeCMapStringToOb(secLstLst); delete secLstLst; secLstLst= NULL; } if (secLst) { entInLst= secLst-> GetUpperBound(); for(i= 0; i <= entInLst; i++) { delSecEnt= (CObjFileSection *)secLst-> GetAt(i); if (delSecEnt) { FreeCObjFileSection(delSecEnt); delete delSecEnt; } } secLst-> ~CMyObArray(); delete secLst; secLst= NULL; } if (newSymLst) { free(newSymLst); newSymLst= NULL; } if (symEntBuf) { free(symEntBuf); symEntBuf= NULL; } if (objMemFil) { FreeCMyMemFile(objMemFil); delete objMemFil; objMemFil= NULL; } if (libFilNam) { free(libFilNam); libFilNam= NULL; } if (freSymNamLst) { while(!freSymNamLst-> IsEmpty()) { symNam= (char *)freSymNamLst-> RemoveHead(); free(symNam); } FreeCMyPtrList(freSymNamLst); delete freSymNamLst; freSymNamLst= NULL; } if (gloPubSymLst) { FreeCMyPtrList(gloPubSymLst); delete gloPubSymLst; gloPubSymLst= NULL; } if (symEntBuf) { free(symEntBuf); symEntBuf= NULL; } if (sstGloTypRawDat) { sstGloTypRawDat-> ~CMyMemFile(); delete sstGloTypRawDat; sstGloTypRawDat= NULL; } dbgTSec= NULL; incExpEnt= NULL; } /******************************************************************************************************/ /*** Einlesen einer Objektdatei und Aufruf der Methode zum Analysieren derselben ***/ /******************************************************************************************************/ BOOL CObjFile::LoadObjFileFromDisc(const char *pszFilNam, CMyPtrList *unResSymLst, CMyMapStringToPtr *pubSymLst) { CFileException *pErr= NULL; CBuffFile objFil; CMyMemFile *objMemFil; DWORD objFilSiz; BOOL lnkOK= TRUE; objFilNam= (char *) malloc(strlen(pszFilNam) + 1); objFilNam= strcpy(objFilNam, (char *)pszFilNam); if (!objFil.Open(pszFilNam, CStdioFile::modeRead | CStdioFile::typeBinary, pErr)) { WriteMessageToPow(ERR_MSGI_OPN_OBJ, (char *)pszFilNam, NULL); return FALSE; } else WriteMessageToPow(INF_MSG_FIL_OPE_SUC, (char *)pszFilNam, NULL); objFilSiz= objFil.GetLength(); objFilBuf= (BYTE *) malloc(objFilSiz + 1); objFil.ReadHuge(objFilBuf, objFilSiz); objFil.Close(); objMemFil= new CMyMemFile(); objMemFil-> SetBufferDirect(objFilBuf, objFilSiz); lnkOK= AnalObjFileData(objMemFil, unResSymLst, pubSymLst); objMemFil-> ~CMyMemFile(); delete objMemFil; objMemFil= NULL; return lnkOK; } /******************************************************************************************************/ /*** Analysieren einer Objektdatei. Verarbeiten des Headers, der Sektionstabelle, der Sektions- ***/ /*** (Rohdaten, Relokationen und Zeilennummern), sowie Aufarbeiten der Symboltabelle. ***/ /******************************************************************************************************/ BOOL CObjFile::AnalObjFileData(CMyMemFile *aMemFil, CMyPtrList *unResSymLst, CMyMapStringToPtr *pubSymLst) { CSectionFragmentEntry *newSecFrg; CObjFileSection *newSec; CObjFileSection *txtSec; mySymbolEntry *nxtSymEnt; DWORD actFilSekPos; DWORD actSymInd; DWORD strTabPtr; WORD i; BOOL lnkOK= TRUE; // Initialising Coff Hdr aMemFil-> SeekToBegin(); aMemFil-> Read(&objCofHdr, COF_HDR_SIZ); if (objCofHdr.mach != IMAGE_FILE_MACHINE_I386) { WriteMessageToPow(ERR_MSGIS_WRG_MAC, objFilNam, NULL); return FALSE; } // Liste der Sektionen wird erstellt secLstLst= new CMyMapStringToOb(objCofHdr.secNum); secLstLst-> InitHashTable(objCofHdr.secNum, TRUE); secLst= new CMyObArray(); secLst-> SetSize(objCofHdr.secNum, 1); if (objCofHdr.optHdrSiz) aMemFil-> Seek(objCofHdr.optHdrSiz, CFile::current); actFilSekPos= (WORD ) aMemFil-> GetPosition(); for(i= 0; i < objCofHdr.secNum; i++) { newSec= new CObjFileSection(); lnkOK= newSec-> ReadSecData(aMemFil, actFilSekPos, this); secLstLst-> SetAt(newSec-> secNam, newSec); secLst-> SetAt(i, newSec); actFilSekPos+= SEC_HDR_SIZ; } if (!lnkOK) return lnkOK; if ((secLstLst-> Lookup(".idata$2", (CObject *&)newSec)) || (secLstLst-> Lookup(".idata$3", (CObject *&)newSec)) || (secLstLst-> Lookup(".idata$5", (CObject *&)newSec))) incDllFun= TRUE; else incDllFun= FALSE; if (!incDllFun) { for(i= 0; i < objCofHdr.secNum; i++) { newSec= (CObjFileSection *)secLst-> GetAt(i); if (newSec-> actSecTab-> rawDatSiz) lnkOK= newSec-> WrapFromObj2Exe(this, ftrExeFil); } if (!lnkOK) return lnkOK; } // Einlesen der Symboltabelle strTabPtr= objCofHdr.symTabPtr + objCofHdr.symNum * SYM_TAB_LEN; if (ftrExeFil-> includeDebugInfo) gloPubSymLst= new CMyPtrList(objCofHdr.symNum); actSymInd= 0; aMemFil-> Seek(objCofHdr.symTabPtr, CFile::begin); DWORD symEntSiz= sizeof(mySymbolEntry); symEntBuf= (BYTE *) malloc (symEntSiz * objCofHdr.symNum); memset(symEntBuf, 0, symEntSiz * objCofHdr.symNum); newSymLst= (mySymbolEntry **) malloc (sizeof(mySymbolEntry*) * objCofHdr.symNum); memset(newSymLst, 0, sizeof(mySymbolEntry*) * objCofHdr.symNum); nxtSymEnt= (mySymbolEntry *)symEntBuf; while(actSymInd < objCofHdr.symNum) { newSymLst[actSymInd]= (mySymbolEntry *)nxtSymEnt; actSymInd+= ReadSymEntData(nxtSymEnt, aMemFil, strTabPtr, this, unResSymLst, pubSymLst); nxtSymEnt= (mySymbolEntry *)symEntBuf + actSymInd; } // Überpüfen ob Dll Import und ermitteln der Funktionsdaten if (incDllFun) { if (ftrExeFil-> includeDebugInfo) { for(i= 0; i < objCofHdr.secNum; i++) { newSec= (CObjFileSection *)secLst-> GetAt(i); if (!strcmp(newSec-> secNam, ".debug$S")) { newSecFrg= new CSectionFragmentEntry(NULL, 0x00, newSec, this, newSec-> aln); newSec-> SetFragEntry(newSecFrg); } } } incExpEnt= NULL; if (secLstLst-> Lookup(".idata$6", (CObject *&)newSec)) { if (secLstLst-> Lookup(".text", (CObject *&)txtSec)) incExpEnt= newSec-> GiveDllExpEntIdata$6(this, objFilNam, txtSec); else { if (secLstLst-> Lookup(".idata$2", (CObject *&)txtSec)) incExpEnt= newSec-> GiveDllExpEntIdata$2(this, objFilNam); else incExpEnt= newSec-> GiveDllExpEntIdata$6(this, objFilNam); } } else { if (secLstLst-> Lookup(".idata$4", (CObject *&)newSec)) { if (secLstLst-> Lookup(".text", (CObject *&)txtSec)) incExpEnt= newSec-> GiveDllExpEntIdata$4(this, objFilNam, txtSec); } else { if (!secLstLst-> Lookup(".idata$3", (CObject *&)newSec)) { WriteMessageToPow(ERR_MSGIS_NO_IMP_SYM, objFilNam, NULL); lnkOK= FALSE; } } } if (!incExpEnt) incDllFun= FALSE; } return lnkOK; } /******************************************************************************************************/ /*** Einlesen des Eportverzeichnisses einer DLL. Wird ab MS VC++ 2.0 nicht mehr verwendet, da es ***/ /*** die .EDATA Sektion in den Bibliotheken nicht mehr gibt. ***/ /******************************************************************************************************/ CMapStringToOb *CObjFile::GiveDllFunDir() { CObjFileSection *expSec; char *expSecNam= ".edata"; if (secLstLst-> Lookup(expSecNam, (CObject *&)expSec)) return expSec-> GiveDllFunDir(); return NULL; } /******************************************************************************************************/ /*** Setzen des Zeigers auf das Objekt der zu erzeugenden PE-Datei ***/ /******************************************************************************************************/ void CObjFile::SetExeFile(CExeFile *ftrExeFile) { ftrExeFil= ftrExeFile; } /******************************************************************************************************/ /*** Zuordnen der Objektdateisektionen in die entsprechenden Sektionen der PE-Datei ***/ /******************************************************************************************************/ BOOL CObjFile::SplitObjSec(CExeFile *aExeFil) { CObjFileSection *actSec; LPCTSTR secNam; POSITION secPos; secPos= secLstLst-> GetStartPosition(); while(secPos != NULL) { secLstLst-> GetNextAssoc(secPos, secNam, (CObject *&)actSec); actSec-> WrapFromObj2Exe(this, aExeFil); } return TRUE; } /******************************************************************************************************/ /*** Hilfsmethode zum Debuggen ***/ /******************************************************************************************************/ void CObjFile::WriteObjDataToFile() { POSITION symPos; LPCTSTR nam; CSection *curSec; logFil = fopen(logFilNam,"a"); if (objFilNam) fprintf(logFil, "\n\nObjectfile: %s", objFilNam); else fprintf(logFil, "\n\nThere' s no Objectfilename:"); if (libFilNam) fprintf(logFil, "(%s)", libFilNam); fprintf(logFil, "\nSektionen : %04d", objCofHdr.secNum); fprintf(logFil, "\nSymbole : %04d", objCofHdr.symNum); fprintf(logFil, "\nCharakteristik : %08X\n", objCofHdr.chr); fclose(logFil); symPos= secLstLst-> GetStartPosition(); while(symPos) { secLstLst-> GetNextAssoc(symPos, nam, (CObject *&)curSec); curSec-> WriteSecDataToFile(); } } /******************************************************************************************************/ /*** Hilfsmethode zum Debuggen ***/ /******************************************************************************************************/ void CObjFile::WriteSymToFile() { mySymbolEntry *aSymEnt; DWORD i; for(i= 0; i < objCofHdr.symNum; i++) { aSymEnt= (mySymbolEntry *)newSymLst + i; if (aSymEnt-> symNam) printf("\n%s", aSymEnt-> symNam); } } /******************************************************************************************************/ /*** Lesen und Aufarbeiten eines Symboleintrags und seiner dazugehöriger Hilfssymboleinträge einer ***/ /*** Objektdatei ***/ /******************************************************************************************************/ DWORD CObjFile::ReadSymEntData(mySymbolEntry *actSymEnt, CMyMemFile *actObjRawDat, DWORD ptrToStrTab, CObjFile *actObjFil, CMyPtrList *unResSymLst, CMyMapStringToPtr *pubSymLst) { mySymbolTable *actSymTab; mySymbolEntry *resSymEnt; DWORD sekPos; actSymEnt-> symObjFil= actObjFil; actSymEnt-> actSymTab= actSymTab= (mySymbolTable *)actObjRawDat-> ReadWithoutMemcpy(SYM_TAB_LEN); actSymEnt-> val= actSymTab-> val; // Speichern von val in einer neuen Variablen, siehe unten !!!!! if (actSymTab-> zero) { /* Symbolname steht im Symbol Table */ if (actSymTab-> val && (actSymTab-> strTabOff / 0x1000000 > 0)) // Überprüfen ob 8.Byte nicht sowieso Null enthält. { actSymEnt-> symNam= (char *)malloc(2 * sizeof(DWORD) + 1); memset(actSymEnt-> symNam, 0x00, 2 * sizeof(DWORD) + 1); strncpy(actSymEnt-> symNam, (char *)actSymTab, 2 * sizeof(DWORD)); if (!freSymNamLst) freSymNamLst= new CMyPtrList(50); freSymNamLst-> AddTail(actSymEnt-> symNam); } else actSymEnt-> symNam= (char *)actSymTab; } else { /*** Symbolname steht im String Table, im Symbol Table steht der Offset ***/ sekPos= actObjRawDat-> GetPosition(); actObjRawDat-> Seek(ptrToStrTab + actSymTab-> strTabOff, CFile::begin); actSymEnt-> symNam= (char *)((CMyMemFile *)actObjRawDat)-> ReadWithoutMemcpy(0); actObjRawDat-> Seek(sekPos, CFile::begin); } if (actSymTab-> storClass == IMAGE_SYM_CLASS_FILE) { if (!srcFilNam) { srcFilNam= (char *) malloc(actSymTab-> auxSymNum * SYM_TAB_LEN + 1); memset(srcFilNam, 0x00, actSymTab-> auxSymNum * SYM_TAB_LEN + 1); sekPos= actObjRawDat-> GetPosition(); actObjRawDat-> Read(srcFilNam, actSymTab-> auxSymNum * SYM_TAB_LEN); actObjRawDat-> Seek(sekPos, CFile::begin); } } if (actSymTab-> secNum) // Zeiger in Sektion desselben Objectfiles --> mgl. Debug Information { // Symbol wird im selben Objektfile aufgelöst actSymEnt-> resSym= actSymEnt; // Es werden nicht alle Symbole im Modul in die Symbolliste aufgenommen if (actSymEnt-> symNam[0] != '$' && actSymEnt-> symNam[0] != '.') if (pubSymLst) pubSymLst-> SetAt(actSymEnt-> symNam, actSymEnt); if (ftrExeFil-> includeDebugInfo) if ((actSymTab-> storClass == IMAGE_SYM_CLASS_EXTERNAL) && (actSymTab-> secNum != 0xFFFF/*IMAGE_SYM_ABSOLUTE*/)) // External Public Symbol --> geht in Debugliste, actObjFil-> gloPubSymLst-> AddTail(actSymEnt); // CV - sstGlobalPub // außer ABS Symbole } else { if (actSymEnt-> symNam[0] != '.') // Es gibt .idata$# Einträge die UNDEF sind, jedoch { // einen .val Wert haben! Haben hier nichts verloren if (actSymEnt-> val && (strncmp(actSymEnt-> symNam, "__F", strlen("__F")))) { // Wenn actSymTab-> val != Null ist, dann handelt es sich um eine Variable actSymEnt-> resSym= actSymEnt; WriteMessageToPow(INF_MSGS_UNI_VAR, actSymEnt-> symNam, NULL); pubSymLst-> SetAt(actSymEnt-> symNam, actSymEnt); actObjFil-> ftrExeFil-> bssSec-> bssVarLst-> AddTail(actSymEnt); // External Public Symbol --> geht in Debugliste außer ABS Symbole if ((ftrExeFil-> includeDebugInfo) && (actSymTab-> storClass == IMAGE_SYM_CLASS_EXTERNAL)) actObjFil-> gloPubSymLst-> AddTail(actSymEnt); // CV - sstGlobalPub } else { if (actSymTab-> storClass == IMAGE_SYM_CLASS_WEAK_EXTERNAL) // Weak External { mySymbolTable *weakExt; sekPos= actObjRawDat-> GetPosition(); weakExt= (mySymbolTable *)actObjRawDat-> ReadWithoutMemcpy(SYM_TAB_LEN); actSymEnt-> resSym= (mySymbolEntry *)symEntBuf + weakExt-> zero; unResSymLst-> AddTail(actSymEnt); actObjRawDat-> Seek(sekPos, CFile::begin); } else { if (unResSymLst) { if (pubSymLst-> Lookup(actSymEnt-> symNam, (void *&)resSymEnt)) { if (resSymEnt-> dllExpEnt) actSymEnt-> dllExpEnt= resSymEnt-> dllExpEnt; actSymEnt-> resSym= resSymEnt; } else { if (!actObjFil-> incDllFun) unResSymLst-> AddTail(actSymEnt); else unResSymLst-> AddHead(actSymEnt); // Soll doppelte Einträge der allgemeinen Import Descriptoren verhindern } } } } } } // Überlesen der Hilfssymboleinträge actObjRawDat-> Seek(actSymTab-> auxSymNum * SYM_TAB_LEN, CFile::current); return actSymTab-> auxSymNum + 1; }
[ [ [ 1, 608 ] ] ]
14f8ee5109a732656b57d4a0658b4f784a0a247f
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/XMLFloat.cpp
081bd1fb32d4b6840f466dc4208b75d6f231cceb
[ "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,719
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: XMLFloat.cpp,v 1.16 2004/09/09 20:09:30 peiyongz Exp $ * $Log: XMLFloat.cpp,v $ * Revision 1.16 2004/09/09 20:09:30 peiyongz * getDataOverflowed() * * Revision 1.15 2004/09/08 13:56:24 peiyongz * Apache License Version 2.0 * * Revision 1.14 2003/12/17 00:18:35 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.13 2003/10/15 14:50:01 peiyongz * Bugzilla#22821: locale-sensitive function used to validate 'double' type, patch * from [email protected] (Jeff Sweeney) * * Revision 1.12 2003/09/23 18:16:07 peiyongz * Inplementation for Serialization/Deserialization * * Revision 1.11 2003/05/16 06:01:53 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.10 2003/05/16 03:11:22 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.9 2003/03/10 20:55:58 peiyongz * Schema Errata E2-40 double/float * * Revision 1.8 2003/02/02 23:54:43 peiyongz * getFormattedString() added to return original and converted value. * * Revision 1.7 2003/01/30 19:14:43 tng * On some platforms like Solaris strtod will return -0.0. So need to consider this scenario as well. * * Revision 1.6 2002/12/11 19:55:16 peiyongz * set negZero/posZero for float. * * Revision 1.5 2002/12/11 00:20:02 peiyongz * Doing businesss in value space. Converting out-of-bound value into special values. * * Revision 1.4 2002/11/04 15:22:05 tng * C++ Namespace Support. * * Revision 1.3 2002/09/24 19:51:24 tng * Performance: use XMLString::equals instead of XMLString::compareString * * Revision 1.2 2002/05/03 16:05:45 peiyongz * Bug 7341: Missing newline at end of util and DOM source files, * patch from Martin Kalen. * * Revision 1.1.1.1 2002/02/01 22:22:15 peiyongz * sane_include * * Revision 1.13 2001/11/19 21:33:42 peiyongz * Reorganization: Double/Float * * Revision 1.12 2001/11/19 17:27:55 peiyongz * Boundary Values updated * * Revision 1.11 2001/10/26 16:37:46 peiyongz * Add thread safe code * * Revision 1.9 2001/09/20 13:11:41 knoaman * Regx + misc. fixes * * Revision 1.8 2001/09/14 13:57:59 peiyongz * exponent is a must if 'E' or 'e' is present. * * Revision 1.7 2001/08/23 11:54:26 tng * Add newline at the end and various typo fixes. * * Revision 1.6 2001/08/21 15:10:15 peiyongz * Bugzilla# 3017: MSVC5.0: C2202: 'compareSpecial' : not all * control paths return a value * * Revision 1.5 2001/08/14 22:10:20 peiyongz * new exception message added * * Revision 1.4 2001/07/31 17:38:16 peiyongz * Fix: memory leak by static (boundry) objects * * Revision 1.3 2001/07/31 13:48:29 peiyongz * fValue removed * * Revision 1.2 2001/07/27 20:43:53 peiyongz * copy ctor: to check for special types. * * Revision 1.1 2001/07/26 20:41:37 peiyongz * XMLFloat * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XMLFloat.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/NumberFormatException.hpp> #include <xercesc/util/Janitor.hpp> #include <string.h> #include <errno.h> #include <stdlib.h> #include <float.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ctor/dtor // --------------------------------------------------------------------------- XMLFloat::XMLFloat(const XMLCh* const strValue, MemoryManager* const manager) :XMLAbstractDoubleFloat(manager) { init(strValue); } XMLFloat::~XMLFloat() { } void XMLFloat::checkBoundary(const XMLCh* const strValue) { char *nptr = XMLString::transcode(strValue, getMemoryManager()); normalizeDecimalPoint(nptr); ArrayJanitor<char> jan1(nptr, getMemoryManager()); int strLen = strlen(nptr); char *endptr = 0; errno = 0; fValue = strtod(nptr, &endptr); // check if all chars are valid char if ( (endptr - nptr) != strLen) { ThrowXMLwithMemMgr(NumberFormatException, XMLExcepts::XMLNUM_Inv_chars, getMemoryManager()); } // check if overflow/underflow occurs if (errno == ERANGE) { fDataConverted = true; if ( fValue < 0 ) { if (fValue > (-1)*DBL_MIN) { fValue = 0; } else { fType = NegINF; fDataOverflowed = true; } } else if ( fValue > 0) { if (fValue < DBL_MIN ) { fValue = 0; } else { fType = PosINF; fDataOverflowed = true; } } } else { /** * float related checking */ if (fValue < (-1) * FLT_MAX) { fType = NegINF; fDataConverted = true; fDataOverflowed = true; } else if (fValue > (-1)*FLT_MIN && fValue < 0) { fDataConverted = true; fValue = 0; } else if (fValue > 0 && fValue < FLT_MIN ) { fDataConverted = true; fValue = 0; } else if (fValue > FLT_MAX) { fType = PosINF; fDataConverted = true; fDataOverflowed = true; } } } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(XMLFloat) XMLFloat::XMLFloat(MemoryManager* const manager) :XMLAbstractDoubleFloat(manager) { } void XMLFloat::serialize(XSerializeEngine& serEng) { XMLAbstractDoubleFloat::serialize(serEng); } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 234 ] ] ]
0bb62d56d4a486d759e231b36b59c0b9f191e319
ccc3e2995bc64d09b9e88fea8c1c7e2029a60ed8
/SO/Trabalhos/Trabalho 2/tmp_src/31401/GestordePistas/Trabalho2/source/Trab2.cpp
6e41b6ceaed55613897f1c379c9314a94873a36a
[]
no_license
masterzdran/semestre5
e559e93017f5e40c29e9f28466ae1c5822fe336e
148d65349073f8ae2f510b5659b94ddf47adc2c7
refs/heads/master
2021-01-25T10:05:42.513229
2011-02-20T17:46:14
2011-02-20T17:46:14
35,061,115
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,829
cpp
// Trab2.cpp : Defines the entry point for the application. // #include "..\headers\stdafx.h" #include "..\headers\Trab2.h" #include <windowsx.h> #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // criar Dialog do 2º trabalho prático //DialogBox(hInst, MAKEINTRESOURCE(IDD_TRAB2_DIALOG), NULL, About); DialogBox(hInst, MAKEINTRESOURCE(IDD_RUNWAY), NULL, About); return (int) 0; } int Landing_Animate_Id[] = { IDC_AT0, IDC_AT1, IDC_AT2, IDC_AT3, IDC_AT4, IDC_AT5, IDC_AT6, IDC_AT7, IDC_AT8, IDC_AT9, IDC_AT10, IDC_AT11, IDC_AT12, IDC_AT13, IDC_AT14, IDC_AT15, IDC_AT16, IDC_AT17, IDC_AT18, IDC_AT19, IDC_AT20, IDC_AT21, IDC_AT22, IDC_AT23, IDC_AT24, IDC_AT25 }; int Takeoff_Animate_Id[] = { IDC_DS0, IDC_DS1, IDC_DS2, IDC_DS3, IDC_DS4, IDC_DS5, IDC_DS6, IDC_DS7, IDC_DS8, IDC_DS9, IDC_DS10, IDC_DS11, IDC_DS12, IDC_DS13, IDC_DS14, IDC_DS15, IDC_DS16, IDC_DS17, IDC_DS18, IDC_DS19, IDC_DS20, IDC_DS21, IDC_DS22, IDC_DS23, IDC_DS24, IDC_DS25 }; DWORD WINAPI thAviaoAterrar(LPVOID p) { HWND hDlg = (HWND)p; for (int i=0; i < 26; ++i) { Edit_SetText(GetDlgItem(hDlg, Landing_Animate_Id[i]), TEXT("A01")); Sleep(200); Edit_SetText(GetDlgItem(hDlg, Landing_Animate_Id[i]), TEXT(" ")); } return 0; } DWORD WINAPI thAviaoDescolar(LPVOID p) { HWND hDlg = (HWND)p; for (int i=26; i >= 0; --i) { Edit_SetText(GetDlgItem(hDlg, Takeoff_Animate_Id[i]), TEXT("A13")); Sleep(300); Edit_SetText(GetDlgItem(hDlg, Takeoff_Animate_Id[i]), TEXT(" ")); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { static HANDLE hAviaoAterrar; static HANDLE hAviaoDescolar; UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: Edit_SetText(GetDlgItem(hDlg, IDC_EDIT5), TEXT("0")); Edit_SetText(GetDlgItem(hDlg, IDC_EDIT2), TEXT("0")); Edit_SetText(GetDlgItem(hDlg, IDC_EDIT1), TEXT("2")); Edit_SetText(GetDlgItem(hDlg, IDC_EDIT4), TEXT("4")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST4),TEXT("A03")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST4),TEXT("A04")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST4),TEXT("A06")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST4),TEXT("A08")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST1),TEXT("A05")); ListBox_AddString(GetDlgItem(hDlg, IDC_LIST1),TEXT("A07")); //Button_SetCheck(GetDlgItem(hDlg, IDC_CHECK1), TRUE); //Button_SetCheck(GetDlgItem(hDlg, IDC_CHECK2), TRUE); return (INT_PTR)TRUE; case WM_COMMAND: switch ( LOWORD(wParam) ) { case IDC_CREATE_LANDING: CreateThread(NULL, 0, thAviaoAterrar, (LPVOID)hDlg, 0, NULL); break; case IDC_CREATE_TAKEOFF: CreateThread(NULL, 0, thAviaoDescolar, (LPVOID)hDlg, 0, NULL); break; break; case IDCANCEL: EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "nuno.cancelo@b139f23c-5e1e-54d6-eab5-85b03e268133" ]
[ [ [ 1, 122 ] ] ]
1e6a2e5c384293aa7399ea7979ce5179d3f0dca3
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/spot_native_Microsoft_SPOT_Math_mshl.cpp
9b4df931e79c533d13e072a8a4e1d12d3d33db26
[ "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
1,244
cpp
//----------------------------------------------------------------------------- // // ** DO NOT EDIT THIS FILE! ** // This file was generated by a tool // re-running the tool will overwrite this file. // //----------------------------------------------------------------------------- #include "spot_native.h" #include "spot_native_Microsoft_SPOT_Math.h" using namespace Microsoft::SPOT; HRESULT Library_spot_native_Microsoft_SPOT_Math::Cos___STATIC__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 0, param0 ) ); INT32 retVal = Math::Cos( param0, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT32( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_native_Microsoft_SPOT_Math::Sin___STATIC__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 0, param0 ) ); INT32 retVal = Math::Sin( param0, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT32( stack, retVal ); } TINYCLR_NOCLEANUP(); }
[ [ [ 1, 44 ] ] ]
df69484063d085e16c7f307743ca35c0a0759c82
ee2f2896bed8455be9564b88666b18ad5eaf9386
/Server/Emu-CV/Emgu.CV.SourceAndExample-1.5.0.1/src/Emgu.CV.Extern/cvSVM.cpp
46f9bac2e9d5ab42d9bcaa43c12da5e0d253f672
[]
no_license
ajdabiya/Pikling
512b190f0e810818ad9f1b68c2001a2b2095d6e9
f58082b0be767994ea09e64613b83eea3e9b1497
refs/heads/master
2023-03-18T18:08:40.528800
2011-06-08T03:46:53
2011-06-08T03:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,608
cpp
#include "cvextern.h" CvSVM* CvSVMDefaultCreate() { return new CvSVM(); } void CvSVMRelease(CvSVM* model) { model->~CvSVM(); } bool CvSVMTrain(CvSVM* model, const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, CvSVMParams _params) { return model->train(_train_data, _responses, _var_idx, _sample_idx, _params); } void CvSVMGetDefaultGrid(int gridType, CvParamGrid* grid) { CvParamGrid defaultGrid = CvSVM::get_default_grid(gridType); grid->max_val = defaultGrid.max_val; grid->min_val = defaultGrid.min_val; grid->step = defaultGrid.step; } bool CvSVMTrainAuto(CvSVM* model, const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, CvSVMParams _params, int k_fold, CvParamGrid C_grid, CvParamGrid gamma_grid, CvParamGrid p_grid, CvParamGrid nu_grid, CvParamGrid coef_grid, CvParamGrid degree_grid) { return model->train_auto(_train_data, _responses, _var_idx, _sample_idx, _params, k_fold, C_grid, gamma_grid, p_grid, nu_grid, coef_grid, degree_grid); } float cvSVMPredict(CvSVM* model, const CvMat* _sample ) { return model->predict(_sample); } const float* cvSVMGetSupportVector(CvSVM* model, int i) { return model->get_support_vector(i); } int cvSVMGetSupportVectorCount(CvSVM* model) { return model->get_support_vector_count(); } int cvSVMGetVarCount(CvSVM* model) { return model->get_var_count(); }
[ [ [ 1, 58 ] ] ]
acbe587fe873f7f9e90c1815e76e1bf6e2083dbc
a6f42311df3830117e9590e446b105db78fdbd3a
/src/framework/base/String.hpp
97c0d348dd8e4e5418669e869cb730d8e16f6536
[]
no_license
wellsoftware/temporal-lightfield-reconstruction
a4009b9da01b93d6d77a4d0d6830c49e0d4e225f
8d0988b5660ba0e53d65e887a51e220dcbc985ca
refs/heads/master
2021-01-17T23:49:05.544012
2011-09-25T10:47:49
2011-09-25T10:47:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,459
hpp
/* * Copyright (c) 2009-2011, NVIDIA Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA Corporation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 <COPYRIGHT HOLDER> 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 "base/Array.hpp" #include <stdarg.h> namespace FW { //------------------------------------------------------------------------ class String { public: String (void) {} String (char chr) { set(chr); } String (const char* chars) { set(chars); } String (const String& other) { set(other); } String (S32 value) { setf("%d", value); } String (F64 value) { setf("%g", value); } ~String (void) {} int getLength (void) const { return max(m_chars.getSize() - 1, 0); } char getChar (int idx) const { FW_ASSERT(idx < getLength()); return m_chars[idx]; } const char* getPtr (void) const { return (m_chars.getSize()) ? m_chars.getPtr() : ""; } String& reset (void) { m_chars.reset(); return *this; } String& set (char chr); String& set (const char* chars); String& set (const String& other) { m_chars = other.m_chars; return *this; } String& setf (const char* fmt, ...); String& setfv (const char* fmt, va_list args); String substring (int start, int end) const; String substring (int start) const { return substring(start, getLength()); } String trimStart (void) const; String trimEnd (void) const; String trim (void) const; void split (char chr, Array<String>& pieces, bool includeEmpty = false) const; String& clear (void) { m_chars.clear(); } String& append (char chr); String& append (const char* chars); String& append (const String& other); String& appendf (const char* fmt, ...); String& appendfv (const char* fmt, va_list args); String& compact (void) { m_chars.compact(); } int indexOf (char chr) const { return m_chars.indexOf(chr); } int indexOf (char chr, int fromIdx) const { return m_chars.indexOf(chr, fromIdx); } int lastIndexOf (char chr) const { return m_chars.lastIndexOf(chr); } int lastIndexOf (char chr, int fromIdx) const { return m_chars.lastIndexOf(chr, fromIdx); } String toUpper (void) const; String toLower (void) const; bool startsWith (const String& str) const; bool endsWith (const String& str) const; String getFileName (void) const; String getDirName (void) const; char operator[] (int idx) const { return getChar(idx); } String& operator= (const String& other) { set(other); return *this; } String& operator+= (char chr) { append(chr); return *this; } String& operator+= (const String& other) { append(other); return *this; } String operator+ (char chr) const { return String(*this).append(chr); } String operator+ (const String& other) const { return String(*this).append(other); } bool operator== (const char* chars) const { return (strcmp(getPtr(), chars) == 0); } bool operator== (const String& other) const { return (strcmp(getPtr(), other.getPtr()) == 0); } bool operator!= (const char* chars) const { return (strcmp(getPtr(), chars) != 0); } bool operator!= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) != 0); } bool operator< (const char* chars) const { return (strcmp(getPtr(), chars) < 0); } bool operator< (const String& other) const { return (strcmp(getPtr(), other.getPtr()) < 0); } bool operator> (const char* chars) const { return (strcmp(getPtr(), chars) > 0); } bool operator> (const String& other) const { return (strcmp(getPtr(), other.getPtr()) > 0); } bool operator>= (const char* chars) const { return (strcmp(getPtr(), chars) <= 0); } bool operator>= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) <= 0); } bool operator<= (const char* chars) const { return (strcmp(getPtr(), chars) >= 0); } bool operator<= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) >= 0); } private: static int strlen (const char* chars); static int strcmp (const char* a, const char* b); private: Array<char> m_chars; }; //------------------------------------------------------------------------ String getDateString (void); bool parseSpace (const char*& ptr); bool parseChar (const char*& ptr, char chr); bool parseLiteral (const char*& ptr, const char* str); bool parseInt (const char*& ptr, S32& value); bool parseInt (const char*& ptr, S64& value); bool parseHex (const char*& ptr, U32& value); bool parseFloat (const char*& ptr, F32& value); //------------------------------------------------------------------------ }
[ [ [ 1, 129 ] ] ]
a632e7e90cb541a7e8995569519ad206fe2305e1
e192bb584e8051905fc9822e152792e9f0620034
/tags/sources_0_1/univers/vaisseau.h
5094ebf7969fae87b0b10bc7771a0749968d2aca
[]
no_license
BackupTheBerlios/projet-univers-svn
708ffadce21f1b6c83e3b20eb68903439cf71d0f
c9488d7566db51505adca2bc858dab5604b3c866
refs/heads/master
2020-05-27T00:07:41.261961
2011-07-31T20:55:09
2011-07-31T20:55:09
40,817,685
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,674
h
/*************************************************************************** * Copyright (C) 2004 by Equipe Projet Univers * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef _PU_UNIVERS_VAISSEAU_H_ #define _PU_UNIVERS_VAISSEAU_H_ #include "ensemble_composition.h" #include "composition.h" #include "bien.h" #include "objet_physique.h" namespace ProjetUnivers { namespace Univers { class Composant ; /* CLASS Vaisseau Représente un vaisseau. TYPE_DE_CLASSE Objet Concret */ class Vaisseau : public Bien, public Noyau::ObjetPhysique { public: // ******************* // GROUP: Construction // ******************* /////////////////// // constructeur. Vaisseau() ; ////////////////// // Ajoute un composant. void AjouterComposant(Composant* _composant) ; protected: private: // **************** // GROUP: Attributs // **************** //////////////// // Les composants du vaisseau. Base::EnsembleComposition< Composant > composants ; //////////////// // Le fabriquant // Association< Groupe > fabriquant ; }; } } #endif
[ "rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73" ]
[ [ [ 1, 93 ] ] ]
4414cc25a2f9f329d532c12fb543d7827620403a
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/lib/boost/gil/extension/io_new/pnm_io_old.hpp
386c5b1ad065b479786f008716deca23c9b94793
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
6,128
hpp
/* Copyright 2008 Christian Henning Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_IO_PNM_IO_OLD_HPP_INCLUDED #define BOOST_GIL_EXTENSION_IO_PNM_IO_OLD_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning \n /// /// \date 2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include "pnm_all.hpp" namespace boost { namespace gil { /// \ingroup PNM_IO /// \brief Returns the width and height of the PNM file at the specified location. /// Throws std::ios_base::failure if the location does not correspond to a valid PNM file template< typename String > inline point2< std::ptrdiff_t > pnm_read_dimensions( const String& filename ) { image_read_info< pnm_tag > info = read_image_info( filename , pnm_tag() ); return point2< std::ptrdiff_t >( info._width , info._height ); } /// \ingroup PNM_IO /// \brief Loads the image specified by the given pnm image file name into the given view. /// Triggers a compile assert if the view color space and channel depth are not supported by the PNM library or by the I/O extension. /// Throws std::ios_base::failure if the file is not a valid PNM file, or if its color space or channel depth are not /// compatible with the ones specified by View, or if its dimensions don't match the ones of the view. template< typename String , typename View > inline void pnm_read_view( const String& filename , const View& view ) { read_view( filename , view , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Allocates a new image whose dimensions are determined by the given pnm image file, and loads the pixels into it. /// Triggers a compile assert if the image color space or channel depth are not supported by the PNM library or by the I/O extension. /// Throws std::ios_base::failure if the file is not a valid PNM file, or if its color space or channel depth are not /// compatible with the ones specified by Image template< typename String , typename Image > inline void pnm_read_image( const String& filename , Image& img ) { read_image( filename , img , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Loads and color-converts the image specified by the given pnm image file name into the given view. /// Throws std::ios_base::failure if the file is not a valid PNM file, or if its dimensions don't match the ones of the view. template< typename String , typename View , typename CC > inline void pnm_read_and_convert_view( const String& filename , const View& view , CC cc ) { read_and_convert_view( filename , view , cc , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Loads and color-converts the image specified by the given pnm image file name into the given view. /// Throws std::ios_base::failure if the file is not a valid PNM file, or if its dimensions don't match the ones of the view. template< typename String , typename View > inline void pnm_read_and_convert_view( const String& filename , const View& view ) { read_and_convert_view( filename , view , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Allocates a new image whose dimensions are determined by the given pnm image file, loads and color-converts the pixels into it. /// Throws std::ios_base::failure if the file is not a valid PNM file template< typename String , typename Image , typename CC > inline void pnm_read_and_convert_image( const String& filename , Image& img , CC cc ) { read_and_convert_image( filename , img , cc , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Allocates a new image whose dimensions are determined by the given pnm image file, loads and color-converts the pixels into it. /// Throws std::ios_base::failure if the file is not a valid PNM file template< typename String , typename Image > inline void pnm_read_and_convert_image( const String filename , Image& img ) { read_and_convert_image( filename , img , pnm_tag() ); } /// \ingroup PNM_IO /// \brief Saves the view to a pnm file specified by the given pnm image file name. /// Triggers a compile assert if the view color space and channel depth are not supported by the PNM library or by the I/O extension. /// Throws std::ios_base::failure if it fails to create the file. template< typename String , typename View > inline void pnm_write_view( const String& filename , const View& view ) { write_view( filename , view , pnm_tag() ); } } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_IO_PNM_IO_OLD_HPP_INCLUDED
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 180 ] ] ]
b09db277840314c2c9ee846f2afbe734a0262075
215fd760efb591ab13e10c421686fef079d826e1
/lib/p4api/include/p4/pathsys.h
239fdeea5dcef1760bb6eb5461b0802e2d930d79
[]
no_license
jairbubbles/P4.net
2021bc884b9940f78e94b950e22c0c4e9ce8edca
58bbe79b30593134a9306e3e37b0b1aab8135ed0
refs/heads/master
2020-12-02T16:21:15.361000
2011-02-15T19:28:31
2011-02-15T19:28:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,576
h
/* * Copyright 1995, 2003 Perforce Software. All rights reserved. * * This file is part of Perforce - the FAST SCM System. */ /* * PathSys.h - OS specific pathnames * * Public classes: * * PathSys - a StrBuf with virtual path manipulations * * Public methods: * * StrBuf::Set() - set value in local syntax * StrBuf::Text() - get value in local syntax * * PathSys::SetCanon() - combine (local) root and canonical path * PathSys::SetLocal() - combine (local) root and local path * * If root is empty, local is used. * If local is empty, results are not defined. * Local can begin with relative references. * * PathSys::GetCanon() - strip root and return rest as canon * PathSys::ToParent() - strip (and return) last element of path * * NB: SetLocal() can take "this" as root, but SetCanon() cannot. * * Static functions: * * Create() - returns an appropriate PathSys, given an OS type flag. * GetOS() - returns a string for the OS name */ class PathSys : public StrBuf { public: virtual ~PathSys(); virtual void SetCanon( const StrPtr &root, const StrPtr &canon ) = 0; virtual void SetLocal( const StrPtr &root, const StrPtr &local ) = 0; virtual int GetCanon( const StrPtr &root, StrBuf &t ) = 0; virtual int ToParent( StrBuf *file = 0 ) = 0; virtual void SetCharSet( int = 0 ); void Expand(); static PathSys *Create(); static PathSys *Create( const StrPtr &os, Error *e ); static const char *GetOS(); private: static PathSys *Create( int os ); } ;
[ [ [ 1, 58 ] ] ]
a0da6033c8be1fed678f0b8470c815361461efd6
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/BjDlgAddData.h
47e658cd24c4d1d9361e28ec98fc0dde4b389478
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
949
h
#if !defined(AFX_BJDLGADDDATA_H__B92BA8A8_F92A_4C28_BD82_F9BBAFA3174D__INCLUDED_) #define AFX_BJDLGADDDATA_H__B92BA8A8_F92A_4C28_BD82_F9BBAFA3174D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class BjDlgAddData : public CDialog { public: BjDlgAddData(CWnd* pParent = NULL); COLORREF m_color; //{{AFX_DATA(BjDlgAddData) enum { IDD = IDD_BJ_ADD_DATA }; UINT m_nDays; //}}AFX_DATA //{{AFX_VIRTUAL(BjDlgAddData) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL protected: //{{AFX_MSG(BjDlgAddData) afx_msg void OnButtonSet(); virtual void OnOK(); virtual void OnCancel(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BJDLGADDDATA_H__B92BA8A8_F92A_4C28_BD82_F9BBAFA3174D__INCLUDED_)
[ [ [ 1, 43 ] ] ]
1898602dd1bd820f945b450c800e35b2a10b1adc
85e86cd5c3bd0458ae94de3c384d1b07e5a9a0cf
/ExternalWindowTracker.cpp
9c63cc98275718b0dfabce65ebb7b3567fb3a445
[]
no_license
dbv771/Ditto
6fbe858e28d73ae5366b4eb864f6a7d1d90b3383
faa5dda8beafd85eb38f06274c0bc6ec2f1ba462
refs/heads/master
2021-05-27T14:57:38.613868
2011-10-29T05:19:24
2011-10-29T05:19:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,803
cpp
#include "stdafx.h" #include "externalwindowtracker.h" #include "Misc.h" #include "SendKeys.h" #include "Options.h" #include "CP_Main.h" ExternalWindowTracker::ExternalWindowTracker(void) { m_activeWnd = NULL; m_focusWnd = NULL; m_dittoHasFocus = false; } ExternalWindowTracker::~ExternalWindowTracker(void) { } bool ExternalWindowTracker::TrackActiveWnd(HWND focus) { BOOL fromHook = true; HWND newFocus = focus; HWND newActive = ::GetForegroundWindow(); if(newFocus == NULL) { if(AttachThreadInput(GetWindowThreadProcessId(newActive, NULL), GetCurrentThreadId(), TRUE)) { newFocus = GetFocus(); AttachThreadInput(GetWindowThreadProcessId(newActive, NULL), GetCurrentThreadId(), FALSE); } else { //Log(_T("TrackActiveWnd - AttachThreadInput failed")); } fromHook = false; } if(newFocus == 0 && newActive != 0) { newFocus = newActive; } else if(newActive == 0 && newFocus != 0) { newActive = newFocus; } if(newFocus == 0 || !IsWindow(newFocus) || newActive == 0 || !IsWindow(newActive)) { Log(_T("TargetActiveWindow values invalid")); return false; } if(newActive == m_activeWnd) { // Log(_T("TargetActiveWindow window the same")); return false; } if(NotifyTrayhWnd(newActive) || NotifyTrayhWnd(newFocus)) { Log(_T("TargetActiveWindow shell tray icon has active")); return false; } if(IsAppWnd(newFocus) || IsAppWnd(newActive)) { if(m_dittoHasFocus == false) { Log(StrF(_T("Ditto has focus - Active: %s (%d), Focus: %s (%d), FromHook %d"), WndName(m_activeWnd), m_activeWnd, WndName(m_focusWnd), m_focusWnd, fromHook)); } m_dittoHasFocus = true; return false; } m_focusWnd = newFocus; m_activeWnd = newActive; m_dittoHasFocus = false; if(theApp.QPasteWnd()) theApp.QPasteWnd()->UpdateStatus(true); Log(StrF(_T("TargetActiveWindow Active: %s (%d), Focus: %s (%d), FromHook %d"), WndName(m_activeWnd), m_activeWnd, WndName(m_focusWnd), m_focusWnd, fromHook)); return true; } bool ExternalWindowTracker::WaitForActiveWnd(HWND activeWnd, int timeout) { DWORD start = GetTickCount(); while(((int)(GetTickCount() - start)) < timeout) { if(::GetForegroundWindow() == activeWnd) { Log(StrF(_T("found focus wait %d"), GetTickCount()-start)); return true; } Sleep(0); ActivateTarget(); } Log(_T("Didn't find focus")); return false; } void ExternalWindowTracker::ActivateFocus(const HWND activeHwnd, const HWND focushWnd) { CString csApp = GetProcessName(m_activeWnd); Log(StrF(_T("SetFocus - AppName: %s, Active: %d, Focus: %d"), csApp, m_activeWnd, m_focusWnd)); if (focushWnd != NULL) { AttachThreadInput(GetWindowThreadProcessId(activeHwnd, NULL), GetCurrentThreadId(), TRUE); if (GetFocus() != focushWnd) { SetFocus(focushWnd); } AttachThreadInput(GetWindowThreadProcessId(activeHwnd, NULL), GetCurrentThreadId(), FALSE); } } bool ExternalWindowTracker::NotifyTrayhWnd(HWND hWnd) { HWND hParent = hWnd; int nCount = 0; while(hParent != NULL) { TCHAR className[100]; GetClassName(hParent, className, (sizeof(className) / sizeof(TCHAR))); if((STRCMP(className, _T("Shell_TrayWnd")) == 0) || (STRCMP(className, _T("NotifyIconOverflowWindow")) == 0) || (STRCMP(className, _T("TrayNotifyWnd")) == 0)) { return true; } hParent = ::GetParent(hParent); if(hParent == NULL) break; nCount++; if(nCount > 100) { Log(_T("GetTargetName reached maximum search depth of 100")); break; } } return false; } bool ExternalWindowTracker::ActivateTarget() { Log(StrF(_T("Activate Target - Active: %d, Focus: %d"), m_activeWnd, m_focusWnd)); if (IsIconic(m_activeWnd)) { ShowWindow(m_activeWnd, SW_RESTORE); } // Save specified timeout period... DWORD timeoutMS = 0; SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &timeoutMS, 0); // ... then set it to zero to disable it SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)0, 0); //If we are doing this and we are not the current foreground window then attach to the current bef //setting the focus window //this shouldn't happen that much, most of the time we are the foreground window bool detach = false; DWORD foreGroundProcessId = GetWindowThreadProcessId(::GetForegroundWindow(), NULL); if(foreGroundProcessId != GetCurrentThreadId()) { Log(_T("Attach to process, calling set foreground from non forground window")); if(AttachThreadInput(foreGroundProcessId, GetCurrentThreadId(), TRUE)) { detach = true; } } BringWindowToTop(m_activeWnd); SetForegroundWindow(m_activeWnd); if(detach) { AttachThreadInput(foreGroundProcessId, GetCurrentThreadId(), FALSE); } //check to see if this app should set focus //this is off by default CString csApp = GetProcessName(m_activeWnd); if(g_Opt.GetSetFocusToApp(csApp)) { ActivateFocus(m_activeWnd, m_focusWnd); } SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)timeoutMS, 0); return true; } void ExternalWindowTracker::SendPaste(bool activateTarget) { HWND activeWnd = m_activeWnd; CSendKeys send; send.AllKeysUp(); if(activateTarget == false) { activeWnd = ::GetForegroundWindow(); } CString csPasteToApp = GetProcessName(activeWnd); CString csPasteString = g_Opt.GetPasteString(csPasteToApp); DWORD delay = g_Opt.SendKeysDelay(); if(activateTarget) { ActivateTarget(); theApp.PumpMessageEx(); WaitForActiveWnd(activeWnd, max(25, g_Opt.WaitForActiveWndTimeout())); } else { theApp.PumpMessageEx(); } m_dittoHasFocus = false; Log(StrF(_T("Sending paste to app %s key stroke: %s, SeDelay: %d"), csPasteToApp, csPasteString, delay)); Sleep(delay); send.SetKeyDownDelay(max(50, delay)); send.SendKeys(csPasteString, true); Log(_T("Post sending paste")); } void ExternalWindowTracker::SendCopy() { CSendKeys send; send.AllKeysUp(); CString csToApp = GetProcessName(m_activeWnd); CString csString = g_Opt.GetCopyString(csToApp); DWORD delay = g_Opt.SendKeysDelay(); Sleep(delay); theApp.PumpMessageEx(); Log(StrF(_T("Sending copy to app %s key stroke: %s, Delay: %d"), csToApp, csString, delay)); //give the app some time to take focus before sending paste Sleep(delay); send.SetKeyDownDelay(max(50, delay)); send.SendKeys(csString, true); Log(_T("Post sending copy")); } // sends Ctrl-X to the TargetWnd void ExternalWindowTracker::SendCut() { CSendKeys send; send.AllKeysUp(); CString csToApp = GetProcessName(m_activeWnd); CString csString = g_Opt.GetCopyString(csToApp); DWORD delay = g_Opt.SendKeysDelay(); Sleep(delay); theApp.PumpMessageEx(); Log(StrF(_T("Sending cut to app %s key stroke: %s, Delay: %d"), csToApp, csString, delay)); //give the app some time to take focus before sending paste Sleep(delay); send.SetKeyDownDelay(max(50, delay)); send.SendKeys(csString, true); Log(_T("Post sending cut")); } CString ExternalWindowTracker::ActiveWndName() { return WndName(m_activeWnd); } CString ExternalWindowTracker::WndName(HWND hWnd) { TCHAR cWindowText[200]; HWND hParent = hWnd; ::GetWindowText(hParent, cWindowText, 100); int nCount = 0; while(STRLEN(cWindowText) <= 0) { hParent = ::GetParent(hParent); if(hParent == NULL) break; ::GetWindowText(hParent, cWindowText, 100); nCount++; if(nCount > 100) { Log(_T("GetTargetName reached maximum search depth of 100")); break; } } return cWindowText; } bool ExternalWindowTracker::ReleaseFocus() { if( IsAppWnd(::GetForegroundWindow()) ) { return ActivateTarget(); } return false; } CPoint ExternalWindowTracker::FocusCaret() { CPoint pt(-1, -1); if(m_activeWnd) { GUITHREADINFO guiThreadInfo; guiThreadInfo.cbSize = sizeof(GUITHREADINFO); DWORD OtherThreadID = GetWindowThreadProcessId(m_activeWnd, NULL); if(GetGUIThreadInfo(OtherThreadID, &guiThreadInfo)) { CRect rc(guiThreadInfo.rcCaret); if(rc.IsRectEmpty() == FALSE) { pt = rc.BottomRight(); ::ClientToScreen(m_focusWnd, &pt); } } if(pt.x < 0 || pt.y < 0) { if(m_focusWnd != NULL && m_activeWnd != NULL && AttachThreadInput(GetWindowThreadProcessId(m_activeWnd, NULL), GetCurrentThreadId(), TRUE)) { BOOL ret = GetCaretPos(&pt); if(ret && (pt.x > 0 || pt.y > 0)) { ClientToScreen(m_focusWnd, &pt); pt.y += 20; } AttachThreadInput(GetWindowThreadProcessId(m_activeWnd, NULL), GetCurrentThreadId(), FALSE); } } } return pt; }
[ "sabrogden@d0e771a7-b16f-4c6e-81b0-f3fd8ace72c5" ]
[ [ [ 1, 376 ] ] ]
0dfefd0c235f26fd5f4e1ba4111bd81c277b0552
d2996420f8c3a6bbeef63a311dd6adc4acc40436
/src/client/ClientNetworkHandler.cpp
266b04feb7ea13616b1e8435c4e36a4b9bdaa0e5
[]
no_license
aruwen/graviator
4d2e06e475492102fbf5d65754be33af641c0d6c
9a881db9bb0f0de2e38591478429626ab8030e1d
refs/heads/master
2021-01-19T00:13:10.843905
2011-03-13T13:15:25
2011-03-13T13:15:25
32,136,578
0
0
null
null
null
null
UTF-8
C++
false
false
6,069
cpp
#include "ClientNetworkHandler.h" #include "..\vec3f.h" #include <string> #include <cstdlib> ClientNetworkHandler::ClientNetworkHandler( ClientObjectManager *objectManager, ClientInputManager *inputManager) : mObjectManager(objectManager), mInputMangager(inputManager), mConnection(&mSocket) { mIsRunning = false; mIsSearchingForServer = false; mSearchingTimeout = 10.0f; mSearchingInterval = 1.0f; initializeSockets(); } ClientNetworkHandler::~ClientNetworkHandler(void) { stop(); shutdownSockets(); } bool ClientNetworkHandler::start(unsigned int port) { if (mIsRunning) return false; if ( !mSocket.open(port) ) return false; mIsRunning = true; return true; } void ClientNetworkHandler::connectToIp( const Address &address ) { if (mIsRunning) { mConnection.connect(address); } } void ClientNetworkHandler::connectToFirstResponingServer() { if (!mIsRunning) return; bool result = mMulticastSender.open( Address(225,1,1,1,1337) ); string portString = toString(mSocket.getPort()); mMulticastSender.send(portString.c_str(), portString.size()); mIsSearchingForServer = true; mSearchingTimeoutTimer.start(); mSearchingIntervalTimer.start(); } void ClientNetworkHandler::stop() { if (mIsRunning) { mSocket.close(); mMulticastSender.close(); mIsRunning = false; } } void ClientNetworkHandler::handleConnection() { while(!mConnection.isDisconnected() && !mConnection.hasConnectFailed() || mIsSearchingForServer) { Sleep(20); processReadReady(); mConnection.update(); unsigned int id = mConnection.getId(); if (id != 0) mObjectManager->setPlayerId(id); if (mIsSearchingForServer && mSearchingTimeoutTimer.getTime() > mSearchingTimeout) { mIsSearchingForServer = false; mConnection.disconnect(); mSearchingIntervalTimer.reset(); mSearchingIntervalTimer.reset(); } else if (mIsSearchingForServer && mSearchingIntervalTimer.getTime() > mSearchingInterval) { mSearchingIntervalTimer.restart(); string portString = toString(mSocket.getPort()); mMulticastSender.send(portString.c_str(), portString.size()); } else { string dataString = parseInfoToDataString(mInputMangager->getControlInfo()); mConnection.sendData(dataString); parseData(); } } mObjectManager->setQuitWithConnectionFailure(true); } void ClientNetworkHandler::processReadReady() { int receivedBytes = 0; Address sender; char data[1024]; string dataString = data; int size = 1024; memset(data, 0, 1024); receivedBytes = mSocket.receive(sender, data, size); while (receivedBytes > 0) { dataString = data; if (mIsSearchingForServer) { // TODO: handle more information from server if (dataString == "I_AM_A_SERVER") { mIsSearchingForServer = false; connectToIp(sender); return; } } else if (sender == mConnection.getAddress()) { mConnection.handleIncomming(dataString); } memset(data, 0, 1024); receivedBytes = mSocket.receive(sender, data, size); } } void ClientNetworkHandler::parseData() { string dataString = mConnection.getData(); while(dataString.size() > 0) { string debugString = dataString; int id = atoi( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); char type = dataString.substr(0, dataString.find(',')).c_str()[0]; dataString = dataString.substr(dataString.find(',')+1); if ((type != 'p') && (type != 'e') && (type != 'g') && (type != 's') && (type != 'r') && (type != 'c') && (type != 'd')) { dataString = mConnection.getData(); continue; } vec3f position; position.x = (float)atof( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); position.y = (float)atof( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); position.z = (float)atof( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); vec3f alignment; alignment.x = (float)atof( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); alignment.y = (float)atof( dataString.substr(0, dataString.find(',')).c_str() ); dataString = dataString.substr(dataString.find(',')+1); alignment.z = (float)atof( dataString.substr(0, dataString.find(';')).c_str() ); dataString = dataString.substr(dataString.find(';')+1); mObjectManager->handleInput(id, type, position, alignment); dataString = mConnection.getData(); } } string ClientNetworkHandler::parseInfoToDataString(ClientControlInfo &info) { string returnString; returnString += toString(info.left) + ","; returnString += toString(info.right) + ","; returnString += toString(info.fire) + ","; returnString += toString(info.cameraVector.x) + ","; returnString += toString(info.cameraVector.y) + ","; returnString += toString(info.cameraVector.z); return returnString; }
[ "[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867" ]
[ [ [ 1, 219 ] ] ]
00d80310938b62ea771d154e802ea3344dd928a6
885fc5f6e056abe95996b4fc6eebef06a94d50ce
/src/FFMpegVideoDecoder.cpp
c5d36993dfce15a95b5f31e4b4d096a4ebf82fac
[]
no_license
jdzyzh/ffmpeg-wrapper
bdf0a6f15db2625b2707cbac57d5bfaca6396e3d
5185bb3695df9adda59f7f849095314f16b2bd48
refs/heads/master
2021-01-10T08:58:06.519741
2011-11-30T06:32:50
2011-11-30T06:32:50
54,611,386
1
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
#include "FFMpegVideoDecoder.h" FFMpegVideoDecoder::FFMpegVideoDecoder(char* codecName) { codec =avcodec_find_decoder_by_name(codecName); if (!codec) { fprintf(stderr,"failed to find decoder: %s\n",codecName); } ctx = avcodec_alloc_context(); decodedFrame = avcodec_alloc_frame(); avcodec_open(ctx,codec); AVPacket avpkt; av_init_packet(&avpkt); } int FFMpegVideoDecoder::decode(unsigned char* inBuf,int inBufSize,unsigned char* outBuf,int outBufSize) { int gotPic = 0; int ret = avcodec_decode_video(ctx,decodedFrame,&gotPic,inBuf,inBufSize); return ret; }
[ "ransomhmc@6544afd8-f103-2cf2-cfd9-24e348754d5f" ]
[ [ [ 1, 28 ] ] ]
1f632aad9d7dff28eb5a754d6e50c565c1a57ea6
0ee189afe953dc99825f55232cd52b94d2884a85
/mstd/atomic_pod.cpp
35d5c074c6520b72817b0af6debdf428b691793d
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#if !defined(_STLP_NO_IOSTREAMS) #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4244) #endif #include <boost/thread/thread.hpp> #if defined(_MSC_VER) #pragma warning(pop) #endif #include "atomic_pod.hpp" namespace mstd { void atomic_pod_base::yield() const { boost::this_thread::yield(); } } #endif
[ [ [ 1, 25 ] ] ]
38020c010db043e2bc6d28995728e2e4216703ff
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Client/Dimensions/SpineCrank.cpp
9baefd44ea78784cb073520258e618ddacd2ba0a
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
#include "StdAfx.h" #include "SpineCrank.h" #include "playercharacter.h" #include "Grid.h" #include "Level.h" SpineCrank::SpineCrank(void) { m_fBaseSpeed = 0.0f; } SpineCrank::~SpineCrank(void) { } bool SpineCrank::Activate(PlayerCharacter *pSkillOwner) { if( Skill::Activate(pSkillOwner) ) { m_fSpeed = m_fBaseSpeed + (pSkillOwner->GetStr() / 50 ); //see if we can instantly kill enemy int iTargetTile = g_pGameState->GetLevel()->GetGrid()->GetTileAtLocation(pSkillOwner->GetLocation() + pSkillOwner->GetHeading()); m_pTarget = g_pGameState->GetLevel()->GetGrid()->GetActor(iTargetTile); if( !m_pTarget && !m_pTarget->HasFlag(ATTACKABLE) ) { m_bReady = true; return false; } int iDeathChance = rand() % 2; if( iDeathChance == 1 ) { m_pTarget->SetCurrentHealth(-1); m_fElaspedSinceCast = m_fSpeed; } return true; } return false; }
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 44 ] ] ]
8f98107487218736af3e74d330fd41bbaafe8b67
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/Shader/ShaderObject.h
9d19d31b2d4a5f61feee2a27e0da7502bd3c5234
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
997
h
#pragma once #include <Depends/Entity/Property.h> namespace Engine { namespace Core { class CoreManager; } namespace Shader { enum ShaderType { V_SHADER, F_SHADER }; class ShaderObject { public: ShaderObject(Engine::Core::CoreManager *coreMgr); virtual ~ShaderObject(){} virtual bool isShaderSet() const { return isSet; } virtual bool isShaderInitialized() const { return initialized; } virtual bool setShader(const CL_String &filename); virtual bool initShader(); virtual void enableShader(); virtual void disableShader(); virtual unsigned int getShaderProg() const { return prog; } protected: int shaderSize(const CL_String &fileName, ShaderType shaderType); int readShader(const CL_String &fileName, ShaderType shaderType, char *shaderText, int size); Engine::Core::CoreManager *coreMgr; bool isSet, initialized; unsigned int vs, fs, prog; char *vertexShaderSource, *fragmentShaderSource; }; }}
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 43 ] ] ]
14f57ac8be1eb219380513c220c15c55bd796455
545dec4462a2febe8e9db02496369b1e8022c6a5
/inc/nvGlutWidgets.h
b0b4174b4c0e6e5d1666de330be244afc52c1088
[]
no_license
andrey-malets/opencl-usu-2009
6d1bcca084c1038249603b35cf09ffc74792af7e
a896419258c98853e90e25afe217b4084131bd1a
refs/heads/master
2020-04-14T07:37:25.561928
2009-12-21T09:51:23
2009-12-21T09:51:23
32,697,173
0
0
null
null
null
null
UTF-8
C++
false
false
5,023
h
/* * Copyright 1993-2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property and * proprietary rights in and to this software and related documentation. * Any use, reproduction, disclosure, or distribution of this software * and related documentation without an express license agreement from * NVIDIA Corporation is strictly prohibited. * * Please refer to the applicable NVIDIA end user license agreement (EULA) * associated with this source code for terms and conditions that govern * your use of this NVIDIA software. * */ // // nvGlutWidgets // // Adaptor classes to integrate the nvWidgets UI library with the GLUT windowing // toolkit. The adaptors convert native GLUT UI data to native nvWidgets data. All // adaptor classes are implemented as in-line code in this header. The adaptor // defaults to using the standard OpenGL paintor implementation. // // Author: Ignacio Castano, Samuel Gateau, Evan Hart // Email: [email protected] // // Copyright (c) NVIDIA Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef NV_GLUT_WIDGETS_H #define NV_GLUT_WIDGETS_H #include <GL/glut.h> #include <nvGLWidgets.h> namespace nv { class GlutUIContext : public UIContext { protected: bool _ownPainter; public: // // Default UI constructor // // Creates private OpenGL painter ////////////////////////////////////////////////////////////////// GlutUIContext() : UIContext( *(new GLUIPainter()) ), _ownPainter(true) { } // // Alternate UI constructor // // Allows for overriding the standard painter ////////////////////////////////////////////////////////////////// GlutUIContext(UIPainter& painter) : UIContext( painter ), _ownPainter(false) { } // // UI destructor // // Destroy painter if it is private ////////////////////////////////////////////////////////////////// ~GlutUIContext() { if (_ownPainter) delete getPainter(); } // // UI method for processing GLUT mouse button events // // Call this method from the glutMouseFunc callback, the // modifier parameter maps to glutGetModifiers. ////////////////////////////////////////////////////////////////// virtual void mouse(int button, int state, int modifier, int x, int y) { int modifierMask = 0; if ( button == GLUT_LEFT_BUTTON) button = MouseButton_Left; else if ( button == GLUT_MIDDLE_BUTTON) button = MouseButton_Middle; else if ( button == GLUT_RIGHT_BUTTON) button = MouseButton_Right; if ( modifier & GLUT_ACTIVE_ALT) modifierMask |= ButtonFlags_Alt; if ( modifier & GLUT_ACTIVE_SHIFT) modifierMask |= ButtonFlags_Shift; if ( modifier & GLUT_ACTIVE_CTRL) modifierMask |= ButtonFlags_Ctrl; if ( state == GLUT_DOWN) state = 1; else state = 0; UIContext::mouse( button, state, modifierMask, x, y); } // // UI method for processing key events // // Call this method from the glutReshapeFunc callback ////////////////////////////////////////////////////////////////// void specialKeyboard(int k, int x, int y) { UIContext::keyboard( translateKey(k), x, y); } // // Translate non-ascii keys from GLUT to nvWidgets ////////////////////////////////////////////////////////////////// unsigned char translateKey( int k ) { switch (k) { case GLUT_KEY_F1 : return Key_F1; case GLUT_KEY_F2 : return Key_F2; case GLUT_KEY_F3 : return Key_F3; case GLUT_KEY_F4 : return Key_F4; case GLUT_KEY_F5 : return Key_F5; case GLUT_KEY_F6 : return Key_F6; case GLUT_KEY_F7 : return Key_F7; case GLUT_KEY_F8 : return Key_F8; case GLUT_KEY_F9 : return Key_F9; case GLUT_KEY_F10 : return Key_F10; case GLUT_KEY_F11 : return Key_F11; case GLUT_KEY_F12 : return Key_F12; case GLUT_KEY_LEFT : return Key_Left; case GLUT_KEY_UP : return Key_Up; case GLUT_KEY_RIGHT : return Key_Right; case GLUT_KEY_DOWN : return Key_Down; case GLUT_KEY_PAGE_UP : return Key_PageUp; case GLUT_KEY_PAGE_DOWN : return Key_PageDown; case GLUT_KEY_HOME : return Key_Home; case GLUT_KEY_END : return Key_End; case GLUT_KEY_INSERT : return Key_Insert; default: return 0; } } }; }; #endif
[ "[email protected]@78a82cd4-d041-11de-a697-fbeabf64b1f8" ]
[ [ [ 1, 166 ] ] ]
423b1843949d1357d1a5b2be73be6f429a8b352c
3fb39751cdf6bb5c5229c4408cda110e2ae547c1
/src/Instruments.h
a90f381d5c2a831a8b39b10e1df6608d5a279d3c
[]
no_license
josephzizys/CM
7308704f9d33f81938f7aeff31b64fb3d217db24
8f8e9a0550e76debfc47fb0f90772a05ca06805b
refs/heads/master
2020-05-20T11:40:06.824661
2011-06-15T11:47:29
2011-06-15T11:47:29
2,552,460
0
0
null
null
null
null
UTF-8
C++
false
false
311
h
/* (Auto-generated binary data file). */ #ifndef BINARY_INSTRUMENTS_H #define BINARY_INSTRUMENTS_H namespace Instruments { extern const char* ins_xml; const int ins_xmlSize = 11734; extern const char* ins_zip; const int ins_zipSize = 372059; }; #endif
[ "taube@d60aafaf-7936-0410-ba4d-d307febf7868" ]
[ [ [ 1, 16 ] ] ]
6887b47ceea6d86d52287e2a71d725601238e1c4
374d23f6a603046a5299596fc59171dc1c6b09b4
/tensores/vtkMarcacionElipse/vtkPlantillaAjustada.h
e30cd9f721a77acbdb037d1511fb69686a6d991b
[]
no_license
mounyeh/tensorespablo
aa9b403ceef82094872e50f7ddd0cdd89b6b7421
f045a5c1e1decf7302de17f4448abbd284b3c2de
refs/heads/master
2021-01-10T06:09:53.357175
2010-09-19T22:57:16
2010-09-19T22:57:16
51,831,049
1
0
null
null
null
null
ISO-8859-1
C++
false
false
3,314
h
////////////////////////////////////////////////////////////////////////////// // Programa: Visualization Toolkit // // Módulo: vtkPlantillaAjustada.h // // Descripción: A partir de una superficie que aproxima el contorno 3D // // genera una serie de parámetros útiles en nuestro algoritmo. // // Fecha: 2004/09/04 // // Lenguaje: C++ // // Autor: Lucilio Cordero Grande // // ETSI Telecomunicacion, Universidad de Valladolid // // Campus Miguel Delibes, Camino del Cementerio, s/n // // e-mail: [email protected] // ////////////////////////////////////////////////////////////////////////////// // .NOMBRE vtkPlantillaAjustada - genera centro, rayos y radios para cada slice. // .SECCION Descripcion // Lleva a cabo la parametrización que se utiliza para la superficie externa de órgano // en nuestro algoritmo. #ifndef __vtkPlantillaAjustada_h #define __vtkPlantillaAjustada_h #include "vtkMarcacionElipsoideConfigure.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkPolyData.h" #include "vtkStructuredPoints.h" #include "vtkIntArray.h" //class VTK_MARCACIONELIPSOIDE_EXPORT vtkPlantillaAjustada : public vtkObject class vtkPlantillaAjustada : public vtkObject { public: static vtkPlantillaAjustada *New(); vtkTypeMacro(vtkPlantillaAjustada, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); //void GeneraParametros (vtkPlane *); //void IntroducePlantilla (vtkPolyData *); void ObtieneParametros(vtkPolyData *); vtkFloatArray *ObtieneCentro(); vtkStructuredPoints *ObtieneParam(); void IntroducePlano(vtkMatrix4x4 *); void EstableceMascaraElipsoide(vtkIntArray *); vtkPolyData *ConstruyeModelo(vtkStructuredPoints *); vtkStructuredPoints *GeneraRhoNulo(); vtkPolyData *LeeModelo(); /*J=número de rayos*/ vtkSetMacro(J,int); vtkGetMacro(J,int); /*K=número de puntos de la deformación*/ vtkSetMacro(K,int); vtkGetMacro(K,int); /*Slth=distancia entre slices*/ vtkSetMacro(Slth,float); vtkGetMacro(Slth,float); vtkSetMacro(UsimagTool,int); vtkGetMacro(UsimagTool,int); /*P=número de slices de interés*/ vtkGetMacro(P,int); /*Máxima desviación radial*/ vtkSetMacro(drmax,float); vtkGetMacro(drmax,float); /*Limites de la caja de inclusión del ajuste inicial*/ vtkSetVector6Macro(limite,double); vtkGetVector6Macro(limite,double); vtkSetVectorMacro(Max,double,4); vtkGetVectorMacro(Max,double,4); vtkSetVectorMacro(Min,double,4); vtkGetVectorMacro(Min,double,4); vtkSetStringMacro(FichModelo); vtkGetStringMacro(FichModelo); protected: vtkPlantillaAjustada(); ~vtkPlantillaAjustada(); vtkFloatArray *Centro; vtkStructuredPoints *Param; //En la componente 0 esta el angulo y en la 1 el radio. vtkMath *Instrumento; vtkMatrix4x4 *Plano; vtkIntArray *MascaraElipsoide; vtkPolyData *Rinon; int K; int J; int P; int salto; int UsimagTool; float drmax; float Slth; double limite[6]; double Max[4]; double Min[4]; char *FichModelo; }; #endif
[ "diodoledzeppelin@9de476db-11b3-a259-9df9-d52a56463d6f" ]
[ [ [ 1, 109 ] ] ]
5917856b5f7ec7b549acc4525ad7820c17bfb60d
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-04-24/common/edaappl.cpp
f443c78c8244a0f5dcbb7384687d3df3f42d5896
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
16,182
cpp
/***************/ /* edaappl.cpp */ /***************/ /* ROLE: methodes relative a la classe winEDA_App, communes aux environements window et linux */ #define EDA_BASE #define COMMON_GLOBL #include "fctsys.h" #include <wx/image.h> #include "wx/html/htmlwin.h" #include "wx/fs_zip.h" #include "wxstruct.h" #include "macros.h" #include "gr_basic.h" #include "common.h" #include "worksheet.h" #include "id.h" #include "build_version.h" #include "bitmaps.h" #include "Language.xpm" #ifdef __WINDOWS__ /* Icons for language choice (only for Windows)*/ #include "Lang_Default.xpm" #include "Lang_En.xpm" #include "Lang_Es.xpm" #include "Lang_Fr.xpm" #include "Lang_Pt.xpm" #include "Lang_It.xpm" #include "Lang_De.xpm" #include "Lang_Sl.xpm" #include "Lang_Hu.xpm" #include "Lang_Po.xpm" #endif #define FONT_DEFAULT_SIZE 10 /* Default font size. The real font size will be computed at run time */ /*****************************/ /* Constructeur de WinEDA_App */ /*****************************/ WinEDA_App::WinEDA_App(void) { m_Checker = NULL; m_MainFrame = NULL; m_PcbFrame = NULL; m_ModuleEditFrame = NULL; // Edition des modules SchematicFrame = NULL; // Edition des Schemas LibeditFrame = NULL; // Edition des composants ViewlibFrame = NULL; // Visualisation des composants m_CvpcbFrame = NULL; m_GerberFrame = NULL; // ecran de visualisation GERBER m_LastProjectMaxCount = 10; m_HtmlCtrl = NULL; m_EDA_CommonConfig = NULL; m_EDA_Config = NULL; m_Env_Defined = FALSE; m_LanguageId = wxLANGUAGE_DEFAULT; m_Language_Menu = NULL; m_Locale = NULL; m_PdfBrowserIsDefault = TRUE; /* Init de variables globales d'interet general: */ g_FloatSeparator = '.'; // Nombres flottants = 0.1 par exemple } /*****************************/ /* Destructeur de WinEDA_App */ /*****************************/ WinEDA_App::~WinEDA_App(void) { SaveSettings(); /* delete data non directement geree par wxAppl */ delete g_Prj_Config; delete m_EDA_Config; delete m_EDA_CommonConfig; delete g_StdFont; delete g_DialogFont; delete g_ItalicFont; delete g_FixedFont; delete g_MsgFont; delete DrawPen; delete DrawBrush; if ( m_Checker ) delete m_Checker; delete m_Locale; } /**************************************************/ void WinEDA_App::InitEDA_Appl(const wxString & name) /***************************************************/ { wxString ident; wxString EnvLang; ident = name + wxT("-") + wxGetUserId(); m_Checker = new wxSingleInstanceChecker(ident); /* Init environnement (KICAD definit le chemin de kicad ex: set KICAD=d:\kicad) */ m_Env_Defined = wxGetEnv( wxT("KICAD"), &m_KicadEnv); if ( m_Env_Defined ) // m_KicadEnv doit finir par "/" ou "\" { m_KicadEnv.Replace(WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP); if ( m_KicadEnv.Last() != '/' ) m_KicadEnv += UNIX_STRING_DIR_SEP; } /* Prepare On Line Help */ m_HelpFileName = name + wxT(".html"); // Init parametres pour configuration SetVendorName(wxT("kicad")); SetAppName(name); m_EDA_Config = new wxConfig(name); m_EDA_CommonConfig = new wxConfig(wxT("kicad_common")); /* Creation des outils de trace */ DrawPen = new wxPen( wxT("GREEN"), 1, wxSOLID); DrawBrush = new wxBrush(wxT("BLACK"), wxTRANSPARENT); /* Creation des fontes utiles */ g_StdFontPointSize = FONT_DEFAULT_SIZE; g_MsgFontPointSize = FONT_DEFAULT_SIZE; g_DialogFontPointSize = FONT_DEFAULT_SIZE; g_FixedFontPointSize = FONT_DEFAULT_SIZE; g_StdFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_MsgFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_DialogFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_ItalicFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxFONTSTYLE_ITALIC, wxNORMAL); g_FixedFont = new wxFont(g_FixedFontPointSize, wxFONTFAMILY_MODERN, wxNORMAL, wxNORMAL); /* installation des gestionnaires de visu d'images (pour help) */ wxImage::AddHandler(new wxPNGHandler); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxJPEGHandler); wxFileSystem::AddHandler(new wxZipFSHandler); // Analyse command line & init binary path SetBinDir(); ReadPdfBrowserInfos(); // Internationalisation: chargement du Dictionnaire de kicad m_EDA_CommonConfig->Read(wxT("Language"), &m_LanguageId, wxLANGUAGE_DEFAULT); bool succes = SetLanguage(TRUE); if ( ! succes ) { } if ( atof("0,1") ) g_FloatSeparator = ','; // Nombres flottants = 0,1 else g_FloatSeparator = '.'; } /*****************************************/ void WinEDA_App::InitOnLineHelp(void) /*****************************************/ /* Init On Line Help */ { wxString fullfilename = FindKicadHelpPath(); fullfilename += wxT("kicad.hhp"); if ( wxFileExists(fullfilename) ) { m_HtmlCtrl = new wxHtmlHelpController(wxHF_TOOLBAR | wxHF_CONTENTS | wxHF_PRINT | wxHF_OPEN_FILES /*| wxHF_SEARCH */); m_HtmlCtrl->UseConfig(m_EDA_Config); m_HtmlCtrl->SetTitleFormat( wxT("Kicad Help") ); m_HtmlCtrl->AddBook(fullfilename); } } /*******************************/ bool WinEDA_App::SetBinDir(void) /*******************************/ /* Analyse la ligne de commande pour retrouver le chemin de l'executable Sauve en WinEDA_App::m_BinDir le repertoire de l'executable */ { /* Calcul du chemin ou se trouve l'executable */ #ifdef __UNIX__ /* Sous LINUX ptarg[0] ne donne pas le chemin complet de l'executable, il faut le retrouver par la commande "which <filename> si aucun chemin n'est donne */ FILE * ftmp; #define TMP_FILE "/tmp/kicad.tmp" char Line[1024]; char FileName[1024]; wxString str_arg0; int ii; FileName[0] = 0; str_arg0 = argv[0]; if( strchr( (const char *)argv[0],'/') == NULL ) /* pas de chemin */ { sprintf( FileName, "which %s > %s", CONV_TO_UTF8(str_arg0), TMP_FILE); ii = system(FileName); if( (ftmp = fopen(TMP_FILE, "rt")) != NULL ) { fgets(Line,1000,ftmp); fclose(ftmp); remove(TMP_FILE); } m_BinDir = CONV_FROM_UTF8(Line); } else m_BinDir = argv[0]; #else m_BinDir = argv[0]; #endif m_BinDir.Replace(WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP); while ( m_BinDir.Last() != '/' ) m_BinDir.RemoveLast(); return TRUE; } /*********************************/ void WinEDA_App::GetSettings(void) /*********************************/ /* Lit les infos utiles sauvees lors de la derniere utilisation du logiciel */ { wxString Line, Ident; unsigned ii; m_HelpSize.x = 500; m_HelpSize.y = 400; if ( m_EDA_CommonConfig ) { m_LanguageId = m_EDA_CommonConfig->Read(wxT("Language"), wxLANGUAGE_DEFAULT); g_EditorName = m_EDA_CommonConfig->Read(wxT("Editor")); } if ( ! m_EDA_Config ) return; for ( ii = 0; ii < 10; ii++ ) { Ident = wxT("LastProject"); if ( ii ) Ident << ii; if( m_EDA_Config->Read(Ident, &Line) ) m_LastProject.Add(Line); } g_StdFontPointSize = m_EDA_Config->Read(wxT("SdtFontSize"), FONT_DEFAULT_SIZE); g_MsgFontPointSize = m_EDA_Config->Read(wxT("MsgFontSize"), FONT_DEFAULT_SIZE); g_DialogFontPointSize = m_EDA_Config->Read(wxT("DialogFontSize"), FONT_DEFAULT_SIZE); g_FixedFontPointSize = m_EDA_Config->Read(wxT("FixedFontSize"), FONT_DEFAULT_SIZE); Line = m_EDA_Config->Read(wxT("SdtFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_StdFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("SdtFontStyle"), wxFONTFAMILY_ROMAN); g_StdFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("SdtFontWeight"), wxNORMAL); g_StdFont->SetWeight(ii); g_StdFont->SetPointSize(g_StdFontPointSize); Line = m_EDA_Config->Read(wxT("MsgFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_MsgFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("MsgFontStyle"), wxFONTFAMILY_ROMAN); g_MsgFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("MsgFontWeight"), wxNORMAL); g_MsgFont->SetWeight(ii); g_MsgFont->SetPointSize(g_MsgFontPointSize); Line = m_EDA_Config->Read(wxT("DialogFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_DialogFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("DialogFontStyle"), wxFONTFAMILY_ROMAN); g_DialogFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("DialogFontWeight"), wxNORMAL); g_DialogFont->SetWeight(ii); g_DialogFont->SetPointSize(g_DialogFontPointSize); g_FixedFont->SetPointSize(g_FixedFontPointSize); m_EDA_Config->Read(wxT("ShowPageLimits"), & g_ShowPageLimits); if( m_EDA_Config->Read(wxT("WorkingDir"), &Line) ) { if ( wxDirExists(Line) ) wxSetWorkingDirectory(Line); } m_EDA_Config->Read( wxT("BgColor"), &g_DrawBgColor); } /**********************************/ void WinEDA_App::SaveSettings(void) /**********************************/ { unsigned int ii; if( m_EDA_Config == NULL ) return; m_EDA_Config->Write(wxT("SdtFontSize"), g_StdFontPointSize); m_EDA_Config->Write(wxT("SdtFontType"), g_StdFont->GetFaceName()); m_EDA_Config->Write(wxT("SdtFontStyle"), g_StdFont->GetStyle()); m_EDA_Config->Write(wxT("SdtFontWeight"), g_StdFont->GetWeight()); m_EDA_Config->Write(wxT("MsgFontSize"), g_MsgFontPointSize); m_EDA_Config->Write(wxT("MsgFontType"), g_MsgFont->GetFaceName()); m_EDA_Config->Write(wxT("MsgFontStyle"), g_MsgFont->GetStyle()); m_EDA_Config->Write(wxT("MsgFontWeight"), g_MsgFont->GetWeight()); m_EDA_Config->Write(wxT("DialogFontSize"), g_DialogFontPointSize); m_EDA_Config->Write(wxT("DialogFontType"), g_DialogFont->GetFaceName()); m_EDA_Config->Write(wxT("DialogFontStyle"), g_DialogFont->GetStyle()); m_EDA_Config->Write(wxT("DialogFontWeight"), g_DialogFont->GetWeight()); m_EDA_Config->Write(wxT("FixedFontSize"), g_FixedFontPointSize); m_EDA_Config->Write(wxT("ShowPageLimits"), g_ShowPageLimits); m_EDA_Config->Write(wxT("WorkingDir"), wxGetCwd()); for( ii = 0; ii < 10; ii++ ) { wxString msg = wxT("LastProject"); if ( ii ) msg << ii; if ( ii < m_LastProject.GetCount() ) m_EDA_Config->Write(msg, m_LastProject[ii]); else m_EDA_Config->Write(msg, wxEmptyString); } } /*********************************************/ bool WinEDA_App::SetLanguage(bool first_time) /*********************************************/ /* Set the dictionary file name for internationalization the files are in kicad/internat/xx or kicad/internat/xx_XX and are named kicad.mo */ { wxString DictionaryName( wxT("kicad")); // dictionary file name without extend (full name is kicad.mo) wxString BaseDictionaryPath( wxT("internat")); // Real path is kicad/internat/xx_XX or kicad/internat/xx wxString dic_path; if ( m_Locale != NULL ) delete m_Locale; m_Locale = new wxLocale(); m_Locale->Init(m_LanguageId); dic_path = ReturnKicadDatasPath() + BaseDictionaryPath; m_Locale->AddCatalogLookupPathPrefix(dic_path); if ( ! first_time ) { if ( m_EDA_CommonConfig ) m_EDA_CommonConfig->Write( wxT("Language"), m_LanguageId); } if ( ! m_Locale->IsLoaded(DictionaryName) ) m_Locale->AddCatalog(DictionaryName); SetLanguageList(NULL); if ( atof("0,1") ) g_FloatSeparator = ','; // Nombres flottants = 0,1 else g_FloatSeparator = '.'; return m_Locale->IsOk(); } /**************************************************/ void WinEDA_App::SetLanguageIdentifier(int menu_id) /**************************************************/ /* return in m_LanguageId the language id (wxWidgets language identifier) from menu id (internal menu identifier) */ { switch (menu_id) { case ID_LANGUAGE_ITALIAN: m_LanguageId = wxLANGUAGE_ITALIAN; break; case ID_LANGUAGE_PORTUGUESE: m_LanguageId = wxLANGUAGE_PORTUGUESE; break; case ID_LANGUAGE_RUSSIAN: m_LanguageId = wxLANGUAGE_RUSSIAN; break; case ID_LANGUAGE_DUTCH: m_LanguageId = wxLANGUAGE_DUTCH; break; case ID_LANGUAGE_SPANISH: m_LanguageId = wxLANGUAGE_SPANISH; break; case ID_LANGUAGE_ENGLISH: m_LanguageId = wxLANGUAGE_ENGLISH; break; case ID_LANGUAGE_FRENCH: m_LanguageId = wxLANGUAGE_FRENCH; break; case ID_LANGUAGE_SLOVENIAN: m_LanguageId = wxLANGUAGE_SLOVENIAN; break; case ID_LANGUAGE_HUNGARIAN: m_LanguageId = wxLANGUAGE_HUNGARIAN ; break; case ID_LANGUAGE_POLISH: m_LanguageId = wxLANGUAGE_POLISH ; break; default: m_LanguageId = wxLANGUAGE_DEFAULT; break; } } /*********************************************************/ wxMenu * WinEDA_App::SetLanguageList(wxMenu * MasterMenu) /*********************************************************/ /* Create menu list for language choice. */ { wxMenuItem * item; if ( m_Language_Menu == NULL ) { m_Language_Menu = new wxMenu; item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_DEFAULT, _("Default"), wxEmptyString, wxITEM_CHECK ); SETBITMAPS(lang_def_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_ENGLISH, wxT("English"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_en_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_FRENCH, _("French"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_fr_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_SPANISH, _("Spanish"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_es_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_PORTUGUESE, _("Portuguese"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_pt_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_ITALIAN, _("Italian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_it_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_DUTCH, _("Dutch"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_de_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_SLOVENIAN, _("Slovenian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_sl_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_HUNGARIAN, _("Hungarian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_hu_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_POLISH, _("Polish"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_po_xpm); m_Language_Menu->Append(item); #if 0 item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_RUSSIAN, _("Russian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_ru_xpm); m_Language_Menu->Append(item); #endif } m_Language_Menu->Check(ID_LANGUAGE_POLISH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_HUNGARIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_ITALIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_PORTUGUESE, FALSE); m_Language_Menu->Check(ID_LANGUAGE_DUTCH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_SPANISH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_FRENCH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_ENGLISH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_DEFAULT, FALSE); switch ( m_LanguageId ) { case wxLANGUAGE_RUSSIAN: m_Language_Menu->Check(ID_LANGUAGE_RUSSIAN, TRUE); break; case wxLANGUAGE_DUTCH: m_Language_Menu->Check(ID_LANGUAGE_DUTCH, TRUE); break; case wxLANGUAGE_FRENCH: m_Language_Menu->Check(ID_LANGUAGE_FRENCH, TRUE); break; case wxLANGUAGE_ENGLISH: m_Language_Menu->Check(ID_LANGUAGE_ENGLISH, TRUE); break; case wxLANGUAGE_SPANISH: m_Language_Menu->Check(ID_LANGUAGE_SPANISH, TRUE); break; case wxLANGUAGE_PORTUGUESE: m_Language_Menu->Check(ID_LANGUAGE_PORTUGUESE, TRUE); break; case wxLANGUAGE_ITALIAN: m_Language_Menu->Check(ID_LANGUAGE_ITALIAN, TRUE); break; case wxLANGUAGE_SLOVENIAN: m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, TRUE); break; case wxLANGUAGE_HUNGARIAN: m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, TRUE); break; case wxLANGUAGE_POLISH: m_Language_Menu->Check(ID_LANGUAGE_POLISH, TRUE); break; default: m_Language_Menu->Check(ID_LANGUAGE_DEFAULT, TRUE); break; } if ( MasterMenu ) { ADD_MENUITEM_WITH_HELP_AND_SUBMENU(MasterMenu, m_Language_Menu, ID_LANGUAGE_CHOICE, _("Language"), wxT("For test only, use Default setup for normal use"), language_xpm); } return m_Language_Menu; }
[ "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 578 ] ] ]
576c127d91801e64428d26ca15329d7b94a7e277
549243b0ca2a23432389529149ffb2b9cbd65bb2
/src/nvcore/FileMonitor.h
f4aad10ec9bfa2efcf6da33050bb2fc03076db4a
[]
no_license
castano/nvidia-oss
bb025c248ac6490673e9b11f544bed70119421dc
91f2030e33ae542005768b1181b2538c37171468
refs/heads/master
2023-07-12T18:12:08.858663
2009-11-05T19:08:45
2009-11-05T19:08:45
32,236,993
2
0
null
null
null
null
UTF-8
C++
false
false
522
h
// This code is in the public domain -- [email protected] #ifndef NV_CORE_FILEMONITOR_H #define NV_CORE_FILEMONITOR_H #include <nvcore/nvcore.h> namespace nv { class FileMonitor { NV_FORBID_COPY(FileMonitor); public: FileMonitor(const char * path, bool recursive); ~FileMonitor(); typedef void (* Notifier)(const char * name); void setNotifier(Notifier notifer); private: struct Private; Private & m; }; } // nv namespace #endif // NV_CORE_FILEMONITOR_H
[ "castano@9a2b036c-014e-11de-8259-6defae454439" ]
[ [ [ 1, 31 ] ] ]
4e0df90b321e764db7ef1007a0411ff9786a684a
7cf0bc0c3120c2040c3ed534421082cd93f0242f
/ab_mfc/ab_mfc/ab_mfcView.h
8708143702eb23136c456af988b088e9fa3c0f34
[]
no_license
zephyrer/ab-mfc
3d7be0283fa3fff3dcb7120fc1544e60a3811d88
f228b27a6fdbcb55f481155e9e9d77302335336a
refs/heads/master
2021-01-13T02:15:55.470629
2010-12-10T12:16:23
2010-12-10T12:16:23
40,066,957
0
0
null
null
null
null
GB18030
C++
false
false
1,703
h
// ab_mfcView.h : Cab_mfcView 类的接口 // #pragma once class Cab_mfcView : public CView { protected: // 仅从序列化创建 Cab_mfcView(); DECLARE_DYNCREATE(Cab_mfcView) //OpenGL定义 GLdouble frenqu; GLdouble m_zTra; GLdouble m_yTra; GLdouble m_xTra; GLdouble m_zRo; GLdouble m_xRo; GLdouble m_yRo; // CDC* m_pDC;//设备描述表 void JIQIREN(); void RenderScene(); BOOL SetWindowPixelFormat(HDC m_hDC); HGLRC m_hRC;//绘制描述表 HDC m_hDC;//设备描述表 int m_GLPixelIndex; float m_size; // 属性 public: Cab_mfcDoc* GetDocument() const; bool isConsole; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 实现 public: virtual ~Cab_mfcView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnConsole(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnDestroy(); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnTimer(UINT_PTR nIDEvent); }; #ifndef _DEBUG // ab_mfcView.cpp 中的调试版本 inline Cab_mfcDoc* Cab_mfcView::GetDocument() const { return reinterpret_cast<Cab_mfcDoc*>(m_pDocument); } #endif
[ "superkiki1989@ce34bfc1-e555-5f21-4a2b-332ae8037cd2" ]
[ [ [ 1, 73 ] ] ]
a88c5c7f62c97f0553737c0912b20cb4c4321105
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/Platforms/MacOS/MacOSPlatformUtils.hpp
1660ca222c8a27ec6430bcd53b1ba0a71f2afcb5
[]
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
4,649
hpp
/* * Copyright 1999-2000,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: MacOSPlatformUtils.hpp 180016 2005-06-04 19:49:30Z jberry $ */ #pragma once #include <cstdlib> #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/Platforms/MacOS/MacAbstractFile.hpp> #if defined(__APPLE__) // Framework includes from ProjectBuilder #include <CoreServices/CoreServices.h> #else // Classic includes otherwise #include <Files.h> #endif XERCES_CPP_NAMESPACE_BEGIN // Notes on our Xerces/Mac paths: // // Wherever paths are used in Xerces, this Macintosh port assumes that they'll // be in "unix" format, or at least as close as you can get to that on the particular // OS. On classic, this means that a path will be a unix style path, separated by '/' and // starting with the Mac OS volume name. Since slash is used as the segment separator, // any slashes that actually exist in the segment name will be converted to colons // (since colon is the Mac OS path separator and would be illegal in a segment name). // For Mac OS X, paths are created and parsed using the FSRefMakePath, etc, routines: // the major difference will be location of the volume name within the path. // // The routines below help to create and interpret these pathnames for these cases. // While the port itself never creates such paths, it does use these same routines to // parse them. // Factory method to create an appropriate concrete object // descended from XMLMacAbstractFile. XMLUTIL_EXPORT XMLMacAbstractFile* XMLMakeMacFile(MemoryManager* manager); // Convert fom FSRef/FSSpec to a Unicode character string path. // Note that you'll need to delete [] that string after you're done with it! XMLUTIL_EXPORT XMLCh* XMLCreateFullPathFromFSRef(const FSRef& startingRef, MemoryManager* const manager = XMLPlatformUtils::fgArrayMemoryManager); XMLUTIL_EXPORT XMLCh* XMLCreateFullPathFromFSSpec(const FSSpec& startingSpec, MemoryManager* const manager = XMLPlatformUtils::fgArrayMemoryManager); // Convert from path to FSRef/FSSpec // You retain ownership of the pathName. // Note: in the general case, these routines will fail if the specified file // does not exist when the routine is called. XMLUTIL_EXPORT bool XMLParsePathToFSRef(const XMLCh* const pathName, FSRef& ref, MemoryManager* const manager = XMLPlatformUtils::fgArrayMemoryManager); XMLUTIL_EXPORT bool XMLParsePathToFSSpec(const XMLCh* const pathName, FSSpec& spec, MemoryManager* const manager = XMLPlatformUtils::fgArrayMemoryManager); // These routines copy characters between their representation in the Unicode Converter // and the representation used by XMLCh. Until a recent change in Xerces, these were // sometimes different on the Macintosh (with GCC), but XMLCh is now fixed at 16 bits. // Code utilitizing these routines may be phased out in time, as a conversion is no // longer necessary. XMLUTIL_EXPORT XMLCh* CopyUniCharsToXMLChs(const UniChar* src, XMLCh* dst, std::size_t charCount, std::size_t maxChars); XMLUTIL_EXPORT UniChar* CopyXMLChsToUniChars(const XMLCh* src, UniChar* dst, std::size_t charCount, std::size_t maxChars); // UTF8/UniChar transcoding utilities XMLUTIL_EXPORT std::size_t TranscodeUniCharsToUTF8(const UniChar* src, char* dst, std::size_t srcCnt, std::size_t maxChars); XMLUTIL_EXPORT std::size_t TranscodeUTF8ToUniChars(const char* src, UniChar* dst, std::size_t maxChars); // Size of our statically allocated path buffers const std::size_t kMaxMacStaticPathChars = 512; // Global variables set in platformInit() extern bool gFileSystemCompatible; extern bool gMacOSXOrBetter; extern bool gHasFSSpecAPIs; extern bool gHasFS2TBAPIs; extern bool gHasHFSPlusAPIs; extern bool gHasFSPathAPIs; extern bool gPathAPIsUsePosixPaths; extern bool gHasMPAPIs; extern bool gUsePosixFiles; XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 105 ] ] ]
b5e32d7c3ad5738a596ab1b79145efe447fa37d8
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Transcoders/IconvGNU/IconvGNUTransService.cpp
cb4938f4e6df30212f2c412aef92f3259fb77b89
[ "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
42,201
cpp
/* * Copyright 2002,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. */ /* * $Log: IconvGNUTransService.cpp,v $ * Revision 1.15 2004/09/08 13:56:45 peiyongz * Apache License Version 2.0 * * Revision 1.14 2004/07/23 15:29:09 amassari * transcode was badly terminating the converted string (jira#1206) * * Revision 1.13 2004/07/23 14:35:03 amassari * A global mutex was not cleaned up * * Revision 1.12 2004/02/25 14:53:24 peiyongz * Bug#27209: Xerces 2.5.0 does not build with option -t IconvGNU because of syntax errors! * * Revision 1.11 2003/12/24 15:24:15 cargilld * More updates to memory management so that the static memory manager. * * Revision 1.10 2003/08/19 14:01:41 neilg * fix for bug 22537 * * Revision 1.9 2003/05/17 16:32:18 knoaman * Memory manager implementation : transcoder update. * * Revision 1.8 2003/05/16 21:37:00 knoaman * Memory manager implementation: Modify constructors to pass in the memory manager. * * Revision 1.7 2003/05/15 18:47:05 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.6 2003/04/07 16:52:13 peiyongz * Bug# 18672: IconvGNUTranscoder can't be build when namespaces is on. * Patch from [email protected] (Vasily Tchekalkin) * * Revision 1.5 2003/03/09 17:03:25 peiyongz * PanicHandler * * Revision 1.4 2002/12/31 18:42:54 tng * [Bug 15608] IconvLCPTranscoder::transcode() is wrong at wcstombs() usage. * * Revision 1.3 2002/11/04 15:14:34 tng * C++ Namespace Support. * * Revision 1.2 2002/09/27 13:33:43 tng * [Bug 12547] Xerces C++ 2.1 fails to build on Linux 64 bits arch with -tlinux. Patch from Guillaume Morin. * * Revision 1.1 2002/08/19 19:38:18 tng * [Bug 11771] Linux specific IconvGNU transcoder. Patch from Vasily Tchekalkin. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <ctype.h> #include <locale.h> #include <iconv.h> #include <errno.h> #include <endian.h> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/TranscodingException.hpp> #include "IconvGNUTransService.hpp" #if !defined(APP_NO_THREADS) #include <xercesc/util/Mutexes.hpp> #include <xercesc/util/XMLRegisterCleanup.hpp> #endif /* !APP_NO_THREADS */ XERCES_CPP_NAMESPACE_BEGIN #if !defined(APP_NO_THREADS) // Iconv() access syncronization point static XMLMutex *gIconvMutex = NULL; static XMLRegisterCleanup IconvGNUMutexCleanup; # define ICONV_LOCK XMLMutexLock lockConverter(gIconvMutex); #else /* APP_NO_THREADS */ # define ICONV_LOCK #endif /* !APP_NO_THREADS */ // --------------------------------------------------------------------------- // Description of encoding schemas, supported by iconv() // --------------------------------------------------------------------------- typedef struct __IconvGNUEncoding { const char* fSchema; // schema name size_t fUChSize; // size of the character unsigned int fUBO; // byte order, relative to the host } IconvGNUEncoding; static const IconvGNUEncoding gIconvGNUEncodings[] = { { "UCS-2LE", 2, LITTLE_ENDIAN }, { "ucs-2-internal", 2, LITTLE_ENDIAN }, { NULL, 0, 0 } }; //-------------------------------------------------- // Macro-definitions to translate "native unicode" // characters <-> XMLCh with different host byte order // and encoding schemas. # if BYTE_ORDER == LITTLE_ENDIAN # define IXMLCh2WC16(x,w) \ *(w) = ((*(x)) >> 8) & 0xFF; \ *((w)+1) = (*(x)) & 0xFF # define IWC162XMLCh(w,x) *(x) = ((*(w)) << 8) | (*((w)+1)) # define XMLCh2WC16(x,w) \ *(w) = (*(x)) & 0xFF; \ *((w)+1) = ((*(x)) >> 8) & 0xFF # define WC162XMLCh(w,x) *(x) = ((*((w)+1)) << 8) | (*(w)) # define IXMLCh2WC32(x,w) \ *(w) = ((*(x)) >> 24) & 0xFF; \ *((w)+1) = ((*(x)) >> 16) & 0xFF; \ *((w)+2) = ((*(x)) >> 8) & 0xFF; \ *((w)+3) = (*(x)) & 0xFF # define IWC322XMLCh(w,x) \ *(x) = ((*(w)) << 24) | ((*((w)+1)) << 16) | \ ((*((w)+2)) << 8) | (*((w)+3)) # define XMLCh2WC32(x,w) \ *((w)+3) = ((*(x)) >> 24) & 0xFF; \ *((w)+2) = ((*(x)) >> 16) & 0xFF; \ *((w)+1) = ((*(x)) >> 8) & 0xFF; \ *(w) = (*(x)) & 0xFF # define WC322XMLCh(w,x) \ *(x) = ((*((w)+3)) << 24) | ((*((w)+2)) << 16) | \ ((*((w)+1)) << 8) | (*(w)) # else /* BYTE_ORDER != LITTLE_ENDIAN */ # define XMLCh2WC16(x,w) \ *(w) = ((*(x)) >> 8) & 0xFF; \ *((w)+1) = (*(x)) & 0xFF # define WC162XMLCh(w,x) *(x) = ((*(w)) << 8) | (*((w)+1)) # define IXMLCh2WC16(x,w) \ *(w) = (*(x)) & 0xFF; \ *((w)+1) = ((*(x)) >> 8) & 0xFF # define IWC162XMLCh(w,x) *(x) = ((*((w)+1)) << 8) | (*(w)) # define XMLCh2WC32(x,w) \ *(w) = ((*(x)) >> 24) & 0xFF; \ *((w)+1) = ((*(x)) >> 16) & 0xFF; \ *((w)+2) = ((*(x)) >> 8) & 0xFF; \ *((w)+3) = (*(x)) & 0xFF # define WC322XMLCh(w,x) \ *(x) = ((*(w)) << 24) | ((*((w)+1)) << 16) | \ ((*((w)+2)) << 8) | (*((w)+3)) # define IXMLCh2WC32(x,w) \ *((w)+3) = ((*(x)) >> 24) & 0xFF; \ *((w)+2) = ((*(x)) >> 16) & 0xFF; \ *((w)+1) = ((*(x)) >> 8) & 0xFF; \ *(w) = (*(x)) & 0xFF # define IWC322XMLCh(w,x) \ *(x) = ((*((w)+3)) << 24) | ((*((w)+2)) << 16) | \ ((*((w)+1)) << 8) | (*(w)) # endif /* BYTE_ORDER == LITTLE_ENDIAN */ #include <wchar.h> #include <string.h> #include <stdlib.h> #include <stdio.h> // --------------------------------------------------------------------------- // Local, const data // --------------------------------------------------------------------------- static const unsigned int gTempBuffArraySize = 4096; static const XMLCh gMyServiceId[] = { chLatin_I, chLatin_C, chLatin_o, chLatin_n, chLatin_v, chNull }; // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static unsigned int getWideCharLength(const XMLCh* const src) { if (!src) return 0; unsigned int len = 0; const XMLCh* pTmp = src; while (*pTmp++) len++; return len; } //---------------------------------------------------------------------------- // There is implementation of the libiconv for FreeBSD (available through the // ports collection). The following is a wrapper around the iconv(). //---------------------------------------------------------------------------- IconvGNUWrapper::IconvGNUWrapper () : fUChSize(0), fUBO(LITTLE_ENDIAN), fCDTo((iconv_t)-1), fCDFrom((iconv_t)-1) { } IconvGNUWrapper::IconvGNUWrapper ( iconv_t cd_from, iconv_t cd_to, size_t uchsize, unsigned int ubo ) : fUChSize(uchsize), fUBO(ubo), fCDTo(cd_to), fCDFrom(cd_from) { if (fCDFrom == (iconv_t) -1 || fCDTo == (iconv_t) -1) { XMLPlatformUtils::panic (PanicHandler::Panic_NoTransService); } } IconvGNUWrapper::~IconvGNUWrapper() { } // Convert "native unicode" character into XMLCh void IconvGNUWrapper::mbcToXMLCh (const char *mbc, XMLCh *toRet) const { if (fUBO == LITTLE_ENDIAN) { if (fUChSize == sizeof(XMLCh)) *toRet = *((XMLCh*) mbc); else if (fUChSize == 2) { WC162XMLCh( mbc, toRet ); } else { WC322XMLCh( mbc, toRet ); } } else { if (fUChSize == 2) { IWC162XMLCh( mbc, toRet ); } else { IWC322XMLCh( mbc, toRet ); } } } // Convert XMLCh into "native unicode" character void IconvGNUWrapper::xmlChToMbc (XMLCh xch, char *mbc) const { if (fUBO == LITTLE_ENDIAN) { if (fUChSize == sizeof(XMLCh)) { memcpy (mbc, &xch, fUChSize); return; } if (fUChSize == 2) { XMLCh2WC16( &xch, mbc ); } else { XMLCh2WC32( &xch, mbc ); } } else { if (fUChSize == 2) { IXMLCh2WC16( &xch, mbc ); } else { IXMLCh2WC32( &xch, mbc ); } } } // Return uppercase equivalent for XMLCh XMLCh IconvGNUWrapper::toUpper (const XMLCh ch) const { if (ch <= 0x7F) return toupper(ch); char wcbuf[fUChSize * 2]; xmlChToMbc (ch, wcbuf); char tmpArr[4]; char* ptr = wcbuf; size_t len = fUChSize; char *pTmpArr = tmpArr; size_t bLen = 2; ICONV_LOCK; if (::iconv (fCDTo, &ptr, &len, &pTmpArr, &bLen) == (size_t) -1) return 0; tmpArr[1] = toupper (*((unsigned char *)tmpArr)); *tmpArr = tmpArr[1]; len = 1; pTmpArr = wcbuf; bLen = fUChSize; ptr = tmpArr; if (::iconv (fCDFrom, &ptr, &len, &pTmpArr, &bLen) == (size_t) -1) return 0; mbcToXMLCh (wcbuf, (XMLCh*) &ch); return ch; } // Return lowercase equivalent for XMLCh XMLCh IconvGNUWrapper::toLower (const XMLCh ch) const { if (ch <= 0x7F) return tolower(ch); char wcbuf[fUChSize * 2]; xmlChToMbc (ch, wcbuf); char tmpArr[4]; char* ptr = wcbuf; size_t len = fUChSize; char *pTmpArr = tmpArr; size_t bLen = 2; ICONV_LOCK; if (::iconv (fCDTo, &ptr, &len, &pTmpArr, &bLen) == (size_t) -1) return 0; tmpArr[1] = tolower (*((unsigned char*)tmpArr)); *tmpArr = tmpArr[1]; len = 1; pTmpArr = wcbuf; bLen = fUChSize; ptr = tmpArr; if (::iconv (fCDFrom, &ptr, &len, &pTmpArr, &bLen) == (size_t) -1) return 0; mbcToXMLCh (wcbuf, (XMLCh*) &ch); return ch; } // Check if passed characters belongs to the :space: class bool IconvGNUWrapper::isSpace(const XMLCh toCheck) const { if (toCheck <= 0x7F) return isspace(toCheck); char wcbuf[fUChSize * 2]; char tmpArr[4]; xmlChToMbc (toCheck, wcbuf); char* ptr = wcbuf; size_t len = fUChSize; char *pTmpArr = tmpArr; size_t bLen = 2; { ICONV_LOCK; if (::iconv (fCDTo, &ptr, &len, &pTmpArr, &bLen) == (size_t) -1) return 0; } return isspace(*tmpArr); } // Fill array of XMLCh characters with data, supplyed in the array // of "native unicode" characters. XMLCh* IconvGNUWrapper::mbsToXML ( const char* mbs_str , size_t mbs_cnt , XMLCh* xml_str , size_t xml_cnt ) const { if (mbs_str == NULL || mbs_cnt == 0 || xml_str == NULL || xml_cnt == 0) return NULL; size_t cnt = (mbs_cnt < xml_cnt) ? mbs_cnt : xml_cnt; if (fUBO == LITTLE_ENDIAN) { if (fUChSize == sizeof(XMLCh)) { // null-transformation memcpy (xml_str, mbs_str, fUChSize * cnt); return xml_str; } if (fUChSize == 2) for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize) { WC162XMLCh( mbs_str, xml_str + i); } else for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize) { WC322XMLCh( mbs_str, xml_str + i ); } } else { if (fUChSize == 2) for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize) { IWC162XMLCh( mbs_str, xml_str + i ); } else for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize) { IWC322XMLCh( mbs_str, xml_str + i ); } } return xml_str; } // Fill array of "native unicode" characters with data, supplyed // in the array of XMLCh characters. char* IconvGNUWrapper::xmlToMbs ( const XMLCh* xml_str , size_t xml_cnt , char* mbs_str , size_t mbs_cnt ) const { if (mbs_str == NULL || mbs_cnt == 0 || xml_str == NULL || xml_cnt == 0) return NULL; size_t cnt = (mbs_cnt < xml_cnt) ? mbs_cnt : xml_cnt; char *toReturn = mbs_str; if (fUBO == LITTLE_ENDIAN) { if (fUChSize == sizeof(XMLCh)) { // null-transformation memcpy (mbs_str, xml_str, fUChSize * cnt); return toReturn; } if (fUChSize == 2) for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize, xml_str++) { XMLCh2WC16( xml_str, mbs_str ); } else for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize, xml_str++) { XMLCh2WC32( xml_str, mbs_str ); } } else { if (fUChSize == 2) for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize, xml_str++) { IXMLCh2WC16( xml_str, mbs_str ); } else for (size_t i = 0; i < cnt; i++, mbs_str += fUChSize, xml_str++) { IXMLCh2WC32( xml_str, mbs_str ); } } return toReturn; } size_t IconvGNUWrapper::iconvFrom ( const char *fromPtr, size_t *fromLen, char **toPtr, size_t toLen ) const { ICONV_LOCK; char ** tmpPtr = (char**)&fromPtr; return ::iconv (fCDFrom, tmpPtr, fromLen, toPtr, &toLen); } size_t IconvGNUWrapper::iconvTo ( const char *fromPtr, size_t *fromLen, char **toPtr, size_t toLen ) const { ICONV_LOCK; char ** tmpPtr = (char**)&fromPtr; return ::iconv (fCDTo, tmpPtr, fromLen, toPtr, &toLen); } // --------------------------------------------------------------------------- // IconvGNUTransService: Constructors and Destructor // --------------------------------------------------------------------------- void reinitIconvGNUMutex() { delete gIconvMutex; gIconvMutex = 0; } IconvGNUTransService::IconvGNUTransService() : IconvGNUWrapper(), fUnicodeCP(0) { #if !defined(APP_NO_THREADS) // Create global lock object if (gIconvMutex == NULL) { gIconvMutex = new XMLMutex; if (gIconvMutex == NULL) XMLPlatformUtils::panic (PanicHandler::Panic_NoTransService); IconvGNUMutexCleanup.registerCleanup(reinitIconvGNUMutex); } #endif // Try to obtain local (host) characterset through the environment char* fLocalCP = setlocale (LC_CTYPE, ""); if (fLocalCP == NULL) fLocalCP = "iso-8859-1"; // fallback locale else { char *ptr = strchr (fLocalCP, '.'); if (ptr == NULL) fLocalCP = "iso-8859-1"; // fallback locale else fLocalCP = ptr + 1; } // Select the native unicode characters encoding schema const IconvGNUEncoding *eptr; // first - try to use the schema with character size, equil to XMLCh for (eptr = gIconvGNUEncodings; eptr->fSchema; eptr++) { if (eptr->fUChSize != sizeof(XMLCh)) continue; ICONV_LOCK; // try to create conversion descriptor iconv_t cd_to = iconv_open(fLocalCP, eptr->fSchema); if (cd_to == (iconv_t)-1) continue; iconv_t cd_from = iconv_open(eptr->fSchema, fLocalCP); if (cd_to == (iconv_t)-1) { iconv_close (cd_to); continue; } // got it setUChSize(eptr->fUChSize); setUBO(eptr->fUBO); setCDTo(cd_to); setCDFrom(cd_from); fUnicodeCP = eptr->fSchema; break; } if (fUnicodeCP == NULL) // try to use any known schema for (eptr = gIconvGNUEncodings; eptr->fSchema; eptr++) { // try to create conversion descriptor ICONV_LOCK; iconv_t cd_to = iconv_open(fLocalCP, eptr->fSchema); if (cd_to == (iconv_t)-1) continue; iconv_t cd_from = iconv_open(eptr->fSchema, fLocalCP); if (cd_to == (iconv_t)-1) { iconv_close (cd_to); continue; } // got it setUChSize(eptr->fUChSize); setUBO(eptr->fUBO); setCDTo(cd_to); setCDFrom(cd_from); fUnicodeCP = eptr->fSchema; break; } if (fUnicodeCP == NULL || cdTo() == (iconv_t)-1 || cdFrom() == (iconv_t)-1) XMLPlatformUtils::panic (PanicHandler::Panic_NoTransService); } IconvGNUTransService::~IconvGNUTransService() { if (cdTo() != (iconv_t) -1) { iconv_close (cdTo()); setCDTo ((iconv_t)-1); } if (cdFrom() != (iconv_t) -1) { iconv_close (cdFrom()); setCDFrom ((iconv_t)-1); } } // --------------------------------------------------------------------------- // IconvGNUTransService: The virtual transcoding service API // --------------------------------------------------------------------------- int IconvGNUTransService::compareIString(const XMLCh* const comp1 , const XMLCh* const comp2) { const XMLCh* cptr1 = comp1; const XMLCh* cptr2 = comp2; XMLCh c1 = toUpper(*cptr1); XMLCh c2 = toUpper(*cptr2); while ( (*cptr1 != 0) && (*cptr2 != 0) ) { if (c1 != c2) break; c1 = toUpper(*(++cptr1)); c2 = toUpper(*(++cptr2)); } return (int) ( c1 - c2 ); } int IconvGNUTransService::compareNIString(const XMLCh* const comp1 , const XMLCh* const comp2 , const unsigned int maxChars) { unsigned int n = 0; const XMLCh* cptr1 = comp1; const XMLCh* cptr2 = comp2; while (true && maxChars) { XMLCh c1 = toUpper(*cptr1); XMLCh c2 = toUpper(*cptr2); if (c1 != c2) return (int) (c1 - c2); // If either ended, then both ended, so equal if (!*cptr1 || !*cptr2) break; cptr1++; cptr2++; // Bump the count of chars done. If it equals the count then we // are equal for the requested count, so break out and return // equal. n++; if (n == maxChars) break; } return 0; } const XMLCh* IconvGNUTransService::getId() const { return gMyServiceId; } bool IconvGNUTransService::isSpace(const XMLCh toCheck) const { return IconvGNUWrapper::isSpace(toCheck); } XMLLCPTranscoder* IconvGNUTransService::makeNewLCPTranscoder() { return new IconvGNULCPTranscoder (cdFrom(), cdTo(), uChSize(), UBO()); } bool IconvGNUTransService::supportsSrcOfs() const { return true; } // --------------------------------------------------------------------------- // IconvGNUTransService: The protected virtual transcoding service API // --------------------------------------------------------------------------- XMLTranscoder* IconvGNUTransService::makeNewXMLTranscoder ( const XMLCh* const encodingName , XMLTransService::Codes& resValue , const unsigned int blockSize , MemoryManager* const manager ) { resValue = XMLTransService::UnsupportedEncoding; IconvGNUTranscoder *newTranscoder = NULL; char *encLocal = XMLString::transcode(encodingName, manager); iconv_t cd_from, cd_to; { ICONV_LOCK; cd_from = iconv_open (fUnicodeCP, encLocal); if (cd_from == (iconv_t)-1) { resValue = XMLTransService::SupportFilesNotFound; if (encLocal) manager->deallocate(encLocal);//delete [] encLocal; return NULL; } cd_to = iconv_open (encLocal, fUnicodeCP); if (cd_to == (iconv_t)-1) { resValue = XMLTransService::SupportFilesNotFound; iconv_close (cd_from); if (encLocal) manager->deallocate(encLocal);//delete [] encLocal; return NULL; } newTranscoder = new (manager) IconvGNUTranscoder (encodingName, blockSize, cd_from, cd_to, uChSize(), UBO(), manager); } if (newTranscoder) resValue = XMLTransService::Ok; if (encLocal) manager->deallocate(encLocal);//delete [] encLocal; return newTranscoder; } void IconvGNUTransService::upperCase(XMLCh* const toUpperCase) const { XMLCh* outPtr = toUpperCase; while (*outPtr) { *outPtr = toUpper(*outPtr); outPtr++; } } void IconvGNUTransService::lowerCase(XMLCh* const toLowerCase) const { XMLCh* outPtr = toLowerCase; while (*outPtr) { *outPtr = toLower(*outPtr); outPtr++; } } // --------------------------------------------------------------------------- // IconvGNULCPTranscoder: The virtual transcoder API // --------------------------------------------------------------------------- unsigned int IconvGNULCPTranscoder::calcRequiredSize (const char* const srcText , MemoryManager* const manager) { if (!srcText) return 0; size_t len, srcLen; len = srcLen = strlen(srcText); if (len == 0) return 0; char tmpWideArr[gTempBuffArraySize]; size_t totalLen = 0; for (;;) { char *pTmpArr = tmpWideArr; const char *ptr = srcText + srcLen - len; size_t rc = iconvFrom(ptr, &len, &pTmpArr, gTempBuffArraySize); if (rc == (size_t) -1 && errno != E2BIG) { ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq, manager); /* return 0; */ } rc = pTmpArr - (char *) tmpWideArr; totalLen += rc; if (rc == 0 || len == 0) break; } return totalLen / uChSize(); } unsigned int IconvGNULCPTranscoder::calcRequiredSize(const XMLCh* const srcText , MemoryManager* const manager) { if (!srcText) return 0; unsigned int wLent = getWideCharLength(srcText); if (wLent == 0) return 0; char tmpWBuff[gTempBuffArraySize]; char *wBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) manager->allocate ( len * sizeof(char) );//new char[len]; if (wBufPtr == NULL) return 0; wBuf = wBufPtr; } else wBuf = tmpWBuff; xmlToMbs (srcText, wLent, wBuf, wLent); } else wBuf = (char *) srcText; char tmpBuff[gTempBuffArraySize]; size_t totalLen = 0; char *srcEnd = wBuf + wLent * uChSize(); for (;;) { char *pTmpArr = tmpBuff; const char *ptr = srcEnd - len; size_t rc = iconvTo(ptr, &len, &pTmpArr, gTempBuffArraySize); if (rc == (size_t) -1 && errno != E2BIG) { if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq, manager); /* return 0; */ } rc = pTmpArr - tmpBuff; totalLen += rc; if (rc == 0 || len == 0) break; } if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; return totalLen; } char* IconvGNULCPTranscoder::transcode(const XMLCh* const toTranscode) { if (!toTranscode) return 0; char* retVal = 0; if (*toTranscode) { unsigned int wLent = getWideCharLength(toTranscode); // Calc needed size. const size_t neededLen = calcRequiredSize (toTranscode); if (neededLen == 0) return 0; // allocate output buffer retVal = new char[neededLen + 1]; if (retVal == NULL) return 0; // prepare the original char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; xmlToMbs (toTranscode, wLent, wideCharBuf, wLent); } else wideCharBuf = (char *) toTranscode; // perform conversion wLent *= uChSize(); char *ptr = retVal; size_t rc = iconvTo(wideCharBuf, (size_t *) &wLent, &ptr, neededLen); if (rc == (size_t)-1) { if (wBufPtr) delete [] wBufPtr; return 0; } if (wBufPtr) delete [] wBufPtr; retVal[neededLen] = 0; } else { retVal = new char[1]; if (retVal == NULL) return 0; retVal[0] = 0; } return retVal; } char* IconvGNULCPTranscoder::transcode(const XMLCh* const toTranscode, MemoryManager* const manager) { if (!toTranscode) return 0; char* retVal = 0; if (*toTranscode) { unsigned int wLent = getWideCharLength(toTranscode); // Calc needed size. const size_t neededLen = calcRequiredSize (toTranscode, manager); if (neededLen == 0) return 0; // allocate output buffer retVal = (char*) manager->allocate((neededLen + 1) * sizeof(char));//new char[neededLen + 1]; if (retVal == NULL) return 0; // prepare the original char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) manager->allocate(len * sizeof(char));//new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; xmlToMbs (toTranscode, wLent, wideCharBuf, wLent); } else wideCharBuf = (char *) toTranscode; // perform conversion wLent *= uChSize(); char *ptr = retVal; size_t rc = iconvTo(wideCharBuf, (size_t *) &wLent, &ptr, neededLen); if (rc == (size_t)-1) { if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; return 0; } if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; retVal[neededLen] = 0; } else { retVal = (char*) manager->allocate(sizeof(char));//new char[1]; if (retVal == NULL) return 0; retVal[0] = 0; } return retVal; } bool IconvGNULCPTranscoder::transcode( const XMLCh* const toTranscode , char* const toFill , const unsigned int maxBytes , MemoryManager* const manager) { // Watch for a couple of pyscho corner cases if (!toTranscode || !maxBytes) { toFill[0] = 0; return true; } if (!*toTranscode) { toFill[0] = 0; return true; } unsigned int wLent = getWideCharLength(toTranscode); if (wLent > maxBytes) wLent = maxBytes; // Fill the "unicode" string char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) manager->allocate ( len * sizeof(char) );//new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; xmlToMbs (toTranscode, wLent, wideCharBuf, wLent); } else wideCharBuf = (char *) toTranscode; // Ok, go ahead and try the transcoding. If it fails, then ... char *ptr = toFill; size_t rc = iconvTo(wideCharBuf, &len, &ptr, maxBytes); if (rc == (size_t)-1) { if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; return false; } if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; // Cap it off *ptr = 0; return true; } XMLCh* IconvGNULCPTranscoder::transcode(const char* const toTranscode) { if (!toTranscode) return 0; XMLCh* retVal = 0; if (*toTranscode) { const unsigned int wLent = calcRequiredSize(toTranscode); if (wLent == 0) { retVal = new XMLCh[1]; retVal[0] = 0; return retVal; } char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); retVal = new XMLCh[wLent + 1]; if (retVal == NULL) return NULL; if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; } else wideCharBuf = (char *) retVal; size_t flen = strlen(toTranscode); char *ptr = wideCharBuf; size_t rc = iconvFrom(toTranscode, &flen, &ptr, len); if (rc == (size_t) -1) { if (wBufPtr) delete [] wBufPtr; return NULL; } if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) mbsToXML (wideCharBuf, wLent, retVal, wLent); if (wBufPtr) delete [] wBufPtr; retVal[wLent] = 0x00; } else { retVal = new XMLCh[1]; if (retVal == NULL ) return 0; retVal[0] = 0; } return retVal; } XMLCh* IconvGNULCPTranscoder::transcode(const char* const toTranscode, MemoryManager* const manager) { if (!toTranscode) return 0; XMLCh* retVal = 0; if (*toTranscode) { const unsigned int wLent = calcRequiredSize(toTranscode, manager); if (wLent == 0) { retVal = (XMLCh*) manager->allocate(sizeof(XMLCh));//new XMLCh[1]; retVal[0] = 0; return retVal; } char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); retVal = (XMLCh*) manager->allocate((wLent + 1) * sizeof(XMLCh));//new XMLCh[wLent + 1]; if (retVal == NULL) return NULL; if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) manager->allocate(len * sizeof(char));//new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; } else wideCharBuf = (char *) retVal; size_t flen = strlen(toTranscode); char *ptr = wideCharBuf; size_t rc = iconvFrom(toTranscode, &flen, &ptr, len); if (rc == (size_t) -1) { if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; return NULL; } if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) mbsToXML (wideCharBuf, wLent, retVal, wLent); if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; retVal[wLent] = 0x00; } else { retVal = (XMLCh*) manager->allocate(sizeof(XMLCh));//new XMLCh[1]; if (retVal == NULL ) return 0; retVal[0] = 0; } return retVal; } bool IconvGNULCPTranscoder::transcode(const char* const toTranscode , XMLCh* const toFill , const unsigned int maxChars , MemoryManager* const manager) { // Check for a couple of psycho corner cases if (!toTranscode || !maxChars) { toFill[0] = 0; return true; } if (!*toTranscode) { toFill[0] = 0; return true; } size_t wLent = calcRequiredSize(toTranscode); if (wLent > maxChars) wLent = maxChars; char tmpWBuff[gTempBuffArraySize]; char *wideCharBuf = 0; char *wBufPtr = 0; size_t len = wLent * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) manager->allocate ( len * sizeof(char) );//new char[len]; if (wBufPtr == NULL) return 0; wideCharBuf = wBufPtr; } else wideCharBuf = tmpWBuff; } else wideCharBuf = (char *) toFill; size_t flen = strlen(toTranscode); // wLent; char *ptr = wideCharBuf; size_t rc = iconvFrom(toTranscode, &flen, &ptr, len); if (rc == (size_t)-1) { if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; return false; } if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) mbsToXML (wideCharBuf, wLent, toFill, wLent); if (wBufPtr) manager->deallocate(wBufPtr);//delete [] wBufPtr; toFill[wLent] = 0x00; return true; } // --------------------------------------------------------------------------- // IconvGNULCPTranscoder: Constructors and Destructor // --------------------------------------------------------------------------- IconvGNULCPTranscoder::IconvGNULCPTranscoder (iconv_t cd_from, iconv_t cd_to, size_t uchsize, unsigned int ubo) : IconvGNUWrapper (cd_from, cd_to, uchsize, ubo) { } IconvGNULCPTranscoder::~IconvGNULCPTranscoder() { } // --------------------------------------------------------------------------- // IconvGNUTranscoder: Constructors and Destructor // --------------------------------------------------------------------------- IconvGNUTranscoder::IconvGNUTranscoder (const XMLCh* const encodingName , const unsigned int blockSize , iconv_t cd_from , iconv_t cd_to , size_t uchsize , unsigned int ubo , MemoryManager* const manager ) : XMLTranscoder(encodingName, blockSize, manager) , IconvGNUWrapper (cd_from, cd_to, uchsize, ubo) { } IconvGNUTranscoder::~IconvGNUTranscoder() { ICONV_LOCK; if (cdTo() != (iconv_t)-1) { iconv_close (cdTo()); setCDTo ((iconv_t)-1); } if (cdFrom() != (iconv_t)-1) { iconv_close (cdFrom()); setCDFrom ((iconv_t)-1); } } // --------------------------------------------------------------------------- // IconvGNUTranscoder: Implementation of the virtual transcoder API // --------------------------------------------------------------------------- unsigned int IconvGNUTranscoder::transcodeFrom ( const XMLByte* const srcData , const unsigned int srcCount , XMLCh* const toFill , const unsigned int maxChars , unsigned int& bytesEaten , unsigned char* const charSizes ) { // Transcode TO XMLCh const char* startSrc = (const char*) srcData; const char* endSrc = (const char*) srcData + srcCount; char tmpWBuff[gTempBuffArraySize]; char *startTarget = 0; char *wBufPtr = 0; size_t len = maxChars * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) getMemoryManager()->allocate ( len * sizeof(char) );//new char[len]; if (wBufPtr == NULL) return 0; startTarget = wBufPtr; } else startTarget = tmpWBuff; } else startTarget = (char *) toFill; // Do character-by-character transcoding char *orgTarget = startTarget; size_t srcLen = srcCount; size_t prevSrcLen = srcLen; unsigned int toReturn = 0; bytesEaten = 0; for (size_t cnt = 0; cnt < maxChars && srcLen; cnt++) { size_t rc = iconvFrom(startSrc, &srcLen, &orgTarget, uChSize()); if (rc == (size_t)-1) { if (errno != E2BIG || prevSrcLen == srcLen) { if (wBufPtr) getMemoryManager()->deallocate(wBufPtr);//delete [] wBufPtr; ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq, getMemoryManager()); } } charSizes[cnt] = prevSrcLen - srcLen; prevSrcLen = srcLen; bytesEaten += charSizes[cnt]; startSrc = endSrc - srcLen; toReturn++; } if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) mbsToXML (startTarget, toReturn, toFill, toReturn); if (wBufPtr) getMemoryManager()->deallocate(wBufPtr);//delete [] wBufPtr; return toReturn; } unsigned int IconvGNUTranscoder::transcodeTo ( const XMLCh* const srcData , const unsigned int srcCount , XMLByte* const toFill , const unsigned int maxBytes , unsigned int& charsEaten , const UnRepOpts options ) { // Transcode FROM XMLCh char tmpWBuff[gTempBuffArraySize]; char *startSrc = tmpWBuff; char *wBufPtr = 0; size_t len = srcCount * uChSize(); if (uChSize() != sizeof(XMLCh) || UBO() != BYTE_ORDER) { if (len > gTempBuffArraySize) { wBufPtr = (char*) getMemoryManager()->allocate ( len * sizeof(char) );//new char[len]; if (wBufPtr == NULL) return 0; startSrc = wBufPtr; } else startSrc = tmpWBuff; xmlToMbs (srcData, srcCount, startSrc, srcCount); } else startSrc = (char *) srcData; char* startTarget = (char *) toFill; size_t srcLen = len; size_t rc = iconvTo (startSrc, &srcLen, &startTarget, maxBytes); if (rc == (size_t)-1 && errno != E2BIG) { if (wBufPtr) getMemoryManager()->deallocate(wBufPtr);//delete [] wBufPtr; ThrowXMLwithMemMgr(TranscodingException, XMLExcepts::Trans_BadSrcSeq, getMemoryManager()); } charsEaten = srcCount - srcLen / uChSize(); if (wBufPtr) getMemoryManager()->deallocate(wBufPtr);//delete [] wBufPtr; return startTarget - (char *)toFill; } bool IconvGNUTranscoder::canTranscodeTo ( const unsigned int toCheck ) const { // // If the passed value is really a surrogate embedded together, then // we need to break it out into its two chars. Else just one. // char srcBuf[2 * uChSize()]; unsigned int srcCount = 1; if (toCheck & 0xFFFF0000) { XMLCh ch1 = (toCheck >> 10) + 0xD800; XMLCh ch2 = toCheck & 0x3FF + 0xDC00; xmlToMbs(&ch1, 1, srcBuf, 1); xmlToMbs(&ch2, 1, srcBuf + uChSize(), 1); srcCount++; } else xmlToMbs((const XMLCh*) &toCheck, 1, srcBuf, 1); size_t len = srcCount * uChSize(); char tmpBuf[64]; char* pTmpBuf = tmpBuf; size_t rc = iconvTo( srcBuf, &len, &pTmpBuf, 64); return (rc != (size_t)-1) && (len == 0); } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 1335 ] ] ]
d9b51be6bdb5dba7071e1c83adac930a93055815
4118f852c5a0a9ac6860de430a26612643eccade
/src/serialport.h
417b8f5ddb5fe7f75b639624eba5cf83d17373cb
[]
no_license
Domesday/BeebEm-AIV
0df6bbea1d0870ffd22a53bb0213992f2d2240a8
24397e4b504822d492ea3731c2ff17858e041968
refs/heads/master
2016-09-06T12:08:59.586263
2011-09-09T21:24:45
2011-09-09T21:24:45
2,354,864
0
0
null
null
null
null
UTF-8
C++
false
false
5,227
h
/**************************************************************** BeebEm - BBC Micro and Master 128 Emulator Copyright (C) 1994 David Alan Gilbert Copyright (C) 1997 Mike Wyatt Copyright (C) 2001 Richard Gellman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ****************************************************************/ /* Module : SERIALPORT.H Purpose: Declaration for an MFC wrapper class for serial ports Created: PJN / 31-05-1999 History: None Copyright (c) 1999 by PJ Naughter. All rights reserved. */ ///////////////////// Macros / Structs etc ////////////////////////// #ifndef __SERIALPORT_H__ #define __SERIALPORT_H__ /////////////////////////// Classes /////////////////////////////////////////// ////// Serial port exception class //////////////////////////////////////////// void AfxThrowSerialException(DWORD dwError = 0); class CSerialException : public CException { public: //Constructors / Destructors CSerialException(DWORD dwError); ~CSerialException(); //Methods #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif virtual BOOL GetErrorMessage(LPTSTR lpstrError, UINT nMaxError, PUINT pnHelpContext = NULL); CString GetErrorMessage(); //Data members DWORD m_dwError; protected: DECLARE_DYNAMIC(CSerialException) }; //// The actual serial port class ///////////////////////////////////////////// class CSerialPort : public CObject { public: //Enums enum FlowControl { NoFlowControl, CtsRtsFlowControl, CtsDtrFlowControl, DsrRtsFlowControl, DsrDtrFlowControl, XonXoffFlowControl }; enum Parity { EvenParity, MarkParity, NoParity, OddParity, SpaceParity }; enum StopBits { OneStopBit, OnePointFiveStopBits, TwoStopBits }; //Constructors / Destructors CSerialPort(); ~CSerialPort(); //General Methods void Open(int nPort, DWORD dwBaud = 9600, Parity parity = NoParity, BYTE DataBits = 8, StopBits stopbits = OneStopBit, FlowControl fc = NoFlowControl, BOOL bOverlapped = FALSE); void Close(); void Attach(HANDLE hComm); HANDLE Detach(); operator HANDLE() const { return m_hComm; }; BOOL IsOpen() const { return m_hComm != INVALID_HANDLE_VALUE; }; #ifdef _DEBUG void CSerialPort::Dump(CDumpContext& dc) const; #endif //Reading / Writing Methods DWORD Read(void* lpBuf, DWORD dwCount); BOOL Read(void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped); void ReadEx(void* lpBuf, DWORD dwCount); DWORD Write(const void* lpBuf, DWORD dwCount); BOOL Write(const void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped); void WriteEx(const void* lpBuf, DWORD dwCount); void TransmitChar(char cChar); void GetOverlappedResult(OVERLAPPED& overlapped, DWORD& dwBytesTransferred, BOOL bWait); void CancelIo(); //Configuration Methods void GetConfig(COMMCONFIG& config); static void GetDefaultConfig(int nPort, COMMCONFIG& config); void SetConfig(COMMCONFIG& Config); static void SetDefaultConfig(int nPort, COMMCONFIG& config); //Misc RS232 Methods void ClearBreak(); void SetBreak(); void ClearError(DWORD& dwErrors); void GetStatus(COMSTAT& stat); void GetState(DCB& dcb); void SetState(DCB& dcb); void Escape(DWORD dwFunc); void ClearDTR(); void ClearRTS(); void SetDTR(); void SetRTS(); void SetXOFF(); void SetXON(); void GetProperties(COMMPROP& properties); void GetModemStatus(DWORD& dwModemStatus); //Timeouts void SetTimeouts(COMMTIMEOUTS& timeouts); void GetTimeouts(COMMTIMEOUTS& timeouts); void Set0Timeout(); void Set0WriteTimeout(); void Set0ReadTimeout(); //Event Methods void SetMask(DWORD dwMask); void GetMask(DWORD& dwMask); void WaitEvent(DWORD& dwMask); void WaitEvent(DWORD& dwMask, OVERLAPPED& overlapped); //Queue Methods void Flush(); void Purge(DWORD dwFlags); void TerminateOutstandingWrites(); void TerminateOutstandingReads(); void ClearWriteBuffer(); void ClearReadBuffer(); void Setup(DWORD dwInQueue, DWORD dwOutQueue); //Overridables virtual void OnCompletion(DWORD dwErrorCode, DWORD dwCount, LPOVERLAPPED lpOverlapped); protected: HANDLE m_hComm; //Handle to the comms port BOOL m_bOverlapped; //Is the port open in overlapped IO static void WINAPI _OnCompletion(DWORD dwErrorCode, DWORD dwCount, LPOVERLAPPED lpOverlapped); DECLARE_DYNAMIC(CSerialPort) }; #endif //__SERIALPORT_H__
[ [ [ 1, 192 ] ] ]
377c936278d563a620bd7f1b6580d58fb5adcc17
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/mpl/aux_/numeric_op.hpp
e7b67e66dfe7234ae8072bbc60158186e89664f0
[ "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
8,715
hpp
#if !defined(BOOST_PP_IS_ITERATING) ///// header body // NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION! // 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/boost/boost/boost/mpl/aux_/numeric_op.hpp,v $ // $Date: 2005/08/25 16:27:21 $ // $Revision: 1.10 $ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/numeric_cast.hpp> # include <boost/mpl/apply_wrap.hpp> # include <boost/mpl/if.hpp> # include <boost/mpl/tag.hpp> # include <boost/mpl/aux_/numeric_cast_utils.hpp> # include <boost/mpl/aux_/na.hpp> # include <boost/mpl/aux_/na_spec.hpp> # include <boost/mpl/aux_/lambda_support.hpp> # include <boost/mpl/aux_/msvc_eti_base.hpp> # include <boost/mpl/aux_/value_wknd.hpp> # include <boost/mpl/aux_/config/eti.hpp> # include <boost/mpl/aux_/nttp_decl.hpp> #endif #include <boost/mpl/aux_/config/static_constant.hpp> #if defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ || defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/limits/arity.hpp> # include <boost/mpl/aux_/preprocessor/partial_spec_params.hpp> # include <boost/mpl/aux_/preprocessor/def_params_tail.hpp> # include <boost/mpl/aux_/preprocessor/repeat.hpp> # include <boost/mpl/aux_/preprocessor/ext_params.hpp> # include <boost/mpl/aux_/preprocessor/params.hpp> # include <boost/mpl/aux_/preprocessor/enum.hpp> # include <boost/mpl/aux_/preprocessor/add.hpp> # include <boost/mpl/aux_/preprocessor/sub.hpp> # include <boost/mpl/aux_/config/ctps.hpp> # include <boost/mpl/aux_/config/eti.hpp> # include <boost/mpl/aux_/config/msvc.hpp> # include <boost/mpl/aux_/config/workaround.hpp> # include <boost/preprocessor/dec.hpp> # include <boost/preprocessor/inc.hpp> # include <boost/preprocessor/iterate.hpp> # include <boost/preprocessor/cat.hpp> #if !defined(AUX778076_OP_ARITY) # define AUX778076_OP_ARITY BOOST_MPL_LIMIT_METAFUNCTION_ARITY #endif #if !defined(AUX778076_OP_IMPL_NAME) # define AUX778076_OP_IMPL_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_impl) #endif #if !defined(AUX778076_OP_TAG_NAME) # define AUX778076_OP_TAG_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_tag) #endif namespace boost { namespace mpl { template< typename Tag1 , typename Tag2 #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) , BOOST_MPL_AUX_NTTP_DECL(int, tag1_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag1)::value , BOOST_MPL_AUX_NTTP_DECL(int, tag2_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag2)::value > struct AUX778076_OP_IMPL_NAME : if_c< ( tag1_ > tag2_ ) #else > struct AUX778076_OP_IMPL_NAME : if_c< ( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1) > BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2) ) #endif , aux::cast2nd_impl< AUX778076_OP_IMPL_NAME<Tag1,Tag1>,Tag1,Tag2 > , aux::cast1st_impl< AUX778076_OP_IMPL_NAME<Tag2,Tag2>,Tag1,Tag2 > >::type { }; /// for Digital Mars C++/compilers with no CTPS/TTP support template<> struct AUX778076_OP_IMPL_NAME<na,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< typename Tag > struct AUX778076_OP_IMPL_NAME<na,Tag> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct AUX778076_OP_IMPL_NAME<Tag,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #else template<> struct AUX778076_OP_IMPL_NAME<na,integral_c_tag> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template<> struct AUX778076_OP_IMPL_NAME<integral_c_tag,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #endif #if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ && BOOST_WORKAROUND(BOOST_MSVC, >= 1300) template< typename T > struct AUX778076_OP_TAG_NAME : tag<T,na> { }; #else template< typename T > struct AUX778076_OP_TAG_NAME { typedef typename T::tag type; }; #endif #if AUX778076_OP_ARITY != 2 # if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) # define AUX778076_OP_RIGHT_OPERAND(unused, i, N) , BOOST_PP_CAT(N, BOOST_MPL_PP_ADD(i, 2))> # define AUX778076_OP_N_CALLS(i, N) \ BOOST_MPL_PP_REPEAT( BOOST_PP_DEC(i), BOOST_MPL_PP_REPEAT_IDENTITY_FUNC, AUX778076_OP_NAME< ) \ N1 BOOST_MPL_PP_REPEAT( BOOST_MPL_PP_SUB(i, 1), AUX778076_OP_RIGHT_OPERAND, N ) \ /**/ template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) BOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename N, na) > struct AUX778076_OP_NAME : AUX778076_OP_N_CALLS(AUX778076_OP_ARITY, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARAMS(AUX778076_OP_ARITY, N) ) ) }; #define BOOST_PP_ITERATION_PARAMS_1 \ (3,( BOOST_PP_DEC(AUX778076_OP_ARITY), 2, <boost/mpl/aux_/numeric_op.hpp> )) #include BOOST_PP_ITERATE() # undef AUX778076_OP_N_CALLS # undef AUX778076_OP_RIGHT_OPERAND # else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION /// forward declaration template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct BOOST_PP_CAT(AUX778076_OP_NAME,2); template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) BOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename N, na) > struct AUX778076_OP_NAME #if BOOST_WORKAROUND(BOOST_MSVC, == 1300) : aux::msvc_eti_base< typename if_< #else : if_< #endif is_na<N3> , BOOST_PP_CAT(AUX778076_OP_NAME,2)<N1,N2> , AUX778076_OP_NAME< BOOST_PP_CAT(AUX778076_OP_NAME,2)<N1,N2> , BOOST_MPL_PP_EXT_PARAMS(3, BOOST_PP_INC(AUX778076_OP_ARITY), N) > >::type #if BOOST_WORKAROUND(BOOST_MSVC, == 1300) > #endif { BOOST_MPL_AUX_LAMBDA_SUPPORT( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARAMS(AUX778076_OP_ARITY, N) ) ) }; template< typename N1 , typename N2 > struct BOOST_PP_CAT(AUX778076_OP_NAME,2) #endif #else // AUX778076_OP_ARITY == 2 template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct AUX778076_OP_NAME #endif #if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG) : AUX778076_OP_IMPL_NAME< typename AUX778076_OP_TAG_NAME<N1>::type , typename AUX778076_OP_TAG_NAME<N2>::type >::template apply<N1,N2>::type #else : aux::msvc_eti_base< typename apply_wrap2< AUX778076_OP_IMPL_NAME< typename AUX778076_OP_TAG_NAME<N1>::type , typename AUX778076_OP_TAG_NAME<N2>::type > , N1 , N2 >::type >::type #endif { #if AUX778076_OP_ARITY != 2 # if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(2, N, na) ) ) # else BOOST_MPL_AUX_LAMBDA_SUPPORT(2, BOOST_PP_CAT(AUX778076_OP_NAME,2), (N1, N2)) # endif #else BOOST_MPL_AUX_LAMBDA_SUPPORT(2, AUX778076_OP_NAME, (N1, N2)) #endif }; BOOST_MPL_AUX_NA_SPEC2(2, AUX778076_OP_ARITY, AUX778076_OP_NAME) }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS ///// iteration, depth == 1 #elif BOOST_PP_ITERATION_DEPTH() == 1 # define i_ BOOST_PP_FRAME_ITERATION(1) template< BOOST_MPL_PP_PARAMS(i_, typename N) > struct AUX778076_OP_NAME<BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na)> #if i_ != 2 : AUX778076_OP_N_CALLS(i_, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na) ) ) }; #endif # undef i_ #endif // BOOST_PP_IS_ITERATING
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 311 ] ] ]
3bdef5378897342a251d5942bc143fc21fc60337
b369aabb8792359175aedfa50e949848ece03180
/src/glWin/procedure.cpp
f0c5dadb7737c177080e86f3f14eb3b8e4fb32dc
[]
no_license
LibreGamesArchive/magiccarpet
6d49246817ab913f693f172fcfc53bf4cc153842
39210d57096d5c412de0f33289fbd4d08c20899b
refs/heads/master
2021-05-08T02:00:46.182694
2009-01-06T20:25:36
2009-01-06T20:25:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,699
cpp
/////////////////////////////////////////////////////////////////////////////// // procedure.cpp // ============= // Window procedure and dialog procedure callback functions. // Windows will call this function whenever an event is triggered. It routes // the message to the controller associated with window handle. // // AUTHOR: Song Ho Ahn ([email protected]) // CREATED: 2006-06-24 // UPDATED: 2007-10-03 /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include "procedure.h" #include "Controller.h" /** * Every window handle has some storage space defined (one LONG), which is * reserved and free for user needs. This programm stores the controller * reference of the controller which is to control the window (react on * window messages) into the window handle. This is done inside the * window proc, when the WM_INITDIALOG message arrives. WM_INITDIALOG is * emitted by CreateDialog() and gets a user defined data item inside its * lparam parameter. The program puts the reference to the controller there. * * As already stated, when the WM_INITDIALOG arrives, the lParam is read and * put into the window handle via SetWindowLongPtr(). As the window proc * receives the handle of the window for which it was called, every subsequent * Window Message, can retrieve the controller from the handle via * GetWindowLongPtr() and can then call the controllers specific methods, so * that the controller reacts on window messages. */ LRESULT CALLBACK Win::windowProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT returnValue = 0; // return value // find controller associated with window handle static Win::Controller *ctrl; ctrl = (Controller*)::GetWindowLongPtr(hwnd, GWL_USERDATA); // Non-Client Create if(msg == WM_NCCREATE) { // WM_NCCREATE message is called before non-client parts(border, // titlebar, menu,etc) are created. This message comes with a pointer // to CREATESTRUCT in lParam. The lpCreateParams member of CREATESTRUCT // actually contains the value of lpPraram of CreateWindowEX(). // First, retrieve the pointrer to the controller specified when // Win::Window is setup. ctrl = (Controller*)(((CREATESTRUCT*)lParam)->lpCreateParams); ctrl->setHandle(hwnd); // Second, store the pointer to the Controller into GWL_USERDATA, // so, other messege can be routed to the associated Controller. ::SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR)ctrl); return ::DefWindowProc(hwnd, msg, wParam, lParam); } // check NULL pointer, because GWL_USERDATA is initially 0, and // we store a valid pointer value when WM_NCCREATE is called. if (!ctrl) return ::DefWindowProc(hwnd, msg, wParam, lParam); // route messages to the associated controller switch(msg) { case WM_CREATE: returnValue = ctrl->create(); break; case WM_SIZE: returnValue = ctrl->size(LOWORD(lParam), HIWORD(lParam), (int)wParam); // width, height, type break; case WM_ENABLE: { bool flag; if(wParam) flag = true; else flag = false; returnValue = ctrl->enable(flag); // TRUE or FALSE break; } case WM_PAINT: ctrl->paint(); returnValue = ::DefWindowProc(hwnd, msg, wParam, lParam); break; case WM_COMMAND: returnValue = ctrl->command(LOWORD(wParam), HIWORD(wParam), lParam); // id, code, msg break; case WM_MOUSEMOVE: //returnValue = ctrl->mouseMove(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; // The WM_CLOSE message is sent as a signal that a window or an // application should terminate. case WM_CLOSE: returnValue = ctrl->close(); break; // The WM_DESTROY message is sent when a window is being destroyed. // It is sent to the window procedure of the window being destroyed // after the window is removed from the screen. // This message is sent first to the window being destroyed and then // to the child windows (if any) as they are destroyed. During the // processing of the message, it can be assumed that all child // windows still exist. case WM_DESTROY: returnValue = ctrl->destroy(); break; case WM_SYSCOMMAND: //returnValue = ctrl->sysCommand(wParam, lParam); returnValue = ::DefWindowProc(hwnd, msg, wParam, lParam); break; /* // Disable Alt-F4 and screensavers switch (wparam & 0xfff0) { case SC_CLOSE: case SC_SCREENSAVE: ret = 0; break; default: returnValue = DefWindowProc(hwnd, message, wparam, lparam); break; } break; */ case WM_CHAR: //returnValue = ctrl->char(wParam, lParam); // route keycode break; case WM_KEYDOWN: case WM_SYSKEYDOWN: //std::cout << "key down in wndproc" << std::endl; returnValue = ctrl->keyDown((int)wParam, lParam); // keyCode, keyDetail break; case WM_KEYUP: case WM_SYSKEYUP: //std::cout << "key up in wndproc" << std::endl; returnValue = ctrl->keyUp((int)wParam, lParam); // keyCode, keyDetail break; case WM_LBUTTONDOWN: returnValue = ctrl->lButtonDown(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_LBUTTONUP: returnValue = ctrl->lButtonUp(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_RBUTTONDOWN: returnValue = ctrl->rButtonDown(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_RBUTTONUP: returnValue = ctrl->rButtonUp(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_MBUTTONDOWN: returnValue = ctrl->mButtonDown(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_MBUTTONUP: returnValue = ctrl->mButtonUp(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y break; case WM_MOUSEWHEEL: //returnValue = ctrl->(LOWORD(wParam), HIWORD(wParam), LOWORD(lParam), HIWORD(lParam)); // state, delta, x, y break; case WM_HSCROLL: returnValue = ctrl->hScroll(wParam, lParam); break; case WM_VSCROLL: returnValue = ctrl->vScroll(wParam, lParam); break; case WM_TIMER: returnValue = ctrl->timer(LOWORD(wParam), HIWORD(wParam)); break; case WM_NOTIFY: returnValue = ctrl->notify((int)wParam, lParam); // controllerID, lParam break; case WM_CONTEXTMENU: returnValue = ctrl->contextMenu((HWND)wParam, LOWORD(lParam), HIWORD(lParam)); // handle, x, y (from screen coords) //case WM_ERASEBKGND: // returnValue = ctrl->eraseBkgnd((HDC)wParam); // handle to device context // break; default: returnValue = ::DefWindowProc(hwnd, msg, wParam, lParam); } return returnValue; } /** * Dialog Procedure * It must return true if the message is handled. * * Every window handle has some storage space defined (one LONG), which is * reserved and free for user needs. This programm stores the controller * reference of the controller which is to control the window (react on * window messages) into the window handle. This is done inside the * window proc, when the WM_INITDIALOG message arrives. WM_INITDIALOG is * emitted by CreateDialog() and gets a user defined data item inside its * lparam parameter. The program puts the reference to the controller there. * * As already stated, when the WM_INITDIALOG arrives, the lParam is read and * put into the window handle via SetWindowLongPtr(). As the window proc * receives the handle of the window for which it was called, every subsequent * Window Message, can retrieve the controller from the handle via * GetWindowLongPtr() and can then call the controllers specific methods, so * that the controller reacts on window messages. */ BOOL CALLBACK Win::dialogProcedure(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { // find controller associated with window handle static Win::Controller *ctrl; ctrl = (Controller*)::GetWindowLongPtr(hwnd, GWL_USERDATA); // WM_INITDIALOG message is called before displaying the dialog box. // lParam contains the value of dwInitParam of CreateDialogBoxParam(), // which is the pointer to the Controller. if(msg == WM_INITDIALOG) { // First, retrieve the pointrer to the controller associated with // the current dialog box. ctrl = (Controller*)lParam; ctrl->setHandle(hwnd); // Second, store the pointer to the Controller into GWL_USERDATA, // so, other messege can be routed to the associated Controller. ::SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR)ctrl); // When WM_INITDIALOG is called, all controls in the dialog are created. // It is good time to initalize the appearance of controls here. // NOTE that we don't handle WM_CREATE message for dialogs because // the message is sent before controls have been create, so you cannot // access them in WM_CREATE message handler. ctrl->create(); return true; } // check NULL pointer, because GWL_USERDATA is initially 0, and // we store a valid pointer value when WM_NCCREATE is called. if(!ctrl) return false; switch(msg) { case WM_COMMAND: ctrl->command(LOWORD(wParam), HIWORD(wParam), lParam); // id, code, msg return true; case WM_TIMER: ctrl->timer(LOWORD(wParam), HIWORD(wParam)); return true; case WM_PAINT: ctrl->paint(); ::DefWindowProc(hwnd, msg, wParam, lParam); return true; case WM_DESTROY: ctrl->destroy(); return true; case WM_CLOSE: ctrl->close(); return true; case WM_HSCROLL: ctrl->hScroll(wParam, lParam); return true; case WM_VSCROLL: ctrl->vScroll(wParam, lParam); return true; case WM_NOTIFY: ctrl->notify((int)wParam, lParam); // controllerID, lParam return true; case WM_MOUSEMOVE: ctrl->mouseMove(wParam, LOWORD(lParam), HIWORD(lParam)); //ctrl->mouseMove(wParam, (int)GET_X_LPARAM(lParam), (int)GET_Y_LPARAM(lParam)); // state, x, y return true; case WM_LBUTTONUP: ctrl->lButtonUp(wParam, LOWORD(lParam), HIWORD(lParam)); // state, x, y return true; case WM_CONTEXTMENU: ctrl->contextMenu((HWND)wParam, LOWORD(lParam), HIWORD(lParam)); // handle, x, y (from screen coords) return true; default: return false; } }
[ [ [ 1, 313 ] ] ]
4bf3944af202c61ad9d4bddecbd2b0fc59649232
a7985fd90271731c73cab45029ee9a9903c8e1a2
/client/westley.hennigh_cs260/westley.hennigh_cs260/Window.cpp
69ce557ef229313eb227c4a0af5a0662846607f7
[]
no_license
WestleyArgentum/cs260-networking
129039f7ad2a89b9350ddcac0cc50a17c6f74bf7
36d2d34400ad93906e2b4839278e4b33de28ae8b
refs/heads/master
2021-01-01T05:47:12.910324
2010-04-07T07:01:40
2010-04-07T07:01:40
32,187,121
0
0
null
null
null
null
UTF-8
C++
false
false
6,845
cpp
// Westley Hennigh // Window.cpp : simple wrapper around windows shit // CS260 Assignment 2 // Feb 22th 2010 #include "Window.hpp" #include <tchar.h> // The string that appears in the application's title bar. const static TCHAR szTitle[] = _T("Meep_Meep"); // The main window class name. const static TCHAR szWindowClass[] = _T("win32app"); const int windowSizeX = 800; const int windowSizeY = 600; const int readOnlyTextBoxSizeX = 500; const int readOnlyTextBoxSizeY = 400; const int readOnlyTextBoxPosX = 150; const int readOnlyTextBoxPosY = 10; const int textBoxSizeX = 500; const int textBoxSizeY = 100; const int textBoxPosX = 150; const int textBoxPosY = 450; const int okButtonSizeX = 100; const int okButtonSizeY = 100; const int okButtonPosX = 670; const int okButtonPosY = 450; const int quitButtonSizeX = 75; const int quitButtonSizeY = 300; const int quitButtonPosX = 30; const int quitButtonPosY = 10; const int listBoxSizeX = 100; const int listBoxSizeY = 400; const int listBoxPosX = 670; const int listBoxPosY = 10; SillyWindow* SillyWindow::window = NULL; // init static pointer SillyWindow::SillyWindow() {} SillyWindow* SillyWindow::GetWindow() { if (!window) window = new SillyWindow; return window; } void SillyWindow::MakeSillyWindow(LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM), HINSTANCE hInstance, int nCmdShow) { //set up your main window class. this class will hold all of your controls //and will be used for the main window WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); //register the class so that you can use it in the future if (!RegisterClassEx(&wcex)) { MessageBox(NULL, _T("Call to RegisterClassEx failed!"), szTitle, NULL); return; } //hInst = hInstance; // Store instance handle in our global variable // The parameters to CreateWindow explained: // szWindowClass: the name of the application // szTitle: the text that appears in the title bar // WS_OVERLAPPEDWINDOW: the type of window to create // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y) // 500, 100: initial size (width, length) // NULL: the parent of this window // NULL: this application doews not have a menu bar // hInstance: the first parameter from WinMain // NULL: not used in this application HWND hWnd = CreateWindow( szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, windowSizeX, windowSizeY, NULL, NULL, hInstance, NULL ); if (!hWnd) { MessageBox(NULL, _T("Call to CreateWindow failed!"), szTitle, NULL); return; } //now hWnd is the handle to our main window //we're going to create a textbox. This is exactly the same as creating a window, however //it's actually a child "window" of the parent window that we just created, so it's technically //not a window although in some ways it behaves like one //We give the class name "EDIT" so that it creates //a textbox instead of an actual window edit = CreateWindow( _T("EDIT"), NULL, WS_VISIBLE | WS_CHILD | WS_VSCROLL | ES_MULTILINE | WS_BORDER, textBoxPosX, textBoxPosY, textBoxSizeX, textBoxSizeY, hWnd, //instead of NULL, here we pass the handle to the window that we want this control to live in NULL, hInstance, NULL ); output = CreateWindow( _T("EDIT"), NULL, WS_VISIBLE | WS_CHILD | WS_VSCROLL | ES_MULTILINE | ES_READONLY | WS_BORDER, //adding readonly for this one readOnlyTextBoxPosX, readOnlyTextBoxPosY, readOnlyTextBoxSizeX, readOnlyTextBoxSizeY, hWnd,//same parent window as before NULL, hInstance, NULL ); // progress bar progress = CreateWindow( _T("EDIT"), NULL, WS_VISIBLE | WS_CHILD | ES_READONLY | WS_BORDER, //adding readonly for this one 150, 420, 500, 20, hWnd,//same parent window as before NULL, hInstance, NULL ); // ---- HWND hwndButton = CreateWindow( _T("BUTTON"), // Predefined class; Unicode assumed. _T("OK"), // Button text. WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_BORDER, // Styles. okButtonPosX, // x position. okButtonPosY, // y position. okButtonSizeX, // Button width. okButtonSizeY, // Button height. hWnd, // Parent window. (HMENU)ID_OKBUTTON, // No menu. (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE), NULL); // Pointer not needed. HWND hwndQuitButton = CreateWindow( _T("BUTTON"), // Predefined class; Unicode assumed. _T("BIG QUIT"), // Button text. WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_BORDER, // Styles. quitButtonPosX, // x position. quitButtonPosY, // y position. quitButtonSizeX, // Button width. quitButtonSizeY, // Button height. hWnd, // Parent window. (HMENU)ID_QUITBUTTON, // No menu. (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE), NULL); // Pointer not needed. listbox = CreateWindow( _T("LISTBOX"), _T("ListBox1"), WS_TABSTOP | WS_VISIBLE | WS_CHILD | LBS_NOSEL | LBS_SORT | WS_BORDER, listBoxPosX, listBoxPosY, listBoxSizeX, listBoxSizeY, hWnd, NULL, (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE), NULL); // use SendMessage to control the properties of controls. pass the handle to the control // that you want to set the property of // This particular message is useful because it allows you to limit the amount of text that a // user can type into a textbox so that you can ensure that you don't have more text than your // buffer can hold when sending the text accross the network. Otherwise you'll have to call // send and recv multiple times to ensure that you get all of the text. Don't assume that the text // will be null-terminated in the buffer when you call recv just because it is when you called send() SendMessage(edit, EM_SETLIMITTEXT, (WPARAM)200, 0); SendMessage(output, EM_SETLIMITTEXT, (WPARAM)25, 0); // The parameters to ShowWindow explained: // hWnd: the value returned from CreateWindow // nCmdShow: the fourth parameter from WinMain ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); }
[ "[email protected]@1f2afcba-5144-80f4-e828-afee2f9acc6f", "knuxjr@1f2afcba-5144-80f4-e828-afee2f9acc6f" ]
[ [ [ 1, 33 ], [ 35, 156 ], [ 173, 233 ] ], [ [ 34, 34 ], [ 157, 172 ] ] ]
c232ddf17ecb4033ca34d5851f821c1b0a3be17b
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/GameNode.cpp
a2e5725bfc74f29a775e2fbda3fa712fd899e090
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UHC
C++
false
false
7,767
cpp
#include <Halak/PCH.h> #include <Halak/GameNode.h> #include <Halak/Assert.h> #include <Halak/Exception.h> #include <Halak/GameComponent.h> #include <Halak/GameStructure.h> #include <algorithm> namespace Halak { GameNode::GameNode(GameComponent* component) : component(component), parent(nullptr), structure(nullptr) { HKAssert(component); } GameNode::GameNode(NullComponentTag) : component(nullptr), parent(nullptr), structure(nullptr) { } GameNode::~GameNode() { DetachAllChildren(); if (component) { GameComponent* temporaryComponent = nullptr; std::swap(temporaryComponent, component); temporaryComponent->node = nullptr; delete temporaryComponent; } } GameNode* GameNode::AttachChild(GameComponent* item) { HKAssert(item); if (item->node == nullptr) item->node = new GameNode(item); AttachChild(item->node); return item->node; } void GameNode::AttachChild(GameNode* item) { HKAssert(item); if (item->parent == this) return; const bool structureChanged = (item->parent == nullptr || item->parent->structure != structure); if (GameNode* oldParent = item->parent) { NodeCollection::iterator it = std::find(oldParent->children.begin(), oldParent->children.end(), item); HKAssertDebug(it != oldParent->children.end()); oldParent->children.erase(it); item->parent = nullptr; // GameStructure::OnGameNodeDetached의 명세대로 GameStructure가 바뀌었을 때만 호출합니다. if (oldParent->structure && structureChanged) oldParent->structure->OnGameNodeDetached(oldParent, item); } item->parent = this; children.push_back(item); // GameStructure::OnGameNodeAttached의 명세대로 GameStructure가 바뀌었을 때만 호출합니다. if (structure && structureChanged) structure->OnGameNodeAttached(this, item); } bool GameNode::DetachChild(GameNode* item) { HKAssert(item); if (item->parent != this || item->structure != this->structure) return false; NodeCollection::iterator it = std::find(children.begin(), children.end(), item); HKAssertDebug(it != children.end()); // 이미 item의 부모가 this인지 확인했기 때문에 반드시 있어야합니다. children.erase(it); item->parent = nullptr; if (structure) structure->OnGameNodeDetached(this, item); delete item; return true; } void GameNode::DetachAllChildren() { NodeCollection temporaryChildren; temporaryChildren.swap(children); for (NodeCollection::reverse_iterator it = temporaryChildren.rbegin(); it != temporaryChildren.rend(); it++) { if (structure) structure->OnGameNodeDetached(this, *it); delete (*it); } } GameComponent* GameNode::FindChild(uint32 id, bool searchAllChildren) const { if (GameNode* foundNode = FindChildNode(id, searchAllChildren)) return foundNode->GetComponent(); else return nullptr; } GameComponent* GameNode::FindChildByClassID(uint32 id, bool searchAllChildren) const { if (GameNode* foundNode = FindChildNodeByClassID(id, searchAllChildren)) return foundNode->GetComponent(); else return nullptr; } GameNode* GameNode::FindChildNode(uint32 id, bool searchAllChildren) const { if (id == GameComponent::UnspecifiedID) return nullptr; if (searchAllChildren) { for (NodeCollection::const_iterator it = children.begin(); it != children.end(); it++) { if ((*it)->GetComponent() && (*it)->GetComponent()->GetID() == id) return (*it); if (GameNode* foundNode = (*it)->FindChildNode(id, true)) return foundNode; } } else { for (NodeCollection::const_iterator it = children.begin(); it != children.end(); it++) { if ((*it)->GetComponent() && (*it)->GetComponent()->GetID() == id) return (*it); } } return nullptr; } GameNode* GameNode::FindChildNodeByClassID(uint32 id, bool searchAllChildren) const { if (searchAllChildren) { for (NodeCollection::const_iterator it = children.begin(); it != children.end(); it++) { if ((*it)->GetComponent() && (*it)->GetComponent()->GetClassID() == id) return (*it); if (GameNode* foundNode = (*it)->FindChildNodeByClassID(id, true)) return foundNode; } } else { for (NodeCollection::const_iterator it = children.begin(); it != children.end(); it++) { if ((*it)->GetComponent() && (*it)->GetComponent()->GetClassID() == id) return (*it); } } return nullptr; } GameNode* GameNode::FindChildNode(GameComponent* item, bool searchAllChildren) const { // 원래는 모든 자식 Node들을 순회하며 검사해야하지만, // GameComponent에서 자신을 가진 Node를 아는 관계로 최적화할 수 있었습니다. // searchAllChildren == true : GameComponent의 조상Node중 this가 있는지 확인합니다. // == false : GameComponent의 부모Node가 this인지 확인합니다. if (item->node == nullptr || item->node->structure != structure) return nullptr; if (searchAllChildren) { struct ThisIsAncestor { static bool Do(GameNode* descendant, const GameNode* ancestor) { if (descendant->parent == nullptr) return false; if (descendant->parent == ancestor) return true; else return Do(descendant->parent, ancestor); } }; if (ThisIsAncestor::Do(item->node, this)) return item->node; else return nullptr; } else { if (item->node->parent == this) { HKAssertDebug(std::find(children.begin(), children.end(), item->node) != children.end()); return item->node; } else return nullptr; } } void GameNode::OnComponentDestructed() { component = nullptr; } void GameNode::OnComponentAliveChanged() { // Alive => 상위 GameComponent와 하위 GameComponent들을 모두 Alive로 만듭니다. // Dead => 하위 GameComponent들을 모두 Dead상태로 만듭니다. const bool alive = component->GetAlive(); if (alive && parent) parent->component->SetAlive(true); for (NodeCollection::iterator it = children.begin(); it != children.end(); it++) (*it)->component->SetAlive(alive); } }
[ [ [ 1, 244 ] ] ]
c5608171a38354f4fb00825cb3cdbccdf29e2328
2b80036db6f86012afcc7bc55431355fc3234058
/src/contrib/waveout/WaveOut.cpp
e6232dc44a65fc191ee371161e1b4784f9fd7216
[ "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
UTF-8
C++
false
false
8,182
cpp
////////////////////////////////////////////////////////////////////////////// // Copyright 2007, Daniel nnerby // // 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. // ////////////////////////////////////////////////////////////////////////////// #include "WaveOut.h" WaveOut::WaveOut() :waveHandle(NULL) ,maxBuffers(32) ,currentVolume(1.0) ,addToRemovedBuffers(false) { } WaveOut::~WaveOut(){ this->ClearBuffers(); if(this->waveHandle!=NULL){ waveOutClose(this->waveHandle); this->waveHandle = NULL; } } void WaveOut::Destroy(){ delete this; } /* void WaveOut::Initialize(IPlayer *player){ this->player = player; } */ void WaveOut::Pause(){ waveOutPause(this->waveHandle); } void WaveOut::Resume(){ waveOutRestart(this->waveHandle); } void WaveOut::SetVolume(double volume){ if(this->waveHandle){ DWORD newVolume = (DWORD)(volume*65535.0); newVolume += newVolume*65536; waveOutSetVolume(this->waveHandle,newVolume); } this->currentVolume = volume; } void WaveOut::ClearBuffers(){ waveOutReset(this->waveHandle); } void WaveOut::RemoveBuffer(WaveOutBuffer *buffer){ BufferList clearBuffers; { boost::mutex::scoped_lock lock(this->mutex); bool found(false); for(BufferList::iterator buf=this->buffers.begin();buf!=this->buffers.end() && !found;){ if(buf->get()==buffer){ // if( !(*buf)->ReadyToRelease() ){ this->removedBuffers.push_back(*buf); // } clearBuffers.push_back(*buf); buf=this->buffers.erase(buf); found=true; }else{ ++buf; } } } } void WaveOut::ReleaseBuffers(){ BufferList clearBuffers; { boost::mutex::scoped_lock lock(this->mutex); for(BufferList::iterator buf=this->removedBuffers.begin();buf!=this->removedBuffers.end();){ clearBuffers.push_back(*buf); buf = this->removedBuffers.erase(buf); } } } bool WaveOut::PlayBuffer(IBuffer *buffer,IPlayer *player){ size_t bufferSize = 0; { boost::mutex::scoped_lock lock(this->mutex); bufferSize = this->buffers.size(); } // if the format should change, wait for all buffers to be released if(bufferSize>0 && (this->currentChannels!=buffer->Channels() || this->currentSampleRate!=buffer->SampleRate())){ // Format has changed // this->player->Notify() return false; } if(bufferSize<this->maxBuffers){ // Start by checking the format this->SetFormat(buffer); // Add to the waveout internal buffers WaveOutBufferPtr waveBuffer(new WaveOutBuffer(this,buffer,player)); // Header should now be prepared, lets add to waveout if( waveBuffer->AddToOutput() ){ // Add to the buffer list { boost::mutex::scoped_lock lock(this->mutex); this->buffers.push_back(waveBuffer); } return true; } } return false; } void WaveOut::SetFormat(IBuffer *buffer){ if(this->currentChannels!=buffer->Channels() || this->currentSampleRate!=buffer->SampleRate() ||this->waveHandle==NULL){ this->currentChannels = buffer->Channels(); this->currentSampleRate = buffer->SampleRate(); // Close old waveout if(this->waveHandle!=NULL){ waveOutClose(this->waveHandle); this->waveHandle = NULL; } // Create a new waveFormat ZeroMemory(&this->waveFormat, sizeof(this->waveFormat)); DWORD speakerconfig; // Set speaker configuration switch(buffer->Channels()){ case 1: speakerconfig = KSAUDIO_SPEAKER_MONO; break; case 2: speakerconfig = KSAUDIO_SPEAKER_STEREO; break; case 4: speakerconfig = KSAUDIO_SPEAKER_QUAD; break; case 5: speakerconfig = (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 6: speakerconfig = KSAUDIO_SPEAKER_5POINT1; break; default: speakerconfig = 0; } this->waveFormat.Format.cbSize = 22; this->waveFormat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; this->waveFormat.Format.nChannels = (WORD)buffer->Channels(); this->waveFormat.Format.nSamplesPerSec = (DWORD)buffer->SampleRate(); this->waveFormat.Format.wBitsPerSample = 32; this->waveFormat.Format.nBlockAlign = (this->waveFormat.Format.wBitsPerSample/8) * this->waveFormat.Format.nChannels; this->waveFormat.Format.nAvgBytesPerSec = ((this->waveFormat.Format.wBitsPerSample/8) * this->waveFormat.Format.nChannels) * this->waveFormat.Format.nSamplesPerSec; //Compute using nBlkAlign * nSamp/Sec // clangen: wValidBitsPerSample/wReserved/wSamplesPerBlock are a union, // so don't set wReserved or wSamplesPerBlock to 0 after assigning // wValidBitsPerSample. (Vista bug) this->waveFormat.Samples.wValidBitsPerSample = 32; this->waveFormat.dwChannelMask = speakerconfig; this->waveFormat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; // Create new waveout int openResult = waveOutOpen( &this->waveHandle, WAVE_MAPPER, (WAVEFORMATEX*)&this->waveFormat, (DWORD_PTR)WaveCallback, (DWORD_PTR)this, CALLBACK_FUNCTION); if(openResult!=MMSYSERR_NOERROR){ throw; } // Set the volume if it's not already set this->SetVolume(this->currentVolume); } } void CALLBACK WaveOut::WaveCallback(HWAVEOUT waveHandle, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD dw2){ if(msg==WOM_DONE){ // A buffer is finished, lets release it LPWAVEHDR waveoutHeader = (LPWAVEHDR)dw1; WaveOutBuffer *waveOutBuffer = (WaveOutBuffer*)waveoutHeader->dwUser; waveOutBuffer->waveOut->RemoveBuffer(waveOutBuffer); waveOutBuffer->player->Notify(); } }
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "bjorn.olievier@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 1 ], [ 11, 11 ], [ 15, 15 ], [ 19, 19 ], [ 34, 34 ], [ 36, 37 ], [ 40, 42 ], [ 45, 45 ], [ 50, 50 ], [ 52, 53 ], [ 56, 57 ], [ 61, 61 ], [ 65, 65 ], [ 69, 69 ], [ 74, 74 ], [ 79, 79 ], [ 82, 83 ], [ 102, 103 ], [ 109, 110 ], [ 115, 116 ], [ 123, 131 ], [ 135, 135 ], [ 137, 138 ], [ 148, 148 ], [ 150, 150 ], [ 152, 153 ], [ 197, 200 ], [ 222, 223 ], [ 229, 229 ], [ 231, 231 ], [ 233, 233 ] ], [ [ 2, 10 ], [ 12, 14 ], [ 16, 18 ], [ 20, 33 ], [ 35, 35 ], [ 38, 39 ], [ 43, 44 ], [ 46, 49 ], [ 51, 51 ], [ 54, 55 ], [ 58, 60 ], [ 62, 64 ], [ 66, 68 ], [ 70, 73 ], [ 75, 78 ], [ 80, 81 ], [ 84, 100 ], [ 104, 108 ], [ 111, 114 ], [ 117, 122 ], [ 132, 134 ], [ 136, 136 ], [ 139, 147 ], [ 151, 151 ], [ 154, 196 ], [ 201, 221 ], [ 224, 228 ], [ 230, 230 ], [ 232, 232 ] ], [ [ 101, 101 ], [ 149, 149 ] ] ]
138b0af2a89b6bb2fb06a74adf7b0903e1b991f1
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/context_text.h
eeb1e9472a18ccaa32359bc8c205cc9c44a9592d
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,402
h
#ifndef CONTEXT_TEXT_H #define CONTEXT_TEXT_H #include "wx/string.h" #include "wx/wxscintilla.h" #include "smart_ptr.h" #include "context_base.h" class LEditor; /** * \ingroup LiteEditor * \brief the basic editor from which complicated editors derives from (e.g. ContextCpp) * * \version 1.0 * first version * * \date 04-30-2007 * * \author Eran * * */ class ContextText : public ContextBase { public: //--------------------------------------- // ctors-dtor //--------------------------------------- ContextText(LEditor *container); ContextText() : ContextBase(wxT("Text")) {}; virtual ~ContextText(); LEditor &GetCtrl() { return *m_container; } virtual ContextBase *NewInstance(LEditor *container); //--------------------------------------- // Operations //--------------------------------------- virtual void CompleteWord(); virtual void CodeComplete(); virtual void GotoDefinition(); virtual void GotoPreviousDefintion(); virtual void AutoIndent(const wxChar&); virtual void CallTipCancel(){}; virtual bool IsCommentOrString(long WXUNUSED(pos)){ return false; } // event handlers virtual void OnDwellEnd(wxScintillaEvent & WXUNUSED(event)) {}; virtual void OnCallTipClick(wxScintillaEvent& WXUNUSED(event)) {}; virtual void OnDwellStart(wxScintillaEvent & WXUNUSED(event)) {}; }; #endif // CONTEXT_TEXT_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 53 ] ] ]
ed555c95ec4c5a975297ac156375920256db4a8c
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/wiseml/writer/tasks/wiseml_scenario_task.cpp
b8b5db2119b3f3042b217ca611eaef92d45296d3
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,080
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2010 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "apps/wiseml/writer/tasks/wiseml_scenario_task.h" #ifdef ENABLE_WISEML #include "apps/wiseml/writer/wiseml_data_keeper.h" namespace wiseml { WisemlScenarioTask::WisemlScenarioTask() { } // ---------------------------------------------------------------------- WisemlScenarioTask::~WisemlScenarioTask() { } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- std::string WisemlScenarioTask::name() const throw() { return "wiseml_scenario"; } // ---------------------------------------------------------------------- std::string WisemlScenarioTask::description() const throw() { return "Creates a new scenario."; } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- void WisemlScenarioTask::run(SimulationController &sc) throw() { WisemlDataKeeper *keeper = sc.keeper_by_name_w<WisemlDataKeeper>("wiseml_data_keeper"); if(keeper == NULL) { cout << "WisemlScenarioTask:" << " Unable to create scenario because WisemlDataKeeper was not" << " found. Make shure to run wiseml_setup before this task, or" << " to create a WisemlDataKeeper by code." << endl; return; } keeper->add_scenario(sc.environment().required_string_param("id")); } } #endif
[ [ [ 1, 49 ] ] ]
8133e146d7eebeb7e10ceb57cadd927029cd18ba
f6a0496efe3e5c93b68c1df66ce35e1c22c9b7b0
/Source/include/LuaFloat.h
7cf6c387578204108bc86aaeb04aed51f22f6fce
[]
no_license
jhays200/C---Lua-Interpreter
479cce89eb782b577e0f350bc4c34e8357b75de6
9ebf62c0ded847753dec0fc98e62445b234eccd4
refs/heads/master
2020-05-18T15:56:23.933827
2011-03-10T20:04:38
2011-03-10T20:04:38
1,462,811
7
7
null
null
null
null
UTF-8
C++
false
false
533
h
#pragma once #include "LuaObject.h" class LuaFloat: public LuaObject { private: double m_value; public: LuaFloat(); LuaFloat(string id, double value); ~LuaFloat(); virtual LuaObject& operator=(LuaObject & rhs); void DisplayValue(); double getValue() const; void setValue(double value); virtual LuaObject operator+(LuaObject & rhs); virtual LuaObject operator-(LuaObject & rhs); virtual LuaObject operator/(LuaObject & rhs); virtual LuaObject operator*(LuaObject & rhs); virtual int getType(); };
[ [ [ 1, 23 ] ] ]
05ccd975387a4ee40e5ae1772acb2abcdd74b530
6581dacb25182f7f5d7afb39975dc622914defc7
/CodeProject/ExcelAddinInEasyIF/MtxEdCol.h
e02fb5e78eb76e75145cea79b0f34e5d4a834017
[]
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
1,746
h
#if !defined(AFX_MTXEDCOL_H__9F2EBE78_17A7_48C4_99F5_BEAC5755947A__INCLUDED_) #define AFX_MTXEDCOL_H__9F2EBE78_17A7_48C4_99F5_BEAC5755947A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // MtxEdCol.h : header file // #include "matrix.h" ///////////////////////////////////////////////////////////////////////////// // MatrixEditCol dialog class MatrixEditCol : public CPropertyPage { DECLARE_DYNCREATE(MatrixEditCol) Matrix *m_pMatrix; // Construction public: MatrixEditCol(); MatrixEditCol(Matrix *pMatrix); ~MatrixEditCol(); void LoadColumnList(); // Dialog Data //{{AFX_DATA(MatrixEditCol) enum { IDD = IDD_MTXEDIT_COLUMNS }; CListCtrl m_oColList; int m_iReturnType; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(MatrixEditCol) public: virtual BOOL OnKillActive(); virtual void OnOK(); virtual BOOL OnSetActive(); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(MatrixEditCol) afx_msg void OnColsAdd(); afx_msg void OnColsProperties(); afx_msg void OnColsRemove(); virtual BOOL OnInitDialog(); afx_msg void OnDblclkColsList(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnColsMovedown(); afx_msg void OnColsMoveup(); afx_msg void OnItemchangedColsList(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MTXEDCOL_H__9F2EBE78_17A7_48C4_99F5_BEAC5755947A__INCLUDED_)
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 67 ] ] ]
f727f77f060f1a61d5adc99a5e2cdb46a13b5e75
b4d726a0321649f907923cc57323942a1e45915b
/CODE/ImpED/ShipSpecialDamage.cpp
efa66bdad80a5e53034042982b6d79165139db44
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
6,170
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ // ShipSpecialDamage.cpp : implementation file // #include "stdafx.h" #include "FRED.h" #include "ShipSpecialDamage.h" #include "globalincs/linklist.h" #include "parse/sexp.h" #include "FREDDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // ShipSpecialDamage dialog ShipSpecialDamage::ShipSpecialDamage(CWnd* pParent /*=NULL*/) : CDialog(ShipSpecialDamage::IDD, pParent) { //{{AFX_DATA_INIT(ShipSpecialDamage) //}}AFX_DATA_INIT } void ShipSpecialDamage::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(ShipSpecialDamage) DDX_Check(pDX, IDC_ENABLE_SHOCKWAVE, m_shock_enabled); DDX_Check(pDX, IDC_ENABLE_SPECIAL_EXP, m_special_exp_enabled); DDX_Text(pDX, IDC_SPECIAL_INNER_RAD, m_inner_rad); DDV_MinMaxInt(pDX, m_inner_rad, 10, 10000); DDX_Text(pDX, IDC_SPECIAL_OUTER_RAD, m_outer_rad); DDV_MinMaxInt(pDX, m_outer_rad, 11, 10000); DDX_Text(pDX, IDC_SPECIAL_DAMAGE, m_damage); DDV_MinMaxInt(pDX, m_damage, 0, 100000); DDX_Text(pDX, IDC_SPECIAL_SHOCK_SPEED, m_shock_speed); DDV_MinMaxInt(pDX, m_shock_speed, 10, 10000); DDX_Text(pDX, IDC_SPECIAL_BLAST, m_blast); DDV_MinMaxInt(pDX, m_blast, 0, 100000); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(ShipSpecialDamage, CDialog) //{{AFX_MSG_MAP(ShipSpecialDamage) ON_BN_CLICKED(IDC_ENABLE_SHOCKWAVE, OnEnableShockwave) ON_BN_CLICKED(IDC_ENABLE_SPECIAL_EXP, OnEnableSpecialExp) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // ShipSpecialDamage message handlers void ShipSpecialDamage::OnEnableShockwave() { // TODO: Add your control notification handler code here UpdateData(TRUE); // enable/disable shock speed DoGray();} void ShipSpecialDamage::OnEnableSpecialExp() { // TODO: Add your control notification handler code here UpdateData(TRUE); DoGray(); } BOOL ShipSpecialDamage::OnInitDialog() { // TODO: Add extra initialization here // get ship num object *objp; m_ship_num = -1; objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if ((objp->type == OBJ_START) || (objp->type == OBJ_SHIP)) { if (objp->flags & OF_MARKED) { m_ship_num = objp->instance; break; } } objp = GET_NEXT(objp); } if (Ships[m_ship_num].special_exp_index == -1) { // get default_table_values ship_info *sip; sip = &Ship_info[Ships[m_ship_num].ship_info_index]; m_inner_rad = (int)sip->inner_rad; m_outer_rad = (int)sip->outer_rad; m_damage = (int) sip->damage; m_blast = (int) sip->blast; m_shock_enabled = (int) sip->explosion_propagates; m_shock_speed = (int) sip->shockwave_speed; m_special_exp_enabled = FALSE; if (m_inner_rad < 10) m_inner_rad = 10; if (m_outer_rad < 11) m_outer_rad = 11; if (m_shock_speed < 10) m_shock_speed = 10; } else { int index = Ships[m_ship_num].special_exp_index; Assert( (index > 0) && (index < MAX_SEXP_VARIABLES-(BLOCK_EXP_SIZE-1)) ); m_inner_rad = atoi(Sexp_variables[index++].text); m_outer_rad = atoi(Sexp_variables[index++].text); m_damage = atoi(Sexp_variables[index++].text); m_blast = atoi(Sexp_variables[index++].text); m_shock_enabled = atoi(Sexp_variables[index++].text); m_shock_speed = atoi(Sexp_variables[index++].text); m_special_exp_enabled = TRUE; } CDialog::OnInitDialog(); // maybe gray out lots of stuff DoGray(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void ShipSpecialDamage::DoGray() { GetDlgItem(IDC_SPECIAL_DAMAGE)->EnableWindow(m_special_exp_enabled); GetDlgItem(IDC_SPECIAL_BLAST)->EnableWindow(m_special_exp_enabled); GetDlgItem(IDC_SPECIAL_INNER_RAD)->EnableWindow(m_special_exp_enabled); GetDlgItem(IDC_SPECIAL_OUTER_RAD)->EnableWindow(m_special_exp_enabled); GetDlgItem(IDC_ENABLE_SHOCKWAVE)->EnableWindow(m_special_exp_enabled); GetDlgItem(IDC_SPECIAL_SHOCK_SPEED)->EnableWindow(m_special_exp_enabled && m_shock_enabled); } void ShipSpecialDamage::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); } void ShipSpecialDamage::OnOK() { UpdateData(TRUE); // TODO: Add extra validation here if (m_special_exp_enabled) { int start; if (m_inner_rad > m_outer_rad) { MessageBox("Inner radius must be less than outer radius"); return; } if (Ships[m_ship_num].special_exp_index == -1) { // get free sexp_variables start = sexp_variable_allocate_block(Ships[m_ship_num].ship_name, SEXP_VARIABLE_BLOCK | SEXP_VARIABLE_BLOCK_EXP); if (start == -1) { MessageBox("Unable to allocate storage, try deleting Sexp variables"); return; } else { Ships[m_ship_num].special_exp_index = start; } } else { start = Ships[m_ship_num].special_exp_index; } // set to update set_modified(); // set em sprintf(Sexp_variables[start+INNER_RAD].text, "%d", m_inner_rad); sprintf(Sexp_variables[start+OUTER_RAD].text, "%d", m_outer_rad); sprintf(Sexp_variables[start+DAMAGE].text, "%d", m_damage); sprintf(Sexp_variables[start+BLAST].text, "%d", m_blast); sprintf(Sexp_variables[start+PROPAGATE].text, "%d", m_shock_enabled); sprintf(Sexp_variables[start+SHOCK_SPEED].text, "%d", m_shock_speed); } else { if (Ships[m_ship_num].special_exp_index != -1) { // set to update set_modified(); // free block sexp_variable_block_free(Ships[m_ship_num].ship_name, Ships[m_ship_num].special_exp_index, SEXP_VARIABLE_BLOCK |SEXP_VARIABLE_BLOCK_EXP); // set index to no exp block Ships[m_ship_num].special_exp_index = -1; } } CDialog::OnOK(); }
[ [ [ 1, 213 ] ] ]
5b9dbb0416c145f4949f1090a168732bcf9087b0
60bc06fb1bcb40b96533bfb9c8dd930c8d05bed5
/Log Reader/AssemblyInfo.cpp
38596ee0aa9e1e2339c55ada8d97bae5a6687ab7
[]
no_license
TheStarport/FLDev
b69b6c42bc10cad1a48c6ac08fc17183e5fedf6d
21ff46442f359a26c3391fd4b27b9f74fd50869c
refs/heads/master
2023-02-22T07:50:09.661915
2010-11-22T04:18:48
2010-11-22T04:18:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,352
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("LogReader")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("Microsoft")]; [assembly:AssemblyProductAttribute("LogReader")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) Microsoft 2010")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ [ [ 1, 40 ] ] ]
89b2f27ea057ca4fe200b5e178226c482569bba1
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/dio/binarydio.h
8c4d47a6cd57eae0ff4a545eff8ff04a960f0985
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
2,326
h
/* * binaryreader.h * * Created on: 17.3.2011 * Author: akin */ #ifndef ICE_BINARYREADER_H_ #define ICE_BINARYREADER_H_ #include <iostream> #include <cstdio> #include "dio" namespace ice { class BinaryDIO : public DIO { private: FILE *file; public: BinaryDIO(); BinaryDIO( std::string path ) throw (DIOException); virtual ~BinaryDIO(); void open( std::string path ) throw (DIOException) ; virtual void readNext(); virtual bool empty(); virtual bool isOk(); virtual void close(); virtual void refresh(); virtual void lock(); virtual void unlock(); virtual unsigned int getDataSize(); virtual int getPosition() throw (DIOException); virtual void setPosition( int position ) throw (DIOException); virtual void forward( int position ) throw (DIOException); virtual void backward( int position ) throw (DIOException); virtual void read( float& arg ) throw (DIOException); virtual void read( char& arg ) throw (DIOException); virtual void read( unsigned char& arg ) throw (DIOException); virtual void read( int& arg ) throw (DIOException); virtual void read( unsigned int& arg ) throw (DIOException); virtual void read( bool& arg ) throw (DIOException); virtual void read( std::string& arg ) throw (DIOException); virtual void readLine( std::string& arg ) throw (DIOException); virtual unsigned int readBlock( unsigned char *buffer , unsigned int byte_count ) throw (DIOException); virtual void writeFloat( const float& arg ) throw (DIOException); virtual void writeByte( const char& arg ) throw (DIOException); virtual void writeByte( const unsigned char& arg ) throw (DIOException); virtual void writeInt( const int& arg ) throw (DIOException); virtual void writeUnsignedInt( const unsigned int& arg ) throw (DIOException); virtual void writeBool( const bool& arg ) throw (DIOException); virtual void writeString( const std::string& arg ) throw (DIOException); virtual void writeLine( const std::string& arg ) throw (DIOException); virtual unsigned int writeBlock( const unsigned char *buffer , unsigned int byte_count ) throw (DIOException); }; } #endif /* BINARYREADER_H_ */
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 7 ], [ 10, 12 ], [ 14, 21 ], [ 23, 24 ], [ 26, 39 ], [ 68, 71 ] ], [ [ 8, 9 ], [ 13, 13 ], [ 22, 22 ], [ 25, 25 ], [ 40, 67 ] ] ]
d6373520cdf6748fc6fb41d73e1360d0b4ac207d
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkUnsigned__Int64Array.h
a361869046dfaaad4f130ae19bb737b308bba58e
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,363
h
/*========================================================================= Program: Visualization Toolkit Module: vtkUnsigned__Int64Array.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkUnsigned__Int64Array - dynamic, self-adjusting array of unsigned __int64 // .SECTION Description // vtkUnsigned__Int64Array is an array of values of type unsigned __int64. // It provides methods for insertion and retrieval of values and will // automatically resize itself to hold new data. #ifndef __vtkUnsigned__Int64Array_h #define __vtkUnsigned__Int64Array_h // Tell the template header how to give our superclass a DLL interface. #if !defined(__vtkUnsigned__Int64Array_cxx) # define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned __int64 #endif #include "vtkDataArray.h" #include "vtkDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. #define vtkDataArray vtkDataArrayTemplate<unsigned __int64> class VTK_COMMON_EXPORT vtkUnsigned__Int64Array : public vtkDataArray #undef vtkDataArray { public: static vtkUnsigned__Int64Array* New(); vtkTypeMacro(vtkUnsigned__Int64Array,vtkDataArray); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Get the data type. int GetDataType() { return VTK_UNSIGNED___INT64; } // Description: // Copy the tuple value into a user-provided array. void GetTupleValue(vtkIdType i, unsigned __int64* tuple) { this->RealSuperclass::GetTupleValue(i, tuple); } // Description: // Set the tuple value at the ith location in the array. void SetTupleValue(vtkIdType i, const unsigned __int64* tuple) { this->RealSuperclass::SetTupleValue(i, tuple); } // Description: // Insert (memory allocation performed) the tuple into the ith location // in the array. void InsertTupleValue(vtkIdType i, const unsigned __int64* tuple) { this->RealSuperclass::InsertTupleValue(i, tuple); } // Description: // Insert (memory allocation performed) the tuple onto the end of the array. vtkIdType InsertNextTupleValue(const unsigned __int64* tuple) { return this->RealSuperclass::InsertNextTupleValue(tuple); } // Description: // Get the data at a particular index. unsigned __int64 GetValue(vtkIdType id) { return this->RealSuperclass::GetValue(id); } // Description: // Set the data at a particular index. Does not do range checking. Make sure // you use the method SetNumberOfValues() before inserting data. void SetValue(vtkIdType id, unsigned __int64 value) { this->RealSuperclass::SetValue(id, value); } // Description: // Specify the number of values for this object to hold. Does an // allocation as well as setting the MaxId ivar. Used in conjunction with // SetValue() method for fast insertion. void SetNumberOfValues(vtkIdType number) { this->RealSuperclass::SetNumberOfValues(number); } // Description: // Insert data at a specified position in the array. void InsertValue(vtkIdType id, unsigned __int64 f) { this->RealSuperclass::InsertValue(id, f); } // Description: // Insert data at the end of the array. Return its location in the array. vtkIdType InsertNextValue(unsigned __int64 f) { return this->RealSuperclass::InsertNextValue(f); } // Description: // Get the address of a particular data index. Make sure data is allocated // for the number of items requested. Set MaxId according to the number of // data values requested. unsigned __int64* WritePointer(vtkIdType id, vtkIdType number) { return this->RealSuperclass::WritePointer(id, number); } // Description: // Get the address of a particular data index. Performs no checks // to verify that the memory has been allocated etc. unsigned __int64* GetPointer(vtkIdType id) { return this->RealSuperclass::GetPointer(id); } // Description: // This method lets the user specify data to be held by the array. The // array argument is a pointer to the data. size is the size of // the array supplied by the user. Set save to 1 to keep the class // from deleting the array when it cleans up or reallocates memory. // The class uses the actual array provided; it does not copy the data // from the suppled array. void SetArray(unsigned __int64* array, vtkIdType size, int save) { this->RealSuperclass::SetArray(array, size, save); } void SetArray(unsigned __int64* array, vtkIdType size, int save, int deleteMethod) { this->RealSuperclass::SetArray(array, size, save, deleteMethod); } protected: vtkUnsigned__Int64Array(vtkIdType numComp=1); ~vtkUnsigned__Int64Array(); private: //BTX typedef vtkDataArrayTemplate<unsigned __int64> RealSuperclass; //ETX vtkUnsigned__Int64Array(const vtkUnsigned__Int64Array&); // Not implemented. void operator=(const vtkUnsigned__Int64Array&); // Not implemented. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 133 ] ] ]
12d41bbfb24e3b05c17ce140989430eeaa538f3b
61576c87f5a1c6a1e94ede4cba8ecf84978836ae
/src/db_access.cpp
0a8a59c569c5114cfcca1c0e8c560968c88d8787
[]
no_license
jdmichaud/newswatch
183553c166860475e055f87c94ab783e1e0d0c11
97aac3d9b16e8160fd407bb3d07c4873291f0500
refs/heads/master
2021-01-21T19:27:53.853232
2008-04-27T19:39:41
2008-04-27T19:39:41
32,138,021
0
0
null
null
null
null
UTF-8
C++
false
false
20,618
cpp
#include <vector> #include <string> #include <boost/thread.hpp> #include <boost/thread/condition.hpp> #include <boost/filesystem.hpp> #include "globals.h" #include "db_access.hpp" #include "callback_handler.hpp" /** * dbaccess implementation */ boost::mutex db_access::m_callback_mutex; //\/:*?"<>| db_access *db_access::get_instance() { #if defined(BOOST_HAS_THREADS) static boost::mutex m_inst_mutex; boost::mutex::scoped_lock scoped_lock(m_inst_mutex); #endif // BOOST_HAS_THREADS static db_access *d = NULL; if (!d) { d = new db_access(); static boost::shared_ptr<db_access> s_ptr_d(d); } return d; } int db_access::generic_callback(void *object, int argc, char **argv, char **azColName) { assert(object); query_result_t *results = (query_result_t *) object; boost::mutex::scoped_lock scoped_lock(db_access::m_callback_mutex); for (int i = 0; i < argc; ++i) { (*results)[azColName[i]].push_back(argv[i]); } return 0; } void db_access::init() { std::ifstream database(configuration::get_instance()->m_article_database.c_str()); LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::init: checking database (" << configuration::get_instance()->m_article_database << ") ..."); if (SQLITE_OK != sqlite3_open(configuration::get_instance()->m_article_database.c_str(), &m_database)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, sqlite3_errmsg(m_database)); return ; } if (!database.is_open()) { LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::init: Database " << configuration::get_instance()->m_article_database << " does not exist, creating it ..."); if (create_database()) { std::string e("Error creating database"); throw e; } } else LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::init: Database " << configuration::get_instance()->m_article_database << " exists"); LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::init: Init newspaper database"); for (unsigned int i = 0; i < configuration::get_instance()->m_medias.size(); ++i) { db_newspaper newspaper; newspaper.m_name = configuration::get_instance()->m_medias[i].m_media_name; if (!newspaper.exist()) { LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::init: " << newspaper.m_name << " does not exist"); newspaper.insert(); callback_handler::get_instance()->new_newspaper(newspaper.m_name); } } } int db_access::create_database() { sqlite3_exec(m_database, "CREATE DATABASE Article_Database;", NULL, NULL, NULL); sqlite3_exec(m_database, "CREATE TABLE newspaper (uid integer PRIMARY KEY, \ name varchar, \ country varchar, \ website varchar, \ language varchar, \ managingEditor varchar, \ image varchar);", NULL, NULL, NULL); sqlite3_exec(m_database, "CREATE TABLE article (uid integer PRIMARY KEY, \ newspaperuid integer, \ title varchar, \ link varchar, \ description varchar, \ author varchar, \ category varchar, \ comments varchar, \ enclosure varchar, \ guid varchar, \ publicationDate date, \ source varchar, \ feedName varchar, \ feedAddress varchar, \ content text);", NULL, NULL, NULL); return 0; } int db_access::execute(const std::string &statement) { assert(m_database); return sqlite3_exec(m_database, statement.c_str(), NULL, NULL, NULL); } int db_access::execute(const std::string &statement, sqlite3_callback callback, void *argument, char **errmsg) { assert(m_database); return sqlite3_exec(m_database, statement.c_str(), callback, argument, errmsg); } const char *db_access::get_last_error() { assert(m_database); return sqlite3_errmsg(m_database); } int db_access::dump_all_articles(const std::string &path) { std::ostringstream query; query << "SELECT name FROM newspaper;"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::dump_all_articles: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1,query.str()); query_result_t newspaper_names; if (SQLITE_OK != execute(query.str(), generic_callback, &newspaper_names, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_access::dump_all_articles: query failed: " << get_last_error()); return -1; } LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::dump_all_articles: " << newspaper_names.size() << " newspapers in the database"); db_access::query_result_t::const_iterator it = newspaper_names.begin(); for (; it != newspaper_names.end(); ++it) { std::cout << it->first << std::endl; for (unsigned int i = 0; i < it->second.size(); ++i) std::cout << "\t" << it->second[i] << std::endl; } for (unsigned int i = 0; i < newspaper_names["Name"].size(); ++i) { std::ostringstream articles_query; articles_query << "SELECT title, content FROM article WHERE newspaperuid='" << newspaper_names["uid"][i] << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::dump_all_articles: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, articles_query.str()); query_result_t articles; if (SQLITE_OK != execute(articles_query.str(), generic_callback, &articles, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_access::dump_all_articles: query failed: " << get_last_error()); return -1; } for (unsigned int j = 0; j < articles["Title"].size(); ++j) { std::ostringstream filename; filename << newspaper_names["Name"][i] << " - " << prepare_string_for_filename(articles["Title"][j], "\\/:*?\"<>|") << ".html"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::dump_all_articles: Writing " << filename.str() << " ..."); std::ofstream output_file(filename.str().c_str()); output_file << articles["Content"][j] << std::endl; output_file.close(); } } return 0; } std::string db_access::prepare_string_for_filename(const std::string &str, const std::string &char_to_delete) { std::string ret = str; std::string::const_iterator it = char_to_delete.begin(); for ( ; it != char_to_delete.end(); ++it) for (std::size_t i = 0; (i < ret.size()) && (i = ret.find(*it, i)) != std::string::npos; i = i + 2) ret.replace(i, 1, "_"); return ret; } int db_access::get_newspapers(std::vector<std::string> &newspapers_name) { std::ostringstream query; query << "SELECT name FROM newspaper;"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::get_newspapers: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); query_result_t newspapers; if (SQLITE_OK != execute(query.str(), generic_callback, &newspapers, NULL)) { std::cerr << get_last_error() << std::endl; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::get_access: query failed: " << get_last_error()); return -1; } newspapers_name = newspapers["Name"]; return 0; } unsigned int db_access::get_number_of_newspapers() { std::ostringstream query; query << "SELECT Count(name) FROM newspaper;"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::get_number_of_newspapers: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); query_result_t newspapers_count; if (SQLITE_OK != execute(query.str(), generic_callback, &newspapers_count, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_access::get_number_of_newspapers: query failed: " << get_last_error()); return -1; } std::string result = newspapers_count.begin()->second[0]; LOGLITE_LOG_(LOGLITE_LEVEL_1, "answer: " << result); return atoi(result.c_str()); } int db_access::get_articles(const std::string &newspaper_name, std::vector<unsigned long int> &uids) { std::ostringstream query; query << "SELECT uid FROM article WHERE NewspaperName='" << newspaper_name << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::get_articles: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); query_result_t article_uids; if (SQLITE_OK != execute(query.str(), generic_callback, &article_uids, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_access::get_number_of_articles: query failed: " << get_last_error()); return -1; } unsigned int i = 0; for (; i < article_uids["uid"].size(); ++i) uids.push_back(atol(article_uids["uid"][i].c_str())); return 0; } unsigned int db_access::get_number_of_articles() { std::ostringstream query; query << "SELECT COUNT(title) FROM article;"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_access::get_number_of_articles: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); query_result_t article_count; if (SQLITE_OK != execute(query.str(), generic_callback, &article_count, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_access::get_number_of_articles: query failed: " << get_last_error()); return -1; } std::string result = article_count.begin()->second[0]; LOGLITE_LOG_(LOGLITE_LEVEL_1, "answer: " << result); return atoi(result.c_str()); } /** * dbobject implementation */ std::string db_object::prepare_string_for_db(const std::string &str) { std::string ret = str; for (std::size_t i = 0; (i < ret.size()) && (i = ret.find("'", i)) != std::string::npos; i = i + 2) ret.replace(i, 1, "''"); return ret; } /** * db_newspaper implementation */ int db_newspaper::insert() { std::ostringstream query; query << "INSERT INTO newspaper (NULL, name, country, website, language, managingEditor, image) VALUES ("; query << "'" << db_object::prepare_string_for_db(m_name) << "', "; query << "'" << db_object::prepare_string_for_db(m_country) << "', "; query << "'" << db_object::prepare_string_for_db(m_website) << "', "; query << "'" << db_object::prepare_string_for_db(m_language) << "', "; query << "'" << db_object::prepare_string_for_db(m_managing_editor) << "', "; query << "'" << db_object::prepare_string_for_db(m_image) << "');"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::insert: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); if (SQLITE_OK != db_access::get_instance()->execute(query.str())) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_newspaper::insert: Insertion failed: " << db_access::get_instance()->get_last_error()); return -1; } else LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::insert: Insertion done"); return 0; } int db_newspaper::exist() { std::ostringstream query; query << "SELECT name FROM newspaper WHERE name='" << db_object::prepare_string_for_db(m_name) << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::exist: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); if (SQLITE_OK != db_access::get_instance()->execute(query.str(), exist_callback, this, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_newspaper::exist: query failed: " << db_access::get_instance()->get_last_error()); return -1; } int ret = 0; if (m_exist) ret = 1; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::insert: newspaper : '" << m_name << (m_exist ? "' exists" : "' do not exists")); m_exist = false; return ret; } int db_newspaper::exist_callback(void *object, int argc, char **argv, char **azColName) { assert(object); db_newspaper *newspaper = (db_newspaper *) object; boost::mutex::scoped_lock scoped_lock(newspaper->m_callback_mutex); if (argc > 0) newspaper->m_exist = true; else newspaper->m_exist = false; return 0; } unsigned int db_newspaper::get_uid(const std::string &newspaper_name) { std::ostringstream query; query << "SELECT uid FROM newspaper WHERE name='" << db_object::prepare_string_for_db(newspaper_name) << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_newspaper::get_uid: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); db_access::query_result_t result; if (SQLITE_OK != db_access::get_instance()->execute(query.str(), db_access::generic_callback, &result, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_newspaper::get_uid: query failed: " << db_access::get_instance()->get_last_error()); return -1; } if (result.find("uid") != result.end()) return atoi(result["uid"].front().c_str()); return 0; } /** * db_article implementation */ int db_article::insert_if_not_exist() { boost::mutex::scoped_lock scoped_lock(m_insert_mutex); if (!exist()) insert(); } int db_article::insert() { int newspaperuid = db_newspaper::get_uid(m_newspaper_name); if (newspaperuid == 0) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "Error: No sush newspaper name in database: " << m_newspaper_name); } std::ostringstream query; query << "INSERT INTO article (uid, newspaperuid, Title, Link, Description, Author, Category, Comments, Enclosure, Guid, PublicationDate, Source, FeedName, FeedAddress, Content) VALUES (NULL, "; query << "'" << newspaperuid << "', "; query << "'" << db_object::prepare_string_for_db(m_title) << "', "; query << "'" << db_object::prepare_string_for_db(m_link) << "', "; query << "'" << db_object::prepare_string_for_db(m_description) << "', "; query << "'" << db_object::prepare_string_for_db(m_author) << "', "; query << "'" << db_object::prepare_string_for_db(m_category) << "', "; query << "'" << db_object::prepare_string_for_db(m_comments) << "', "; query << "'" << db_object::prepare_string_for_db(m_enclosure) << "', "; query << "'" << db_object::prepare_string_for_db(m_guid) << "', "; query << "'" << db_object::prepare_string_for_db(m_publication_date) << "', "; query << "'" << db_object::prepare_string_for_db(m_source) << "', "; query << "'" << db_object::prepare_string_for_db(m_feed_name) << "', "; query << "'" << db_object::prepare_string_for_db(m_feed_address) << "', "; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::insert: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); query << "'" << db_object::prepare_string_for_db(m_content) << "');"; if (SQLITE_OK != db_access::get_instance()->execute(query.str())) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_article::insert: Insertion failed: " << db_access::get_instance()->get_last_error()); return -1; } else { LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::insert: Insertion done"); query.str(""); query << "SELECT uid FROM Article WHERE Title='" << db_object::prepare_string_for_db(m_title) << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::insert: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); db_access::query_result_t result; if (SQLITE_OK != db_access::get_instance()->execute(query.str(), db_access::generic_callback, &result, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_article::insert: Query failed: " << db_access::get_instance()->get_last_error()); return -1; } else m_uid = atoi(result["uid"].front().c_str()); } return 0; } int db_article::exist() { std::ostringstream query; query << "SELECT Title FROM Article WHERE Title='" << db_object::prepare_string_for_db(m_title) << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::exist: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); if (SQLITE_OK != db_access::get_instance()->execute(query.str(), exist_callback, this, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_article::insert: query failed: " << db_access::get_instance()->get_last_error()); return -1; } int ret = 0; if (m_exist) ret = 1; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::insert: article title : " << m_title << (m_exist ? " exists" : " do not exists")); m_exist = false; return ret; } int db_article::exist_callback(void *object, int argc, char **argv, char **azColName) { assert(object); db_article *article = (db_article *) object; boost::mutex::scoped_lock scoped_lock(article->m_callback_mutex); if (argc > 0) article->m_exist = true; else article->m_exist = false; return 0; } int db_article::get() { std::ostringstream query; query << "SELECT * FROM Article WHERE uid='" << m_uid << "';"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::exist: query -->"); LOGLITE_LOG_(LOGLITE_LEVEL_1, query.str()); db_access::query_result_t result; if (SQLITE_OK != db_access::get_instance()->execute(query.str(), db_access::generic_callback, &result, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_article::insert: query failed: " << db_access::get_instance()->get_last_error()); return -1; } m_newspaper_name = result["NewspaperName"].front(); m_title = result["Title"].front(); m_link = result["Link"].front(); m_description = result["Description"].front(); m_author = result["Author"].front(); m_category = result["Category"].front(); m_comments = result["Comments"].front(); m_enclosure = result["Enclosure"].front(); m_guid = result["Guid"].front(); m_publication_date = result["PublicationDate"].front(); m_source = result["Source"].front(); m_feed_name = result["FeedName"].front(); m_feed_address = result["FeedAddress"].front(); m_content = result["Content"].front(); LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_article::get: article extracted Title: " << m_title); return 0; } /** * db_marker implementation */ int db_marker::load() { std::string query; query = "SELECT article_uid FROM m_marker_name;"; db_access::query_result_t result; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_marker::load: loading marker table with query: " << query); if (SQLITE_OK != db_access::get_instance()->execute(query, db_access::generic_callback, &result, NULL)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_article::insert: query failed: " << db_access::get_instance()->get_last_error()); return -1; } LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_marker::load: found " << result["article_uid"].size() << " uids for marker " << m_marker_name); unsigned int i = 0; for ( ; i < result["article_uid"].size(); ++i) m_article_uids.push_back(atoi(result["article_uid"][i].c_str())); return 0; } int db_marker::create() { std::string query; query = "CREATE TABLE " + m_marker_name + " (integer article_uid);"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_marker::create: Creating marker table with query: " << query); if (SQLITE_OK != db_access::get_instance()->execute(query)) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_marker::create: query failed: " << db_access::get_instance()->get_last_error()); return -1; } return 0; } int db_marker::add_giud(unsigned long int uid) { std::ostringstream query; query << "INSERT INTO " << m_marker_name << " (article_uid) VALUES (" << uid << ");"; LOGLITE_LOG_(LOGLITE_LEVEL_1, "db_marker::add_giud: adding uid: " << uid << " to " << m_marker_name << " with query: " << query); if (SQLITE_OK != db_access::get_instance()->execute(query.str())) { LOGLITE_LOG(LOGLITE_LEVEL_1, loglite::error, "db_marker::create: query failed: " << db_access::get_instance()->get_last_error()); return -1; } return 0; } int db_marker::delete_table() { return -1; }
[ "jean.daniel.michaud@750302d9-4032-0410-994c-055de1cff029" ]
[ [ [ 1, 561 ] ] ]
4658aeaa64f7f574fbb0c6b3d3854bf4e9fb17e6
8a816dc2da5158e8d4f2081e6086575346869a16
/RenderCSM/RenderCSMMFC/CSMMeshData.cpp
a0d97486d4da315f0ad5be3c3d4ba2f7f0aabe0c
[]
no_license
yyzreal/3ds-max-exporter-plugin
ca43f9193afd471581075528b27d8a600fd2b7fa
249f24c29dcfd6dd072c707f7642cf56cba06ef0
refs/heads/master
2020-04-10T14:50:13.717379
2011-06-12T15:10:54
2011-06-12T15:10:54
50,292,994
0
1
null
2016-01-24T15:07:28
2016-01-24T15:07:28
null
GB18030
C++
false
false
4,725
cpp
#include "stdafx.h" #include "CSMMeshData.h" CSMMeshData::CSMMeshData() { m_pHeader = NULL; m_pDrawNormal = NULL; } CSMMeshData::~CSMMeshData() { SAFE_DELETE( m_pHeader ); for ( SubMeshList::iterator i = m_vpSubMeshes.begin(); i != m_vpSubMeshes.end(); i ++ ) { SAFE_DELETE( *i ); } SAFE_DELETE( m_pDrawNormal ); } /*! \param fileName CSM文件名 *! \return 读取失败返回FALSE */ BOOL CSMMeshData::LoadCSM( const string &fileName ) { if ( BeginReading( m_inFileCSM, fileName ) ) { //! 读Header if ( NULL == m_pHeader ) { m_pHeader = new CSMHeader(); } m_inFileCSM.read( reinterpret_cast< char* >( m_pHeader ), sizeof( CSMHeader ) ); //! 读取TAG int offset = m_pHeader->nHeaderSize; for ( int i = 0; i < m_pHeader->numTags; i ++ ) { CSMTagData tag; m_inFileCSM.seekg( offset ); m_inFileCSM.read( reinterpret_cast< char* >( tag.name ), MAX_STRING_LENGTH ); offset += MAX_STRING_LENGTH; m_inFileCSM.seekg( offset ); m_inFileCSM.read( reinterpret_cast< char* >( &tag.numAnimFrames ), sizeof( int ) ); offset += sizeof( int ); for ( int j = 0; j < tag.numAnimFrames; j ++ ) { D3DXMATRIX mtx;; m_inFileCSM.seekg( offset ); m_inFileCSM.read( reinterpret_cast< char* >( &mtx ), sizeof( MATRIX ) ); offset += sizeof( MATRIX ); tag.vFrameData.push_back( mtx ); } m_vpTags.push_back( tag ); } //! 读骨骼名称,初始化骨骼列表 vector< string > boneNames; for ( int i = 0; i < m_pHeader->numBones; i ++ ) { CSMBoneData boneData; m_inFileCSM.seekg( m_pHeader->nOffBones + i * sizeof( CSMBoneData ) ); m_inFileCSM.read( reinterpret_cast< char* >( &boneData ), sizeof( CSMBoneData ) ); m_boneList.push_back( boneData ); } //! 读Sub Mesh int lastOffset = m_pHeader->nOffSubMesh; for ( int i = 0; i < m_pHeader->numSubMesh; i ++ ) { CSMSubMesh *pSubMesh = new CSMSubMesh(); //! 读Sub Mesh的Header m_inFileCSM.seekg( lastOffset, ifstream::beg ); m_inFileCSM.read( reinterpret_cast<char*>( &( pSubMesh->subMeshHeader ) ), sizeof( CSMSubMeshHeader ) ); //! 读Sub Mesh的纹理 m_inFileCSM.seekg( lastOffset + pSubMesh->subMeshHeader.nHeaderSize, ifstream::beg ); m_inFileCSM.read( pSubMesh->textureFile, MAX_STRING_LENGTH ); //! 读顶点 m_inFileCSM.seekg( lastOffset + pSubMesh->subMeshHeader.nOffVertices, ifstream::beg ); CSMVertexData *vertices = new CSMVertexData[ pSubMesh->subMeshHeader.numVertices ]; m_inFileCSM.read( reinterpret_cast< char* >( vertices ), sizeof( CSMVertexData ) * pSubMesh->subMeshHeader.numVertices ); for ( int j = 0; j < pSubMesh->subMeshHeader.numVertices; j ++ ) { //vertices[j].position[0] /= 100; //vertices[j].position[1] /= 100; //vertices[j].position[1] /= 100; pSubMesh->vVertexData.push_back( vertices[j] ); } //! 读Skin Data int numSkinData; if ( pSubMesh->subMeshHeader.numAnimFrames > 1 ) { numSkinData = pSubMesh->subMeshHeader.numVertices; m_inFileCSM.seekg( lastOffset + pSubMesh->subMeshHeader.nOffSkin, ifstream::beg ); CSMSkinData *skinData = new CSMSkinData[ numSkinData ]; m_inFileCSM.read( reinterpret_cast< char* >( skinData ), sizeof( CSMSkinData ) * numSkinData ); for ( int j = 0; j < numSkinData; j ++ ) { pSubMesh->vSkinData.push_back( skinData[j] ); } } //! 读三角形面 m_inFileCSM.seekg( lastOffset + pSubMesh->subMeshHeader.nOffFaces, ifstream::beg ); CSMTriangleData *triangles = new CSMTriangleData[ pSubMesh->subMeshHeader.numFaces ]; m_inFileCSM.read( reinterpret_cast< char* >( triangles ), sizeof( CSMTriangleData ) * pSubMesh->subMeshHeader.numFaces ); for ( int j = 0; j < pSubMesh->subMeshHeader.numFaces; j ++ ) { pSubMesh->vTriangleData.push_back( triangles[j] ); } m_vpSubMeshes.push_back( pSubMesh ); //! 更新新的起始位置 lastOffset = lastOffset + pSubMesh->subMeshHeader.nOffEnd; } EndReading( m_inFileCSM ); // 初始化Normal绘制器 UINT normalLen = 2; m_pDrawNormal = new DrawNormal( normalLen ); for ( SubMeshList::iterator i = m_vpSubMeshes.begin(); i != m_vpSubMeshes.end(); i ++ ) { CSMSubMesh *pSubMesh = *i; for ( vector< CSMVertexData >::iterator j = pSubMesh->vVertexData.begin(); j != pSubMesh->vVertexData.end(); j ++ ) { CSMVertexData &vtx = *j; m_pDrawNormal->AddNormal( D3DXVECTOR3( vtx.position[0], vtx.position[1], vtx.position[2] ), D3DXVECTOR3( vtx.normal[0], vtx.normal[1], vtx.normal[2] ) ); } } return TRUE; } return FALSE; }
[ "[email protected]@4008efc8-90d6-34c1-d252-cb7169c873e6" ]
[ [ [ 1, 147 ] ] ]
605cdc30673d04971539c6db381fc48c82483fb9
06a812828178249355ae08dd9ad5dc01ffdf7e23
/prog4/tree.h
1803fdda8af4d5bf323978110ece715ab705b426
[]
no_license
johntalton/cs220
6fbc5f8cb177475e3696e3d17eda2eb6d3a05a75
32ded5643cc6969d173fdaa7f50b2ee1a4abf929
refs/heads/master
2021-06-22T18:18:45.216713
1997-11-12T22:59:00
2017-08-15T23:09:30
100,425,946
0
0
null
null
null
null
UTF-8
C++
false
false
736
h
#ifndef TREE_H #define TREE_H class Tree; //forward declaration class TreeNode { friend class Tree; public: TreeNode *LeftChild; char data; TreeNode *RightChild; }; class Tree { public: Tree() {root = 0; Num_of_Nodes = 0;}; void inorder(); void inorder(TreeNode*); void preorder(); void preorder(TreeNode*); void postorder(); void postorder(TreeNode*); void print_tree(TreeNode*, int); void print_tree(); void AddNode(TreeNode*,char,char); void buildTree(char[], char[]); void maketree(TreeNode*,char[],char[],char); private: TreeNode *root; int Num_of_Nodes; }; #endif
[ [ [ 1, 38 ] ] ]
4091ce6aaaa5848e12738ab8d3cb4f7c04586f73
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/SMPreprocessing/NullPreProcessor.cpp
56228c766bba012ddc3a8e383515ae73929bc20f
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
5,274
cpp
#include "StdAfx.h" #include "NullPreProcessor.h" #include "boost/dynamic_bitset.hpp" #include <algorithm> #include "EncodedDoubleAttribute.h" void NullPreProcessor::elimiateNullValues(){ vector<EncodedAttributeInfo*> atts = m_original_datasource->codedAttributes(); boost::dynamic_bitset<> existanceBitMap = m_original_datasource->ExistanceDatabitMap(); vector<int> nullbitIDs = getInactiveBitIDs(existanceBitMap); if (existanceBitMap.count() == m_original_datasource->noOfRows()) { this->ds = m_original_datasource; return; } WrapDataSource* newDS = new WrapDataSource(); newDS->setDSName(m_original_datasource->DataSourceName()); newDS->DataSourceID(m_original_datasource->DataSourceID()); newDS->setSourceType(m_original_datasource->SourceType()); newDS->noOfRows((m_original_datasource->noOfRows()) - nullbitIDs.size()); newDS->noOfAttributes(m_original_datasource->noOfAttributes()); newDS->ExistanceDatabitMap(m_original_datasource->ExistanceDatabitMap()); vector<EncodedAttributeInfo*> newAtts; newAtts.resize(atts.size()); for (int i = 0 ; i < atts.size() ; i++) { EncodedAttributeInfo *att = atts[i]; int attType = (int)att->attributeType(); vector<BitStreamInfo*> currBitStreams = att->vBitStreams(); switch(attType){ case 0: { EncodedIntAttribute* intAtt = static_cast<EncodedIntAttribute*>(att); EncodedIntAttribute* modifiedAtt = new EncodedIntAttribute(); modifiedAtt->setAttName(intAtt->attributeName()); modifiedAtt->setAttID(intAtt->attributeID()); modifiedAtt->setAttType(intAtt->attributeType()); modifiedAtt->setMaxVal(intAtt->maxAttVal()); modifiedAtt->setMinVal(intAtt->minAttVal()); modifiedAtt->setSignBitMap(intAtt->SignBitMap()); modifiedAtt->setVBitStreams(nullEliminatedBitstreams(currBitStreams,nullbitIDs)); modifiedAtt->setNoOfVBitStreams(intAtt->NoOfVBitStreams(),0); newAtts[i] = modifiedAtt; break; } case 1: { EncodedDoubleAttribute* doubleAtt = static_cast<EncodedDoubleAttribute*> (att); EncodedDoubleAttribute* modifiedAtt = new EncodedDoubleAttribute(); modifiedAtt->setAttName(doubleAtt->attributeName()); modifiedAtt->setAttID(doubleAtt->attributeID()); modifiedAtt->setAttType(doubleAtt->attributeType()); modifiedAtt->setMaxVal(doubleAtt->maxAttVal()); modifiedAtt->setMinVal(doubleAtt->minAttVal()); modifiedAtt->SignBitMap(doubleAtt->SignBitMap()); modifiedAtt->Precision(doubleAtt->Precision()); modifiedAtt->setVBitStreams(nullEliminatedBitstreams(currBitStreams,nullbitIDs)); modifiedAtt->setNoOfVBitStreams(doubleAtt->NoOfVBitStreams(),0); newAtts[i] = modifiedAtt; break; } case 3: { EncodedMultiCatAttribute* mulAtt = static_cast<EncodedMultiCatAttribute*>(att); EncodedMultiCatAttribute* modifiedAtt = new EncodedMultiCatAttribute(); modifiedAtt->setAttID(mulAtt->attributeID()); modifiedAtt->setAttName(mulAtt->attributeName()); modifiedAtt->setAttType(mulAtt->attributeType()); modifiedAtt->setNoOfVBitStreams(mulAtt->NoOfVBitStreams(),0); vector<string> _uniqueValList = mulAtt->uniqueValList(); //int nullPOS = std::find(_uniqueValList.begin(),_uniqueValList.end(),"?") - _uniqueValList.begin(); //_uniqueValList.erase(_uniqueValList.begin() + nullPOS); modifiedAtt->setUniqueValList(_uniqueValList); vector<BitStreamInfo*> newBitStreams = nullEliminatedBitstreams(mulAtt->vBitStreams(),nullbitIDs); //newBitStreams.erase(newBitStreams.begin() + nullPOS); modifiedAtt->setVBitStreams(newBitStreams); newAtts[i] = modifiedAtt; break; } } } newDS->CodedAtts(newAtts); this->ds = newDS; } vector<int> NullPreProcessor::getInactiveBitIDs(boost::dynamic_bitset<> bitSet){ vector<int> activeIDs; for (int i = 0 ; i < bitSet.size() ; i++) { if ((int)bitSet[i] == 0) activeIDs.push_back(i); } return activeIDs; } vector<BitStreamInfo*> NullPreProcessor::nullEliminatedBitstreams(vector<BitStreamInfo*> bitStreams,vector<int> nullBits){ vector<BitStreamInfo*> nullEliminatedBitStreams; nullEliminatedBitStreams.resize(bitStreams.size()); for (int i = 0 ; i < bitStreams.size() ; i++) { int NullbitsCountDown = 0; VBitStream* currentBitStream = static_cast<VBitStream*>(bitStreams[i]); dynamic_bitset<> currentBitSet = currentBitStream->Decompress(); int bitCount = currentBitSet.size() - nullBits.size(); BitStreamInfo* vBitStream = new VBitStream(bitCount); vBitStream->setBitStreamAllocAttID(currentBitStream->BitStreamAllocAttID()); vBitStream->setBitStreamAllocAttName(currentBitStream->BitStreamAllocAttName()); dynamic_bitset<> nullEliminatedBitSet(bitCount); for (int j = 0,k = 0 ; j <= currentBitSet.size() ; j++) { if ((NullbitsCountDown < nullBits.size())&& (j == nullBits[NullbitsCountDown])) { NullbitsCountDown++; continue; } nullEliminatedBitSet[k++] = currentBitSet[j]; } vBitStream->convert(nullEliminatedBitSet); nullEliminatedBitStreams[i] = vBitStream; } return nullEliminatedBitStreams; } NullPreProcessor::~NullPreProcessor(void) { }
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1", "[email protected]@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 4 ], [ 6, 20 ], [ 22, 46 ], [ 56, 56 ], [ 63, 131 ] ], [ [ 5, 5 ], [ 21, 21 ], [ 47, 55 ], [ 57, 62 ] ] ]
287ae2bd7506a2afe362e5e08f95d5505097ed25
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/CryEngine/CryCommon/IGameFramework.h
9fece46bf2b2ca1e363d1fe5c590ad082fe5091a
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
23,274
h
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: This is the interface which the launcher.exe will interact with to start the game framework. For an implementation of this interface refer to CryAction. ------------------------------------------------------------------------- History: - 20:7:2004 10:34 : Created by Marco Koegler - 3:8:2004 11:29 : Taken-over by Márcio Martins *************************************************************************/ #ifndef __IGAMEFRAMEWORK_H__ #define __IGAMEFRAMEWORK_H__ #if _MSC_VER > 1000 # pragma once #endif #include "IGameStartup.h" #include "Cry_Color.h" #include "TimeValue.h" struct pe_explosion; struct IPhysicalEntity; // Summary // Generic factory creation // Description // This macro is used to register new game object extension classes. #define REGISTER_FACTORY(host, name, impl, isAI) \ (host)->RegisterFactory((name), (impl *)0, (isAI), (impl *)0) \ #define DECLARE_GAMEOBJECT_FACTORY(impl) \ public: \ virtual void RegisterFactory(const char *name, impl *(*)(), bool isAI) = 0; \ template <class T> void RegisterFactory(const char *name, impl *, bool isAI, T *) \ { \ struct Factory \ { \ static impl *Create() \ { \ return new T(); \ } \ }; \ RegisterFactory(name, Factory::Create, isAI); \ } // game object extensions need more information than the generic interface can provide struct IGameObjectExtension; struct IGameObjectExtensionCreatorBase { virtual IGameObjectExtension * Create() = 0; virtual void GetGameObjectExtensionRMIData( void ** ppRMI, size_t * nCount ) = 0; }; #define DECLARE_GAMEOBJECTEXTENSION_FACTORY(name) \ struct I##name##Creator : public IGameObjectExtensionCreatorBase \ { \ }; \ template <class T> \ struct C##name##Creator : public I##name##Creator \ { \ I##name * Create() \ { \ return new T(); \ } \ void GetGameObjectExtensionRMIData( void ** ppRMI, size_t * nCount ) \ { \ T::GetGameObjectExtensionRMIData( ppRMI, nCount ); \ } \ }; \ virtual void RegisterFactory(const char *name, I##name##Creator*, bool isAI) = 0; \ template <class T> void RegisterFactory(const char *name, I##name *, bool isAI, T *) \ { \ static C##name##Creator<T> creator; \ RegisterFactory(name, &creator, isAI); \ } struct ISystem; struct IUIDraw; struct ILanQueryListener; struct IActor; struct IActorSystem; struct IItem; struct IGameRules; struct IWeapon; struct IItemSystem; struct ILevelSystem; struct IActionMapManager; struct IGameChannel; struct IViewSystem; struct IVehicle; struct IVehicleSystem; struct IGameRulesSystem; struct IFlowSystem; struct IGameTokenSystem; struct IEffectSystem; struct IGameObject; struct IGameObjectExtension; struct IGameObjectSystem; struct IGameplayRecorder; struct IAnimationStateNodeFactory; struct ISaveGame; struct ILoadGame; struct IGameObject; struct IMaterialEffects; struct INetChannel; struct IPlayerProfileManager; struct IMusicLogic; struct IAnimationGraphState; struct INetNub; struct ISaveGame; struct ILoadGame; struct IDebugHistoryManager; struct IDebrisMgr; struct ISubtitleManager; struct IDialogSystem; struct INeuralNet; typedef _smart_ptr<INeuralNet> INeuralNetPtr; enum EGameStartFlags { eGSF_NoLevelLoading = 0x0001, eGSF_Server = 0x0002, eGSF_Client = 0x0004, eGSF_NoDelayedStart = 0x0008, eGSF_BlockingClientConnect = 0x0010, eGSF_NoGameRules = 0x0020, eGSF_LocalOnly = 0x0040, eGSF_NoQueries = 0x0080, eGSF_NoSpawnPlayer = 0x0100, eGSF_BlockingMapLoad = 0x0200, eGSF_DemoRecorder = 0x0400, eGSF_DemoPlayback = 0x0800, eGSF_ImmersiveMultiplayer = 0x1000, eGSF_RequireController = 0x2000, eGSF_RequireKeyboardMouse = 0x4000, }; enum ESaveGameReason { eSGR_LevelStart, eSGR_FlowGraph, eSGR_Command, eSGR_QuickSave }; static const EntityId LOCAL_PLAYER_ENTITY_ID = 0xeeeeu; // 61166 struct SGameContextParams { const char * levelName; const char * gameRules; const char * demoRecorderFilename; const char * demoPlaybackFilename; SGameContextParams() { levelName = 0; gameRules = 0; demoRecorderFilename = 0; demoPlaybackFilename = 0; } }; struct SGameStartParams { // a combination of EGameStartFlags - needed if bServer==true unsigned flags; // UDP port to connect to uint16 port; // ip address/hostname of server to connect to - needed if bClient==true const char * hostname; // optional connection string for client const char * connectionString; // context parameters - needed if bServer==true const SGameContextParams * pContextParams; // maximum players to allow to connect int maxPlayers; SGameStartParams() { flags = 0; port = 0; hostname = 0; connectionString = 0; pContextParams = NULL; maxPlayers = 32; } }; //provides an interface to game so game will be able to display numeric stats in user-friendly way struct IGameStatsConfig { virtual ~IGameStatsConfig(){} virtual int GetStatsVersion() = 0; virtual int GetCategoryMod(const char* cat) = 0; virtual const char* GetValueNameByCode(const char* cat, int id) = 0; }; struct IPersistantDebug { virtual void Begin( const char * name, bool clear ) = 0; virtual void AddSphere( const Vec3& pos, float radius, ColorF clr, float timeout ) = 0; virtual void AddDirection( const Vec3& pos, float radius, const Vec3& dir, ColorF clr, float timeout ) = 0; virtual void AddLine( const Vec3& pos1, const Vec3& pos2, ColorF clr, float timeout ) = 0; virtual void AddPlanarDisc( const Vec3& pos, float innerRadius, float outerRadius, ColorF clr, float timeout ) = 0; virtual void Add2DText ( const char * text, float size, ColorF clr, float timeout ) = 0; virtual void AddText ( float x, float y, float size, ColorF clr, float timeout, const char * fmt, ... ) = 0; virtual void Add2DLine( float x1, float y1, float x2, float y2, ColorF clr, float timeout ) = 0; virtual void AddQuat( const Vec3& pos, const Quat& q, float r, ColorF clr, float timeout ) = 0; }; // when you add stuff here, also update in CCryAction::Init enum EGameFrameworkEvent { eGFE_PauseGame, eGFE_ResumeGame, eGFE_OnCollision, eGFE_OnPostStep, eGFE_OnStateChange, eGFE_ResetAnimationGraphs, eGFE_OnBreakable2d, eGFE_OnBecomeVisible, eGFE_PreFreeze, eGFE_PreShatter, eGFE_BecomeLocalPlayer, eGFE_DisablePhysics, eGFE_EnablePhysics, }; //all events game should be aware of need to be added here enum EActionEvent { eAE_channelCreated, eAE_channelDestroyed, eAE_connectFailed, eAE_connected, eAE_disconnected, eAE_clientDisconnected, // map resetting eAE_resetBegin, eAE_resetEnd, eAE_resetProgress, eAE_preSaveGame, // m_value -> ESaveGameReason eAE_postSaveGame, // m_value -> ESaveGameReason, m_description: 0 (failed), != 0 (successful) eAE_inGame, eAE_serverName, //started server eAE_serverIp, //obtained server ip eAE_earlyPreUpdate, // called from CryAction's PreUpdate loop after System has been updated, but before subsystems }; struct SActionEvent { SActionEvent(EActionEvent e, int val=0,const char* des = 0): m_event(e), m_value(val), m_description(des) {} EActionEvent m_event; int m_value; const char* m_description; }; // We must take care of order in which listeners are called. // Priority order is from low to high. // As an example, menu must follow hud as it must be drawn on top of the rest. enum EFRAMEWORKLISTENERPRIORITY { // Default priority should not be used unless you don't care about order (it will be called first) FRAMEWORKLISTENERPRIORITY_DEFAULT, // Add your order somewhere here if you need to be called between one of them FRAMEWORKLISTENERPRIORITY_GAME, FRAMEWORKLISTENERPRIORITY_HUD, FRAMEWORKLISTENERPRIORITY_MENU }; struct IGameFrameworkListener { virtual void OnPostUpdate(float fDeltaTime) = 0; virtual void OnSaveGame(ISaveGame* pSaveGame) = 0; virtual void OnLoadGame(ILoadGame* pLoadGame) = 0; virtual void OnLevelEnd(const char* nextLevel) = 0; virtual void OnActionEvent(const SActionEvent& event) = 0; }; // Summary // Interface which exposes the CryAction subsystems struct IGameFramework { DECLARE_GAMEOBJECT_FACTORY(IAnimationStateNodeFactory); DECLARE_GAMEOBJECT_FACTORY(ISaveGame); DECLARE_GAMEOBJECT_FACTORY(ILoadGame); DECLARE_GAMEOBJECTEXTENSION_FACTORY(Actor); DECLARE_GAMEOBJECTEXTENSION_FACTORY(Item); DECLARE_GAMEOBJECTEXTENSION_FACTORY(Vehicle); DECLARE_GAMEOBJECTEXTENSION_FACTORY(GameObjectExtension); // Summary // Entry function to the game framework // Description // Entry function used to create a new instance of the game framework from // outside its own DLL. // Returns // a new instance of the game framework typedef IGameFramework *(*TEntryFunction)(); // Summary: // Initialize CryENGINE with every system needed for a general action game. // Independently of the success of this method, Shutdown must be called. // Arguments: // startupParams - Pointer to SSystemInitParams structure containg system initialization setup! // Return Value: // 0 if something went wrong with initialization, non-zero otherwise. virtual bool Init(SSystemInitParams &startupParams) = 0; // Summary: // Complete initialization of game framework with things that can only be done // after all entities have been registered. virtual bool CompleteInit() = 0; // Description: // Shuts down CryENGINE and any other subsystem created during initialization. virtual void Shutdown() = 0; // Description: // Updates CryENGINE before starting a game frame. // Arguments: // haveFocus - Boolean describing if the game has the input focus or not. // updateFlags - Flags specifying how to update. // Return Value: // 0 if something went wrong with initialization, non-zero otherwise. virtual bool PreUpdate(bool haveFocus, unsigned int updateFlags) = 0; // Description: // Updates CryENGINE after a game frame. // Arguments: // haveFocus - Boolean describing if the game has the input focus or not. // updateFlags - Flags specifying how to update. virtual void PostUpdate(bool haveFocus, unsigned int updateFlags) = 0; // Description: // Resets the current game virtual void Reset(bool clients) = 0; // Description: // Pauses the game // Arguments: // pause - Boolean describing if it's pausing or not. virtual void PauseGame(bool pause, bool force) = 0; // Description: // Returns the pause status // Return Value: // true - if the game is pause, false - otherwise virtual bool IsGamePaused() = 0; // Description: // Are we completely into game mode? virtual bool IsGameStarted() = 0; // Description: // Returns a pointer to the ISystem interface. // Return Value: // Pointer to ISystem interface. virtual ISystem *GetISystem() = 0; // Description: // Retrieve a pointer to the ILanQueryListener interface // Return Value: // Pointer to ILanQueryListener interface. virtual ILanQueryListener *GetILanQueryListener() = 0; // Description: // Returns a pointer to the IUIDraw interface. // Return Value: // Pointer to IUIDraw interface. virtual IUIDraw *GetIUIDraw() = 0; // Description: // Returns a pointer to the IGameObjectSystem interface. // Return Value: // Pointer to IGameObjectSystem interface. virtual IGameObjectSystem *GetIGameObjectSystem() = 0; // Description: // Returns a pointer to the ILevelSystem interface. // Return Value: // Pointer to ILevelSystem interface. virtual ILevelSystem *GetILevelSystem() = 0; // Description: // Returns a pointer to the IActorSystem interface. // Return Value: // Pointer to IActorSystem interface. virtual IActorSystem *GetIActorSystem() = 0; // Description: // Returns a pointer to the IItemSystem interface. // Return Value: // Pointer to IItemSystem interface. virtual IItemSystem *GetIItemSystem() = 0; // Description: // Returns a pointer to the IActionMapManager interface. // Return Value: // Pointer to IActionMapManager interface. virtual IActionMapManager *GetIActionMapManager() = 0; // Description: // Returns a pointer to the IViewSystem interface. // Return Value: // Pointer to IViewSystem interface. virtual IViewSystem *GetIViewSystem() = 0; // Description: // Returns a pointer to the IGameplayRecorder interface. // Return Value: // Pointer to IGameplayRecorder interface. virtual IGameplayRecorder *GetIGameplayRecorder() = 0; // Description: // Returns a pointer to the IVehicleSystem interface. // Return Value: // Pointer to IVehicleSystem interface. virtual IVehicleSystem *GetIVehicleSystem() = 0; // Description: // Returns a pointer to the IGameRulesSystem interface. // Return Value: // Pointer to IGameRulesSystem interface. virtual IGameRulesSystem *GetIGameRulesSystem() = 0; // Description: // Returns a pointer to the IFlowSystem interface. // Return Value: // Pointer to IFlowSystem interface. virtual IFlowSystem *GetIFlowSystem() = 0; // Description: // Returns a pointer to the IGameTokenSystem interface // Return Value: // Pointer to IGameTokenSystem interface. virtual IGameTokenSystem *GetIGameTokenSystem() = 0; // Description: // Returns a pointer to the IEffectSystem interface // Return Value: // Pointer to IEffectSystem interface. virtual IEffectSystem *GetIEffectSystem() = 0; // Description: // Returns a pointer to the IMaterialEffects interface. // Return Value: // Pointer to IMaterialEffects interface. virtual IMaterialEffects *GetIMaterialEffects() = 0; // Description: // Returns a pointer to the IDialogSystem interface // Return Value: // Pointer to IDialogSystem interface. virtual IDialogSystem *GetIDialogSystem() = 0; // Description: // Returns a pointer to the IPlayerProfileManager interface. // Return Value: // Pointer to IPlayerProfileManager interface. virtual IPlayerProfileManager *GetIPlayerProfileManager() = 0; virtual IDebrisMgr *GetDebrisMgr () = 0; // Description: // Returns a pointer to the ISubtitleManager interface. // Return Value: // Pointer to ISubtitleManager interface. virtual ISubtitleManager *GetISubtitleManager() = 0; // Description: // Initialises a game context // Arguments: // pGameStartParams - parameters for configuring the game // Return Value: // true if successful virtual bool StartGameContext( const SGameStartParams * pGameStartParams ) = 0; // Description: // Changes a game context (levels and rules, etc); only allowed on the server // Arguments: // pGameContextParams - parameters for configuring the context // Return Value: // true if successful virtual bool ChangeGameContext( const SGameContextParams * pGameContextParams ) = 0; // Description: // Finished a game context (no game running anymore) virtual void EndGameContext() = 0; // Description: // Detect if a context is currently running // Return Value: // true if a game context is running virtual bool StartedGameContext() const = 0; // Description: // For the editor: spawn a player and wait for connection virtual bool BlockingSpawnPlayer() = 0; // Description: // For the game : fix the broken game objects (to restart the map) virtual void ResetBrokenGameObjects() = 0; // Description: // Inform the GameFramework of the current level loaded in the editor. virtual void SetEditorLevel(const char *levelName, const char *levelFolder) = 0; // Description: // Retrieves the current level loaded by the editor. // Arguments: // Pointers to receive the level infos. virtual void GetEditorLevel(char **levelName, char **levelFolder) = 0; // Description: // Begin a query on the LAN for games virtual void BeginLanQuery() = 0; // Description: // End the current game query virtual void EndCurrentQuery() = 0; // Description: // Returns the Actor associated with the client (or NULL) virtual IActor * GetClientActor() const = 0; // Description: // Returns the Actor Id associated with the client (or NULL) virtual EntityId GetClientActorId() const = 0; // Description: // Returns the INetChannel associated with the client (or NULL) virtual INetChannel * GetClientChannel() const = 0; // Description: // Returns the (synched) time of the server (so use this for timed events, such as MP round times) virtual CTimeValue GetServerTime() = 0; // Description: // Retrieve the Game Server Channel Id associated with the specified INetChannel. // Return Value: // The Game Server ChannelId associated with the specified INetChannel. virtual uint16 GetGameChannelId(INetChannel *pNetChannel) = 0; // Description: // Check if the game server channel has lost connection but still on hold and able to recover... // Return Value: // Returns true if the specified game server channel has lost connection but it's stil able to recover... virtual bool IsChannelOnHold(uint16 channelId) = 0; // Description: // Retrieve a pointer to the INetChannel associated with the specified Game Server Channel Id. // Return Value: // Pointer to INetChannel associated with the specified Game Server Channel Id. virtual INetChannel *GetNetChannel(uint16 channelId) = 0; // Description: // Retrieve an IGameObject from an entity id // Return Value: // Pointer to IGameObject of the entity if it exists (or NULL otherwise) virtual IGameObject * GetGameObject(EntityId id) = 0; // Description: // Retrieve a network safe entity class id, that will be the same in client and server // Return Value: // true if an entity class with this name has been registered virtual bool GetNetworkSafeClassId(uint16 &id, const char *className) = 0; // Description: // Retrieve a network safe entity class name, that will be the same in client and server // Return Value: // true if an entity class with this id has been registered virtual bool GetNetworkSafeClassName(char *className, size_t maxn, uint16 id) = 0; // Description: // Retrieve an IGameObjectExtension by name from an entity // Return Value: // Pointer to IGameObjectExtension of the entity if it exists (or NULL otherwise) virtual IGameObjectExtension * QueryGameObjectExtension( EntityId id, const char * name) = 0; // Description: // Save the current game to disk virtual bool SaveGame( const char * path, bool quick = false, bool bForceImmediate = true, ESaveGameReason reason = eSGR_QuickSave, bool ignoreDelay = false, const char* checkPoint = NULL) = 0; // Description: // Load a game from disk (calls StartGameContext...) virtual bool LoadGame( const char * path, bool quick = false, bool ignoreDelay = false) = 0; // Description: // Notification that game mode is being entered/exited // iMode values: 0-leave game mode, 1-enter game mode, 3-leave AI/Physics mode, 4-enter AI/Physics mode virtual void OnEditorSetGameMode( int iMode ) = 0; virtual bool IsEditing() = 0; virtual bool IsInLevelLoad() = 0; virtual bool IsLoadingSaveGame() = 0; virtual bool IsInTimeDemo() = 0; virtual void AllowSave(bool bAllow = true) = 0; virtual void AllowLoad(bool bAllow = true) = 0; virtual bool CanSave() = 0; virtual bool CanLoad() = 0; // Description: // Check if the current game can activate cheats (flymode, godmode, nextspawn) virtual bool CanCheat() = 0; // Returns: // path relative to the levels folder e.g. "Multiplayer\PS\Shore" virtual const char * GetLevelName() = 0; // Description: // absolute because downloaded content might anywhere // e.g. "c:/MasterCD/Game/Levels/Testy" // Returns // 0 if no level is loaded virtual const char * GetAbsLevelPath() = 0; virtual IPersistantDebug * GetIPersistantDebug() = 0; virtual IGameStatsConfig * GetIGameStatsConfig() = 0; // Music Logic virtual IAnimationGraphState * GetMusicGraphState() = 0; virtual IMusicLogic * GetMusicLogic() = 0; virtual void RegisterListener (IGameFrameworkListener *pGameFrameworkListener, const char * name,EFRAMEWORKLISTENERPRIORITY eFrameworkListenerPriority) = 0; virtual void UnregisterListener (IGameFrameworkListener *pGameFrameworkListener) = 0; virtual INetNub * GetServerNetNub() = 0; virtual void SetGameGUID( const char * gameGUID) = 0; virtual const char* GetGameGUID() = 0; virtual INetContext *GetNetContext() = 0; virtual void GetMemoryStatistics( ICrySizer * ) = 0; virtual void EnableVoiceRecording(const bool enable) = 0; virtual void MutePlayerById(EntityId mutePlayer) = 0; virtual IDebugHistoryManager* CreateDebugHistoryManager() = 0; virtual void DumpMemInfo(const char* format, ...) PRINTF_PARAMS(2, 3) = 0; // Description: // Check whether the client actor is using voice communication. virtual bool IsVoiceRecordingEnabled() = 0; virtual bool IsImmersiveMPEnabled() = 0; // Description: // Executes console command on next frame's beginning virtual void ExecuteCommandNextFrame(const char*) = 0; // Description: // Opens a page in default browser virtual void ShowPageInBrowser(const char* URL) = 0; // Description: // Opens a page in default browser virtual bool StartProcess(const char* cmd_line) = 0; // Description: // Saves dedicated server console variables in server config file virtual bool SaveServerConfig(const char* path) = 0; // Description: // to avoid stalls during gameplay and to get a list of all assets needed for the level (bEnforceAll=true) // Arguments: // bEnforceAll - true to ensure all possible assets become registered (list should not be too conservative - to support level stripification) virtual void PrefetchLevelAssets( const bool bEnforceAll ) = 0; }; ILINE bool IsDemoPlayback() { ISystem* pSystem = GetISystem(); IGame* pGame = pSystem->GetIGame(); IGameFramework* pFramework = pGame->GetIGameFramework(); INetContext* pNetContext = pFramework->GetNetContext(); return pNetContext ? pNetContext->IsDemoPlayback() : false; } #endif //__IGAMEFRAMEWORK_H__
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 115 ], [ 117, 141 ], [ 145, 163 ], [ 166, 170 ], [ 173, 201 ], [ 211, 220 ], [ 222, 250 ], [ 262, 294 ], [ 296, 556 ], [ 569, 576 ], [ 578, 579 ], [ 581, 592 ], [ 600, 615 ], [ 617, 617 ], [ 619, 619 ], [ 621, 634 ], [ 637, 644 ], [ 647, 659 ], [ 661, 668 ], [ 677, 679 ] ], [ [ 116, 116 ], [ 142, 144 ], [ 164, 165 ], [ 171, 172 ], [ 202, 210 ], [ 221, 221 ], [ 251, 261 ], [ 295, 295 ], [ 557, 568 ], [ 577, 577 ], [ 580, 580 ], [ 593, 599 ], [ 616, 616 ], [ 618, 618 ], [ 620, 620 ], [ 635, 636 ], [ 645, 646 ], [ 660, 660 ], [ 669, 676 ] ] ]
a932c4393b3026b88d208585747a9ed11538d48e
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/trunk/engine/script/include/ZoneProcessor.h
3437826fc57e2ccac4152d1d1cdcaf7a6a9e8fd6
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __ZoneProcessor_H__ #define __ZoneProcessor_H__ #include "ScriptPrerequisites.h" #include "AbstractMapNodeProcessor.h" namespace rl { class ZoneProcessor : private AbstractMapNodeProcessor { public: virtual bool processNode(const TiXmlElement* nodeElem, const Ogre::String& resourceGroup, bool loadGameObjects); }; } #endif //__ZoneNodeProcessor_H__
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 32 ] ] ]
4285e3f7d5defdd4e882bb9f50c1a4324236ee12
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/client/wscPcReceiveThread.cpp
310a62f47669a912b3c744b5cabbd9409dcde959
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
#include "wscPcReceiveThread.h" #include "wsiPcWorkingContext.h" #include <wcpp/net/wscDatagramPacket.h> #include <wcpp/net/wsiDatagramSocket.h> #include <wcpp/lang/wscArray.h> #include "wscPimapClientConfig.h" #include "wsiPcEventDispatcher.h" wscPcReceiveThread::wscPcReceiveThread(wsiPcWorkingContext * wc) { m_WorkingContext.Set( wc ); } wscPcReceiveThread::~wscPcReceiveThread(void) { } ws_result wscPcReceiveThread::Run(void) { ws_ptr<wsiPcWorkingContext> wkContext; m_WorkingContext.Get( & wkContext ); if (!wkContext) return WS_RLT_ILLEGAL_STATE; ws_ptr<wsiDatagramSocket> dgSock; ws_result rlt = wkContext->GetDatagramSocket( &dgSock ); if (rlt!=WS_RLT_SUCCESS) return rlt; ws_ptr<wsiByteArray> buf; const ws_int buflen = wscPimapClientConfig::MAX_PACKET_SIZE; rlt = NewObj<wscByteArray>( &buf , buflen ); if (rlt!=WS_RLT_SUCCESS) return rlt; ws_ptr<wsiDatagramPacket> dgPack; rlt = NewObj<wscDatagramPacket>( &dgPack , buf , buflen ); if (rlt!=WS_RLT_SUCCESS) return rlt; while ( ! wkContext->GetStopFlag() ) { rlt = dgSock->Receive( dgPack ); if (rlt==WS_RLT_SUCCESS) { // dgPack ... ; } } return WS_RLT_SUCCESS; }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 49 ] ] ]
2c7a3cf4e00570b54a52d7089b8dd92dd5105e7d
be78c6c17e74febd81d3f89e88347a0d009f4c99
/src/GoIO_cpp/GThread.cpp
076c4df6788696a3199c709d0dffcec50fed5f66
[]
no_license
concord-consortium/goio_sdk
87b3f816199e0bc3bd03cf754e0daf2b6a10f792
e371fd14b8962748e853f76a3a1b472063d12284
refs/heads/master
2021-01-22T09:41:53.246014
2011-07-14T21:33:34
2011-07-14T21:33:34
851,663
1
0
null
null
null
null
UTF-8
C++
false
false
2,598
cpp
// GThread.cpp #include "stdafx.h" #include "GThread.h" #include "GUtils.h" #ifdef _DEBUG #include "GPlatformDebug.h" // for DEBUG_NEW definition #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif GThread::GThread(StdThreadFunctionPtr pFunction, StdThreadFunctionPtr pStopFunction, StdThreadFunctionPtr pStartFunction, StdThreadFunctionPtr pLockFunction, StdThreadFunctionPtr pUnlockFunction, void * pThreadParam, // GMBLSource * void * /*pThreadData*/, bool bOneShot) { m_bThreadAlive = true; m_pThreadRef = NULL; // only used on Mac m_pFunction = pFunction; m_pStopFunction = pStopFunction; m_pStartFunction = pStartFunction; m_pLockFunction = pLockFunction; m_pUnlockFunction = pUnlockFunction; m_pThreadParam = pThreadParam; m_bKillThread = bOneShot; m_bStop = m_bStart = false; } GThread::~GThread() { OSStopThread(); } int GThread::Main(void *pGThreadObject) // pointer to this GThread object { // "main" routine for this thread GThread * pThread = static_cast<GThread *> (pGThreadObject); int nResult = 0; if (pThread != NULL) { StdThreadFunctionPtr pStdFunction = pThread->GetThreadFunction(); StdThreadFunctionPtr pStopFunction = pThread->GetStopFunction(); StdThreadFunctionPtr pStartFunction = pThread->GetStartFunction(); StdThreadFunctionPtr pLockFunction = pThread->GetLockFunction(); StdThreadFunctionPtr pUnlockFunction = pThread->GetUnlockFunction(); void * pParam = pThread->GetThreadParam(); if ((pLockFunction == NULL) || pLockFunction(pParam)) { if (pStdFunction != NULL) { do { // Test for thread death before calling function (brain and such may not exist during shutdown) if (pThread->IsKillThread()) break; if (pThread->IsStop()) { pStopFunction(pParam); pThread->SetStop(false); } if (pThread->IsStart()) { pStartFunction(pParam); pThread->SetStart(false); } // Call worker thread function nResult = (int) pStdFunction(pParam); if (nResult == kResponse_Error) // exit thread on error break; // Let other threads have a crack at the CPU GThread::OSYield(); GUtils::Sleep(30); } while (true); // Loop until thread death flag is set, or worker function returns break value } if ((pUnlockFunction != NULL) && !pUnlockFunction(pParam)) GSTD_ASSERT(0); } else GSTD_ASSERT(0); pThread->SetThreadAlive(false); } return nResult; }
[ [ [ 1, 103 ] ] ]