blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
bca9777a62f70de2650ec050efb167841f44fdbb
a01b67b20207e2d31404262146763d3839ee833d
/trunk/Projet/tags/Monofin_20090606_release/Ui/graphic.h
bcd409f22b18fbd676eaa1a0c096dc1353aeb09a
[]
no_license
BackupTheBerlios/qtfin-svn
49b59747b6753c72a035bf1e2e95601f91f5992c
ee18d9eb4f80a57a9121ba32dade96971196a3a2
refs/heads/master
2016-09-05T09:42:14.189410
2010-09-21T17:34:43
2010-09-21T17:34:43
40,801,620
0
0
null
null
null
null
UTF-8
C++
false
false
3,654
h
#ifndef GRAPHIC_H #define GRAPHIC_H #include <QApplication> #include <QtGui/QWidget> #include <QDialog> #include "ui_graphic.h" #include "../ui_parametersModifier.h" #include "../EdgeDetection/edgesextractionscene.h" #include "../EdgeDetection/edgesextractionview.h" #include "../EdgeDetection/pixmapitem.h" #include "../EdgeDetection/rotatecircle.h" #include "../EdgeDetection/algosnake.h" #include "../EdgeDetection/drawpreview.h" class Graphic : public QWidget { Q_OBJECT public: /** * constructor * a graphic's object is a factory wich contains all of the elements to work on one image and to start the two algorithms * detecteting and extracting the edges of this image * it is also the graphic's users interface and put the slots and signals in relation * @param parent : the parent of the graphic */ Graphic(QWidget *parent = 0, Data::ProjectFile* monofin = 0, qreal width = 0, qreal height = 0); /** * setter * @param width : the width of the scene * @param height : the height of the scene */ void setSize(qreal width, qreal height); /** * setter * @param monofin : the project file */ void setProjectFile(Data::ProjectFile *monofin, qreal width = 0, qreal height = 0); public slots: /** * displays an openWindow when the button "open image" is clicked * the user choose an image (.png or .bmp) and this image is integrated into the interface */ void setPixmap(); /** * rotates the images when the value of the spinBox "value" is changing * @param angle : the value of the spinBox and so the angle of rotation */ void rotate(double angle); /** * changes the scale of the image when the value of spinBox "scale" is changing * @param scale : the value of the spinBox and so the sclae of the image (in %) */ void setScale(double scale); /** * changes the value of the spinBox "positionX" and "positionY" * in function of the position of the image in the scene */ void positionChanged(); /** * changes the value of the spinBox scale * in function of the scale of the image in the scene */ void scaleChanged(); /** * set the position of the "Pixmapitem" to (x,y) in the scene's coordinate * @param x : the coordinate X */ void setPixmapPositionX(int x); /** * set the position of the "Pixmapitem" to (x,y) in the scene's coordinate * @param y : the coordinate Y */ void setPixmapPositionY(int y); /** * slot wich start the two algorithms (edges detection and extraction) */ void startAlgo(); /** * the draw detected by the algorithm is kept * close the graphic */ //void kept(); /** * the draw detected by the algorithm is not kept * the graphic is still open */ void doNotKept(); void changeParameters(); void doNotChangeParameters(); signals: void kept(); protected: Ui::EdgesExtraction _graphic; // the graphic's interface QDialog* _parametersDialog; Ui::Dialog _diag; EdgesExtractionScene* _graphicsScene; // the scene wich contains all of the items (image, "rotateCircle",...) EdgesExtractionView* _graphicsView; // the view wich contains the scene (_graphicsScene) AlgoSnake* _algo; // object wich contains the two algorithms working on the opened image Data::ProjectFile* _monofin; DrawPreview* _preview; }; #endif // GRAPHIC_H
[ "kryptos@314bda93-af5c-0410-b653-d297496769b1" ]
[ [ [ 1, 126 ] ] ]
284d5d489be95811d7d3d3fd10b4d020d8e81170
90aa2eebb1ab60a2ac2be93215a988e3c51321d7
/castor/branches/boost/libs/castor/test/test_finite_automata.cpp
e4f4621f4e433e0cc8fc4a7db315ac67f99e4f90
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
roshannaik/castor
b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6
e86e2bf893719bf3164f9da9590217c107cbd913
refs/heads/master
2021-04-18T19:24:38.612073
2010-08-18T05:10:39
2010-08-18T05:10:39
126,150,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,559
cpp
#include <boost/castor.h> #include <boost/test/minimal.hpp> using namespace castor; struct Nfa { // all tranistions in the NFA => ((ab) * ba) | b static relation transition(lref<int> state1, lref<char> input, lref<int> state2) { return eq(state1, 0) && eq(input, 'a') && eq(state2, 1) || eq(state1, 0) && eq(input, 'b') && eq(state2, 2) || eq(state1, 0) && eq(input, 'b') && eq(state2, 4) || eq(state1, 1) && eq(input, 'b') && eq(state2, 0) || eq(state1, 2) && eq(input, 'a') && eq(state2, 3); } // all final states of the NFA static relation final(lref<int> state) { return eq(state, 3) || eq(state, 4); } }; // rule determining successful exuecution of a FA relation runNfa(lref<std::string> input, lref<int> startState = 0) { lref<char> firstChar; lref<std::string> rest; lref<int> nextState; #ifdef __BCPLUSPLUS__ relation (*self)(lref<std::string>, lref<int>) = &runNfa; return eq(input, "") && Nfa::final(startState) || head(input, firstChar) && Nfa::transition(startState, firstChar, nextState) && tail(input, rest) && recurse(self, rest, nextState); #else return eq(input, "") && Nfa::final(startState) || head(input, firstChar) && Nfa::transition(startState, firstChar, nextState) && tail(input, rest) && recurse(runNfa, rest, nextState); #endif } int test_main(int, char * []) { BOOST_CHECK(runNfa("abba")()); BOOST_CHECK(!runNfa("aabba")()); return 0; }
[ [ [ 1, 46 ] ] ]
703010214d9d339bfec2fbd454c23ae1a24487f9
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osg/Camera
1ee401b1edfdb1175e3185060a17fcb00f52ea18
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
31,518
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #ifndef OSG_CAMERA #define OSG_CAMERA 1 #include <osg/Transform> #include <osg/Viewport> #include <osg/ColorMask> #include <osg/CullSettings> #include <osg/Texture> #include <osg/Image> #include <osg/GraphicsContext> #include <osg/Stats> #include <OpenThreads/Mutex> namespace osg { // forward declare View to allow Camera to point back to the View that its within class View; class RenderInfo; /** Camera - is a subclass of Transform which represents encapsulates the settings of a Camera. */ class OSG_EXPORT Camera : public Transform, public CullSettings { public : Camera(); /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ Camera(const Camera&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); META_Node(osg, Camera); /** Set the View that this Camera is part of. */ void setView(View* view) { _view = view; } /** Get the View that this Camera is part of. */ View* getView() { return _view; } /** Get the const View that this Camera is part of. */ const View* getView() const { return _view; } /** Set the Stats object used for collect various frame related timing and scene graph stats.*/ void setStats(osg::Stats* stats) { _stats = stats; } /** Get the Stats object.*/ osg::Stats* getStats() { return _stats.get(); } /** Get the const Stats object.*/ const osg::Stats* getStats() const { return _stats.get(); } /** Set whether this camera allows events to be generated by the associated graphics window to be associated with this camera.*/ void setAllowEventFocus(bool focus) { _allowEventFocus = focus; } /** Get whether this camera allows events to be generated by the associated graphics window to be associated with this camera.*/ bool getAllowEventFocus() const { return _allowEventFocus; } /** Set the DisplaySettings object associated with this view.*/ void setDisplaySettings(osg::DisplaySettings* ds) { _displaySettings = ds; } /** Get the DisplaySettings object associated with this view.*/ osg::DisplaySettings* getDisplaySettings() { return _displaySettings.get(); } /** Get the const DisplaySettings object associated with this view.*/ const osg::DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); } /** Set the clear mask used in glClear(..). * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */ inline void setClearMask(GLbitfield mask) { _clearMask = mask; applyMaskAction(CLEAR_MASK); } /** Get the clear mask.*/ inline GLbitfield getClearMask() const { return _clearMask; } /** Set the clear color used in glClearColor(..). * glClearColor is only called if mask & GL_COLOR_BUFFER_BIT is true*/ void setClearColor(const osg::Vec4& color) { _clearColor=color; applyMaskAction(CLEAR_COLOR); } /** Get the clear color.*/ const osg::Vec4& getClearColor() const { return _clearColor; } /** Set the clear accum used in glClearAccum(..). * glClearAcumm is only called if mask & GL_ACCUM_BUFFER_BIT is true. */ void setClearAccum(const osg::Vec4& color) { _clearAccum=color; } /** Get the clear accum value.*/ const osg::Vec4& getClearAccum() const { return _clearAccum; } /** Set the clear depth used in glClearDepth(..). Defaults to 1.0 * glClearDepth is only called if mask & GL_DEPTH_BUFFER_BIT is true. */ void setClearDepth(double depth) { _clearDepth=depth; } /** Get the clear depth value.*/ double getClearDepth() const { return _clearDepth; } /** Set the clear stencil value used in glClearStencil(). Defaults to 0; * glClearStencil is only called if mask & GL_STENCIL_BUFFER_BIT is true*/ void setClearStencil(int stencil) { _clearStencil=stencil; } /** Get the clear stencil value.*/ int getClearStencil() const { return _clearStencil; } /** Set the color mask of the camera to use specified osg::ColorMask. */ void setColorMask(osg::ColorMask* colorMask); /** Set the color mask of the camera to specified values. */ void setColorMask(bool red, bool green, bool blue, bool alpha); /** Get the const ColorMask. */ const ColorMask* getColorMask() const { return _colorMask.get(); } /** Get the ColorMask. */ ColorMask* getColorMask() { return _colorMask.get(); } /** Set the viewport of the camera to use specified osg::Viewport. */ void setViewport(osg::Viewport* viewport); /** Set the viewport of the camera to specified dimensions. */ void setViewport(int x,int y,int width,int height); /** Get the const viewport. */ const Viewport* getViewport() const { return _viewport.get(); } /** Get the viewport. */ Viewport* getViewport() { return _viewport.get(); } enum TransformOrder { PRE_MULTIPLY, POST_MULTIPLY }; /** Set the transformation order for world-to-local and local-to-world transformation.*/ void setTransformOrder(TransformOrder order) { _transformOrder = order; } /** Get the transformation order.*/ TransformOrder getTransformOrder() const { return _transformOrder; } enum ProjectionResizePolicy { FIXED, /** Keep the projection matrix fixed, despite window resizes.*/ HORIZONTAL, /** Adjust the HORIZOTNAL field of view on window resizes.*/ VERTICAL /** Adjust the VERTICAL field of view on window resizes.*/ }; /** Set the policy used to determine if and how the projection matrix should be adjusted on window resizes. */ inline void setProjectionResizePolicy(ProjectionResizePolicy policy) { _projectionResizePolicy = policy; } /** Get the policy used to determine if and how the projection matrix should be adjusted on window resizes. */ inline ProjectionResizePolicy getProjectionResizePolicy() const { return _projectionResizePolicy; } /** Set the projection matrix. Can be thought of as setting the lens of a camera. */ inline void setProjectionMatrix(const osg::Matrixf& matrix) { _projectionMatrix.set(matrix); } /** Set the projection matrix. Can be thought of as setting the lens of a camera. */ inline void setProjectionMatrix(const osg::Matrixd& matrix) { _projectionMatrix.set(matrix); } /** Set to an orthographic projection. See OpenGL glOrtho for documentation further details.*/ void setProjectionMatrixAsOrtho(double left, double right, double bottom, double top, double zNear, double zFar); /** Set to a 2D orthographic projection. See OpenGL glOrtho2D documentation for further details.*/ void setProjectionMatrixAsOrtho2D(double left, double right, double bottom, double top); /** Set to a perspective projection. See OpenGL glFrustum documentation for further details.*/ void setProjectionMatrixAsFrustum(double left, double right, double bottom, double top, double zNear, double zFar); /** Create a symmetrical perspective projection, See OpenGL gluPerspective documentation for further details. * Aspect ratio is defined as width/height.*/ void setProjectionMatrixAsPerspective(double fovy,double aspectRatio, double zNear, double zFar); /** Get the projection matrix.*/ osg::Matrixd& getProjectionMatrix() { return _projectionMatrix; } /** Get the const projection matrix.*/ const osg::Matrixd& getProjectionMatrix() const { return _projectionMatrix; } /** Get the orthographic settings of the orthographic projection matrix. * Returns false if matrix is not an orthographic matrix, where parameter values are undefined.*/ bool getProjectionMatrixAsOrtho(double& left, double& right, double& bottom, double& top, double& zNear, double& zFar) const; /** Get the frustum setting of a perspective projection matrix. * Returns false if matrix is not a perspective matrix, where parameter values are undefined.*/ bool getProjectionMatrixAsFrustum(double& left, double& right, double& bottom, double& top, double& zNear, double& zFar) const; /** Get the frustum setting of a symmetric perspective projection matrix. * Returns false if matrix is not a perspective matrix, where parameter values are undefined. * Note, if matrix is not a symmetric perspective matrix then the shear will be lost. * Asymmetric matrices occur when stereo, power walls, caves and reality center display are used. * In these configurations one should use the 'getProjectionMatrixAsFrustum' method instead.*/ bool getProjectionMatrixAsPerspective(double& fovy,double& aspectRatio, double& zNear, double& zFar) const; /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */ inline void setViewMatrix(const osg::Matrixf& matrix) { _viewMatrix.set(matrix); dirtyBound();} /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */ inline void setViewMatrix(const osg::Matrixd& matrix) { _viewMatrix.set(matrix); dirtyBound();} /** Get the view matrix. */ osg::Matrixd& getViewMatrix() { return _viewMatrix; } /** Get the const view matrix. */ const osg::Matrixd& getViewMatrix() const { return _viewMatrix; } /** Set to the position and orientation of view matrix, using the same convention as gluLookAt. */ void setViewMatrixAsLookAt(const osg::Vec3d& eye,const osg::Vec3d& center,const osg::Vec3d& up); /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */ void getViewMatrixAsLookAt(osg::Vec3d& eye,osg::Vec3d& center,osg::Vec3d& up,double lookDistance=1.0) const; /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */ void getViewMatrixAsLookAt(osg::Vec3f& eye,osg::Vec3f& center,osg::Vec3f& up,float lookDistance=1.0f) const; /** Get the inverse view matrix.*/ Matrixd getInverseViewMatrix() const; enum RenderOrder { PRE_RENDER, NESTED_RENDER, POST_RENDER }; /** Set the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within. * For rendering to a texture, one typically uses PRE_RENDER. * For Head Up Displays, one would typically use POST_RENDER.*/ void setRenderOrder(RenderOrder order, int orderNum = 0) { _renderOrder = order; _renderOrderNum = orderNum; } /** Get the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within.*/ RenderOrder getRenderOrder() const { return _renderOrder; } /** Get the rendering order number of this camera relative to any sibling cameras in this subgraph.*/ int getRenderOrderNum() const { return _renderOrderNum; } /** Return true if this Camera is set up as a render to texture camera, i.e. it has textures assigned to it.*/ bool isRenderToTextureCamera() const; enum RenderTargetImplementation { FRAME_BUFFER_OBJECT, PIXEL_BUFFER_RTT, PIXEL_BUFFER, FRAME_BUFFER, SEPERATE_WINDOW }; /** Set the render target.*/ void setRenderTargetImplementation(RenderTargetImplementation impl); /** Set the render target and fall-back that's used if the former isn't available.*/ void setRenderTargetImplementation(RenderTargetImplementation impl, RenderTargetImplementation fallback); /** Get the render target.*/ RenderTargetImplementation getRenderTargetImplementation() const { return _renderTargetImplementation; } /** Get the render target fallback.*/ RenderTargetImplementation getRenderTargetFallback() const { return _renderTargetFallback; } /** Set the draw buffer used at the start of each frame draw. * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/ void setDrawBuffer(GLenum buffer) { _drawBuffer = buffer; applyMaskAction( DRAW_BUFFER ); } /** Get the draw buffer used at the start of each frame draw. */ GLenum getDrawBuffer() const { return _drawBuffer; } /** Set the read buffer for any required copy operations to use. * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/ void setReadBuffer(GLenum buffer) { _readBuffer = buffer; applyMaskAction( READ_BUFFER ); } /** Get the read buffer for any required copy operations to use. */ GLenum getReadBuffer() const { return _readBuffer; } enum BufferComponent { DEPTH_BUFFER, STENCIL_BUFFER, PACKED_DEPTH_STENCIL_BUFFER, COLOR_BUFFER, COLOR_BUFFER0, COLOR_BUFFER1 = COLOR_BUFFER0+1, COLOR_BUFFER2 = COLOR_BUFFER0+2, COLOR_BUFFER3 = COLOR_BUFFER0+3, COLOR_BUFFER4 = COLOR_BUFFER0+4, COLOR_BUFFER5 = COLOR_BUFFER0+5, COLOR_BUFFER6 = COLOR_BUFFER0+6, COLOR_BUFFER7 = COLOR_BUFFER0+7, COLOR_BUFFER8 = COLOR_BUFFER0+8, COLOR_BUFFER9 = COLOR_BUFFER0+9, COLOR_BUFFER10 = COLOR_BUFFER0+10, COLOR_BUFFER11 = COLOR_BUFFER0+11, COLOR_BUFFER12 = COLOR_BUFFER0+12, COLOR_BUFFER13 = COLOR_BUFFER0+13, COLOR_BUFFER14 = COLOR_BUFFER0+14, COLOR_BUFFER15 = COLOR_BUFFER0+15 }; /** Attach a buffer with specified OpenGL internal format.*/ void attach(BufferComponent buffer, GLenum internalFormat); /** Attach a Texture to specified buffer component. * The level parameter controls the mip map level of the texture that is attached. * The face parameter controls the face of texture cube map or z level of 3d texture. * The mipMapGeneration flag controls whether mipmap generation should be done for texture.*/ void attach(BufferComponent buffer, osg::Texture* texture, unsigned int level = 0, unsigned int face=0, bool mipMapGeneration=false, unsigned int multisampleSamples = 0, unsigned int multisampleColorSamples = 0); /** Attach a Image to specified buffer component.*/ void attach(BufferComponent buffer, osg::Image* image, unsigned int multisampleSamples = 0, unsigned int multisampleColorSamples = 0); /** Detach specified buffer component.*/ void detach(BufferComponent buffer); struct Attachment { Attachment(): _internalFormat(GL_NONE), _level(0), _face(0), _mipMapGeneration(false), _multisampleSamples(0), _multisampleColorSamples(0) {} int width() const { if (_texture.valid()) return _texture->getTextureWidth(); if (_image.valid()) return _image->s(); return 0; }; int height() const { if (_texture.valid()) return _texture->getTextureHeight(); if (_image.valid()) return _image->t(); return 0; }; int depth() const { if (_texture.valid()) return _texture->getTextureDepth(); if (_image.valid()) return _image->r(); return 0; }; GLenum _internalFormat; ref_ptr<Image> _image; ref_ptr<Texture> _texture; unsigned int _level; unsigned int _face; bool _mipMapGeneration; unsigned int _multisampleSamples; unsigned int _multisampleColorSamples; }; typedef std::map< BufferComponent, Attachment> BufferAttachmentMap; /** Get the BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/ BufferAttachmentMap& getBufferAttachmentMap() { return _bufferAttachmentMap; } /** Get the const BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/ const BufferAttachmentMap& getBufferAttachmentMap() const { return _bufferAttachmentMap; } /** Explicit control over implicit allocation of buffers when using FBO. Implicit buffers are automatically substituted when user have not attached such buffer. Camera may set up two FBOs: primary Render FBO and secondary Resolve FBO for multisample usage. So in practive we have two masks defined for the Camera: implicitBufferAttachmentRenderMask implicitBufferAttachmentResolveMask They can be set together by setImplicitBufferAttachmentMask method, or separately by setImplicitBufferAttachmentRenderMask and setImplicitBufferAttachmentResolveMask. Camera defaults are USE_DISPLAY_SETTINGS_MASK which means that by default Camera chooses to substitue buffer attachments as defined by DisplaySettings. Usually DisplaySettings implicit buffer attachment selection defaults to: DEPTH and COLOR for both primary (Render) FBO and seconday Multisample (Resolve) FBO ie: IMPLICT_DEPTH_BUFFER_ATTACHMENT | IMPLICIT_COLOR_BUFFER_ATTACHMENT If these masks are not changed and user did not attach depth buffer and/or color buffer to Camera, then OSG implicitly substitues these buffers. By default it does not implicitly allocate a stencil buffer. Use implicti buffer attachment masks to override default behavior: to turn off DEPTH or COLOR buffer substitution or to enforce STENCIL buffer substitution. Note that both values are ignored if not using FBO. Note that the second mask value is ignored if not using MSFBO. */ enum ImplicitBufferAttachment { IMPLICIT_DEPTH_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_DEPTH_BUFFER_ATTACHMENT, IMPLICIT_STENCIL_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_STENCIL_BUFFER_ATTACHMENT, IMPLICIT_COLOR_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_COLOR_BUFFER_ATTACHMENT, USE_DISPLAY_SETTINGS_MASK = (~0) }; typedef int ImplicitBufferAttachmentMask; void setImplicitBufferAttachmentMask(ImplicitBufferAttachmentMask renderMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT, ImplicitBufferAttachmentMask resolveMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT) { _implicitBufferAttachmentRenderMask = renderMask; _implicitBufferAttachmentResolveMask = resolveMask; } void setImplicitBufferAttachmentRenderMask(ImplicitBufferAttachmentMask implicitBufferAttachmentRenderMask) { _implicitBufferAttachmentRenderMask = implicitBufferAttachmentRenderMask; } void setImplicitBufferAttachmentResolveMask(ImplicitBufferAttachmentMask implicitBufferAttachmentResolveMask) { _implicitBufferAttachmentResolveMask = implicitBufferAttachmentResolveMask; } /** Get mask selecting implict buffer attachments for Camera primary FBO if effectiveMask parameter is set, method follows USE_DISPLAY_SETTINGS_MASK dependence and returns effective mask if effectiveMask parameter is reset, method returns nominal mask set by the Camera */ ImplicitBufferAttachmentMask getImplicitBufferAttachmentRenderMask(bool effectiveMask = false) const { if( effectiveMask && _implicitBufferAttachmentRenderMask == USE_DISPLAY_SETTINGS_MASK ) { const DisplaySettings * ds = getDisplaySettings(); if ( !ds ) ds = DisplaySettings::instance(); return ds->getImplicitBufferAttachmentRenderMask(); } else { return _implicitBufferAttachmentRenderMask; } } /** Get mask selecting implict buffer attachments for Camera secondary MULTISAMPLE FBO if effectiveMask parameter is set, method follows USE_DISPLAY_SETTINGS_MASK dependence and returns effective mask if effectiveMask parameter is reset, method returns nominal mask set by the Camera */ ImplicitBufferAttachmentMask getImplicitBufferAttachmentResolveMask(bool effectiveMask = false) const { if( effectiveMask && _implicitBufferAttachmentResolveMask == USE_DISPLAY_SETTINGS_MASK ) { const DisplaySettings * ds = getDisplaySettings(); if ( !ds ) ds = DisplaySettings::instance(); return ds->getImplicitBufferAttachmentRenderMask(); } else { return _implicitBufferAttachmentResolveMask; } } /** Create a operation thread for this camera.*/ void createCameraThread(); /** Assign a operation thread to the camera.*/ void setCameraThread(OperationThread* gt); /** Get the operation thread assigned to this camera.*/ OperationThread* getCameraThread() { return _cameraThread.get(); } /** Get the const operation thread assigned to this camera.*/ const OperationThread* getCameraThread() const { return _cameraThread.get(); } /** Set the GraphicsContext that provides the mechansim for managing the OpenGL graphics context associated with this camera.*/ void setGraphicsContext(GraphicsContext* context); /** Get the GraphicsContext.*/ GraphicsContext* getGraphicsContext() { return _graphicsContext.get(); } /** Get the const GraphicsContext.*/ const GraphicsContext* getGraphicsContext() const { return _graphicsContext.get(); } /** Set the Rendering object that is used to implement rendering of the subgraph.*/ void setRenderer(osg::GraphicsOperation* rc) { _renderer = rc; } /** Get the Rendering object that is used to implement rendering of the subgraph.*/ osg::GraphicsOperation* getRenderer() { return _renderer.get(); } /** Get the const Rendering object that is used to implement rendering of the subgraph.*/ const osg::GraphicsOperation* getRenderer() const { return _renderer.get(); } /** Set the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ void setRenderingCache(osg::Object* rc) { _renderingCache = rc; } /** Get the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ osg::Object* getRenderingCache() { return _renderingCache.get(); } /** Get the const Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ const osg::Object* getRenderingCache() const { return _renderingCache.get(); } /** Draw callback for custom operations.*/ struct OSG_EXPORT DrawCallback : virtual public Object { DrawCallback() {} DrawCallback(const DrawCallback&,const CopyOp&) {} META_Object(osg, DrawCallback); /** Functor method called by rendering thread. Users will typically override this method to carry tasks such as screen capture.*/ virtual void operator () (osg::RenderInfo& renderInfo) const; /** Functor method, provided for backwards compatibility, called by operator() (osg::RenderInfo& renderInfo) method.*/ virtual void operator () (const osg::Camera& /*camera*/) const {} }; /** Set the initial draw callback for custom operations to be done before the drawing of the camera's subgraph and pre render stages.*/ void setInitialDrawCallback(DrawCallback* cb) { _initialDrawCallback = cb; } /** Get the initial draw callback.*/ DrawCallback* getInitialDrawCallback() { return _initialDrawCallback.get(); } /** Get the const initial draw callback.*/ const DrawCallback* getInitialDrawCallback() const { return _initialDrawCallback.get(); } /** Set the pre draw callback for custom operations to be done before the drawing of the camera's subgraph but after any pre render stages have been completed.*/ void setPreDrawCallback(DrawCallback* cb) { _preDrawCallback = cb; } /** Get the pre draw callback.*/ DrawCallback* getPreDrawCallback() { return _preDrawCallback.get(); } /** Get the const pre draw callback.*/ const DrawCallback* getPreDrawCallback() const { return _preDrawCallback.get(); } /** Set the post draw callback for custom operations to be done after the drawing of the camera's subgraph but before the any post render stages have been completed.*/ void setPostDrawCallback(DrawCallback* cb) { _postDrawCallback = cb; } /** Get the post draw callback.*/ DrawCallback* getPostDrawCallback() { return _postDrawCallback.get(); } /** Get the const post draw callback.*/ const DrawCallback* getPostDrawCallback() const { return _postDrawCallback.get(); } /** Set the final draw callback for custom operations to be done after the drawing of the camera's subgraph and all of the post render stages has been completed.*/ void setFinalDrawCallback(DrawCallback* cb) { _finalDrawCallback = cb; } /** Get the final draw callback.*/ DrawCallback* getFinalDrawCallback() { return _finalDrawCallback.get(); } /** Get the const final draw callback.*/ const DrawCallback* getFinalDrawCallback() const { return _finalDrawCallback.get(); } OpenThreads::Mutex* getDataChangeMutex() const { return &_dataChangeMutex; } /** Resize any per context GLObject buffers to specified size. */ virtual void resizeGLObjectBuffers(unsigned int maxSize); /** If State is non-zero, this function releases any associated OpenGL objects for * the specified graphics context. Otherwise, releases OpenGL objexts * for all graphics contexts. */ virtual void releaseGLObjects(osg::State* = 0) const; public: /** Transform method that must be defined to provide generic interface for scene graph traversals.*/ virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor*) const; /** Transform method that must be defined to provide generic interface for scene graph traversals.*/ virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor*) const; /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/ virtual void inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask); protected : virtual ~Camera(); mutable OpenThreads::Mutex _dataChangeMutex; View* _view; osg::ref_ptr<osg::Stats> _stats; bool _allowEventFocus; osg::ref_ptr<osg::DisplaySettings> _displaySettings; GLbitfield _clearMask; osg::Vec4 _clearColor; osg::Vec4 _clearAccum; double _clearDepth; int _clearStencil; ref_ptr<ColorMask> _colorMask; ref_ptr<Viewport> _viewport; TransformOrder _transformOrder; ProjectionResizePolicy _projectionResizePolicy; Matrixd _projectionMatrix; Matrixd _viewMatrix; RenderOrder _renderOrder; int _renderOrderNum; GLenum _drawBuffer; GLenum _readBuffer; RenderTargetImplementation _renderTargetImplementation; RenderTargetImplementation _renderTargetFallback; BufferAttachmentMap _bufferAttachmentMap; ImplicitBufferAttachmentMask _implicitBufferAttachmentRenderMask; ImplicitBufferAttachmentMask _implicitBufferAttachmentResolveMask; ref_ptr<OperationThread> _cameraThread; ref_ptr<GraphicsContext> _graphicsContext; ref_ptr<GraphicsOperation> _renderer; ref_ptr<Object> _renderingCache; ref_ptr<DrawCallback> _initialDrawCallback; ref_ptr<DrawCallback> _preDrawCallback; ref_ptr<DrawCallback> _postDrawCallback; ref_ptr<DrawCallback> _finalDrawCallback; }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 670 ] ] ]
2f49967053df05375fcbc5c56329567e21bc13ea
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/container/container_item_fwd.hpp
fbbadd40940913adde0aaf1cf8a4fd7778f1cea6
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
UTF-8
C++
false
false
273
hpp
#ifndef CONTAINER_ITEM_FWD_HPP #define CONTAINER_ITEM_FWD_HPP #include <memory> class container_item; typedef std::tr1::shared_ptr<container_item> container_item_ptr; typedef std::tr1::weak_ptr<container_item> container_item_wptr; #endif // CONTAINER_ITEM_FWD_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 8 ] ] ]
b581d8f0791315eb52d02e9466c22201c4d24e4f
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testlibcwchar/src/tlibcwhar_io.cpp
1eb1bd3cd73eff63b2505d15052bdfdc20b8bcdb
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
42,173
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : tlibcwhar_io.cpp * Part of : testlibcwchar * * Description : ?Description * Version: 0.5 * */ #include "tlibcwchar.h" TInt CTestLibcwchar::TestfgetwcL() { INFO_PRINTF1(_L("Libcwchar Test Getting (test migrated from STIFF)")); int retval=0; FILE *fp; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0000,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b}; int iTestResult; int counter=0; char *filename = "c:\\FgetwcInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fgetwc Failed !! %d"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fgetwc Failed !!"), errno); iTestResult = KErrGeneral; return iTestResult; } counter = 1; while((int)(retval = fgetwc(fp) )!= WEOF) { if(((int)retval == WEOF) && (counter <= 10)) { iTestResult = KErrGeneral; break; } counter++; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fgetwc Failed !!"), errno); } else { INFO_PRINTF2(_L("fgetwc Passed!!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOnefgetwsL //API Tested : fgetws //TestCase Description : This test case will open a unicode file and will read //fixed number of the characters from the file and displays it on the console. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOnefgetwsL() { FILE *fp; wchar_t buf[20]; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0000,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b}; int iFCreateRetVal; int iTestResult; char *filename = "c:\\FgetwsInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fgetws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fgetws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } if(fgetws(buf,18,fp) == NULL) { iTestResult = KErrGeneral; } buf[0] = L'\0'; if(fgetws(buf,1,fp) != NULL) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fgetws:1 Failed!!"), errno); } else { INFO_PRINTF2(_L("fgetws:1 Passed!!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestTwofgetwsL //API Tested : fgetws //TestCase Description : This test case will open a unicode file and will read //strings where the length is less than, equal to and greater than the number //of characters in the file. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestTwofgetwsL() { FILE *fp; wchar_t buf[30]; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0000,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b}; int iFCreateRetVal; int iTestResult; char *filename = "c:\\FgetwsInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fgetws:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : Error : File open... fgetws:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } if(fgetws(buf,5,fp) == NULL) { iTestResult = KErrGeneral; } rewind(fp); if(fgetws(buf,10,fp) == NULL) { iTestResult = KErrGeneral; } rewind(fp); if(fgetws(buf,15,fp) == NULL) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fgetws:2 Failed!!"), errno); } else { INFO_PRINTF2(_L("fgetws:2 Passed!!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestThreefgetwsL //API Tested : fgetws //TestCase Description : This test case will open a unicode file and will read //fixed number of the characters from the file with a newline character in the //middle. It displays the characters read from the file on the console. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestThreefgetwsL() { FILE *fp; wchar_t buf[20]; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0000,0x0909,0x000a,0x090f,0x090d,0x090e,0x090b}; int iFCreateRetVal; int iTestResult; char *filename = "c:\\FgetwsInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename ,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fgetws:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fgetws:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } if(fgetws(buf,10,fp) == NULL) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fgetws:3 Failed!!"), errno); } else { INFO_PRINTF2(_L("fgetws:3 Passed!!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestgetwcL //API Tested : getwc //TestCase Description : This test case will open a unicode file and will read // the characters from the file till EOF. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestgetwcL() { FILE *fp; wint_t retval; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0000,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b}; int iTestResult; int counter; char *filename = "c:\\GetwcInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... getwc Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... getwsc Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } counter = 1; while((int)(retval = getwc(fp) )!= WEOF) { if(((int)retval == WEOF) && (counter <= 10)) { iTestResult = KErrGeneral; break; } counter++; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("getwc Failed!!"), errno); } else { INFO_PRINTF2(_L("getwc Passed!!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOnefwideL //API Tested : fwide //TestCase Description : This test case will first read the orientation of the //and then set the orientation of the stream to wide char and once again read //back the orientation that was set. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOnefwideL() { FILE *fp; int retval; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult; char *filename = "c:\\FwideTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fwide Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fwide:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } INFO_PRINTF1(_L("fwide:1 Passed !!")); fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestTwofwideL //API Tested : fwide //TestCase Description : This test case will first read the orientation of the //and then set the orientation of the stream to byte and once again read //back the orientation that was set. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestTwofwideL() { FILE *fp; int retval; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult; char *filename = "c:\\FwideTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fwide:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fwide:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,-1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } INFO_PRINTF1(_L("fwide:2 Passed !!")); fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestThreefwideL //API Tested : fwide //TestCase Description : This test case will first read the orientation of the //and then set the orientation of the stream to byte and then tries to change //the orientation to wide. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestThreefwideL() { FILE *fp; int retval; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult; char *filename = "c:\\FwideTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fwide:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fwide:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,-1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } INFO_PRINTF1(_L("fwide:3 Passed !!")); fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestFourfwideL //API Tested : fwide //TestCase Description : This test case will first read the orientation of the //and then set the orientation of the stream to wide and then tries to change //the orientation to byte. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestFourfwideL() { FILE *fp; int retval; int iFCreateRetVal; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult; char *filename = "c:\\FwideTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fwide:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fwide:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } retval = fwide(fp,0); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } retval = fwide(fp,-1); if(retval == 0) { INFO_PRINTF1(_L("No Orientation is set\n")); } if(retval < 0) { INFO_PRINTF1(_L("Stream is set to Byte Orientation\n")); } if(retval > 0) { INFO_PRINTF1(_L("Stream is set to Wide Orientation\n")); } INFO_PRINTF1(_L("fwide:4 Passed !!")); fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOnefputwcL //API Tested : fputwc //TestCase Description : This test case writes a wchar to the stream and //closes the file. The file is again opened and the character that was written //by fputwc is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOnefputwcL() { FILE *fp; wint_t rretval,wretval; int iTestResult; char *filename = "c:\\FputwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputwc(wchar_t(0x0905),fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputwc:1 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rretval = fgetwc(fp); if(wretval != rretval) { iTestResult = KErrGeneral; } else { iTestResult = KErrNone; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputwc:1 Failed!!"), errno); } else { INFO_PRINTF2(_L("fputwc:1 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestTwofputwcL //API Tested : fputwc //TestCase Description : This test case writes a set of wide characters to //the stream and closes the file. The file is again opened and the characters //that were written is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestTwofputwcL() { FILE *fp; wint_t rretval,wretval; wchar_t wchar_letters[20] = {0x0905,0x0906,0x0907,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b,0x090c}; int iTestResult; int i; char *filename = "c:\\FputwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } for(i=0;i<10;i++) { wretval = fputwc(wchar_letters[i],fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputwc:2 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } for(i=0;i<10;i++) { rretval = fgetwc(fp); if(wchar_letters[i] != rretval) { iTestResult = KErrGeneral; break; } } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputwc:2 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputwc:2 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestThreefputwcL //API Tested : fputwc //TestCase Description : This test case writes a new line character then //closes the file. The file is again opened and the character that was written // is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestThreefputwcL() { FILE *fp; wint_t rretval,wretval; int iTestResult; char *filename = "c:\\FputwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputwc(L'\n',fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputwc:3 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rretval = fgetwc(fp); if(wretval != rretval) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputwc:3 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputwc:3 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestFourfputwcL //API Tested : fputwc //TestCase Description : This test case tries to write of a file that is //as readonly. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestFourfputwcL() { FILE *fp; wint_t wretval; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult,iFCreateRetVal; char *filename = "c:\\FputwcTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fputwc:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputwc:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputwc(L'\n',fp); if((signed int)wretval != WEOF) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputwc:4 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputwc:4 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOneputwcL //API Tested : putwc //TestCase Description : This test case writes a wchar to the stream and //closes the file. The file is again opened and the character that was written //by fputwc is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOneputwcL( ) { FILE *fp; wint_t rretval,wretval; int iTestResult; char *filename = "c:\\PutwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = putwc(wchar_t(0x0905),fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("putwc:1 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rretval = fgetwc(fp); if(wretval != rretval) { iTestResult = KErrGeneral; } else { iTestResult = KErrNone; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("putwc:1 Failed!!"), errno); } else { INFO_PRINTF2(_L("putwc:1 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestTwoputwcL //API Tested : putwc //TestCase Description : This test case writes a set of wide characters to //the stream and closes the file. The file is again opened and the characters //that were written is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestTwoputwcL( ) { FILE *fp; wint_t rretval,wretval; wchar_t wchar_letters[20] = {0x0905,0x0906,0x0907,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b,0x090c}; int iTestResult; int i; char *filename = "c:\\PutwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } for(i=0;i<10;i++) { wretval = putwc(wchar_letters[i],fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("putwc:2 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } for(i=0;i<10;i++) { rretval = fgetwc(fp); if(wchar_letters[i] != rretval) { iTestResult = KErrGeneral; break; } } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("putwc:2 Failed !!"), errno); } else { INFO_PRINTF2(_L("putwc:2 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestThreeputwcL //API Tested : putwc //TestCase Description : This test case writes a new line character then //closes the file. The file is again opened and the character that was written // is read back and compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestThreeputwcL( ) { FILE *fp; wint_t rretval,wretval; int iTestResult; char *filename = "c:\\PutwcTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = putwc(L'\n',fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("putwc:3 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rretval = fgetwc(fp); if(wretval != rretval) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("putwc:3 Failed !!"), errno); } else { INFO_PRINTF2(_L("putwc:3 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestFourputwcL //API Tested : putwc //TestCase Description : This test case tries to write of a file that is //as readonly. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestFourputwcL( ) { FILE *fp; wint_t wretval; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907}; int iTestResult,iFCreateRetVal; char *filename = "c:\\PutwcTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... putwc:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... putwc:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = putwc(L'\n',fp); if((signed int)wretval != WEOF) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("putwc:4 Failed !!"), errno); } else { INFO_PRINTF2(_L("putwc:4 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOnefputwsL //API Tested : fputws //TestCase Description : This test case reads a string from a file and writes //it into another file and then closes the file. The file is again is opened //the string that was written is read back. The string that was written and //read back from the file are compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOnefputwsL( ) { FILE *fp; wint_t wretval; wchar_t rws1[10],rws2[10]; wchar_t *rptr; unsigned int wchar_letters[20] = {0x0905,0x0906,0x0907,0x0909,0x090a,0x090f,0x090d,0x090e,0x090b,0x090c}; int iTestResult,iFCreateRetVal,retval; char *filename = "c:\\FputwsTestInputFile.txt"; char *fname = "c:\\FputwsTestFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,10); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rptr = fgetws(rws1,10,fp); if(rptr == NULL) { INFO_PRINTF2(_L("Error : Reading from the input file... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(fname,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputws(rws1,fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(fname,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rptr = fgetws(rws2,10,fp); if(rptr == NULL) { INFO_PRINTF2(_L("Error : Reading back from the file ... fputws:1 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } retval = wcscmp(rws1,rws2); if(retval != 0) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputws:1 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputws:1 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestTwofputwsL //API Tested : fputws //TestCase Description : This test case writes a wide string which has a //newline character in the middle of the string and the file is closed. Then //the file is again opened and the string that was written is read back and //the strings are compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestTwofputwsL( ) { FILE *fp; wint_t wretval; wchar_t rws1[10] = L"abcd\r\nefg"; wchar_t *rptr,rws2[10]; int retval,iTestResult; char *filename = "c:\\FputwsTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputws(rws1,fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputws:2 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:2 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rptr = fgetws(rws2,10,fp); if(rptr == NULL) { INFO_PRINTF2(_L("Error : Reading back from the file... fputws:2 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } retval = wcscmp(L"abcd\r\n",rws2); if(retval != 0) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputws:2 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputws:2 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestThreefputwsL //API Tested : fputws //TestCase Description : This test case tries to write of a file that is //as readonly. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestThreefputwsL( ) { FILE *fp; wint_t wretval; unsigned int wchar_letters[5] = {0x0905,0x0906,0x0907}; int iTestResult,iFCreateRetVal; char *filename = "c:\\FputwsTestInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... fputws:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:3 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputws(L"a",fp); if((signed int)wretval != WEOF) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("fputws:3 Failed !!"), errno); } else { INFO_PRINTF2(_L("fputws:3 Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestFourfputwsL //API Tested : fputws //TestCase Description : This test case writes a wide string which has a //string terminator character in the middle of the string and the file is //closed. Then the file is again opened and the string that was written is //read back and the strings are compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestFourfputwsL( ) { FILE *fp; wint_t wretval; wchar_t rws1[10] = L"abcd\0efg"; wchar_t *rptr,rws2[10]; int iTestResult,retval; char *filename = "c:\\FputwsTestInputFile.txt"; iTestResult = KErrNone; fp = fopen(filename,"w"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } wretval = fputws(rws1,fp); if((signed int)wretval == WEOF) { INFO_PRINTF2(_L("fputws:4 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } fclose(fp); fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... fputws:4 Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } rptr = fgetws(rws2,10,fp); if(rptr == NULL) { INFO_PRINTF2(_L("Error : Reading back from the file... fputws:4 Failed!!"), errno); iTestResult = KErrGeneral; fclose(fp); return iTestResult; } retval = wcscmp(L"abcd",rws2); if(retval != 0) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) INFO_PRINTF2(_L("fputws:4 Failed !!"), errno); else INFO_PRINTF2(_L("fputws:4 Passed !!"), errno); fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOneungetwcL //API Tested : ungetwc //TestCase Description : The testcase function will test ungetwc randomly by //calling getwc and ungetwc is some random order. The values returned by both //ungetwc and getwc are compared. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOneungetwcL( ) { FILE *fp; wint_t c; int iTestResult; int iFCreateRetVal; unsigned int wchar_letters[5] = {0x0062,0x006c,0x0061}; char *filename = "c:\\UngetwcInputFile.txt"; iTestResult = KErrNone; iFCreateRetVal = CreateTestDataFile(filename,wchar_letters,3); if(iFCreateRetVal != 0) { INFO_PRINTF2(_L("Error : Input File creation... ungetwc Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } fp = fopen(filename,"r"); if(fp == NULL) { INFO_PRINTF2(_L("Error : File open... ungetwc Failed!!"), errno); iTestResult = KErrGeneral; return iTestResult; } if(ungetwc (L'z', fp) != L'z') { iTestResult = KErrGeneral; } if(getwc (fp) != L'z') { iTestResult = KErrGeneral; } if(getwc (fp) != L'b') { iTestResult = KErrGeneral; } if(getwc (fp) != L'l') { iTestResult = KErrGeneral; } if(ungetwc (L'm', fp) != L'm') { iTestResult = KErrGeneral; } if(getwc (fp) != L'm') { iTestResult = KErrGeneral; } if((c = getwc (fp)) != L'a') { iTestResult = KErrGeneral; } if((signed int)getwc (fp) != WEOF) { iTestResult = KErrGeneral; } if(ungetwc (c, fp) != c) { iTestResult = KErrGeneral; } if(getwc (fp) != c) { iTestResult = KErrGeneral; } if((signed int)getwc (fp) != WEOF) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("ungetwc Failed !!"), errno); } else { INFO_PRINTF2(_L("ungetwc Passed !!"), errno); } fclose(fp); return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOneputwcharL //API Tested : putwchar //TestCase Description : This test case writes a wide character and checks for //the return value of putwchar. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOneputwcharL( ) { wint_t wc2; wchar_t wc1; int iTestResult; iTestResult = KErrNone; wprintf(L"A wide character is printed : "); wc1 = 0x0906; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } INFO_PRINTF2(_L("%x : This testcase printed a some wide character !"), wc1); wprintf(L"\n\nPress any key to continue....\n"); getwchar(); wprintf(L"Null termination character is printed : "); wc1 = L'\0'; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } INFO_PRINTF2(_L("%x : This testcase printed a null character !"),wc2); wprintf(L"\n\nPress any key to continue....\n"); getwchar(); wprintf(L"A new line character is printed : "); wc1 = L'\n'; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } INFO_PRINTF2(_L("%x : This testcase printed a new line character !"),wc1); wprintf(L"\n\nPress any key to continue....\n"); getwchar(); wprintf(L"Few random characters are printed: "); wc1 = L'a'; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } wc1 = L' '; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } wc1 = L'x'; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } wc1 = L'\n'; wc2 = putwchar(wc1); if(wc1 != (wchar_t)wc2) { iTestResult = KErrGeneral; } if(iTestResult == KErrGeneral) { wprintf(L"\n\nputwchar Failed !!"); } else { wprintf(L"\n\nputwchar Passed !!"); } wprintf(L"\n\nPress any key to exit the testcase....\n"); getwchar(); if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("putwchar Failed !!"), errno); } else { INFO_PRINTF2(_L("putwchar Passed !!"), errno); } return iTestResult; } //---------------------------------------------------------------------------- //Function Name : CTestLibcwchar::TestOnegetwcharL //API Tested : getwchar //TestCase Description : getwchar can be tested using this testcase function //by entering different characters. The character that was entered will be //displayed on the console and the return value of getwchar is also checked. //---------------------------------------------------------------------------- TInt CTestLibcwchar::TestOnegetwcharL( ) { wint_t wc; int iTestResult; iTestResult = KErrNone; wprintf(L"Enter any character : "); wc = getwchar(); if((signed int)wc == WEOF) { iTestResult = KErrGeneral; } wprintf(L"\nCharacter that was entered : %lc\n",wc); if(iTestResult == KErrGeneral) { wprintf(L"\n\ngetwchar Failed !!"); } else { wprintf(L"\n\ngetwchar Passed !!"); } wprintf(L"\n\nPress any key to exit the testcase....\n"); getwchar(); if(iTestResult == KErrGeneral) { INFO_PRINTF2(_L("getwchar Failed !!"), errno); } else { INFO_PRINTF2(_L("getwchar Passed !!"), errno); } return iTestResult; } TInt CTestLibcwchar::CreateTestDataFile(char *filename,unsigned int *arr, int count) { FILE *iFp; int i; int iRval; unsigned int *iStartaddr; iFp = NULL; iFp = fopen(filename,"w"); if(iFp == NULL) { return -1; } iStartaddr = arr; for(i=0;i<count;i++) { iRval = fputwc((wchar_t) (*iStartaddr),iFp); if((signed int)iRval == WEOF) { fclose(iFp); return -2; } iStartaddr++; } fclose(iFp); return 0; }
[ "none@none" ]
[ [ [ 1, 1810 ] ] ]
048c472e9f35e8e289ba4075e05843c427421bbd
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_audio_basics/midi/juce_MidiMessageSequence.cpp
937dfdfec11d377fdc68403c284c2cbd59bfd6aa
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
10,599
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== MidiMessageSequence::MidiMessageSequence() { } MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other) { list.ensureStorageAllocated (other.list.size()); for (int i = 0; i < other.list.size(); ++i) list.add (new MidiEventHolder (other.list.getUnchecked(i)->message)); } MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other) { MidiMessageSequence otherCopy (other); swapWith (otherCopy); return *this; } void MidiMessageSequence::swapWith (MidiMessageSequence& other) noexcept { list.swapWithArray (other.list); } MidiMessageSequence::~MidiMessageSequence() { } void MidiMessageSequence::clear() { list.clear(); } int MidiMessageSequence::getNumEvents() const { return list.size(); } MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const { return list [index]; } double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const { const MidiEventHolder* const meh = list [index]; if (meh != nullptr && meh->noteOffObject != nullptr) return meh->noteOffObject->message.getTimeStamp(); else return 0.0; } int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const { const MidiEventHolder* const meh = list [index]; return meh != nullptr ? list.indexOf (meh->noteOffObject) : -1; } int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const { return list.indexOf (event); } int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const { const int numEvents = list.size(); int i; for (i = 0; i < numEvents; ++i) if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp) break; return i; } //============================================================================== double MidiMessageSequence::getStartTime() const { return getEventTime (0); } double MidiMessageSequence::getEndTime() const { return getEventTime (list.size() - 1); } double MidiMessageSequence::getEventTime (const int index) const { const MidiEventHolder* const e = list [index]; return e != nullptr ? e->message.getTimeStamp() : 0.0; } //============================================================================== void MidiMessageSequence::addEvent (const MidiMessage& newMessage, double timeAdjustment) { MidiEventHolder* const newOne = new MidiEventHolder (newMessage); timeAdjustment += newMessage.getTimeStamp(); newOne->message.setTimeStamp (timeAdjustment); int i; for (i = list.size(); --i >= 0;) if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment) break; list.insert (i + 1, newOne); } void MidiMessageSequence::deleteEvent (const int index, const bool deleteMatchingNoteUp) { if (isPositiveAndBelow (index, list.size())) { if (deleteMatchingNoteUp) deleteEvent (getIndexOfMatchingKeyUp (index), false); list.remove (index); } } struct MidiMessageSequenceSorter { static int compareElements (const MidiMessageSequence::MidiEventHolder* const first, const MidiMessageSequence::MidiEventHolder* const second) noexcept { const double diff = first->message.getTimeStamp() - second->message.getTimeStamp(); return (diff > 0) - (diff < 0); } }; void MidiMessageSequence::addSequence (const MidiMessageSequence& other, double timeAdjustment, double firstAllowableTime, double endOfAllowableDestTimes) { firstAllowableTime -= timeAdjustment; endOfAllowableDestTimes -= timeAdjustment; for (int i = 0; i < other.list.size(); ++i) { const MidiMessage& m = other.list.getUnchecked(i)->message; const double t = m.getTimeStamp(); if (t >= firstAllowableTime && t < endOfAllowableDestTimes) { MidiEventHolder* const newOne = new MidiEventHolder (m); newOne->message.setTimeStamp (timeAdjustment + t); list.add (newOne); } } MidiMessageSequenceSorter sorter; list.sort (sorter, true); } //============================================================================== void MidiMessageSequence::updateMatchedPairs() { for (int i = 0; i < list.size(); ++i) { const MidiMessage& m1 = list.getUnchecked(i)->message; if (m1.isNoteOn()) { list.getUnchecked(i)->noteOffObject = nullptr; const int note = m1.getNoteNumber(); const int chan = m1.getChannel(); const int len = list.size(); for (int j = i + 1; j < len; ++j) { const MidiMessage& m = list.getUnchecked(j)->message; if (m.getNoteNumber() == note && m.getChannel() == chan) { if (m.isNoteOff()) { list.getUnchecked(i)->noteOffObject = list[j]; break; } else if (m.isNoteOn()) { list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note))); list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp()); list.getUnchecked(i)->noteOffObject = list[j]; break; } } } } } } void MidiMessageSequence::addTimeToMessages (const double delta) { for (int i = list.size(); --i >= 0;) list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp() + delta); } //============================================================================== void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract, MidiMessageSequence& destSequence, const bool alsoIncludeMetaEvents) const { for (int i = 0; i < list.size(); ++i) { const MidiMessage& mm = list.getUnchecked(i)->message; if (mm.isForChannel (channelNumberToExtract) || (alsoIncludeMetaEvents && mm.isMetaEvent())) { destSequence.addEvent (mm); } } } void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const { for (int i = 0; i < list.size(); ++i) { const MidiMessage& mm = list.getUnchecked(i)->message; if (mm.isSysEx()) destSequence.addEvent (mm); } } void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove) { for (int i = list.size(); --i >= 0;) if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove)) list.remove(i); } void MidiMessageSequence::deleteSysExMessages() { for (int i = list.size(); --i >= 0;) if (list.getUnchecked(i)->message.isSysEx()) list.remove(i); } //============================================================================== void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber, const double time, OwnedArray<MidiMessage>& dest) { bool doneProg = false; bool donePitchWheel = false; Array <int> doneControllers; doneControllers.ensureStorageAllocated (32); for (int i = list.size(); --i >= 0;) { const MidiMessage& mm = list.getUnchecked(i)->message; if (mm.isForChannel (channelNumber) && mm.getTimeStamp() <= time) { if (mm.isProgramChange()) { if (! doneProg) { dest.add (new MidiMessage (mm, 0.0)); doneProg = true; } } else if (mm.isController()) { if (! doneControllers.contains (mm.getControllerNumber())) { dest.add (new MidiMessage (mm, 0.0)); doneControllers.add (mm.getControllerNumber()); } } else if (mm.isPitchWheel()) { if (! donePitchWheel) { dest.add (new MidiMessage (mm, 0.0)); donePitchWheel = true; } } } } } //============================================================================== MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_) : message (message_), noteOffObject (nullptr) { } MidiMessageSequence::MidiEventHolder::~MidiEventHolder() { } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 332 ] ] ]
f17ceddd5bbe700825c0d9f008b480cb73ed8c4a
7ccf42cf95c94b3d18766451d5641c55cb37bc30
/src/main.cpp
2aa0a6f03eb5869e49130fb9bfc66e7b2b6f85b9
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yoshin4444/bjne
4b8846e69bb4b6735091296489183996fa80a844
d00e1e401a31e3f716453b267e531199071f63d6
refs/heads/master
2021-01-22T19:54:34.318633
2010-03-14T23:20:53
2010-03-14T23:20:53
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,790
cpp
#include <SDL.h> #include <iostream> #include <ctime> #include <string> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include "nes.h" #include "sdl_renderer.h" #include "timer.h" using namespace std; namespace fs=boost::filesystem; string get_base_name(fs::path &p) { string s=p.leaf(); string::size_type pos=s.rfind("."); if (pos==string::npos) return s; else return s.substr(0,pos); } int main(int argc,char *argv[]) { freopen("CON","w",stdout); if (argc<2){ cout<<"usage: "<<argv[0]<<" <romimage>"<<endl; return 0; } // ファイル周り fs::path rom_file(argv[1],fs::native); fs::path save_dir("save"); fs::create_directory(save_dir); string save_base=get_base_name(rom_file); // 初期化 cout<<"Initializing SDL renderer ..."<<endl; if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER)<0){ cout<<"failed to initialize SDL"<<endl; return -1; } SDL_Surface *sur=SDL_SetVideoMode(256,240,0,0); if (sur==NULL){ cout<<"failed to set video mode"<<endl; SDL_Quit(); return -1; } SDL_WM_SetCaption("NES Emulator","NES Emulator"); renderer *nr=new sdl_renderer(sur); cout<<"Creating NES virtual machine ..."<<endl; nes *_nes=new nes(nr); cout<<"Loading ROM image ..."<<endl; cout<<endl; if (!_nes->load(rom_file.native_file_string().c_str())){ cout<<"invalid rom-image"<<endl; goto _quit; } if (!_nes->check_mapper()){ cout<<"unsupported mapper."<<endl; goto _quit; } { fs::path sram_path=(save_dir/(save_base+".sram")); if (fs::exists(sram_path)){ cout<<"Loading SRAM ..."<<endl; if (!_nes->load_sram(sram_path.native_file_string().c_str())) cout<<"Fail to load SRAM ..."<<endl; } } //_nes->get_cpu()->set_logging(true); // 実行ループ { cout<<"Start emulation ..."<<endl; fps_timer timer(60); for(int cnt=0;;cnt++){ SDL_Event event; while (SDL_PollEvent(&event)){ switch(event.type){ case SDL_QUIT: goto _quit; case SDL_KEYDOWN: { SDLKey ks=event.key.keysym.sym; if (ks==SDLK_t) _nes->get_cpu()->set_logging(true); else if (ks==SDLK_r) _nes->reset(); else if (ks==SDLK_F1||ks==SDLK_F2||ks==SDLK_F3||ks==SDLK_F4||ks==SDLK_F5|| ks==SDLK_F6||ks==SDLK_F7||ks==SDLK_F8||ks==SDLK_F9){ int n=(ks==SDLK_F1?1:ks==SDLK_F2?2:ks==SDLK_F3?3:ks==SDLK_F4?4:ks==SDLK_F5?5: ks==SDLK_F6?6:ks==SDLK_F7?7:ks==SDLK_F8?8:ks==SDLK_F9?9:0); string s=(save_dir/(save_base+"-"+(char)('0'+n)+".state")).native_file_string(); if (event.key.keysym.mod&KMOD_SHIFT){ if (_nes->save_state(s.c_str())) cout<<"Save State to #"<<n<<endl; } else{ if (_nes->load_state(s.c_str())) cout<<"Restore State from #"<<n<<endl; else cout<<"Fail to Restore State #"<<n<<endl; } } } break; } } _nes->exec_frame(); Uint8 *keys=SDL_GetKeyState(NULL); bool fast=keys[SDLK_TAB]==SDL_PRESSED; ((sdl_renderer*)nr)->skip_render(fast&&(cnt%10!=0)); if (!fast) timer.elapse(); } } _quit:; { fs::path sram_path=(save_dir/(save_base+".sram")); if (_nes->save_sram(sram_path.native_file_string().c_str())) cout<<"Saving SRAM ..."<<endl; } delete nr; delete _nes; SDL_Quit(); return 0; }
[ [ [ 1, 144 ] ] ]
ea507f5ae566f310baccd0b6200041c29bfc0fb3
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/npc.hpp
47708663d0b579fe129183bc7319fc7f4f1a82b6
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
WINDOWS-1251
C++
false
false
1,790
hpp
#ifndef NPC_HPP #define NPC_HPP #include "npc_fwd.hpp" #include "npc_i.hpp" #include "core/module_h.hpp" #include "basic_types.hpp" class npc :public container ,public npc_events::on_request_class_i ,public npc_events::on_spawn_i { public: typedef npc_ptr_t ptr_t; enum playback_type_e { playback_type_none ,playback_type_driver ,playback_type_onfoot }; public: npc(unsigned int id); virtual ~npc(); public: unsigned int id_get() const {return id;} std::string const& name_get() const {return name;} public: virtual void on_request_class(); virtual void on_spawn(); public: // Методы работы с npc // Желательно вызвать во время конекта void set_spawn_info(int skin_id, pos4 const& pos = pos4()); void set_color(unsigned int color); void put_to_vehicle(int vehicle_id); void playback_start(playback_type_e playback_type, std::string const& recording_name); void playback_stop(); void playback_pause(); void playback_resume(); void kick(); bool is_valid() const; // Возращает истину, если бот не был кикнут public: // Внутренние метода void do_kick(); // Кикает бота, если в этом есть необходимость private: samp::api::ptr api_ptr; unsigned int id; std::string name; bool is_spawn_seted; bool is_spawned; private: int spawn_skin_id; pos4 spawn_pos; unsigned int spawn_color; bool is_kicked; // Если истина, то нужно выгнать бота с сервера }; #endif // NPC_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 63 ] ] ]
5ce4a519b19b8bdedd0d779caa7c9c7b1bd4ca14
6c8c4728e608a4badd88de181910a294be56953a
/UiModule/Ether/View/EllipseMenu.cpp
ba1337a900053665eec90f0bf6b01f0ff5f11c44
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,725
cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "EllipseMenu.h" #include "MemoryLeakCheck.h" #include <math.h> #define M_PI_2 1.57079632679489661923 // In naali this didnt get defined from math.h namespace Ether { namespace View { EllipseMenu::EllipseMenu(TYPE type) { type_ = type; } EllipseMenu::~EllipseMenu() { } void EllipseMenu::CalculatePositions(QVector<QPointF> &positions) { QRectF boundaries = boundaries_; qreal start_phase; qreal end_phase; int visible_objects = max_visible_objects_; boundaries.setWidth(boundaries.width() - current_card_max_size_.width()); qreal width_radius = boundaries.width()/2; qreal phase_change = 0; qreal height_bias = 0; if(type_ == EllipseMenu::ELLIPSE_OPENS_UP) { start_phase = M_PI_2; end_phase = 0; phase_change = -fabs(end_phase - start_phase) / ((visible_objects/2)); height_bias = boundaries.top(); boundaries.setBottom(boundaries.bottom()-current_card_max_size_.height()); } if(type_ == EllipseMenu::ELLIPSE_OPENS_DOWN) { start_phase = -M_PI_2; end_phase = 0; phase_change = fabs(end_phase - start_phase) / ((visible_objects/2)); boundaries.setBottom(boundaries.bottom()-current_card_max_size_.height()); height_bias = boundaries.bottom(); } qreal current_phase = start_phase; QPointF pos; pos.setX(boundaries.left()+width_radius); pos.setY(sin(current_phase)*boundaries.height()+ height_bias); positions.push_back(pos); //calculate the rest of the positions for (int i=1; i<visible_objects; i++) { QPointF pos; qreal cosine=0; //if indexer is paired, we will negate the cos of phase if(i%2==1) { current_phase += phase_change; cosine = cos(current_phase); } else { cosine = -cos(current_phase); } pos.setX(cosine*width_radius+boundaries.left()+ width_radius); pos.setY(sin(current_phase)*boundaries.height()+height_bias); //since sometimes rect can be so small, that the points are forming a line, we want to adjust the cards a bit /*if(type_ == EllipseMenu::OPENS_DOWN) { qreal scaled_h = current_card_max_size_.height() * pow(current_scale_factor_ ,static_cast<qreal>((i+1)/2)); qreal bot = pos.y() + scaled_h; if(bot< (boundaries.top() + current_card_max_size_.height())) { pos.setY(boundaries.top() + (current_card_max_size_.height() - scaled_h)); } }*/ positions.push_back(pos); } hide_point_.setX(boundaries.right()/2); if(type_ == EllipseMenu::ELLIPSE_OPENS_UP) hide_point_.setY(boundaries.top()); if(type_ == EllipseMenu::ELLIPSE_OPENS_DOWN) hide_point_.setY(boundaries.bottom()); } } }
[ "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 3 ], [ 5, 6 ], [ 9, 17 ], [ 19, 41 ], [ 43, 49 ], [ 51, 86 ], [ 102, 105 ], [ 107, 107 ], [ 109, 112 ] ], [ [ 4, 4 ], [ 7, 8 ] ], [ [ 18, 18 ], [ 42, 42 ], [ 50, 50 ], [ 87, 101 ], [ 106, 106 ], [ 108, 108 ] ] ]
ad7343b1e3d34087cdd1801ac65b446f56494277
465943c5ffac075cd5a617c47fd25adfe496b8b4
/TRAFF_T.CPP
6ca5ae712fa97838ece630b86ecb15e831cf84b8
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
/* test driver class for traffic Paul Wilson 8/4/96 */ # include "stdatc.h" # include "airport.h" # include "gate.h" # include "traffic.h" int main() { Traffic t; Plane *p; Position::MaxX = 20; Position::MaxY = 20; Airport a2 (Position (5,5), 1, D180); p = new Plane ('a' , Vector3D (Position (5,4), D0,1) , Jet, &a2); cout <<"\n\n\n"; p->AlterTargAlt (0); t.NewAirborne (p); cout << '\n' << t.SafeCnt() << '\t' << t.Crashed(); t.StepAll(); cout << '\n' << t.SafeCnt() << '\t' << t.Crashed(); return 0; } /**/
[ [ [ 1, 49 ] ] ]
4239498c6dc43f8c212d4de893e225f45b88a76c
a7a890e753c6f69e8067d16a8cd94ce8327f80b7
/tclient/network.cpp
eb7f34d09ab8166e3374e7dbbe33786db558c630
[]
no_license
jbreslin33/breslinservergame
684ca8b97f36e265f30ae65e1a65435b2e7a3d8b
292285f002661c3d9483fb080845564145d47999
refs/heads/master
2021-01-21T13:11:50.223394
2011-03-14T11:33:30
2011-03-14T11:33:30
37,391,245
0
0
null
null
null
null
UTF-8
C++
false
false
11,767
cpp
/******************************************/ /* MMOG programmer's guide */ /* Tutorial game client */ /* Programming: */ /* Teijo Hakala */ /******************************************/ #include "client.h" #include "network.h" //char serverIP[32] = "127.0.0.1"; char serverIP[32] = "192.168.2.126"; //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::StartConnection() { // LogString("StartConnection"); //gameIndex = ind; int ret = networkClient->Initialise("", serverIP, 30004); if(ret == DREAMSOCK_CLIENT_ERROR) { char text[64]; sprintf(text, "Could not open client socket"); //MessageBox(NULL, text, "Error", MB_OK); } Connect(); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::ReadPackets(void) { char data[1400]; struct sockaddr address; clientData *clList; int type; int ind; int local; int ret; char name[50]; dreamMessage mes; mes.Init(data, sizeof(data)); while(ret = networkClient->GetPacket(mes.data, &address)) { mes.SetSize(ret); mes.BeginReading(); type = mes.ReadByte(); switch(type) { case DREAMSOCK_MES_ADDCLIENT: local = mes.ReadByte(); ind = mes.ReadByte(); strcpy(name, mes.ReadString()); AddClient(local, ind, name); break; case DREAMSOCK_MES_REMOVECLIENT: ind = mes.ReadByte(); LogString("Got removeclient %d message", ind); RemoveClient(ind); break; case USER_MES_FRAME: // Skip sequences mes.ReadShort(); mes.ReadShort(); for(clList = clientList; clList != NULL; clList = clList->next) { // LogString("Reading DELTAFRAME for client %d", clList->index); ReadDeltaMoveCommand(&mes, clList); } break; case USER_MES_NONDELTAFRAME: // Skip sequences mes.ReadShort(); mes.ReadShort(); clList = clientList; for(clList = clientList; clList != NULL; clList = clList->next) { LogString("Reading NONDELTAFRAME for client %d", clList->index); ReadMoveCommand(&mes, clList); } break; case USER_MES_SERVEREXIT: // MessageBox(NULL, "Server disconnected", "Info", MB_OK); Disconnect(); break; } } } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::AddClient(int local, int ind, char *name) { // First get a pointer to the beginning of client list clientData *list = clientList; clientData *prev; LogString("App: Client: Adding client with index %d", ind); // No clients yet, adding the first one if(clientList == NULL) { LogString("App: Client: Adding first client"); clientList = (clientData *) calloc(1, sizeof(clientData)); if(local) { LogString("App: Client: This one is local"); localClient = clientList; } clientList->index = ind; strcpy(clientList->nickname, name); if(clients % 2 == 0) createPlayer(ind); else createPlayer(ind); clientList->next = NULL; } else { LogString("App: Client: Adding another client"); prev = list; list = clientList->next; while(list != NULL) { prev = list; list = list->next; } list = (clientData *) calloc(1, sizeof(clientData)); if(local) { LogString("App: Client: This one is local"); localClient = list; } list->index = ind; strcpy(list->nickname, name); clientList->next = NULL; list->next = NULL; prev->next = list; if(clients % 2 == 0) createPlayer(ind); else createPlayer(ind); } clients++; // If we just joined the game, request a non-delta compressed frame if(local) SendRequestNonDeltaFrame(); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::RemoveClient(int ind) { clientData *list = clientList; clientData *prev = NULL; clientData *next = NULL; // Look for correct client and update list for( ; list != NULL; list = list->next) { if(list->index == ind) { if(prev != NULL) { prev->next = list->next; } break; } prev = list; } // First entry if(list == clientList) { if(list) { next = list->next; free(list); } list = NULL; clientList = next; } // Other else { if(list) { next = list->next; free(list); } list = next; } clients--; } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::RemoveClients(void) { clientData *list = clientList; clientData *next; while(list != NULL) { if(list) { next = list->next; free(list); } list = next; } clientList = NULL; clients = 0; } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::SendCommand(void) { if(networkClient->GetConnectionState() != DREAMSOCK_CONNECTED) return; dreamMessage message; char data[1400]; int i = networkClient->GetOutgoingSequence() & (COMMAND_HISTORY_SIZE-1); message.Init(data, sizeof(data)); message.WriteByte(USER_MES_FRAME); // type message.AddSequences(networkClient); // sequences // Build delta-compressed move command BuildDeltaMoveCommand(&message, &inputClient); // Send the packet networkClient->SendPacket(&message); // Store the command to the input client's history memcpy(&inputClient.frame[i], &inputClient.command, sizeof(command_t)); clientData *clList = clientList; // Store the commands to the clients' history for( ; clList != NULL; clList = clList->next) { memcpy(&clList->frame[i], &clList->command, sizeof(command_t)); } } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::SendRequestNonDeltaFrame(void) { char data[1400]; dreamMessage message; message.Init(data, sizeof(data)); message.WriteByte(USER_MES_NONDELTAFRAME); message.AddSequences(networkClient); networkClient->SendPacket(&message); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::Connect(void) { if(init) { LogString("ArmyWar already initialised"); return; } LogString("CArmyWar::Connect"); init = true; networkClient->SendConnect("myname"); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::Disconnect(void) { if(!init) return; LogString("CArmyWar::Disconnect"); init = false; localClient = NULL; memset(&inputClient, 0, sizeof(clientData)); networkClient->SendDisconnect(); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::ReadMoveCommand(dreamMessage *mes, clientData *client) { // Key client->serverFrame.key = mes->ReadByte(); // Heading //client->serverFrame.heading = mes->ReadShort(); // Origin client->serverFrame.origin.x = mes->ReadFloat(); client->serverFrame.origin.y = mes->ReadFloat(); client->serverFrame.vel.x = mes->ReadFloat(); client->serverFrame.vel.y = mes->ReadFloat(); // Read time to run command client->serverFrame.msec = mes->ReadByte(); memcpy(&client->command, &client->serverFrame, sizeof(command_t)); // Fill the history array with the position we got for(int f = 0; f < COMMAND_HISTORY_SIZE; f++) { client->frame[f].predictedOrigin.x = client->command.origin.x; client->frame[f].predictedOrigin.y = client->command.origin.y; } } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::ReadDeltaMoveCommand(dreamMessage *mes, clientData *client) { int processedFrame; int flags = 0; // Flags flags = mes->ReadByte(); // Key if(flags & CMD_KEY) { client->serverFrame.key = mes->ReadByte(); client->command.key = client->serverFrame.key; LogString("Client %d: Read key %d", client->index, client->command.key); } if(flags & CMD_ORIGIN) { processedFrame = mes->ReadByte(); } // Origin if(flags & CMD_ORIGIN) { client->serverFrame.origin.x = mes->ReadFloat(); client->serverFrame.origin.y = mes->ReadFloat(); client->serverFrame.vel.x = mes->ReadFloat(); client->serverFrame.vel.y = mes->ReadFloat(); if(client == localClient) { CheckPredictionError(processedFrame); } else { client->command.origin.x = client->serverFrame.origin.x; client->command.origin.y = client->serverFrame.origin.y; client->command.vel.x = client->serverFrame.vel.x; client->command.vel.y = client->serverFrame.vel.y; } } // Read time to run command client->command.msec = mes->ReadByte(); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::BuildDeltaMoveCommand(dreamMessage *mes, clientData *theClient) { int flags = 0; int last = (networkClient->GetOutgoingSequence() - 1) & (COMMAND_HISTORY_SIZE-1); // Check what needs to be updated if(theClient->frame[last].key != theClient->command.key) flags |= CMD_KEY; // Add to the message // Flags mes->WriteByte(flags); // Key if(flags & CMD_KEY) { mes->WriteByte(theClient->command.key); } mes->WriteByte(theClient->command.msec); } //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- void CArmyWar::RunNetwork(int msec) { //MovePlayer(); static int time = 0; time += msec; // Framerate is too high if(time < (1000 / 60)) { MovePlayer(); return; } frametime = time / 1000.0f; time = 0; // Read packets from server, and send new commands ReadPackets(); SendCommand(); int ack = networkClient->GetIncomingAcknowledged(); int current = networkClient->GetOutgoingSequence(); // Check that we haven't gone too far if(current - ack > COMMAND_HISTORY_SIZE) return; // Predict the frames that we are waiting from the server for(int a = ack + 1; a < current; a++) { int prevframe = (a-1) & (COMMAND_HISTORY_SIZE-1); int frame = a & (COMMAND_HISTORY_SIZE-1); PredictMovement(prevframe, frame); } MoveObjects(); }
[ "jbreslin33@localhost" ]
[ [ [ 1, 524 ] ] ]
ff9b7ff20b3dd87db3bc665a37ec1f94d48a29b0
7fae7848ccc0644e2b0a85804c989603c4a850c4
/Season4/Source/Config/Protocols.cpp
c7310624c3c9fcda69f7176efdb7a97e56cb057c
[]
no_license
brunohkbx/pendmu-server
9a67a08b812517a9ac7dc35dddef4770c362ee9a
2ff144a75739db45755a6bfba2dba8ee6ad28728
refs/heads/master
2021-01-21T12:03:32.243128
2010-10-10T17:01:29
2010-10-10T17:01:29
39,051,181
1
1
null
null
null
null
UTF-8
C++
false
false
25,957
cpp
/******************************************** * Syrius DLL Season 4 FULL + MOD * Code By: Mr.Lai * Year: 2009 * Support: All Protocol * Credit goes to lots of people *********************************************/ //Includes & Defines #include "Protocols.h" #include "GameServer.h" #include "Global.h" #include "ChatCore.h" #include "User.h" //#include "DropItem.h" #include "Creature.h" #include "Log.h" #include "Common.h" #include "DuelSystem.h" #include "PCpoints.h" #include "NPC.h" #include "Structure.h" #include "CQuestSystem.h" #include "ChaosMachine.h" #include "MoveReq.h" #include "ImperialEvent.h" BYTE RecvTable[256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0xD7,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0x1D,0xD4,0xD5,0xD6,0xDC,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xD6, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF } ; extern BYTE RecvTable[256]; //Protocol Server-->Client BYTE ProtocolServer(BYTE Type) { if(Config.IsProtocol == 0) //KOR { switch(Type) { case 0x1D: return 0xD3; //Walk case 0xD6: return 0xDF; //Movefix case 0xDC: return 0xD7; //Attack //case 0xD7: return 0x10; //MagicSkill } } /* else if(Config.IsProtocol == 1) //JPN { switch(Type) { case 0x1D: return 0x1D; //Walk case 0xD6: return 0xD6; //Movefix case 0xDC: return 0xDC; //Attack //case 0xD7: return 0xD7; //MagicSkill } } */ else if(Config.IsProtocol == 2) //VTM { switch(Type) { case 0x1D: return 0xD9; //Walk case 0xD6: return 0xDC; //Movefix case 0xDC: return 0x15; //Attack //case 0xD7: return 0x1D; //MagicSkill } } else if(Config.IsProtocol == 3) //ENG { switch(Type) { case 0x1D: return 0xD4; //Walk case 0xD6: return 0x15; //Movefix case 0xDC: return 0x11; //Attack //case 0xD7: return 0xD7; //MagicSkill } } else if(Config.IsProtocol == 4) //CHS { switch(Type) { //case 0x1D: return 0xD7; //Walk 1D case 0xD6: return 0xD7; //Movefix case 0xDC: return 0xD9; //Attack //case 0xD7: return 0x1D; //MagicSkill } } else { switch(Type) { case 0x1D: return 0xD3; //Walk case 0xD6: return 0xDF; //Movefix case 0xDC: return 0xD7; //Attack //case 0xD7: return 0x10; //MagicSkill } } return Type; } //Protocol Client-->Server BYTE ProtocolClient(BYTE Type) { if(Config.IsProtocol == 0) //KOR { switch(Type) { case 0xD3: return 0x1D; //Walk case 0xDF: return 0xD6; //Movefix case 0xD7: return 0xDC; //Attack //case 0x10: return 0xD7; //MagicSkill } } /* else if(Config.IsProtocol == 1) //JPN { switch(Type) { case 0x1D: return 0x1D; //Walk case 0xD6: return 0xD6; //Movefix case 0xDC: return 0xDC; //Attack //case 0xD7: return 0xD7; //MagicSkill } } */ else if(Config.IsProtocol == 2) //VTM { switch(Type) { case 0xD9: return 0x1D; //Walk case 0xDC: return 0xD6; //Movefix case 0x15: return 0xDC; //Attack //case 0x1D: return 0xD7; //MagicSkill } } else if(Config.IsProtocol == 3) //ENG { switch(Type) { case 0xD4: return 0x1D; //Walk case 0x15: return 0xD6; //Movefix case 0x11: return 0xDC; //Attack //case 0xD7: return 0xD7; //MagicSkill } } else if(Config.IsProtocol == 4) //CHS { switch(Type) { //case 0xD7: return 0x1D; //Walk 1D case 0xD7: return 0xD6; //Movefix case 0xD9: return 0xDC; //Attack D9 //case 0x1D: return 0xD7; //MagicSkill } } else { switch(Type) { case 0xD3: return 0x1D; //Walk case 0xDF: return 0xD6; //Movefix case 0xD7: return 0xDC; //Attack //case 0x10: return 0xD7; //MagicSkill } } return Type; } //Something with "Protocol of skills" WORD MakeWord(BYTE loByte,BYTE hiByte) { WORD x=0; _asm { XOR EAX,EAX MOV AL, loByte MOV AH, hiByte MOV x, AX } return x; } //Protocol Core bool ProtocolCore(BYTE protoNum,LPBYTE aRecv,DWORD aLen,DWORD aIndex,DWORD Encrypt,int Serial) { GOBJSTRUCT *gObj = (GOBJSTRUCT*)OBJECT_POINTER(aIndex); //BYTE pProtocol[pMaxLen] ; //memcpy (pProtocol,aRecv,aLen+1 ); BYTE ProtocolType = aRecv[0]; switch (ProtocolType) { case 0xC1: if(Config.IsProtocol==0) { switch(BYTE(protoNum)) { case 0x10: protoNum = 0xD7; aRecv[2] = 0xD7; break; case 0xF1: // FIx Login aRecv[1] -= 0x02; aLen = aRecv[1]; int i; for(i = 24; i<50; i++) aRecv[i] = aRecv[i+2]; break; case 0xD0: if(aRecv[1]== 0x04&&aRecv[3] == 0x06) { PCPoint.OpenShop(aIndex); return true; } if(aRecv[3] == 0x05) { PCPoint.BuyItem(aIndex,aRecv[4]); return true; } break; } } else if(Config.IsProtocol==1) //JPN { switch(BYTE(protoNum)) { /* case 0xD7: protoNum = 0xD7; aRecv[2] = 0xD7; break; */ case 0xD0: if(aRecv[1]== 0x04&&aRecv[3] == 0x06) { PCPoint.OpenShop(aIndex); return true; } if(aRecv[3] == 0x05) { PCPoint.BuyItem(aIndex,aRecv[4]); return true; } break; } } else if(Config.IsProtocol == 2) //VTM { switch(BYTE(protoNum)) { case 0x10: protoNum = 0xD7; aRecv[2] = 0xD7; break; } } else if(Config.IsProtocol == 3) //ENG { switch(BYTE(protoNum)) { case 0xDB: protoNum = 0xD7; aRecv[2] = 0xD7; break; } } else if(Config.IsProtocol == 4) //CHS { switch(BYTE(protoNum)) { case 0x1D: protoNum = 0xD7; aRecv[2] = 0xD7; break; } } break; } switch(BYTE(protoNum)) { case 0x00: //Move & chat Protocol { ChatSystem.ChatDataSend(aIndex,aRecv); } break; case 0x03: { int Map = (int)gObj_GetMap(aIndex); if(Map == 64)gObjMoveGate_JMP(aIndex, 294); //SetPCPoint(aIndex); //PCPoint.SQLGetPoints(aIndex); PCPoint.GetInfo(aIndex); GCServerMsgStringSend(ConnectNotice1,aIndex,0); GCServerMsgStringSend(ConnectNotice2,aIndex,0); GCServerMsgStringSend(ConnectNotice3,aIndex,0); g_Quest.LoadQuest(aIndex); conLog.ConsoleOutputDT("[%s][%s][%d] Connect.",gObj->AccountID,gObj->Name,aIndex); #ifdef Season5 if(gObj->pInventory[RING_01].m_Type == 0x1A7A || gObj->pInventory[RING_02].m_Type == 0x1A7A) //SKeleton Ring { gObj->m_Change = 14; gObjViewportListProtocolCreate(gObj); } //Load Quest Pending BYTE Packet3[6]={0xC1,0x05,0xF6,0x0F,0x255,0x00}; BYTE Packet4[6]={0xC1,0x05,0xF7,0x0F,0x255,0x00}; Log.outError("Season 5 Quest System"); DataSend(aIndex, &Packet3[0], Packet3[1]); DataSend(aIndex, &Packet4[0], Packet4[1]); #endif } break; #ifdef Season5 //case 0x06: // CGLevelUpPointAdd((PMSG_LVPOINTADD *)aRecv, aIndex); // break; case 0xF1://Login protocol (Season 5) { aRecv[1] -= 0x02; aLen = aRecv[1]; for (int i = 24; i<52; i++) aRecv[i] = aRecv[i+2]; }break; case 0xF6://New S5 Packet { BYTE Packet3[6]={0xC1,0x05,0xF6,0x0F,0x255,0x00}; BYTE Packet4[6]={0xC1,0x05,0xF7,0x0F,0x255,0x00}; BYTE pNewProtocol[0x05]={0xC1,0x05,0x18,0x01,0x7A}; DataRecv(RecvTable[pNewProtocol[2]], pNewProtocol, pNewProtocol[1], aIndex, Encrypt, Serial ); //SCFPanelInfoSend(aIndex); // return true; Log.outError("Season 5 Quest System"); DataSend(aIndex, &Packet3[0], Packet3[1]); return true; } break; case 0x8E: //S5 Warp Menu Fix if(gObj->m_iDuelUser == -1) { g_MoveReq.Teleport(aIndex,aRecv[8]); } return true; break; case 0x24: //Panda Fix (Equip Guardian) if(aRecv[4] == RING_01 || aRecv[4] == RING_02) { if(gObj->m_Change == 14) //SKeleton Ring { gObj->m_Change = -1; gObjViewportListProtocolCreate(gObj); } } break; case 0x86: // Chaos Machine (New Wing Mix) ChaosboxCombinationEx(aIndex,aRecv[3]); break; //IN WORK - Imperial Guardian and Double Goer EVENT PROTOCOLS case 0xF7: Imperial.CheckCanEnter(aIndex); return true; break; /* case 0xBF: // Season 5 Double Goer Event { if(aRecv[1] == 0x05 && aRecv[3] == 0x0E) { DoubleGoer.EnterDoubleGoer(aIndex,(int)aRecv[4]+12); return true; } }break; */ case 0xDC: //Can't Kill Gate, while Event not started, or in standby. ^^ if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 0) { return true; } else if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 1) { for(int i=0;i<ImperialGateCfg.nGateOfEvent;i++) { if(ImperialGateCfg.GatesID[i] != 0) { if((aRecv[4] + aRecv[3] * 256) == ImperialGateCfg.GatesID[i] && ImperialGateCfg.GatesNum[i] != 1) { //Messages.outYellow(aIndex,"Attack Gate : %d %d",(aRecv[4] + aRecv[3] * 256), ImperialGateCfg.GatesID[i]); return true; } } } //Messages.outYellow(aIndex,"Attack Mob : %d",(aRecv[4] + aRecv[3] * 256)); } break; case 0x19: //Can't Kill Gate, while Event not started, or in standby. ^^ if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 0) { return true; } else if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 1) { for(int i=0;i<ImperialGateCfg.nGateOfEvent;i++) { if(ImperialGateCfg.GatesID[i] != 0) { if((aRecv[6] + aRecv[5] * 256) == ImperialGateCfg.GatesID[i] && ImperialGateCfg.GatesNum[i] != 1) { //Messages.outYellow(aIndex,"Attack Gate : %d %d",(aRecv[6] + aRecv[5] * 256), ImperialGateCfg.GatesID[i]); return true; } } } } break; case 0x10: //Can't Kill Gate, while Event not started, or in standby. ^^ if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 0) { return true; } else if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 1) { for(int i=0;i<ImperialGateCfg.nGateOfEvent;i++) { if(ImperialGateCfg.GatesID[i] != 0) { if((aRecv[10] + aRecv[9] * 256) == ImperialGateCfg.GatesID[i] && ImperialGateCfg.GatesNum[i] != 1) { //Messages.outYellow(aIndex,"Attack Gate : %d %d",(aRecv[10] + aRecv[9] * 256), ImperialGateCfg.GatesID[i]); return true; } } } } break; case 0x1E: //Can't Kill Gate, while Event not started, or in standby. ^^ if(Imperial.EventDay == 1) { if(gObj->MapNumber == 69) { if(gObj->Y >= 52 && (gObj->X > 230 && gObj->X < 236) && Imperial.CanUseTwisting == 0) //Gate 2 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 77 && gObj->Y <= 82) && (gObj->X >= 216 && gObj->X <= 219) && Imperial.CanUseTwisting == 0) //Gate 3 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 22 && gObj->Y <= 29) && (gObj->X >= 193 && gObj->X <= 197) && Imperial.CanUseTwisting == 0) //Gate 4 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 22 && gObj->Y <= 29) && (gObj->X >= 166 && gObj->X <= 170) && Imperial.CanUseTwisting == 0) //Gate 5 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 50 && gObj->Y <= 70) && (gObj->X >= 152 && gObj->X <= 157) && Imperial.CanUseTwisting == 0) //Gate 6 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 76 && gObj->Y <= 80) && (gObj->X >= 178 && gObj->X <= 184) && Imperial.CanUseTwisting == 0) //Gate 7 { if(aRecv[4] == 0x29) return true; } } } if(Imperial.EventDay == 2) { if(gObj->MapNumber == 70) { if((gObj->Y >= 61 && gObj->Y <= 68) && (gObj->X > 50 && gObj->X < 54) && Imperial.CanUseTwisting == 0) //Gate 2 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 63 && gObj->Y <= 66) && (gObj->X >= 19 && gObj->X <= 21) && Imperial.CanUseTwisting == 0) //Gate 3 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 90 && gObj->Y <= 92) && (gObj->X >= 34 && gObj->X <= 39) && Imperial.CanUseTwisting == 0) //Gate 4 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 114 && gObj->Y <= 116) && (gObj->X >= 38 && gObj->X <= 45) && Imperial.CanUseTwisting == 0) //Gate 5 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 151 && gObj->Y <= 153) && (gObj->X >= 53 && gObj->X <= 57) && Imperial.CanUseTwisting == 0) //Gate 6 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 108 && gObj->Y <= 113) && (gObj->X >= 107 && gObj->X <= 109) && Imperial.CanUseTwisting == 0) //Gate 7 { if(aRecv[4] == 0x29) return true; } } } if(Imperial.EventDay == 3) { if(gObj->MapNumber == 71) { if((gObj->Y >= 190 && gObj->Y <= 195) && (gObj->X > 119 && gObj->X < 122) && Imperial.CanUseTwisting == 0) //Gate 2 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 192 && gObj->Y <= 198) && (gObj->X >= 89 && gObj->X <= 92) && Imperial.CanUseTwisting == 0) //Gate 3 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 131 && gObj->Y <= 133) && (gObj->X >= 220 && gObj->X <= 226) && Imperial.CanUseTwisting == 0) //Gate 4 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 157 && gObj->Y <= 159) && (gObj->X >= 220 && gObj->X <= 226) && Imperial.CanUseTwisting == 0) //Gate 5 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 190 && gObj->Y <= 192) && (gObj->X >= 220 && gObj->X <= 226) && Imperial.CanUseTwisting == 0) //Gate 6 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 215 && gObj->Y <= 217) && (gObj->X >= 165 && gObj->X <= 170) && Imperial.CanUseTwisting == 0) //Gate 7 { if(aRecv[4] == 0x29) return true; } } } if(Imperial.EventDay == 4) { if(gObj->MapNumber == 72) { if((gObj->Y >= 66 && gObj->Y <= 70) && (gObj->X >= 50 && gObj->X <= 52) && Imperial.CanUseTwisting == 0) //Gate 2 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 92 && gObj->Y <= 90) && (gObj->X >= 30 && gObj->X <= 35) && Imperial.CanUseTwisting == 0) //Gate 3 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 174 && gObj->Y <= 176) && (gObj->X >= 31 && gObj->X <= 37) && Imperial.CanUseTwisting == 0) //Gate 4 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 188 && gObj->Y <= 194) && (gObj->X >= 50 && gObj->X <= 52) && Imperial.CanUseTwisting == 0) //Gate 5 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 190 && gObj->Y <= 192) && (gObj->X >= 220 && gObj->X <= 226) && Imperial.CanUseTwisting == 0) //Gate 6 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 129 && gObj->Y <= 135) && (gObj->X >= 155 && gObj->X <= 157) && Imperial.CanUseTwisting == 0) //Gate 7 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 129 && gObj->Y <= 135) && (gObj->X >= 195 && gObj->X <= 197) && Imperial.CanUseTwisting == 0) //Gate 8 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 157 && gObj->Y <= 159) && (gObj->X >= 222 && gObj->X <= 227) && Imperial.CanUseTwisting == 0) //Gate 9 { if(aRecv[4] == 0x29) return true; } if((gObj->Y >= 21 && gObj->Y <= 28) && (gObj->X >= 214 && gObj->X <= 216) && Imperial.CanUseTwisting == 0) //Gate 10 { if(aRecv[4] == 0x29) return true; } } } if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 0) { if(aRecv[4] == 0x29) return true; } //else if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 1) // { // if(aRecv[4] == 0x29) return true; // } break; case 0xD7: //Can't Kill Gate, while Event not started, or in standby. ^^ if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 0) { return true; } else if(gObj->MapNumber == Imperial.EventMap && ImperialMain.UserIsInFort[GET_USER_INDEX(aIndex)] == 1 && ImperialMain.Status == 1) { for(int i=0;i<ImperialGateCfg.nGateOfEvent;i++) { if(ImperialGateCfg.GatesID[i] != 0) { if((aRecv[10] + aRecv[9] * 256) == ImperialGateCfg.GatesID[i] && ImperialGateCfg.GatesNum[i] != 1) { //Messages.outYellow(aIndex,"Attack Gate : %d %d",(aRecv[10] + aRecv[9] * 256), ImperialGateCfg.GatesID[i]); return true; } } } } break; #endif case 0x30: NPCTalkEx(aIndex, (aRecv[4] + aRecv[3] * 256)); break; case 0x95: { DWORD Address=0x00; BYTE MyTable[2]={aRecv[4],aRecv[3]}; memcpy(&Address,&MyTable,sizeof(MyTable)); GoldenArcher(aIndex,Address); //Log Tracing //conLog.ConsoleOutput("%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",aRecv[0],aRecv[1],aRecv[2],aRecv[3],aRecv[4],aRecv[5],aRecv[6],aRecv[7],aRecv[8],aRecv[9],aRecv[10],aRecv[11],aRecv[12],aRecv[13],aRecv[14],aRecv[15],aRecv[16],aRecv[17],aRecv[18],aRecv[19],aRecv[20],aRecv[21],aRecv[22],aRecv[23],aRecv[24],aRecv[25],aRecv[26],aRecv[27],aRecv[28],aRecv[29],aRecv[30]); } break; case 0xBC: // Lahap dupe { int Error = 0; for(int i = 8000; i<9000; i++) { if(gObj->TargetNumber == i) Error = 1; if(Error) break; } if(Error) { Log.outError("[%s][%s] ANTI-HACK [LAHAP PACKET]",gObj->AccountID,gObj->Name); conLog.ConsoleOutputDT("[%s][%s] ANTI-HACK [LAHAP PACKET]",gObj->AccountID,gObj->Name); return true; } } break; case 0xAA: { if (Duel.isNewSystem==1) { if(aRecv[3]==0x01) { //Log Tracing //conLog.ConsoleOutput("%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",aRecv[0],aRecv[1],aRecv[2],aRecv[3],aRecv[4],aRecv[5],aRecv[6],aRecv[7],aRecv[8],aRecv[9],aRecv[10],aRecv[11],aRecv[12],aRecv[13],aRecv[14],aRecv[15],aRecv[16],aRecv[17],aRecv[18],aRecv[19],aRecv[20],aRecv[21],aRecv[22],aRecv[23],aRecv[24],aRecv[25],aRecv[26],aRecv[27],aRecv[28],aRecv[29],aRecv[30]); #ifdef GameServer90_CS //Fake Packet BYTE pNewProtocol[0x05]={0xC1,0x05,0x18,0x01,0x7A}; DataRecv (RecvTable[pNewProtocol[2]], pNewProtocol, pNewProtocol[1], aIndex, Encrypt, Serial ); GCServerMsgStringSend("Can't Duel In This Server",aIndex, 0x01); return true; #endif #ifdef GameServer90 DWORD TargetID=0x00; BYTE ConCatenate[2]={aRecv[5],aRecv[4]}; memcpy(&TargetID,&ConCatenate,sizeof(ConCatenate)); int playerLevel = gObj_GetLevel(aIndex); int targetLevel = gObj_GetLevel(TargetID); if((playerLevel < Duel.MinLevel) || (targetLevel < Duel.MinLevel)) { //Fake Packet BYTE pNewProtocol[0x05]={0xC1,0x05,0x18,0x01,0x7A}; DataRecv (RecvTable[pNewProtocol[2]], pNewProtocol, pNewProtocol[1], aIndex, Encrypt, Serial ); char sbuf[255]={0}; wsprintf(sbuf,MSG23,Duel.MinLevel); GCServerMsgStringSend(sbuf,aIndex, 0x01); return true; } //Save User IDs for eachother pObjGS[aIndex-MIN_PLAYERID].DuelRequested=TargetID; pObjGS[TargetID-MIN_PLAYERID].DuelRequested=aIndex; //Create New Packet BYTE pNewLen=aRecv[1]-1; aRecv[0] = 0xC1; aRecv[1] = pNewLen; aRecv[2] = 0xAA; memcpy (&aRecv[3], &aRecv[4], pNewLen-4 ); DataRecv(protoNum, aRecv, pNewLen, aIndex, Encrypt, Serial ); return true; } if(aRecv[3] == 0x02) { if(aRecv[4] == 0x00) { DWORD TargetID = 0; BYTE ConCatenate[2]={aRecv[6],aRecv[5]}; memcpy(&TargetID,&ConCatenate,2); BYTE aRecv[5]={0xC1,0x05,0xAA,0x03,0x00}; DataSend ( TargetID, aRecv ,aRecv[1]); gObj_Write(TargetID,0xF04,-1); gObj_Write(aIndex,0xF08,-1); return true; } BYTE pNewLen=aRecv[1]-2; aRecv[0] = 0xC1; aRecv[1] = pNewLen; aRecv[2] = 0xAC; memcpy (&aRecv[3], &aRecv[4], pNewLen-3 ); protoNum = 0xAC; DataRecv(protoNum, aRecv, pNewLen, aIndex, Encrypt, Serial ); return true; } if(aRecv[3] == 0x07) { //Fake Packet BYTE pNewProtocol[0x05]={0xC1,0x05,0x18,0x01,0x7A}; DataRecv(RecvTable[pNewProtocol[2]], pNewProtocol, pNewProtocol[1], aIndex, Encrypt, Serial ); Duel.WarpRoom(aIndex,aRecv[4]); return true; } #endif } } break; } DataRecv(protoNum,aRecv,aLen,aIndex,Encrypt,Serial); return true; } void ProtocolCoreSend(DWORD PlayerID,PBYTE tpProtocol,DWORD ProtocolLen) { int iKorSend = 0; BYTE pNewProtocol[pMaxLen]; DWORD dwNewLen = 0; BYTE ProtocolType; GOBJSTRUCT *gObj = (GOBJSTRUCT*)OBJECT_POINTER(PlayerID); /* switch(tpProtocol[0]) { case 0xC1: switch(tpProtocol[2]) { case 0x17: // NPC Die //DieNPCEx(aIndex,(aSend[4] + aSend[3] * 256)); //PCPoint.IncreasePoints(PlayerID,3); break; case 0xF3: switch(tpProtocol[3]) { case 0x05: // Level Up //PCPoint.IncreasePoints(PlayerID,UpPoints); break; } break; } break; } */ if (tpProtocol[0] < (BYTE)0xC1 || tpProtocol[0] > (BYTE)0xC4) { return; } if ((tpProtocol[0] == (BYTE)0xC1) || tpProtocol[0] == (BYTE)0xC3) { ProtocolType = tpProtocol[2] ; } else { ProtocolType = tpProtocol[3] ; } switch (ProtocolType) { #ifdef GameServer90 case 0xAA: //DUEL DIALOG SEND TO OPPONENT ANS { if ((Duel.isNewSystem == 1)) { DWORD TargetID; BYTE ConCatenate[2]={tpProtocol[5],tpProtocol[4]}; memcpy(&TargetID,&ConCatenate,2); PBYTE pProtocol = tpProtocol; iKorSend=1 ; dwNewLen=0x11 ; pNewProtocol[0]= 0xC1; pNewProtocol[1]= dwNewLen; pNewProtocol[2]= 0xAA; pNewProtocol[3]= 0x01; if(pProtocol[4]==0x00) { pNewProtocol[4]= 0x0F; //CANCEL } else { pNewProtocol[4]= 0x00; //OK } memcpy (&pNewProtocol[5], &pProtocol[4], dwNewLen-4 ); if(pNewProtocol[4] == 0x00) { Duel.DuelOK_EnterRoom(pObjGS[PlayerID-MIN_PLAYERID].DuelRequested,PlayerID); //return; // -------------------------- } } } break; case 0xAB: //END DUEL { if (Duel.isNewSystem==1) { PBYTE pProtocol = tpProtocol; iKorSend=1 ; dwNewLen=0x05 ; pNewProtocol[0]= 0xC1; pNewProtocol[1]= dwNewLen; pNewProtocol[2]= 0xAA; pNewProtocol[3]= 0x03; pNewProtocol[4]= 0x00; //BYTE Win = 0; //if(pProtocol[5] == 0x53) //{ // Win = 1; //} Duel.ClearRoombyPlayerID(PlayerID); } }break; case 0xAC: //DUEL DIALOG SEND TO OPPONENT { if (Duel.isNewSystem==1) { PBYTE pProtocol = tpProtocol; iKorSend=1 ; dwNewLen=0x10 ; pNewProtocol[0]= 0xC1; pNewProtocol[1]= dwNewLen; pNewProtocol[2]= 0xAA; pNewProtocol[3]= 0x02; memcpy (&pNewProtocol[4], &pProtocol[3], dwNewLen-3 ); } } break; case 0xAD: //DUEL SCORE SEND { if (Duel.isNewSystem==1) { PBYTE pProtocol = tpProtocol; iKorSend=1 ; dwNewLen=0x0A ; pNewProtocol[0]= 0xC1; pNewProtocol[1]= dwNewLen; pNewProtocol[2]= 0xAA; pNewProtocol[3]= 0x04; memcpy (&pNewProtocol[4], &pProtocol[3], dwNewLen-3 ); } } break; #endif } if(iKorSend == 1) DataSend(PlayerID, pNewProtocol ,dwNewLen); else DataSend ( PlayerID, tpProtocol ,ProtocolLen); }
[ "hackeralin@9c614f3a-9621-f771-f2fc-7608378cfbb4" ]
[ [ [ 1, 942 ] ] ]
f9cd6427e2d6d91ab641f0e361babcf48a6f94f5
102d8810abb4d1c8aecb454304ec564030bf2f64
/TP2/Nahuel/xml.cpp
44fa7abf60d3d371156ff4e8e7f8c1a458d9a8fe
[]
no_license
jfacorro/tp-taller-prog-1-fiuba
2742d775b917cc6df28188ecc1f671d812017a0a
a1c95914c3be6b1de56d828ea9ff03e982560526
refs/heads/master
2016-09-14T04:32:49.047792
2008-07-15T20:17:27
2008-07-15T20:17:27
56,912,077
0
0
null
null
null
null
ISO-8859-2
C++
false
false
14,815
cpp
// xml.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "XmlDictionaryParser.h" #include <iostream> #include <set> #include "conio.h" #include "sdl.h" #include "math.h" void PrintDictionary ( XmlDictionaryNode* p , string indent ) { cout << indent << "(" << p->nodeId << ") " << p->nodeName << " {"; map<string,string>::iterator iter; for ( iter = p->nodeAttrs.begin() ; iter != p->nodeAttrs.end() ; ++iter ) cout << "\"" << iter->first << "\":\"" << iter->second << "\","; cout << "}" << endl; XmlDictionaryNode* c = p->children; while ( c != NULL ) { PrintDictionary ( c , indent + " " ); c = c->next; } } bool GetAttribute ( XmlDictionaryNode* p , string attrName , int* val ) { map<string,string>::iterator iter = p->nodeAttrs.find(attrName); if ( iter == p->nodeAttrs.end() ) { cout << "Warning!!! Missing attribute '" << attrName << "' in node " << p->nodeId << endl; return false; } // TODO: Verificar validez de val sscanf ( iter->second.c_str() , "%d" , val ); return true; } typedef struct _Point { int X; int Y; } Point; Point* GetPosition ( XmlDictionaryNode* p , string tagName ) { int x, y; XmlDictionaryNode* tmp = p->children; while ( tmp != NULL ) { if ( tmp->nodeName == tagName ) { map<string,string>::iterator iter = tmp->nodeAttrs.find("x"); if ( iter == tmp->nodeAttrs.end() ) { cout << "Warning!!! Missing position parameter 'x' in node " << tmp->nodeId << " (parent=" << p->nodeId << ")" << endl; return NULL; } // TODO: Verificar validez de x sscanf ( iter->second.c_str() , "%d" , &x ); iter = tmp->nodeAttrs.find("y"); if ( iter == tmp->nodeAttrs.end() ) { cout << "Warning!!! Missing position parameter 'y' in node " << tmp->nodeId << " (parent=" << p->nodeId << ")" << endl; return NULL; } // TODO: Verificar validez de x sscanf ( iter->second.c_str() , "%d" , &y ); Point* retval = new Point(); retval->X = x; retval->Y = y; return retval; } tmp = tmp->next; } cout << "Warning!!! Missing position tag under node " << p->nodeId << endl; return NULL; } // DrawPixel // Tomada del tutorial de sdl // http://www.libsdl.org/intro.en/usingvideo.html void DrawPixel(SDL_Surface *screen, int x, int y, Uint8 R, Uint8 G, Uint8 B) { if ( x < 0 || x >= screen->clip_rect.w || y < 0 || y >= screen->clip_rect.h ) return; Uint32 color = SDL_MapRGB(screen->format, R, G, B); switch (screen->format->BytesPerPixel) { case 1: { /* Assuming 8-bpp */ Uint8 *bufp; bufp = (Uint8 *)screen->pixels + y*screen->pitch + x; *bufp = color; } break; case 2: { /* Probably 15-bpp or 16-bpp */ Uint16 *bufp; bufp = (Uint16 *)screen->pixels + y*screen->pitch/2 + x; *bufp = color; } break; case 3: { /* Slow 24-bpp mode, usually not used */ Uint8 *bufp; bufp = (Uint8 *)screen->pixels + y*screen->pitch + x; *(bufp+screen->format->Rshift/8) = R; *(bufp+screen->format->Gshift/8) = G; *(bufp+screen->format->Bshift/8) = B; } break; case 4: { /* Probably 32-bpp */ Uint32 *bufp; bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x; *bufp = color; } break; } } void GetPixel(SDL_Surface *screen, int x, int y, Uint8* R, Uint8* G, Uint8* B) { x = x % screen->clip_rect.w; y = y % screen->clip_rect.h; switch (screen->format->BytesPerPixel) { case 1: { /* Assuming 8-bpp */ Uint8 *bufp; bufp = (Uint8 *)screen->pixels + y*screen->pitch + x; SDL_GetRGB ( *bufp , screen->format , R , G , B ); } break; case 2: { /* Probably 15-bpp or 16-bpp */ Uint16 *bufp; bufp = (Uint16 *)screen->pixels + y*screen->pitch/2 + x; SDL_GetRGB ( *bufp , screen->format , R , G , B ); } break; case 3: { /* Slow 24-bpp mode, usually not used */ Uint8 *bufp; bufp = (Uint8 *)screen->pixels + y*screen->pitch + x; SDL_GetRGB ( *bufp , screen->format , R , G , B ); } break; case 4: { /* Probably 32-bpp */ Uint32 *bufp; bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x; SDL_GetRGB ( *bufp , screen->format , R , G , B ); } break; } } typedef struct _Color { Uint8 R; Uint8 G; Uint8 B; } Color; void DrawSquare ( SDL_Surface* screen , int x , int y , int l , Color color , SDL_Surface* texture , int nodeId ) { if ( x < 0 || y < 0 || l <= 0 ) { cout << "Warning!!! Invalid square coordinates (" << x << "," << y << "," << l << ") in node " << nodeId << endl; return; } for ( int posY = y ; posY < (y + l) ; posY++ ) for ( int posX = x ; posX < (x + l) ; posX++ ) { if ( texture != NULL ) GetPixel ( texture , posX - x , posY - y , &color.R , &color.G , &color.B ); DrawPixel ( screen , posX , posY , color.R , color.G , color.B ); } } void DrawCircle ( SDL_Surface* screen , int x , int y , int r , Color color , int nodeId ) { if ( x < 0 || y < 0 || r <= 0 ) { cout << "Warning!!! Invalid circle coordinates (" << x << "," << y << "," << r << ") in node " << nodeId << endl; return; } for ( int posY = y - r ; posY <= (y + r) ; posY++ ) { int dY = abs(y - posY); int dX = (int) sqrt ( (double) (r * r - dY * dY) ); for ( int posX = x - dX ; posX <= (x + dX) ; posX++ ) DrawPixel ( screen , posX , posY , color.R , color.G , color.B ); } } void DrawRectangle ( SDL_Surface* screen , int x , int y , int b , int h , Color color , int nodeId ) { if ( x < 0 || y < 0 || b <= 0 || h <= 0 ) { cout << "Warning!!! Invalid rectangle coordinates (" << x << "," << y << "," << b << "," << h << ") in node " << nodeId << endl; return; } for ( int posY = y ; posY < (y + h) ; posY++ ) for ( int posX = x ; posX < (x + b) ; posX++ ) DrawPixel ( screen , posX , posY , color.R , color.G , color.B ); } #define USE_ANTIALIASING #ifndef USE_ANTIALIASING #define CALCULATE_ANTIALIAS(c1,c2,ref,offset) int c1 = 0, c2 = ref; #else #define CALCULATE_ANTIALIAS(c1,c2,ref,offset) \ int c1 = (int) ((double) ref * (offset - (double) (int) offset)); \ int c2 = ref - c1; \ if ( c1 > c2 ) corr = sqrt((double) (c1 + c2) / (double) c1); \ else corr = sqrt((double) (c1 + c2) / (double) c2); \ c1 = (int) (corr * (double) c1); \ c2 = (int) (corr * (double) c2); #endif void DrawSegment ( SDL_Surface* screen , int x1 , int y1 , int x2 , int y2 , Color color , int nodeId ) { if ( x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0 ) { cout << "Warning!!! Invalid segment coordinates (" << x1 << "," << y1 << "-" << x2 << "," << y2 << ") in node " << nodeId << endl; return; } if ( x2 < x1 ) { int tmpx, tmpy; tmpx = x1; x1 = x2; x2 = tmpx; tmpy = y1; y1 = y2; y2 = tmpy; } #ifdef USE_ANTIALIASING double corr = 0; #endif if ( (x2 - x1) > (y2 - y1) ) { double y = y1; for ( int posX = x1 ; posX <= x2 ; posX++ ) { CALCULATE_ANTIALIAS(r1,r2,color.R,y); CALCULATE_ANTIALIAS(g1,g2,color.G,y); CALCULATE_ANTIALIAS(b1,b2,color.B,y); DrawPixel ( screen , posX , (int) y , r2 , g2 , b2 ); DrawPixel ( screen , posX , (int) y + 1 , r1 , g1 , b1 ); y += (double) (y2 - y1) / (double) (x2 - x1); } } else { double x = x1; for ( int posY = y1 ; posY <= y2 ; posY++ ) { CALCULATE_ANTIALIAS(r1,r2,color.R,x); CALCULATE_ANTIALIAS(g1,g2,color.G,x); CALCULATE_ANTIALIAS(b1,b2,color.B,x); DrawPixel ( screen , (int) x , posY , r2 , g2 , b2 ); DrawPixel ( screen , (int) x + 1 , posY , r1 , g1 , b1 ); x += (double) (x2 - x1) / (double) (y2 - y1); } } } map<string,SDL_Surface*> textures; SDL_Surface* GetTexture ( XmlDictionaryNode* p ) { SDL_Surface* retval = NULL; map<string,string>::iterator iter = p->nodeAttrs.find("textura"); if ( iter != p->nodeAttrs.end() ) { map<string,SDL_Surface*>::iterator texture = textures.find(iter->second); if ( texture == textures.end() ) cout << "Warning!!! Texture not found in node " << p->nodeId << endl; else retval = texture->second; } return retval; } #define PRINT_COLOR_SYNTAX_ERROR() cout << "Warning!!! Invalid color syntax in node " << p->nodeId << endl Color GetColorAttribute ( XmlDictionaryNode* p , string attrName ) { Color retval; retval.R = 255; retval.G = 255; retval.B = 255; map<string,string>::iterator iter = p->nodeAttrs.find(attrName); if ( iter != p->nodeAttrs.end () ) { if ( iter->second.size() != 9 ) PRINT_COLOR_SYNTAX_ERROR(); else { int tmpR, tmpG, tmpB; sscanf ( iter->second.substr(0,3).c_str() , "%d" , &tmpR ); sscanf ( iter->second.substr(3,3).c_str() , "%d" , &tmpG ); sscanf ( iter->second.substr(6,3).c_str() , "%d" , &tmpB ); if ( tmpR < 0 || tmpR > 255 || tmpG < 0 || tmpG > 255 || tmpB < 0 || tmpB > 255 ) { PRINT_COLOR_SYNTAX_ERROR(); } else { retval.R = tmpR; retval.G = tmpG; retval.B = tmpB; } } } return retval; } void LoadTexture ( XmlDictionaryNode* p ) { map<string,string>::iterator id = p->nodeAttrs.find("id"); map<string,string>::iterator path = p->nodeAttrs.find("path"); if ( id == p->nodeAttrs.end() || path == p->nodeAttrs.end() ) cout << "Warning!!! Attributes 'id' and 'path' are mandatory in node " << p->nodeId << endl; else { if ( textures.find(id->second) != textures.end() ) cout << "Warning!!! Texture '" << id->second << "' already loaded in node " << p->nodeId << endl; else { SDL_Surface* bmp = SDL_LoadBMP ( path->second.c_str() ); if ( bmp == NULL ) cout << "Warning!!! Invalid texture file '" << path->second << "' in node " << p->nodeId << endl; else textures.insert(make_pair(id->second,bmp)); } } } void ParseDictionary ( SDL_Surface* screen , XmlDictionaryNode* p ) { XmlDictionaryNode* current = p->children; set<string> ids; Point* pos = NULL, *pos2 = NULL; int p1,p2; while ( current != NULL ) { if ( current->nodeName == "cuadrado" ) { pos = GetPosition ( current , "posicion" ); if ( pos != NULL && GetAttribute(current,"lado",&p1) ) DrawSquare ( screen , pos->X , pos->Y , p1 , GetColorAttribute(current,"colorFigura") , GetTexture(current) , current->nodeId ); } else if ( current->nodeName == "circulo" ) { pos = GetPosition ( current , "posicion" ); if ( pos != NULL && GetAttribute(current,"radio",&p1) ) DrawCircle ( screen , pos->X , pos->Y , p1 , GetColorAttribute(current,"colorFigura") , current->nodeId ); } else if ( current->nodeName == "rectangulo" ) { pos = GetPosition ( current , "posicion" ); if ( pos != NULL && GetAttribute(current,"base",&p1) && GetAttribute(current,"altura",&p2) ) { DrawRectangle ( screen , pos->X , pos->Y , p1 , p2 , GetColorAttribute(current,"colorFigura") , current->nodeId ); } } else if ( current->nodeName == "segmento" ) { pos = GetPosition ( current , "inicio" ); pos2 = GetPosition ( current , "fin" ); if ( pos != NULL && pos2 != NULL ) DrawSegment ( screen , pos->X , pos->Y , pos2->X , pos2->Y , GetColorAttribute(current,"colorLinea") , current->nodeId ); if ( pos2 != NULL ) { delete pos2; pos2 = NULL; } } else if ( current->nodeName == "textura" ) LoadTexture ( current ); else cout << "Warning!!! Unrecognized shape '" << current->nodeName << "' in node " << current->nodeId << endl; map<string,string>::iterator iter = current->nodeAttrs.find("id"); if ( iter == current->nodeAttrs.end() ) cout << "Warning!!! Attribute 'id' is mandatory in node " << current->nodeId << endl; else { if ( ids.find(iter->second) != ids.end() ) cout << "Warning!!! Attribute 'id' is not unique in node " << current->nodeId << endl; else ids.insert(iter->second); } current = current->next; if ( pos != NULL ) { delete pos; pos = NULL; } } } void PrintShapes ( XmlDictionaryNode* p ) { SDL_Surface* screen; screen = SDL_SetVideoMode ( 640 , 480 , 16, SDL_SWSURFACE ); if ( screen == NULL ) { printf ( "Unable to set 640x480 video: %s\n", SDL_GetError() ); return; } if ( SDL_MUSTLOCK(screen) ) if ( SDL_LockSurface(screen) < 0 ) { printf ( "Unable lock surface: %s\n", SDL_GetError() ); return; } ParseDictionary ( screen , p ); if ( SDL_MUSTLOCK(screen) ) { SDL_UnlockSurface(screen); } SDL_UpdateRect(screen, 0, 0, 640, 480); } int _tmain(int argc, _TCHAR* argv[]) { if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) cout << "Unable to initialize SDL: " << SDL_GetError() << endl; else { string xml = (string) "<root>" + (string) "<textura id='stone' path='C:\\Archivos de programa\\Microsoft Office\\Office10\\Bitmaps\\Styles\\stone.bmp'/>" + (string) "<textura id='cafe' path='C:\\windows\\grano de café.bmp'/>" + (string) "<cuadrado id='cuadrado1' textura='stone' colorFigura='255000000' lado='10'><posicion x='0' y='0' /></cuadrado>" + (string) "<cuadrado id='cuadrado2' colorFigura='000255000' lado='200' textura='cafe'><posicion x='100' y='100' /></cuadrado>" + (string) "<rectangulo id='r1' colorFigura='000000255' base='10' altura='20'><posicion x='0' y='100'/></rectangulo>" + (string) "<segmento id='s1' colorLinea='100200100'><inicio x='0' y='0' /><fin x='639' y='20' /></segmento>" + (string) "<segmento id='s2' colorLinea='200100200'><inicio x='0' y='0' /><fin x='20' y='479' /></segmento>" + (string) "<circulo id='c1'colorFigura='255255255' radio='30'><posicion x='200' y='200' /></circulo>" + (string) "</root>"; XmlDictionaryParser parser(xml); parser.Parse(); XmlDictionaryNode* d = parser.GetRoot(); if ( d != NULL ) { cout << endl << "Dumping dictionary..." << endl; PrintDictionary ( d , "" ); cout << endl << "Printing shapes... "; PrintShapes ( d ); cout << "Ready." << endl; } cout << "Press any key to continue..."; getch(); //int k; //cin >> k; SDL_Quit(); } return 0; }
[ "nahuelgonzalez@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb" ]
[ [ [ 1, 535 ] ] ]
bc23d500b430f3b3d154407aa8de2a353b9ac934
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/SRC/Topology/Ring1.cpp
266634ba67445e2db323b3c84b3837732e07b450
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
5,296
cpp
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //Project Homepage:http://code.google.com/p/whutnetsim/ //corresponding author's email: [email protected] //All rights reserved // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Date: //Modify Author: //Author Organization: //Modify Date: //更改人:李玉 //更改时间:2010-1-28 #include "Ring1.h" #include "G_debug.h" #include "node.h" #include "linkp2p.h" #include "mask.h" #include <math.h> #include <stdio.h> using namespace std; // Constructors CRing::CRing(Count_t count, IPAddr_t i, const Linkp2p& link, SystemId_t id) :CPlatTopoBase(count,i,link,id) /* 描述:CRing的构造函数 参数:[IN] count :拓扑的节点数目 [IN] i :拓扑节点的基IP [IN] link :拓扑的节点间的连接方式 [IN] id :分布式系统标识符 返回:空 备注: */ { } bool CRing::GenerateTopo() /* 描述:生成拓扑 参数:无 返回:是否生成成功 备注: */ { ConstructorHelper(link, ip); return true; } // Private methods void CRing::ConstructorHelper(const Linkp2p& link, IPAddr_t leafIP) /* 描述:生成拓扑的帮助函数 参数:[IN] link :拓扑的节点间的连接方式 [IN] leafIP :拓扑节点的基IP 返回:无 备注:参数可以不要,因为用的都是类中的成员 */ { first = Node::nextId; Node *n = new Node (); n->SetIPAddr(ip++); //nodes.push_back(n); Node *firstnode = n; //nodeCount = count; IPAddr_t nextIP = leafIP; for (Count_t l = 1; l <= nodeCount; ++l) { // Create each subsequent level Node *newnode; if (l!=nodeCount) { newnode = new Node(); newnode->SetIPAddr(ip++); //nodes.push_back(newnode); } else newnode = firstnode; //if (nextIP == IPADDR_NONE) //{ // No IP specified // n->AddDuplexLink(newnode, link); //} //else //{ // n->AddDuplexLink(newnode, link, // nextIP++, Mask(32), // IPADDR_NONE, Mask(32)); //} //n = newnode; n->AddDuplexLink(newnode, link); } last = Node::nextId; } void CRing::SetLocationViaBoundBox(const Location& ll, const Location& ur, BoxType type) /* 描述:通过绑定位置来给节点设置坐标 参数:[in]ll :左下角的位置 [in]ur :右上角的位置 [in]type :设置位置的类型 返回:无 */ { Meters_t xRadius = fabs(ur.X() - ll.X())/2; Meters_t yRadius = fabs(ur.Y() - ll.Y())/2; Meters_t xCenter = (ur.X() + ll.X())/2; Meters_t yCenter = (ur.Y() + ll.Y())/2; double angle = (2 * M_PI)/ nodeCount; NodeId_t thisNode = first; const NodeVec_t& nodes = Node::GetNodes(); DEBUG0((cout<<"Putting Ring nodes in place"<<endl)); // Assign locations for each level for (Count_t l = 0; l < nodeCount; ++l) { Meters_t yLoc = yCenter + yRadius * sin(angle * l); Meters_t xLoc = xCenter + xRadius * cos(angle * l); nodes[thisNode++]->SetLocation(xLoc,yLoc); DEBUG0((cout<<"Putting node "<<l<<" in ("<<xLoc<<","<<yLoc<<")"<<endl)); } }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 179 ] ] ]
2f706ef88793a07549c188989ae7167f3ae8bb26
3b2322c1adf5e6166259540e767ec67df0887c17
/src/state/StateFighterApproachTarget.h
7192fe8ba851c03e3f03d0459abff22ff9a046bd
[]
no_license
aruwen/various-stefan-ebner
750aac6e546ddb3e571ac468ecc26087843817d3
49eac46ed3a01131d711ea6feca77c32accb4733
refs/heads/master
2021-01-20T00:42:40.803881
2011-03-13T14:08:22
2011-03-13T14:08:22
32,136,593
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
#pragma once #include "State.h" #include "..\MovingObject.h" class EnemyFighter; class StateFighterApproachTarget: public State { public: StateFighterApproachTarget(EnemyFighter *ownFighter, MovingObject *target):mOwnFighter(ownFighter), mTarget(target) {initState();}; ~StateFighterApproachTarget(){}; virtual void initState(); virtual void enterState(); virtual void exitState(); virtual int update(); // update game logic static const float attackRadius; private: EnemyFighter *mOwnFighter; MovingObject *mTarget; };
[ "nightwolve@bb536436-bb54-8cee-38f9-046b9e77f541" ]
[ [ [ 1, 25 ] ] ]
b1d97b8157b50d40e5bfdb9893168f6865e9958f
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/eeschema/plugins/netlist_form_pads-pcb.cpp
6909b3754ab6ed6566d9c4f24b67eaab14519948
[]
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
6,710
cpp
/**********************************/ /* Netlist generator for pads-pcb */ /**********************************/ /* read the generic netlist created by eeschema and convert it to a pads-pcb form */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef __UNIX__ #define stricmp strcasecmp #define strnicmp strncasecmp #endif /* Pads-pcb sample: *PADS-PCB* *PART* C1 CHIP_D C2 C1206 C3 CHIP_B C4 CHIP_B D1 CHIP_B JP1 unknown *NET* *SIGNAL* N03791 C3.1 R1.1 JP2.7 U1.3 *SIGNAL* VCC U2.14 Y1.8 JP5.2 U3.2 C1.1 U1.20 JP1.8 JP1.3 C5.2 C6.1 C7.2 U1.7 Y1.7 *SIGNAL* N01384 JP5.1 U1.1 *SIGNAL* N02594 *END* */ /* Generic netlist sample: $BeginNetlist $BeginComponentList $BeginComponent TimeStamp=32568D1E Footprint= Reference=JP1 Value=CONN_8X2 Libname=CONN_8X2 $BeginPinList 1=GND 2=REF10_1 3=GND 4=REF11_1 5=GND 6=REF7_1 7=GND 8=REF9_1 9=GND 10=REF6_1 11=GND 12=REF8_1 13=GND 14=REF4_1 15=GND 16=REF5_1 $EndPinList $EndComponent $BeginComponent TimeStamp=325679C1 Footprint= Reference=RR1 Value=9x1K Libref=RR9 $BeginPinList 1=VCC 2=REF5_1 3=REF4_1 4=REF8_1 5=REF6_1 6=REF9_1 7=REF7_1 8=REF11_1 9=REF10_1 10=? $EndPinList $EndComponent $EndComponentList $BeginNets Net 0 "" Net 1 "GND" BUS1 31 U3 19 U3 10 U3 1 Net 172 "" BUS1 32 Net 173 "" BUS1 30 $EndNets $EndNetlist */ char * GetLine(FILE *File, char *Line, int *LineNum, int SizeLine); int ReadAndWriteComponentDataSection(FILE * InFile, FILE * OutFile, int *LineNumber); int ReadAndWriteNetsDataSection(FILE * InFile, FILE * OutFile, int * LineNumber); class ComponentDataClass { public: char m_Reference[256]; char m_Value[256]; char m_Footprint[256]; char m_LibRef[256]; long m_TimeStamp; public: ComponentDataClass(void) { InitData(); } void InitData(void) { m_TimeStamp = 0; m_Reference[0] = 0; m_Value[0] = 0; m_Footprint[0] = 0; m_LibRef[0] = 0; } }; /********************************/ int main(int argc, char ** argv ) /********************************/ { char * InputfileName, * OutputFilename; FILE * InFile, * OutFile; int LineNumber; char Line[1024]; if ( argc < 3 ) { printf("\nUsage; netlist_form_pads-pcb infile outfile\n"); return -1; } InputfileName = argv[1]; OutputFilename = argv[2]; if ( (InFile = fopen(InputfileName, "rt")) == NULL) { printf ( "Failed to open file %s", InputfileName); return -2; } if ( (OutFile = fopen(OutputFilename, "wt")) == NULL) { printf ( "Failed to create file %s", OutputFilename); return -3; } /* Write header: */ fprintf( OutFile, "*PADS-PCB*\n*PART*\n" ); /* Read and write data lines */ while( GetLine(InFile, Line, &LineNumber, sizeof(Line) ) ) { if ( stricmp(Line, "$BeginComponent") == 0 ) { ReadAndWriteComponentDataSection(InFile, OutFile, &LineNumber); continue; } if ( stricmp(Line, "$BeginNets") == 0 ) { fprintf( OutFile, "\n*NET*\n" ); ReadAndWriteNetsDataSection(InFile, OutFile, &LineNumber); continue; } } fprintf( OutFile, "*END*\n" ); fclose(InFile); fclose(OutFile); return 0; } /****************************************************************/ int ReadAndWriteComponentDataSection(FILE * InFile, FILE * OutFile, int *LineNumber) /****************************************************************/ /* Read the Components Section from the Generic Netlist and create Components section in Pads-Pcb format For the component section only reference and footprint are used. Create lines like: C1 CHIP_D C2 unknown */ { char Line[1024]; class ComponentDataClass ComponentData; char * ident, *data; while( GetLine(InFile, Line, LineNumber, sizeof(Line) ) ) { if ( stricmp(Line, "$BeginPinList") == 0 ) { while( GetLine(InFile, Line, LineNumber, sizeof(Line) ) ) if ( stricmp(Line, "$EndPinList") == 0 ) break; continue; } if ( stricmp(Line, "$EndComponent") == 0 ) // Create the output for the component: { /* Create the line like: C2 unknown */ fprintf(OutFile, "%s ", ComponentData.m_Reference ); fprintf(OutFile, "%s\n", strlen(ComponentData.m_Footprint) ? ComponentData.m_Footprint : "unknown"); return 0; } ident = strtok(Line,"=\n\r"); data = strtok(NULL,"=\n\r"); if ( data == NULL ) continue; if ( stricmp(Line, "TimeStamp") == 0 ) { ComponentData.m_TimeStamp = atol(data); continue; } if ( stricmp(Line, "Footprint") == 0 ) { strncpy(ComponentData.m_Footprint, data, 255); continue; } if ( stricmp(Line, "Reference") == 0 ) { strncpy(ComponentData.m_Reference, data, 255); continue; } if ( stricmp(Line, "Value") == 0 ) { strncpy(ComponentData.m_Value, data, 255); continue; } if ( stricmp(Line, "Libref") == 0 ) { strncpy(ComponentData.m_LibRef, data, 255); continue; } } return 1; } /****************************************************************/ int ReadAndWriteNetsDataSection(FILE * InFile, FILE * OutFile, int *LineNumber) /****************************************************************/ /* Read the Nets Section from the Generic Netlist and create Nets section in Pads-Pcb format create info type: *SIGNAL* N03791 C3.1 R1.1 JP2.7 U1.3 */ { char Line[1024]; char * ident, *netnum, *netname, * pin; while( GetLine(InFile, Line, LineNumber, sizeof(Line) ) ) { if ( stricmp(Line, "$EndNets") == 0 ) return 0; ident = strtok(Line," \n\r"); if ( stricmp(ident, "Net") == 0 ) { netnum = strtok(NULL," \n\r"); netname = strtok(NULL," \"\n\r"); if ( (netname == NULL) || strlen(netname) == 0 ) { // Create the line like: *SIGNAL* N03791 int num = atoi(netnum); sprintf(Line, "N-%6.6d", num); netname = Line; } fprintf(OutFile, "*SIGNAL* %s\n", netname); } else { // Create the line like: C3.1 R1.1 JP2.7 U1.3 pin = strtok(NULL," \n\r"); fprintf(OutFile, " %s.%s\n", ident, pin); } } return 1; } /*****************************************************************/ char * GetLine(FILE *File, char *Line, int *LineNum, int SizeLine) /*****************************************************************/ /* Return a non empty line increment *LineNum for each read line Comment lines (starting by '#') are skipped */ { do { if (fgets(Line, SizeLine, File) == NULL) return NULL; if( LineNum ) *LineNum += 1; } while (Line[0] == '#' || Line[0] == '\n' || Line[0] == '\r' || Line[0] == 0); strtok(Line,"\n\r"); return Line; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 319 ] ] ]
af2eabca4f474929d493cd4ce5876b0c70b21231
9eb4d50f6f499d091c036b5745dd17173693b8bf
/src/wii/wii_vb_language.cpp
03dd11a3b053ad4a33913cbbec19c48ab50a60ac
[]
no_license
MathewWi/wiirtual-boy
53efab60de238134c43e00502186c1cfe39245ec
4f4a2b75a721e42e036a91956ca32a549ec0a8ff
refs/heads/master
2021-01-01T17:00:37.708274
2011-06-27T15:22:53
2011-06-27T15:22:53
32,204,974
1
1
null
null
null
null
UTF-8
C++
false
false
3,970
cpp
/* WiirtualBoy : Wii port of the Mednafen Virtual Boy emulator Copyright (C) 2011 raz0red and Arikado This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "wii_vb_language.h" #include <stdio.h> using namespace std; Language::Language() {} Language::~Language() {} /* Loads a language file. Returns true if successful. False if not. */ bool Language::languageLoad(char *filepath) { string filebuffer; FILE *fp = fopen(filepath, "rb"); if(!fp) return false; do { filebuffer += fgetc(fp); } while(!feof(fp)); this->name = this->parseTag("name", filebuffer); this->control = this->parseTag("control", filebuffer); this->menu[0] = this->parseTag("menu0", filebuffer); this->load[0] = this->parseTag("load0", filebuffer); this->load[1] = this->parseTag("load1", filebuffer); this->menu[1] = this->parseTag("menu1", filebuffer); this->save[0] = this->parseTag("save0", filebuffer); this->save[1] = this->parseTag("save1", filebuffer); this->save[2] = this->parseTag("save2", filebuffer); this->menu[2] = this->parseTag("menu2", filebuffer); this->display[0] = this->parseTag("display0", filebuffer); this->display[1] = this->parseTag("display1", filebuffer); this->menu[3] = this->parseTag("menu3", filebuffer); this->advanced[0] = this->parseTag("advanced0", filebuffer); this->advanced[1] = this->parseTag("advanced1", filebuffer); this->advanced[2] = this->parseTag("advanced2", filebuffer); return true; } /* Returns the string stored inbetween a tag. */ string Language::parseTag(string tag, string filebuffer) { string ret; string tag1 = "<" + tag + ">"; string tag2 = "</" + tag + ">"; int first = filebuffer.find(tag1); int last = filebuffer.find(tag2); ret = filebuffer.substr(first + tag1.size(), last - first - tag1.size()); return ret; } /* Generates the english language file. Returns true if successful. False if not. */ bool generateEnglishLanguageFile(char *filepath) { FILE *fp = fopen(filepath, "wb"); if(!fp) return false; fprintf( fp, "<language>\n"); fprintf( fp, "<name>English</name>\n"); fprintf( fp, "<control>U/D = Scroll. A = Select. Home = Exit</control>\n"); fprintf( fp, "<menu0>Load Cartridge</menu0>\n"); fprintf( fp, "<load0>U/D = Scroll. L/R = Page. A = Select. B = Back. Home = Exit</load0>\n"); fprintf( fp, "<load1> cartridges found. displaying </load1>\n"); fprintf( fp, "<menu1>Save state management</menu1>\n"); fprintf( fp, "<save0>Auto load:</save0>\n"); fprintf( fp, "<save1>Auto save:</save1>\n"); fprintf( fp, "<save2>Load saved state</save2>\n"); fprintf( fp, "<menu2>Display settings</save2>\n"); fprintf( fp, "<display0>Screen size:</display0>\n"); fprintf( fp, "<display1>Display mode:</display1>\n"); fprintf( fp, "<menu3>Advanced</menu3>\n"); fprintf( fp, "<advanced0>Debug mode:</advanced0>\n"); fprintf( fp, "<advanced1>Top menu exit:</advanced1>\n"); fprintf( fp, "<advanced2>Wiimote [menu]:</advanced2>\n"); fprintf( fp, "</language>"); fclose(fp); return true; }
[ "[email protected]@00a74ce0-9458-8d50-ee98-3d1c5c732d48", "[email protected]@00a74ce0-9458-8d50-ee98-3d1c5c732d48" ]
[ [ [ 1, 59 ], [ 69, 70 ], [ 72, 116 ], [ 132, 137 ] ], [ [ 60, 68 ], [ 71, 71 ], [ 117, 131 ] ] ]
ede9767fac0342540097e93e23657f5b18814ca7
99527557aee4f1db979a7627e77bd7d644098411
/utils/argsplitter.h
05291722f1d06e1cda8d14b3eae79daba6e69e23
[]
no_license
GunioRobot/2deffects
7aeb02400090bb7118d23f1fc435ffbdd4417c59
39d8e335102d6a51cab0d47a3a2dc7686d7a7c67
refs/heads/master
2021-01-18T14:10:32.049756
2008-09-15T15:56:50
2008-09-15T15:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
642
h
// $Id: ArgSplitter.h,v 1.2 2002/03/21 21:52:18 noname Exp $ #ifndef _ARGSPLITTER_H_ #define _ARGSPLITTER_H_ #include <vector> #include <string> namespace syd { std::vector<std::string> arg_split ( const char* argv ); class ArgSplitter { std::vector<std::string> args_; char rawArgs_[1024]; public: ArgSplitter ( const char* argv ); public: ArgSplitter& putRawArgs ( const char* argv ); public: bool empty() const; void printArgs(std::ostream& o) const; const std::vector<std::string> getArgs () const; private: ArgSplitter (); }; //ArgSplitter } //syd #endif //_ARGSPLITTER_H_
[ [ [ 1, 40 ] ] ]
1c589a3e6ccda2ed153f8e46e97ab6109b40fb87
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/date_time/test/local_time/testcustom_time_zone.cpp
57d5532c0df60e8d32002a295b688167c88764bc
[ "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
3,399
cpp
/* Copyright (c) 2003-2005 CrystalClear Software, Inc. * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) * Author: Jeff Garland, Bart Garst * $Date: 2005/05/03 14:27:04 $ */ #include "boost/date_time/local_time/local_time.hpp" #include "boost/date_time/testfrmwk.hpp" #include <iostream> int main() { using namespace boost::gregorian; using namespace boost::posix_time; using namespace boost::local_time; boost::shared_ptr<dst_calc_rule> rule1(new partial_date_dst_rule(partial_date(30,Apr), partial_date(30,Oct))); boost::shared_ptr<dst_calc_rule> rule2(new first_last_dst_rule(first_last_dst_rule::start_rule(Sunday,Apr), first_last_dst_rule::end_rule(Sunday,Oct))); boost::shared_ptr<dst_calc_rule> rule3(new last_last_dst_rule(last_last_dst_rule::start_rule(Sunday,Mar), last_last_dst_rule::end_rule(Sunday,Oct))); boost::shared_ptr<dst_calc_rule> rule4; // no daylight savings time_zone_names pst("Pacific Standard Time", "PST", "Pacific Daylight Time" , "PDT"); time_zone_names mst("Mountain Standard Time", "MST", "" , ""); dst_adjustment_offsets of(hours(1), hours(2), hours(2)); dst_adjustment_offsets of2(hours(0), hours(0), hours(0)); // no daylight savings time_zone_ptr tz1(new custom_time_zone(pst, hours(-8), of, rule1)); time_zone_ptr tz2(new custom_time_zone(pst, hours(-8), of, rule2)); time_zone_ptr tz3(new custom_time_zone(pst, hours(-8), of, rule3)); time_zone_ptr tz4(new custom_time_zone(mst, hours(-7), of2, rule4)); check("out string", tz1->dst_zone_abbrev() == std::string("PDT")); check("out string", tz1->std_zone_abbrev() == std::string("PST")); check("out string", tz1->std_zone_name() == std::string("Pacific Standard Time")); check("out string", tz1->dst_zone_name() == std::string("Pacific Daylight Time")); check("dst offset", tz1->dst_offset() == hours(1)); check("base offset", tz1->base_utc_offset() == hours(-8)); check("has dst", tz1->has_dst()); check("dst start time", tz1->dst_local_start_time(2003) == ptime(date(2003,Apr,30),hours(2))); check("dst end time", tz1->dst_local_end_time(2003) == ptime(date(2003,Oct,30),hours(2))); check("tz1 to posix string", tz1->to_posix_string() == std::string("PST-08PDT+01,120/02:00,303/02:00")); check("tz2 to posix string", tz2->to_posix_string() == std::string("PST-08PDT+01,M4.1.0/02:00,M10.5.0/02:00")); check("tz3 to posix string", tz3->to_posix_string() == std::string("PST-08PDT+01,M3.5.0/02:00,M10.5.0/02:00")); check("tz4 to posix string", tz4->to_posix_string() == std::string("MST-07")); // test start/end for non-dst zone check("has dst in non-dst zone", !tz4->has_dst()); check("dst start in non-dst zone", tz4->dst_local_start_time(2005) == ptime(not_a_date_time)); check("dst end in non-dst zone", tz4->dst_local_end_time(2005) == ptime(not_a_date_time)); return printTestStats(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 88 ] ] ]
a3b82846b03e5f41485edff7f27534262e7d772f
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Animation/Playback/Control/hkaAnimationControl.inl
b2a31830a9cdcff0e3415e259355049dfd7fbc6c
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,832
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ // Return the local time for the control inline hkReal hkaAnimationControl::getLocalTime() const { return m_localTime; } // Set the local time for the animation inline void hkaAnimationControl::setLocalTime( hkReal lTime ) { m_localTime = lTime; } inline hkReal hkaAnimationControl::getWeight() const { return m_weight; } inline const hkaAnimationBinding* hkaAnimationControl::getAnimationBinding() const { return m_binding; } inline hkUint8 hkaAnimationControl::getTransformTrackWeight(hkUint32 track) const { return m_transformTrackWeights[track]; } inline hkUint8 hkaAnimationControl::getFloatTrackWeight(hkUint32 track) const { return m_floatTrackWeights[track]; } inline void hkaAnimationControl::setTransformTrackWeight(hkUint32 track, hkUint8 weight) { m_transformTrackWeights[track] = weight; } inline void hkaAnimationControl::setFloatTrackWeight(hkUint32 track, hkUint8 weight) { m_floatTrackWeights[track] = weight; } // Get the weight values for all tracks (non-const access) inline const hkArray<hkUint8>& hkaAnimationControl::getTransformTracksWeights() const { return m_transformTrackWeights; } // Get the weight values for all tracks (non-const access) inline const hkArray<hkUint8>& hkaAnimationControl::getFloatTracksWeights() const { return m_floatTrackWeights; } // Get the motion track weight for this control inline hkReal hkaAnimationControl::getMotionTrackWeight() const { return m_motionTrackWeight; } // Set the motion track weight for this control inline void hkaAnimationControl::setMotionTrackWeight(hkReal w) { m_motionTrackWeight = w; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 90 ] ] ]
be96c3366fb8bb6b6ff13530d7d66fdaf92868af
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/KeyValuePair.hpp
0abf63001f60b8130adadcd6a528becebde95bf2
[ "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
3,606
hpp
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: KeyValuePair.hpp,v $ * Revision 1.5 2004/09/08 13:56:22 peiyongz * Apache License Version 2.0 * * Revision 1.4 2004/01/29 11:48:46 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.3 2003/05/15 19:04:35 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.2 2002/11/04 15:22:04 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:10 peiyongz * sane_include * * Revision 1.4 2000/03/02 19:54:41 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/24 20:05:24 abagchi * Swat for removing Log from API docs * * Revision 1.2 2000/02/06 07:48:02 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:04:31 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:09 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(KEYVALUEPAIR_HPP) #define KEYVALUEPAIR_HPP #include <xercesc/util/XMemory.hpp> XERCES_CPP_NAMESPACE_BEGIN template <class TKey, class TValue> class KeyValuePair : public XMemory { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- KeyValuePair(); KeyValuePair(const TKey& key, const TValue& value); KeyValuePair(const KeyValuePair<TKey,TValue>& toCopy); ~KeyValuePair(); // ------------------------------------------------------------------- // Getters // ------------------------------------------------------------------- const TKey& getKey() const; TKey& getKey(); const TValue& getValue() const; TValue& getValue(); // ------------------------------------------------------------------- // Setters // ------------------------------------------------------------------- TKey& setKey(const TKey& newKey); TValue& setValue(const TValue& newValue); private : // unimplemented: KeyValuePair<TKey,TValue>& operator=(const KeyValuePair<TKey,TValue>&); // ------------------------------------------------------------------- // Private data members // // fKey // The object that represents the key of the pair // // fValue // The object that represents the value of the pair // ------------------------------------------------------------------- TKey fKey; TValue fValue; }; XERCES_CPP_NAMESPACE_END #if !defined(XERCES_TMPLSINC) #include <xercesc/util/KeyValuePair.c> #endif #endif
[ [ [ 1, 112 ] ] ]
3e45db59817af4b687a98681a40adf7549bc0ebb
21da454a8f032d6ad63ca9460656c1e04440310e
/src/org/xml/sax/wsiContentHandler.h
76934639e3664e782ad6ee022d5cd0f897527c2f
[]
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
120
h
#pragma once class wsiContentHandler : public wsiObject { public: static const ws_iid sIID; public: };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 10 ] ] ]
3b2f98e36d2c4570779e1d4cea678f1e821786d2
0045750d824d633aba04e1d92987e91fb87e0ee7
/mythread.h
6fa5d6bebc7aa6874de8d6b11e9790468fb6af88
[]
no_license
mirelon/vlaciky
eaab3cbae7d7438c4fcb87d2b5582b0492676efc
30f5155479a3f3556199aa2d845fcac0c9a2d225
refs/heads/master
2020-05-23T15:05:26.370548
2010-06-16T18:55:52
2010-06-16T18:55:52
33,381,959
0
0
null
null
null
null
UTF-8
C++
false
false
855
h
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> #include <QMap> #include <queue> #include "graphics.h" class OpacityEvent{ public: OpacityEvent(){} ~OpacityEvent(){} bool operator <(OpacityEvent &oe); int epoch; int pos; int value; int priority; }; class MyThread : public QThread { Q_OBJECT public: MyThread(); void init(); void run(); public slots: void setOpacity(int i,int opacity); void updateEpoch(); signals: void ssetOpacity(int i,int opacity); void updateStatus(QString stat); public: bool stopped; //je to opacne kvoli priorite //chcem skor vykreslit veci s vacsou opacitou std::priority_queue<OpacityEvent*> opac; QMap<int,int> lastEpoch; QMap<int,int> lastOpacity; float avgPriority; int sumPriority; int epoch; Graphics* graphics; }; #endif // MYTHREAD_H
[ "mirelon@a6d88fff-da04-0f23-7c93-28760c376c6a" ]
[ [ [ 1, 46 ] ] ]
84d2c599fa33e2d9700935b0d4d271499ab62b14
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ui/include/MovementControlState.h
3f7186018db7c934ef64a171254198c0de4ae390
[ "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
ISO-8859-1
C++
false
false
7,038
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 __MovementCharacterController_H__ #define __MovementCharacterController_H__ #include "UiPrerequisites.h" #include "GameTask.h" #include "CreatureController.h" #include "PhysicsController.h" #include "PhysicsGenericContactCallback.h" #include "ControlState.h" #include "DebugVisualisable.h" #include "Selector.h" #include <deque> namespace rl { class Actor; class Creature; class MeshObject; class PhysicsMaterialRaycast; /** * This class handles character control via user input. */ class _RlUiExport MovementControlState : public ControlState, public PhysicsController, public PhysicsGenericContactCallback, public DebugVisualisable { public: typedef enum {VM_THIRD_PERSON, VM_FIRST_PERSON, VM_FREE_CAMERA, VM_PNYX_MODE} ViewMode; /** * @throw NullPointerException if camera or character is NULL. * @throw InvalidArgumentException if character is not placed in the scene. */ MovementControlState(CommandMapper* cmdMapper, Actor* camera, Creature* character); virtual ~MovementControlState(); virtual void pause(); virtual void resume(); void run(Ogre::Real elapsedTime); /// This is the OgreNewt contact process callback for the combination /// Character <-> Level int onAABBOverlap( OgreNewt::Body* body0, OgreNewt::Body* body1, int threadIndex ); void userProcess(OgreNewt::ContactJoint &contactJoint, Ogre::Real timestep, int threadid); /// Newton force and torque callback void OnApplyForceAndTorque(PhysicalThing* thing, float timestep); /// First oder Third person view. void setViewMode(ViewMode mode); ViewMode getViewMode(); void toggleViewMode(); /** Setzt die Camera in einen 30-Grad-Winkel dem Helden auf den Hinterkopf * schauend im aktuellen Abstand vom Helden, wie durch den Spieler bestimmt. */ void resetCamera(); virtual bool mouseReleased(const OIS::MouseEvent& evt, OIS::MouseButtonID id, bool handled); virtual bool mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id, bool handled); virtual bool keyPressed(const OIS::KeyEvent& evt, bool handled); virtual bool keyReleased(const OIS::KeyEvent& evt, bool handled); // Overrides from DebugVisualisable virtual DebugVisualisableFlag getFlag() const; virtual void updatePrimitive(); bool updateAfterGameObjectLoading(); bool beforeLoadingSaveGame(); protected: virtual void doCreatePrimitive(); CreatureController* mController; private: /// private struct for holding state info of the controller struct CharacterState { CharacterState(); int mCurrentMovementState; int mLastMovementState; }; static Ogre::String msDebugWindowPageName; CharacterState mCharacterState;// does only refer to the movement caused by the keyboard // camera control params /// optimal distance to the character Ogre::Real mDesiredDistance; std::pair<Ogre::Real, Ogre::Real> mDistanceRange; Ogre::Degree mCamYaw; // für VM_FREE_CAMERA Ogre::Degree mCamVirtualYaw; // helps to simulate strafe+forward/backward movement Ogre::Degree mNewCamVirtualYaw; // s.o. Ogre::Degree mPitch; Ogre::Degree mRoll; std::pair<Ogre::Degree, Ogre::Degree> mPitchRange; Ogre::Vector3 mLookAtOffset; Ogre::Radian mRotationSpeed; Ogre::Real mMouseSensitivity; bool mInvertedMouse; // like in old games ViewMode mViewMode; PhysicsMaterialRaycast* mRaycast; PhysicsMaterialConvexcast * mConvexcast; OgreNewt::Collision *mCameraCastCollision; HalfSphereSelector mSelector; HalfSphereSelector mCombatSelector; /// Camera Spring-Damping System (smooth movement) spring-factor Ogre::Real mLinearSpringK; /// Camera Spring-Damping System (smooth movement) damping-factor Ogre::Real mLinearDampingK; /// with this velocity the optimal Position of the cam moves away from the char Ogre::Real mCamMoveAwayVelocity; /// if there was no collision of the cam for this time, the cam can securely move backward Ogre::Real mCamMoveAwayStartTime; /// if the angle between the last camera pos and the character and the new one is smaller than this value, the camera can move away from the character Ogre::Radian mCamMoveAwayRange; void updateSelection(); bool isEnemyNear(); void updateCameraLookAt(Ogre::Real elapsedTime); void updateCharacter(Ogre::Real elapsedTime); //void interpolateAnimationLookAtOffset(std::string actAnim, std::string newAnim, Ogre::Real factor); std::vector<Ogre::Vector3> mCharPositionsBuffer; size_t mCharPositionsBufferIdx; Ogre::Real mCharacterOccludedTime; unsigned int mCharacterOccludedFrameCount; Ogre::Real mLastDistance; Ogre::Real mLastCameraCollision; Ogre::Real mTimeOfLastCollision; bool mIsPathfinding; unsigned int mLastReachableBufPos; /** Does all camera-stuff, moves the camera to the right position * and does pathfinding (in a very simple way) * @warning this does only work well, if the character's material is not used for other objects! */ void calculateCamera(const Ogre::Real& timestep); /** Calculates the position, * the camera should move to. * @param SlowlyMoveBackward if set, the camera moves more slowly away from the character then toward it. * @param timestep in order to reset the camera (no valid last position) the timestep can be 0. */ Ogre::Vector3 calculateOptimalCameraPosition(bool SlowlyMoveBackward, const Ogre::Real &timestep); MessagePump::ScopedConnection mMessageType_GameObjectsLoaded_Handler; MessagePump::ScopedConnection mMessageType_SaveGameLoading_Handler; }; } #endif
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 184 ] ] ]
b911c8fd8497708e318d053806a53a003a901941
c2468061ba23ee1fe5e109e6dafae9c65dd1adf1
/lib/OceanTile.cpp
48ce4894fc8350cb9da9980ca7c35adb287ffaa6
[]
no_license
dmzgroup/osgocean
8e19809535714b18d5278728511e733f26460b20
5fe2935e7a1e85847e092dd9ed71064589751f54
refs/heads/master
2020-09-22T15:23:19.127314
2009-12-19T02:38:49
2009-12-19T02:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,424
cpp
/* * This source file is part of the osgOcean library * * Copyright (C) 2009 Kim Bale * Copyright (C) 2009 The University of Hull, UK * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * http://www.gnu.org/copyleft/lesser.txt. */ #include <stdlib.h> // Need to include this for linux compatibility not sure why. #include <osgOcean/OceanTile> #ifdef DEBUG_DATA #include <osgDB/WriteFile> #include <fstream> #include <sstream> #endif using namespace osgOcean; OceanTile::OceanTile( void ): _resolution (0), _rowLength (0), _numVertices (0), _spacing (0), _maxDelta (0), _averageHeight(0) {} OceanTile::OceanTile( osg::FloatArray* heights, unsigned int resolution, const float spacing, osg::Vec2Array* displacements ): _resolution ( resolution ), _rowLength ( _resolution + 1 ), _numVertices( _rowLength*_rowLength ), _vertices ( new osg::Vec3Array ), _normals ( new osg::Vec3Array(_numVertices) ), _spacing ( spacing ), _maxDelta ( 0.f ) { _vertices->reserve( _numVertices ); #ifdef DEBUG_DATA static int count = 0; std::stringstream ss; ss << "Tile_" << count << ".txt"; std::ofstream outFile( ss.str().c_str() ); outFile << _rowLength << std::endl; ++count; #endif float x1,y1; float sumHeights = 0.f; osg::Vec3f v; for(int y = 0; y <= (int)_resolution; ++y ) { y1 = y % _resolution; for(int x = 0; x <= (int)_resolution; ++x ) { x1 = x % _resolution; unsigned int ptr = array_pos(x1,y1,_resolution); if (displacements) // Displacements are optional, default value is NULL { v.x() = displacements->at(ptr).x(); v.y() = displacements->at(ptr).y(); } v.z() = heights->at( ptr ); #ifdef DEBUG_DATA outFile << v.x() << std::endl; outFile << v.y() << std::endl; outFile << v.z() << std::endl; #endif sumHeights += v.z(); _vertices->push_back( v ); } } #ifdef DEBUG_DATA outFile.close(); #endif _averageHeight = sumHeights / (float)_vertices->size(); computeNormals(); //computeMaxDelta(); } OceanTile::OceanTile( const OceanTile& tile, unsigned int resolution, const float spacing ): _resolution ( resolution ), _rowLength ( _resolution + 1 ), _numVertices( _rowLength*_rowLength ), _vertices ( new osg::Vec3Array(_numVertices) ), _normals ( new osg::Vec3Array(_numVertices) ), _spacing ( spacing ), _maxDelta ( 0.f ) { unsigned int parentRes = tile.getResolution(); unsigned int inc = parentRes/_resolution; unsigned int inc2 = inc/2; // Take an average of four points for (unsigned int y = 0; y < parentRes; y+=inc) { for (unsigned int x = 0; x < parentRes; x+=inc) { const osg::Vec3f& a = tile.getVertex( x, y ); const osg::Vec3f& b = tile.getVertex( x+inc2, y ); const osg::Vec3f& c = tile.getVertex( x, y+inc2 ); const osg::Vec3f& d = tile.getVertex( x+inc2, y+inc2 ); osg::Vec3f sum = a + b + c + d; (*_vertices)[ array_pos(x/inc, y/inc, _rowLength) ] = sum * 0.25f; } } for( unsigned int i = 0; i < _rowLength-1; ++i ) { // Copy top row into skirt (*_vertices)[ array_pos( i, _rowLength-1, _rowLength) ] = (*_vertices)[ i ]; // Copy first column into skirt (*_vertices)[ array_pos( _rowLength-1, i, _rowLength) ] = (*_vertices)[ i*_rowLength ]; } // Copy corner value (*_vertices)[ array_pos( _rowLength-1, _rowLength-1, _rowLength ) ] = (*_vertices)[0]; computeNormals(); } OceanTile::OceanTile( const OceanTile& copy ): _vertices ( copy._vertices ), _normals ( copy._normals ), _resolution ( copy._resolution ), _rowLength ( copy._rowLength ), _numVertices ( copy._numVertices ), _spacing ( copy._spacing ), _maxDelta ( copy._maxDelta ), _averageHeight ( copy._averageHeight ) { } OceanTile::~OceanTile( void ) { } OceanTile& OceanTile::operator=(const OceanTile& rhs) { if (this != &rhs) { _vertices = rhs._vertices; _normals = rhs._normals; _resolution = rhs._resolution; _rowLength = rhs._rowLength; _numVertices = rhs._numVertices; _spacing = rhs._spacing; _maxDelta = rhs._maxDelta; _averageHeight = rhs._averageHeight; } return *this; } void OceanTile::computeNormals( void ) { int x1,x2,y1,y2; osg::Vec3f a,b,c,d,v1,v2,v3,n1,n2; const osg::Vec3f s2 = osg::Vec3f( 0.f, -_spacing, 0.f ); const osg::Vec3f s3 = osg::Vec3f( _spacing, 0.f, 0.f ); const osg::Vec3f s4 = osg::Vec3f( _spacing, -_spacing, 0.f ); // Compute normals for an N+2 x N+2 grid to ensure continuous // normals for tiles of the same resolution // Using first row as last row and first column as last column. osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array( (_resolution+2)*(_resolution+2) ); for( int y = -1; y < (int)_resolution; ++y ) { y1 = y % _resolution; y2 = (y+1) % _resolution; for( int x = -1; x < (int)_resolution; ++x ) { x1 = x % _resolution; x2 = (x+1) % _resolution; a = getVertex(x1, y1); // a| /|c b = s2 + getVertex(x1, y2); // | / | c = s3 + getVertex(x2, y1); // | / | d = s4 + getVertex(x2, y2); // b|/ |d v1 = b - a; v2 = b - c; v3 = b - d; n1 = v2 ^ v1; n2 = v3 ^ v2; (*normals)[ array_pos(x+1, y+1, _resolution+2) ] += n1; // a| /c (*normals)[ array_pos(x+1, y+2, _resolution+2) ] += n1; // | / (*normals)[ array_pos(x+2, y+1, _resolution+2) ] += n1; // b|/ (*normals)[ array_pos(x+1, y+2, _resolution+2) ] += n2; // /|c (*normals)[ array_pos(x+2, y+1, _resolution+2) ] += n2; // / | (*normals)[ array_pos(x+2, y+2, _resolution+2) ] += n2; // b/__|d } } for( osg::Vec3Array::iterator itr = normals->begin(); itr != normals->end(); ++itr ) { itr->normalize(); } // copy normals into member normal array discarding first row and column; unsigned int ptr = 0; for(unsigned int y = 1; y <= _resolution+1; ++y ) { for(unsigned int x = 1; x <= _resolution+1; ++x ) { (*_normals)[ptr] = (*normals)[ array_pos(x,y,_resolution+2) ]; ++ptr; } } } void OceanTile::computeMaxDelta( void ) { float deltaMax = 0; int step = 2; int numLevels = 6; for (int level=1; level < numLevels; ++level) { for( unsigned int i=0; i < _resolution; ++i) { int posY = i/step * step; for( unsigned int j=0; j < _resolution; ++j) { if (i%step != 0 || j%step != 0) { int posX = j/step * step; float delta = biLinearInterp(posX, posX+step, posY, posY+step, j, i); delta -= getVertex(j, i).z(); delta = abs(delta); deltaMax = std::max(deltaMax, delta); } } } step *= 2; } } float OceanTile::biLinearInterp(int lx, int hx, int ly, int hy, int tx, int ty ) const { float s00 = getVertex(lx, ly).z(); float s01 = getVertex(hx, ly).z(); float s10 = getVertex(lx, hy).z(); float s11 = getVertex(hx, hy).z(); int dx = hx - lx; int dtx = tx - lx; float v0 = (s01 - s00)/dx*dtx + s00; float v1 = (s11 - s10)/dx*dtx + s10; float value = (v1 - v0)/(hy - ly)*(ty - ly) + v0; return value; } float OceanTile::biLinearInterp(float x, float y ) const { float dx = x/_spacing; float dy = y/_spacing; unsigned int ix = dx; unsigned int iy = dy; dx -= ix; dy -= iy; float s00 = getVertex(ix , iy ).z(); float s01 = getVertex(ix+1, iy ).z(); float s10 = getVertex(ix , iy+1).z(); float s11 = getVertex(ix+1, iy+1).z(); return s00*(1.f-dx)*(1.f-dy) + s01*dx*(1.f-dy) + s10*(1.f-dx)*dy + s11*dx*dy; } osg::Vec3f OceanTile::normalBiLinearInterp(float x, float y ) const { float dx = x / _spacing; float dy = y / _spacing; unsigned int ix = dx; unsigned int iy = dy; dx -= ix; dy -= iy; osg::Vec3f s00 = getNormal(ix,iy); osg::Vec3f s01 = getNormal(ix + 1,iy); osg::Vec3f s10 = getNormal(ix,iy + 1); osg::Vec3f s11 = getNormal(ix + 1,iy + 1); return s00*(1.f - dx)*(1.f-dy) + s01*dx*(1.f-dy) + s10*(1.f - dx)*dy + s11*dx*dy; } osg::ref_ptr<osg::Texture2D> OceanTile::createNormalMap( void ) { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; unsigned char* pixels = new unsigned char[_resolution*_resolution*3]; unsigned int idx = 0; unsigned int i = 0; for(unsigned int r = 0; r < _resolution; ++r ) { for(unsigned int c = 0; c < _resolution; ++c ) { idx = i*3; osg::Vec3f n = getNormal(c,r); pixels[idx] = (unsigned char)(127.f * n.x() + 128.f); pixels[idx+1] = (unsigned char)(127.f * n.y() + 128.f); pixels[idx+2] = (unsigned char)(127.f * n.z() + 128.f); i++; } } osg::Image* img = new osg::Image; img->setImage(_resolution, _resolution, 1, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, pixels, osg::Image::USE_NEW_DELETE, 1); #ifdef DEBUG_DATA // saves normal map as image static int count = 0; std::stringstream ss; ss << "Tile_" << count << ".bmp"; osgDB::writeImageFile( *img, ss.str() ); ++count; #endif texture->setFilter( osg::Texture::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR ); texture->setFilter( osg::Texture::MAG_FILTER, osg::Texture::LINEAR ); texture->setWrap ( osg::Texture::WRAP_S, osg::Texture::REPEAT ); texture->setWrap ( osg::Texture::WRAP_T, osg::Texture::REPEAT ); texture->setImage ( img ); return texture; }
[ [ [ 1, 377 ] ] ]
68fcc1bb8809f145be1580e8d7eb1582e75a5aaa
dadf8e6f3c1adef539a5ad409ce09726886182a7
/airplay/src/toeConfig.cpp
404171ce285aa5326107c1ee49ab6547dd494de0
[]
no_license
sarthakpandit/toe
63f59ea09f2c1454c1270d55b3b4534feedc7ae3
196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b
refs/heads/master
2021-01-10T04:04:45.575806
2011-06-09T12:56:05
2011-06-09T12:56:05
53,861,788
0
0
null
null
null
null
UTF-8
C++
false
false
3,409
cpp
#include "toeConfig.h" #include "pugixml.hpp" using namespace TinyOpenEngine; namespace TinyOpenEngine { const char* toeConfigFilePath = "ram://app.config"; pugi::xml_document* toeConfigDocument=0; pugi::xml_node toeGetConfigNodeText(const char* name) { pugi::xml_node configuration = toeConfigDocument->child("configuration"); if (!configuration) configuration = toeConfigDocument->append_child("configuration"); pugi::xml_node appSettings = configuration.child("appSettings"); if (!appSettings) appSettings = configuration.append_child("appSettings"); pugi::xml_node item = appSettings.child(name); if (!item) { item = appSettings.append_child(name); } pugi::xml_node text = item.first_child(); if (!text) text = item.append_child(pugi::node_pcdata); return text; } } //Get scriptable class declaration CtoeScriptableClassDeclaration* CtoeConfig::GetClassDescription() { static TtoeScriptableClassDeclaration<CtoeConfig> d ("CtoeConfig", ScriptTraits::Method("GetInteger", &CtoeConfig::GetInteger), ScriptTraits::Method("GetFloat", &CtoeConfig::GetFloat), ScriptTraits::Method("GetString", &CtoeConfig::GetString), ScriptTraits::Method("SetInteger", &CtoeConfig::SetInteger), ScriptTraits::Method("SetFloat", &CtoeConfig::SetFloat), ScriptTraits::Method("SetString", &CtoeConfig::SetString), 0); return &d; } void CtoeConfig::SetInteger(const char* name, int val) { pugi::xml_node text = toeGetConfigNodeText(name); char buf [32]; sprintf(buf,"%d",val); text.set_value(buf); } void CtoeConfig::SetFloat(const char* name, float val) { pugi::xml_node text = toeGetConfigNodeText(name); char buf [32]; sprintf(buf,"%g",val); text.set_value(buf); } void CtoeConfig::SetString(const char* name, const char* val) { pugi::xml_node text = toeGetConfigNodeText(name); if (!val) text.set_value(""); else text.set_value(val); } bool CtoeConfig::IsExist(const char* name) { pugi::xml_node text = toeGetConfigNodeText(name); const char* v = text.value(); if (!v || !*v) return false; return true; } int CtoeConfig::GetInteger(const char* name) { pugi::xml_node text = toeGetConfigNodeText(name); const char* v = text.value(); int r = 0; if (!v || !*v) return r; sscanf(v,"%d",&r); return r; } float CtoeConfig::GetFloat(const char* name) { pugi::xml_node text = toeGetConfigNodeText(name); const char* v = text.value(); float r = 0; if (!v || !*v) return r; sscanf(v,"%f",&r); return r; } const char* CtoeConfig::GetString(const char* name) { pugi::xml_node text = toeGetConfigNodeText(name); const char* v = text.value(); return v; } void CtoeConfig::Load() { if (!toeConfigDocument) toeConfigDocument = new pugi::xml_document(); if (s3eFileCheckExists(toeConfigFilePath)) { pugi::xml_parse_result r = toeConfigDocument->load_file(toeConfigFilePath); if (r.status == pugi::status_ok) return; IwAssertMsg(TOE, false, (r.description())); } toeConfigDocument->load("<?xml version=\"1.0\" encoding=\"utf-8\" ?><configuration><appSettings></appSettings></configuration>"); } void CtoeConfig::Save() { if (toeConfigDocument) toeConfigDocument->save_file(toeConfigFilePath); } void CtoeConfig::Close() { if (toeConfigDocument) { delete toeConfigDocument; toeConfigDocument = 0; } }
[ [ [ 1, 121 ] ] ]
920361592b80040671ea40da68e98781f64f5b13
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectWrite/DWriteFont.cpp
9a544e4ad3f7f7a3a19c95796ac1d69110d49a80
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
3,302
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" #include "DWriteFont.h" #include "DWriteFontFace.h" #include "DWriteFontFamily.h" IDictionary<CultureInfo^, System::String^>^ DWrite::Font::FaceNames::get() { if (m_faceNames == nullptr) { IDWriteLocalizedStrings* names = NULL; try { CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->GetFaceNames(&names)); if (names) m_faceNames = CommonUtils::GetCultureNameDictionary(names); } finally { if (names) names->Release(); } } return m_faceNames; } IDictionary<CultureInfo^, System::String^>^ DWrite::Font::GetInformationalStrings(InformationalStringId informationalStringID) { IDWriteLocalizedStrings* names = NULL; try { BOOL exists = FALSE; CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->GetInformationalStrings( static_cast<DWRITE_INFORMATIONAL_STRING_ID>(informationalStringID), &names, &exists)); if (exists && names) return CommonUtils::GetCultureNameDictionary(names); else return nullptr; } finally { if (names) names->Release(); } } DWrite::FontFamily^ DWrite::Font::FontFamily::get() { if (m_fontFamily == nullptr) { IDWriteFontFamily* fontFamily = NULL; CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->GetFontFamily(&fontFamily)); m_fontFamily = fontFamily ? gcnew DWrite::FontFamily(fontFamily) : nullptr; } return m_fontFamily; } FontWeight DWrite::Font::Weight::get() { return static_cast<FontWeight>(GetInterface<IDWriteFont>()->GetWeight()); } FontStretch DWrite::Font::Stretch::get() { return static_cast<FontStretch>(GetInterface<IDWriteFont>()->GetStretch()); } FontStyle DWrite::Font::Style::get() { return static_cast<FontStyle>(GetInterface<IDWriteFont>()->GetStyle()); } Boolean DWrite::Font::IsSymbolFont::get() { return GetInterface<IDWriteFont>()->IsSymbolFont() != 0; } FontSimulations DWrite::Font::Simulations::get() { return static_cast<FontSimulations>(GetInterface<IDWriteFont>()->GetSimulations()); } FontMetrics DWrite::Font::Metrics::get() { DWRITE_FONT_METRICS metricsCopy; GetInterface<IDWriteFont>()->GetMetrics(&metricsCopy); FontMetrics metrics; metrics.CopyFrom(metricsCopy); return metrics; } Boolean DWrite::Font::HasCharacter(UInt32 unicodeValue) { BOOL exists; CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->HasCharacter(unicodeValue, &exists)); return exists != 0; } Boolean DWrite::Font::HasCharacter(System::Char unicodeChar) { BOOL exists; CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->HasCharacter(Convert::ToUInt32(unicodeChar), &exists)); return exists != 0; } FontFace^ DWrite::Font::CreateFontFace() { IDWriteFontFace* fontFace = NULL; CommonUtils::VerifyResult(GetInterface<IDWriteFont>()->CreateFontFace(&fontFace)); return fontFace ? gcnew FontFace(fontFace) : nullptr; }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 131 ] ] ]
09afe1a1710875dd84184923e039700606a3b29e
3b2322c1adf5e6166259540e767ec67df0887c17
/physics1/src/Body.h
ff5a8dfa7bb402b11e9fc26ed6fb799f6aa7c961
[]
no_license
aruwen/various-stefan-ebner
750aac6e546ddb3e571ac468ecc26087843817d3
49eac46ed3a01131d711ea6feca77c32accb4733
refs/heads/master
2021-01-20T00:42:40.803881
2011-03-13T14:08:22
2011-03-13T14:08:22
32,136,593
0
0
null
null
null
null
UTF-8
C++
false
false
518
h
#ifndef BODY_H #define BODY_H #include "ofMain.h" // this abstract is used by all bodies participating in the physical simulation class Body { public: ofPoint mPosition; ofPoint mVelocity; float mMass; ofPoint mForce; Body(); // we have to declare a virtual destructor virtual ~Body(); // update the body with a simulation time step of dt virtual void update(float dt); // draw the body virtual void draw() = 0; // virtual void applyForce(ofPoint const &force); }; #endif
[ "nightwolve@bb536436-bb54-8cee-38f9-046b9e77f541" ]
[ [ [ 1, 27 ] ] ]
2a18dca6a3b5ba5bd11644c407d636beeecce90b
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/tabctrl.hpp
eb169c0bedd2854fb162fe5d07f576f691f5c396
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
1,357
hpp
#pragma once class TabControl: public CTabCtrl { public: TabControl(); virtual ~TabControl(); UINT GetLastMovementSource() const { return m_nSrcTab; } UINT GetLastMovementDestionation() const { return m_nDstTab; } BOOL ReorderTab(unsigned int nSrcTab, unsigned int nDstTab); void SetTabTextColor(int i, DWORD color); protected: bool m_bDragging; // Specifies that whether drag 'n drop is in progress. UINT m_nSrcTab; // Specifies the source tab that is going to be moved. UINT m_nDstTab; // Specifies the destination tab (drop position). bool m_bHotTracking; // Specifies the state of whether the tab control has hot tracking enabled. CRect m_InsertPosRect; CPoint m_lclickPoint; CSpinButtonCtrl * m_pSpinCtrl; virtual void DrawItem(LPDRAWITEMSTRUCT lpDIS); BOOL DragDetectPlus(CWnd* Handle, CPoint p); bool DrawIndicator(CPoint point); DECLARE_MESSAGE_MAP() afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnCaptureChanged(CWnd *); // ==> Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle #if _MSC_VER>=1600 afx_msg BOOL OnEraseBkgnd(CDC* pDC); #endif // <== Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle };
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 33 ], [ 39, 39 ] ], [ [ 34, 38 ] ] ]
11960f49b084468f314d45f34d16c6ebd5ca0c58
50e6ba037f1c60e5342c707a9d4223ac379a8047
/BlueTooth.cpp
73485b62d758c08329612b8c9006a61ac51d49d2
[]
no_license
buryhuang/blueplus
299bbe23efa93f9d3acceeedccd5e8194cb71891
7843ccfa4b8fc773c6de1992acb9c9bb805671ed
refs/heads/master
2021-05-06T15:59:40.471142
2011-05-31T06:50:46
2011-05-31T06:50:46
113,696,936
1
0
null
null
null
null
UTF-8
C++
false
false
27,987
cpp
/** \addtogroup bluetooth * @{ */ #include "BlueTooth.h" #include "Utils.h" #include <iostream> #include <algorithm> using namespace std; vector<int> CBlueTooth::BTServiceUuid16List; CBlueTooth* CBlueTooth::m_instance=NULL; CBlueTooth::CBlueTooth(void): m_bBluetoothStackPresent(false), m_bStarted(false), m_hDeviceLookup(NULL), m_bInitialBtIsDiscoverable(false), m_bRestoreBtMode(false), m_pHandler(NULL) { WSADATA data; if (WSAStartup(MAKEWORD(2, 2), &data) != 0) { WSAGetLastError(); m_bStarted = false; } else { m_bStarted = true; } if(CBlueTooth::BTServiceUuid16List.size()==0){ #if 0 CBlueTooth::BTServiceUuid16List.push_back(SyncMLClient_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(ServiceDiscoveryServerServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(BrowseGroupDescriptorServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(PublicBrowseGroupServiceClassID_UUID16 ); #endif CBlueTooth::BTServiceUuid16List.push_back(SerialPortServiceClassID_UUID16 ); #if 0 CBlueTooth::BTServiceUuid16List.push_back(LANAccessUsingPPPServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(DialupNetworkingServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(IrMCSyncServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(OBEXObjectPushServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(OBEXFileTransferServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(IrMcSyncCommandServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(HeadsetServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(CordlessServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(AudioSourceServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(AudioSinkServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(AV_RemoteControlTargetServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(AdvancedAudioDistributionServiceClassID_UUID16); CBlueTooth::BTServiceUuid16List.push_back(AV_RemoteControlServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(VideoConferencingServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(IntercomServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(FaxServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(HeadsetAudioGatewayServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(PANUServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(NAPServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(GNServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(HandsfreeServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(HandsfreeAudioGatewayServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(PnPInformationServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(GenericNetworkingServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(GenericFileTransferServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(GenericAudioServiceClassID_UUID16 ); CBlueTooth::BTServiceUuid16List.push_back(GenericTelephonyServiceClassID_UUID16 ); #endif reverse(CBlueTooth::BTServiceUuid16List.begin(),CBlueTooth::BTServiceUuid16List.end()); } } CBlueTooth::~CBlueTooth(void) { if (m_bStarted) { if (m_bRestoreBtMode) { BluetoothEnableDiscovery(NULL, m_bInitialBtIsDiscoverable); m_bRestoreBtMode = false; } WSACleanup(); } } bool CBlueTooth::GetLocalAddress(SOCKADDR_BTH& btAddr) { if(InitializationStatus()==false){ return false; } SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); //Utils::ShowError(TEXT("isBluetoothStackPresent")); if (s == INVALID_SOCKET) { int last_error = WSAGetLastError(); //debug(("socket error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("isBluetoothStackPresent")); return false; } memset(&btAddr, 0, sizeof(SOCKADDR_BTH)); btAddr.addressFamily = AF_BTH; btAddr.port = BT_PORT_ANY; if (bind(s, (SOCKADDR *)&btAddr, sizeof(SOCKADDR_BTH))) { int last_error = WSAGetLastError(); //debug(("bind error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("isBluetoothStackPresent")); closesocket(s); return false; } int size = sizeof(SOCKADDR_BTH); if (getsockname(s, (sockaddr*)&btAddr, &size)) { int last_error = WSAGetLastError(); // debug(("getsockname error [%d] %S", last_error, getWinErrorMessage(last_error))); closesocket(s); return false; } closesocket(s); return true; } bool CBlueTooth::IsBluetoothStackPresent() { SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); //Utils::ShowError(TEXT("isBluetoothStackPresent")); if (s == INVALID_SOCKET) { int last_error = WSAGetLastError(); //debug(("socket error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("isBluetoothStackPresent")); return false; } SOCKADDR_BTH btAddr; memset(&btAddr, 0, sizeof(SOCKADDR_BTH)); btAddr.addressFamily = AF_BTH; #ifdef _WIN32_WCE btAddr.port = 0; #else btAddr.port = BT_PORT_ANY; #endif if (bind(s, (SOCKADDR *)&btAddr, sizeof(SOCKADDR_BTH))) { int last_error = WSAGetLastError(); //debug(("bind error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("isBluetoothStackPresent")); closesocket(s); return false; } int size = sizeof(SOCKADDR_BTH); if (getsockname(s, (sockaddr*)&btAddr, &size)) { int last_error = WSAGetLastError(); // debug(("getsockname error [%d] %S", last_error, getWinErrorMessage(last_error))); closesocket(s); return false; } closesocket(s); //return true; m_bBluetoothStackPresent = (btAddr.btAddr != 0); return m_bBluetoothStackPresent; } bool CBlueTooth::InitializationStatus() { if (!m_bBluetoothStackPresent) { if (!IsBluetoothStackPresent()) { //throwBluetoothStateException(env, "BluetoothStack not detected"); Utils::ShowError(L"initializationStatus"); return false; } } if (m_bStarted) { if (BluetoothIsDiscoverable(NULL)) { m_bInitialBtIsDiscoverable = true; } return true; } return false; } bool CBlueTooth::GetBluetoothGetRadioInfo(BTH_ADDR address, BLUETOOTH_RADIO_INFO* info) { HANDLE hRadio; BLUETOOTH_FIND_RADIO_PARAMS btfrp = { sizeof(btfrp) }; HBLUETOOTH_RADIO_FIND hFind = BluetoothFindFirstRadio( &btfrp, &hRadio ); if ( NULL != hFind ) { do { BLUETOOTH_RADIO_INFO radioInfo; radioInfo.dwSize = sizeof(radioInfo); if (ERROR_SUCCESS == BluetoothGetRadioInfo(hRadio, &radioInfo)) { if (radioInfo.address.ullLong == address) { BluetoothFindRadioClose(hFind); memcpy(info, &radioInfo, sizeof(BLUETOOTH_RADIO_INFO)); return true; } } } while( BluetoothFindNextRadio( hFind, &hRadio ) ); BluetoothFindRadioClose( hFind ); } return false; } bool CBlueTooth::GetBluetoothDeviceInfo(BTH_ADDR address, BLUETOOTH_DEVICE_INFO* pbtdi, BOOL issueInquiry) { BLUETOOTH_DEVICE_SEARCH_PARAMS btsp; memset(&btsp, 0, sizeof(btsp)); btsp.dwSize = sizeof(btsp); btsp.fIssueInquiry = issueInquiry; btsp.fReturnAuthenticated = true; btsp.fReturnConnected = true; btsp.fReturnRemembered = true; btsp.fReturnUnknown = true; if (issueInquiry) { btsp.cTimeoutMultiplier = 10; } memset(pbtdi, 0, sizeof(BLUETOOTH_DEVICE_INFO)); pbtdi->dwSize = sizeof(BLUETOOTH_DEVICE_INFO); HBLUETOOTH_DEVICE_FIND hFind = BluetoothFindFirstDevice(&btsp, pbtdi); if (NULL != hFind) { do { if (pbtdi->Address.ullLong == address) { BluetoothFindDeviceClose(hFind); return true; } printf("found device %i", pbtdi->Address.ullLong); memset(pbtdi, 0, sizeof(BLUETOOTH_DEVICE_INFO)); pbtdi->dwSize = sizeof(BLUETOOTH_DEVICE_INFO); } while (BluetoothFindNextDevice(hFind, pbtdi)); BluetoothFindDeviceClose(hFind); } return false; } string CBlueTooth::GetRadioName(long address) { BLUETOOTH_RADIO_INFO radioInfo; if (GetBluetoothGetRadioInfo(address, &radioInfo)) { return string((char*)radioInfo.szName, (int) wcslen(radioInfo.szName)); } return NULL; } int CBlueTooth::GetDeviceVersion(long address) { BLUETOOTH_RADIO_INFO radioInfo; if (GetBluetoothGetRadioInfo(address, &radioInfo)) { return radioInfo.lmpSubversion; } return -1; } int CBlueTooth::GetDeviceManufacturer(long address) { BLUETOOTH_RADIO_INFO radioInfo; if (GetBluetoothGetRadioInfo(address, &radioInfo)) { return radioInfo.manufacturer; } return -1; } int CBlueTooth::RunDeviceInquiry(int duration) { // build device query BTH_QUERY_DEVICE query; query.LAP = 0;//accessCode; MSDN: Reserved. Must be set to zero. query.length = (unsigned char)duration; // build BLOB pointing to device query BLOB blob; blob.cbSize = sizeof(query); blob.pBlobData = (BYTE *)&query; // build query WSAQUERYSET queryset; memset(&queryset, 0, sizeof(WSAQUERYSET)); queryset.dwSize = sizeof(WSAQUERYSET); queryset.dwNameSpace = NS_BTH; // TODO Test this. //queryset.lpBlob = &blob; queryset.lpBlob = &blob; // begin query if (m_hDeviceLookup != NULL) { //throwBluetoothStateException(env, cINQUIRY_RUNNING); return INQUIRY_ERROR; } if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE|LUP_CONTAINERS, &m_hDeviceLookup)) { //int last_error = WSAGetLastError(); //throwBluetoothStateExceptionWinErrorMessage(env, "Can't start Lookup", last_error); // debug(("WSALookupServiceBegin error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("runDeviceInquiry")); return INQUIRY_ERROR; } // fetch results int result = -1; int bufSize = 0x2000; void* buf = malloc(bufSize); if (buf == NULL) { result = INQUIRY_ERROR; } while (result == -1) { memset(buf, 0, bufSize); LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf; pwsaResults->dwSize = sizeof(WSAQUERYSET); pwsaResults->dwNameSpace = NS_BTH; DWORD size = bufSize; if (m_hDeviceLookup == NULL) { result = INQUIRY_TERMINATED; //debug(("doInquiry, INQUIRY_TERMINATED")); break; } //debug(("doInquiry, WSALookupServiceNext")); if (WSALookupServiceNext(m_hDeviceLookup, LUP_RETURN_NAME|LUP_RETURN_ADDR|LUP_RETURN_BLOB, &size, pwsaResults)) { int last_error = WSAGetLastError(); switch(last_error) { case WSAENOMORE: case WSA_E_NO_MORE: result = INQUIRY_COMPLETED; break; default: // debug(("Device lookup error [%d] %S", last_error, getWinErrorMessage(last_error))); Utils::ShowError(TEXT("runDeviceInquiry")); result = INQUIRY_ERROR; } WSALookupServiceEnd(m_hDeviceLookup); m_hDeviceLookup = NULL; //debug(("doInquiry, exits")); break; } //debug(("doInquiry, has next Service")); BTH_DEVICE_INFO *p_inqRes = (BTH_DEVICE_INFO *)pwsaResults->lpBlob->pBlobData; // get device name WCHAR name[256]; bool bHaveName = pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName); _stprintf(name, sizeof(name),L"%s",bHaveName ? pwsaResults->lpszServiceInstanceName : L""); // debug(("ServiceInstanceName [%S]", name)); wstring deviceName((WCHAR *)name, (int)wcslen(name)); bool paired = false; int deviceClass = p_inqRes->classOfDevice; if (p_inqRes->flags & BDIF_PAIRED) { paired = true; } BTH_ADDR deviceAddr; deviceAddr = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr; // notify listener //debug(("doInquiry, notify listener")); if(m_pHandler != NULL){ m_pHandler->OnDeviceDiscovered(deviceAddr, deviceClass, deviceName, paired); } //debug(("doInquiry, listener returns")); } if (buf != NULL) { free(buf); } if (m_hDeviceLookup != NULL) { WSALookupServiceEnd(m_hDeviceLookup); m_hDeviceLookup = NULL; } return result; } // callback for BluetoothSdpEnumAttributes() BOOL __stdcall callback(ULONG uAttribId, LPBYTE pValueStream, ULONG cbStreamSize, LPVOID pvParam) { SDP_ELEMENT_DATA element; // Just a verification, uncomment to see the output!!! //printf("Callback() uAttribId: %ul\n", uAttribId); //printf("Callback() pValueStream: %d\n ", pValueStream); //printf("Callback() cbStreamSize: %ul\n ", cbStreamSize); if (BluetoothSdpGetElementData(pValueStream, cbStreamSize, &element) != ERROR_SUCCESS) { // Just a verification //printf("BluetoothSdpGetElementData() failed with error code %ld\n", WSAGetLastError()); return false; } else { // Just a verification //printf("BluetoothSdpGetElementData() is OK!\n"); return true; } } bool CBlueTooth::RunSearchServices(BTH_ADDR address, int duration) { vector<ServiceRecord> serviceList; SOCKET s; WSAPROTOCOL_INFO protocolInfo; int protocolInfoSize; WSAQUERYSET querySet, *pResults, querySet2; HANDLE hLookup, hLookup2; int result; bool returnResult = true; static int i; BYTE buffer[1000]; BYTE buffer1[2000]; DWORD bufferLength, flags, addressSize, bufferLength1; CSADDR_INFO *pCSAddr; BTH_DEVICE_INFO *pDeviceInfo; char addressAsString[2000]; BLOB *pBlob; GUID protocol; // Load the winsock2 library // if (WSAStartup(MAKEWORD(2,2), &m_data) != 0) { // return false; // } //printf("WSAStartup() should be fine!\n"); // Create a blutooth socket s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); if (s == INVALID_SOCKET) { wcout<<L"\tFailed to get bluetooth socket with error code "<<WSAGetLastError()<<endl; returnResult = false; goto search_error; } else{ //printf("socket() is OK!\n"); } protocolInfoSize = sizeof(protocolInfo); // Get the bluetooth device info using getsockopt() if (getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFO, (char*)&protocolInfo, &protocolInfoSize) != 0) { wcout<<L"\tgetsockopt(SO_PROTOCOL_INFO) failed with error code "<<WSAGetLastError()<<endl; returnResult = false; goto search_error; } else{ wcout<<L"\tgetsockopt(SO_PROTOCOL_INFO) is OK!"<<endl; } // Query set criteria BTH_QUERY_DEVICE query; query.LAP = 0;//accessCode; MSDN: Reserved. Must be set to zero. query.length = (unsigned char)duration; // build BLOB pointing to device query BLOB blob; blob.cbSize = sizeof(query); blob.pBlobData = (BYTE *)&query; // build query memset(&querySet, 0, sizeof(WSAQUERYSET)); querySet.dwSize = sizeof(WSAQUERYSET); querySet.dwNameSpace = NS_BTH; querySet.lpBlob = &blob; //memset(&querySet, 0, sizeof(querySet)); //querySet.dwSize = sizeof(querySet); //querySet.dwNameSpace = NS_BTH; // Set the flags for query flags = LUP_RETURN_NAME | LUP_CONTAINERS | LUP_RETURN_ADDR | LUP_FLUSHCACHE | LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RES_SERVICE; // Start a device in range query... result = WSALookupServiceBegin(&querySet, flags, &hLookup); // If OK if (result != 0) { wcout<<L"\tWSALookupServiceBegin() failed with error code "<<WSAGetLastError<<endl; returnResult = false; goto search_error; }// end WSALookupServiceBegin() wcout<<L"\tWSALookupServiceBegin() is OK!"<<endl;; while (result == 0) { bufferLength = sizeof(buffer); pResults = (WSAQUERYSET *)&buffer; // Next query... result = WSALookupServiceNext(hLookup, flags, &bufferLength, pResults); if (result != 0) { printf("\tWSALookupServiceNext() failed with error code %ld\n", WSAGetLastError()); returnResult = false; goto search_error; } // Get the device info, name, address etc //printf(" WSALookupServiceNext() is OK!\n"); //printf(" The service instance name is %S\n", pResults->lpszServiceInstanceName); pCSAddr = (CSADDR_INFO *)pResults->lpcsaBuffer; pDeviceInfo = (BTH_DEVICE_INFO *)pResults->lpBlob; memset(&querySet2, 0, sizeof(querySet2)); querySet2.dwSize = sizeof(querySet2); protocol = L2CAP_PROTOCOL_UUID; querySet2.lpServiceClassId = &protocol; querySet2.dwNameSpace = NS_BTH; addressSize = sizeof(addressAsString); // Print the local bluetooth device address... if (WSAAddressToString(pCSAddr->LocalAddr.lpSockaddr, pCSAddr->LocalAddr.iSockaddrLength, &protocolInfo, (LPWSTR)addressAsString, &addressSize) == 0) { //printf(" WSAAddressToString() for local address is fine!\n"); //printf(" The local address: %S\n", addressAsString); } else{ //printf(" WSAAddressToString() for local address failed with error code %ld\n", WSAGetLastError()); } addressSize = sizeof(addressAsString); // Print the remote bluetooth device address... if (WSAAddressToString(pCSAddr->RemoteAddr.lpSockaddr, pCSAddr->RemoteAddr.iSockaddrLength, &protocolInfo, (LPWSTR)addressAsString, &addressSize) == 0) { //printf(" WSAAddressToString() for remote address is fine!\n"); //printf(" The remote device address: %S\n", addressAsString); } else{ //printf(" WSAAddressToString() for remote address failed with error code %ld\n", WSAGetLastError()); } if(address ==((SOCKADDR_BTH *)(pCSAddr->RemoteAddr.lpSockaddr))->btAddr) { // Prepare for service query set querySet2.lpszContext = (LPWSTR)addressAsString; flags = LUP_FLUSHCACHE |LUP_RETURN_NAME | LUP_RETURN_TYPE | LUP_RETURN_ADDR | LUP_RETURN_BLOB | LUP_RETURN_COMMENT; // Start service query result = WSALookupServiceBegin(&querySet2, flags, &hLookup2); if (result != 0) { printf("WSALookupServiceBegin() failed with error code %ld\n", WSAGetLastError()); //Maybe expected...? continue; // don't do the rest //returnResult = false; //goto search_error; } //printf(" WSALookupServiceBegin() is OK!\n"); while (result == 0) { bufferLength1 = sizeof(buffer1); pResults = (WSAQUERYSET *)&buffer1; // Next service query result = WSALookupServiceNext(hLookup2, flags, &bufferLength1, pResults); if(result != 0) { printf(" WSALookupServiceNext() failed with error code %ld\n", WSAGetLastError()); printf(" Error code = 11011 ~ WSA_E_NO_MORE ~ No more device!\n"); //Don't goto service_error. This error is expected. break; } ServiceRecord sr; // Populate the service info //printf(" WSALookupServiceNext() is OK!\n"); //printf(" WSALookupServiceNext() - service instance name: %S\n", // pResults->lpszServiceInstanceName); //printf(" WSALookupServiceNext() - comment (if any): %s\n", pResults->lpszComment); //printf(" WSALookupServiceNext() - port (if any): %x\n", ((SOCKADDR_BTH *)pResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->port); pCSAddr = (CSADDR_INFO *)pResults->lpcsaBuffer; sr.serviceInstanceName=pResults->lpszServiceInstanceName; sr.comment=pResults->lpszComment; sr.sockaddrBth = *((SOCKADDR_BTH *)pResults->lpcsaBuffer->RemoteAddr.lpSockaddr); if(sr.serviceInstanceName.find(L"Serial")!=wstring::npos){ //TODO hard code for now serviceList.push_back(sr); } // Extract the sdp info if (pResults->lpBlob) { pBlob = (BLOB*)pResults->lpBlob; if (!BluetoothSdpEnumAttributes(pBlob->pBlobData, pBlob->cbSize, callback, 0)) { printf("BluetoothSdpEnumAttributes() failed with error code %ld\n", WSAGetLastError()); } else { //printf("BluetoothSdpEnumAttributes() #%d is OK!\n", i++); } } } // Close the handle to service query if(WSALookupServiceEnd(hLookup2) == 0){ //printf("WSALookupServiceEnd(hLookup2) is fine!\n", WSAGetLastError()); }else{ printf("WSALookupServiceEnd(hLookup2) failed with error code %ld\n", WSAGetLastError()); //returnResult = false; //goto search_error; // Maybe still expected..? } } } // Close handle to the device query if(WSALookupServiceEnd(hLookup) == 0){ //printf("WSALookupServiceEnd(hLookup) is fine!\n", WSAGetLastError()); }else{ printf("WSALookupServiceEnd(hLookup) failed with error code %ld\n", WSAGetLastError()); goto search_error; } search_error: // Cleanup the winsock library startup //if(WSACleanup() == 0){ // printf("WSACleanup() pretty fine!\n"); //}else{ // printf("WSACleanup() failed with error code %ld\n", WSAGetLastError()); //} if(serviceList.size() == 0) { //No service found. returnResult = false; } else if (m_pHandler!=NULL){ returnResult = true; m_pHandler->OnServiceDiscovered(address, serviceList); } return returnResult; } #if 0 vector<int> CBlueTooth::RunSearchServices(vector<SdpQueryUuid> uuidSet, BTH_ADDR address) { //debug(("runSearchServices")); vector<int> result; vector<int> finalResult; vector<SdpQueryUuid> uuidSetFull=uuidSet; // check if we can handle the number of UUIDs supplied while (uuidSetFull.size() > 0) { int maxSize = uuidSetFull.size(); uuidSet.clear(); result.clear(); if(maxSize > MAX_UUIDS_IN_QUERY){ maxSize = MAX_UUIDS_IN_QUERY; } for(int i=0;i<maxSize;i++){ uuidSet.push_back(uuidSetFull.back()); uuidSetFull.pop_back(); } // generate a Bluetooth address string (WSAAddressToString doesn't work on WinCE) SOCKADDR_BTH addr; memset(&addr, 0, sizeof(SOCKADDR_BTH)); addr.addressFamily = AF_BTH; addr.btAddr = address; //addr.port = channel; WCHAR addressString[20]; swprintf_s(addressString, L"(%02x:%02x:%02x:%02x:%02x:%02x)", (int)(address>>40&0xff), (int)(address>>32&0xff), (int)(address>>24&0xff), (int)(address>>16&0xff), (int)(address>>8&0xff), (int)(address&0xff)); // build service query BTH_QUERY_SERVICE queryservice; memset(&queryservice, 0, sizeof(queryservice)); queryservice.type = SDP_SERVICE_SEARCH_REQUEST; for(int i = 0; i<uuidSet.size(); i++) { //UUID is full 128 bits queryservice.uuids[i].uuidType = SDP_ST_UUID16; queryservice.uuids[i].u.uuid16 = uuidSet[i].u.uuid16; } // build BLOB pointing to service query BLOB blob; blob.cbSize = sizeof(queryservice); blob.pBlobData = (BYTE *)&queryservice; // build query WSAQUERYSET queryset; memset(&queryset, 0, sizeof(WSAQUERYSET)); queryset.dwSize = sizeof(WSAQUERYSET); queryset.dwNameSpace = NS_BTH; queryset.lpBlob = &blob; queryset.lpszContext = addressString; HANDLE hLookupSearchServices; // begin query if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE, &hLookupSearchServices)) { Utils::ShowError(L"RunSearchServices"); //return result; continue; } // fetch results int bufSize = 0x2000; void* buf = malloc(bufSize); if (buf == NULL) { WSALookupServiceEnd(hLookupSearchServices); continue; //return result; } memset(buf, 0, bufSize); LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf; pwsaResults->dwSize = sizeof(WSAQUERYSET); pwsaResults->dwNameSpace = NS_BTH; pwsaResults->lpBlob = NULL; DWORD size = bufSize; if (WSALookupServiceNext(hLookupSearchServices, LUP_RETURN_BLOB, &size, pwsaResults)) { int last_error = WSAGetLastError(); switch(last_error) { case WSANO_DATA: result.clear(); break; default: //debug(("WSALookupServiceNext error [%i] %S", last_error, getWinErrorMessage(last_error))); result.clear(); } } else { // construct int array to hold handles result.resize(pwsaResults->lpBlob->cbSize/sizeof(ULONG)); memcpy(&result[0], pwsaResults->lpBlob->pBlobData, pwsaResults->lpBlob->cbSize); } WSALookupServiceEnd(hLookupSearchServices); free(buf); //merge to final result before next batch for(vector<int>::iterator vi=result.begin();vi!=result.end();vi++){ finalResult.push_back(*vi); } } return finalResult; } #endif vector<char> CBlueTooth::GetServiceAttributes(vector<int> attrIDs, BTH_ADDR address, int handle) { //debug(("getServiceAttributes")); vector<char> result; // generate a Bluetooth address string (WSAAddressToString doesn't work on WinCE) WCHAR addressString[20]; swprintf_s(addressString, L"(%02x:%02x:%02x:%02x:%02x:%02x)", (int)(address>>40&0xff), (int)(address>>32&0xff), (int)(address>>24&0xff), (int)(address>>16&0xff), (int)(address>>8&0xff), (int)(address&0xff)); // build attribute query BTH_QUERY_SERVICE *queryservice = (BTH_QUERY_SERVICE *)malloc(sizeof(BTH_QUERY_SERVICE)+sizeof(SdpAttributeRange)*(attrIDs.size()-1)); memset(queryservice, 0, sizeof(BTH_QUERY_SERVICE)-sizeof(SdpAttributeRange)); queryservice->type = SDP_SERVICE_ATTRIBUTE_REQUEST; queryservice->serviceHandle = handle; queryservice->numRange = (ULONG)attrIDs.size(); // set attribute ranges for(unsigned int i = 0; i < attrIDs.size(); i++) { queryservice->pRange[i].minAttribute = (USHORT)attrIDs[i]; queryservice->pRange[i].maxAttribute = (USHORT)attrIDs[i]; } // build BLOB pointing to attribute query BLOB blob; blob.cbSize = sizeof(BTH_QUERY_SERVICE); blob.pBlobData = (BYTE *)queryservice; // build query WSAQUERYSET queryset; memset(&queryset, 0, sizeof(WSAQUERYSET)); queryset.dwSize = sizeof(WSAQUERYSET); queryset.dwNameSpace = NS_BTH; queryset.lpszContext = addressString; queryset.lpBlob = &blob; HANDLE hLookupServiceAttributes; // begin query if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE, &hLookupServiceAttributes)) { free(queryservice); //throwIOExceptionWSAGetLastError(env, "Failed to begin attribute query"); Utils::ShowError(L"GetServiceAttributes"); return result; } free(queryservice); // fetch results int bufSize = 0x2000; void* buf = malloc(bufSize); if (buf == NULL) { WSALookupServiceEnd(hLookupServiceAttributes); return result; } memset(buf, 0, bufSize); LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf; pwsaResults->dwSize = sizeof(WSAQUERYSET); pwsaResults->dwNameSpace = NS_BTH; pwsaResults->lpBlob = NULL; DWORD size = bufSize; if (WSALookupServiceNext(hLookupServiceAttributes, LUP_RETURN_BLOB, &size, pwsaResults)) { //throwIOExceptionWSAGetLastError(env, "Failed to perform attribute query"); Utils::ShowError(L"GetServiceAttributes"); result.clear(); } else { // construct byte array to hold blob result.resize(pwsaResults->lpBlob->cbSize); memcpy(&result[0], pwsaResults->lpBlob->pBlobData, pwsaResults->lpBlob->cbSize); } WSALookupServiceEnd(hLookupServiceAttributes); free(buf); return result; } bool CBlueTooth::RegisterHandler(CBTHandler* pHandler) { if(pHandler!=NULL){ m_pHandler = pHandler; return true; } return false; } #ifdef UNITTEST #include "unittest_config.h" #include "gtest/gtest.h" CBlueTooth cbt; SOCKADDR_BTH localBtAddr; TEST(BlueToothTest,Init) { ASSERT_TRUE(cbt.InitializationStatus()); ASSERT_TRUE(cbt.GetLocalAddress(localBtAddr)); wcout<<L"Local BT address is "<<hex<<localBtAddr.btAddr<<endl; } #endif /** @}*/
[ [ [ 1, 901 ] ] ]
42aeade8a068795448844f78b14518ad78cf683b
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/MobiHealth/ui_AnagraficaForm.h
875f096dd6348b1af5f65d13db3264e5c7e1653b
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,483
h
/******************************************************************************** ** Form generated from reading UI file 'AnagraficaForm.ui' ** ** Created: Sun Apr 11 11:47:58 2010 ** by: Qt User Interface Compiler version 4.6.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ANAGRAFICAFORM_H #define UI_ANAGRAFICAFORM_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_AnagraficaFormClass { public: void setupUi(QWidget *AnagraficaFormClass) { if (AnagraficaFormClass->objectName().isEmpty()) AnagraficaFormClass->setObjectName(QString::fromUtf8("AnagraficaFormClass")); AnagraficaFormClass->resize(400, 300); retranslateUi(AnagraficaFormClass); QMetaObject::connectSlotsByName(AnagraficaFormClass); } // setupUi void retranslateUi(QWidget *AnagraficaFormClass) { AnagraficaFormClass->setWindowTitle(QApplication::translate("AnagraficaFormClass", "AnagraficaForm", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class AnagraficaFormClass: public Ui_AnagraficaFormClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ANAGRAFICAFORM_H
[ [ [ 1, 50 ] ] ]
479f08f5129cf0f35a25ac506b8840fbc18805a9
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/Sources/Tutorials/Simple Chat/ServerTest/ServerTest/ServerTest.cpp
113d65bc8322755ab7061c7e90bc70ead03c5362
[]
no_license
asdlei00/project-jb
1cc70130020a5904e0e6a46ace8944a431a358f6
0bfaa84ddab946c90245f539c1e7c2e75f65a5c0
refs/heads/master
2020-05-07T21:41:16.420207
2009-09-12T03:40:17
2009-09-12T03:40:17
40,292,178
0
0
null
null
null
null
UHC
C++
false
false
2,269
cpp
// ServerTest.cpp : 응용 프로그램에 대한 클래스 동작을 정의합니다. // #include "stdafx.h" #include "ServerTest.h" #include "ServerTestDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CServerTestApp BEGIN_MESSAGE_MAP(CServerTestApp, CWinApp) ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() // CServerTestApp 생성 CServerTestApp::CServerTestApp() { // TODO: 여기에 생성 코드를 추가합니다. // InitInstance에 모든 중요한 초기화 작업을 배치합니다. } // 유일한 CServerTestApp 개체입니다. CServerTestApp theApp; // CServerTestApp 초기화 BOOL CServerTestApp::InitInstance() { // 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을 // 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControls()가 필요합니다. // InitCommonControls()를 사용하지 않으면 창을 만들 수 없습니다. InitCommonControls(); CWinApp::InitInstance(); if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // 표준 초기화 // 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면 // 아래에서 필요 없는 특정 초기화 루틴을 제거해야 합니다. // 해당 설정이 저장된 레지스트리 키를 변경하십시오. // TODO: 이 문자열을 회사 또는 조직의 이름과 같은 // 적절한 내용으로 수정해야 합니다. SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성한 응용 프로그램")); CServerTestDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 여기에 대화 상자가 확인을 눌러 없어지는 경우 처리할 // 코드를 배치합니다. } else if (nResponse == IDCANCEL) { // TODO: 여기에 대화 상자가 취소를 눌러 없어지는 경우 처리할 // 코드를 배치합니다. } // 대화 상자가 닫혔으므로 응용 프로그램의 메시지 펌프를 시작하지 않고 // 응용 프로그램을 끝낼 수 있도록 FALSE를 반환합니다. return FALSE; }
[ [ [ 1, 78 ] ] ]
eafce4d691b93893de6c04babdc4c4c115786741
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestgrids/inc/bctestgridsdocument.h
5e26e0fa55e7afcc5ac8a0fcfd56fd30e30f6fd8
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef C_BCTESTGRIDSDOCUMENT_H #define C_BCTESTGRIDSDOCUMENT_H // INCLUDES #include <eikdoc.h> // CONSTANTS // FORWARD DECLARATIONS class CEikAppUi; // CLASS DECLARATION /** * CBCTestGridsDocument application class. */ class CBCTestGridsDocument : public CEikDocument { public: // Constructors and destructor /** * Symbian OS two-phased constructor. * @return Pointer to created Document class object. * @param aApp Reference to Application class object. */ static CBCTestGridsDocument* NewL( CEikApplication& aApp ); /** * Destructor. */ virtual ~CBCTestGridsDocument(); private: // Constructors /** * Overload constructor. * @param aApp Reference to Application class object. */ CBCTestGridsDocument( CEikApplication& aApp ); private: // From CEikDocument /** * From CEikDocument, CreateAppUiL. * Creates CBCTestGridsAppUi "App UI" object. * @return Pointer to created AppUi class object. */ CEikAppUi* CreateAppUiL(); }; #endif // C_BCTESTGRIDSDOCUMENT_H
[ "none@none" ]
[ [ [ 1, 71 ] ] ]
2d0bae1269866d76abc1ebffaa2120702d07886d
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CHotkeyHandler.h
c2b89db17714d91940adb46c4adf1b20d13e9cab
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
2,713
h
#ifndef __HOTKEYHANDLER__INC_ #define __HOTKEYHANDLER__INC_ /* ----------------------------------------------------------------------------- Check implementation file for copyright information and for this library usage info. ----------------------------------------------------------------------------- */ #include "window.h" #include <vector> using std::vector; class CHotkeyHandler { private: // on hotkey occurence callback typedef void (*tHotkeyCB)(void *); // hotkey definition typedef struct { WORD mod; WORD virt; tHotkeyCB callback; ATOM id; bool deleted; } tHotkeyDef; // hotkeys definition list typedef vector<tHotkeyDef> tHotkeyList; // hotkey list tHotkeyList m_listHk; // window call back static LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM); // our hotkey processing window HWND m_hWnd; // register window class and creates the window int MakeWindow(bool bUnmake = false); // static DWORD WINAPI MessageLoop(LPVOID Param); // int EnableHotkey(const int); int DisableHotkey(const int); // Finds the unique ID (ATOM) of an already enabled hotkey int FindHandlerById(const ATOM id, tHotkeyDef *&); // Finds the index of an already inserted Hotkey def by Mod&Virt int FindHandler(WORD mod, WORD virt, int &index); // Finds for a deleted entry int FindDeletedHandler(int &idx); // handle of the message loop thread HANDLE m_hMessageLoopThread; // Error code that I poll from inside the MessageLoop() int m_PollingError; HANDLE m_hPollingError; // Parameter passed to the callback of every hotkey LPVOID m_lpCallbackParam; // Race condition prevention mutex HANDLE m_hRaceProtection; bool BeginRaceProtection(); void EndRaceProtection(); bool m_bStarted; public: bool bDebug; CHotkeyHandler(bool Debug = false); ~CHotkeyHandler(); int Start(LPVOID = NULL); int Stop(); // Inserts a hotkey definition int InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &index); // Removes a hotkey definition int RemoveHandler(const int index); static WORD HotkeyModifiersToFlags(WORD modf); static WORD HotkeyFlagsToModifiers(WORD hkf); //HotKeyHandlerErrorsXXXX enum {hkheOk = 0, // success hkheClassError, // window class registration error hkheWindowError, // window creation error hkheNoEntry, // No handler found at given index hkheRegHotkeyError, // could not register hotkey hkheMessageLoop, // could not create message loop thread hkheInternal // Internal error }; }; #endif
[ [ [ 1, 105 ] ] ]
4a9ebe2cb2354fb4810b2f220cce4533f21c834d
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/ScriptBind_GameRules.cpp
6f48439d760a73578355087ad331c0ea0920b907
[]
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
70,687
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ ------------------------------------------------------------------------- History: - 27:10:2004 11:29 : Created by Márcio Martins *************************************************************************/ #include "StdAfx.h" #include "ScriptBind_GameRules.h" #include "GameRules.h" #include "Actor.h" #include "Game.h" #include "GameCVars.h" #include "MPTutorial.h" //------------------------------------------------------------------------ CScriptBind_GameRules::CScriptBind_GameRules(ISystem *pSystem, IGameFramework *pGameFramework) : m_pSystem(pSystem), m_pSS(pSystem->GetIScriptSystem()), m_pGameFW(pGameFramework) { Init(m_pSS, m_pSystem, 1); m_players.Create(m_pSS); m_teamplayers.Create(m_pSS); m_spawnlocations.Create(m_pSS); m_spawngroups.Create(m_pSS); m_spectatorlocations.Create(m_pSS); RegisterMethods(); RegisterGlobals(); } //------------------------------------------------------------------------ CScriptBind_GameRules::~CScriptBind_GameRules() { } //------------------------------------------------------------------------ void CScriptBind_GameRules::RegisterGlobals() { m_pSS->SetGlobalValue("TextMessageCenter", eTextMessageCenter); m_pSS->SetGlobalValue("TextMessageConsole", eTextMessageConsole); m_pSS->SetGlobalValue("TextMessageError", eTextMessageError); m_pSS->SetGlobalValue("TextMessageInfo", eTextMessageInfo); m_pSS->SetGlobalValue("TextMessageServer", eTextMessageServer); m_pSS->SetGlobalValue("ChatToTarget", eChatToTarget); m_pSS->SetGlobalValue("ChatToTeam", eChatToTeam); m_pSS->SetGlobalValue("ChatToAll", eChatToAll); m_pSS->SetGlobalValue("TextMessageToAll", eRMI_ToAllClients); m_pSS->SetGlobalValue("TextMessageToAllRemote", eRMI_ToRemoteClients); m_pSS->SetGlobalValue("TextMessageToClient", eRMI_ToClientChannel); m_pSS->SetGlobalValue("eTE_TurretUnderAttack", eTE_TurretUnderAttack); m_pSS->SetGlobalValue("eTE_GameOverWin", eTE_GameOverWin); m_pSS->SetGlobalValue("eTE_GameOverLose", eTE_GameOverLose); m_pSS->SetGlobalValue("eTE_TACTankStarted", eTE_TACTankStarted); m_pSS->SetGlobalValue("eTE_SingularityStarted", eTE_SingularityStarted); m_pSS->SetGlobalValue("eTE_TACTankCompleted", eTE_TACTankCompleted); m_pSS->SetGlobalValue("eTE_TACLauncherCompleted", eTE_TACLauncherCompleted); m_pSS->SetGlobalValue("eTE_SingularityCompleted", eTE_SingularityCompleted); m_pSS->SetGlobalValue("eTE_EnemyNearBase", eTE_EnemyNearBase); m_pSS->SetGlobalValue("eTE_Promotion", eTE_Promotion); m_pSS->SetGlobalValue("eTE_Reactor50", eTE_Reactor50); m_pSS->SetGlobalValue("eTE_Reactor100", eTE_Reactor100); m_pSS->SetGlobalValue("eTE_ApproachEnemyHq", eTE_ApproachEnemyHq); m_pSS->SetGlobalValue("eTE_ApproachEnemySub", eTE_ApproachEnemySub); m_pSS->SetGlobalValue("eTE_ApproachEnemyCarrier", eTE_ApproachEnemyCarrier); } //------------------------------------------------------------------------ void CScriptBind_GameRules::RegisterMethods() { #undef SCRIPT_REG_CLASSNAME #define SCRIPT_REG_CLASSNAME &CScriptBind_GameRules:: SCRIPT_REG_TEMPLFUNC(IsServer, ""); SCRIPT_REG_TEMPLFUNC(IsClient, ""); SCRIPT_REG_TEMPLFUNC(CanCheat, ""); SCRIPT_REG_TEMPLFUNC(SpawnPlayer, "channelId, name, className, pos, angles"); SCRIPT_REG_TEMPLFUNC(ChangePlayerClass, "channelId, className, pos, angles"); SCRIPT_REG_TEMPLFUNC(RevivePlayer, "playerId, pos, angles, teamId, clearInventory"); SCRIPT_REG_TEMPLFUNC(RevivePlayerInVehicle, "playerId, vehicleId, seatId, teamId, clearInventory"); SCRIPT_REG_TEMPLFUNC(RenamePlayer, "playerId, name"); SCRIPT_REG_TEMPLFUNC(KillPlayer, "playerId, dropItem, ragdoll, shooterId, weaponId, damage, material, headshot, melee, impulse"); SCRIPT_REG_TEMPLFUNC(MovePlayer, "playerId, pos, angles"); SCRIPT_REG_TEMPLFUNC(GetPlayerByChannelId, "channelId"); SCRIPT_REG_TEMPLFUNC(GetChannelId, "playerId"); SCRIPT_REG_TEMPLFUNC(GetPlayerCount, ""); SCRIPT_REG_TEMPLFUNC(GetSpectatorCount, ""); SCRIPT_REG_TEMPLFUNC(GetPlayers, ""); SCRIPT_REG_TEMPLFUNC(IsPlayerInGame, "playerId"); SCRIPT_REG_TEMPLFUNC(IsProjectile, "entityId"); SCRIPT_REG_TEMPLFUNC(IsSameTeam, "entityId0, entityId1"); SCRIPT_REG_TEMPLFUNC(IsNeutral, "entityId"); SCRIPT_REG_TEMPLFUNC(AddSpawnLocation, "entityId"); SCRIPT_REG_TEMPLFUNC(RemoveSpawnLocation, "id"); SCRIPT_REG_TEMPLFUNC(GetSpawnLocationCount, ""); SCRIPT_REG_TEMPLFUNC(GetSpawnLocationByIdx, "idx"); SCRIPT_REG_TEMPLFUNC(GetSpawnLocations, ""); SCRIPT_REG_TEMPLFUNC(GetSpawnLocation, "playerId, teamId, ignoreTeam, includeNeutral"); SCRIPT_REG_TEMPLFUNC(GetFirstSpawnLocation, "teamId"); SCRIPT_REG_TEMPLFUNC(AddSpawnGroup, "groupId"); SCRIPT_REG_TEMPLFUNC(AddSpawnLocationToSpawnGroup, "groupId, location"); SCRIPT_REG_TEMPLFUNC(RemoveSpawnLocationFromSpawnGroup, "groupId, location"); SCRIPT_REG_TEMPLFUNC(RemoveSpawnGroup, "groupId"); SCRIPT_REG_TEMPLFUNC(GetSpawnLocationGroup, "spawnId"); SCRIPT_REG_TEMPLFUNC(GetSpawnGroups, ""); SCRIPT_REG_TEMPLFUNC(IsSpawnGroup, "entityId"); SCRIPT_REG_TEMPLFUNC(GetTeamDefaultSpawnGroup, "teamId"); SCRIPT_REG_TEMPLFUNC(SetTeamDefaultSpawnGroup, "teamId, groupId"); SCRIPT_REG_TEMPLFUNC(SetPlayerSpawnGroup, "playerId, groupId"); SCRIPT_REG_TEMPLFUNC(AddSpectatorLocation, "location"); SCRIPT_REG_TEMPLFUNC(RemoveSpectatorLocation, "id"); SCRIPT_REG_TEMPLFUNC(GetSpectatorLocationCount, ""); SCRIPT_REG_TEMPLFUNC(GetSpectatorLocation, "idx"); SCRIPT_REG_TEMPLFUNC(GetSpectatorLocations, ""); SCRIPT_REG_TEMPLFUNC(GetRandomSpectatorLocation, ""); SCRIPT_REG_TEMPLFUNC(GetInterestingSpectatorLocation, ""); SCRIPT_REG_TEMPLFUNC(GetNextSpectatorTarget, "playerId, change"); SCRIPT_REG_TEMPLFUNC(ChangeSpectatorMode, "playerId, mode, targetId"); SCRIPT_REG_TEMPLFUNC(CanChangeSpectatorMode, "playerId"); SCRIPT_REG_TEMPLFUNC(AddMinimapEntity, "entityId, type, lifetime"); SCRIPT_REG_TEMPLFUNC(RemoveMinimapEntity, "entityId"); SCRIPT_REG_TEMPLFUNC(ResetMinimap, ""); SCRIPT_REG_TEMPLFUNC(GetPing, "channelId"); SCRIPT_REG_TEMPLFUNC(ResetEntities, ""); SCRIPT_REG_TEMPLFUNC(ServerExplosion, "shooterId, weaponId, dmg, pos, dir, radius, angle, press, holesize, [effect], [effectScale]"); SCRIPT_REG_TEMPLFUNC(ServerHit, "targetId, shooterId, weaponId, dmg, radius, materialId, partId, typeId, [pos], [dir], [normal]"); SCRIPT_REG_TEMPLFUNC(CreateTeam, "name"); SCRIPT_REG_TEMPLFUNC(RemoveTeam, "teamId"); SCRIPT_REG_TEMPLFUNC(GetTeamName, "teamId"); SCRIPT_REG_TEMPLFUNC(GetTeamId, "teamName"); SCRIPT_REG_TEMPLFUNC(GetTeamCount, ""); SCRIPT_REG_TEMPLFUNC(GetTeamPlayerCount, "teamId"); SCRIPT_REG_TEMPLFUNC(GetTeamChannelCount, "teamId"); SCRIPT_REG_TEMPLFUNC(GetTeamPlayers, "teamId"); SCRIPT_REG_TEMPLFUNC(SetTeam, "teamId, playerId"); SCRIPT_REG_TEMPLFUNC(GetTeam, "playerId"); SCRIPT_REG_TEMPLFUNC(GetChannelTeam, "channelId"); SCRIPT_REG_TEMPLFUNC(AddObjective, "teamId, objective, status, entityId"); SCRIPT_REG_TEMPLFUNC(SetObjectiveStatus, "teamId, objective, status"); SCRIPT_REG_TEMPLFUNC(SetObjectiveEntity, "teamId, objective, entityId"); SCRIPT_REG_TEMPLFUNC(RemoveObjective, "teamId, objective"); SCRIPT_REG_TEMPLFUNC(ResetObjectives, ""); SCRIPT_REG_TEMPLFUNC(TextMessage, "type, msg"); SCRIPT_REG_TEMPLFUNC(SendTextMessage, "type, msg"); SCRIPT_REG_TEMPLFUNC(SendChatMessage, "type, sourceId, targetId, msg"); SCRIPT_REG_TEMPLFUNC(ForbiddenAreaWarning, "active, timer, targetId"); SCRIPT_REG_TEMPLFUNC(ResetGameTime, ""); SCRIPT_REG_TEMPLFUNC(GetRemainingGameTime, ""); SCRIPT_REG_TEMPLFUNC(IsTimeLimited, ""); SCRIPT_REG_TEMPLFUNC(ResetRoundTime, ""); SCRIPT_REG_TEMPLFUNC(GetRemainingRoundTime, ""); SCRIPT_REG_TEMPLFUNC(IsRoundTimeLimited, ""); SCRIPT_REG_TEMPLFUNC(ResetPreRoundTime, ""); SCRIPT_REG_TEMPLFUNC(GetRemainingPreRoundTime, ""); SCRIPT_REG_TEMPLFUNC(ResetReviveCycleTime, ""); SCRIPT_REG_TEMPLFUNC(GetRemainingReviveCycleTime, ""); SCRIPT_REG_TEMPLFUNC(ResetGameStartTimer, "time"); SCRIPT_REG_TEMPLFUNC(GetRemainingStartTimer, ""); SCRIPT_REG_TEMPLFUNC(EndGame, ""); SCRIPT_REG_TEMPLFUNC(NextLevel, ""); SCRIPT_REG_TEMPLFUNC(RegisterHitMaterial, "materialName"); SCRIPT_REG_TEMPLFUNC(GetHitMaterialId, "materialName"); SCRIPT_REG_TEMPLFUNC(GetHitMaterialName, "materialId"); SCRIPT_REG_TEMPLFUNC(ResetHitMaterials, ""); SCRIPT_REG_TEMPLFUNC(RegisterHitType, "type"); SCRIPT_REG_TEMPLFUNC(GetHitTypeId, "type"); SCRIPT_REG_TEMPLFUNC(GetHitType, "id"); SCRIPT_REG_TEMPLFUNC(ResetHitTypes, ""); SCRIPT_REG_TEMPLFUNC(ForceScoreboard, "force"); SCRIPT_REG_TEMPLFUNC(FreezeInput, "freeze"); SCRIPT_REG_TEMPLFUNC(ScheduleEntityRespawn, "entityId, unique, timer"); SCRIPT_REG_TEMPLFUNC(AbortEntityRespawn, "entityId, destroyData"); SCRIPT_REG_TEMPLFUNC(ScheduleEntityRemoval, "entityId, timer, visibility"); SCRIPT_REG_TEMPLFUNC(AbortEntityRemoval, "entityId"); SCRIPT_REG_TEMPLFUNC(SetSynchedGlobalValue, "key, value"); SCRIPT_REG_TEMPLFUNC(GetSynchedGlobalValue, "key"); SCRIPT_REG_TEMPLFUNC(SetSynchedEntityValue, "entityId, key, value"); SCRIPT_REG_TEMPLFUNC(GetSynchedEntityValue, "entityId, key"); SCRIPT_REG_TEMPLFUNC(ResetSynchedStorage, ""); SCRIPT_REG_TEMPLFUNC(ForceSynchedStorageSynch, "channelId"); SCRIPT_REG_TEMPLFUNC(IsDemoMode, ""); SCRIPT_REG_TEMPLFUNC(GetTimeLimit, ""); SCRIPT_REG_TEMPLFUNC(GetPreRoundTime, ""); SCRIPT_REG_TEMPLFUNC(GetRoundTime, ""); SCRIPT_REG_TEMPLFUNC(GetRoundLimit, ""); SCRIPT_REG_TEMPLFUNC(GetFragLimit, ""); SCRIPT_REG_TEMPLFUNC(GetFragLead, ""); SCRIPT_REG_TEMPLFUNC(GetFriendlyFireRatio, ""); SCRIPT_REG_TEMPLFUNC(GetReviveTime, ""); SCRIPT_REG_TEMPLFUNC(GetMinPlayerLimit, ""); SCRIPT_REG_TEMPLFUNC(GetMinTeamLimit, ""); SCRIPT_REG_TEMPLFUNC(GetTeamLock, ""); SCRIPT_REG_TEMPLFUNC(IsFrozen, "entityId"); SCRIPT_REG_TEMPLFUNC(FreezeEntity, "entityId, freeze, vapor"); SCRIPT_REG_TEMPLFUNC(ShatterEntity, "entityId, pos, impulse"); SCRIPT_REG_TEMPLFUNC(DebugCollisionDamage, ""); SCRIPT_REG_TEMPLFUNC(DebugHits, ""); SCRIPT_REG_TEMPLFUNC(SendHitIndicator, "shooterId"); SCRIPT_REG_TEMPLFUNC(SendDamageIndicator, "shooterId"); SCRIPT_REG_TEMPLFUNC(IsInvulnerable, "playerId"); SCRIPT_REG_TEMPLFUNC(SetInvulnerability, "playerId, invulnerable"); SCRIPT_REG_TEMPLFUNC(TutorialEvent, "type"); SCRIPT_REG_TEMPLFUNC(GameOver, "localWinner"); SCRIPT_REG_TEMPLFUNC(EnteredGame, ""); SCRIPT_REG_TEMPLFUNC(EndGameNear, "entityId"); SCRIPT_REG_TEMPLFUNC(SPNotifyPlayerKill, "targetId, weaponId, headShot"); SCRIPT_REG_TEMPLFUNC(ProcessEMPEffect, "targetId, timeScale"); SCRIPT_REG_TEMPLFUNC(PerformDeadHit, ""); } //------------------------------------------------------------------------ CGameRules *CScriptBind_GameRules::GetGameRules(IFunctionHandler *pH) { return static_cast<CGameRules *>(m_pGameFW->GetIGameRulesSystem()->GetCurrentGameRules()); } //------------------------------------------------------------------------ CActor *CScriptBind_GameRules::GetActor(EntityId id) { return static_cast<CActor *>(m_pGameFW->GetIActorSystem()->GetActor(id)); } //------------------------------------------------------------------------ void CScriptBind_GameRules::AttachTo(CGameRules *pGameRules) { IScriptTable *pScriptTable = pGameRules->GetEntity()->GetScriptTable(); if (pScriptTable) { SmartScriptTable thisTable(m_pSS); thisTable->Delegate(GetMethodsTable()); pScriptTable->SetValue("game", thisTable); } } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsServer(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(gEnv->bServer); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsClient(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(gEnv->bClient); } //------------------------------------------------------------------------ int CScriptBind_GameRules::CanCheat(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); if (g_pGame->GetIGameFramework()->CanCheat()) return pH->EndFunction(1); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SpawnPlayer(IFunctionHandler *pH, int channelId, const char *name, const char *className, Vec3 pos, Vec3 angles) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = pGameRules->SpawnPlayer(channelId, name, className, pos, Ang3(angles)); if (pActor) return pH->EndFunction(pActor->GetEntity()->GetScriptTable()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ChangePlayerClass(IFunctionHandler *pH, int channelId, const char *className) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = pGameRules->ChangePlayerClass(channelId, className); if (pActor) return pH->EndFunction(pActor->GetEntity()->GetScriptTable()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RevivePlayer(IFunctionHandler *pH, ScriptHandle playerId, Vec3 pos, Vec3 angles, int teamId, bool clearInventory) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)playerId.n); if (pActor) pGameRules->RevivePlayer(pActor, pos, Ang3(angles), teamId, clearInventory); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RevivePlayerInVehicle(IFunctionHandler *pH, ScriptHandle playerId, ScriptHandle vehicleId, int seatId, int teamId, bool clearInventory) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)playerId.n); if (pActor) pGameRules->RevivePlayerInVehicle(pActor, (EntityId)vehicleId.n, seatId, teamId, clearInventory); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RenamePlayer(IFunctionHandler *pH, ScriptHandle playerId, const char *name) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)playerId.n); if (pActor) pGameRules->RenamePlayer(pActor, name); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::KillPlayer(IFunctionHandler *pH, ScriptHandle playerId, bool dropItem, bool ragdoll, ScriptHandle shooterId, ScriptHandle weaponId, float damage, int material, int hit_type, Vec3 impulse) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)playerId.n); if (pActor) pGameRules->KillPlayer(pActor, dropItem, ragdoll, (EntityId)shooterId.n, (EntityId)weaponId.n, damage, material, hit_type, impulse); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::MovePlayer(IFunctionHandler *pH, ScriptHandle playerId, Vec3 pos, Vec3 angles) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = GetActor((EntityId)playerId.n); if (pActor) pGameRules->MovePlayer(pActor, pos, Ang3(angles)); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetPlayerByChannelId(IFunctionHandler *pH, int channelId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); CActor *pActor = pGameRules->GetActorByChannelId(channelId); if (pActor) return pH->EndFunction(pActor->GetEntity()->GetScriptTable()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetChannelId(IFunctionHandler *pH, ScriptHandle playerId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int channelId=pGameRules->GetChannelId((EntityId)playerId.n); return pH->EndFunction(channelId); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetPlayerCount(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); bool inGame=false; if (pH->GetParamCount()>0) pH->GetParam(1, inGame); return pH->EndFunction(pGameRules->GetPlayerCount(inGame)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpectatorCount(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); bool inGame=false; if (pH->GetParamCount()>0) pH->GetParam(1, inGame); return pH->EndFunction(pGameRules->GetSpectatorCount(inGame)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetPlayers(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int count=pGameRules->GetPlayerCount(); if (!count) return pH->EndFunction(); int tcount=m_players->Count(); int i=0; int k=0; while(i<count) { IEntity *pEntity=gEnv->pEntitySystem->GetEntity(pGameRules->GetPlayer(i)); if (pEntity) { IScriptTable *pEntityScript=pEntity->GetScriptTable(); if (pEntityScript) { m_players->SetAt(k+1, pEntityScript); ++k; } } ++i; } while(k<tcount) m_players->SetNullAt(++k); return pH->EndFunction(m_players); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsPlayerInGame(IFunctionHandler *pH, ScriptHandle playerId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules && pGameRules->IsPlayerInGame((EntityId)playerId.n)) return pH->EndFunction(true); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsProjectile(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->IsProjectile((EntityId)entityId.n)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsSameTeam(IFunctionHandler *pH, ScriptHandle entityId0, ScriptHandle entityId1) { CGameRules *pGameRules=GetGameRules(pH); int t0=pGameRules->GetTeam((EntityId)entityId0.n); int t1=pGameRules->GetTeam((EntityId)entityId1.n); if (t0==t1) return pH->EndFunction(true); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsNeutral(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); int t=pGameRules->GetTeam((EntityId)entityId.n); if (t==0) return pH->EndFunction(true); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddSpawnLocation(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->AddSpawnLocation((EntityId)entityId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveSpawnLocation(IFunctionHandler *pH, ScriptHandle id) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->RemoveSpawnLocation((EntityId)id.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnLocationCount(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) return pH->EndFunction(pGameRules->GetSpawnLocationCount()); return pH->EndFunction(0); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnLocationByIdx(IFunctionHandler *pH, int idx) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { EntityId id = pGameRules->GetSpawnLocation(idx); if (id) return pH->EndFunction(ScriptHandle(id)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnLocations(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int count=pGameRules->GetSpawnLocationCount(); if (!count) return pH->EndFunction(); int tcount=m_spawnlocations->Count(); int i=0; while(i<count) { m_spawnlocations->SetAt(i, ScriptHandle(pGameRules->GetSpawnLocation(i))); ++i; } while(i<tcount) m_spawnlocations->SetNullAt(++i); return pH->EndFunction(m_spawnlocations); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnLocation(IFunctionHandler *pH, ScriptHandle playerId, bool ignoreTeam, bool includeNeutral) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { EntityId groupId=0; float minDistanceToDeath=0.0f; float zOffset=0.0f; Vec3 deathPos(ZERO); if (pH->GetParamCount()>3 && pH->GetParamType(4)==svtPointer) { ScriptHandle groupIdHdl; pH->GetParam(4, groupIdHdl); groupId=(EntityId)groupIdHdl.n; } if (pH->GetParamCount()>5 && pH->GetParamType(5)==svtNumber && pH->GetParamType(6)==svtObject) { pH->GetParam(5, minDistanceToDeath); pH->GetParam(6, deathPos); } EntityId id=pGameRules->GetSpawnLocation((EntityId)playerId.n, ignoreTeam, includeNeutral, groupId, minDistanceToDeath, deathPos, &zOffset); if (id) return pH->EndFunction(ScriptHandle(id), zOffset); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetFirstSpawnLocation(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { EntityId id=pGameRules->GetFirstSpawnLocation(teamId); if (id) return pH->EndFunction(ScriptHandle(id)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddSpawnGroup(IFunctionHandler *pH, ScriptHandle groupId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->AddSpawnGroup((EntityId)groupId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddSpawnLocationToSpawnGroup(IFunctionHandler *pH, ScriptHandle groupId, ScriptHandle location) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->AddSpawnLocationToSpawnGroup((EntityId)groupId.n, (EntityId)location.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveSpawnLocationFromSpawnGroup(IFunctionHandler *pH, ScriptHandle groupId, ScriptHandle location) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->RemoveSpawnLocationFromSpawnGroup((EntityId)groupId.n, (EntityId)location.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveSpawnGroup(IFunctionHandler *pH, ScriptHandle groupId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->RemoveSpawnGroup((EntityId)groupId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnLocationGroup(IFunctionHandler *pH, ScriptHandle spawnId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { EntityId groupId=pGameRules->GetSpawnLocationGroup((EntityId)spawnId.n); if (groupId) return pH->EndFunction(ScriptHandle(groupId)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpawnGroups(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int teamId=-1; if (pH->GetParamCount()>0 && pH->GetParamType(1)==svtNumber) pH->GetParam(1, teamId); int count=pGameRules->GetSpawnGroupCount(); if (!count) return pH->EndFunction(); int tcount=m_spawngroups->Count(); int i=0; int k=0; while(i<count) { EntityId groupId=pGameRules->GetSpawnGroup(i); if (teamId==-1 || teamId==pGameRules->GetTeam(groupId)) m_spawngroups->SetAt(k++, ScriptHandle(groupId)); ++i; } while(i<tcount) m_spawngroups->SetNullAt(++i); return pH->EndFunction(m_spawngroups); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsSpawnGroup(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); if (pGameRules->IsSpawnGroup((EntityId)entityId.n)) return pH->EndFunction(true); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamDefaultSpawnGroup(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { EntityId id=pGameRules->GetTeamDefaultSpawnGroup(teamId); if (id) return pH->EndFunction(ScriptHandle(id)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetTeamDefaultSpawnGroup(IFunctionHandler *pH, int teamId, ScriptHandle groupId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->SetTeamDefaultSpawnGroup(teamId, (EntityId)groupId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetPlayerSpawnGroup(IFunctionHandler *pH, ScriptHandle playerId, ScriptHandle groupId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->SetPlayerSpawnGroup((EntityId)playerId.n, (EntityId)groupId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddSpectatorLocation(IFunctionHandler *pH, ScriptHandle location) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->AddSpectatorLocation((EntityId)location.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveSpectatorLocation(IFunctionHandler *pH, ScriptHandle id) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->RemoveSpectatorLocation((EntityId)id.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpectatorLocationCount(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) return pH->EndFunction(pGameRules->GetSpectatorLocationCount()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpectatorLocation(IFunctionHandler *pH, int idx) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) return pH->EndFunction(ScriptHandle(pGameRules->GetSpectatorLocation(idx))); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSpectatorLocations(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int count=pGameRules->GetSpectatorLocationCount(); if (!count) return pH->EndFunction(); int tcount=m_spectatorlocations->Count(); int i=0; while(i<count) { m_spectatorlocations->SetAt(i, ScriptHandle(pGameRules->GetSpectatorLocation(i))); ++i; } while(i<tcount) m_spectatorlocations->SetNullAt(++i); return pH->EndFunction(m_spectatorlocations); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRandomSpectatorLocation(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { if (EntityId locationId=pGameRules->GetRandomSpectatorLocation()) return pH->EndFunction(ScriptHandle(locationId)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetInterestingSpectatorLocation(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) { if (EntityId locationId=pGameRules->GetInterestingSpectatorLocation()) return pH->EndFunction(ScriptHandle(locationId)); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetNextSpectatorTarget(IFunctionHandler *pH, ScriptHandle playerId, int change) { if(change >= 1) change = 1; if(change <= 0) change = -1; CGameRules* pGameRules = GetGameRules(pH); if(pGameRules) { CPlayer* pPlayer = (CPlayer*)gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor((EntityId)playerId.n); if(pPlayer) { // get list of possible players (team mates or all players) CGameRules::TPlayers players; int team = pGameRules->GetTeam((EntityId)playerId.n); if(g_pGame->GetCVars()->g_spectate_TeamOnly == 0 || pGameRules->GetTeamCount() == 0 || team == 0) { pGameRules->GetPlayers(players); } else { pGameRules->GetTeamPlayers(team, players); } int numPlayers = players.size(); // work out which one we are currently watching int index = 0; for(; index < players.size(); ++index) if(players[index] == pPlayer->GetSpectatorTarget()) break; // loop through the players to find a valid one. bool found = false; if(numPlayers > 0) { int newTargetIndex = index; int numAttempts = numPlayers; do { newTargetIndex += change; --numAttempts; // wrap around if(newTargetIndex < 0) newTargetIndex = numPlayers-1; if(newTargetIndex >= numPlayers) newTargetIndex = 0; // skip ourself if(players[newTargetIndex] == playerId.n) continue; // skip dead players IActor* pActor = gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(players[newTargetIndex]); if(!pActor || pActor->GetHealth() <= 0) continue; // skip spectating players if(((CPlayer*)pActor)->GetSpectatorMode() != CActor::eASM_None) continue; // otherwise this one will do. found = true; } while(!found && numAttempts > 0); if(found) return pH->EndFunction(ScriptHandle(players[newTargetIndex])); } } } return pH->EndFunction(0); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ChangeSpectatorMode(IFunctionHandler* pH, ScriptHandle playerId, int mode, ScriptHandle targetId) { CGameRules *pGameRules = GetGameRules(pH); CActor* pActor = (CActor*)g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor((EntityId)playerId.n); if(pGameRules && pActor) pGameRules->ChangeSpectatorMode(pActor, mode, (EntityId)targetId.n, false); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::CanChangeSpectatorMode(IFunctionHandler* pH, ScriptHandle playerId) { IActor* pActor = g_pGame->GetIGameFramework()->GetClientActor(); CHUD* pHUD = g_pGame->GetHUD(); if(gEnv->bMultiplayer && pHUD && pActor && pActor->GetEntityId() == playerId.n) { if(pHUD->IsBuyMenuActive() || pHUD->IsScoreboardActive() || pHUD->IsPDAActive()) return pH->EndFunction(false); } return pH->EndFunction(true); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddMinimapEntity(IFunctionHandler *pH, ScriptHandle entityId, int type, float lifetime) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->AddMinimapEntity((EntityId)entityId.n, type, lifetime); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveMinimapEntity(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->RemoveMinimapEntity((EntityId)entityId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetMinimap(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetMinimap(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetPing(IFunctionHandler *pH, int channelId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); INetChannel *pNetChannel = g_pGame->GetIGameFramework()->GetNetChannel(channelId); if (pNetChannel) return pH->EndFunction(pNetChannel->GetPing(true)); return pH->EndFunction(0); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetEntities(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->ResetEntities(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ServerExplosion(IFunctionHandler *pH, ScriptHandle shooterId, ScriptHandle weaponId, float dmg, Vec3 pos, Vec3 dir, float radius, float angle, float pressure, float holesize) { CGameRules *pGameRules=GetGameRules(pH); if (!gEnv->bServer) return pH->EndFunction(); const char *effect=""; float effectScale=1.0f; int type=0; if (pH->GetParamCount()>9 && pH->GetParamType(10)!=svtNull) pH->GetParam(10, effect); if (pH->GetParamCount()>10 && pH->GetParamType(11)!=svtNull) pH->GetParam(11, effectScale); if (pH->GetParamCount()>11 && pH->GetParamType(12)!=svtNull) pH->GetParam(12, type); float minRadius = radius/2.0f; float minPhysRadius = radius/2.0f; float physRadius = radius; if (pH->GetParamCount()>12 && pH->GetParamType(13)!=svtNull) pH->GetParam(13, minRadius); if (pH->GetParamCount()>13 && pH->GetParamType(14)!=svtNull) pH->GetParam(14, minPhysRadius); if (pH->GetParamCount()>14 && pH->GetParamType(15)!=svtNull) pH->GetParam(15, physRadius); ExplosionInfo info(shooterId.n, weaponId.n, dmg, pos, dir.GetNormalized(), minRadius, radius, minPhysRadius, physRadius, angle, pressure, holesize, 0); IParticleEffect* pParticleEffect = gEnv->p3DEngine->FindParticleEffect(effect); info.SetEffect(pParticleEffect, effectScale, 0.0f); info.type = type; pGameRules->ServerExplosion(info); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ServerHit(IFunctionHandler *pH, ScriptHandle targetId, ScriptHandle shooterId, ScriptHandle weaponId, float dmg, float radius, int materialId, int partId, int typeId) { CGameRules *pGameRules=GetGameRules(pH); if (!gEnv->bServer) return pH->EndFunction(); HitInfo info(shooterId.n, targetId.n, weaponId.n, dmg, radius, materialId, partId, typeId); if (pH->GetParamCount()>8 && pH->GetParamType(9)!=svtNull) pH->GetParam(9, info.pos); if (pH->GetParamCount()>9 && pH->GetParamType(10)!=svtNull) pH->GetParam(10, info.dir); if (pH->GetParamCount()>10 && pH->GetParamType(11)!=svtNull) pH->GetParam(11, info.normal); pGameRules->ServerHit(info); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::CreateTeam(IFunctionHandler *pH, const char *name) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->CreateTeam(name)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveTeam(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->RemoveTeam(teamId); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamName(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); const char *name=pGameRules->GetTeamName(teamId); if (name) return pH->EndFunction(name); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamId(IFunctionHandler *pH, const char *teamName) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int id=pGameRules->GetTeamId(teamName); if (id) return pH->EndFunction(id); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamCount(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetTeamCount()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamPlayerCount(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); bool inGame=false; if (pH->GetParamCount()>1) pH->GetParam(2, inGame); return pH->EndFunction(pGameRules->GetTeamPlayerCount(teamId, inGame)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamChannelCount(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); bool inGame=false; if (pH->GetParamCount()>1) pH->GetParam(2, inGame); return pH->EndFunction(pGameRules->GetTeamChannelCount(teamId, inGame)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamPlayers(IFunctionHandler *pH, int teamId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int count=pGameRules->GetTeamPlayerCount(teamId); if (!count) return pH->EndFunction(); int tcount=m_teamplayers->Count(); int i=0; while(i<count) { IEntity *pEntity=gEnv->pEntitySystem->GetEntity(pGameRules->GetTeamPlayer(teamId, i)); if (pEntity) { IScriptTable *pEntityScript=pEntity->GetScriptTable(); if (pEntityScript) m_teamplayers->SetAt(i+1, pEntityScript); else m_teamplayers->SetNullAt(i+1); } ++i; } while(i<tcount) m_teamplayers->SetNullAt(++i); return pH->EndFunction(m_teamplayers); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetTeam(IFunctionHandler *pH, int teamId, ScriptHandle playerId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->SetTeam(teamId, (EntityId)playerId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeam(IFunctionHandler *pH, ScriptHandle playerId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetTeam((EntityId)playerId.n)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetChannelTeam(IFunctionHandler *pH, int channelId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetChannelTeam(channelId)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AddObjective(IFunctionHandler *pH, int teamId, const char *objective, int status, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->AddObjective(teamId, objective, status, (EntityId)entityId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetObjectiveStatus(IFunctionHandler *pH, int teamId, const char *objective, int status) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->SetObjectiveStatus(teamId, objective, status); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetObjectiveEntity(IFunctionHandler *pH, int teamId, const char *objective, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->SetObjectiveEntity(teamId, objective, (EntityId)entityId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RemoveObjective(IFunctionHandler *pH, int teamId, const char *objective) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->RemoveObjective(teamId, objective); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetObjectives(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetObjectives(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::TextMessage(IFunctionHandler *pH, int type, const char *msg) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); if (pH->GetParamCount()>2) { string p[4]; for (int i=0;i<pH->GetParamCount()-2;i++) { switch(pH->GetParamType(3+i)) { case svtPointer: { ScriptHandle sh; pH->GetParam(3+i, sh); if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity((EntityId)sh.n)) p[i]=pEntity->GetName(); } break; default: { ScriptAnyValue value; pH->GetParamAny(3+i, value); switch(value.GetVarType()) { case svtNumber: p[i].Format("%g", value.number); break; case svtString: p[i]=value.str; break; case svtBool: p[i]=value.b?"true":"false"; break; default: break; } } break; } } pGameRules->OnTextMessage((ETextMessageType)type, msg, p[0].empty()?0:p[0].c_str(), p[1].empty()?0:p[1].c_str(), p[2].empty()?0:p[2].c_str(), p[3].empty()?0:p[3].c_str() ); } else pGameRules->OnTextMessage((ETextMessageType)type, msg); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SendTextMessage(IFunctionHandler *pH, int type, const char *msg) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); int to=eRMI_ToAllClients; int channelId=-1; if (pH->GetParamCount()>2) pH->GetParam(3, to); if (pH->GetParamCount()>3) { if (pH->GetParamType(4)==svtPointer) { ScriptHandle playerId; pH->GetParam(4, playerId); channelId=pGameRules->GetChannelId((EntityId)playerId.n); } else if (pH->GetParamType(4)==svtNumber) pH->GetParam(4, channelId); } if (pH->GetParamCount()>4) { string p[4]; for (int i=0;i<pH->GetParamCount()-4;i++) { switch(pH->GetParamType(5+i)) { case svtPointer: { ScriptHandle sh; pH->GetParam(5+i, sh); if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity((EntityId)sh.n)) p[i]=pEntity->GetName(); } break; default: { ScriptAnyValue value; pH->GetParamAny(5+i, value); switch(value.GetVarType()) { case svtNumber: p[i].Format("%g", value.number); break; case svtString: p[i]=value.str; break; case svtBool: p[i]=value.b?"true":"false"; break; default: break; } } break; } } pGameRules->SendTextMessage((ETextMessageType)type, msg, to, channelId, p[0].empty()?0:p[0].c_str(), p[1].empty()?0:p[1].c_str(), p[2].empty()?0:p[2].c_str(), p[3].empty()?0:p[3].c_str() ); } else pGameRules->SendTextMessage((ETextMessageType)type, msg, to, channelId); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SendChatMessage(IFunctionHandler *pH, int type, ScriptHandle sourceId, ScriptHandle targetId, const char *msg) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->SendChatMessage((EChatMessageType)type, (EntityId)sourceId.n, (EntityId)targetId.n, msg); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ForbiddenAreaWarning(IFunctionHandler *pH, bool active, int timer, ScriptHandle targetId) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ForbiddenAreaWarning(active, timer, (EntityId)targetId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetGameTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetGameTime(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRemainingGameTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetRemainingGameTime()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsTimeLimited(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules || !pGameRules->IsTimeLimited()) return pH->EndFunction(); return pH->EndFunction(true); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetRoundTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetRoundTime(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRemainingRoundTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetRemainingRoundTime()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsRoundTimeLimited(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules || !pGameRules->IsRoundTimeLimited()) return pH->EndFunction(); return pH->EndFunction(true); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetPreRoundTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetPreRoundTime(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRemainingPreRoundTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetRemainingPreRoundTime()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetReviveCycleTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetReviveCycleTime(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRemainingReviveCycleTime(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetRemainingReviveCycleTime()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetGameStartTimer(IFunctionHandler *pH, float time) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); pGameRules->ResetGameStartTimer(time); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRemainingStartTimer(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (!pGameRules) return pH->EndFunction(); return pH->EndFunction(pGameRules->GetRemainingStartTimer()); } //------------------------------------------------------------------------ int CScriptBind_GameRules::EndGame(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->OnEndGame(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::NextLevel(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules) pGameRules->NextLevel(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RegisterHitMaterial(IFunctionHandler *pH, const char *materialName) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->RegisterHitMaterial(materialName)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetHitMaterialId(IFunctionHandler *pH, const char *materialName) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->GetHitMaterialId(materialName)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetHitMaterialName(IFunctionHandler *pH, int materialId) { CGameRules *pGameRules=GetGameRules(pH); if (ISurfaceType *pSurfaceType=pGameRules->GetHitMaterial(materialId)) return pH->EndFunction(pSurfaceType->GetName()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetHitMaterials(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ResetHitMaterials(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::RegisterHitType(IFunctionHandler *pH, const char *type) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->RegisterHitType(type)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetHitTypeId(IFunctionHandler *pH, const char *type) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->GetHitTypeId(type)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetHitType(IFunctionHandler *pH, int id) { CGameRules *pGameRules=GetGameRules(pH); return pH->EndFunction(pGameRules->GetHitType(id)); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetHitTypes(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ResetHitTypes(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ForceScoreboard(IFunctionHandler *pH, bool force) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ForceScoreboard(force); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::FreezeInput(IFunctionHandler *pH, bool freeze) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->FreezeInput(freeze); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ScheduleEntityRespawn(IFunctionHandler *pH, ScriptHandle entityId, bool unique, float timer) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ScheduleEntityRespawn((EntityId)entityId.n, unique, timer); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AbortEntityRespawn(IFunctionHandler *pH, ScriptHandle entityId, bool destroyData) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->AbortEntityRespawn((EntityId)entityId.n, destroyData); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ScheduleEntityRemoval(IFunctionHandler *pH, ScriptHandle entityId, float timer, bool visibility) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ScheduleEntityRemoval((EntityId)entityId.n, timer, visibility); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::AbortEntityRemoval(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->AbortEntityRemoval((EntityId)entityId.n); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetSynchedGlobalValue(IFunctionHandler *pH, int key) { CGameRules *pGameRules=GetGameRules(pH); if (pH->GetParamCount()==2) { switch (pH->GetParamType(2)) { case svtString: { const char *s=0; pH->GetParam(2, s); pGameRules->SetSynchedGlobalValue(key, string(s)); } break; case svtPointer: { ScriptHandle e; pH->GetParam(2, e); pGameRules->SetSynchedGlobalValue(key, (EntityId)e.n); } break; case svtBool: { bool b; pH->GetParam(2, b); pGameRules->SetSynchedGlobalValue(key, b); } break; case svtNumber: { float f; int i; pH->GetParam(2, f); i=(int)f; if (f==i) pGameRules->SetSynchedGlobalValue(key, i); else pGameRules->SetSynchedGlobalValue(key, f); } break; default: assert(0); } } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSynchedGlobalValue(IFunctionHandler *pH, int key) { CGameRules *pGameRules=GetGameRules(pH); int type=pGameRules->GetSynchedGlobalValueType(key); if (type==eSVT_None) return pH->EndFunction(); switch (type) { case eSVT_Bool: { bool b; pGameRules->GetSynchedGlobalValue(key, b); return pH->EndFunction(b); } break; case eSVT_Float: { float f; pGameRules->GetSynchedGlobalValue(key, f); return pH->EndFunction(f); } break; case eSVT_Int: { int i; pGameRules->GetSynchedGlobalValue(key, i); return pH->EndFunction(i); } break; case eSVT_EntityId: { EntityId e; pGameRules->GetSynchedGlobalValue(key, e); return pH->EndFunction(ScriptHandle(e)); } break; case eSVT_String: { static string s; pGameRules->GetSynchedGlobalValue(key, s); return pH->EndFunction(s.c_str()); } break; default: assert(0); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetSynchedEntityValue(IFunctionHandler *pH, ScriptHandle entityId, int key) { CGameRules *pGameRules=GetGameRules(pH); EntityId id=(EntityId)entityId.n; if (pH->GetParamCount()==3) { switch (pH->GetParamType(3)) { case svtString: { const char *s=0; pH->GetParam(3, s); pGameRules->SetSynchedEntityValue(id, key, string(s)); } break; case svtPointer: { ScriptHandle e; pH->GetParam(3, e); pGameRules->SetSynchedEntityValue(id, key, (EntityId)e.n); } break; case svtBool: { bool b; pH->GetParam(3, b); pGameRules->SetSynchedEntityValue(id, key, b); } break; case svtNumber: { float f; int i; pH->GetParam(3, f); i=(int)f; if (f==i) pGameRules->SetSynchedEntityValue(id, key, i); else pGameRules->SetSynchedEntityValue(id, key, f); } break; default: assert(0); } } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetSynchedEntityValue(IFunctionHandler *pH, ScriptHandle entityId, int key) { CGameRules *pGameRules=GetGameRules(pH); EntityId id=(EntityId)entityId.n; int type=pGameRules->GetSynchedEntityValueType(id, key); if (type==eSVT_None) return pH->EndFunction(); switch (type) { case eSVT_Bool: { bool b; pGameRules->GetSynchedEntityValue(id, key, b); return pH->EndFunction(b); } break; case eSVT_Float: { float f; pGameRules->GetSynchedEntityValue(id, key, f); return pH->EndFunction(f); } break; case eSVT_Int: { int i; pGameRules->GetSynchedEntityValue(id, key, i); return pH->EndFunction(i); } break; case eSVT_EntityId: { EntityId e; pGameRules->GetSynchedEntityValue(id, key, e); return pH->EndFunction(ScriptHandle(e)); } break; case eSVT_String: { static string s; pGameRules->GetSynchedEntityValue(id, key, s); return pH->EndFunction(s.c_str()); } break; default: assert(0); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ResetSynchedStorage(IFunctionHandler *pH) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ResetSynchedStorage(); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ForceSynchedStorageSynch(IFunctionHandler *pH, int channelId) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ForceSynchedStorageSynch(channelId); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsDemoMode(IFunctionHandler *pH) { int demoMode = IsDemoPlayback(); return pH->EndFunction(demoMode); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTimeLimit(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_timelimit); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRoundTime(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_roundtime); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetPreRoundTime(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_preroundtime); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetRoundLimit(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_roundlimit); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetFragLimit(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_fraglimit); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetFragLead(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_fraglead); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetFriendlyFireRatio(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_friendlyfireratio); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetReviveTime(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_revivetime); } int CScriptBind_GameRules::GetMinPlayerLimit(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_minplayerlimit); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetMinTeamLimit(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_minteamlimit); } //------------------------------------------------------------------------ int CScriptBind_GameRules::GetTeamLock(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_teamlock); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsFrozen(IFunctionHandler *pH, ScriptHandle entityId) { CGameRules *pGameRules=GetGameRules(pH); if (pGameRules->IsFrozen((EntityId)entityId.n)) return pH->EndFunction(1); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::FreezeEntity(IFunctionHandler *pH, ScriptHandle entityId, bool freeze, bool vapor) { CGameRules *pGameRules=GetGameRules(pH); bool force=false; if (pH->GetParamCount()>3 && pH->GetParamType(4)==svtBool) pH->GetParam(4, force); pGameRules->FreezeEntity((EntityId)entityId.n, freeze, vapor, force); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::ShatterEntity(IFunctionHandler *pH, ScriptHandle entityId, Vec3 pos, Vec3 impulse) { CGameRules *pGameRules=GetGameRules(pH); pGameRules->ShatterEntity((EntityId)entityId.n, pos, impulse); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::DebugCollisionDamage(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_debugCollisionDamage); } //------------------------------------------------------------------------ int CScriptBind_GameRules::DebugHits(IFunctionHandler *pH) { return pH->EndFunction(g_pGameCVars->g_debugHits); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SendHitIndicator(IFunctionHandler* pH, ScriptHandle shooterId) { if(!gEnv->bServer) return pH->EndFunction(); EntityId id = EntityId(shooterId.n); if(!id) return pH->EndFunction(); CGameRules *pGameRules = GetGameRules(pH); CActor* pActor = pGameRules->GetActorByEntityId(id); if (!pActor || !pActor->IsPlayer()) return pH->EndFunction(); pGameRules->GetGameObject()->InvokeRMI(CGameRules::ClHitIndicator(), CGameRules::NoParams(), eRMI_ToClientChannel, pGameRules->GetChannelId(id)); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SendDamageIndicator(IFunctionHandler* pH, ScriptHandle targetId, ScriptHandle shooterId, ScriptHandle weaponId) { if(!gEnv->bServer) return pH->EndFunction(); CGameRules *pGameRules = GetGameRules(pH); EntityId tId = EntityId(targetId.n); EntityId sId= EntityId(shooterId.n); EntityId wId= EntityId(weaponId.n); if (!tId) return pH->EndFunction(); CActor* pActor = pGameRules->GetActorByEntityId(tId); if (!pActor || !pActor->IsPlayer()) return pH->EndFunction(); pGameRules->GetGameObject()->InvokeRMIWithDependentObject(CGameRules::ClDamageIndicator(), CGameRules::DamageIndicatorParams(sId, wId), eRMI_ToClientChannel, sId, pGameRules->GetChannelId(tId)); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::IsInvulnerable(IFunctionHandler* pH, ScriptHandle playerId) { CGameRules *pGameRules = GetGameRules(pH); CActor* pActor = pGameRules->GetActorByEntityId((EntityId)playerId.n); if (!pActor || !pActor->IsPlayer()) return pH->EndFunction(); if (pActor->GetActorClass() != CPlayer::GetActorClassType()) return pH->EndFunction(); CPlayer *pPlayer=static_cast<CPlayer *>(pActor); if (CNanoSuit *pNanoSuit=pPlayer->GetNanoSuit()) return pH->EndFunction(pNanoSuit->IsInvulnerable()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::SetInvulnerability(IFunctionHandler* pH, ScriptHandle playerId, bool invulnerable) { if(!gEnv->bServer) return pH->EndFunction(); CGameRules *pGameRules = GetGameRules(pH); CActor* pActor = pGameRules->GetActorByEntityId((EntityId)playerId.n); if (!pActor || !pActor->IsPlayer()) return pH->EndFunction(); if (pActor->GetActorClass() != CPlayer::GetActorClassType()) return pH->EndFunction(); CPlayer *pPlayer=static_cast<CPlayer *>(pActor); if (CNanoSuit *pNanoSuit=pPlayer->GetNanoSuit()) { pNanoSuit->SetInvulnerability(invulnerable); float timeout=-1.0f; if (pH->GetParamCount()>2 && pH->GetParamType(3)==svtNumber) pH->GetParam(3, timeout); if (timeout>0.0f) pNanoSuit->SetInvulnerabilityTimeout(timeout); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_GameRules::TutorialEvent(IFunctionHandler* pH, int eventType) { CMPTutorial* pTutorial = GetGameRules(pH)->GetMPTutorial(); if(pTutorial) { pTutorial->TriggerEvent(static_cast<ETutorialEvent>(eventType)); } return pH->EndFunction(); } //------------------------------------------------------------------------- int CScriptBind_GameRules::GameOver(IFunctionHandler* pH, int localWinner) { CGameRules* pGameRules = g_pGame->GetGameRules(); if (pGameRules) pGameRules->GameOver(localWinner); return pH->EndFunction(); } //------------------------------------------------------------------------- int CScriptBind_GameRules::EnteredGame(IFunctionHandler* pH) { CGameRules* pGameRules = g_pGame->GetGameRules(); if (pGameRules) pGameRules->EnteredGame(); return pH->EndFunction(); } //-------------------------------------------------------------------------- int CScriptBind_GameRules::EndGameNear(IFunctionHandler* pH, ScriptHandle entityId) { CGameRules* pGameRules = g_pGame->GetGameRules(); if(pGameRules) pGameRules->EndGameNear(EntityId(entityId.n)); return pH->EndFunction(); } int CScriptBind_GameRules::SPNotifyPlayerKill(IFunctionHandler* pH, ScriptHandle targetId, ScriptHandle weaponId, bool bHeadShot) { CGameRules* pGameRules = g_pGame->GetGameRules(); if(pGameRules) pGameRules->SPNotifyPlayerKill((EntityId)targetId.n, (EntityId)weaponId.n, bHeadShot); return pH->EndFunction(); } //----------------------------------------------------------------------------- int CScriptBind_GameRules::ProcessEMPEffect(IFunctionHandler* pH, ScriptHandle targetId, float timeScale) { if(timeScale>0.0f) { CActor* pActor = static_cast<CActor*>(g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(EntityId(targetId.n))); if (pActor && (pActor->GetSpectatorMode() == 0) && (pActor->GetActorClass() == CPlayer::GetActorClassType())) { CPlayer* pPlayer = static_cast<CPlayer*>(pActor); if (CNanoSuit* pSuit = pPlayer->GetNanoSuit()) { const float baseTime = 15.0f; float time = max(3.0f, baseTime*timeScale); pSuit->Activate(false); pSuit->SetSuitEnergy(0.0f); pSuit->Activate(true, time); pPlayer->GetGameObject()->InvokeRMI(CPlayer::ClEMP(), CPlayer::EMPParams(time), eRMI_ToClientChannel, pPlayer->GetChannelId()); } } } return pH->EndFunction(); } //----------------------------------------------------------------------------- int CScriptBind_GameRules::PerformDeadHit(IFunctionHandler* pH) { #ifdef CRAPDOLLS return pH->EndFunction(false); #else return pH->EndFunction(true); #endif // CRAPDOLLS }
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 70 ], [ 76, 92 ], [ 94, 95 ], [ 97, 100 ], [ 104, 109 ], [ 111, 118 ], [ 120, 132 ], [ 135, 145 ], [ 148, 151 ], [ 153, 156 ], [ 158, 181 ], [ 188, 192 ], [ 194, 216 ], [ 218, 229 ], [ 231, 236 ], [ 244, 249 ], [ 255, 397 ], [ 399, 407 ], [ 409, 443 ], [ 456, 500 ], [ 502, 508 ], [ 513, 516 ], [ 519, 533 ], [ 570, 645 ], [ 647, 652 ], [ 658, 659 ], [ 661, 663 ], [ 671, 671 ], [ 673, 785 ], [ 800, 946 ], [ 949, 986 ], [ 988, 998 ], [ 1000, 1005 ], [ 1032, 1121 ], [ 1134, 1168 ], [ 1191, 1247 ], [ 1263, 1321 ], [ 1333, 1656 ], [ 1704, 1742 ], [ 1754, 2066 ], [ 2076, 2078 ], [ 2080, 2141 ], [ 2148, 2160 ], [ 2166, 2185 ], [ 2187, 2187 ], [ 2197, 2199 ], [ 2201, 2203 ], [ 2205, 2206 ], [ 2208, 2212 ], [ 2214, 2214 ], [ 2216, 2216 ], [ 2218, 2218 ], [ 2258, 2260 ], [ 2265, 2266 ], [ 2282, 2326 ] ], [ [ 71, 75 ], [ 93, 93 ], [ 96, 96 ], [ 101, 103 ], [ 110, 110 ], [ 119, 119 ], [ 133, 134 ], [ 146, 147 ], [ 152, 152 ], [ 157, 157 ], [ 182, 187 ], [ 193, 193 ], [ 217, 217 ], [ 230, 230 ], [ 237, 243 ], [ 250, 254 ], [ 398, 398 ], [ 408, 408 ], [ 444, 455 ], [ 501, 501 ], [ 509, 512 ], [ 517, 518 ], [ 534, 569 ], [ 646, 646 ], [ 653, 657 ], [ 660, 660 ], [ 664, 670 ], [ 672, 672 ], [ 786, 799 ], [ 947, 948 ], [ 987, 987 ], [ 999, 999 ], [ 1006, 1031 ], [ 1122, 1133 ], [ 1169, 1190 ], [ 1248, 1262 ], [ 1322, 1332 ], [ 1657, 1703 ], [ 1743, 1753 ], [ 2067, 2075 ], [ 2079, 2079 ], [ 2142, 2147 ], [ 2161, 2165 ], [ 2186, 2186 ], [ 2188, 2196 ], [ 2200, 2200 ], [ 2204, 2204 ], [ 2207, 2207 ], [ 2213, 2213 ], [ 2215, 2215 ], [ 2217, 2217 ], [ 2219, 2257 ], [ 2261, 2264 ], [ 2267, 2281 ], [ 2327, 2369 ] ] ]
cdc64372678f7809cedbaa48ba4bf3b3a9a4394d
c6311b5096eeed35f7b8cdb5c228de915075eb71
/tp3/Tp_3_Mundial2010v1/TestResultsDialog.cpp
8c3e2e9a129fc744ed33e63b70b6fd175b13ee10
[]
no_license
kevinalle/metnum2010
5dccdba68bb4d3065c6a696f02836e7119eba657
142a5464429e564c13aabd339a7b01800ea9023e
refs/heads/master
2020-05-28T05:01:34.835358
2010-07-23T19:19:27
2010-07-23T19:19:27
32,120,707
0
0
null
null
null
null
UTF-8
C++
false
false
4,674
cpp
/** \file \author Pablo Haramburu Copyright: Copyright (C)2010 Pablo Haramburu. License: This file is part of mundial2010. mundial2010 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. mundial2010 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 mundial2010. If not, see <http://www.gnu.org/licenses/>. */ // Generated by DialogBlocks (unregistered), 01/06/2010 01:49:44 // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include "TestResultsDialog.h" ////@begin XPM images ////@end XPM images /*! * TestResultsDialog type definition */ IMPLEMENT_DYNAMIC_CLASS( TestResultsDialog, wxDialog ) /*! * TestResultsDialog event table definition */ BEGIN_EVENT_TABLE( TestResultsDialog, wxDialog ) ////@begin TestResultsDialog event table entries ////@end TestResultsDialog event table entries END_EVENT_TABLE() /*! * TestResultsDialog constructors */ TestResultsDialog::TestResultsDialog() { Init(); } TestResultsDialog::TestResultsDialog( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, caption, pos, size, style); } /*! * TestResultsDialog creator */ bool TestResultsDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin TestResultsDialog creation SetExtraStyle(wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end TestResultsDialog creation return true; } /*! * TestResultsDialog destructor */ TestResultsDialog::~TestResultsDialog() { ////@begin TestResultsDialog destruction ////@end TestResultsDialog destruction } /*! * Member initialisation */ void TestResultsDialog::Init() { ////@begin TestResultsDialog member initialisation m_results = NULL; m_summary = NULL; m_cancelBtn = NULL; ////@end TestResultsDialog member initialisation } /*! * Control creation for TestResultsDialog */ void TestResultsDialog::CreateControls() { ////@begin TestResultsDialog content construction // Generated by DialogBlocks, 01/06/2010 04:20:21 (unregistered) TestResultsDialog* itemDialog1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemDialog1->SetSizer(itemBoxSizer2); m_results = new wxListCtrl( itemDialog1, ID_LISTCTRL1, wxDefaultPosition, wxSize(300, 100), wxLC_REPORT ); itemBoxSizer2->Add(m_results, 1, wxGROW|wxALL|wxFIXED_MINSIZE, 5); m_summary = new wxListCtrl( itemDialog1, ID_LISTCTRL2, wxDefaultPosition, wxSize(100, 100), wxLC_REPORT ); itemBoxSizer2->Add(m_summary, 0, wxGROW|wxALL, 5); m_cancelBtn = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer2->Add(m_cancelBtn, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); ////@end TestResultsDialog content construction m_results->InsertColumn(0,_("Arquero")); m_results->InsertColumn(1,_("Test")); m_results->InsertColumn(2,_("Resultado")); m_summary->InsertColumn(0,_("Arquero")); m_summary->InsertColumn(1,_("Atajo")); m_summary->InsertColumn(2,_("de (tiros)")); } /*! * Should we show tooltips? */ bool TestResultsDialog::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap TestResultsDialog::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin TestResultsDialog bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end TestResultsDialog bitmap retrieval } /*! * Get icon resources */ wxIcon TestResultsDialog::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin TestResultsDialog icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end TestResultsDialog icon retrieval }
[ "kevinalle@8062f241-9d54-ddaa-24e5-4d4b1e181026" ]
[ [ [ 1, 193 ] ] ]
e5e4e47e4fc7e071d949fd4b97d293b202a01879
d411188fd286604be7670b61a3c4c373345f1013
/zomgame/ZGame/event_add_effect.cpp
adaf870910a84fd518cbfb4c14f7d0aa246e7a9c
[]
no_license
kjchiu/zomgame
5af3e45caea6128e6ac41a7e3774584e0ca7a10f
1f62e569da4c01ecab21a709a4a3f335dff18f74
refs/heads/master
2021-01-13T13:16:58.843499
2008-09-13T05:11:16
2008-09-13T05:11:16
1,560,000
0
1
null
null
null
null
UTF-8
C++
false
false
406
cpp
#include "event_add_effect.h" EventAddEffect::EventAddEffect(Entity* _target, Effect* _effect) : target(_target), effect(_effect), Event(ADD_EFFECT) { } Message* EventAddEffect::resolve() { effect->setTickCount(getTick()); target->addEffect(effect); char* buf = new char[128]; sprintf_s(buf, 128, "target now has %d effects", target->getEffects()->size()); return new Message(buf); }
[ "krypes@9b66597e-bb4a-0410-bce4-15c857dd0990" ]
[ [ [ 1, 14 ] ] ]
7778d809a392d2c7036c58476b5b0c2d3fedbecc
d22b77645ee83ee72fed70cb2a3ca4fb268ada4a
/servers/zone_db_srv/WindowsService.cpp
6619d8db5ea88dfea5be690878128ff3243076ed
[]
no_license
catid/Splane
8f94f7d8983cf994955e599fc53ce6f763157486
c9f79f0034d1762948b7c26e42f50f58793067ac
refs/heads/master
2020-04-26T00:28:48.571474
2010-06-02T05:37:43
2010-06-02T05:37:43
628,653
1
0
null
null
null
null
UTF-8
C++
false
false
8,870
cpp
/* Copyright (c) 2009-2010 Christopher A. Taylor. 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 LibCat nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WindowsService.hpp" using namespace cat; //// Entrypoint int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if (!InitializeFramework("ZoneDatabaseServer")) { FatalStop("Unable to initialize framework!"); } if (lpCmdLine && iStrEqual(lpCmdLine, "install")) { if (WindowsService::ref()->IsExistingService()) { WindowsService::ref()->RemoveService(); } if (!WindowsService::ref()->InstallService()) { MessageBoxA(0, "Unable to install service", "Cannot Install Server", 0); } } else if (lpCmdLine && iStrEqual(lpCmdLine, "remove")) { if (WindowsService::ref()->IsExistingService()) { if (!WindowsService::ref()->RemoveService()) { MessageBoxA(0, "Unable to remove service", "Cannot Remove Server", 0); } } else { MessageBoxA(0, "Service is not installed", "Cannot Remove Server", 0); } } else { if (!WindowsService::ref()->StartServiceMain()) { MessageBoxA(0, "Unable to initialize service.\n\nThe server should be started from an Administrator command prompt by typing\n\n\"zone_srv.exe install\"", "Cannot Start Server", 0); } } ShutdownFramework(true); return 0; } WindowsService::WindowsService() { const char *settings_service_name = Settings::ii->getStr("Service.Name", "ZoneDatabaseServer"); CAT_STRNCPY(_service_name, settings_service_name, sizeof(_service_name)); _service_handle = 0; _server = 0; } WindowsService::~WindowsService() { } bool WindowsService::IsExistingService() { // If able to open Service Control Manager to check service, SC_HANDLE scm_check = OpenSCManager(0, 0, SC_MANAGER_CONNECT); if (scm_check) { // If service already exists, SC_HANDLE svc_check = OpenServiceA(scm_check, _service_name, SERVICE_QUERY_STATUS); if (svc_check) { CloseServiceHandle(svc_check); CloseServiceHandle(scm_check); return true; } CloseServiceHandle(scm_check); } else { FATAL("ServiceManager") << "IsExistingService(): Unable to connect Service Control Manager"; } return false; } bool WindowsService::InstallService() { // If able to open Service Control Manager to create service, SC_HANDLE scm_create = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (scm_create) { char path[MAX_PATH+1]; // Get the path to this executable module DWORD len = GetModuleFileNameA(0, path, sizeof(path)); path[sizeof(path) - 1] = '\0'; if (len == strlen(path)) { // Create the service SC_HANDLE svc_create = CreateServiceA(scm_create, _service_name, _service_name, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, path, 0, 0, 0, 0, 0); if (svc_create) { INFO("ServiceManager") << "InstallService(): Starting service"; StartService(svc_create, 0, 0); CloseServiceHandle(svc_create); CloseServiceHandle(scm_create); return true; } else { FATAL("ServiceManager") << "InstallService(): Unable to create service"; } } else { FATAL("ServiceManager") << "InstallService(): Unable to get module file path"; } CloseServiceHandle(scm_create); } else { FATAL("ServiceManager") << "InstallService(): Unable to create Service Control Manager"; } return false; } bool WindowsService::RemoveService() { // If able to open Service Control Manager to create service, SC_HANDLE scm_remove = OpenSCManager(0, 0, STANDARD_RIGHTS_REQUIRED); if (scm_remove) { // If service already exists, SC_HANDLE svc_remove = OpenServiceA(scm_remove, _service_name, SERVICE_STOP | DELETE); if (svc_remove) { SERVICE_STATUS status; ControlService(svc_remove, SERVICE_CONTROL_STOP, &status); if (DeleteService(svc_remove)) { CloseServiceHandle(svc_remove); CloseServiceHandle(scm_remove); return true; } else { FATAL("ServiceManager") << "RemoveService(): Unable to delete service, error " << GetLastError(); } CloseServiceHandle(svc_remove); } else { FATAL("ServiceManager") << "RemoveService(): Unable to open service for deletion, error " << GetLastError(); } CloseServiceHandle(scm_remove); } else { FATAL("ServiceManager") << "RemoveService(): Unable to open Service Control Manager, error " << GetLastError(); } return false; } bool WindowsService::StartServiceMain() { _quit_handle = CreateEvent(0, FALSE, FALSE, 0); if (!_quit_handle) { FATAL("ServiceManager") << "StartServiceMain(): Unable to create quit event"; return false; } SERVICE_TABLE_ENTRYA table[] = { { (LPSTR)WindowsService::ii->_service_name, ServiceMain }, { 0, 0 } }; if (!StartServiceCtrlDispatcherA(table)) { FATAL("ServiceManager") << "StartServiceMain(): Unable to start service control dispatcher"; return false; } return true; } void WindowsService::OnControl(DWORD fdwControl) { switch (fdwControl) { case SERVICE_CONTROL_PAUSE: Pause(); break; case SERVICE_CONTROL_CONTINUE: Continue(); break; case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: Shutdown(); break; } } void WindowsService::OnMain(DWORD dwNumServicesArgs, LPSTR *lpServiceArgVectors) { _service_handle = RegisterServiceCtrlHandlerA(_service_name, ServiceHandler); if (!_service_handle) { FATAL("ServiceManager") << "ServiceMain(): Unable to register control handler for " << _service_name; return; } Startup(); // Wait until quit object is signaled WaitForSingleObject(_quit_handle, INFINITE); } void WINAPI WindowsService::ServiceHandler(DWORD fdwControl) { WindowsService::ii->OnControl(fdwControl); } void WINAPI WindowsService::ServiceMain(DWORD dwNumServicesArgs, LPSTR *lpServiceArgVectors) { WindowsService::ii->OnMain(dwNumServicesArgs, lpServiceArgVectors); } void WindowsService::SetState(DWORD state) { if (_service_handle) { SERVICE_STATUS serv_status; CAT_OBJCLR(serv_status); serv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serv_status.dwCurrentState = state; serv_status.dwControlsAccepted = SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP; SetServiceStatus(_service_handle, &serv_status); } } //// Service Events void WindowsService::Startup() { SetState(SERVICE_START_PENDING); _server = new ZoneDatabaseServer; if (!_server) { Shutdown(); return; } if (!_server->Initialize()) { Shutdown(); return; } SetState(SERVICE_RUNNING); } void WindowsService::Shutdown() { SetState(SERVICE_STOP_PENDING); // If server is started, if (_server) { _server->Shutdown(); _server = 0; } SetEvent(_quit_handle); // Need to set state to stopped or else application will never terminate SetState(SERVICE_STOPPED); } void WindowsService::Pause() { SetState(SERVICE_PAUSE_PENDING); if (_server) { _server->Pause(); } SetState(SERVICE_PAUSED); } void WindowsService::Continue() { SetState(SERVICE_CONTINUE_PENDING); if (_server) { _server->Continue(); } SetState(SERVICE_RUNNING); }
[ "kuang@.(none)" ]
[ [ [ 1, 356 ] ] ]
2387064c785b9d1c58493343b1a1c758dc379df3
ee2e06bda0a5a2c70a0b9bebdd4c45846f440208
/c++/Pattern/Source/Builder/Builder.h
0077bbe6b7ada2033fd9b9c43ed1d845d913b21b
[]
no_license
RobinLiu/Test
0f53a376e6753ece70ba038573450f9c0fb053e5
360eca350691edd17744a2ea1b16c79e1a9ad117
refs/heads/master
2021-01-01T19:46:55.684640
2011-07-06T13:53:07
2011-07-06T13:53:07
1,617,721
2
0
null
null
null
null
GB18030
C++
false
false
1,510
h
/******************************************************************** created: 2006/07/19 filename: Builder.h author: 李创 http://www.cppblog.com/converse/ purpose: Builder模式的演示代码 *********************************************************************/ #ifndef BUILDER_H #define BUILDER_H // 虚拟基类,是所有Builder的基类,提供不同部分的构建接口函数 class Builder { public: Builder(){}; virtual ~Builder(){} // 纯虚函数,提供构建不同部分的构建接口函数 virtual void BuilderPartA() = 0; virtual void BuilderPartB() = 0; }; // 使用Builder构建产品,构建产品的过程都一致,但是不同的builder有不同的实现 // 这个不同的实现通过不同的Builder派生类来实现,存有一个Builder的指针,通过这个来实现多态调用 class Director { public: Director(Builder* pBuilder); ~Director(); void Construct(); private: Builder* m_pBuilder; }; // Builder的派生类,实现BuilderPartA和BuilderPartB接口函数 class ConcreateBuilder1 : public Builder { public: ConcreateBuilder1(){} virtual ~ConcreateBuilder1(){} virtual void BuilderPartA(); virtual void BuilderPartB(); }; // Builder的派生类,实现BuilderPartA和BuilderPartB接口函数 class ConcreateBuilder2 : public Builder { public: ConcreateBuilder2(){} virtual ~ConcreateBuilder2(){} virtual void BuilderPartA(); virtual void BuilderPartB(); }; #endif
[ "[email protected]@43938a50-64aa-11de-9867-89bd1bae666e" ]
[ [ [ 1, 63 ] ] ]
0f78fc58a3c143cafe056113f3fb66239d763328
460d5c0a45d3d377bfc4ce71de99f4abc517e2b6
/Proj2/player.cpp
fd58d200738a7a2c77b600c4e1da9c8861f976b5
[]
no_license
wilmer/CS211
3ba910e9cc265ca7e3ecea2c71cf1246d430f269
1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0
refs/heads/master
2020-12-25T09:38:34.633541
2011-03-06T04:53:54
2011-03-06T04:53:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,445
cpp
#include "player.h" #include <iomanip> using namespace std; player::player() //Constructor { count = 0; } bool player::bePlayed(crazy8card c1, crazy8card c2) //pre:none //post: returns true or false if a card can legally be played { return c1.bePlayed(c1, c2); } void player::takeCard(crazy8card cards) //pre:none //post: count of cards increased by one, card is added to hand { ++count; hand[count] = cards; } crazy8card player::pickCard(int cardnum) //pre: none //post: returns a card { return (hand[cardnum]); } crazy8card player::playCard() //pre: player has chosen to play a card //post: chosen card is returned and hand count is decremented by one { int cardnum; crazy8card temp; cout << endl << "Choose card # to play:" << endl; cin >> cardnum; assert (cardnum <= count); //swap card choice with card at end of hand temp = hand[count]; hand[count] = hand[cardnum]; hand[cardnum] = temp; --count; return (hand[count+1]); } crazy8card player::compcard(int cardnum) //pre: computer strategy determines a card can be played //post: a card is returned and the count is decremented by one { crazy8card temp; temp = hand[count]; hand[count] = hand[cardnum]; hand[cardnum] = temp; --count; return (hand[count+1]); } void player::restore() //restores the count when a card can't be played //pre: none //post: count increased by one { count++; } void player::print() //pre: none //post: cards in hand are output to screen { int i; cout << setw(2) << " # " << "Card" << endl; for (i = 1; i <= count; i++) { cout << setw(2) << i << " "; cout << getHand(i); } } crazy8card player::getHand(int cardnum) //pre: none //post: returns a particular card { return hand[cardnum]; } int player::getHandVal(int cardnum) //pre: none //post: returns the value of a particular card { return hand[cardnum].getValue(); } void player::getHandSuit(int cardnum) //pre: none //post: returns the suit of a particular card { hand[cardnum].getSuit(); } int player::getCount() //pre: none //post: returns the current # of cards in a hand { return count; } void player::chgSuit(char suite) //pre: an 8 has been played //post: the suit of the card is changed { hand[count].chgSuit(suite); }
[ [ [ 1, 118 ] ] ]
8ecccd25ef10b800fb93e800aa444bc46167767c
96f796a966025265020459ca2a38346c3c292b1e
/Ansoply/stdafx.h
248819887ef8e8c121218de409cb2e014d9dc5ec
[]
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
1,694
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef STRICT #define STRICT #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. #define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 2000 or later. #endif #ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. #define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif #define _ATL_APARTMENT_THREADED #define _ATL_NO_AUTOMATIC_NAMESPACE #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off ATL's hiding of some common and often safely ignored warning messages #define _ATL_ALL_WARNINGS #define __AFX_H__ #include <atlbase.h> #include <atlcom.h> #include <atlwin.h> #include <atltypes.h> #include <atlctl.h> #include <atlhost.h> #include <atlcoll.h> #include "error.h" using namespace ATL;
[ "Gmagic10@26f92a05-6149-0410-981d-7deb1f891687" ]
[ [ [ 1, 50 ] ] ]
fc7736690f16d30906450788e36c630d5a117e0f
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/LayoutEditor/TestState.cpp
94dd1ccb34a52795ecc06b7b0d34bc98ff47bac0
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,675
cpp
/*! @file @author Albert Semenov @date 08/2010 */ #include "precompiled.h" #include "TestState.h" #include "CommandManager.h" #include "StateManager.h" #include "DialogManager.h" #include "MessageBoxManager.h" #include "EditorWidgets.h" #include "WidgetSelectorManager.h" namespace tools { TestState::TestState() { CommandManager::getInstance().registerCommand("Command_Quit", MyGUI::newDelegate(this, &TestState::commandQuit)); } TestState::~TestState() { } void TestState::initState() { MyGUI::xml::Document* mTestLayout = EditorWidgets::getInstance().savexmlDocument(); EditorWidgets::getInstance().clear(); EditorWidgets::getInstance().loadxmlDocument(mTestLayout, true); WidgetSelectorManager::getInstance().setSelectedWidget(nullptr); } void TestState::cleanupState() { MyGUI::xml::Document* mTestLayout = EditorWidgets::getInstance().savexmlDocument(); EditorWidgets::getInstance().clear(); EditorWidgets::getInstance().loadxmlDocument(mTestLayout, false); WidgetSelectorManager::getInstance().setSelectedWidget(nullptr); } void TestState::pauseState() { } void TestState::resumeState() { } void TestState::commandQuit(const MyGUI::UString& _commandName) { if (!checkCommand()) return; StateManager::getInstance().stateEvent(this, "Exit"); } bool TestState::checkCommand() { if (DialogManager::getInstance().getAnyDialog()) return false; if (MessageBoxManager::getInstance().hasAny()) return false; if (!StateManager::getInstance().getStateActivate(this)) return false; return true; } } // namespace tools
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 75 ] ] ]
f575bcc5ebdf05719e704a36f651a80baa708ded
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/SplitterFilter/SplitterFilterApp.cpp
08e510a5058b252404efd8f5b583a9134a5b1ae0
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
2,097
cpp
// SplitterFilter.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "SplitterFilterApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // //TODO: If this DLL is dynamically linked against the MFC DLLs, // any functions exported from this DLL which call into // MFC must have the AFX_MANAGE_STATE macro added at the // very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // HMODULE g_hModule = 0; extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); extern "C" BOOL WINAPI _DllMainCRTStartup(HINSTANCE, ULONG, LPVOID); HMODULE GetModule() { return g_hModule; } BOOL APIENTRY FilterDllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: g_hModule = hModule; break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } _DllMainCRTStartup((HINSTANCE)hModule, dwReason, lpReserved); return DllEntryPoint((HINSTANCE)(hModule), dwReason, lpReserved); } // CSplitterFilterApp BEGIN_MESSAGE_MAP(CSplitterFilterApp, CWinApp) END_MESSAGE_MAP() // CSplitterFilterApp construction CSplitterFilterApp::CSplitterFilterApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CSplitterFilterApp object CSplitterFilterApp theApp; // CSplitterFilterApp initialization BOOL CSplitterFilterApp::InitInstance() { CWinApp::InitInstance(); return TRUE; }
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 95 ] ] ]
25a2103b68d1d57103f9285d7e03999bf6ac94af
674dbf23a55b4920285086b6d4cda1fc0fb36188
/src/SplashKit/Host/MainWindow.h
48ea3543cd9d37308b154da6ce0f68706036e1a9
[]
no_license
alexdmark/splashkit
077f0c472f7efb00fc9eb8d79b6ee852c959fa3c
189c3450d7d27a652315ffa4abbae6a8aafc1c82
refs/heads/master
2021-01-15T13:11:21.104879
2010-07-19T09:28:34
2010-07-19T09:28:34
35,467,492
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
h
#pragma once #include <Windows.h> #include <WebKit/WebKit.h> #include <WebKit/WebKitCOMAPI.h> #include <JavaScriptCore/JavaScript.h> #include <commctrl.h> #include <commdlg.h> #include <objbase.h> #include <shlwapi.h> #include <wininet.h> #include "../Resources/Resource.h" #include <atlbase.h> #include <string> #include "IWindow.h" #include "ApplicationRuntime.h" #include "ApplicationConfiguration.h" #include "../Browser/Page.h" class MainWindow : public IWindow { private: HINSTANCE _hInstance; HWND _hMainWnd; long _DefEditProc; IWebView* _webView; HWND _viewWindow; bool _isShown; ApplicationConfiguration *_configuration; protected: public: MainWindow(ApplicationRuntime *instance, ApplicationConfiguration *configuration); ~MainWindow(void); void Navigate(Page *page); void Navigate(string *str); void Navigate(LPCSTR str); virtual bool HandleMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void Show(); };
[ "paul@localhost" ]
[ [ [ 1, 44 ] ] ]
03e6df18dd1d35a8016e3e70e4c514b453b9a23b
22575f4bfceb68b4ca9b5c1146dd86ca4bd5c4ed
/include/zamara/mpq/mpq_hash_entry.h
1d0a875d153b4a235e4002282eb6b573e5bbb879
[ "BSD-2-Clause" ]
permissive
aphistic/zamara
b4ef491949c02b65b164a2bff3ea9d2f349457c6
c2a587bd8281540b4083ec5bcc47d992f1e75bf7
refs/heads/master
2016-09-05T11:28:11.983667
2011-12-09T03:37:13
2011-12-09T03:37:13
2,944,990
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
h
/* Zamara Library * Copyright (c) 2011, Erik Davidson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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 ZAMARA_MPQ_MPQ_HASH_ENTRY_H_ #define ZAMARA_MPQ_MPQ_HASH_ENTRY_H_ #include <stdint.h> namespace zamara { namespace mpq { class MpqHashEntry { public: MpqHashEntry(); ~MpqHashEntry(); void Load(char* buffer); void set_file_path_hash_a(uint32_t hash); uint32_t file_path_hash_a(); void set_file_path_hash_b(uint32_t hash); uint32_t file_path_hash_b(); void set_language(uint16_t language); uint16_t language(); void set_platform(uint16_t platform); uint16_t platform(); void set_block_index(uint32_t block_index); uint32_t block_index(); private: uint32_t file_path_hash_a_; uint32_t file_path_hash_b_; uint16_t language_; uint16_t platform_; uint32_t block_index_; }; } } #endif // ZAMARA_MPQ_MPQ_HASH_ENTRY_H_
[ [ [ 1, 74 ] ] ]
5d67a580e71009b0648dc072f85de8ed8c35ba9c
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Com/ScdMdl/ScdSpecieDefns.h
8fad9b83531d7090171d75ad6bb8398be11d3b11
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,193
h
// ScdSpecieDefns.h : Declaration of the CScdSpecieDefns #ifndef __SCDSPECIES_H_ #define __SCDSPECIES_H_ #include "resource.h" //#include "vector" ///////////////////////////////////////////////////////////////////////////// // CScdSpecieDefns class ATL_NO_VTABLE CScdSpecieDefns : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CScdSpecieDefns, &CLSID_ScdSpecieDefns>, public ISupportErrorInfo, public IConnectionPointContainerImpl<CScdSpecieDefns>, public IDispatchImpl<IScdSpecieDefns, &IID_IScdSpecieDefns, &LIBID_ScdMdl> { public: CScdSpecieDefns() { m_pUnkMarshaler = NULL; } DECLARE_REGISTRY_RESOURCEID(IDR_SCDSPECIEDEFNS) DECLARE_GET_CONTROLLING_UNKNOWN() DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CScdSpecieDefns) COM_INTERFACE_ENTRY(IScdSpecieDefns) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IConnectionPointContainer) COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CScdSpecieDefns) END_CONNECTION_POINT_MAP() DECLARE_SCD(long); HRESULT FinalConstruct() { // delay creation of m_Spcs until SpecieDB Inited return CoCreateFreeThreadedMarshaler( GetControllingUnknown(), &m_pUnkMarshaler.p); } void FinalRelease() { m_pUnkMarshaler.Release(); for (long i=0; i<m_Spcs.GetSize(); i++) m_Spcs[i]->Release(); } CComPtr<IUnknown> m_pUnkMarshaler; CArray <LPDISPATCH, LPDISPATCH> m_Spcs; // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IScdSpecieDefns public: STDMETHOD(Specie)(VARIANT WhichOne, IScdSpecieDefn** pItem); STDMETHOD(get__NewEnum)(LPUNKNOWN *pVal); STDMETHOD(get_Count)(LONG * pVal); STDMETHOD(get_SomAll)(LONG * pVal); STDMETHOD(get_SomVap)(LONG * pVal); STDMETHOD(get_SomLiq)(LONG * pVal); STDMETHOD(get_SomSol)(LONG * pVal); STDMETHOD(get_SomSL)(LONG * pVal); STDMETHOD(get_Phases)(LONG ReqdPhases, SAFEARRAY * * pVal); STDMETHOD(get_MolecularWeights)(SAFEARRAY * * pVal); }; #endif //__SCDSPECIES_H_
[ [ [ 1, 76 ] ] ]
94eef33a25c9f74dcca2ded4e751fb1c2036b019
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/idechoserver.hpp
ebfc7b7ba7261fa951f51bf5ccb43a2b06a0cd94
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
1,617
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IdEchoServer.pas' rev: 6.00 #ifndef IdEchoServerHPP #define IdEchoServerHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <IdComponent.hpp> // Pascal unit #include <IdTCPServer.hpp> // Pascal unit #include <IdGlobal.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idechoserver { //-- type declarations ------------------------------------------------------- class DELPHICLASS TIdECHOServer; class PASCALIMPLEMENTATION TIdECHOServer : public Idtcpserver::TIdTCPServer { typedef Idtcpserver::TIdTCPServer inherited; protected: virtual bool __fastcall DoExecute(Idtcpserver::TIdPeerThread* AThread); public: __fastcall virtual TIdECHOServer(Classes::TComponent* AOwner); __published: __property DefaultPort = {default=7}; public: #pragma option push -w-inl /* TIdTCPServer.Destroy */ inline __fastcall virtual ~TIdECHOServer(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Idechoserver */ using namespace Idechoserver; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdEchoServer
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 55 ] ] ]
00035950d78f77912712420bb56cb2149023ce60
028d6009f3beceba80316daa84b628496a210f8d
/uidesigner/com.nokia.sdt.referenceprojects.test/data2/empty_container_3_0/reference/inc/empty_container_3_0AppUi.h
caa2d8a55e9c7b57bfc3c0c41d534391a33c7114
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,705
h
#ifndef EMPTY_CONTAINER_3_0APPUI_H #define EMPTY_CONTAINER_3_0APPUI_H // [[[ begin generated region: do not modify [Generated Includes] #include <aknviewappui.h> // ]]] end generated region [Generated Includes] // [[[ begin generated region: do not modify [Generated Forward Declarations] class CEmptyContainerView; // ]]] end generated region [Generated Forward Declarations] /** * @class Cempty_container_3_0AppUi empty_container_3_0AppUi.h * @brief The AppUi class handles application-wide aspects of the user interface, including * view management and the default menu, control pane, and status pane. */ class Cempty_container_3_0AppUi : public CAknViewAppUi { public: // constructor and destructor Cempty_container_3_0AppUi(); virtual ~Cempty_container_3_0AppUi(); void ConstructL(); public: // from CCoeAppUi TKeyResponse HandleKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ); // from CEikAppUi void HandleCommandL( TInt aCommand ); void HandleResourceChangeL( TInt aType ); // from CAknAppUi void HandleViewDeactivation( const TVwsViewId& aViewIdToBeDeactivated, const TVwsViewId& aNewlyActivatedViewId ); private: void InitializeContainersL(); // [[[ begin generated region: do not modify [Generated Methods] public: // ]]] end generated region [Generated Methods] // [[[ begin generated region: do not modify [Generated Instance Variables] private: CEmptyContainerView* iEmptyContainerView; // ]]] end generated region [Generated Instance Variables] // [[[ begin [User Handlers] protected: // ]]] end [User Handlers] }; #endif // EMPTY_CONTAINER_3_0APPUI_H
[ [ [ 1, 58 ] ] ]
6feb9c61a298b78eb7831980933893517cafa620
02ecaf771a1997379b7c0ab789b3c76fc84c42f8
/references/mmas/Ant.cpp
3fbb4301719a4c061c7333cf50e765f95eeee0af
[]
no_license
tingyingwu2010/heuristicschallenge
b31a8f7dd8a2a0ca83ec5d77ecce394760fe512c
b69f534a3b641888e45f2466276743a7237e6bbb
refs/heads/master
2021-05-27T19:53:39.500569
2008-08-01T04:42:56
2008-08-01T04:42:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
/*************************************************************************** Ant.cpp - Implementation of the ant. ------------------- begin : Sun Mar 10, 2002 copyright : (C) 2002 by Krzysztof Socha email : [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. * * * ***************************************************************************/ #include "Ant.h" Ant::Ant(MMAsProblem* problem, Random *rnd) { // memeber variables initialization this->problem = problem; solution = new Solution(problem,rnd); fitness = -1; } Ant::~Ant() { delete solution; } void Ant::Move() { // itarate through all the events to complete the path for (int i=0;i<problem->n_of_events;i++) { // chose next event from the list int e = problem->sorted_event_list[i]; // finding the range for normalization double range = 0.0; for (int j=0;j<N_OF_TIMESLOTS;j++) range += problem->event_timeslot_pheromone[e][j]; // choose a random number between 0.0 and sum of the pheromone level // for this event and current sum of heuristic information double rnd = solution->rg->next() * range; // choose a timeslot for the event based on the pheromone table and the random number double total = 0.0; int timeslot = -1; for(int j=0;j<N_OF_TIMESLOTS;j++) { // check the pheromone total += problem->event_timeslot_pheromone[e][j]; if (total>=rnd) { timeslot = j; break; } } // put an event i into timeslot t solution->sln[e].first = timeslot; solution->timeslot_events[timeslot].push_back(e); } // assign rooms to events in each non-empty timeslot for(int i=0;i<N_OF_TIMESLOTS;i++) if((int)solution->timeslot_events[i].size()) solution->assignRooms(i); } void Ant::depositPheromone() { // calculate pheromone update for (int i=0;i<problem->n_of_events;i++) { int timeslot = solution->sln[i].first; problem->event_timeslot_pheromone[i][timeslot] += 1.0; } } int Ant::computeFitness() { // simple fitness function fitness = solution->computeHcv(); return fitness; }
[ "pedro@pedro-laptop.(none)" ]
[ [ [ 1, 85 ] ] ]
c6af8bd67c537bfa545d13711be1a730e69cf57e
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/idwhoisserver.hpp
39d09051817058ea04bddda0fbeac97d868cccc6
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
1,857
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IdWhoIsServer.pas' rev: 6.00 #ifndef IdWhoIsServerHPP #define IdWhoIsServerHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <IdComponent.hpp> // Pascal unit #include <IdTCPServer.hpp> // Pascal unit #include <IdGlobal.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idwhoisserver { //-- type declarations ------------------------------------------------------- typedef void __fastcall (__closure *TGetEvent)(Idtcpserver::TIdPeerThread* AThread, AnsiString ALookup); class DELPHICLASS TIdWhoIsServer; class PASCALIMPLEMENTATION TIdWhoIsServer : public Idtcpserver::TIdTCPServer { typedef Idtcpserver::TIdTCPServer inherited; protected: TGetEvent FOnCommandLookup; virtual bool __fastcall DoExecute(Idtcpserver::TIdPeerThread* AThread); public: __fastcall virtual TIdWhoIsServer(Classes::TComponent* AOwner); __published: __property TGetEvent OnCommandLookup = {read=FOnCommandLookup, write=FOnCommandLookup}; __property DefaultPort = {default=43}; public: #pragma option push -w-inl /* TIdTCPServer.Destroy */ inline __fastcall virtual ~TIdWhoIsServer(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Idwhoisserver */ using namespace Idwhoisserver; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdWhoIsServer
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 59 ] ] ]
241037ecae84a4b74726163ee7c3bca6f66f1a1b
971b000b9e6c4bf91d28f3723923a678520f5bcf
/fop_miniscribus.1.0.0/fop_lib/fop_handler.cpp
e1130d1d208edaf1cc2d8dcbd698fddea567832a
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
70,766
cpp
#include "fop_handler.h" /* paragraph fop -> qt */ void Fop_Handler::ParserParagraph( const QDomElement e , QTextDocument * d , Fop_Layer * layer , int CursorPositon , bool firsttdcell ) { /////if (FoTag(e.firstChild().toElement()) != BLOCK_TAG) { //////////ParserParagraph(e.firstChild().toElement(),d,layer,0); ///////// } if (FoTag(e) != BLOCK_TAG) { return; } ParaGraphCounter++; Fop_Block *foppi = new Fop_Block(ParaGraphCounter,e); int CursorEndPosition = 0; bool IsOnTable = false; const QString Actual_Line_Text = e.text(); QTextCursor Tcursor = QTextCursor(d); bool IsCorrectCursor = Tcursor.movePosition(QTextCursor::End); CursorEndPosition = Tcursor.position(); ///////qDebug() << "### ParserParagraph ### (" << e.tagName().toLower() << " txt->" << Actual_Line_Text << " nr." << ParaGraphCounter << " cursorP->" << CursorPositon << " cursor_end->" << CursorEndPosition << ")"; /* elements not on block format fop */ if (CursorPositon !=0) { ////////qDebug() << "### ParserParagraph cursor 1 ### from CursorPositon "; Tcursor.setPosition(CursorPositon); } else if (CursorStatementPosition > 4 ) { //////qDebug() << "### ParserParagraph cursor 2 ### from CursorStatementPosition "; Tcursor.setPosition(CursorStatementPosition); /* the last end from paragraph line or table cell paragraph ! */ } else { //////qDebug() << "### ParserParagraph cursor 3 ### from goto end document "; Tcursor.setPosition(CursorEndPosition); /* end of document if no ram position */ } QTextBlockFormat GlobalZeroMargin = DefaultMargin(); /* default QTextBlockFormat */ QTextBlockFormat EntireBlockFormat = TextBlockFormFromDom(e,GlobalZeroMargin); /* overwrite */ QTextCharFormat ParCharFormat = GlobalCharFormat(e); ParCharFormat.setToolTip ( foppi->Get_XML() ); if (CursorEndPosition !=0 && !firsttdcell ) { Tcursor.insertBlock(); } /* Tcursor.beginEditBlock(); Tcursor.setBlockFormat(EntireBlockFormat); Tcursor.insertText(Actual_Line_Text+QString(" -%1-").arg(ParaGraphCounter)); Tcursor.endEditBlock(); */ Tcursor.beginEditBlock(); QTextBlock blockNow = Tcursor.block(); blockNow.setUserData(foppi); /* fop source original to show */ Tcursor.setBlockFormat(EntireBlockFormat); Tcursor.setCharFormat(ParCharFormat); if (ParaGraphCounter == 1) { Tcursor.insertText("",targetAnchor); /* layer destination link #layernummer */ } QDomNode child = e.firstChild(); while ( !child.isNull() ) { if ( child.isElement() ) { const QDomElement childElement = child.toElement(); const QTextCharFormat InlineStyle = GlobalCharFormat(childElement); if ( FoTag(childElement) == INLINE_STYLE) { Tcursor.setCharFormat(InlineStyle); Tcursor.insertText(childElement.text().replace("\n"," ")); Tcursor.insertText(""); Tcursor.setCharFormat(ParCharFormat); } else if ( FoTag(childElement) == LINK_DOC ) { Tcursor.setCharFormat(InlineStyle); Tcursor.insertText(childElement.text().replace("\n"," ")); Tcursor.setCharFormat(ParCharFormat); } else if ( FoTag(childElement) == FOCHAR ) { Tcursor.setCharFormat(InlineStyle); Tcursor.insertText(childElement.attribute ("character")); Tcursor.setCharFormat(ParCharFormat); } else if ( FoTag(childElement) == TABLE_TAG ) { Tcursor.setBlockFormat(DefaultMargin()); ParserTable(childElement,d,layer,Tcursor.position()); } else if ( FoTag(childElement) == BLOCK_TAG ) { ParserParagraph(childElement,d,layer,Tcursor.position()); /* only block/block loops */ } else if ( FoTag(childElement) == IMAGE_SRC ) { Tcursor.setBlockFormat(DefaultMargin()); ImageParserTag(childElement,d,layer,Tcursor.position()); /* fo:external-graphic */ } else if ( FoTag(childElement) == IMAGE_INLINE ) { Tcursor.setBlockFormat(DefaultMargin()); ObjectParserTag(childElement,d,layer,Tcursor.position()); /* inline svg images */ } } else if (child.isText()) { const QString FragText = child.toText().data().replace("\n"," "); if (FragText.size() > 0) { Tcursor.insertText(FragText); } else { Tcursor.insertText("error null text "); } Tcursor.setCharFormat(ParCharFormat); } child = child.nextSibling(); } Tcursor.endEditBlock(); Tcursor.atBlockEnd(); /* bring cursor on the same end line block ! not new line */ if (firsttdcell) { CursorStatementPosition = Tcursor.position(); /* latest cursor position */ } else { CursorStatementPosition = 0; } } /* paragraph qt -> fop */ void Fop_Handler::HandleBlock( QTextBlock para , QDomElement appender ) { if (!para.isValid()) { return; } const QString Actual_Text_Param = para.text(); QTextBlockFormat ParaBlockFormat = para.blockFormat(); const QTextCharFormat CharFromPara = para.charFormat(); QDomElement paragraph; QTextImageFormat Pics; QTextTableFormat Tabl; QTextListFormat Uls; QTextCharFormat paraformats; QString newnameimage; QString ImageFilename; int positioner = -1; paragraph = wdoc.createElement("fo:block"); PaintFopBlockFormat(paragraph,ParaBlockFormat); /* block */ PaintCharFormat(paragraph,CharFromPara); //////////////qDebug() << "### open block fo:block .................................."; QTextBlock::iterator de; for (de = para.begin(); !(de.atEnd()); ++de) { QTextFragment fr = de.fragment(); if (fr.isValid()) { positioner++; bool tisalviono; const QTextCharFormat base = fr.charFormat(); int staycursorpos = fr.position(); Pics = base.toImageFormat(); Tabl = base.toTableFormat(); Uls = base.toListFormat(); /* ############################### Image blocks ###########################################*/ /* ############################### Image blocks ###########################################*/ if (Pics.isValid()) { const QString hrefadress = Pics.name(); if (hrefadress.startsWith("/svg/",Qt::CaseInsensitive)) { /* difference only dwo way vector and other as png! */ newnameimage = FilenameAllow( hrefadress + ".svg"); } else { newnameimage = FilenameAllow( hrefadress + ".png"); } ImageFilename = newnameimage; newnameimage = newnameimage.prepend(ImageFopBaserRefDir); QFileInfo PictureonDisc( newnameimage ); if (!hrefadress.contains("instream")) { if (!PictureonDisc.exists()) { tisalviono = SaveImageExterPath(hrefadress,newnameimage); } else { tisalviono = true; } QDomElement imageELO = wdoc.createElement("fo:external-graphic"); imageELO.setAttribute ("src",FOPIMAGEDIR + ImageFilename); if (Pics.width() > 0) { imageELO.setAttribute ("width",QString("%1pt").arg(Pics.width())); } if (Pics.height() > 0) { imageELO.setAttribute ("height",QString("%1pt").arg(Pics.height())); } /* if saved image append */ if (tisalviono) { paragraph.appendChild(imageELO); } //////////qDebug() << "### salvataggio di -> " << ImageFilename << " si/no->" << aisalvato; } else if (hrefadress.contains("SVG_instream-foreign-object")) { QDomElement imageinline = wdoc.createElement("fo:instream-foreign-object"); /* svg inline */ if (Pics.width() > 0) { imageinline.setAttribute ("width",QString("%1pt").arg(Pics.width())); } if (Pics.height() > 0) { imageinline.setAttribute ("height",QString("%1pt").arg(Pics.height())); } /* lets grab xml from vector image */ bool takesvghaving = BuildSvgInlineonDom(hrefadress,imageinline,wdoc); if (takesvghaving) { paragraph.appendChild(imageinline); } } /* ############################### Image blocks ###########################################*/ /* ############################### Image blocks ###########################################*/ } else if (Tabl.isValid()) { //////qDebug() << "### Table "; //////////QTextTable *childTable = qobject_cast<QTextTable*>(fr); ///////////HandleTable( QTextTable * childTable ,paragraph); /////////HandleTable(childTable,paragraph); } else if (Uls.isValid()) { ////////qDebug() << "### List "; } else if (base.isAnchor()) { /* link normal */ QDomElement linkers = wdoc.createElement("fo:basic-link"); if ( !base.anchorHref().startsWith("#") ) { linkers.setAttribute ("external-destination",base.anchorHref()); } else { linkers.setAttribute ("internal-destination",base.anchorHref()); } linkers.setAttribute ("color","red"); linkers.setAttribute ("text-decoration","underline"); /* text-decoration="underline" */ QDomText linktext = wdoc.createTextNode(fr.text()); linkers.appendChild(linktext); paragraph.appendChild(linkers); } else if (CharFromPara !=base) { /* found diffs from fragment to paragraph ... */ if (Actual_Text_Param == fr.text()) { PaintCharFormat(paragraph,base); paragraph.appendChild(wdoc.createTextNode(fr.text())); } else { QDomElement inlinestyle = wdoc.createElement("fo:inline"); PaintCharFormat(inlinestyle,base); QDomText normaltext = wdoc.createTextNode(fr.text()); inlinestyle.appendChild(normaltext); paragraph.appendChild(inlinestyle); } } else { /* charformat from block text is same as fragment */ QString txtfrag = fr.text(); if (txtfrag.size() > 0) { ////////////qDebug() << "### not on fragment 3/4 -> " << txtfrag; } paragraph.appendChild(wdoc.createTextNode(txtfrag)); } } else { /////////////qDebug() << "### unknow out QTextFragment "; } } /////////qDebug() << "### close block fo:block .................................."; appender.appendChild(paragraph); ////////////appender.appendChild( param ); /* append result from this block */ } /* qt -> fop*/ void Fop_Handler::HandleTable( QTextTable * childTable , QDomElement appender ) { const int coolsums = childTable->columns(); QTextTableFormat tbforms = childTable->format(); const QString TablebackgroundColor = tbforms.background().color().name(); QDomElement toptable = wdoc.createElement("fo:table"); toptable.setAttribute ("table-layout","fixed"); toptable.setAttribute ("background-color",TablebackgroundColor); appender.appendChild(toptable); QVector<QTextLength> constraints = tbforms.columnWidthConstraints(); qreal pageMin = FopInt("17cm"); qreal onfixcolumsMinimum = pageMin / coolsums; qreal tablewithd = 0; for (int i = 0; i < coolsums; ++i) { const QTextLength length = constraints.at(i); qreal lenghs = length.rawValue(); QDomElement cools = wdoc.createElement("fo:table-column"); if (length.type() == QTextLength::FixedLength) { cools.setAttribute ("column-width",QString("%1pt").arg(lenghs)); tablewithd +=lenghs; } else { /* xsl-fo dont having % onfixcolumsMinimum */ cools.setAttribute ("column-width",QString("%1pt").arg(onfixcolumsMinimum)); tablewithd +=onfixcolumsMinimum; } toptable.appendChild(cools); } toptable.setAttribute ("width",QString("%1pt").arg(tablewithd)); QDomElement tbody = wdoc.createElement("fo:table-body"); tbody.setAttribute ("background-color",TablebackgroundColor); tbody.setAttribute ("cell-space",QString("%1pt").arg(tbforms.cellSpacing())); /* QString("%1pt").arg(tbforms.cellSpacing()) */ tbody.setAttribute ("padding-start",QString("%1pt").arg(tbforms.cellPadding())); tbody.setAttribute ("border-width",QString("%1pt").arg(tbforms.border())); toptable.appendChild(tbody); int rowline = childTable->rows(); for (int ttr = 0; ttr < rowline; ++ttr) { bool rowline = true; QDomElement rows = wdoc.createElement("fo:table-row"); for (int ttd = 0; ttd < coolsums; ++ttd) { QTextTableCell cell = childTable->cellAt(ttr, ttd); const int rspan = cell.rowSpan(); const int cspan = cell.columnSpan(); QDomElement celltds = wdoc.createElement("fo:table-cell"); if (cell.format().background().color().name() !=TablebackgroundColor && !cell.format().background().color().name().contains("000000")) { celltds.setAttribute ("background-color",cell.format().background().color().name()); } if (cspan > 1) { ttd = ttd + cspan - 1; celltds.setAttribute ("number-columns-spanned",cspan); } QTextFrame::iterator di; for (di = cell.begin(); !(di.atEnd()); ++di) { QTextFrame *tdFrame = di.currentFrame(); QTextBlock tdpara = di.currentBlock(); if (tdFrame) { HandleFrame(tdFrame,FRAME_TDCELL,celltds); //////////qDebug() << "### cell frame 1#"; } else if (tdpara.isValid()) { HandleBlock(tdpara,celltds); ///////////qDebug() << "### cell block 2 #"; } } if ( cspan > 1 || cspan == 1 ) { rows.appendChild(celltds); } } tbody.appendChild(rows); } } Fop_Handler::Fop_Handler( const QString file , bool modus , PageDB *dbin , QWidget * parent ) { ErrorSumm = 0; db = dbin; BigParent = parent; canContinue = true; ErnoMap.clear(); codecx = QTextCodec::codecForMib(106); /* utf-8 codec to write */ fopinfo = QFileInfo(file); Fopfile = fopinfo.absoluteFilePath(); FopBaserRefDir = fopinfo.absolutePath(); if (!FopBaserRefDir.endsWith("/")) { FopBaserRefDir.append("/"); } ImageFopBaserRefDir = FopBaserRefDir; ImageFopBaserRefDir.append(FOPIMAGEDIR); /////////Cache( ImageFopBaserRefDir ); QString errorStr; int errorLine, errorColumn; remotefilecounter = 0; Fopdevice = new QFile(Fopfile); if (modus) { /* open file */ doc.clear(); if(!Fopdevice->open( QIODevice::ReadOnly ) ) { ErrorSumm++; canContinue = false; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::Fop_Handler / Unable to open file %1").arg(fopinfo.fileName())); Fopdevice->close(); } if (canContinue) { if (!doc.setContent(Fopdevice,false, &errorStr, &errorLine, &errorColumn)) { ErrorSumm++; canContinue = false; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::Fop_Handler / XML error on line %2 column %1 string %3.").arg(fopinfo.fileName()).arg(errorColumn).arg(errorLine).arg(errorStr)); } } } else { /* go to write on file !! */ if (!Fopdevice->open( QFile::WriteOnly | QFile::Text ) ) { ErrorSumm++; canContinue = false; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::Fop_Handler / Unable to write on file %1").arg(fopinfo.fileName())); Fopdevice->close(); } else { Fopdevice->close(); } } if (parent !=0) { //////qDebug() << "### objectName " << parent->objectName(); if (canContinue && modus) { /* continue to open file to read + remote image work on signal */ QTimer::singleShot(110, this, SLOT(CheckRemoteImage())); } } else { if (canContinue && modus) { /* continue to open file to read */ OpenModus(); } } } /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* Init to save new pageitem */ QDomDocument Fop_Handler::GetStructure( QRectF page , QRectF margin , QColor pagebg , const QString PaperName , int pagesum ) { wdoc.clear(); CurrentPrinterNameFormat = PaperName; QDomProcessingInstruction header = wdoc.createProcessingInstruction( "xml",QString("version=\"1.0\" encoding=\"utf-8\"" )); wdoc.appendChild( header ); //////////const QString masterefName = QString("Simple-%1-Page").arg(PaperName); const QString bodyrefName = "PageBody"; QDateTime timer1( QDateTime::currentDateTime() ); /* time root */ QDomElement basexslforoot = wdoc.createElement("fo:root"); basexslforoot.setAttribute ("xmlns:fo","http://www.w3.org/1999/XSL/Format"); basexslforoot.setAttribute ("xmlns:svg","http://www.w3.org/2000/svg"); basexslforoot.setAttribute ("xmlns:cms","http://www.pulitzer.ch/2007/CMSFormat"); basexslforoot.setAttribute ("xmlns:fox","http://xmlgraphics.apache.org/fop/extensions"); QDomElement fopeditor = wdoc.createElement("cms:pager"); fopeditor.setAttribute ("build",timer1.toString(Qt::LocalDate)); if (pagesum !=0) { fopeditor.setAttribute ("pagesumm",pagesum); } fopeditor.setAttribute ("editor",_PROGRAM_NAME_LIB_ ); fopeditor.setAttribute ("printer_format",PaperName); basexslforoot.appendChild( fopeditor ); wdoc.appendChild( basexslforoot ); QDomElement layout = wdoc.createElement("fo:layout-master-set"); basexslforoot.appendChild( layout ); QDomElement pagesetup = wdoc.createElement("fo:simple-page-master"); const qreal TopMargin = margin.x(); const qreal RightMargin = margin.y(); const qreal BottomMargin = margin.width(); const qreal LeftMargin = margin.height(); pagesetup.setAttribute ("master-name",PaperName); pagesetup.setAttribute ("margin-top",QString("%1pt").arg(TopMargin)); pagesetup.setAttribute ("margin-bottom",QString("%1pt").arg(BottomMargin)); pagesetup.setAttribute ("margin-left",QString("%1pt").arg(LeftMargin)); pagesetup.setAttribute ("margin-right",QString("%1pt").arg(RightMargin)); pagesetup.setAttribute ("page-width",QString("%1pt").arg(page.width())); pagesetup.setAttribute ("page-height",QString("%1pt").arg(page.height())); layout.appendChild( pagesetup ); /* margin QRectF margin(top,bottom,right,left); */ /* */ QDomElement rb = wdoc.createElement("fo:region-body"); rb.setAttribute ("margin-top",QString("%1pt").arg(margin.x())); rb.setAttribute ("margin-bottom",QString("%1pt").arg(margin.y())); rb.setAttribute ("margin-left",QString("%1pt").arg(margin.height())); rb.setAttribute ("margin-right",QString("%1pt").arg(margin.width())); rb.setAttribute ("background-color",pagebg.name()); rb.setAttribute ("region-name","xsl-region-body"); pagesetup.appendChild( rb ); QDomElement pageseq1 = wdoc.createElement("fo:page-sequence"); pageseq1.setAttribute ("master-reference",PaperName); basexslforoot.appendChild( pageseq1 ); flowwrite = wdoc.createElement("fo:flow"); flowwrite.setAttribute ("flow-name","xsl-region-body"); pageseq1.appendChild( flowwrite ); if (canContinue) { QByteArray data = wdoc.toByteArray(5); /* tmp write to find error ... */ if (data.size() > 0) { if ( Fopdevice->open( QIODevice::WriteOnly ) ) { Fopdevice->write(data); Fopdevice->close(); } } } return wdoc; } void Fop_Handler::AppendLayer( QDomElement e , QTextDocument * d ) { Cache( ImageFopBaserRefDir ); BigframeProcessing = 0; QTextFrame *Tframe = d->rootFrame(); QChar letter('A' + (qrand() % 26)); QString Alternate = QString("layer%1-%2").arg(letter).arg(qrand() % 255); CurrentIdLayer = e.attribute ("id",Alternate); HandleFrame(Tframe,FRAME_ROOT,e); flowwrite.appendChild(e); //////////IncommingFromLayer = d->clone(); } void Fop_Handler::HandleFrame( QTextFrame * Tframe , FRAME_TYP dd , QDomElement appender ) { BigframeProcessing++; QTextFrame::iterator it; for (it = Tframe->begin(); !(it.atEnd()); ++it) { /* to find tree structure */ QTextFrame *childFrame = it.currentFrame(); QTextBlock para = it.currentBlock(); if (childFrame) { QTextTable *childTable = qobject_cast<QTextTable*>(childFrame); /* if is table */ if (childTable->columns() > 0) { HandleTable(childTable,appender); } } /* param */ if (para.isValid()) { HandleBlock(para,appender); } } if (dd == FRAME_ROOT) { } } void Fop_Handler::Writtelnend() { QByteArray data = wdoc.toByteArray(5); if (data.size() > 0) { if ( Fopdevice->open( QIODevice::WriteOnly ) ) { Fopdevice->write(data); Fopdevice->close(); } } } /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* ################################################ write fop file############################################################*/ /* fop -> qt */ void Fop_Handler::ParserTable( const QDomElement e , QTextDocument * d , Fop_Layer * layer , int CursorPositon ) { if (FoTag(e) != TABLE_TAG) { return; } Fop_Block *foppi = new Fop_Block(imagecounter,e,"fo:table"); /* grep current source to play */ qreal tableborderborder = TakeOneBorder(e); qreal tablewidth = Unit(e.attribute ("width",QString("0"))); QDomElement co = e.parentNode().toElement(); QTextCursor Tcursor = QTextCursor(d); bool IsCorrectCursor = Tcursor.movePosition(QTextCursor::End); int mappos = Tcursor.position(); /* last position from last cursor on class ! */ QTextCursor cellCursor; /* new cursor only for cell tabbing */ QString tatype = e.attribute( "table-layout" ); /* on attribute root table */ QStringList coolsizes; /* grep column size in pt cm mm ecc... */ coolsizes.clear(); QDomElement bodytable = e.firstChildElement("fo:table-body"); int rowCounter = 0; int columnCounter = 0; QDomElement column = e.firstChildElement("fo:table-column"); while (!column.isNull()) { const QString sizefromcool = column.attribute( "column-width" ); if (sizefromcool.size() > 0) { coolsizes.append(sizefromcool); /* append unit widht string 22pt */ } column = column.nextSiblingElement("fo:table-column"); } if (coolsizes.size() > 0) { columnCounter = coolsizes.size(); } QDomElement rows = bodytable.firstChildElement("fo:table-row"); while (!rows.isNull()) { rowCounter++; rows = rows.nextSiblingElement("fo:table-row"); } if (rowCounter < 1) { //////qDebug() << "### false row? " << columnCounter << " list" << coolsizes; return; } ////////qDebug() << "### true row " << columnCounter << " list" << coolsizes; /* #########################base table #######################################*/ QTextTable *qtable = Tcursor.insertTable( rowCounter, columnCounter ); ///////qDebug() << "### parse table... "; ////////qDebug() << "### rowCounter " << rowCounter; ////////qDebug() << "### columnCounter " << columnCounter; QTextTableFormat tableFormat; QString tbg = bodytable.attribute("background-color"); if (tablewidth !=0) { tableFormat.setWidth ( QTextLength ( QTextLength::FixedLength, tablewidth ) ); ///////tableFormat.setHeight ( QTextLength ( QTextLength::FixedLength, tablewidth ) ); } qreal borderDik = TakeOneBorder(bodytable); ////////qDebug() << "### table borderDik " << borderDik; /* qt4 4.3 bug unable to set table border on QGraphicsTextItem */ if (!tbg.isEmpty()) { tableFormat.setBackground ( QColor(tbg) ); } tableFormat.setBorder(borderDik); tableFormat.setCellSpacing(Unit(bodytable.attribute ("cell-space",QString("0")))); tableFormat.setCellPadding(TakeOnePadding(bodytable)); /* colums on mm cm pt <-> */ if (coolsizes.size() > 0) { tableFormat.clearColumnWidthConstraints(); QVector<QTextLength> constraints; for (int i = 0; i < coolsizes.size(); ++i) { const qreal cellmesure = Unit(coolsizes.at(i)); constraints.insert(i,QTextLength(QTextLength::FixedLength, cellmesure )); } tableFormat.setColumnWidthConstraints(constraints); } if (tatype == "fixed") { tableFormat.setAlignment ( Qt::AlignLeft ); } else { tableFormat.setAlignment ( Qt::AlignJustify ); } int qlistlargeNr = -1; /* cell and row count from 0 */ QDomElement setrows = bodytable.firstChildElement("fo:table-row"); while (!setrows.isNull()) { int is_spancol = 0; int startStorno = 0; int stopStorno = 0; bool bypassisactive = false; qlistlargeNr++; QTextBlockFormat tdformat; tdformat.setBottomMargin(0); tdformat.setTopMargin(0); QDomElement columnElement = setrows.firstChildElement(); /* sub element from row */ int columnCounter = -1; /* cell and row count from 0 */ while ( !columnElement.isNull() ) { if ( columnElement.tagName().toLower() == "fo:table-cell" ) { columnCounter++; QTextTableCell cell; is_spancol = columnElement.attribute( "number-columns-spanned" ).trimmed().toInt(); if (is_spancol > 1) { for (int i = 0; i < is_spancol; ++i) { QTextTableCell cellstart = qtable->cellAt( qlistlargeNr , columnCounter + i); QTextCharFormat firster = cellstart.format(); if (!columnElement.attribute("background-color").isEmpty()) { firster.setBackground(QColor(columnElement.attribute("background-color"))); } cellstart.setFormat(firster); } /* point to last cell number-columns-spanned to fill text */ qtable->mergeCells ( qlistlargeNr ,columnCounter,1,is_spancol); cell = qtable->cellAt( qlistlargeNr , columnCounter ); } else { cell = qtable->cellAt( qlistlargeNr , columnCounter ); } Tcursor = cell.firstCursorPosition(); const qreal cellpadding = Unit(columnElement.attribute ("padding",QString("0"))); const qreal cellwidht = Get_Cell_Width(tableFormat,columnCounter); /* paint cell Background and table border here */ QTextCharFormat existformat = cell.format(); if (!columnElement.attribute("background-color").isEmpty()) { existformat.setBackground(QColor(columnElement.attribute("background-color"))); } existformat.setToolTip ( foppi->Get_XML() ); cell.setFormat(existformat); Tcursor = cell.firstCursorPosition(); int FirstcellInitCursor = Tcursor.position(); int blocksDD = 0; QDomElement cellinside = columnElement.firstChildElement("fo:block"); while ( !cellinside.isNull() ) { blocksDD++; if (blocksDD == 1) { ParserParagraph(cellinside,d,layer,FirstcellInitCursor,true); } else { ParserParagraph(cellinside,d,layer,CursorStatementPosition,true); } cellinside = cellinside.nextSiblingElement("fo:block"); } } columnElement = columnElement.nextSiblingElement(); } setrows = setrows.nextSiblingElement("fo:table-row"); } qtable->setFormat( tableFormat ); ActualBackgroundColor = QString(default_background); /* reset color background */ CursorStatementPosition = 0; /* go to end document ! */ } void Fop_Handler::ParserLayerFloating( Fop_Layer * layer , const QDomElement e ) { const QString t = e.tagName().toLower(); if (FoTag(e) !=BLOCK_CONTAINER) { return; } ParaGraphCounter = 0; CursorStatementPosition = 0; qreal wqwi = Unit(e.attribute ("width",QString("500mm"))); int LockStatus = e.attribute ("lock","0").toInt(); int RotateVar = e.attribute ("rotate","0").toInt(); QTextDocument *d = layer->Qdoc(); if (LockStatus !=0) { layer->SetLock(); } if (RotateVar > 0) { layer->SetRotate( RotateVar ); } QTextCursor Tcursor = QTextCursor(d); /* reset cursor to the new layer */ QTextFrame *Tframe = d->rootFrame(); QTextFrameFormat rootformats = Tframe->frameFormat(); rootformats.setBottomMargin ( qMax ( Unit(e.attribute ("margin-after",QString("0"))), Unit(e.attribute ("margin-bottom",QString("0")) ) )); rootformats.setTopMargin( qMax (Unit(e.attribute ("margin-before",QString("0"))), Unit(e.attribute ("margin-top",QString("0")) ) )); rootformats.setRightMargin ( qMax ( Unit(e.attribute ("margin-end",QString("0"))), Unit(e.attribute ("margin-right",QString("0")) ) )); rootformats.setLeftMargin ( qMax (Unit(e.attribute ("margin-start",QString("0"))),Unit(e.attribute ("margin-left",QString("0")) ) )); rootformats.setPadding ( TakeOnePadding(e)); rootformats.setWidth ( wqwi ); Tframe->setFrameFormat ( rootformats ); d->setTextWidth ( wqwi - 2 ); /* set the base document */ const QString idname = e.attribute ("id",layer->IdName()); qreal Zvalue = e.attribute ("z-index",QString("0")).toDouble(); if (Zvalue !=0) { layer->SetZindex(Zvalue); } if (!layerNames.contains(idname)) { layer->SetRealName( idname ); } else { layer->SetRealName( layer->IdName() ); } qreal BorderDicks = TakeOneBorder(e); QString Setcolor; int opacity = e.attribute("opacity",QString("1")).toInt(); /* opacity transparent from background color */ QString usercolorxml = e.attribute("background-color","errorcolor"); if (opacity < 22) { opacity = 1; } if (opacity > 255) { opacity = 1; } if (usercolorxml !="errorcolor") { Setcolor = usercolorxml; } else { Setcolor = default_background; opacity = 1; } if (opacity == 0) { opacity = 1; } layer->SetRects(Unit(e.attribute ("left",QString("10mm"))), Unit(e.attribute ("top",QString("10mm"))), Unit(e.attribute ("width",QString("500mm"))), Unit(e.attribute ("height",QString("500mm"))), BorderDicks, QString(e.attribute("border-start-color",QString(default_background))), Setcolor, opacity); /* grep frame format */ targetAnchor = QTextCharFormat(); /* new layer target link */ targetAnchor.setAnchor(true); targetAnchor.setAnchorNames ( QStringList ( idname ) ); QTextBlockFormat blockFormat = GetBlockFormat(e); /* summ attribute from fo:block */ QTextCharFormat defaultformat = GetCharFormat(e); QDomNode child = e.firstChild(); while ( !child.isNull() ) { if ( child.isElement() ) { const QDomElement childElement = child.toElement(); const QTextCharFormat inliner = GetCharFormat(childElement); /////////////////////qDebug() << "### ParserLayerFloating loop (" << childElement.tagName().toLower() << ") ############"; if ( FoTag(childElement) == INLINE_STYLE ) { ///////////Tcursor.insertText(childElement.text(), inliner ); } else if ( FoTag(childElement) == LINK_DOC ) { /////ParserLink(childElement,d); ////////////Tcursor.insertText( " " +childElement.text().trimmed() + " ", inliner ); } else if ( FoTag(childElement) == IMAGE_SRC ) { ImageParserTag(childElement,d,layer); /* fo:external-graphic */ } else if ( FoTag(childElement) == BLOCK_CONTAINER ) { /* relax NG http://relaxng.org/ not allowed here! */ } else if ( FoTag(childElement) == BLOCK_TAG ) { ////////qDebug() << "### ParserLayerFloating go para 1 (" << FoTag(childElement) << ")"; ParserParagraph(childElement,d,layer); } else if ( FoTag(childElement) == IMAGE_INLINE ) { ObjectParserTag(childElement,d,layer); /* inline svg images */ } else if ( FoTag(childElement) == TABLE_TAG ) { ParserTable(childElement,d,layer); } } else if (child.isText()) { //////////const QDomText childText = child.toText(); /////////QString stremtext = childText.data(); //////////Tcursor.setBlockFormat( blockFormat ); /////////qDebug() << "### fo:block text (" << stremtext << ")"; //////////Tcursor.insertText( stremtext); ////////Tcursor.insertBlock(); } child = child.nextSibling(); } /////////qDebug() << "### errorsize " << ErnoMap.size(); if (ErnoMap.size() > 0) { //////ReportError(); } } QTextBlockFormat Fop_Handler::GetBlockFormat( const QDomElement e ) { /* pf = parent format */ QTextBlockFormat pf; QDomNamedNodeMap attlist = e.attributes(); for (int i=0; i<attlist.count(); i++){ QDomNode nod = attlist.item(i); if (nod.nodeName().toLower() == "break-before") { pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysBefore ); } if (nod.nodeName().toLower() == "break-after") { pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysAfter ); } if (nod.nodeName().toLower() == "text-align") { if (nod.nodeValue().toLower() == "center" ) { pf.setAlignment( Qt::AlignCenter ); } else if (nod.nodeValue().toLower() == "left" || nod.nodeValue().toLower() == "start" || nod.nodeValue().toLower() == "inside" ) { pf.setAlignment( Qt::AlignLeft ); } else if (nod.nodeValue().toLower() == "right" || nod.nodeValue().toLower() == "end" ) { pf.setAlignment( Qt::AlignRight ); } else if (nod.nodeValue().toLower() == "justify") { pf.setAlignment( Qt::AlignJustify ); } else if (nod.nodeValue().toLower() == "inherit") { /* align same as parent before */ pf.setAlignment( Qt::AlignAbsolute ); } } } return pf; } QTextBlockFormat Fop_Handler::ParamFormat( const QDomElement e , QTextBlockFormat f ) { /* pf = parent format */ QTextBlockFormat pf = GetCharFormat(e).toBlockFormat(); pf.merge(f); QDomNamedNodeMap attlist = e.attributes(); for (int i=0; i<attlist.count(); i++){ QDomNode nod = attlist.item(i); if (nod.nodeName().toLower() == "space-after.optimum") { pf.setBottomMargin(Unit(nod.nodeValue())); } if (nod.nodeName().toLower() == "break-before") { pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysBefore ); } if (nod.nodeName().toLower() == "break-after") { pf.setPageBreakPolicy ( QTextFormat::PageBreak_AlwaysAfter ); } if (nod.nodeName().toLower() == "line-height") { } if (nod.nodeName().toLower() == "background-color") { pf.setBackground ( QBrush(QColor(nod.nodeValue()) ) ); } if ( nod.nodeName().toLower().contains("space-before") ) { pf.setTopMargin(Unit(nod.nodeValue())); } if ( nod.nodeName().toLower().contains("space-after") ) { pf.setBottomMargin(Unit(nod.nodeValue())); } if ( nod.nodeName().toLower().contains("space-start") ) { /* right */ pf.setRightMargin(Unit(nod.nodeValue())); } if ( nod.nodeName().toLower().contains("space-end") ) { /* left */ pf.setLeftMargin(Unit(nod.nodeValue())); } if ( nod.nodeName().toLower().contains("start-indent") ) { /* left */ pf.setIndent(Unit(nod.nodeValue()) / 7); } if (nod.nodeName().toLower() == "text-align") { if (nod.nodeValue().toLower() == "center" ) { pf.setAlignment( Qt::AlignCenter ); } else if (nod.nodeValue().toLower() == "left" || nod.nodeValue().toLower() == "start" || nod.nodeValue().toLower() == "inside" ) { pf.setAlignment( Qt::AlignLeft ); } else if (nod.nodeValue().toLower() == "right" || nod.nodeValue().toLower() == "end" ) { pf.setAlignment( Qt::AlignRight ); } else if (nod.nodeValue().toLower() == "justify") { pf.setAlignment( Qt::AlignJustify ); } else if (nod.nodeValue().toLower() == "inherit") { /* align same as parent before */ pf.setAlignment( Qt::AlignAbsolute ); } } } return pf; } QTextCharFormat Fop_Handler::GetCharFormat( const QDomElement e , QTextCharFormat f ) { QDomNamedNodeMap attlist = e.attributes(); QStringList option; option.clear(); int fontstrech = e.attribute ("font-stretch",QString("0")).toInt(); QString idref="id-NOTSET"; /* id identificativ if having? */ for (int i=0; i<attlist.count(); i++){ QDomNode nod = attlist.item(i); if (_PARSE_DEBUG_FOP_ == 1) { option.append(nod.nodeName().toLower()+"="+nod.nodeValue()); } if (nod.nodeName().toLower() == "background-color") { f.setBackground (QBrush(QColor(nod.nodeValue())) ); } if (nod.nodeName().toLower() == "color") { f.setForeground(QBrush(QColor(nod.nodeValue()))); } if (nod.nodeName().toLower() == "id") { idref = nod.nodeValue(); } if (nod.nodeName().toLower() == "font-family") { QFont userfont( nod.nodeValue() ); if (userfont.exactMatch()) { if (fontstrech !=0) { userfont.setStretch ( fontstrech ); } f.setFont(userfont); } else { notexistFontMap.insert(nod.nodeValue(),QApplication::font()); /* prepare replace font item ? */ f.setFont(QApplication::font()); } } if (nod.nodeName().toLower() == "font-size") { f.setFontPointSize(Unit(nod.nodeValue())); } if (nod.nodeName().toLower() == "external-destination" || nod.nodeName().toLower() == "internal-destination") { f.setAnchorHref(nod.nodeValue()); f.setAnchor(true); f.setForeground ( QBrush ( QColor ("#ff0000") ) ); /* red link */ } else { ///////////f.setAnchor(false); } if (nod.nodeName().toLower() == "font-style" || nod.nodeName().toLower() == "font-weight") { if (nod.nodeValue().toLower() == "italic") { f.setFontItalic(true); } else if (nod.nodeValue().toLower() == "oblique") { f.setFontItalic(true); } else if (nod.nodeValue().toLower() == "bold") { f.setFontWeight(QFont::Bold); } } if (nod.nodeName().toLower() == "text-decoration" ) { if (nod.nodeValue().toLower() == "underline") { f.setFontUnderline(true); f.setUnderlineStyle ( QTextCharFormat::SingleUnderline ); } else if (nod.nodeValue().toLower() == "overline") { f.setFontOverline(true); } else if (nod.nodeValue().toLower() == "blink") { f.setFontUnderline(true); f.setUnderlineStyle ( QTextCharFormat::DotLine ); } } else { ///////f.setFontUnderline(false); } /* text-decoration */ } if (_PARSE_DEBUG_FOP_ == 1) { idref.append("\n"); idref.append(option.join("\n")); f.setToolTip(idref); } else { f.setToolTip(idref); } if (f.isValid()) { return f; } else { QTextCharFormat erno; erno.setToolTip("Error format result!"); ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::GetCharFormat / Format Error on file %1 tagname %2.").arg(fopinfo.fileName()).arg(e.tagName().toLower())); return erno; } } /* QTimer::singleShot(10000, this, SLOT(ReloadFileAttach())); */ /* ------------------------------ remote action ---------------------------------------------------------*/ QVariant Fop_Handler::ResourceBlockRemoteImage( const QString urlimage ) { QVariant nullimage; QMapIterator<QString,QVariant> i(RemoteImageMap); while (i.hasNext()) { i.next(); if ( i.key() == urlimage ) { return i.value(); } } return nullimage; } void Fop_Handler::SaveSreamList( int nr , QByteArray data , QString url ) { RemoteImageMap.insert(url,data); ///////qDebug() << "### SaveSreamList position " << nr; ///////////qDebug() << "### SaveSreamList chain " << RemoteImageMap.size(); QApplication::restoreOverrideCursor(); if (dlg->isVisible ()) { dlg->close(); dlg->deleteLater(); } int nextItemtoGet = nr + 1; if (WaitList.size() !=nextItemtoGet) { GetFileatPos(nextItemtoGet); return; } if (WaitList.size() == RemoteImageMap.size()) { WaitList.clear(); OpenModus(); } } void Fop_Handler::UpdateStatus( int sums ) { if (sums < 1) { return; } dlg->setValue(sums); } void Fop_Handler::GetFileatPos( int on ) { dlg = new QProgressDialog(BigParent,Qt::Popup); LoadPage *imageremote = new LoadPage(WaitList.at(on),on); imageremote->Start(); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); dlg->setLabelText (tr("Get File \"%1\"").arg( WaitList.at(on) )); dlg->setCancelButton(0); dlg->setMinimumDuration(700); ///////dlg->setMaximum(100); connect(imageremote, SIGNAL(LastDone(int,QByteArray,QString)),this, SLOT(SaveSreamList(int,QByteArray,QString))); connect(imageremote, SIGNAL(SendLog(int)),this, SLOT(UpdateStatus(int))); } void Fop_Handler::RegisterRemoteFile( const QString urlimage ) { remotefilecounter++; WaitList.append(urlimage); } void Fop_Handler::CheckRemoteImage() { root = doc.documentElement(); if (root.tagName() !="fo:root") { ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::OpenModus / Unable to find a fo:root tag on root by file %1").arg(fopinfo.fileName())); return; } /* reset network activity */ RemoteImageMap.clear(); WaitList.clear(); remotefilecounter = 0; /////////RegisterRemoteFile( FIXEDIMAGE_CIZ ); layout_master = root.firstChildElement("fo:layout-master-set"); master = root.firstChildElement("fo:page-sequence"); page = master.firstChildElement("fo:flow"); LoopOnTagRemoteFile(page); if (WaitList.size() < 1) { OpenModus(); } else { GetFileatPos(0); } } /* Finder from remote image on tag IMAGE_SRC*/ void Fop_Handler::LoopOnTagRemoteFile( const QDomElement e ) { /* grep block container */ QDomNode child = e.firstChild(); while ( !child.isNull() ) { if ( child.isElement() ) { const QDomElement el = child.toElement(); if (FoTag(el) == IMAGE_SRC) { const QString url = ImagesrcUrl(el); if (IsNetFile(url)) { RegisterRemoteFile(url); } } else if (FoTag(el) == BLOCK_CONTAINER) { LoopOnTagRemoteFile(el); } else if (FoTag(el) == BLOCK_TAG) { LoopOnTagRemoteFile(el); } else if (FoTag(el) == IMAGE_INLINE) { /* not follow svg dom tag !! */ } else { LoopOnTagRemoteFile(el); } /////qDebug() << "### LoopOnTagRemoteFile " << el.tagName(); } child = child.nextSibling(); } } /* Final render from the fop page ........... last emit */ void Fop_Handler::OpenModus() { if (!db) { ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::OpenModus/ Unable to find Printer data-base list on file %1 try to handle.").arg(fopinfo.fileName())); return; } LayerSum = 0; /////////////remotefilecounter = 0; imagecounter = 0; layerlist.clear(); layerNames.clear(); root = doc.documentElement(); if (root.tagName() !="fo:root") { ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::OpenModus / Unable to find a fo:root tag on root by file %1").arg(fopinfo.fileName())); return; } layout_master = root.firstChildElement("fo:layout-master-set"); QDomElement extrat = root.firstChildElement("cms:pager"); Page_summer = extrat.attribute("pagesumm",0).toInt(); qDebug() << "#### pagesumme xml say " << Page_summer; ////////qreal pagerwi = Unit(layout.attribute ("page-width",0)); QDomElement layout = layout_master.firstChildElement("fo:simple-page-master"); while (!layout.isNull()) { if (layout.tagName() == "fo:simple-page-master" ) { qreal xBottomMargin = Unit(layout.attribute ("margin-bottom",QString("1cm")) ); qreal xTopMargin = Unit(layout.attribute ("margin-top",QString("1cm")) ) ; qreal xRightMargin = Unit(layout.attribute ("margin-right",QString("1cm")) ) ; qreal xLeftMargin = Unit(layout.attribute ("margin-left",QString("1cm")) ) ; /* register name and dimension page and margin ! */ CurrentPrinterNameFormat = layout.attribute ("master-name","unknow_master_name"); PageDimensionName *dim = new PageDimensionName(CurrentPrinterNameFormat, Unit(layout.attribute ("page-width",QString("21cm"))) , Unit(layout.attribute ("page-height",QString("29.8cm"))), QRectF (xTopMargin,xRightMargin,xBottomMargin,xLeftMargin), QColor(layout.attribute ("background-color",default_background)),0); db->AppInsert(dim); /* formato pagines */ } layout = layout.nextSiblingElement("fo:simple-page-master"); } if (db->connect()) { Pmargin = db->last()->margin(); /* to first default page */ db->reload(); } else { ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::OpenModus/ Unable to send new data on data-base list dimension on file %1 try to handle.").arg(fopinfo.fileName())); } master = root.firstChildElement("fo:page-sequence"); page = master.firstChildElement("fo:flow"); ActualBackgroundColor = QString(default_background); QDomElement testhavingfloatingelement = page.firstChildElement("fo:block-container"); if (testhavingfloatingelement.isNull() && db->connect() ) { /* QRectF (xTopMargin,xRightMargin,xBottomMargin,xLeftMargin), QRectF ( qreal x, qreal y, qreal width, qreal height ) */ QDomElement box = doc.createElement("fo:block-container"); box.setAttribute("width",QString("%1pt").arg(db->last()->internalwi())); box.setAttribute("height",QString("%1pt").arg(db->last()->internalhi())); box.setAttribute("left",QString("%1pt").arg(db->last()->margin().y())); box.setAttribute("top",QString("%1pt").arg(db->last()->margin().x())); QDomNode chi = page.firstChild(); while ( !chi.isNull() ) { if ( chi.isElement() ) { box.appendChild(doc.importNode(chi,true).toElement()); } else if (chi.isText()) { box.appendChild(doc.createTextNode(chi.toText().data())); } chi = chi.nextSibling(); } Fop_Layer *ihacke = new Fop_Layer(fopinfo,0); layerlist.prepend(ihacke); ParserLayerFloating(ihacke,box); /* QFile f( "testout.html" ); if ( f.open( QFile::WriteOnly | QFile::Text ) ) { QTextStream sw( &f ); sw.setCodec(QTextCodec::codecForMib(106)); sw << ihacke->Qdoc()->toHtml("utf-8"); f.close(); } qDebug() << "### not conform block container " << wihack; */ ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::OpenModus/ Unable to find a fo:block-container element on file %1 try to handle.").arg(fopinfo.fileName())); emit ConnectList(true); return; } /* grep block container */ QDomNode child = page.firstChild(); while ( !child.isNull() ) { if ( child.isElement() ) { const QDomElement el = child.toElement(); if (FoTag(el) == BLOCK_CONTAINER) { LayerSum++; Fop_Layer *item = new Fop_Layer(fopinfo,LayerSum); layerlist.prepend(item); ParserLayerFloating(item,el); } } child = child.nextSibling(); } ////////////qDebug() << "### OpenModus end / remotefilecounter ->" << remotefilecounter; /////////qDebug() << "### OpenModus end / ErrorSize ->" << ErrorSize(); emit ConnectList(true); } QPixmap Fop_Handler::RenderSvg( const QDomElement e , Fop_Layer * layer , const QString nameresource ) { ///////nrloop++; /* count element to addresource ! */ /* QString trytosave = QString("svg_%1.svg").arg(nrloop); */ QDomDocument em; QDomProcessingInstruction header = em.createProcessingInstruction( "xml", "version=\"1.0\" standalone=\"no\"" ); em.appendChild( header ); em.appendChild( e.firstChildElement() ); QDomElement root = em.documentElement(); root.setAttribute ("xmlns","http://www.w3.org/2000/svg"); root.setAttribute ("version","1.2"); root.setAttribute ("baseProfile","tiny"); QString srcsv = em.toString(); if (srcsv.contains("svg:svg")) { srcsv = srcsv.replace("svg:",""); } QByteArray streamsvg; streamsvg.append ( srcsv ); layer->AppendImage(nameresource,streamsvg); QPixmap pix = RenderPixmapFromSvgByte( streamsvg ); /* on main.h static inline */ if (pix.isNull() ) { QPixmap pixe(22,22); pixe.fill(QColor("crimson")); /* a error red pixel */ ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::RenderSvg / Unable to render SVG resource \"%1\" on file %2").arg(nameresource).arg(fopinfo.fileName())); return pixe; } else { return pix; } } void Fop_Handler::ImageParserTag( const QDomElement e , QTextDocument * d , Fop_Layer * layer , int CursorPositon ) { ////////////qDebug() << "### ImageParserTag " << FoTag(e); QDir::setCurrent(FopBaserRefDir); /* cd to dir from file fop */ imagecounter++; Fop_Block *foppi = new Fop_Block(imagecounter,e,"fo:external-graphic"); /* <fo:external-graphic src="url(boxes.svg)"/> */ /* read dimension setting from tag */ QTextCursor Tcursor = QTextCursor(d); if (CursorPositon !=0) { Tcursor.setPosition(CursorPositon); } else { Tcursor.movePosition(QTextCursor::End); } qreal wi = qMax ( Unit( e.attribute( "width" , "0" )) , Unit( e.attribute( "content-width" , "0" )));; qreal hi = qMax ( Unit( e.attribute( "height" , "0")) , Unit( e.attribute( "content-height" , "0" ))); QString scaling = e.attribute("scaling","0"); qreal havingnummer = qMax(wi,hi); /* dont scale if not having set nothing width / height */ if (havingnummer < 1) { scaling = "0"; } QString extension; QByteArray derangedata; QPixmap resultimage; QPixmap scaledsimage; QString resourceName; const QString hrefimageplace = ImagesrcUrl(e); /* grab url from image on main.h */ ////////////qDebug() << "### hrefimageplace " << hrefimageplace; ////////qDebug() << "### ImageParserTag " << wi << "X" << hi; QFileInfo fixurl(hrefimageplace); if (IsNetFile(hrefimageplace)) { /* remote file is placed on qmap container is downloaded before init QTextDocument */ QUrl neturi(hrefimageplace); QString findfile = neturi.path(); findfile = findfile.right(findfile.lastIndexOf("/")).toLower(); if (findfile.contains(".")) { extension = findfile.right(findfile.lastIndexOf(".")); } else { extension = findfile; } /* remote file on container qmap typedef QMap<QString,QVariant> TypImageContainer; url data */ derangedata = ResourceBlockRemoteImage( hrefimageplace ).toByteArray(); } else { extension = fixurl.completeSuffix().toLower(); /* decompressed item xx */ if (extension.endsWith(".gz")) { derangedata = OpenGzipOneFileByte( fixurl.absoluteFilePath() ); } else { /* normal image file */ QFile f(fixurl.absoluteFilePath()); if (f.open(QIODevice::ReadOnly)) { derangedata = f.readAll(); f.close(); } } } /* all data avaiable */ /////////qDebug() << "### extension " << extension; /* begin render image */ if (extension.contains("sv")) { resultimage = RenderPixmapFromSvgByte( derangedata ); resourceName = QString("/svg/Z_SVG_external-graphic_%1").arg(imagecounter); } else { resultimage.loadFromData( derangedata ); QString tmpfilename = FilenameAllow(fixurl.baseName()); tmpfilename = tmpfilename.replace("png",""); /* leave start png and resave on same name leave / */ resourceName = QString("/png/%1").arg(tmpfilename); } if (resultimage.isNull()) { /* not valid image to register ! */ ErrorSumm++; ErnoMap.insert(ErrorSumm,tr("Fop_Handler::ImageParserTag / Unable to render image \"%1\" from file %2").arg(hrefimageplace).arg(fopinfo.fileName())); QDir::setCurrent(startdir); /* reset to start dir xx */ return; } else { if (wi !=0 && wi !=resultimage.width() && scaling=="0") { scaling = "uniform"; } if (hi !=0 && hi !=resultimage.height() && scaling=="0") { scaling = "uniform"; } /* scaling image size ?? */ if (scaling == "uniform") { if (wi !=0) { scaledsimage = resultimage.scaledToWidth(wi); } else if (hi !=0) { scaledsimage = resultimage.scaledToHeight(hi); } } else if (scaling == "non-uniform" && wi!=0 && hi!=0) { scaledsimage = resultimage.scaled(wi,hi,Qt::IgnoreAspectRatio); } else { scaledsimage = resultimage; } /* scaling image size ?? */ QUrl recresourcein(resourceName); /* fill image on QTextDocument */ d->addResource( QTextDocument::ImageResource,recresourcein, resultimage ); layer->AppendImage(resourceName,derangedata); QTextImageFormat format; format.setName( resourceName ); if (hi !=0 && scaling!="0") { format.setHeight ( hi ); } else { format.setHeight ( scaledsimage.height() ); } if (wi !=0 && scaling!="0") { format.setWidth ( wi ); } else { format.setWidth ( scaledsimage.width() ); } format.setToolTip ( foppi->Get_XML() ); Tcursor.insertImage( format ); /* cursor insert image QPixmap */ QDir::setCurrent(startdir); } } /* Handle inline svg format image ......... */ bool Fop_Handler::ObjectParserTag( const QDomElement e , QTextDocument * d , Fop_Layer * layer , int CursorPositon ) { QTextCursor Tcursor = QTextCursor(d); if (CursorPositon !=0) { Tcursor.setPosition(CursorPositon); } else { Tcursor.movePosition(QTextCursor::End); } qreal wi = qMax ( Unit( e.attribute( "width" , "0" )) , Unit( e.attribute( "content-width" , "0" )));; qreal hi = qMax ( Unit( e.attribute( "height" , "0")) , Unit( e.attribute( "content-height" , "0" ))); Fop_Block *foppi = new Fop_Block(imagecounter,e,"fo:instream-foreign-object"); imagecounter++; QDomElement domObject = e.firstChildElement(); if ( domObject.tagName().toLower() == "svg:svg" || domObject.tagName().toLower() == "svg" ) { QDir::setCurrent(FopBaserRefDir); const QString resourceName = QString("/svg/Z_SVG_instream-foreign-object_%1").arg(imagecounter); QPixmap paintsvg = RenderSvg(e,layer,resourceName); QUrl recresourcein(resourceName); d->addResource( QTextDocument::ImageResource,recresourcein, paintsvg ); QTextImageFormat format; format.setName( resourceName ); if (wi !=0) { format.setWidth ( wi ); } else { format.setWidth ( paintsvg.width() ); } if (hi !=0) { format.setHeight ( hi ); } else { format.setHeight ( paintsvg.height() ); } format.setToolTip ( foppi->Get_XML() ); Tcursor.insertImage( format ); /* cursor insert image QPixmap */ QDir::setCurrent(startdir); return true; } return false; } /* remove objekt */ Fop_Handler::~Fop_Handler() { Fopdevice->close(); deleteLater(); }
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 1721 ] ] ]
9d8004a191c9c8a3e051190c89c26b7681b86a52
dd738ae41d10b95f71680d9f38e6dd31f2e6d113
/Devices/SmartJaguar.h
177b688edce5a0e1de8baf6c36ec70064f4f2c24
[]
no_license
mbh1100/frc2009
8ece016010aa170b1b34859f58d5a9d9447bad2e
62808972421e8823657ed69fbdf8f80367a5685e
refs/heads/master
2021-01-23T08:38:57.103159
2009-02-17T02:43:17
2009-02-17T02:43:17
34,929,820
0
0
null
null
null
null
UTF-8
C++
false
false
457
h
#ifndef SMARTJAGUAR_H #define SMARTJAGUAR_H #include "WPILib.h" #include <list> #include <cmath> #define kRampDownMult .8 class SmartJaguar { public: SmartJaguar(Jaguar* motor); ~SmartJaguar(); void SetSpeed(float speed); void Update(); protected: Jaguar *m_motor; float m_target; std::list<float> m_prevValues; static const UINT8 kMaxSamples = 5; static const UINT8 kMinSamples = 2; }; #endif //SMARTJAGUAR_H
[ "first.team1100@ddad09ec-df38-11dd-a8eb-ddf07f3c1838" ]
[ [ [ 1, 28 ] ] ]
468a108be69bf18cc8886ad3a1546715ec5c59fd
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/spirit/test/karma/sequence.cpp
61553d72f37c88d5e1741f20a4d72a06a7cfa657
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,994
cpp
// Copyright (c) 2001-2009 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #define KARMA_TEST_COMPILE_FAIL #include <boost/config/warning_disable.hpp> #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/include/support_argument.hpp> #include <boost/spirit/include/karma_char.hpp> #include <boost/spirit/include/karma_string.hpp> #include <boost/spirit/include/karma_numeric.hpp> #include <boost/spirit/include/karma_generate.hpp> #include <boost/spirit/include/karma_operator.hpp> #include <boost/spirit/include/karma_directive.hpp> #include <boost/spirit/include/karma_action.hpp> #include <boost/fusion/include/vector.hpp> #include <boost/spirit/include/support_unused.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include "test.hpp" using namespace spirit_test; /////////////////////////////////////////////////////////////////////////////// int main() { using namespace boost::spirit; namespace fusion = boost::fusion; { { BOOST_TEST(test("xi", char_('x') << char_('i'))); BOOST_TEST(!test("xi", char_('x') << char_('o'))); } { BOOST_TEST(test_delimited("x i ", char_('x') << 'i', char(' '))); BOOST_TEST(!test_delimited("x i ", char_('x') << char_('o'), char(' '))); } { BOOST_TEST(test_delimited("Hello , World ", lit("Hello") << ',' << "World", char(' '))); } { fusion::vector<char, char, std::string> p ('a', 'b', "cdefg"); BOOST_TEST(test("abcdefg", char_ << char_ << lit, p)); BOOST_TEST(test_delimited("a b cdefg ", char_ << char_ << lit, p, char(' '))); } { fusion::vector<char, int, char> p ('a', 12, 'c'); BOOST_TEST(test("a12c", char_ << int_ << char_, p)); BOOST_TEST(test_delimited("a 12 c ", char_ << int_ << char_, p, char(' '))); } { // if all elements of a sequence have unused parameters, the whole // sequence has an unused parameter as well fusion::vector<char, char> p ('a', 'e'); BOOST_TEST(test("abcde", char_ << (char_('b') << 'c' << 'd') << char_, p)); BOOST_TEST(test_delimited("a b c d e ", char_ << (char_('b') << 'c' << 'd') << char_, p, char(' '))); } { // literal generators do not need a parameter fusion::vector<char, char> p('a', 'c'); BOOST_TEST(test("abc", char_ << 'b' << char_, p)); BOOST_TEST(test_delimited("a b c ", char_ << 'b' << char_, p, char(' '))); } { using namespace boost::spirit::ascii; BOOST_TEST(test("aa", lower[char_('A') << 'a'])); BOOST_TEST(test_delimited("BEGIN END ", upper[lit("begin") << "end"], char(' '))); BOOST_TEST(!test_delimited("BEGIN END ", upper[lit("begin") << "nend"], char(' '))); BOOST_TEST(test("Aa ", left_align[char_('A') << 'a'])); BOOST_TEST(test(" Aa ", center[char_('A') << 'a'])); BOOST_TEST(test(" Aa", right_align[char_('A') << 'a'])); } // action tests { using namespace boost::phoenix; using namespace boost::spirit::arg_names; using namespace boost::spirit::ascii; BOOST_TEST(test("abcdefg", (char_ << char_ << lit)[_1 = 'a', _2 = 'b', _3 = "cdefg"])); BOOST_TEST(test_delimited("a b cdefg ", (char_ << char_ << lit)[_1 = 'a', _2 = 'b', _3 = "cdefg"], char(' '))); BOOST_TEST(test_delimited("a 12 c ", (char_ << int_(12) << char_)[_1 = 'a', _2 = 'c'], char(' '))); char c = 'c'; BOOST_TEST(test("abc", (char_[_1 = 'a'] << 'b' << char_)[_1 = 'x', _2 = ref(c)])); BOOST_TEST(test_delimited("a b c ", (char_[_1 = 'a'] << 'b' << char_)[_2 = ref(c)], char(' '))); BOOST_TEST(test("aa", lower[char_ << 'A'][_1 = 'A'])); BOOST_TEST(test("AA", upper[char_ << 'a'][_1 = 'a'])); BOOST_TEST(test("Aa ", left_align[char_ << 'a'][_1 = 'A'])); BOOST_TEST(test(" Aa ", center[char_ << 'a'][_1 = 'A'])); BOOST_TEST(test(" Aa", right_align[char_ << 'a'][_1 = 'A'])); } } return boost::report_errors(); }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 131 ] ] ]
6f5cbb04d028cc9bad20ffc2ccba9901f1799ac3
b8fbe9079ce8996e739b476d226e73d4ec8e255c
/src/engine/rb_math/seg2.h
7fb6b9bafa4276365ad2a6ba2ad75c96568aacb5
[]
no_license
dtbinh/rush
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
ad75072777438c564ccaa29af43e2a9fd2c51266
refs/heads/master
2021-01-15T17:14:48.417847
2011-06-16T17:41:20
2011-06-16T17:41:20
41,476,633
1
0
null
2015-08-27T09:03:44
2015-08-27T09:03:44
null
UTF-8
C++
false
false
1,409
h
/***********************************************************************************/ // File: Seg2.h // Date: 12.08.2005 // Author: Ruslan Shestopalyuk /***********************************************************************************/ #ifndef __SEG2_H__ #define __SEG2_H__ #include "vec2.h" #include "mathconst.h" /***********************************************************************************/ // Class: Seg2 // Desc: /***********************************************************************************/ class Seg2 { public: Vec2 a; Vec2 b; Seg2 () {} Seg2 ( const Vec2& va, const Vec2& vb ) : a( va ), b( vb ) {} Seg2 ( float ax, float ay, float bx, float by ) : a( Vec2( ax, ay ) ), b( Vec2( bx, by ) ) {} bool intersects ( const Seg2& s, bool bInclusive = true, Vec2* pPt = NULL ) const; inline bool is_vertical () const { return (_fabs( a.x - b.x ) < c_FltEpsilon); } inline float length () const { return sqrtf( (a.y - b.y)* (a.y - b.y) + (a.y - b.y)* (a.y - b.y) ); } bool contains ( const Vec2& p, float eps = c_FltEpsilon ); float dist2 ( const Seg2& s ) const; float dist2 ( const Vec2& p ) const; }; // class Seg2 #endif //__SEG2_H__
[ [ [ 1, 35 ] ] ]
27500af03027672fa2238577208d664c51ab311e
e31046aee3ad2d4600c7f35aaeeba76ee2b99039
/trunk/libs/bullet/includes/BulletCollision/CollisionShapes/btStridingMeshInterface.h
4bd5a88222c664901978737758c3a41e1e5fa70b
[]
no_license
BackupTheBerlios/trinitas-svn
ddea265cf47aff3e8853bf6d46861e0ed3031ea1
7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca
refs/heads/master
2021-01-23T08:14:44.215249
2009-02-18T19:37:51
2009-02-18T19:37:51
40,749,519
0
0
null
null
null
null
UTF-8
C++
false
false
4,138
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef STRIDING_MESHINTERFACE_H #define STRIDING_MESHINTERFACE_H #include "LinearMath/btVector3.h" #include "btTriangleCallback.h" /// PHY_ScalarType enumerates possible scalar types. /// See the btStridingMeshInterface for its use typedef enum PHY_ScalarType { PHY_FLOAT, PHY_DOUBLE, PHY_INTEGER, PHY_SHORT, PHY_FIXEDPOINT88 } PHY_ScalarType; /// The btStridingMeshInterface is the interface class for high performance generic access to triangle meshes, used in combination with btBvhTriangleMeshShape and some other collision shapes. /// Using index striding of 3*sizeof(integer) it can use triangle arrays, using index striding of 1*sizeof(integer) it can handle triangle strips. /// It allows for sharing graphics and collision meshes. Also it provides locking/unlocking of graphics meshes that are in gpu memory. class btStridingMeshInterface { protected: btVector3 m_scaling; public: btStridingMeshInterface() :m_scaling(btScalar(1.),btScalar(1.),btScalar(1.)) { } virtual ~btStridingMeshInterface(); virtual void InternalProcessAllTriangles(btInternalTriangleIndexCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; ///brute force method to calculate aabb void calculateAabbBruteForce(btVector3& aabbMin,btVector3& aabbMax); /// get read and write access to a subpart of a triangle mesh /// this subpart has a continuous array of vertices and indices /// in this way the mesh can be handled as chunks of memory with striding /// very similar to OpenGL vertexarray support /// make a call to unLockVertexBase when the read and write access is finished virtual void getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0)=0; virtual void getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,const unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0) const=0; /// unLockVertexBase finishes the access to a subpart of the triangle mesh /// make a call to unLockVertexBase when the read and write access (using getLockedVertexIndexBase) is finished virtual void unLockVertexBase(int subpart)=0; virtual void unLockReadOnlyVertexBase(int subpart) const=0; /// getNumSubParts returns the number of seperate subparts /// each subpart has a continuous array of vertices and indices virtual int getNumSubParts() const=0; virtual void preallocateVertices(int numverts)=0; virtual void preallocateIndices(int numindices)=0; virtual bool hasPremadeAabb() const { return false; } virtual void setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax ) const {} virtual void getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax ) const {} const btVector3& getScaling() const { return m_scaling; } void setScaling(const btVector3& scaling) { m_scaling = scaling; } }; #endif //STRIDING_MESHINTERFACE_H
[ "paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333" ]
[ [ [ 1, 95 ] ] ]
60b706948facc3058b0437191fda04072b1c4dfa
e53e8063c01668038088636f74e0e6455dfbb43f
/src/qtwprojectoptions.h
efd8e18c76558176a62ced79b3a7cbc0f3d103ce
[]
no_license
anhlehoang410/qtworkbench
43d04302b51bef23c4ed384afcdf0f2dd27fd56e
8b1e6b532e08dbbe54df98aee82a078e989af4ab
refs/heads/master
2021-01-21T00:45:10.311186
2009-07-13T09:36:15
2009-07-13T09:36:15
33,586,434
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
h
/*************************************************************** * Name: qtwprojectoptions.h * Purpose: Code::Blocks plugin * Author: Yorgos Pagles<[email protected]> * Copyright: (c) Yorgos Pagles * License: GPL **************************************************************/ #include "configurationpanel.h" #include "qtwutilities.h" class cbProject; class QtWProjectHandler; class QtWProjectOptions : public cbConfigurationPanel { public: QtWProjectOptions(wxWindow* parent, cbProject* project, QMakeEnabledProjectsMap &enabledProjects); ~QtWProjectOptions(); virtual wxString GetTitle() const { return _("Qt Workbench"); } virtual wxString GetBitmapBaseName() const { return _T("generic-plugin"); } virtual void OnApply() { SaveSettings(); } virtual void OnCancel() {} private: void PopulateTargetsListBox(); void PopulateWorld(); void PopulateBuildMode(); void PopulateRequirements(); void PopulateModules(); void PopulateFileLocations(); void PopulateVariablesList(); void PopulateValuesList(); void OnBrowseMocButtonClick(wxCommandEvent&); void OnBrowseUicButtonClick(wxCommandEvent&); void OnBrowseRccButtonClick(wxCommandEvent&); void OnAddValue(wxCommandEvent&); void OnAddVariable(wxCommandEvent&); void OnRemoveValue(wxCommandEvent&); void OnRemoveVariable(wxCommandEvent&); void OnTargetListClick(wxCommandEvent&); void OnNotebookPageChange(wxNotebookEvent&); void OnUpdateAdvancedView(wxCommandEvent&); void OnUsingQtWorkbench(wxCommandEvent&); void SaveSettings(); void Update(); void ReadTargets(); void UpdateTarget(); cbProject* m_Project; QtWProjectHandler *m_Handler; QMakeEnabledProjectsMap &m_EnabledProjects; WX_DECLARE_STRING_HASH_MAP(QtWProjectHandler *, QtWProjectHandlersMap); QtWProjectHandlersMap m_TargetHandlers; DECLARE_EVENT_TABLE() };
[ "y.pagles@localhost" ]
[ [ [ 1, 69 ] ] ]
6083190c8207c42bae027768e7c5c44bbbb637ed
e580637678397200ed79532cd34ef78983e9aacd
/Grapplon/HealthPowerUp.cpp
75a6fa00153612b1ccc34734a6bd627ff24037ca
[]
no_license
TimToxopeus/grapplon2
03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b
60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5
refs/heads/master
2021-01-10T21:11:59.438625
2008-07-13T06:49:06
2008-07-13T06:49:06
41,954,527
0
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
#include "HealthPowerUp.h" #include "ODEManager.h" #include "PlayerObject.h" #include "GameSettings.h" #include "ResourceManager.h" #include "Sound.h" #include "AnimatedTexture.h" CHealthPowerUp::CHealthPowerUp(void) { m_ePowerUpType = HEALTH; m_pImage = new CAnimatedTexture("media/scripts/texture_powerup_repair.txt"); } CHealthPowerUp::~CHealthPowerUp(void) { } void CHealthPowerUp::CollideWith(CBaseObject* pOther, Vector &pos) { if(pOther->getType() == SHIP && this->m_bIsGrabable) { dynamic_cast<CPlayerObject*>(pOther)->TookHealthPowerUp(); CSound *pSound = (CSound *)CResourceManager::Instance()->GetResource("media/sounds/powerup_pickup.wav", RT_SOUND); if ( pSound ) pSound->Play(); } CPowerUp::CollideWith(pOther, pos); }
[ [ [ 1, 11 ], [ 13, 21 ], [ 23, 25 ], [ 31, 31 ], [ 33, 33 ] ], [ [ 12, 12 ], [ 22, 22 ], [ 26, 30 ], [ 32, 32 ] ] ]
e445f816049be7c4ffbcb96c9566d920b0f9a23d
62a5260bf242add996041111c92a795f2e5a4e8b
/ocgcore/field.h
28658d594a7aa00c7b54a7fda868e30b9fd420ec
[]
no_license
zh99998/ygocore
cc0d1f8d628ab37e5217aed543966f775d93a8d4
362daff35e17ea338b8873b9cc1ab8ee10bc2c7f
refs/heads/master
2021-01-22T05:24:24.120543
2011-11-27T13:21:34
2011-11-27T13:21:34
3,000,435
6
1
null
null
null
null
UTF-8
C++
false
false
27,601
h
/* * field.h * * Created on: 2010-5-8 * Author: Argon */ #ifndef FIELD_H_ #define FIELD_H_ #include "common.h" #include "duel.h" #include "card.h" #include "group.h" #include "effect.h" #include "effectset.h" #include <vector> #include <set> #include <map> #include <list> #include <array> class card; struct card_data; class duel; class group; class effect; struct event { uint32 event_code; void* event_cards; uint32 event_value; uint8 event_player; effect* reason_effect; uint32 reason; uint8 reason_player; }; struct optarget { group* op_cards; uint8 op_count; uint8 op_player; int32 op_param; }; struct chain { typedef std::map<uint32, optarget > opmap; uint16 chain_id; uint8 chain_count; uint8 chain_type; uint8 triggering_player; uint8 triggering_controler; uint8 triggering_location; uint8 triggering_sequence; effect* triggering_effect; group* target_cards; int32 replace_op; uint8 target_player; int32 target_param; effect* disable_reason; uint8 disable_player; event evt; opmap opinfos; uint32 flag; static bool chain_operation_sort(chain c1, chain c2); }; struct player_info { typedef std::vector<card*> card_vector; int32 lp; int32 start_count; int32 draw_count; uint32 used_location; uint32 disabled_location; card_vector list_mzone; card_vector list_szone; card_vector list_main; card_vector list_grave; card_vector list_hand; card_vector list_remove; card_vector list_extra; }; struct field_effect { typedef std::multimap<uint32, effect*> effect_container; typedef std::map<effect*, effect_container::iterator > effect_indexer; typedef std::map<effect*, effect*> oath_effects; typedef std::set<effect*> effect_collection; effect_container aura_effect; effect_container startup_effect; effect_container activate_effect; effect_container trigger_o_effect; effect_container trigger_f_effect; effect_container instant_o_effect; effect_container instant_f_effect; effect_container continuous_effect; effect_indexer indexer; oath_effects oath; effect_collection pheff; effect_collection cheff; effect_collection rechargeable; std::list<card*> disable_check_list; std::set<card*, card_sort> disable_check_set; }; struct field_info { int16 effect_id; int16 copy_id; int16 turn_id; int16 field_id; int16 card_id; uint8 phase; uint8 turn_player; uint8 priorities[2]; }; struct lpcost { int32 count; int32 amount; int32 lpstack[8]; }; struct processor_unit { uint16 type; uint16 step; effect* peffect; group* ptarget; ptr arg1; ptr arg2; }; union return_value { int8 bvalue[64]; int16 svalue[32]; int32 ivalue[16]; int64 lvalue[8]; }; struct processor { typedef std::vector<effect*> effect_vector; typedef std::vector<card*> card_vector; typedef std::vector<uint32> option_vector; typedef std::list<card*> card_list; typedef std::list<event> event_list; typedef std::list<chain> chain_list; typedef std::map<effect*, chain> instant_f_list; typedef std::vector<chain> chain_array; typedef std::list<processor_unit> processor_list; typedef std::set<card*, card_sort> card_set; processor_list units; processor_list subunits; processor_unit reserved; card_vector select_cards; card_vector summonable_cards; card_vector spsummonable_cards; card_vector repositionable_cards; card_vector msetable_cards; card_vector ssetable_cards; card_vector attackable_cards; effect_vector select_effects; option_vector select_options; event_list point_event; event_list instant_event; event_list queue_event; event_list used_event; event_list single_event; event_list solving_event; event_list sub_solving_event; chain_array select_chains; chain_array current_chain; chain_list tpchain; chain_list ntpchain; chain_list continuous_chain; chain_list desrep_chain; chain_list new_fchain; chain_list new_fchain_s; chain_list new_ochain; chain_list new_ochain_s; chain_list flip_chain; chain_list new_fchain_b; chain_list new_ochain_b; chain_list flip_chain_b; chain_list new_chains; instant_f_list instant_f_chain; card_set leave_confirmed; card_set special_summoning; card_list adjust_list; card_set adjust_set; card_set destroy_set; card_set battle_destroy_rep; card_set fusion_materials; card_set synchro_materials; card_set operated_set; card_set discarded_set; card_set destroy_canceled; effect_set disfield_effects; effect_set extraz_effects; effect_set extraz_effects_e; std::set<effect*> reseted_effects; effect_vector delayed_tp; effect_vector delayed_ntp; event_list delayed_tev; event_list delayed_ntev; void* temp_var[4]; uint16 pre_field[5]; int32 chain_limit; uint8 chain_limp; int32 chain_limit_p; uint8 chain_limp_p; uint8 chain_solving; uint8 win_player; uint8 win_reason; uint8 re_adjust; effect* reason_effect; uint8 reason_player; card* summoning_card; card* spsummoning_card; uint8 summon_depth; card* attacker; card* sub_attacker; card* attack_target; card* sub_attack_target; card* limit_tuner; int32 battle_damage[2]; int32 summon_count[2]; int32 spe_effect[2]; int32 duel_options; uint32 copy_reset; uint8 copy_reset_count; uint8 dice_result[5]; uint8 coin_result[5]; uint8 to_bp; uint8 to_m2; uint8 to_ep; uint8 chain_attack; card* chain_attack_target; uint8 selfdes_disabled; uint8 overdraw[2]; int32 check_level; uint8 shuffle_check_disabled; uint8 shuffle_hand_check[2]; uint8 shuffle_deck_check[2]; uint8 flip_delayed; uint8 damage_calculated; uint8 summon_state[2]; uint8 normalsummon_state[2]; uint8 flipsummon_state[2]; uint8 spsummon_state[2]; uint8 attack_state[2]; uint8 phase_action; uint32 hint_timing[2]; }; class field { public: typedef std::multimap<uint32, effect*> effect_container; typedef std::list<card*> check_list; typedef std::map <effect*, effect_container::iterator> effect_indexer; typedef std::set<card*, card_sort> card_set; typedef std::vector<effect*> effect_vector; typedef std::vector<card*> card_vector; typedef std::vector<uint32> option_vector; typedef std::list<card*> card_list; typedef std::list<event> event_list; typedef std::list<chain> chain_list; typedef std::map<effect*, chain> instant_f_list; typedef std::vector<chain> chain_array; typedef std::list<processor_unit> processor_list; typedef std::map<effect*, effect*> oath_effects; duel* pduel; player_info player[2]; card* temp_card; field_info infos; lpcost cost[2]; field_effect effects; processor core; return_value returns; event nil_event; static int32 field_used_count[32]; field(duel* pduel); ~field(); void add_card(uint8 playerid, card* pcard, uint8 location, uint8 sequence); void remove_card(card* pcard); void move_card(uint8 playerid, card* pcard, uint8 location, uint8 sequence); void set_control(card* pcard, uint8 playerid, uint8 reset_phase, uint8 reset_count); card* get_field_card(uint8 playerid, uint8 location, uint8 sequence); int32 is_location_useable(uint8 playerid, uint8 location, uint8 sequence); int32 get_useable_count(uint8 playerid, uint8 location, uint32* list = 0); void shuffle(uint8 playerid, uint8 location); void reset_sequence(uint8 playerid, uint8 location); void swap_deck_and_grave(uint8 playerid); void add_effect(effect* peffect, uint8 owner_player = 2); void remove_effect(effect* peffect); void remove_oath_effect(effect* reason_effect); void reset_effect(uint32 id, uint32 reset_type); void reset_phase(uint32 phase); void reset_chain(); void filter_field_effect(uint32 code, effect_set* eset, uint8 sort = TRUE); void filter_affected_cards(effect* peffect, card_set* cset); void filter_player_effect(uint8 playerid, uint32 code, effect_set* eset, uint8 sort = TRUE); int32 filter_matching_card(int32 findex, uint8 self, uint32 location1, uint32 location2, group* pgroup, card* pexception, uint32 extraargs, card** pret = 0, int32 fcount = 0, int32 is_target = FALSE); int32 filter_field_card(uint8 self, uint32 location, uint32 location2, group* pgroup); int32 is_player_affected_by_effect(uint8 playerid, uint32 code); int32 get_release_list(uint8 playerid, card_set* release_list); int32 get_summon_release_list(card* target, card_set* release_list); int32 get_summon_count_limit(uint8 playerid); int32 get_draw_count(uint8 playerid); void get_ritual_material(uint8 playerid, card_set* material); void ritual_release(card_set* material); void get_exceed_material(card* scard, card_set* material); void get_overlay_group(uint8 self, uint8 s, uint8 o, card_set* pset); int32 get_overlay_count(uint8 self, uint8 s, uint8 o); void update_disable_check_list(effect* peffect); void add_to_disable_check_list(card* pcard); void adjust_disable_check_list(); int32 check_lp_cost(uint8 playerid, uint32 cost); void save_lp_cost(); void restore_lp_cost(); int32 pay_lp_cost(uint32 step, uint8 playerid, uint32 cost); uint32 get_field_counter(uint8 self, uint8 s, uint8 o, uint16 countertype); int32 effect_replace_check(uint32 code, event e); int32 get_attack_target(card* pcard, card_vector* v, uint8 chain_attack = FALSE); int32 check_synchro_material(card* pcard, int32 findex1, int32 findex2, int32 min); int32 check_tuner_material(card* pcard, card* tuner, int32 findex1, int32 findex2, int32 min); int32 check_with_sum_limit(card_vector* mats, int32 acc, int32 index, int32 count, int32 min); int32 is_player_can_draw(uint8 playerid); int32 is_player_can_discard_deck(uint8 playerid); int32 is_player_can_discard_deck_as_cost(uint8 playerid, int32 count); int32 is_player_can_discard_hand(uint8 playerid, card* pcard, effect* peffect, uint32 reason); int32 is_player_can_summon(uint32 sumtype, uint8 playerid, card* pcard); int32 is_player_can_mset(uint32 sumtype, uint8 playerid, card* pcard); int32 is_player_can_sset(uint8 playerid, card* pcard); int32 is_player_can_spsummon(effect* peffect, uint32 sumtype, uint8 sumpos, uint8 playerid, uint8 toplayer, card* pcard); int32 is_player_can_flipsummon(uint8 playerid, card* pcard); int32 is_player_can_spsummon_token(uint8 playerid, uint8 toplayer, uint8 sumpos, card_data* pdata); int32 is_player_can_release(uint8 playerid, card* pcard); int32 is_player_can_remove_counter(uint8 playerid, card* pcard, uint8 s, uint8 o, uint16 countertype, uint16 count, uint32 reason); int32 is_player_can_remove_overlay_card(uint8 playerid, card* pcard, uint8 s, uint8 o, uint16 count, uint32 reason); int32 is_player_can_send_to_grave(uint8 playerid, card* pcard); int32 is_player_can_send_to_hand(uint8 playerid, card* pcard); int32 is_player_can_send_to_deck(uint8 playerid, card* pcard); int32 is_player_can_remove(uint8 playerid, card* pcard); int32 is_chain_inactivatable(uint8 chaincount); int32 is_chain_disablable(uint8 chaincount); int32 check_chain_target(uint8 chaincount, card* pcard); void add_process(uint16 type, uint16 step, effect* peffect, group* target, ptr arg1, ptr arg2); int32 process(); int32 execute_cost(uint16 step, effect* peffect, uint8 triggering_player); int32 execute_operation(uint16 step, effect* peffect, uint8 triggering_player); int32 execute_target(uint16 step, effect* peffect, uint8 triggering_player); void raise_event(card* event_card, uint32 event_code, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value); void raise_event(card_set* event_cards, uint32 event_code, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value); void raise_single_event(card* event_card, uint32 event_code, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value ); int32 check_event(uint32 code, event* pe = 0); int32 check_hint_timing(effect* peffect); int32 process_phase_event(int16 step, int32 phase_event); int32 process_point_event(int16 step, int32 special, int32 skip_new); int32 process_quick_effect(int16 step, int32 special, uint8 priority); int32 process_instant_event(); int32 process_single_event(); int32 process_idle_command(uint16 step); int32 process_battle_command(uint16 step); int32 process_damage_phase(uint16 step); int32 process_turn(uint16 step, uint8 turn_player); int32 add_chain(uint16 step); int32 sort_chain(uint16 step, uint8 tp); int32 solve_continuous(uint16 step, effect* peffect, uint8 triggering_player); int32 solve_chain(uint16 step, uint32 skip_new); int32 break_effect(); void adjust_instant(); void adjust_all(); void refresh_location_info_instant(); int32 refresh_location_info(uint16 step); int32 adjust_step(uint16 step); //operations int32 negate_chain(uint8 chaincount); int32 disable_chain(uint8 chaincount); void change_chain_effect(uint8 chaincount, int32 replace_op); void change_target(uint8 chaincount, group* targets); void change_target_player(uint8 chaincount, uint8 playerid); void change_target_param(uint8 chaincount, int32 param); void remove_counter(uint32 reason, card* pcard, uint32 rplayer, uint32 s, uint32 o, uint32 countertype, uint32 count); void remove_overlay_card(uint32 reason, card* pcard, uint32 rplayer, uint32 s, uint32 o, uint16 min, uint16 max); void get_control(effect* reason_effect, uint32 reason_player, card* pcard, uint32 playerid, uint32 reset_phase, uint32 reset_count); void swap_control(effect* reason_effect, uint32 reason_player, card* pcard1, card* pcard2, uint32 reset_phase, uint32 reset_count); void equip(uint32 equip_player, card* equip_card, card* target, uint32 up); void draw(effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid, uint32 count); void damage(effect* reason_effect, uint32 reason, uint32 reason_player, card* pcard, uint32 playerid, uint32 amount); void recover(effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid, uint32 amount); void summon(uint32 sumplayer, card* target, effect* proc, uint32 ignore_count); void special_summon_rule(uint32 sumplayer, card* target); void special_summon(card_set* target, uint32 sumtype, uint32 sumplayer, uint32 playerid, uint32 nocheck, uint32 nolimit, uint32 positions); void special_summon_step(card* target, uint32 sumtype, uint32 sumplayer, uint32 playerid, uint32 nocheck, uint32 nolimit, uint32 positions); void special_summon_complete(effect* reason_effect, uint8 reason_player); void destroy(card_set* targets, effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid = 2, uint32 destination = 0, uint32 sequence = 0); void destroy(card* target, effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid = 2, uint32 destination = 0, uint32 sequence = 0); void release(card_set* targets, effect* reason_effect, uint32 reason, uint32 reason_player); void release(card* target, effect* reason_effect, uint32 reason, uint32 reason_player); void send_to(card_set* targets, effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid, uint32 destination, uint32 sequence, uint32 position); void send_to(card* target, effect* reason_effect, uint32 reason, uint32 reason_player, uint32 playerid, uint32 destination, uint32 sequence, uint32 position); void move_to_field(card* target, uint32 move_player, uint32 playerid, uint32 destination, uint32 positions, uint32 enable = FALSE, uint32 ret = FALSE); void change_position(card_set* targets, effect* reason_effect, uint32 reason_player, uint32 au, uint32 ad, uint32 du, uint32 dd, uint32 noflip, uint32 enable = FALSE); void change_position(card* target, effect* reason_effect, uint32 reason_player, uint32 npos, uint32 noflip, uint32 enable = FALSE); int32 remove_counter(uint16 step, uint32 reason, card* pcard, uint8 rplayer, uint8 s, uint8 o, uint16 countertype, uint16 count); int32 remove_overlay_card(uint16 step, uint32 reason, card* pcard, uint8 rplayer, uint8 s, uint8 o, uint16 min, uint16 max); int32 get_control(uint16 step, effect* reason_effect, uint8 reason_player, card* pcard, uint8 playerid, uint8 reset_phase, uint8 reset_count); int32 swap_control(uint16 step, effect* reason_effect, uint8 reason_player, card* pcard1, card* pcard2, uint8 reset_phase, uint8 reset_count); int32 equip(uint16 step, uint8 equip_player, card* equip_card, card* target, uint32 up); int32 draw(uint16 step, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 playerid, uint32 count); int32 damage(uint16 step, effect* reason_effect, uint32 reason, uint8 reason_player, card* pcard, uint8 playerid, uint32 amount); int32 recover(uint16 step, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 playerid, uint32 amount); int32 summon(uint16 step, uint8 sumplayer, card* target, effect* proc, uint8 ignore_count); int32 flip_summon(uint16 step, uint8 sumplayer, card* target); int32 mset(uint16 step, uint8 setplayer, card* ptarget, effect* proc, uint8 ignore_count); int32 sset(uint16 step, uint8 setplayer, card* ptarget); int32 special_summon_rule(uint16 step, uint8 sumplayer, card* target); int32 special_summon_step(uint16 step, group* targets, card* target); int32 special_summon(uint16 step, effect* reason_effect, uint8 reason_player, group* targets); int32 destroy(uint16 step, group* targets, card* target, uint8 battle); int32 destroy(uint16 step, group* targets, effect* reason_effect, uint32 reason, uint8 reason_player); int32 release(uint16 step, group* targets, card* target); int32 release(uint16 step, group* targets, effect* reason_effect, uint32 reason, uint8 reason_player); int32 send_to(uint16 step, group* targets, card* target); int32 send_to(uint16 step, group* targets, effect* reason_effect, uint32 reason, uint8 reason_player); int32 discard_deck(uint16 step, uint8 playerid, uint8 count, uint32 reason); int32 move_to_field(uint16 step, card* target, uint32 enable, uint32 ret); int32 change_position(uint16 step, group* targets, effect* reason_effect, uint8 reason_player, uint32 enable); int32 operation_replace(uint16 step, effect* replace_effect, group* targets, ptr arg, ptr replace_type); int32 select_synchro_material(int16 step, uint8 playerid, card* pcard, int32 min); int32 toss_coin(uint16 step, uint8 playerid, uint8 count); int32 toss_dice(uint16 step, uint8 playerid, uint8 count); int32 select_battle_command(uint16 step, uint8 playerid); int32 select_idle_command(uint16 step, uint8 playerid); int32 select_effect_yes_no(uint16 step, uint8 playerid, card* pcard); int32 select_yes_no(uint16 step, uint8 playerid, uint32 description); int32 select_option(uint16 step, uint8 playerid); int32 select_card(uint16 step, uint8 playerid, uint8 cancelable, uint8 min, uint8 max); int32 select_chain(uint16 step, uint8 playerid, uint8 spe_count); int32 select_place(uint16 step, uint8 playerid, uint32 flag, uint8 count); int32 select_position(uint16 step, uint8 playerid, uint32 code, uint8 positions); int32 select_tribute(uint16 step, uint8 playerid, uint8 cancelable, uint8 min, uint8 max); int32 select_counter(uint16 step, uint8 playerid, uint16 countertype, uint16 count); int32 select_with_sum_limit(int16 step, uint8 playerid, int32 acc, int32 min); int32 sort_card(int16 step, uint8 playerid, uint8 is_chain); int32 announce_race(int16 step, uint8 playerid, int32 count, int32 available); int32 announce_attribute(int16 step, uint8 playerid, int32 count, int32 available); int32 announce_card(int16 step, uint8 playerid); int32 announce_number(int16 step, uint8 playerid); }; //Chain Info #define CHAIN_DISABLE_ACTIVATE 0x01 #define CHAIN_DISABLE_EFFECT 0x02 #define CHAIN_NEGATED 0x04 #define CHAININFO_CHAIN_COUNT 0x01 #define CHAININFO_TRIGGERING_EFFECT 0x02 #define CHAININFO_TRIGGERING_PLAYER 0x04 #define CHAININFO_TRIGGERING_CONTROLER 0x08 #define CHAININFO_TRIGGERING_LOCATION 0x10 #define CHAININFO_TRIGGERING_SEQUENCE 0x20 #define CHAININFO_TARGET_CARDS 0x40 #define CHAININFO_TARGET_PLAYER 0x80 #define CHAININFO_TARGET_PARAM 0x100 #define CHAININFO_DISABLE_REASON 0x200 #define CHAININFO_DISABLE_PLAYER 0x400 #define CHAININFO_CHAIN_ID 0x800 #define CHAININFO_CHAIN_TYPE 0x1000 //Timing #define TIMING_DRAW_PHASE 0x1 #define TIMING_STANDBY_PHASE 0x2 #define TIMING_MAIN_END 0x4 #define TIMING_BATTLE_START 0x8 #define TIMING_BATTLE_END 0x10 #define TIMING_END_PHASE 0x20 #define TIMING_SUMMON 0x40 #define TIMING_SPSUMMON 0x80 #define TIMING_FLIPSUMMON 0x100 #define TIMING_MSET 0x200 #define TIMING_SSET 0x400 #define TIMING_POS_CHANGE 0x800 #define TIMING_ATTACK 0x1000 #define TIMING_DAMAGE_STEP 0x2000 #define TIMING_DAMAGE_CAL 0x4000 #define TIMING_CHAIN_END 0x8000 #define TIMING_DRAW 0x10000 #define TIMING_DAMAGE 0x20000 #define TIMING_RECOVER 0x40000 #define TIMING_DESTROY 0x80000 #define TIMING_REMOVE 0x100000 #define TIMING_TOHAND 0x200000 #define TIMING_TODECK 0x400000 #define TIMING_TOGRAVE 0x800000 // #define PROCESSOR_NONE 0 #define PROCESSOR_WAITING 0x10000 #define PROCESSOR_END 0x20000 #define PROCESSOR_ADJUST 1 #define PROCESSOR_HINT 2 #define PROCESSOR_TURN 3 #define PROCESSOR_WAIT 4 #define PROCESSOR_REFRESH_LOC 5 #define PROCESSOR_SELECT_IDLECMD 10 #define PROCESSOR_SELECT_EFFECTYN 11 #define PROCESSOR_SELECT_BATTLECMD 12 #define PROCESSOR_SELECT_YESNO 13 #define PROCESSOR_SELECT_OPTION 14 #define PROCESSOR_SELECT_CARD 15 #define PROCESSOR_SELECT_CHAIN 16 #define PROCESSOR_SELECT_PLACE 18 #define PROCESSOR_SELECT_POSITION 19 #define PROCESSOR_SELECT_TRIBUTE 20 #define PROCESSOR_SORT_CHAIN 21 #define PROCESSOR_SELECT_COUNTER 22 #define PROCESSOR_SELECT_SUM 23 #define PROCESSOR_SELECT_DISFIELD 24 #define PROCESSOR_SORT_CARD 25 #define PROCESSOR_POINT_EVENT 30 #define PROCESSOR_QUICK_EFFECT 31 #define PROCESSOR_IDLE_COMMAND 32 #define PROCESSOR_PHASE_EVENT 33 #define PROCESSOR_BATTLE_COMMAND 34 #define PROCESSOR_DAMAGE_PHASE 35 #define PROCESSOR_ADD_CHAIN 40 #define PROCESSOR_SOLVE_CHAIN 42 #define PROCESSOR_SOLVE_CONTINUOUS 43 #define PROCESSOR_EXECUTE_COST 44 #define PROCESSOR_EXECUTE_OPERATION 45 #define PROCESSOR_EXECUTE_TARGET 46 #define PROCESSOR_DESTROY 50 #define PROCESSOR_RELEASE 51 #define PROCESSOR_SENDTO 52 #define PROCESSOR_MOVETOFIELD 53 #define PROCESSOR_CHANGEPOS 54 #define PROCESSOR_OPERATION_REPLACE 55 #define PROCESSOR_DESTROY_STEP 56 #define PROCESSOR_RELEASE_STEP 57 #define PROCESSOR_SENDTO_STEP 58 #define PROCESSOR_SUMMON_RULE 60 #define PROCESSOR_SPSUMMON_RULE 61 #define PROCESSOR_SPSUMMON 62 #define PROCESSOR_FLIP_SUMMON 63 #define PROCESSOR_MSET 64 #define PROCESSOR_SSET 65 #define PROCESSOR_SPSUMMON_STEP 66 #define PROCESSOR_DRAW 70 #define PROCESSOR_DAMAGE 71 #define PROCESSOR_RECOVER 72 #define PROCESSOR_EQUIP 73 #define PROCESSOR_GET_CONTROL 74 #define PROCESSOR_SWAP_CONTROL 75 #define PROCESSOR_PAY_LPCOST 80 #define PROCESSOR_REMOVE_COUNTER 81 #define PROCESSOR_DESTROY_S 100 #define PROCESSOR_RELEASE_S 101 #define PROCESSOR_SENDTO_S 102 #define PROCESSOR_CHANGEPOS_S 103 #define PROCESSOR_ANNOUNCE_RACE 110 #define PROCESSOR_ANNOUNCE_ATTRIB 111 #define PROCESSOR_ANNOUNCE_LEVEL 112 #define PROCESSOR_ANNOUNCE_CARD 113 #define PROCESSOR_ANNOUNCE_TYPE 114 #define PROCESSOR_ANNOUNCE_NUMBER 115 #define PROCESSOR_ANNOUNCE_COIN 116 #define PROCESSOR_TOSS_DICE 117 #define PROCESSOR_TOSS_COIN 118 #define PROCESSOR_SELECT_YESNO_S 120 #define PROCESSOR_SELECT_OPTION_S 121 #define PROCESSOR_SELECT_CARD_S 122 #define PROCESSOR_SELECT_EFFECTYN_S 123 #define PROCESSOR_SELECT_PLACE_S 125 #define PROCESSOR_SELECT_POSITION_S 126 #define PROCESSOR_SELECT_TRIBUTE_S 127 #define PROCESSOR_SORT_CARDS_S 128 #define PROCESSOR_SELECT_TARGET 129 #define PROCESSOR_SELECT_FUSION 130 #define PROCESSOR_SELECT_SYNCHRO 131 #define PROCESSOR_SELECT_SUM_S 132 #define PROCESSOR_SELECT_DISFIELD_S 133 #define PROCESSOR_SPSUMMON_S 135 #define PROCESSOR_SPSUMMON_STEP_S 136 #define PROCESSOR_SPSUMMON_COMP_S 137 #define PROCESSOR_RANDOM_SELECT_S 138 #define PROCESSOR_DRAW_S 140 #define PROCESSOR_DAMAGE_S 141 #define PROCESSOR_RECOVER_S 142 #define PROCESSOR_EQUIP_S 143 #define PROCESSOR_GET_CONTROL_S 144 #define PROCESSOR_SWAP_CONTROL_S 145 #define PROCESSOR_DISCARD_HAND_S 150 #define PROCESSOR_DISCARD_DECK_S 151 #define PROCESSOR_SORT_DECK_S 152 #define PROCESSOR_REMOVEOL_S 160 //Hints #define HINT_EVENT 1 #define HINT_MESSAGE 2 #define HINT_SELECTMSG 3 #define HINT_OPSELECTED 4 #define HINT_EFFECT 5 #define HINT_RACE 6 #define HINT_ATTRIB 7 #define HINT_CODE 8 #define HINT_NUMBER 9 //Messages #define MSG_RETRY 1 #define MSG_HINT 2 #define MSG_WAITING 3 #define MSG_START 4 #define MSG_WIN 5 #define MSG_UPDATE_DATA 6 #define MSG_UPDATE_CARD 7 #define MSG_REQUEST_DECK 8 #define MSG_SELECT_BATTLECMD 10 #define MSG_SELECT_IDLECMD 11 #define MSG_SELECT_EFFECTYN 12 #define MSG_SELECT_YESNO 13 #define MSG_SELECT_OPTION 14 #define MSG_SELECT_CARD 15 #define MSG_SELECT_CHAIN 16 #define MSG_SELECT_PLACE 18 #define MSG_SELECT_POSITION 19 #define MSG_SELECT_TRIBUTE 20 #define MSG_SORT_CHAIN 21 #define MSG_SELECT_COUNTER 22 #define MSG_SELECT_SUM 23 #define MSG_SELECT_DISFIELD 24 #define MSG_SORT_CARD 25 #define MSG_CONFIRM_DECKTOP 30 #define MSG_CONFIRM_CARDS 31 #define MSG_SHUFFLE_DECK 32 #define MSG_SHUFFLE_HAND 33 #define MSG_REFRESH_DECK 34 #define MSG_SWAP_GRAVE_DECK 35 #define MSG_SHUFFLE_SET_CARD 36 #define MSG_NEW_TURN 40 #define MSG_NEW_PHASE 41 #define MSG_MOVE 50 #define MSG_DESTROY 51 #define MSG_RELEASE 52 #define MSG_POS_CHANGE 53 #define MSG_SET 54 #define MSG_SWAP 55 #define MSG_FIELD_DISABLED 56 #define MSG_SUMMONING 60 #define MSG_SUMMONED 61 #define MSG_SPSUMMONING 62 #define MSG_SPSUMMONED 63 #define MSG_FLIPSUMMONING 64 #define MSG_FLIPSUMMONED 65 #define MSG_CHAINING 70 #define MSG_CHAINED 71 #define MSG_CHAIN_SOLVING 72 #define MSG_CHAIN_SOLVED 73 #define MSG_CHAIN_END 74 #define MSG_CHAIN_INACTIVATED 75 #define MSG_CHAIN_DISABLED 76 #define MSG_CARD_SELECTED 80 #define MSG_RANDOM_SELECTED 81 #define MSG_BECOME_TARGET 83 #define MSG_DRAW 90 #define MSG_DAMAGE 91 #define MSG_RECOVER 92 #define MSG_EQUIP 93 #define MSG_LPUPDATE 94 #define MSG_UNEQUIP 95 #define MSG_CARD_TARGET 96 #define MSG_CANCEL_TARGET 97 #define MSG_PAY_LPCOST 100 #define MSG_ADD_COUNTER 101 #define MSG_REMOVE_COUNTER 102 #define MSG_ATTACK 110 #define MSG_BATTLE 111 #define MSG_ATTACK_DISABLED 112 #define MSG_DAMAGE_STEP_START 113 #define MSG_DAMAGE_STEP_END 114 #define MSG_MISSED_EFFECT 120 #define MSG_BE_CHAIN_TARGET 121 #define MSG_CREATE_RELATION 122 #define MSG_RELEASE_RELATION 123 #define MSG_TOSS_COIN 130 #define MSG_TOSS_DICE 131 #define MSG_ANNOUNCE_RACE 140 #define MSG_ANNOUNCE_ATTRIB 141 #define MSG_ANNOUNCE_CARD 142 #define MSG_ANNOUNCE_NUMBER 143 #define MSG_COUNT_TURN 160 #endif /* FIELD_H_ */
[ "[email protected]@a812b692-228c-6283-38e5-8e5dc2e8e749" ]
[ [ [ 1, 698 ] ] ]
f806b3059a6341bb760ef17aeee72bb3b0104148
f695ff54770f828d18e0013d12d9d760ec6363a3
/datastructures/SkipList.h
a8e706dedaa30a6c65a09cf048059e521b77c509
[]
no_license
dbremner/airhan
377e1b1f446a44170f745d3a3a47e0a30bc917e1
a436fda7799c1032d060c30355c309ec1589e058
refs/heads/master
2021-01-10T19:42:16.321886
2010-05-29T02:16:25
2010-05-29T02:16:25
34,024,271
0
0
null
null
null
null
UTF-8
C++
false
false
4,968
h
/*************************************************************** Copyright (c) 2008 Michael Liang Han 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 AIRHAN_DATASTRUCTURE_SKIPLIST_H_ #define AIRHAN_DATASTRUCTURE_SKIPLIST_H_ #include <ctime> #include <cmath> #define AIRHAN_SKIPLIST_MAX_LEVEL 16 #define AIRHAN_SKIPLIST_PROB 0.5 namespace lianghancn { namespace air { namespace datastructures { template<class T> class SkipList { private: template<class T> struct Node { T data; Node<T>** forward; Node(int level, T data) { forward = new Node<T>*[level + 1]; for (int i = 0; i < level + 1; i ++) { forward[i] = NULL; } this->data = data; } ~Node() { delete[] forward; } }; public: virtual ~SkipList() { delete _header; } SkipList() { _header = new Node<T>(AIRHAN_SKIPLIST_MAX_LEVEL, T()); _level = 0; } // test func int RandomLevel() { return GenerateRandomLevel(); } void Insert(T data) { Node<T>* current = _header; Node<T>* update[AIRHAN_SKIPLIST_MAX_LEVEL + 1]; for (int i = 0; i < AIRHAN_SKIPLIST_MAX_LEVEL + 1; i ++) { update[i] = NULL; } for (int i = _level; i >= 0; i --) { while (current->forward[i] != NULL && current->forward[i]->data < data) { current = current->forward[i]; } update[i] = current; } current = current->forward[0]; if (current == NULL || current->data != data) { int level = GenerateRandomLevel(); if (level > _level) { for (int i = _level + 1; i <= level; i ++) { update[i] = _header; } _level = level; } current = new Node<T>(level, data); for (int i = 0; i <= level; i ++) { current->forward[i] = update[i]->forward[i]; update[i]->forward[i] = current; } } } bool Exists(const T& data) { Node<T>* current = _header; for (int i = _level; i >=0; i --) { while (current->forward[i] != NULL && current->forward[i]->data < data) { current = current->forward[i]; } } current = current->forward[0]; return current != NULL && current->data == data; } void Delete(const T& data) { Node<T>* current = _header; Node<T>* update[AIRHAN_SKIPLIST_MAX_LEVEL + 1]; for (int i = 0; i < AIRHAN_SKIPLIST_MAX_LEVEL + 1; i ++) { update[i] = NULL; } for (int i = _level; i >= 0; i --) { while (current->forward[i] != NULL && current->forward[i]->data < data) { current = current->forward[i]; } update[i] = current; } current = current->forward[0]; if (current->data == data) { for (int i = 0; i <= _level; i++) { if (update[i]->forward[i] != current) { break; } update[i]->forward[i] = current->forward[i]; } delete current; while (_level > 0 && _header->forward[_level] == NULL) { _level --; } } } private: int GenerateRandomLevel() { static bool seeded = false; if (!seeded) { srand((unsigned)time(NULL)); seeded = true; } int level = 1; while (((rand() * 1.0/RAND_MAX)) < AIRHAN_SKIPLIST_PROB && level < AIRHAN_SKIPLIST_MAX_LEVEL) { level ++; } return level; } private: Node<T>* _header; int _level; private: SkipList(const SkipList&); SkipList& operator=(const SkipList&); }; }; }; }; #endif
[ "lianghancn@29280b2a-3d39-11de-8f11-b9fadefa0f10" ]
[ [ [ 1, 223 ] ] ]
214d64254db3d2c258eb613ec15344546280f33a
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/GameCore/Source/DataHelper.cpp
bb1c675c2747adf6b10cf0674f209dae1305848d
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
46
cpp
#include "stdafx.h" #include "DataHelper.h"
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 2 ] ] ]
73259456825ab0d5f3b03a98a52e8981f7329872
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/nv38box/Math/WmlPoint4.cpp
b952af04be39e5374bd71b3e8e8b613f63ca44ad
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
3,314
cpp
#include "base.h" // precompiled headers support // Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlPoint4.h" namespace Wml { #include "WmlPoint.inl" } using namespace Wml; //---------------------------------------------------------------------------- template<class Real> Point4<Real>::Point4() { // the point is uninitialized } //---------------------------------------------------------------------------- template<class Real> Point4<Real>::Point4(Real fX, Real fY, Real fZ, Real fW) { m_afTuple[0] = fX; m_afTuple[1] = fY; m_afTuple[2] = fZ; m_afTuple[3] = fW; } //---------------------------------------------------------------------------- template<class Real> Point4<Real>::Point4(const Point4& rkP) { memcpy(m_afTuple, rkP.m_afTuple, 4 * sizeof(Real)); } //---------------------------------------------------------------------------- template<class Real> Point4<Real>::Point4(const Point<4, Real>& rkP) { memcpy(m_afTuple, (const Real *) rkP, 4 * sizeof(Real)); } //---------------------------------------------------------------------------- template<class Real> Real Point4<Real>::X() const { return m_afTuple[0]; } //---------------------------------------------------------------------------- template<class Real> Real& Point4<Real>::X() { return m_afTuple[0]; } //---------------------------------------------------------------------------- template<class Real> Real Point4<Real>::Y() const { return m_afTuple[1]; } //---------------------------------------------------------------------------- template<class Real> Real& Point4<Real>::Y() { return m_afTuple[1]; } //---------------------------------------------------------------------------- template<class Real> Real Point4<Real>::Z() const { return m_afTuple[2]; } //---------------------------------------------------------------------------- template<class Real> Real& Point4<Real>::Z() { return m_afTuple[2]; } //---------------------------------------------------------------------------- template<class Real> Real Point4<Real>::W() const { return m_afTuple[3]; } //---------------------------------------------------------------------------- template<class Real> Real& Point4<Real>::W() { return m_afTuple[3]; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template class WML_ITEM Point<4, float>; template class WML_ITEM Point4<float>; const Point4f Point4f::ZERO(0.0f, 0.0f, 0.0f, 0.0f); template class WML_ITEM Point<4, double>; template class WML_ITEM Point4<double>; const Point4d Point4d::ZERO(0.0, 0.0, 0.0, 0.0); } //----------------------------------------------------------------------------
[ [ [ 1, 117 ] ] ]
2cd3259663c87cb85f00b1498273ccade6175aff
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/src/GUI/proRataTablePane.h
3a595a7f27a7d352a9daf4b9ec8db63c9221f777
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
972
h
#ifndef PRORATATABLEPANE_H #define PRORATATABLEPANE_H #include "proRataProteinTable.h" #include "proRataPeptideTable.h" #include "proRataXmlProcessor.h" #include "proRataSearchPane.h" #include <QSplitter> class ProRataTablePane : public QWidget { Q_OBJECT; public: ProRataTablePane( ProRataXmlProcessors * prxpProcessor, QWidget * qwParent = 0 ); ProRataTablePane( QWidget * qwParent = 0 ); ~ProRataTablePane(); void setProteinTable( ProRataTable * prtTable ); void setPeptideTable( ProRataTable * prtTable ); /* public slots: void hideSearchPane(bool); void reEmitSlot( QString ); signals: void reEmitSearchString( QString ); */ private: void buildUI(); QVBoxLayout *qvbLayout; ProRataProteinTable *prtProtein; ProRataPeptideTable *prtPeptide; ProRataSearchPane *prspFind; ProteomeInfo *mainProteomeInfoInstance; QSplitter *qsTableDivider; }; #endif //PRORATATABLEPANE_H
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 46 ] ] ]
040f0b5b0cddc9078bc389fde845ddd7e183e55c
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Utility/Indicator.h
bd0d625049f52cee65f0dfb24fae890e643e0372
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
3,611
h
/* Indicator.h Written by Matthew Fisher the Indicator class rapidly renders spheres or cylinders between arbitrary points in three space by using stored mesh data and loading a new Matrix4 each time a cylinder or sphere needs "indicating." also can do basic viewing frustrum (camera) analysis or rendering. */ #pragma once enum IndicatorShapeType { IndicatorShapeSphere, IndicatorShapeCylinder, }; struct IndicatorShape { IndicatorShape() {} IndicatorShape(IndicatorShapeType _Type, const Vec3f &Pos0, const Vec3f &Pos1, float _Radius, RGBColor _Color) { Type = _Type; Pos[0] = Pos0; Pos[1] = Pos1; Color = _Color; Radius = _Radius; } static IndicatorShape Sphere(const Vec3f &Pos, float Radius, RGBColor Color); static IndicatorShape Cylinder(const Vec3f &P0, const Vec3f &P1, float Radius, RGBColor Color); Matrix4 TransformMatrix() const; IndicatorShapeType Type; Vec3f Pos[2]; RGBColor Color; float Radius; }; class Indicator { public: void Init(GraphicsDevice &GD, int SphereRefinement, int Stacks, int Slices); //creates a new sphere with the given number of refinements, //and a new cylinder with the given number of stacks/slices void RenderCylinder(GraphicsDevice &GD, MatrixController &MC, float Radius, const Vec3f &P1, const Vec3f &P2, const RGBColor &Color, bool RenderArrow = false, bool ColorNormals = false); void RenderBox(GraphicsDevice &GD, MatrixController &MC, float Radius, const Rectangle3f &Rect, RGBColor Color); void RenderArrow(GraphicsDevice &GD, MatrixController &MC, const Vec3f &P1, const Vec3f &P2, const RGBColor &Color, bool ColorNormals = false); void RenderSphere(GraphicsDevice &GD, MatrixController &MC, //renders the existing sphere in the given color such that its center is float Radius, const Vec3f &P1, const RGBColor &Color); //P1 and it has the given radius. void GetCameraLine(const Matrix4 &Projection, const Camera &C, //given x and y both on the perspective cube (the interval -1 to 1), returns the same line float x, float y, Vec3f &P1Out, Vec3f &P2Out); //segment in world coordinates given the provided perspective Matrix4 and camera's view Matrix4. void DrawCameraLine(GraphicsDevice &GD, MatrixController &MC, const Matrix4 &Projection, //calls GetCameraLine and then renders the given line as a cylinder float Radius, const RGBColor &Color, const Camera &C, float x, float y); //having the given radius and color void DrawCamera(GraphicsDevice &GD, MatrixController &MC, //renders the entire 8 lines of the perspective cube (x, y) from (-1 to 1) and z from (0 to 1) const Matrix4 &Perspective, float Radius, float Length, const Camera &C); //as cylinders of the given radius. Also renders the camera's eye vector as a sphere, //and the 3 orthogonal vectors (VecEye, VecLookDir, VecLeft) that represent that camera's basis //as cylinders of the given Length centered on VecEye. void CreateMesh(const Vector<IndicatorShape> &Shapes, BaseMesh &MOut) const; private: RGBColor _CylinderColor; Mesh _Cylinder, _ArrowHead, _Sphere, _Lozenge, _Box; };
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 71 ] ] ]
d74616309c0e34fed4a4efe1791036463bc0f8f6
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Animation/Animation/SplineCompressed/hkaSplineSkeletalAnimation.inl
a2371e189e1c7623f1d2f5098b68177bb4bc55e6
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,777
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ /// Copies dynamic and static values into their respective components, based on a mask /// \param mask Mask describing the dynamic and static components of the data /// \param S Static values /// \param I Identity values /// \param inOut Output with static/identity values overwritten void hkaSplineSkeletalAnimation::recompose( hkUint8 mask, const hkVector4& S, const hkVector4& I, hkVector4& inOut ) { #if defined( HK_PLATFORM_XBOX360 ) // This mask reverses bits static const int reverse[16] = { 0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF }; hkVector4Comparison stat; stat.set( static_cast< hkVector4Comparison::Mask >( reverse[ mask & 0x0F ] ) ); hkVector4Comparison iden; iden.set( static_cast< hkVector4Comparison::Mask >( reverse[ ~mask & ( ~mask >> 4 ) & 0x0F ] ) ); inOut.select32( inOut, S, stat ); inOut.select32( inOut, I, iden ); #else int stat = mask & 0x0F; int iden = ~mask & ( ~mask >> 4 ) & 0x0F; int shift = 0x01; for ( int i = 0; i < 4; i++ ) { if ( stat & shift ) { inOut( i ) = S( i ); } else if ( iden & shift ) { inOut( i ) = I( i ); } shift <<= 1; } #endif } /// Reads 8 bits from an internal buffer /// \param dataInOut Buffer which is incremented hkUint8 hkaSplineSkeletalAnimation::read8( const hkUint8*& dataInOut ) { return *dataInOut++; } /// Reads 16 bits from an internal buffer /// \param dataInOut Buffer which is incremented hkUint16 hkaSplineSkeletalAnimation::read16( const hkUint8*& dataInOut ) { return *reinterpret_cast< const hkUint16*& >( dataInOut )++; } /// Reads a real value from an internal buffer /// \param dataInOut Buffer which is incremented hkReal hkaSplineSkeletalAnimation::readReal( const hkUint8*& dataInOut ) { return *reinterpret_cast< const hkReal*& >( dataInOut )++; } /// Update a pointer to be aligned /// \param align Number of bytes to align (must be a multiple of 2) void hkaSplineSkeletalAnimation::readAlign( int align, const hkUint8*& dataInOut ) { dataInOut = reinterpret_cast< const hkUint8 * > ( HK_NEXT_MULTIPLE_OF( align, reinterpret_cast< hk_size_t >( dataInOut ) ) ); } /// Align a point for quaternions (varies based on the number of bytes per quaternion) /// \param type The type of quaternion compression to use /// \param dataInOut Pointer to byte buffer (updated) void hkaSplineSkeletalAnimation::readAlignQuaternion( TrackCompressionParams::RotationQuantization type, const hkUint8*& dataInOut ) { HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( type ), "Spline data corrupt." ); // Bit mask for byte alignment // Each type has it's own unique byte alignment static const int align[6] = { 4, 1, 2, 1, 2, 4 }; readAlign( align[ type ], dataInOut ); } /// \return The number of bytes required for the current quaternion packing scheme /// \param type The type of quaternion compression to use int hkaSplineSkeletalAnimation::bytesPerQuaternion( TrackCompressionParams::RotationQuantization type ) { HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( type ), "Spline data corrupt." ); static const int size[6] = { 4, 5, 6, 3, 2, 16 }; return size[ type ]; } /// \return The number of bytes required per component for the current packing scheme /// \param type The type of quaternion compression to use int hkaSplineSkeletalAnimation::bytesPerComponent( TrackCompressionParams::ScalarQuantization type ) { HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( type ), "Spline data corrupt." ); static const int size[2] = { 1, 2 }; return size[ type ]; } /// \return A packed floating point value expanded /// \param minp Minimum expected value /// \param maxp Maximum expected value /// \param Packed value to expand hkReal hkaSplineSkeletalAnimation::unpack16( hkReal minp, hkReal maxp, hkUint16 val ) { const hkReal span = 65535.0f; return ( static_cast< hkReal >( val ) / span ) * ( maxp - minp ) + minp; } /// Unpack the representation of the given quantization types /// \param translation The type of translation quantization given /// \param rotation The type of rotation quantization given /// \param scale The type of scale quantization given void hkaSplineSkeletalAnimation::unpackQuantizationTypes( hkUint8 packedQuatizationTypes, TrackCompressionParams::ScalarQuantization& translation, TrackCompressionParams::RotationQuantization& rotation, TrackCompressionParams::ScalarQuantization& scale ) { translation = static_cast< TrackCompressionParams::ScalarQuantization >( ( packedQuatizationTypes >> 0 ) & 0x03 ); rotation = static_cast< TrackCompressionParams::RotationQuantization >( ( packedQuatizationTypes >> 2 ) & 0x0F ); scale = static_cast< TrackCompressionParams::ScalarQuantization >( ( packedQuatizationTypes >> 6 ) & 0x03 ); HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( translation ), "Spline data corrupt." ); HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( rotation ), "Spline data corrupt." ); HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( scale ), "Spline data corrupt." ); } void hkaSplineSkeletalAnimation::unpackMaskAndQuantizationType( hkUint8 packedMaskAndQuatizationType, hkUint8& mask, TrackCompressionParams::ScalarQuantization& floatQuantization ) { // Read in the floatQuantization from the 1st (not 0th) bit floatQuantization = static_cast< TrackCompressionParams::ScalarQuantization >( ( packedMaskAndQuatizationType >> 1 ) & 0x03 ); mask = packedMaskAndQuatizationType & ~0x06; HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( floatQuantization ), "Spline data corrupt." ); HK_ASSERT2( 0x3aa3eb74, ( mask & 0x06 ) == 0, "Spline data corrupt." ); } /// \return A packed floating point value expanded /// \param minp Minimum expected value /// \param maxp Maximum expected value /// \param Packed value to expand hkReal hkaSplineSkeletalAnimation::unpack8( hkReal minp, hkReal maxp, hkUint8 val ) { const hkReal span = 255.0f; return ( static_cast< hkReal >( val ) / span ) * ( maxp - minp ) + minp; } /// Expands a quantized quaternion /// \param type The type of quaternion compression to use /// \param in Input buffer to read from /// \param out Quaternion to store the result void hkaSplineSkeletalAnimation::unpackQuaternion( TrackCompressionParams::RotationQuantization type, const hkUint8* in, hkQuaternion* out ) { static void ( HK_CALL * unpackfunc[6] )( const hkUint8* in, hkQuaternion* out ) = { unpackSignedQuaternion32, unpackSignedQuaternion40, unpackSignedQuaternion48, unpackSignedQuaternion24, unpackSignedQuaternion16, unpackSignedQuaternion128 }; HK_ASSERT2( 0x3aa3eb74, TrackCompressionParams::validQuantization( type ), "Spline data corrupt." ); (* unpackfunc[ type ] )( in, out ); } /// Evaluate the spline at a given time. Chooses from several optimized function implementations /// \param u Time to evaluate at /// \param p Degree of the curve /// \param U Array of knot values for the given time /// \param P Array of control point values for the given time /// \param out Output value void hkaSplineSkeletalAnimation::evaluate( hkReal u, int p, hkReal U[ MAX_DEGREE * 2 ], hkVector4 P[ MAX_ORDER ], hkVector4& out ) { static void (* evaluateFunction[4] )( hkReal u, int p, hkReal U[ MAX_DEGREE * 2 ], hkVector4 P[ MAX_ORDER ], hkVector4& out ) = #if (HK_CONFIG_SIMD == HK_CONFIG_SIMD_ENABLED) && !defined(HK_SIMULATE_SPU_DMA_ON_CPU) { HK_NULL, evaluateLinear, evaluateSIMD, evaluateSIMD }; #else { HK_NULL, evaluateLinear, evaluateSimple, evaluateSimple }; #endif HK_ASSERT2( 0x3aa3eb74, p >= 1 && p <= 3, "Spline data corrupt." ); return evaluateFunction[ p ]( u, p, U, P, out ); } /// Algorithm A2.1 The NURBS Book p68 - Determine the knot span index /// \return The index i such that U[i] <= u < U[i+1] /// \param n Max control point index /// \param p Degree /// \param u Knot value to find span for as byte /// \param U Array of knots as bytes int hkaSplineSkeletalAnimation::findSpan( int n, int p, hkUint8 u, const hkUint8* U ) { // Bounds protect // Splines can extrapolate, so times (slightly) outside the range are OK. if ( u >= U[ n+1 ] ) return n; if ( u <= U[0] ) return p; // Search int low = p; int high = n + 1; int mid = ( low + high ) / 2; while ( u < U[mid] || u >= U[mid+1] ) { if ( u < U[mid] ) high = mid; else low = mid; mid = ( low + high ) / 2; } return mid; } /// Find the local time within a block and computes the data pointer /// \param time Time to query the animation /// \param blockOut Which block the local time lies within /// \param blockTimeOut Local time within the block /// \param quantizedTimeOut Time expressed as integer within the block void hkaSplineSkeletalAnimation::getBlockAndTime( hkReal time, int& blockOut, hkReal& blockTimeOut, hkUint8& quantizedTimeOut ) const { // Find the appropriate block blockOut = static_cast< int >( time * m_blockInverseDuration ); // Clamp the block blockOut = hkMath::max2( blockOut, 0 ); blockOut = hkMath::min2( blockOut, m_numBlocks-1 ); // Find the local time within the block blockTimeOut = time - static_cast< hkReal >( blockOut ) * m_blockDuration; // Find the truncated time quantizedTimeOut = static_cast< hkUint8 >( ( blockTimeOut * m_blockInverseDuration ) * ( m_maxFramesPerBlock - 1 ) ); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 274 ] ] ]
a770f50f605cdaf62c9754da2be7b66dd2f69ad0
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/common/weak_reference.h
586a04b88e0c8752076cee8595893cde65681673
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
h
#pragma once template<typename T> class weak_reference { public: weak_reference() {} explicit weak_reference(T* object) : m_object(object) { if(object) { ASSERT(dynamic_cast<T::weak_ref_type*>(object)); if(!((T::weak_ref_type*)object)->m_weak_ref_flag) ((T::weak_ref_type*)object)->m_weak_ref_flag = make_shared<bool>(true); m_valid = ((T::weak_ref_type*)object)->m_weak_ref_flag; } } inline T* get() const { return (m_valid && *m_valid) ? m_object : NULL; } inline T* operator->() const { ASSERT(operator bool()); return get(); } inline operator bool() const { return m_valid && *m_valid && m_object; } weak_reference<T>& operator=(T* object) { m_object = object; if(object) { ASSERT(dynamic_cast<T::weak_ref_type*>(object)); if(!((T::weak_ref_type*)object)->m_weak_ref_flag) ((T::weak_ref_type*)object)->m_weak_ref_flag = make_shared<bool>(true); m_valid = ((T::weak_ref_type*)object)->m_weak_ref_flag; } else m_valid.reset(); return *this; } private: shared_ptr<bool> m_valid; T* m_object; }; template<typename T> class weak_ref_provider { template<typename T> friend class weak_reference; public: typedef weak_ref_provider<T> weak_ref_type; ~weak_ref_provider() { if(m_weak_ref_flag) *m_weak_ref_flag = false; } private: mutable shared_ptr<bool> m_weak_ref_flag; };
[ [ [ 1, 64 ] ] ]
dce4fdd8fb7db8a2b8c52a0b2cf0d2d12434665f
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/lang/OutOfMemoryError.h
600148d159c477126bc0ec509b8a2e60b416ad4f
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
746
h
#ifndef _CLASS_GOD_LANG_OUTOFMEMORYERROR_H #define _CLASS_GOD_LANG_OUTOFMEMORYERROR_H #ifdef __cplusplus #include "lang/Error.h" using namespace goddk::lang; namespace goddk { namespace lang { /*!\brief This class is used to indicate that the application has run * out of memory. * \ingroup CXX_LANG_m */ class OutOfMemoryError : public virtual Error { public: inline OutOfMemoryError() { } inline OutOfMemoryError(const char* message) : Error(message) { } inline OutOfMemoryError(const String* message) : Error(message) { } inline ~OutOfMemoryError() { } }; typedef CSmartPtr<OutOfMemoryError> OutOfMemoryErrorPtr; } } #endif #endif
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 38 ] ] ]
238701e0f4e241f25afb62e3b16b7a4a345ff1a2
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Graphics/Volume/Julia.h
5ef4a09b05c3d7c9daac792811a1dd1b79bdce98
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
1,588
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the LGPL like the rest of the engine. ----------------------------------------------------------------------------- */ /* Original author: John C. Hare * Date: June 26, 1996 (although I've had these around for at least 6 years) * Adapted to C++ by W.J. van der Laan 2004 */ #ifndef H_Q_Julia #define H_Q_Julia #include <cmath> namespace OUAN { struct Quat { float r,i,j,k; }; inline void qadd(Quat &a, const Quat &b) { a.r += b.r; a.i += b.i; a.j += b.j; a.k += b.k; } inline void qmult(Quat &c, const Quat &a, const Quat &b) { c.r = a.r*b.r - a.i*b.i - a.j*b.j - a.k*b.k; c.i = a.r*b.i + a.i*b.r + a.j*b.k - a.k*b.j; c.j = a.r*b.j + a.j*b.r + a.k*b.i - a.i*b.k; c.k = a.r*b.k + a.k*b.r + a.i*b.j - a.j*b.i; } inline void qsqr(Quat &b, const Quat &a) { b.r = a.r*a.r - a.i*a.i - a.j*a.j - a.k*a.k; b.i = 2.0f*a.r*a.i; b.j = 2.0f*a.r*a.j; b.k = 2.0f*a.r*a.k; } class Julia { private: float global_real, global_imag, global_theta; Quat oc,c,eio,emio; public: Julia(); Julia(float global_real, float global_imag, float global_theta); float eval(float x, float y, float z); }; } #endif
[ "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 66 ] ] ]
8ecc445467195a578aea7aca6b2c113358bd3a72
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndShop.cpp
c16011daff411e82e2986a080545f81637bb5d6b
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
96,310
cpp
#include "stdafx.h" #include "defineSound.h" #include "defineText.h" #include "defineObj.h" #include "AppDefine.h" #include "WndManager.h" #include "DPClient.h" extern CDPClient g_DPlay; #if __VER >= 12 // __TAX #include "Tax.h" #endif // __TAX #define PARTSMESH_HAIR( nSex ) ( nSex == SEX_MALE ? _T( "Part_maleHair%02d.o3d" ) : _T( "Part_femaleHair%02d.o3d" ) ) #define PARTSMESH_HEAD( nSex ) ( nSex == SEX_MALE ? _T( "Part_maleHead%02d.o3d" ) : _T( "Part_femaleHead%02d.o3d" ) ) #define PARTSMESH_UPPER( nSex ) ( nSex == SEX_MALE ? _T( "Part_maleUpper.o3d" ) : _T( "Part_femaleUpper.o3d" ) ) #define PARTSTEX_UPPER( nSex ) ( nSex == SEX_MALE ? _T( "Part_maleUpper%02d.dds" ) : _T( "Part_femaleUpper%02d.dds" ) ) #define TEX_PART_UPPER( nSex ) ( nSex == SEX_MALE ? _T( "Part_maleUpper01.dds" ) : _T( "Part_femaleUpper01.dds" ) ) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndWarning::CWndWarning() { m_pMover = NULL; m_pItemElem = NULL; } CWndWarning::~CWndWarning() { } BOOL CWndWarning::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { InitDialog( g_Neuz.GetSafeHwnd(), dwWndId, WBS_KEY, 0, pWndParent ); MoveParentCenter(); // CWndStatic* pLabel = (CWndStatic *)GetDlgItem( WIDC_STATIC1 ); // pLabel->m_dwColor = 0xffff0000; // pLabel = (CWndStatic *)GetDlgItem( WIDC_STATIC2 ); // pLabel->m_dwColor = 0xffff0000; return TRUE; } BOOL CWndWarning::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_OK ) { SAFE_DELETE( ((CWndShop*)m_pParentWnd)->m_pWndConfirmSell ); ((CWndShop*)m_pParentWnd)->m_pWndConfirmSell = new CWndConfirmSell; ((CWndShop*)m_pParentWnd)->m_pWndConfirmSell->m_pItemElem = m_pItemElem; ((CWndShop*)m_pParentWnd)->m_pWndConfirmSell->m_pMover = m_pMover; ((CWndShop*)m_pParentWnd)->m_pWndConfirmSell->Initialize( m_pParentWnd, APP_CONFIRM_SELL ); Destroy(); } if( nID == WIDC_CANCEL ) { Destroy(); } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndConfirmSell::CWndConfirmSell() { m_pMover = NULL; m_pItemElem = NULL; m_pEdit = NULL; m_pStatic = NULL; } CWndConfirmSell::~CWndConfirmSell() { } #if __VER >= 14 // __DROP_CONFIRM_BUG BOOL CWndConfirmSell::Process( void ) { if(m_pItemElem->GetExtra() > 0) { Destroy(); } return TRUE; } #endif // __DROP_CONFIRM_BUG void CWndConfirmSell::OnDraw( C2DRender* p2DRender ) { if( m_pItemElem->IsEmpty() ) { m_pStaticGold->SetTitle( CString( "0" ) ); return; } LPCTSTR szNumber; szNumber = m_pEdit->GetString(); int nNumber = atoi( szNumber ); if( m_pItemElem->m_nItemNum == 1 ) { m_pEdit->SetString( "1" ); } else { if( m_pItemElem->m_nItemNum < nNumber ) { char szNumberbuf[16] = {0, }; nNumber = m_pItemElem->m_nItemNum; _itoa( m_pItemElem->m_nItemNum, szNumberbuf, 10 ); m_pEdit->SetString( szNumberbuf ); } int i; for( i = 0 ; i < 8 ; i++ ) { char szNumberbuf[8] = {0, }; strncpy( szNumberbuf, szNumber, 8 ); // 0 : 공백, 48 : 숫자 0, 57 : 숫자 9 if( 47 >= szNumberbuf[i] || szNumberbuf[i] >= 58 ) { if( szNumberbuf[i] != 0 ) { nNumber = m_pItemElem->m_nItemNum; _itoa( m_pItemElem->m_nItemNum, szNumberbuf, 10 ); m_pEdit->SetString( szNumberbuf ); break; } } } } DWORD dwCost = m_pItemElem->GetCost(); DWORD BuyGold = dwCost / 4; #ifdef __SHOP_COST_RATE BuyGold = static_cast< DWORD >( static_cast< float >( BuyGold ) * prj.m_fShopSellRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX if( CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, m_pItemElem ) ) BuyGold -= ( static_cast<DWORD>(BuyGold * CTax::GetInstance()->GetSalesTaxRate( g_pPlayer )) ); #endif // __TAX // TCHAR szNumberGold[ 64 ]; CString szNumberGold; #if __VER < 8 // __S8_PK KarmaProp* pProp = prj.GetKarmaProp( g_pPlayer->m_nSlaughter ); if( pProp && pProp->fSellPenaltyRate != 0 ) BuyGold *= pProp->fSellPenaltyRate; #endif // __VER < 8 // __S8_PK if( BuyGold < 1 ) BuyGold = 1; BuyGold *= nNumber; // _itot( BuyGold, szNumberGold, 10 ); szNumberGold.Format("%u", BuyGold); m_pStaticGold->SetTitle( szNumberGold ); } void CWndConfirmSell::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); CWndButton* pOk = (CWndButton*)GetDlgItem( WIDC_OK ); CWndBase* pEdit = (CWndButton*)GetDlgItem( WIDC_EDITSELL ); CWndStatic* pStatic = (CWndStatic *)GetDlgItem( WIDC_STATIC2 ); pStatic->AddWndStyle(WSS_MONEY); pOk->SetDefault( TRUE ); pEdit->SetFocus(); } BOOL CWndConfirmSell::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { InitDialog( g_Neuz.GetSafeHwnd(), APP_CONFIRM_SELL, WBS_KEY, 0, pWndParent ); MoveParentCenter(); CWndStatic* pLabel = (CWndStatic *)GetDlgItem( WIDC_STATIC ); // pLabel->m_dwColor = 0xff000000; m_pEdit = (CWndEdit *)GetDlgItem( WIDC_EDITSELL ); m_pStatic = (CWndStatic *)GetDlgItem( WIDC_CONTROL1 ); m_pStaticGold = (CWndStatic *)GetDlgItem( WIDC_STATIC2 ); // m_pStatic->m_dwColor = m_pStaticGold->m_dwColor = 0xff000000; if( m_pItemElem->m_nItemNum == 1 ) { m_pEdit->SetString( "1" ); // m_pEdit->SetVisible( FALSE ); } else { TCHAR szNumber[ 64 ]; _itot( m_pItemElem->m_nItemNum, szNumber, 10 ); m_pEdit->SetString( szNumber ); } DWORD dwCost = m_pItemElem->GetCost(); DWORD BuyGold = dwCost / 4; #ifdef __SHOP_COST_RATE BuyGold = static_cast< DWORD >( static_cast< float >( BuyGold ) * prj.m_fShopSellRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX BuyGold -= ( static_cast<DWORD>(BuyGold * CTax::GetInstance()->GetSalesTaxRate( g_pPlayer )) ); #endif // __TAX #if __VER < 8 // __S8_PK KarmaProp* pProp = prj.GetKarmaProp( g_pPlayer->m_nSlaughter ); if( pProp && pProp->fSellPenaltyRate != 0 ) BuyGold *= pProp->fSellPenaltyRate; #endif // __VER < 8 // __S8_PK if( BuyGold < 1 ) BuyGold = 1; BuyGold *= m_pItemElem->m_nItemNum; // TCHAR szNumberGold[ 64 ]; CString szNumberGold; szNumberGold.Format("%u", BuyGold); // _itot( BuyGold, szNumberGold, 10 ); m_pStaticGold->SetTitle( szNumberGold ); return TRUE; } BOOL CWndConfirmSell::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndConfirmSell::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndConfirmSell::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndConfirmSell::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndConfirmSell::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_OK ) { PLAYSND( SND_INF_TRADE ); int SellNum = 0; if( m_pItemElem->m_nItemNum >= 1 ) { SellNum = atoi( m_pEdit->GetString() ); } if( SellNum != 0 ) { g_DPlay.SendSellItem( (BYTE)( m_pItemElem->m_dwObjId ), SellNum ); } } if( nID == WIDC_CANCEL ) { } if( nID != WIDC_EDITSELL ) { Destroy(); } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndConfirmBuy::CWndConfirmBuy() { m_pMover = NULL; m_pItemElem = NULL; m_dwItemId = 0; m_pEdit = NULL; m_pStatic = NULL; #if __VER >= 11 // __CSC_VER11_3 m_nBuyType = 0; #endif //__CSC_VER11_3 } CWndConfirmBuy::~CWndConfirmBuy() { } void CWndConfirmBuy::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); } BOOL CWndConfirmBuy::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndConfirmBuy::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndConfirmBuy::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndConfirmBuy::OnLButtonDown( UINT nFlags, CPoint point ) { } // 살려는 수량이 바뀌면, 가격표시도 변경시킨다. void CWndConfirmBuy::OnChangeBuyCount( DWORD dwBuy ) { // TCHAR szString[ 64 ]; CString szString; if( dwBuy != atoi(m_pEdit->GetString()) ) { // _itot( dwBuy, szString, 10 ); // integer to string szString.Format("%u", dwBuy); m_pEdit->SetString( szString ); } DWORD dwTotalBuy = 0; DWORD dwCost = 0; #if __VER >= 8 // __S8_PK #if __VER >= 11 // __CSC_VER11_3 if(m_nBuyType == 0) { dwCost = m_pItemElem->GetCost(); #ifdef __SHOP_COST_RATE dwCost = static_cast< int >( static_cast< float >( dwCost ) * prj.m_fShopBuyRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX if( CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, m_pItemElem ) ) dwCost += ( static_cast<DWORD>(dwCost * CTax::GetInstance()->GetPurchaseTaxRate( g_pPlayer )) ); #endif // __TAX } else if(m_nBuyType == 1) dwCost = m_pItemElem->GetChipCost(); #else //__CSC_VER11_3 dwCost = m_pItemElem->GetCost(); #endif //__CSC_VER11_3 dwTotalBuy = (DWORD)( dwBuy * dwCost * prj.m_fShopCost ); #if __VER >= 11 // __MA_VER11_02 if( m_pItemElem->m_dwItemId == II_SYS_SYS_SCR_PERIN ) { dwCost = PERIN_VALUE; dwTotalBuy = dwBuy * dwCost; } #endif //__MA_VER11_02 if(dwTotalBuy > INT_MAX) { dwBuy--; szString.Format("%u", dwBuy); m_pEdit->SetString( szString ); dwTotalBuy = (DWORD)( dwBuy * dwCost * prj.m_fShopCost ); } szString.Format("%u", dwTotalBuy); // _itot( dwTotalBuy, szString, 10 ); // integer to string #else // KarmaProp* pProp = prj.GetKarmaProp( g_pPlayer->m_nSlaughter ); if( pProp ) { dwTotalBuy = m_pItemElem->GetCost() * pProp->fDiscountRate; if( dwTotalBuy <= 0 ) dwTotalBuy = 1; dwTotalBuy = dwBuy * dwCost * prj.m_fShopCost; #if __VER >= 11 // __MA_VER11_02 if( m_pItemElem->m_dwItemId == II_SYS_SYS_SCR_PERIN ) { dwCost = PERIN_VALUE; dwTotalBuy = dwBuy * dwCost } #endif //__MA_VER11_02 // _itot( dwTotalBuy, szString, 10 ); // integer to string szString.Format("%u", dwTotalBuy); } #endif // __VER < 8 // __S8_PK m_pStaticGold->SetTitle( szString ); } BOOL CWndConfirmBuy::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { InitDialog( g_Neuz.GetSafeHwnd(), APP_CONFIRM_BUY_, 0, 0, pWndParent ); MoveParentCenter(); if( m_pItemElem ) m_dwItemId = m_pItemElem->m_dwItemId; CWndStatic* pLabel = (CWndStatic *)GetDlgItem( WIDC_STATIC ); // pLabel->m_dwColor = 0xff000000; m_pEdit = (CWndEdit *)GetDlgItem( WIDC_CONTROL2 ); m_pStatic = (CWndStatic *)GetDlgItem( WIDC_CONTROL1 ); m_pStaticGold = (CWndStatic *)GetDlgItem( WIDC_STATIC2 ); // m_pStatic->m_dwColor = m_pStaticGold->m_dwColor = 0xff000000; m_pStaticGold->AddWndStyle(WSS_MONEY); #if __VER >= 11 // __CSC_VER11_3 DWORD dwCost; if(m_nBuyType == 0) { dwCost = m_pItemElem->GetCost(); #ifdef __SHOP_COST_RATE dwCost = static_cast< int >( static_cast< float >( dwCost ) * prj.m_fShopBuyRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX if( CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, m_pItemElem ) ) dwCost += ( static_cast<DWORD>(dwCost * CTax::GetInstance()->GetPurchaseTaxRate( g_pPlayer )) ); #endif // __TAX } else if(m_nBuyType == 1) dwCost = m_pItemElem->GetChipCost(); #else //__CSC_VER11_3 DWORD dwCost = m_pItemElem->GetCost(); #endif //__CSC_VER11_3 if( dwCost == 0 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0006) ) ); // "다른 사용자에게 팔렸습니다." Destroy(); return TRUE; } OnChangeBuyCount( 1 ); return TRUE; } void CWndConfirmBuy::OnDraw( C2DRender* p2DRender ) { DWORD dwCost = m_pItemElem->GetCost(); #ifdef __SHOP_COST_RATE dwCost = static_cast< int >( static_cast< float >( dwCost ) * prj.m_fShopBuyRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX if( CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, m_pItemElem ) ) dwCost += ( static_cast<DWORD>(dwCost * CTax::GetInstance()->GetPurchaseTaxRate( g_pPlayer )) ); #endif // __TAX if( dwCost == 0 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0006) ) ); // 다른 사용자에게 팔렸습니다. Destroy(); return; } return; } const int MAX_BUY_ITEMCOUNT = 99; BOOL CWndConfirmBuy::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { int nBuyNum = 0; switch( nID ) { case WIDC_PLUS: nBuyNum = atoi(m_pEdit->GetString()); ++nBuyNum; #if __VER >= 13 // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_BCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_RCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW || m_pItemElem->GetProp()->dwID == II_CHP_RED ) { if ( nBuyNum > 9999 ) nBuyNum = 9999; } #else // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW ) { if ( nBuyNum > 1000 ) nBuyNum = 1000; } #endif // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 else { if ( nBuyNum > MAX_BUY_ITEMCOUNT ) nBuyNum = MAX_BUY_ITEMCOUNT; } OnChangeBuyCount(nBuyNum); break; case WIDC_MINUS: nBuyNum = atoi(m_pEdit->GetString()); if ( --nBuyNum < 1 ) nBuyNum = 1; OnChangeBuyCount(nBuyNum); break; case WIDC_MAX: { #if __VER >= 13 // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_BCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_RCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW || m_pItemElem->GetProp()->dwID == II_CHP_RED ) OnChangeBuyCount( 9999 ); #else // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW ) OnChangeBuyCount( 1000 ); #endif // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 #if __VER >= 11 // __MA_VER11_02 else if( m_pItemElem->m_dwItemId == II_SYS_SYS_SCR_PERIN ) OnChangeBuyCount( 21 ); #endif //__MA_VER11_02 else OnChangeBuyCount( MAX_BUY_ITEMCOUNT ); } break; case WIDC_CONTROL2: if( EN_CHANGE == message ) { if( m_pEdit == NULL ) { ADDERRORMSG( "CWndConfirmBuy::OnChildNotify : m_pEdit == NULL" ); char szMsg[256]; sprintf( szMsg, "CWndConfirmBuy::OnChildNotify : more info(%d, %d)", pLResult, GetDlgItem( WIDC_CONTROL2 ) ); ADDERRORMSG( szMsg ); nBuyNum = 1; } else nBuyNum = atoi(m_pEdit->GetString()); nBuyNum = max( nBuyNum, 0 ); DWORD dwMAXCount = MAX_BUY_ITEMCOUNT; #if __VER >= 13 // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_BCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_RCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW || m_pItemElem->GetProp()->dwID == II_CHP_RED ) dwMAXCount = 9999; #else // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW ) dwMAXCount = 1000; #endif // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 #if __VER >= 11 // __MA_VER11_02 else if( m_pItemElem->m_dwItemId == II_SYS_SYS_SCR_PERIN ) dwMAXCount = 21; #endif //__MA_VER11_02 nBuyNum = min( nBuyNum, (int)( dwMAXCount ) ); OnChangeBuyCount(nBuyNum); } break; case WIDC_CANCEL: Destroy(); break; case WIDC_OK: OnOK(); Destroy(); break; } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndConfirmBuy::OnOK() { #if __VER >= 11 // __CSC_VER11_3 //아래 메세지 처리 할 것 DWORD dwCost; int nBuy; if(m_nBuyType == 1) { dwCost = m_pItemElem->GetChipCost(); if( m_pItemElem->m_nItemNum < 1 || dwCost == 0 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0006) ) ); // 다른 사용자에게 팔렸습니다. return; } nBuy = atoi( m_pEdit->GetString() ); if( (int)( (nBuy * dwCost) ) > g_pPlayer->m_Inventory.GetAtItemNum( II_CHP_RED ) ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_GAME_CANNTBUY_REDCHIP) ) ); // 칩이 부족합니다. return; } } else if(m_nBuyType == 0) { dwCost = m_pItemElem->GetCost(); #if __VER >= 12 // __TAX if( m_pItemElem->m_dwItemId != II_SYS_SYS_SCR_PERIN ) { if( CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, m_pItemElem ) ) dwCost += ( static_cast<DWORD>(dwCost * CTax::GetInstance()->GetPurchaseTaxRate( g_pPlayer )) ); } #endif // __TAX if( m_pItemElem->m_nItemNum < 1 || dwCost == 0 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0006) ) ); // 다른 사용자에게 팔렸습니다. return; } nBuy = atoi( m_pEdit->GetString() ); if( (int)( (nBuy * dwCost) ) > g_pPlayer->GetGold() ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0009) ) ); // 돈이 부족합니다. return; } } #else //__CSC_VER11_3 DWORD dwCost = m_pItemElem->GetCost(); if( m_pItemElem->m_nItemNum < 1 || dwCost == 0 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0006) ) ); // 다른 사용자에게 팔렸습니다. return; } int nBuy = atoi( m_pEdit->GetString() ); if( (nBuy * dwCost) > g_pPlayer->GetGold() ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0009) ) ); // 돈이 부족합니다. return; } #endif //__CSC_VER11_3 DWORD dwMAXCount = MAX_BUY_ITEMCOUNT; #if __VER >= 13 // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_BCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_RCHARM || m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW || m_pItemElem->GetProp()->dwID == II_CHP_RED ) dwMAXCount = 9999; #else // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( m_pItemElem->GetProp()->dwItemKind3 == IK3_ARROW ) dwMAXCount = 1000; #endif // __MAX_BUY_ITEM9999 // 화살포스터구입갯수9999개 if( nBuy < 1 || nBuy > (int)( dwMAXCount ) ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0086) ) ); // 상점 거래 중 구입 / 판매 개수가 1 ~ 99 사이가 아닌 수를 입력 return; } if( nBuy > m_pItemElem->m_nItemNum ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0087) ) ); // 개인 상점 거래 중 구입 하려는 개수가 상점에 판매하는 개수 보다 많거나, 이미 품절 return; } CWndShop* pWndShop = (CWndShop*)GetWndBase( APP_SHOP_ ); CWndTabCtrl* pTabCtrl = (CWndTabCtrl*)pWndShop->GetDlgItem( WIDC_INVENTORY ); CHAR cTab = (CHAR)pTabCtrl->GetCurSel(); #if __VER >= 11 // __CSC_VER11_3 if(m_nBuyType == 0) g_DPlay.SendBuyItem( cTab, (BYTE)( m_pItemElem->m_dwObjId ), nBuy, m_dwItemId ); else if(m_nBuyType == 1) g_DPlay.SendBuyChipItem( cTab, (BYTE)( m_pItemElem->m_dwObjId ), nBuy, m_dwItemId ); #else //__CSC_VER11_3 g_DPlay.SendBuyItem( cTab, m_pItemElem->m_dwObjId, nBuy, m_dwItemId ); #endif //__CSC_VER11_3 PLAYSND( SND_INF_TRADE ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndItemCtrlVendor::CWndItemCtrlVendor() { m_bVisibleCount = FALSE; } CWndItemCtrlVendor::~CWndItemCtrlVendor() { } BOOL CWndItemCtrlVendor::OnDropIcon( LPSHORTCUT pShortcut, CPoint point ) { if( pShortcut->m_dwShortcut == SHORTCUT_ITEM ) GetParentWnd()->OnChildNotify( WIN_ITEMDROP, m_nIdWnd, (LRESULT*)pShortcut ); return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndShop::CWndShop() { m_pMover = NULL; m_pWndConfirmSell = NULL; m_pWndWarning = NULL; m_bSexSort = FALSE; m_bLevelSort = FALSE; } CWndShop::~CWndShop() { SAFE_DELETE( m_pWndConfirmSell ); SAFE_DELETE( m_pWndWarning ); SAFE_DELETE( g_WndMng.m_pWndTradeGold ); } void CWndShop::OnDraw( C2DRender* p2DRender ) { LPCHARACTER lpCharacter = m_pMover->GetCharacter(); if( lpCharacter == NULL) return; CString string; CWndStatic* pCost = (CWndStatic*) GetDlgItem( WIDC_COST ); CWndTabCtrl* pTabCtrl = (CWndTabCtrl*)GetDlgItem( WIDC_INVENTORY ); WTCITEM item; pTabCtrl->GetItem( pTabCtrl->GetCurSel(), &item ); CWndItemCtrl* pItemCtrl = (CWndItemCtrl*)item.pWndBase; DWORD dwCost = 0; int nIndex = -1; if( pItemCtrl->GetSelectedCount() > 0 ) nIndex = pItemCtrl->GetSelectedItem( 0 ); if( nIndex >= 0 ) { // CItemBase* pItemBase = pItemCtrl->m_pArrayItemBase[nIndex]; CItemBase* pItemBase = pItemCtrl->GetItemFromArr( nIndex ); #if __VER >= 11 // __CSC_VER11_3 if( pItemBase && m_pMover ) { LPCHARACTER lpCharacter = m_pMover->GetCharacter(); if(lpCharacter) { if(lpCharacter->m_nVenderType == 0) { dwCost += pItemBase->GetCost(); #ifdef __SHOP_COST_RATE dwCost = static_cast< int >( static_cast< float >( dwCost ) * prj.m_fShopBuyRate ); #endif // __SHOP_COST_RATE #if __VER >= 12 // __TAX if(CTax::GetInstance()->IsApplyTaxRate( g_pPlayer, (CItemElem*)pItemBase )) dwCost += ( static_cast<DWORD>(dwCost * CTax::GetInstance()->GetPurchaseTaxRate( g_pPlayer )) ); #endif // __TAX } else if(lpCharacter->m_nVenderType == 1) dwCost += pItemBase->GetChipCost(); } } #else //__CSC_VER11_3 if( pItemBase ) dwCost += pItemBase->GetCost()/* * ( (CItemElem*)pItemBase )->m_nItemNum*/; #endif //__CSC_VER11_3 } dwCost = (int)((float)dwCost * prj.m_fShopCost ); #if __VER < 8 // __S8_PK KarmaProp* pProp = prj.GetKarmaProp( g_pPlayer->m_nSlaughter ); if( pProp ) { dwCost = (int)( dwCost * pProp->fDiscountRate ); if( dwCost <= 0 ) dwCost = 1; } #endif // __VER < 8 // __S8_PK #if __VER >= 11 // __MA_VER11_02 if( nIndex >= 0 ) { CItemBase* pItemBase = pItemCtrl->GetItemFromArr( nIndex ); if( pItemBase && pItemBase->m_dwItemId == II_SYS_SYS_SCR_PERIN ) dwCost = PERIN_VALUE; } #endif //__MA_VER11_02 string.Format( _T( "%d" ), dwCost ); pCost->SetTitle( string ); } void CWndShop::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); #if __VER >= 11 // __SYS_POCKET if(GetWndBase( APP_BAG_EX )) GetWndBase( APP_BAG_EX )->Destroy(); #endif if( g_WndMng.m_pWndTrade || g_WndMng.m_pWndBank || g_WndMng.m_pWndGuildBank || g_WndMng.GetWndVendorBase() ) { Destroy(); return; } CWndTabCtrl* pTabCtrl = (CWndTabCtrl*)GetDlgItem( WIDC_INVENTORY ); WTCITEM tabTabItem; tabTabItem.mask = WTCIF_TEXT | WTCIF_PARAM; LPCHARACTER lpCharacter = m_pMover->GetCharacter(); if( lpCharacter ) { int i; for( i = 0; i < MAX_VENDOR_INVENTORY_TAB; i++ ) { if( lpCharacter->m_venderSlot[ i ].IsEmpty() == FALSE ) { m_wndItemCtrl[ i ].Create( WLVS_ICON, CRect( 0, 0, 250, 250 ), pTabCtrl, i + 10 ); m_wndItemCtrl[ i ].InitItem( m_pMover->m_ShopInventory[ i ], APP_SHOP_ ); tabTabItem.pszText = lpCharacter->m_venderSlot[ i ].LockBuffer(); lpCharacter->m_venderSlot[ i ].UnlockBuffer(); tabTabItem.pWndBase = &m_wndItemCtrl[ i ]; pTabCtrl->InsertItem( i, &tabTabItem ); } } for( i = pTabCtrl->GetSize(); i < 3; i++ ) { tabTabItem.pszText = ""; tabTabItem.pWndBase = NULL; pTabCtrl->InsertItem( i, &tabTabItem ); } } CWndInventory* pWndInventory = (CWndInventory*)GetWndBase( APP_INVENTORY ); CRect rectInventory = pWndInventory->GetWindowRect( TRUE ); CPoint ptInventory = rectInventory.TopLeft(); CPoint ptMove; CRect rect = GetWindowRect( TRUE ); if( ptInventory.x > rect.Width() / 2 ) ptMove = ptInventory - CPoint( rect.Width(), 0 ); else ptMove = ptInventory + CPoint( rectInventory.Width(), 0 ); Move( ptMove ); } BOOL CWndShop::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { return InitDialog( g_Neuz.GetSafeHwnd(), APP_SHOP_, 0, 0, pWndParent ); } BOOL CWndShop::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndShop::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndShop::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndShop::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndShop::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { BOOL bWarning = FALSE; if( message == WIN_ITEMDROP ) { LPSHORTCUT lpShortcut = (LPSHORTCUT)pLResult; CWndBase* pWndFrame = lpShortcut->m_pFromWnd->GetFrameWnd(); BOOL bForbid = TRUE; if( lpShortcut->m_dwType == ITYPE_ITEM && lpShortcut->m_dwData != 0 ) { if( nID == 10 || nID == 11 || nID == 12 || nID == 13) // item { BOOL bResult = TRUE; if( ( (CItemElem*)lpShortcut->m_dwData )->IsQuest() ) { bResult = FALSE; } if( bResult && pWndFrame->GetWndId() == APP_INVENTORY ) { CItemElem *pItemElem = (CItemElem*)lpShortcut->m_dwData; if( pItemElem ) { ItemProp *pProp = pItemElem->GetProp(); if( pProp ) { if( pItemElem->IsCharged() ) { // 090527 김창섭 - 유료지역입장권 사용 후 사용기간이 남아있는 상태에서 NPC를 통해 상점에 팔 경우 경고창이 뜨지않는 현상 수정 //if( !pItemElem->m_dwKeepTime ) bWarning = TRUE; } } else { LPCTSTR szErr = Error( "CWndShop::OnChildNotify : pProp==NULL %d", pItemElem->m_dwItemId ); ADDERRORMSG( szErr ); } } else { LPCTSTR szErr = Error( "CWndShop::OnChildNotify : pItemElem==NULL %d", pItemElem->m_dwItemId ); ADDERRORMSG( szErr ); } if( FALSE == g_pPlayer->m_Inventory.IsEquip( ( (CItemElem*)lpShortcut->m_dwData)->m_dwObjId ) ) { if( bWarning ) { SAFE_DELETE( m_pWndWarning ); SAFE_DELETE( m_pWndConfirmSell ); m_pWndWarning = new CWndWarning; m_pWndWarning->m_pItemElem = (CItemElem*)lpShortcut->m_dwData; m_pWndWarning->m_pMover = m_pMover; m_pWndWarning->Initialize( this, APP_WARNING ); } else { SAFE_DELETE( m_pWndWarning ); SAFE_DELETE( m_pWndConfirmSell ); m_pWndConfirmSell = new CWndConfirmSell; m_pWndConfirmSell->m_pItemElem = (CItemElem*)lpShortcut->m_dwData; m_pWndConfirmSell->m_pMover = m_pMover; m_pWndConfirmSell->Initialize( this, APP_CONFIRM_SELL ); } bForbid = FALSE; } else { g_WndMng.PutString( prj.GetText(TID_GAME_EQUIPTRADE), NULL, prj.GetTextColor(TID_GAME_EQUIPTRADE) ); // g_WndMng.PutString( "장착된아이템은 팔수 없습니다.", NULL, 0xffff0000 ); } } } } SetForbid( bForbid ); } switch( nID ) { case WIDC_CHECK_LEVEL: { m_bLevelSort = !m_bLevelSort; } break; case WIDC_CHECK2: { m_bSexSort = !m_bSexSort; } break; } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndShop::OnDestroyChildWnd( CWndBase* pWndChild ) { if( pWndChild == m_pWndConfirmSell ) SAFE_DELETE( m_pWndConfirmSell ); } void CWndShop::OnDestroy( void ) { g_pPlayer->m_vtInfo.SetOther( NULL ); g_DPlay.SendCloseShopWnd(); CWndInventory* pWndInventory = (CWndInventory*)g_WndMng.GetWndBase( APP_INVENTORY ); if( pWndInventory ) { SAFE_DELETE( pWndInventory->m_pWndConfirmBuy ); } SAFE_DELETE( m_pWndConfirmSell ); } ////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndBeautyShop::CWndBeautyShop() { // SetPutRegInfo( FALSE ); m_pWndConfirmSell = NULL; m_pModel = NULL; m_dwHairMesh = 1; memset( m_ColorRect, 0, sizeof(CRect)*3 ); memset( m_fColor, 0, sizeof(FLOAT)*3 ); m_bLButtonClick = FALSE; m_nHairCost = 0; #if __VER >= 8 //__CSC_VER8_4 m_pApplyModel = NULL; m_nHairColorCost = 0; #else m_nHairColorCostR = 0; m_nHairColorCostG = 0; m_nHairColorCostB = 0; #endif //__CSC_VER8_4 #ifdef __Y_BEAUTY_SHOP_CHARGE m_bChange = FALSE; #endif //__Y_BEAUTY_SHOP_CHARGE #if __VER >= 8 //__CSC_VER8_4 for(int i=0; i<4; i++) { m_nHairNum[i] = 0; } m_pHairModel = NULL; m_dwSelectHairMesh = 1; m_ChoiceBar = -1; m_pWndBeautyShopConfirm = NULL; #endif //__CSC_VER8_4 #ifdef __NEWYEARDAY_EVENT_COUPON m_bUseCoupon = FALSE; m_pWndUseCouponConfirm = NULL; #endif //__NEWYEARDAY_EVENT_COUPON } CWndBeautyShop::~CWndBeautyShop() { // m_Texture.DeleteDeviceObjects(); SAFE_DELETE( m_pModel ); SAFE_DELETE( m_pWndConfirmSell ); #if __VER >= 8 //__CSC_VER8_4 SAFE_DELETE(m_pApplyModel); SAFE_DELETE(m_pHairModel); SAFE_DELETE(m_pWndBeautyShopConfirm); #endif //__CSC_VER8_4 #ifdef __NEWYEARDAY_EVENT_COUPON SAFE_DELETE(m_pWndUseCouponConfirm); #endif //__NEWYEARDAY_EVENT_COUPON } #ifdef __NEWYEARDAY_EVENT_COUPON void CWndBeautyShop::UseHairCoupon(BOOL isUse) { m_bUseCoupon = isUse; if(m_bUseCoupon) { CString title = GetTitle(); CString addText; addText.Format(" %s", prj.GetText( TID_GAME_NOWUSING_COUPON )); title = title + addText; SetTitle(title); } } #endif //__NEWYEARDAY_EVENT_COUPON HRESULT CWndBeautyShop::InvalidateDeviceObjects() { #ifdef __YDEBUG m_Texture.Invalidate(); #endif //__YDEBUG CWndBase::InvalidateDeviceObjects(); return S_OK; } HRESULT CWndBeautyShop::DeleteDeviceObjects() { CWndBase::DeleteDeviceObjects(); return InvalidateDeviceObjects(); } HRESULT CWndBeautyShop::RestoreDeviceObjects() { #ifdef __YDEBUG m_Texture.SetInvalidate(m_pApp->m_pd3dDevice); #endif //__YDEBUG CWndBase::RestoreDeviceObjects(); return S_OK; } void CWndBeautyShop::OnDraw( C2DRender* p2DRender ) { #if __VER >= 8 //__CSC_VER8_4 if( g_pPlayer == NULL || m_pModel == NULL || m_pApplyModel == NULL ) #else if( g_pPlayer == NULL || m_pModel == NULL ) #endif //__CSC_VER8_4 return; LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice; pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_ARGB( 255, 255,255,255) ); CRect rect = GetClientRect(); // 뷰포트 세팅 D3DVIEWPORT9 viewport; // 월드 D3DXMATRIXA16 matWorld; D3DXMATRIXA16 matScale; D3DXMATRIXA16 matRot; D3DXMATRIXA16 matTrans; // 카메라 D3DXMATRIX matView; D3DXVECTOR3 vecLookAt( 0.0f, 0.0f, 3.0f ); D3DXVECTOR3 vecPos( 0.0f, 0.7f, -3.5f ); D3DXMatrixLookAtLH( &matView, &vecPos, &vecLookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f) ); pd3dDevice->SetTransform( D3DTS_VIEW, &matView ); #ifdef __YENV D3DXVECTOR3 vDir( 0.0f, 0.0f, 1.0f ); SetLightVec( vDir ); #endif //__YENV // 왼쪽 원본 모델 랜더링 { LPWNDCTRL lpFace = GetWndCtrl( WIDC_CUSTOM5 ); viewport.X = p2DRender->m_ptOrigin.x + lpFace->rect.left;//2; viewport.Y = p2DRender->m_ptOrigin.y + lpFace->rect.top;//5; viewport.Width = lpFace->rect.Width();//p2DRender->m_clipRect.Width(); viewport.Height = lpFace->rect.Height();// - 10;//p2DRender->m_clipRect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; /* D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4.0f, fAspect, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); */ FLOAT fov = D3DX_PI/4.0f;//796.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matWorld); D3DXMatrixScaling(&matScale, 4.5f, 4.5f, 4.5f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.0f,-5.6f,0.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-5.2f,0.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); // 랜더링 pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );//m_bViewLight ); ::SetLight( FALSE ); ::SetFog( FALSE ); SetDiffuse( 1.0f, 1.0f, 1.0f ); SetAmbient( 1.0f, 1.0f, 1.0f ); m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = g_pPlayer->m_fHairColorR; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = g_pPlayer->m_fHairColorG; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = g_pPlayer->m_fHairColorB; D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV ::SetTransformView( matView ); ::SetTransformProj( matProj ); if( g_pPlayer ) g_pPlayer->OverCoatItemRenderCheck(m_pModel); #if __VER < 8 //__CSC_VER8_4 // 헬멧이 머리카락 날려야하는것이냐? // 인벤이 있는 경우 CItemElem* pItemElem = g_pPlayer->GetEquipItem( PARTS_CAP ); if( pItemElem ) { O3D_ELEMENT* pElement = NULL; ItemProp* pItemProp = pItemElem->GetProp(); if( pItemProp && pItemProp->dwBasePartsIgnore != -1 ) { pElement = m_pModel->GetParts(pItemProp->dwBasePartsIgnore); //if( pElement ) // pElement->m_nEffect |= XE_HIDE; } // 외투의상을 입었을경우 머리날릴것인가의 기준을 외투 모자를 기준으로 바꾼다 CItemElem* pItemElemOvercoat = g_pPlayer->GetEquipItem( PARTS_HAT ); if( pItemElemOvercoat ) { if( !pItemElemOvercoat->IsFlag( CItemElem::expired ) ) { ItemProp* pItemPropOC = pItemElemOvercoat->GetProp(); if( pItemPropOC && pItemPropOC->dwBasePartsIgnore != -1 ) { if( pItemPropOC->dwBasePartsIgnore == PARTS_HEAD ) m_pModel->SetEffect(PARTS_HAIR, XE_HIDE); m_pModel->SetEffect(pItemPropOC->dwBasePartsIgnore, XE_HIDE); } else { if( pElement ) pElement->m_nEffect &= ~XE_HIDE; } } } } else { // 외투의상을 입었을경우 머리날릴것인가의 기준을 외투 모자를 기준으로 바꾼다 CItemElem* pItemElemOvercoat = g_pPlayer->GetEquipItem( PARTS_HAT ); if( pItemElemOvercoat ) { if( !pItemElemOvercoat->IsFlag( CItemElem::expired ) ) { ItemProp* pItemPropOC = pItemElemOvercoat->GetProp(); if( pItemPropOC && pItemPropOC->dwBasePartsIgnore != -1 ) { if( pItemPropOC->dwBasePartsIgnore == PARTS_HEAD ) m_pModel->SetEffect(PARTS_HAIR, XE_HIDE); m_pModel->SetEffect(pItemPropOC->dwBasePartsIgnore, XE_HIDE); } } } } #endif //__CSC_VER8_4 m_pModel->Render( p2DRender->m_pd3dDevice, &matWorld ); } // 오른쪽 색입힌 모델 랜더링 { LPWNDCTRL lpFace = GetWndCtrl( WIDC_CUSTOM6 ); viewport.X = p2DRender->m_ptOrigin.x + lpFace->rect.left;//2; viewport.Y = p2DRender->m_ptOrigin.y + lpFace->rect.top;//5; viewport.Width = lpFace->rect.Width();//p2DRender->m_clipRect.Width(); viewport.Height = lpFace->rect.Height();// - 10;//p2DRender->m_clipRect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; /* D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4.0f, fAspect, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); */ FLOAT fov = D3DX_PI/4.0f;//796.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matRot); D3DXMatrixIdentity(&matWorld); D3DXMatrixRotationY(&matRot,g_tmCurrent/1000.0f); D3DXMatrixScaling(&matScale, 4.5f, 4.5f, 4.5f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.0f,-5.6f,0.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-5.2f,0.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matRot ); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); ::SetLight( FALSE ); ::SetFog( FALSE ); #if __VER >= 8 //__CSC_VER8_4 m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = m_fColor[0]; m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = m_fColor[1]; m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = m_fColor[2]; #else m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = m_fColor[0]; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = m_fColor[1]; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = m_fColor[2]; #endif //__CSC_VER8_4 D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV #if __VER >= 8 //__CSC_VER8_4 if( g_pPlayer ) g_pPlayer->OverCoatItemRenderCheck(m_pApplyModel); #endif //__CSC_VER8_4 ::SetTransformView( matView ); ::SetTransformProj( matProj ); #if __VER < 8 //__CSC_VER8_4 // 헬멧이 머리카락 날려야하는것이냐? // 인벤이 있는 경우 CItemElem* pItemElem = g_pPlayer->GetEquipItem( PARTS_CAP ); if( pItemElem ) { ItemProp* pItemProp = pItemElem->GetProp(); if( pItemProp && pItemProp->dwBasePartsIgnore != -1 ) { if( pItemProp->dwBasePartsIgnore == PARTS_HEAD ) m_pModel->SetEffect(PARTS_HAIR, XE_HIDE ); m_pModel->SetEffect(pItemProp->dwBasePartsIgnore, XE_HIDE ); } } else { pItemElem = g_pPlayer->GetEquipItem( PARTS_HAT ); if( pItemElem ) { if( !pItemElem->IsFlag( CItemElem::expired ) ) { ItemProp* pItemProp = pItemElem->GetProp(); if( pItemProp && pItemProp->dwBasePartsIgnore != -1 ) { if( pItemProp->dwBasePartsIgnore == PARTS_HEAD ) m_pModel->SetEffect(PARTS_HAIR, XE_HIDE ); m_pModel->SetEffect(pItemProp->dwBasePartsIgnore, XE_HIDE ); } } } } #endif //__CSC_VER8_4 #if __VER >= 8 //__CSC_VER8_4 m_pApplyModel->Render( p2DRender->m_pd3dDevice, &matWorld ); m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = 1.0f; m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = 1.0f; m_pApplyModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = 1.0f; #else m_pModel->Render( p2DRender->m_pd3dDevice, &matWorld ); m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = 1.0f; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = 1.0f; m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = 1.0f; #endif //__CSC_VER8_4 } #if __VER >= 8 //__CSC_VER8_4 DrawHairKind(p2DRender, matView); #endif //__CSC_VER8_4 viewport.X = p2DRender->m_ptOrigin.x;// + 5; viewport.Y = p2DRender->m_ptOrigin.y;// + 5; viewport.Width = p2DRender->m_clipRect.Width(); viewport.Height = p2DRender->m_clipRect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); for( int i=0; i<3; i++ ) { CPoint pt = CPoint( m_ColorScrollBar[i].x - ( m_Texture.m_size.cx / 2 ), m_ColorScrollBar[i].y ); m_Texture.Render( p2DRender, pt ); } for( int j=0; j<3; j++ ) { if( m_ColorScrollBar[j].x != m_OriginalColorScrollBar[j].x ) m_Texture.Render( p2DRender, CPoint( m_OriginalColorScrollBar[j].x - ( m_Texture.m_size.cx / 2 ), m_OriginalColorScrollBar[j].y ), 160 ); } pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); // 가격 계산 BYTE nColorR = (BYTE)( (m_fColor[0] * 255) ); BYTE nColorG = (BYTE)( (m_fColor[1] * 255) ); BYTE nColorB = (BYTE)( (m_fColor[2] * 255) ); BYTE nOrignalR = (BYTE)( g_pPlayer->m_fHairColorR * 255 ); BYTE nOrignalG = (BYTE)( g_pPlayer->m_fHairColorG * 255 ); BYTE nOrignalB = (BYTE)( g_pPlayer->m_fHairColorB * 255 ); #if __VER >= 8 //__CSC_VER8_4 #ifdef __NEWYEARDAY_EVENT_COUPON if( (nColorR != nOrignalR || nColorG != nOrignalG || nColorB != nOrignalB) && !m_bUseCoupon ) #else //__NEWYEARDAY_EVENT_COUPON if( nColorR != nOrignalR || nColorG != nOrignalG || nColorB != nOrignalB ) #endif //__NEWYEARDAY_EVENT_COUPON m_nHairColorCost = HAIRCOLOR_COST; else m_nHairColorCost = 0; #else if( nColorR >= nOrignalR ) m_nHairColorCostR = (nColorR - nOrignalR)*13; else m_nHairColorCostR = (nOrignalR - nColorR)*7; if( nColorG >= nOrignalG ) m_nHairColorCostG = (nColorG - nOrignalG)*13; else m_nHairColorCostG = (nOrignalG - nColorG)*7; if( nColorB >= nOrignalB ) m_nHairColorCostB = (nColorB - nOrignalB)*13; else m_nHairColorCostB = (nOrignalB - nColorB)*7; #endif //__CSC_VER8_4 CString string; CWndStatic* pCost = (CWndStatic*) GetDlgItem( WIDC_COST ); if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) { string = "0"; } else { #if __VER >= 8 //__CSC_VER8_4 string.Format( _T( "%d" ), m_nHairCost + m_nHairColorCost ); #else string.Format( _T( "%d" ), m_nHairCost + m_nHairColorCostR + m_nHairColorCostG + m_nHairColorCostB ); #endif //__CSC_VER8_4 } pCost->SetTitle( string ); pCost = (CWndStatic*) GetDlgItem( WIDC_STATIC1 ); if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) { string = "0"; } else { string.Format( _T( "%d" ), m_nHairCost ); } pCost->SetTitle( string ); pCost = (CWndStatic*) GetDlgItem( WIDC_STATIC2 ); if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) { string = "0"; } else { #if __VER >= 8 //__CSC_VER8_4 string.Format( _T( "%d" ), m_nHairColorCost ); #else string.Format( _T( "%d" ), m_nHairColorCostR + m_nHairColorCostG + m_nHairColorCostB ); #endif //__CSC_VER8_4 } pCost->SetTitle( string ); } #if __VER >= 8 //__CSC_VER8_4 void CWndBeautyShop::DrawHairKind(C2DRender* p2DRender, D3DXMATRIX matView) { // 뷰포트 세팅 D3DVIEWPORT9 viewport; // 월드 D3DXMATRIXA16 matWorld; D3DXMATRIXA16 matScale; D3DXMATRIXA16 matTrans; //Hair Kind DWORD HairNum = m_dwHairMesh; LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice; int custom[4] = {WIDC_CUSTOM1, WIDC_CUSTOM2, WIDC_CUSTOM3, WIDC_CUSTOM4}; if(m_pHairModel == NULL) return; LPWNDCTRL lpHair = GetWndCtrl( custom[0] ); viewport.Width = lpHair->rect.Width() - 2; viewport.Height = lpHair->rect.Height() - 2; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; FLOAT fov = D3DX_PI/4.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); for(int i=0; i<4; i++) { ( HairNum > MAX_HAIR ) ? HairNum = 1: HairNum; m_nHairNum[i] = HairNum; lpHair = GetWndCtrl( custom[i] ); //Model Draw CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, HairNum-1, g_pPlayer->m_dwHeadMesh, g_pPlayer->m_aEquipInfo, m_pHairModel, NULL ); viewport.X = p2DRender->m_ptOrigin.x + lpHair->rect.left; viewport.Y = p2DRender->m_ptOrigin.y + lpHair->rect.top; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matWorld); D3DXMatrixScaling(&matScale, 6.0f, 6.0f, 6.0f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.05f,-8.0f,-1.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-7.5f,-1.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); ::SetLight( FALSE ); ::SetFog( FALSE ); SetDiffuse( 1.0f, 1.0f, 1.0f ); SetAmbient( 1.0f, 1.0f, 1.0f ); m_pHairModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = g_pPlayer->m_fHairColorR; m_pHairModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = g_pPlayer->m_fHairColorG; m_pHairModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = g_pPlayer->m_fHairColorB; D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV ::SetTransformView( matView ); ::SetTransformProj( matProj ); m_pHairModel->Render( p2DRender->m_pd3dDevice, &matWorld ); //Select Draw if(m_dwSelectHairMesh == m_nHairNum[i]) { CRect rect; rect = lpHair->rect; p2DRender->RenderFillRect( rect, 0x60ffff00 ); } HairNum++; } } void CWndBeautyShop::UpdateModels() { if(m_pModel != NULL) CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pModel, &g_pPlayer->m_Inventory ); if(m_pApplyModel != NULL) CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwSelectHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); } #endif //__CSC_VER8_4 void CWndBeautyShop::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); CWndInventory* pWndInventory = (CWndInventory*)GetWndBase( APP_INVENTORY ); CRect rectInventory = pWndInventory->GetWindowRect( TRUE ); CPoint ptInventory = rectInventory.TopLeft(); CPoint ptMove; CRect rect = GetWindowRect( TRUE ); if( ptInventory.x > rect.Width() / 2 ) ptMove = ptInventory - CPoint( rect.Width(), 0 ); else ptMove = ptInventory + CPoint( rectInventory.Width(), 0 ); Move( ptMove ); #if __VER >= 8 //__CSC_VER8_4 LPWNDCTRL lpWndCtrl; lpWndCtrl = GetWndCtrl( WIDC_CUSTOM_R ); rect = lpWndCtrl->rect; m_ColorRect[0].left = rect.left; m_ColorRect[0].top = rect.top + 25; m_ColorRect[0].right = rect.right; m_ColorRect[0].bottom = rect.bottom + 25; m_ColorRect[0] = rect; lpWndCtrl = GetWndCtrl( WIDC_CUSTOM_G ); rect = lpWndCtrl->rect; m_ColorRect[1].left = rect.left; m_ColorRect[1].top = rect.top + 25; m_ColorRect[1].right = rect.right; m_ColorRect[1].bottom = rect.bottom + 25; m_ColorRect[1] = rect; lpWndCtrl = GetWndCtrl( WIDC_CUSTOM_B ); rect = lpWndCtrl->rect; m_ColorRect[2].left = rect.left; m_ColorRect[2].top = rect.top + 25; m_ColorRect[2].right = rect.right; m_ColorRect[2].bottom = rect.bottom + 25; m_ColorRect[2] = rect; ReSetBar( m_fColor[0], m_fColor[1], m_fColor[2] ); m_OriginalColorScrollBar[0] = m_ColorScrollBar[0]; m_OriginalColorScrollBar[1] = m_ColorScrollBar[1]; m_OriginalColorScrollBar[2] = m_ColorScrollBar[2]; m_pRGBEdit[0] = (CWndEdit*)GetDlgItem( WIDC_EDIT1 ); m_pRGBEdit[1] = (CWndEdit*)GetDlgItem( WIDC_EDIT2 ); m_pRGBEdit[2] = (CWndEdit*)GetDlgItem( WIDC_EDIT3 ); SetRGBToEdit(m_fColor[0], 0); SetRGBToEdit(m_fColor[1], 1); SetRGBToEdit(m_fColor[2], 2); CWndStatic* kindcost = (CWndStatic*)GetDlgItem( WIDC_STATIC1 ); CWndStatic* colorcost = (CWndStatic*)GetDlgItem( WIDC_STATIC2 ); CWndStatic* totalcost = (CWndStatic*)GetDlgItem( WIDC_COST ); kindcost->AddWndStyle(WSS_MONEY); colorcost->AddWndStyle(WSS_MONEY); totalcost->AddWndStyle(WSS_MONEY); #endif //__CSC_VER8_4 } BOOL CWndBeautyShop::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { if( g_pPlayer == NULL ) return FALSE; m_bLButtonClick = FALSE; m_dwHairMesh = g_pPlayer->m_dwHairMesh+1; SAFE_DELETE( m_pModel ); int nMover = (g_pPlayer->GetSex() == SEX_MALE ? MI_MALE : MI_FEMALE); m_pModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pModel, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pModel, &g_pPlayer->m_Inventory ); m_pModel->InitDeviceObjects( g_Neuz.GetDevice() ); #if __VER >= 8 //__CSC_VER8_4 SAFE_DELETE( m_pApplyModel ); m_pApplyModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pApplyModel, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); m_pApplyModel->InitDeviceObjects( g_Neuz.GetDevice() ); #endif //__CSC_VER8_4 /// m_fColor[0] = g_pPlayer->m_fHairColorR; m_fColor[1] = g_pPlayer->m_fHairColorG; m_fColor[2] = g_pPlayer->m_fHairColorB; #if __VER >= 8 //__CSC_VER8_4 m_dwSelectHairMesh = m_dwHairMesh; SAFE_DELETE(m_pHairModel); m_pHairModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pHairModel, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pHairModel, &g_pPlayer->m_Inventory ); m_pHairModel->InitDeviceObjects( g_Neuz.GetDevice() ); m_nHairCost = 0; m_nHairColorCost = 0; #else /// m_ColorRect[0].left = 44; m_ColorRect[0].top = 251; m_ColorRect[0].right = 162; m_ColorRect[0].bottom = 267; m_ColorRect[1].left = 44; m_ColorRect[1].top = 272; m_ColorRect[1].right = 162; m_ColorRect[1].bottom = 287; m_ColorRect[2].left = 44; m_ColorRect[2].top = 293; m_ColorRect[2].right = 162; m_ColorRect[2].bottom = 307; m_nHairCost = 0; m_nHairColorCostR = 0; m_nHairColorCostG = 0; m_nHairColorCostB = 0; ReSetBar( m_fColor[0], m_fColor[1], m_fColor[2] ); m_OriginalColorScrollBar[0] = m_ColorScrollBar[0]; m_OriginalColorScrollBar[1] = m_ColorScrollBar[1]; m_OriginalColorScrollBar[2] = m_ColorScrollBar[2]; #endif m_Texture.LoadTexture( g_Neuz.GetDevice(), MakePath( DIR_THEME, "yellowbuttten.tga" ), 0xffff00ff, TRUE ); #if __VER >= 8 //__CSC_VER8_4 return InitDialog( g_Neuz.GetSafeHwnd(), APP_BEAUTY_SHOP_EX, 0, 0, pWndParent ); #else return InitDialog( g_Neuz.GetSafeHwnd(), APP_BEAUTY_SHOP, 0, 0, pWndParent ); #endif //__CSC_VER8_4 } #if __VER >= 8 //__CSC_VER8_4 void CWndBeautyShop::SetRGBToEdit(float color, int editnum) { char szNumberbuf[8] = {0, }; #ifdef __Y_HAIR_BUG_FIX float colorval = (color / 1.0f) * 255; #else //__Y_HAIR_BUG_FIX float colorval = ((color-0.3f)/(1.0f - 0.3f)) * 255 + 0.5f; #endif //__Y_HAIR_BUG_FIX _itot( (int)( colorval ), szNumberbuf, 10 ); m_pRGBEdit[editnum]->SetString(szNumberbuf); } void CWndBeautyShop::SetRGBToBar(int editnum) { float RGBNum; int ColorNum; CWndEdit* pWndEdit; if(editnum == WIDC_EDIT1) { ColorNum = 0; pWndEdit = m_pRGBEdit[0]; } else if(editnum == WIDC_EDIT2) { ColorNum = 1; pWndEdit = m_pRGBEdit[1]; } else if(editnum == WIDC_EDIT3) { ColorNum = 2; pWndEdit = m_pRGBEdit[2]; } RGBNum = (float)( atoi(pWndEdit->GetString()) ); if(RGBNum < 0) { RGBNum = 0; pWndEdit->SetString("0"); } #ifdef __Y_HAIR_BUG_FIX else if(RGBNum > 255) { RGBNum = 255; pWndEdit->SetString("255"); } #else //__Y_HAIR_BUG_FIX else if(RGBNum > 254) { RGBNum = 254; pWndEdit->SetString("254"); } #endif //__Y_HAIR_BUG_FIX #ifdef __Y_HAIR_BUG_FIX m_fColor[ColorNum] = (RGBNum / 255) * 1.0f; #else //__Y_HAIR_BUG_FIX m_fColor[ColorNum] = (RGBNum / 255) * (1.0f - 0.3f) + 0.3f; #endif //__Y_HAIR_BUG_FIX ReSetBar( m_fColor[0], m_fColor[1], m_fColor[2] ); } #endif //__CSC_VER8_4 void CWndBeautyShop::ReSetBar( FLOAT r, FLOAT g, FLOAT b ) { #ifdef __Y_HAIR_BUG_FIX FLOAT fR = (r/1.0f) * 100.0f; FLOAT fG = (g/1.0f) * 100.0f; FLOAT fB = (b/1.0f) * 100.0f; #else //__Y_HAIR_BUG_FIX FLOAT fR = ((r-0.3f)/(1.0f - 0.3f)) * 100.0f; FLOAT fG = ((g-0.3f)/(1.0f - 0.3f)) * 100.0f; FLOAT fB = ((b-0.3f)/(1.0f - 0.3f)) * 100.0f; #endif //__Y_HAIR_BUG_FIX #if __VER >= 8 //__CSC_VER8_4 m_ColorScrollBar[0].x = (LONG)( (((m_ColorRect[0].right-m_ColorRect[0].left) * fR) / 100.0f) + m_ColorRect[0].left ); m_ColorScrollBar[0].y = m_ColorRect[0].top; m_ColorScrollBar[1].x = (LONG)( (((m_ColorRect[1].right-m_ColorRect[1].left) * fG) / 100.0f) + m_ColorRect[1].left ); m_ColorScrollBar[1].y = m_ColorRect[1].top; m_ColorScrollBar[2].x = (LONG)( (((m_ColorRect[2].right-m_ColorRect[2].left) * fB) / 100.0f) + m_ColorRect[2].left ); m_ColorScrollBar[2].y = m_ColorRect[2].top; #else m_ColorScrollBar[0].x = (LONG)( (((m_ColorRect[0].right-m_ColorRect[0].left) * fR) / 100.0f) + m_ColorRect[0].left ); m_ColorScrollBar[0].y = m_ColorRect[0].top - 20; m_ColorScrollBar[1].x = (LONG)( (((m_ColorRect[1].right-m_ColorRect[1].left) * fG) / 100.0f) + m_ColorRect[1].left ); m_ColorScrollBar[1].y = m_ColorRect[1].top - 20; m_ColorScrollBar[2].x = (LONG)( (((m_ColorRect[2].right-m_ColorRect[2].left) * fB) / 100.0f) + m_ColorRect[2].left ); m_ColorScrollBar[2].y = m_ColorRect[2].top - 20; #endif //__CSC_VER8_4 } void CWndBeautyShop::OnMouseWndSurface( CPoint point ) { if( g_pPlayer == NULL ) return; #if __VER >= 8 //__CSC_VER8_4 CRect rect = CRect( 44, 198, 186, 398 ); #else CRect rect = CRect( 22, 198, 186, 298 ); #endif //__CSC_VER8_4 if( !rect.PtInRect( point ) ) m_bLButtonClick = FALSE; #if __VER >= 8 //__CSC_VER8_4 if( m_ChoiceBar != -1 && m_bLButtonClick ) { CRect DrawRect = m_ColorRect[m_ChoiceBar]; point.x = (point.x > DrawRect.right) ? DrawRect.right : point.x; LONG Width = DrawRect.right - DrawRect.left; LONG Pos = point.x - DrawRect.left; FLOAT p = ((FLOAT)((FLOAT)Pos / (FLOAT)Width)); #ifdef __Y_HAIR_BUG_FIX D3DXVECTOR2 vec1= D3DXVECTOR2( 0.0f, 1.0f ); D3DXVECTOR2 vec2= D3DXVECTOR2( 1.0f, 1.0f ); #else //__Y_HAIR_BUG_FIX D3DXVECTOR2 vec1= D3DXVECTOR2( 0.3f, 0.998f ); D3DXVECTOR2 vec2= D3DXVECTOR2( 0.998f, 0.998f ); #endif //__Y_HAIR_BUG_FIX D3DXVECTOR2 vec3; D3DXVec2Lerp( &vec3, &vec1, &vec2, p ); m_fColor[m_ChoiceBar] = vec3.x; m_ColorScrollBar[m_ChoiceBar].x = point.x; #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = TRUE; #endif //__Y_BEAUTY_SHOP_CHARGE SetRGBToEdit(m_fColor[m_ChoiceBar], m_ChoiceBar); } #else for( int i=0; i<3; i++ ) { CRect DrawRect = m_ColorRect[i]; DrawRect.top -= 22; DrawRect.bottom -= 22; if( DrawRect.PtInRect( point ) && m_bLButtonClick ) { point.x = (point.x > DrawRect.right) ? DrawRect.right : point.x; LONG Width = DrawRect.right - DrawRect.left; LONG Pos = point.x - DrawRect.left; FLOAT p = ((FLOAT)((FLOAT)Pos / (FLOAT)Width)); #ifdef __Y_HAIR_BUG_FIX D3DXVECTOR2 vec1= D3DXVECTOR2( 0.0f, 1.0f ); D3DXVECTOR2 vec2= D3DXVECTOR2( 1.0f, 1.0f ); #else //__Y_HAIR_BUG_FIX D3DXVECTOR2 vec1= D3DXVECTOR2( 0.3f, 1.0f ); D3DXVECTOR2 vec2= D3DXVECTOR2( 1.0f, 1.0f ); #endif //__Y_HAIR_BUG_FIX D3DXVECTOR2 vec3; D3DXVec2Lerp( &vec3, &vec1, &vec2, p ); m_fColor[i] = vec3.x; m_ColorScrollBar[i].x = point.x; #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = TRUE; #endif //__Y_BEAUTY_SHOP_CHARGE } } #endif //__CSC_VER8_4 } BOOL CWndBeautyShop::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndBeautyShop::OnSize( UINT nType, int cx, int cy ) { CWndNeuz::OnSize( nType, cx, cy ); } void CWndBeautyShop::OnLButtonUp( UINT nFlags, CPoint point ) { #if __VER >= 8 //__CSC_VER8_4 m_ChoiceBar = -1; #endif //__CSC_VER8_4 m_bLButtonClick = FALSE; } void CWndBeautyShop::OnLButtonDown( UINT nFlags, CPoint point ) { #if __VER >= 8 //__CSC_VER8_4 int i; int custom[4] = {WIDC_CUSTOM1, WIDC_CUSTOM2, WIDC_CUSTOM3, WIDC_CUSTOM4}; LPWNDCTRL lpWndCtrl; for( i=0; i<3; i++ ) { CRect DrawRect = m_ColorRect[i]; if(DrawRect.PtInRect( point )) m_ChoiceBar = i; } for( i=0; i<4; i++ ) { lpWndCtrl = GetWndCtrl( custom[i] ); CRect DrawRect = lpWndCtrl->rect; if(DrawRect.PtInRect( point )) { //Hair 선택.. m_dwSelectHairMesh = m_nHairNum[i]; CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwSelectHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); //요금 계산.. #ifdef __NEWYEARDAY_EVENT_COUPON if( g_pPlayer->m_dwHairMesh != m_dwSelectHairMesh-1 && !m_bUseCoupon) #else //__NEWYEARDAY_EVENT_COUPON if( g_pPlayer->m_dwHairMesh != m_dwSelectHairMesh-1 ) #endif //__NEWYEARDAY_EVENT_COUPON { m_nHairCost = HAIR_COST; #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = TRUE; #endif //__Y_BEAUTY_SHOP_CHARGE } else m_nHairCost = 0; } } #endif //__CSC_VER8_4 m_bLButtonClick = TRUE; } BOOL CWndBeautyShop::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( g_pPlayer == NULL ) return FALSE; if( message == WNM_CLICKED ) { switch(nID) { case WIDC_BUTTON1: { //m_pModel->DeleteDeviceObjects(); m_dwHairMesh = g_pPlayer->m_dwHairMesh+1; #if __VER >= 8 //__CSC_VER8_4 CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); #else CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pModel, &g_pPlayer->m_Inventory ); #endif //__CSC_VER8_4 m_fColor[0] = g_pPlayer->m_fHairColorR; m_fColor[1] = g_pPlayer->m_fHairColorG; m_fColor[2] = g_pPlayer->m_fHairColorB; m_nHairCost = 0; ReSetBar( m_fColor[0], m_fColor[1], m_fColor[2] ); #if __VER >= 8 //__CSC_VER8_4 m_nHairColorCost = 0; m_dwSelectHairMesh = m_dwHairMesh; SetRGBToEdit(m_fColor[0], 0); SetRGBToEdit(m_fColor[1], 1); SetRGBToEdit(m_fColor[2], 2); #endif //__CSC_VER8_4 #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = FALSE; #endif //__Y_BEAUTY_SHOP_CHARGE } break; case WIDC_HAIRSTYLE_LEFT: // hair { m_dwHairMesh--; ( m_dwHairMesh < 1 ) ? m_dwHairMesh = MAX_HAIR: m_dwHairMesh; #if __VER < 8 //__CSC_VER8_4 CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pModel, &g_pPlayer->m_Inventory ); if( g_pPlayer->m_dwHairMesh != m_dwHairMesh-1 ) { switch( m_dwHairMesh ) { case 1: m_nHairCost = 2500; break; case 2: m_nHairCost = 2500; break; case 3: m_nHairCost = 2500; break; case 4: m_nHairCost = 2500; break; case 5: m_nHairCost = 2500; break; default: m_nHairCost = 4000; break; } #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = TRUE; #endif //__Y_BEAUTY_SHOP_CHARGE } else m_nHairCost = 0; #endif //__CSC_VER8_4 } break; case WIDC_HAIRSTYLE_RIGHT: // hair { m_dwHairMesh++; ( m_dwHairMesh > MAX_HAIR ) ? m_dwHairMesh = 1: m_dwHairMesh; #if __VER < 8 //__CSC_VER8_4 CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, m_dwHairMesh-1, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pModel, &g_pPlayer->m_Inventory ); if( g_pPlayer->m_dwHairMesh != m_dwHairMesh-1 ) { switch( m_dwHairMesh ) { case 1: m_nHairCost = 2500; break; case 2: m_nHairCost = 2500; break; case 3: m_nHairCost = 2500; break; case 4: m_nHairCost = 2500; break; case 5: m_nHairCost = 2500; break; default: m_nHairCost = 4000; break; } #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) m_bChange = TRUE; #endif //__Y_BEAUTY_SHOP_CHARGE } else m_nHairCost = 0; #endif //__CSC_VER8_4 } break; case WIDC_OK: { #ifdef __NEWYEARDAY_EVENT_COUPON BOOL noChange = FALSE; BYTE nColorR = (BYTE)( (m_fColor[0] * 255) ); BYTE nColorG = (BYTE)( (m_fColor[1] * 255) ); BYTE nColorB = (BYTE)( (m_fColor[2] * 255) ); BYTE nOrignalR = (BYTE)( g_pPlayer->m_fHairColorR * 255 ); BYTE nOrignalG = (BYTE)( g_pPlayer->m_fHairColorG * 255 ); BYTE nOrignalB = (BYTE)( g_pPlayer->m_fHairColorB * 255 ); if((g_pPlayer->m_dwHairMesh == m_dwSelectHairMesh-1 ) && (nColorR == nOrignalR && nColorG == nOrignalG && nColorB == nOrignalB)) noChange = TRUE; #endif //__NEWYEARDAY_EVENT_COUPON #ifdef __Y_BEAUTY_SHOP_CHARGE if( ::GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_HK ) { if( m_bChange && g_pPlayer ) { #if __VER >= 8 //__CSC_VER8_4 if(m_pWndBeautyShopConfirm == NULL) { m_pWndBeautyShopConfirm = new CWndBeautyShopConfirm; m_pWndBeautyShopConfirm->Initialize(this); } #else g_DPlay.SendSetHair( m_dwHairMesh-1, m_fColor[0], m_fColor[1], m_fColor[2] ); //, nCost ); #endif //__CSC_VER8_4 } } else #endif //__Y_BEAUTY_SHOP_CHARGE { if( g_pPlayer ) { #if __VER >= 8 //__CSC_VER8_4 int nCost = m_nHairCost + m_nHairColorCost; #else int nCost = m_nHairCost + m_nHairColorCostR + m_nHairColorCostG + m_nHairColorCostB; #endif //__CSC_VER8_4 if( nCost < 0 ) nCost = 0; #if __VER >= 8 //__CSC_VER8_4 #ifdef __NEWYEARDAY_EVENT_COUPON if(m_bUseCoupon && !noChange) { if(m_pWndUseCouponConfirm == NULL) { m_pWndUseCouponConfirm = new CWndUseCouponConfirm; m_pWndUseCouponConfirm->SetInfo(APP_BEAUTY_SHOP_EX, 1); m_pWndUseCouponConfirm->Initialize(this); } } #endif //__NEWYEARDAY_EVENT_COUPON if(nCost > 0) { if(m_pWndBeautyShopConfirm == NULL) { m_pWndBeautyShopConfirm = new CWndBeautyShopConfirm; m_pWndBeautyShopConfirm->Initialize(this); } } #else g_DPlay.SendSetHair( m_dwHairMesh-1, m_fColor[0], m_fColor[1], m_fColor[2] ); //, nCost ); #endif //__CSC_VER8_4 } } #if __VER >= 8 //__CSC_VER8_4 int nCost = m_nHairCost + m_nHairColorCost; #ifdef __NEWYEARDAY_EVENT_COUPON if(nCost <= 0 && (!m_bUseCoupon || noChange)) #else //__NEWYEARDAY_EVENT_COUPON if(nCost <= 0) #endif //__NEWYEARDAY_EVENT_COUPON Destroy(); #else Destroy(); #endif //__CSC_VER8_4 } break; case WIDC_CANCEL: { Destroy(); } break; } } #if __VER >= 8 //__CSC_VER8_4 if(nID == WIDC_EDIT1 || nID == WIDC_EDIT2 || nID == WIDC_EDIT3) SetRGBToBar(nID); #endif //__CSC_VER8_4 return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndBeautyShop::OnDestroyChildWnd( CWndBase* pWndChild ) { #if __VER < 8 //__CSC_VER8_4 if( pWndChild == m_pWndConfirmSell ) SAFE_DELETE( m_pWndConfirmSell ); SAFE_DELETE( m_pModel ); #endif //__CSC_VER8_4 } void CWndBeautyShop::OnDestroy( void ) { SAFE_DELETE( m_pModel ); SAFE_DELETE( m_pWndConfirmSell ); #if __VER >= 8 //__CSC_VER8_4 SAFE_DELETE(m_pApplyModel); SAFE_DELETE(m_pHairModel); SAFE_DELETE(m_pWndBeautyShopConfirm); #endif //__CSC_VER8_4 } #if __VER >= 8 //__CSC_VER8_4 #ifdef __NEWYEARDAY_EVENT_COUPON CWndUseCouponConfirm::CWndUseCouponConfirm() { m_bUseCoupon = FALSE; m_checkClose = TRUE; m_TargetWndId = -1; } CWndUseCouponConfirm::~CWndUseCouponConfirm() { } void CWndUseCouponConfirm::OnDestroy() { if( m_bUseCoupon == FALSE ) return; if(!m_checkClose && m_MainFlag == 0) { if(m_TargetWndId != -1) { if(m_TargetWndId == APP_BEAUTY_SHOP_EX) { g_WndMng.CreateApplet( APP_INVENTORY ); SAFE_DELETE( g_WndMng.m_pWndBeautyShop ); g_WndMng.m_pWndBeautyShop = new CWndBeautyShop; g_WndMng.m_pWndBeautyShop->Initialize( NULL, APP_BEAUTY_SHOP_EX ); g_WndMng.m_pWndBeautyShop->UseHairCoupon(m_bUseCoupon); } else if(m_TargetWndId == APP_BEAUTY_SHOP_SKIN) { g_WndMng.CreateApplet( APP_INVENTORY ); SAFE_DELETE( g_WndMng.m_pWndFaceShop ); g_WndMng.m_pWndFaceShop = new CWndFaceShop; g_WndMng.m_pWndFaceShop->Initialize( NULL, APP_BEAUTY_SHOP_EX ); g_WndMng.m_pWndFaceShop->UseFaceCoupon(m_bUseCoupon); } } } if(this->GetParentWnd() == g_WndMng.GetWndBase( APP_WORLD )) g_WndMng.m_pWndUseCouponConfirm = NULL; else if(this->GetParentWnd() == g_WndMng.GetWndBase( APP_BEAUTY_SHOP_EX )) g_WndMng.m_pWndBeautyShop->m_pWndUseCouponConfirm = NULL; else if(this->GetParentWnd() == g_WndMng.GetWndBase( APP_BEAUTY_SHOP_SKIN )) g_WndMng.m_pWndFaceShop->m_pWndUseCouponConfirm = NULL; } void CWndUseCouponConfirm::OnDraw( C2DRender* p2DRender ) { } void CWndUseCouponConfirm::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 /* CWndStatic* pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC1 ); pStatic->SetVisible(FALSE); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC2 ); pStatic->SetVisible(FALSE); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC3 ); pStatic->SetVisible(FALSE); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC4 ); pStatic->SetVisible(FALSE); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC5 ); pStatic->SetVisible(FALSE); pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC6 ); pStatic->SetVisible(FALSE); */ CWndText* pText = (CWndText*)GetDlgItem( WIDC_TEXT1 ); SetTitle(prj.GetText(TID_GAME_USE_CHANGE_COUPON)); if(m_TargetWndId != -1) { if(m_MainFlag == 0) pText->AddString(prj.GetText( TID_GAME_ASKUSE_COUPON1 )); else if(m_MainFlag == 1) { pText->AddString(prj.GetText( TID_GAME_ASKUSE_COUPON2 )); pText->AddString("\n"); pText->AddString(prj.GetText( TID_GAME_WARNNING_USE_COUPON ), 0xffff0000); } } MoveParentCenter(); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndUseCouponConfirm::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_BEAUTY_SHOP_EX_CONFIRM, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndUseCouponConfirm::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndUseCouponConfirm::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndUseCouponConfirm::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndUseCouponConfirm::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndUseCouponConfirm::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_YES ) { if(m_MainFlag == 0) m_bUseCoupon = TRUE; else if(m_MainFlag == 1) { if(m_TargetWndId == APP_BEAUTY_SHOP_EX) { CWndBeautyShop* pWndBeautyShop = (CWndBeautyShop*)this->GetParentWnd(); g_DPlay.SendSetHair( (BYTE)( pWndBeautyShop->m_dwSelectHairMesh-1 ), pWndBeautyShop->m_fColor[0], pWndBeautyShop->m_fColor[1], pWndBeautyShop->m_fColor[2] ); pWndBeautyShop->Destroy(); } else if(m_TargetWndId == APP_BEAUTY_SHOP_SKIN) { CWndFaceShop* pWndFaceShop = (CWndFaceShop*)this->GetParentWnd(); g_DPlay.SendChangeFace( g_pPlayer->m_idPlayer, pWndFaceShop->m_nSelectedFace-1, pWndFaceShop->m_nCost ); pWndFaceShop->Destroy(); } } m_checkClose = FALSE; } else if( nID == WIDC_NO ) m_checkClose = FALSE; else if( nID == WTBID_CLOSE ) m_checkClose = TRUE; Destroy(); return CWndNeuz::OnChildNotify( message, nID, pLResult ); } void CWndUseCouponConfirm::SetInfo(DWORD targetWndId, int flag) { m_TargetWndId = targetWndId; m_MainFlag = flag; } #endif //__NEWYEARDAY_EVENT_COUPON /************************* CWndBeautyShopConfirm Class *************************/ CWndBeautyShopConfirm::CWndBeautyShopConfirm() { m_ParentId = 0; } CWndBeautyShopConfirm::~CWndBeautyShopConfirm() { } void CWndBeautyShopConfirm::OnDestroy() { CWndBase* pWndBase = this->GetParentWnd(); if(m_ParentId == APP_BEAUTY_SHOP_EX) { CWndBeautyShop* pWndBeautyShop = (CWndBeautyShop*)pWndBase; pWndBeautyShop->m_pWndBeautyShopConfirm = NULL; } else if(m_ParentId == APP_BEAUTY_SHOP_SKIN) { CWndFaceShop* pWndFaceShop = (CWndFaceShop*)pWndBase; pWndFaceShop->m_pWndBeautyShopConfirm = NULL; } } void CWndBeautyShopConfirm::OnDraw( C2DRender* p2DRender ) { } void CWndBeautyShopConfirm::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 /* char szNumberbuf[16] = {0, }; int TotalCost; CWndStatic* pCostStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC6 ); pCostStatic->AddWndStyle(WSS_MONEY); CWndStatic* pStatic1 = (CWndStatic*)GetDlgItem( WIDC_STATIC2 ); CWndStatic* pStatic2 = (CWndStatic*)GetDlgItem( WIDC_STATIC5 ); CWndBase* pWndBase = this->GetParentWnd(); m_ParentId = pWndBase->GetWndApplet()->dwWndId; if(m_ParentId == APP_BEAUTY_SHOP_EX) { CWndBeautyShop* pWndBeautyShop = (CWndBeautyShop*)pWndBase; TotalCost = pWndBeautyShop->m_nHairCost + pWndBeautyShop->m_nHairColorCost; pStatic1->SetTitle(prj.GetText(TID_GAME_CHANGE_HAIR)); pStatic2->SetTitle(prj.GetText(TID_GAME_CHANGE_HAIR_QUESTION)); } else if(m_ParentId == APP_BEAUTY_SHOP_SKIN) { CWndFaceShop* pWndFaceShop = (CWndFaceShop*)pWndBase; TotalCost = pWndFaceShop->m_nCost; pStatic1->SetTitle(prj.GetText(TID_GAME_CHANGE_FACE)); pStatic2->SetTitle(prj.GetText(TID_GAME_CHANGE_FACE_QUESTION)); } _itoa( TotalCost, szNumberbuf, 10 ); pCostStatic->SetTitle(szNumberbuf); */ int TotalCost; CString strText, strNum; CWndBase* pWndBase = this->GetParentWnd(); m_ParentId = pWndBase->GetWndApplet()->dwWndId; if(m_ParentId == APP_BEAUTY_SHOP_EX) { CWndBeautyShop* pWndBeautyShop = (CWndBeautyShop*)pWndBase; TotalCost = pWndBeautyShop->m_nHairCost + pWndBeautyShop->m_nHairColorCost; strNum.Format("%d", TotalCost); strText.Format("%s %s %s %s %s %s", prj.GetText(TID_GAME_SHOP_CHOICE), prj.GetText(TID_GAME_CHANGE_HAIR), prj.GetText(TID_GAME_SHOP_COST), GetNumberFormatEx(strNum), prj.GetText(TID_GAME_SHOP_PENYA), prj.GetText(TID_GAME_CHANGE_HAIR_QUESTION) ); } else if(m_ParentId == APP_BEAUTY_SHOP_SKIN) { CWndFaceShop* pWndFaceShop = (CWndFaceShop*)pWndBase; TotalCost = pWndFaceShop->m_nCost; strNum.Format("%d", TotalCost); strText.Format("%s %s %s %s %s %s", prj.GetText(TID_GAME_SHOP_CHOICE), prj.GetText(TID_GAME_CHANGE_FACE), prj.GetText(TID_GAME_SHOP_COST), GetNumberFormatEx(strNum), prj.GetText(TID_GAME_SHOP_PENYA), prj.GetText(TID_GAME_CHANGE_FACE_QUESTION) ); } CWndText* pText = (CWndText*)GetDlgItem( WIDC_TEXT1 ); pText->SetString(strText); MoveParentCenter(); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndBeautyShopConfirm::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_BEAUTY_SHOP_EX_CONFIRM, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndBeautyShopConfirm::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndBeautyShopConfirm::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndBeautyShopConfirm::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndBeautyShopConfirm::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndBeautyShopConfirm::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_YES ) { if(m_ParentId == APP_BEAUTY_SHOP_EX) { CWndBeautyShop* pWndBeautyShop = (CWndBeautyShop*)this->GetParentWnd(); if( pWndBeautyShop ) { g_DPlay.SendSetHair( (BYTE)( pWndBeautyShop->m_dwSelectHairMesh-1 ), pWndBeautyShop->m_fColor[0], pWndBeautyShop->m_fColor[1], pWndBeautyShop->m_fColor[2] ); } pWndBeautyShop->Destroy(); } else if(m_ParentId == APP_BEAUTY_SHOP_SKIN) { CWndFaceShop* pWndFaceShop = (CWndFaceShop*)this->GetParentWnd(); if( pWndFaceShop ) { g_DPlay.SendChangeFace( g_pPlayer->m_idPlayer, pWndFaceShop->m_nSelectedFace-1, pWndFaceShop->m_nCost ); } pWndFaceShop->Destroy(); } Destroy(); } else if( nID == WIDC_NO || nID == WTBID_CLOSE ) Destroy(); return CWndNeuz::OnChildNotify( message, nID, pLResult ); } /************************* CWndFaceShop Class *************************/ CWndFaceShop::CWndFaceShop() { m_pMainModel = NULL; m_pApplyModel = NULL; m_pFriendshipFace = NULL; m_pNewFace = NULL; m_pWndBeautyShopConfirm = NULL; m_nSelectedFace = 1; m_dwFriendshipFace = 1; m_dwNewFace = 6; m_nCost = 0; m_ChoiceBar = -1; #ifdef __NEWYEARDAY_EVENT_COUPON m_bUseCoupon = FALSE; m_pWndUseCouponConfirm = NULL; #endif //__NEWYEARDAY_EVENT_COUPON } CWndFaceShop::~CWndFaceShop() { SAFE_DELETE(m_pMainModel); SAFE_DELETE(m_pApplyModel); SAFE_DELETE(m_pFriendshipFace); SAFE_DELETE(m_pNewFace); SAFE_DELETE(m_pWndBeautyShopConfirm); #ifdef __NEWYEARDAY_EVENT_COUPON SAFE_DELETE(m_pWndUseCouponConfirm); #endif //__NEWYEARDAY_EVENT_COUPON } void CWndFaceShop::OnDestroy() { SAFE_DELETE(m_pMainModel); SAFE_DELETE(m_pApplyModel); SAFE_DELETE(m_pFriendshipFace); SAFE_DELETE(m_pNewFace); SAFE_DELETE(m_pWndBeautyShopConfirm); } void CWndFaceShop::OnDestroyChildWnd( CWndBase* pWndChild ) { } #ifdef __NEWYEARDAY_EVENT_COUPON void CWndFaceShop::UseFaceCoupon(BOOL isUse) { m_bUseCoupon = isUse; if(m_bUseCoupon) { CString title = GetTitle(); CString addText; addText.Format(" %s", prj.GetText( TID_GAME_NOWUSING_COUPON )); title = title + addText; SetTitle(title); } } #endif //__NEWYEARDAY_EVENT_COUPON void CWndFaceShop::OnDraw( C2DRender* p2DRender ) { if( g_pPlayer == NULL || m_pMainModel == NULL || m_pApplyModel == NULL ) return; LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice; pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); pd3dDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_ARGB( 255, 255,255,255) ); CRect rect = GetClientRect(); // 뷰포트 세팅 D3DVIEWPORT9 viewport; // 월드 D3DXMATRIXA16 matWorld; D3DXMATRIXA16 matScale; D3DXMATRIXA16 matRot; D3DXMATRIXA16 matTrans; // 카메라 D3DXMATRIX matView; D3DXVECTOR3 vecLookAt( 0.0f, 0.0f, 3.0f ); D3DXVECTOR3 vecPos( 0.0f, 0.7f, -3.5f ); D3DXMatrixLookAtLH( &matView, &vecPos, &vecLookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f) ); pd3dDevice->SetTransform( D3DTS_VIEW, &matView ); #ifdef __YENV D3DXVECTOR3 vDir( 0.0f, 0.0f, 1.0f ); SetLightVec( vDir ); #endif //__YENV // 왼쪽 원본 모델 랜더링 { LPWNDCTRL lpFace = GetWndCtrl( WIDC_CUSTOM5 ); viewport.X = p2DRender->m_ptOrigin.x + lpFace->rect.left; viewport.Y = p2DRender->m_ptOrigin.y + lpFace->rect.top; viewport.Width = lpFace->rect.Width(); viewport.Height = lpFace->rect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; FLOAT fov = D3DX_PI/4.0f;//796.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matWorld); D3DXMatrixScaling(&matScale, 4.5f, 4.5f, 4.5f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.0f,-5.6f,0.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-5.2f,0.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); // 랜더링 pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); ::SetLight( FALSE ); ::SetFog( FALSE ); SetDiffuse( 1.0f, 1.0f, 1.0f ); SetAmbient( 1.0f, 1.0f, 1.0f ); D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV ::SetTransformView( matView ); ::SetTransformProj( matProj ); if( g_pPlayer ) g_pPlayer->OverCoatItemRenderCheck(m_pMainModel); m_pMainModel->Render( p2DRender->m_pd3dDevice, &matWorld ); } // 오른쪽 얼굴변경 모델 랜더링 { LPWNDCTRL lpFace = GetWndCtrl( WIDC_CUSTOM6 ); viewport.X = p2DRender->m_ptOrigin.x + lpFace->rect.left; viewport.Y = p2DRender->m_ptOrigin.y + lpFace->rect.top; viewport.Width = lpFace->rect.Width(); viewport.Height = lpFace->rect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; FLOAT fov = D3DX_PI/4.0f;//796.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matRot); D3DXMatrixIdentity(&matWorld); D3DXMatrixRotationY(&matRot,g_tmCurrent/1000.0f); D3DXMatrixScaling(&matScale, 4.5f, 4.5f, 4.5f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.0f,-5.6f,0.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-5.2f,0.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matRot ); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); ::SetLight( FALSE ); ::SetFog( FALSE ); D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV ::SetTransformView( matView ); ::SetTransformProj( matProj ); if( g_pPlayer ) g_pPlayer->OverCoatItemRenderCheck(m_pApplyModel); m_pApplyModel->Render( p2DRender->m_pd3dDevice, &matWorld ); } viewport.X = p2DRender->m_ptOrigin.x;// + 5; viewport.Y = p2DRender->m_ptOrigin.y;// + 5; viewport.Width = p2DRender->m_clipRect.Width(); viewport.Height = p2DRender->m_clipRect.Height(); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; pd3dDevice->SetViewport(&viewport); pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); DrawFaces(0, p2DRender, matView); DrawFaces(1, p2DRender, matView); } void CWndFaceShop::DrawFaces(int ChoiceFlag, C2DRender* p2DRender, D3DXMATRIX matView) { // 뷰포트 세팅 D3DVIEWPORT9 viewport; // 월드 D3DXMATRIXA16 matWorld; D3DXMATRIXA16 matScale; D3DXMATRIXA16 matTrans; //Face Kind DWORD FaceNum; LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice; CModelObject* m_pFaceModel; if(ChoiceFlag == 0) { m_pFaceModel = m_pFriendshipFace; FaceNum = m_dwFriendshipFace; } else if(ChoiceFlag == 1) { m_pFaceModel = m_pNewFace; FaceNum = m_dwNewFace; } int custom_friend[4] = {WIDC_CUSTOM1, WIDC_CUSTOM2, WIDC_CUSTOM3, WIDC_CUSTOM4}; int custom_new[4] = {WIDC_CUSTOM7, WIDC_CUSTOM8, WIDC_CUSTOM9, WIDC_CUSTOM10}; if(m_pFaceModel == NULL) return; LPWNDCTRL lpFace = GetWndCtrl( custom_friend[0] ); viewport.Width = lpFace->rect.Width() - 2; viewport.Height = lpFace->rect.Height() - 2; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height; FLOAT fov = D3DX_PI/4.0f; FLOAT h = cos(fov/2) / sin(fov/2); FLOAT w = h * fAspect; D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane ); for(int i=0; i<4; i++) { if(ChoiceFlag == 0) { ( FaceNum > MAX_DEFAULT_HEAD ) ? FaceNum = 1: FaceNum; lpFace = GetWndCtrl( custom_friend[i] ); m_nFriendshipFaceNum[i] = FaceNum; } else if(ChoiceFlag == 1) { ( FaceNum > MAX_HEAD ) ? FaceNum = 6: FaceNum; lpFace = GetWndCtrl( custom_new[i] ); m_nNewFaceNum[i] = FaceNum; } //Model Draw CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, FaceNum-1,g_pPlayer->m_aEquipInfo, m_pFaceModel, NULL ); viewport.X = p2DRender->m_ptOrigin.x + lpFace->rect.left; viewport.Y = p2DRender->m_ptOrigin.y + lpFace->rect.top; pd3dDevice->SetViewport(&viewport); pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ; pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMatrixIdentity(&matScale); D3DXMatrixIdentity(&matTrans); D3DXMatrixIdentity(&matWorld); D3DXMatrixScaling(&matScale, 7.5f, 7.5f, 7.5f); if( g_pPlayer->GetSex() == SEX_MALE ) D3DXMatrixTranslation(&matTrans,0.05f,-10.0f,-1.0f); else D3DXMatrixTranslation(&matTrans,0.0f,-9.5f,-1.0f); D3DXMatrixMultiply(&matWorld,&matWorld,&matScale); D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); ::SetLight( FALSE ); ::SetFog( FALSE ); SetDiffuse( 1.0f, 1.0f, 1.0f ); SetAmbient( 1.0f, 1.0f, 1.0f ); D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f ); #ifdef __YENV g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst ); #else //__YENV pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 ); #endif //__YENV ::SetTransformView( matView ); ::SetTransformProj( matProj ); m_pFaceModel->Render( p2DRender->m_pd3dDevice, &matWorld ); //Select Draw if(ChoiceFlag == 0) { if(m_nSelectedFace == m_nFriendshipFaceNum[i]) { CRect rect; rect = lpFace->rect; p2DRender->RenderFillRect( rect, 0x60ffff00 ); } } else if(ChoiceFlag == 1) { if(m_nSelectedFace == m_nNewFaceNum[i]) { CRect rect; rect = lpFace->rect; p2DRender->RenderFillRect( rect, 0x60ffff00 ); } } FaceNum++; } } void CWndFaceShop::UpdateModels() { if(m_pMainModel != NULL) CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pMainModel, &g_pPlayer->m_Inventory ); if(m_pApplyModel != NULL) CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, m_nSelectedFace-1, g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); } void CWndFaceShop::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); CWndInventory* pWndInventory = (CWndInventory*)GetWndBase( APP_INVENTORY ); CRect rectInventory = pWndInventory->GetWindowRect( TRUE ); CPoint ptInventory = rectInventory.TopLeft(); CPoint ptMove; CRect rect = GetWindowRect( TRUE ); if( ptInventory.x > rect.Width() / 2 ) ptMove = ptInventory - CPoint( rect.Width(), 0 ); else ptMove = ptInventory + CPoint( rectInventory.Width(), 0 ); Move( ptMove ); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndFaceShop::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { if( g_pPlayer == NULL ) return FALSE; if(g_pPlayer->m_dwHeadMesh >= 0 && g_pPlayer->m_dwHeadMesh < 6) m_dwFriendshipFace = g_pPlayer->m_dwHeadMesh + 1; else if(g_pPlayer->m_dwHeadMesh >= 6 && g_pPlayer->m_dwHeadMesh < 15) m_dwNewFace = g_pPlayer->m_dwHeadMesh + 1; m_nSelectedFace = g_pPlayer->m_dwHeadMesh + 1; int nMover = (g_pPlayer->GetSex() == SEX_MALE ? MI_MALE : MI_FEMALE); SAFE_DELETE( m_pMainModel ); m_pMainModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pMainModel, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pMainModel, &g_pPlayer->m_Inventory ); m_pMainModel->InitDeviceObjects( g_Neuz.GetDevice() ); SAFE_DELETE( m_pApplyModel ); m_pApplyModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pApplyModel, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); m_pApplyModel->InitDeviceObjects( g_Neuz.GetDevice() ); SAFE_DELETE(m_pFriendshipFace); m_pFriendshipFace = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pFriendshipFace, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pFriendshipFace, &g_pPlayer->m_Inventory ); m_pFriendshipFace->InitDeviceObjects( g_Neuz.GetDevice() ); SAFE_DELETE(m_pNewFace); m_pNewFace = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE ); prj.m_modelMng.LoadMotion( m_pNewFace, OT_MOVER, nMover, MTI_STAND2 ); CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, g_pPlayer->m_dwHeadMesh,g_pPlayer->m_aEquipInfo, m_pNewFace, &g_pPlayer->m_Inventory ); m_pNewFace->InitDeviceObjects( g_Neuz.GetDevice() ); // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_BEAUTY_SHOP_SKIN, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndFaceShop::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndFaceShop::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndFaceShop::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndFaceShop::OnLButtonDown( UINT nFlags, CPoint point ) { int i; int custom[8] = {WIDC_CUSTOM1, WIDC_CUSTOM2, WIDC_CUSTOM3, WIDC_CUSTOM4, WIDC_CUSTOM7, WIDC_CUSTOM8, WIDC_CUSTOM9, WIDC_CUSTOM10}; LPWNDCTRL lpWndCtrl; for( i=0; i<8; i++ ) { lpWndCtrl = GetWndCtrl( custom[i] ); CRect DrawRect = lpWndCtrl->rect; if(DrawRect.PtInRect( point )) { //Face 선택.. if(i>=0 && i<4) m_nSelectedFace = m_nFriendshipFaceNum[i]; else if(i>=4 && i<8) m_nSelectedFace = m_nNewFaceNum[i-4]; CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, m_nSelectedFace-1, g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); //요금 계산.. #ifdef __NEWYEARDAY_EVENT_COUPON if( g_pPlayer->m_dwHeadMesh != m_nSelectedFace-1 && !m_bUseCoupon) #else //__NEWYEARDAY_EVENT_COUPON if( g_pPlayer->m_dwHeadMesh != m_nSelectedFace-1 ) #endif //__NEWYEARDAY_EVENT_COUPON m_nCost = CHANGE_FACE_COST; else m_nCost = 0; } } } BOOL CWndFaceShop::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( g_pPlayer == NULL ) return FALSE; if( message == WNM_CLICKED ) { switch(nID) { case WIDC_BTN_RESET: { if(g_pPlayer->m_dwHeadMesh >= 0 && g_pPlayer->m_dwHeadMesh < 6) { m_dwFriendshipFace = g_pPlayer->m_dwHeadMesh + 1; m_dwNewFace = 6; } else if(g_pPlayer->m_dwHeadMesh >= 6 && g_pPlayer->m_dwHeadMesh < 16) { m_dwNewFace = g_pPlayer->m_dwHeadMesh + 1; m_dwFriendshipFace = 1; } m_nSelectedFace = g_pPlayer->m_dwHeadMesh + 1; CMover::UpdateParts( g_pPlayer->GetSex(), g_pPlayer->m_dwSkinSet, g_pPlayer->m_dwFace, g_pPlayer->m_dwHairMesh, m_nSelectedFace-1,g_pPlayer->m_aEquipInfo, m_pApplyModel, &g_pPlayer->m_Inventory ); m_nCost = 0; } break; case WIDC_FRIENDSHIPFACE_LEFT: { m_dwFriendshipFace--; ( m_dwFriendshipFace < 1 ) ? m_dwFriendshipFace = MAX_DEFAULT_HEAD: m_dwFriendshipFace; } break; case WIDC_FRIENDSHIPFACE_RIGHT: { m_dwFriendshipFace++; ( m_dwFriendshipFace > MAX_DEFAULT_HEAD ) ? m_dwFriendshipFace = 1: m_dwFriendshipFace; } break; case WIDC_NEWFACE_LEFT: { m_dwNewFace--; ( m_dwNewFace < 6 ) ? m_dwNewFace = MAX_HEAD: m_dwNewFace; } break; case WIDC_NEWFACE_RIGHT: { m_dwNewFace++; ( m_dwNewFace > MAX_HEAD ) ? m_dwNewFace = 6: m_dwNewFace; } break; case WIDC_BTN_OK: { #ifdef __NEWYEARDAY_EVENT_COUPON BOOL noChange = FALSE; if(g_pPlayer->m_dwHeadMesh == m_nSelectedFace-1) noChange = TRUE; if(m_nCost <= 0 && (!m_bUseCoupon || noChange)) #else //__NEWYEARDAY_EVENT_COUPON if(m_nCost <= 0) #endif //__NEWYEARDAY_EVENT_COUPON Destroy(); else if( g_pPlayer ) { if( m_nCost < 0 ) m_nCost = 0; #ifdef __NEWYEARDAY_EVENT_COUPON if(m_bUseCoupon && !noChange) { if(m_pWndUseCouponConfirm == NULL) { m_pWndUseCouponConfirm = new CWndUseCouponConfirm; m_pWndUseCouponConfirm->SetInfo(APP_BEAUTY_SHOP_SKIN, 1); m_pWndUseCouponConfirm->Initialize(this); } } #endif //__NEWYEARDAY_EVENT_COUPON if(m_nCost > 0) { if(m_pWndBeautyShopConfirm == NULL) { m_pWndBeautyShopConfirm = new CWndBeautyShopConfirm; m_pWndBeautyShopConfirm->Initialize(this); } } } } break; case WIDC_BTN_CANCEL: { Destroy(); } break; } } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } #endif //__CSC_VER8_4
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 3069 ] ] ]
0ec80b639b9210634aef58f3f1427b555273596b
8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076
/code/RenderDevice/fxRenderDevice.h
94e549268116edcb5a21f642619dac80a0a53f69
[]
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
1,756
h
//--------------------------------------------------------------------------- #ifndef fxRenderDeviceH #define fxRenderDeviceH //--------------------------------------------------------------------------- #include "../insanefx.h" #include "../kernel/fxClass.h" #include "../kernel/fxTimer.h" #include "../kernel/fxVars.h" #include "../Math/fxVertex.h" #include "../Camera/fxCamera.h" #include "../materials/fxTexture.h" #include "../materials/fxMaterial.h" #ifdef _WIN32 #include "fxRenderWindow.h" #endif class INSANEFX_API fxRenderDevice : public fxClass { protected: fxVars * Vars; fxTimer * Timer; fxRenderWindow * wnd; public: fxRenderDevice() { ClassName = "fxRenderDevice"; RegisterObject(this, ClassName); Vars = NULL; Timer = NULL; } virtual ~fxRenderDevice(void) { UnregisterObject("RenderDevice"); } // open and close render window virtual void OpenWindow(void); virtual void CloseWindow(void); // resize window or viewport virtual void Resize(int x, int y, int width, int height, int windowwidth, int windowheight){}; // start drawing a frame virtual void BeginFrame(void){}; // end drawing a frame virtual void EndFrame(void){}; // draws triangle lists virtual void DrawBuffer(fxVertex * VertexList, int VertexCount, int * IndexList, int IndexCount){}; // uploads the texture data to the video hardware virtual void RegisterTexture(fxTexture * t){}; // deletes an uploaded texture virtual void UnregisterTexture(fxTexture * t){}; // set current camera virtual void SetCamera (fxCamera* cam){}; // set current material virtual void SetMaterial (fxMaterial * m){}; }; #endif
[ "josef" ]
[ [ [ 1, 73 ] ] ]
ded831321f2d6f8ede8548f11d27d306e9821831
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/misc/ncsrv_main.cc
5b012076762ca9899dd33543ff1b0f347ec3b600
[]
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
20,984
cc
//------------------------------------------------------------------- // ncsrv_main.cc // (C) 1999 A.Weissflog //------------------------------------------------------------------- #include "precompiled/pchnnebula.h" #include "kernel/nkernelserver.h" #include "kernel/nenv.h" #include "gfx2/ngfxserver2.h" #include "input/ninputevent.h" #include "input/ninputserver.h" #include "misc/nconserver.h" #include "kernel/nscriptserver.h" #include "kernel/nloghandler.h" nNebulaScriptClass(nConServer, "nroot"); // all keys which may not be routed to the application if the console is open static int keyKillSet[] = { N_KEY_BACK, N_KEY_RETURN, N_KEY_SHIFT, N_KEY_CONTROL, N_KEY_SPACE, N_KEY_END, N_KEY_HOME, N_KEY_LEFT, N_KEY_UP, N_KEY_RIGHT, N_KEY_DOWN, N_KEY_INSERT, N_KEY_DELETE, N_KEY_1, N_KEY_2, N_KEY_3, N_KEY_4, N_KEY_5, N_KEY_6, N_KEY_7, N_KEY_8, N_KEY_9, N_KEY_0, N_KEY_A, N_KEY_B, N_KEY_C, N_KEY_D, N_KEY_E, N_KEY_F, N_KEY_G, N_KEY_H, N_KEY_I, N_KEY_J, N_KEY_K, N_KEY_L, N_KEY_M, N_KEY_N, N_KEY_O, N_KEY_P, N_KEY_Q, N_KEY_R, N_KEY_S, N_KEY_T, N_KEY_U, N_KEY_V, N_KEY_W, N_KEY_X, N_KEY_Y, N_KEY_Z, N_KEY_NUMPAD0, N_KEY_NUMPAD1, N_KEY_NUMPAD2, N_KEY_NUMPAD3, N_KEY_NUMPAD4, N_KEY_NUMPAD5, N_KEY_NUMPAD6, N_KEY_NUMPAD7, N_KEY_NUMPAD8, N_KEY_NUMPAD9, N_KEY_MULTIPLY, N_KEY_ADD, N_KEY_SEPARATOR, N_KEY_SUBTRACT, N_KEY_DECIMAL, N_KEY_DIVIDE, N_KEY_NONE }; nConServer* nConServer::Singleton = 0; //------------------------------------------------------------------------------ /** */ nConServer::nConServer() : refInputServer("/sys/servers/input"), refScriptServer("/sys/servers/script"), envClass(0), consoleOpen(false), watchersOpen(false), historyIndex(0), cursorPos(0), overstrike(false), ctrlDown(false), scrollOffset(0) { n_assert(0 == Singleton); Singleton = this; memset(this->inputBuffer, 0, sizeof(this->inputBuffer)); this->envClass = kernelServer->FindClass("nenv"); n_assert(this->envClass); } //------------------------------------------------------------------------------ /** */ nConServer::~nConServer() { n_assert(Singleton); Singleton = 0; } //------------------------------------------------------------------------------ /** */ void nConServer::Open() { this->consoleOpen = true; } //------------------------------------------------------------------------------ /** */ void nConServer::Close() { this->consoleOpen = false; } //------------------------------------------------------------------------------ /** */ void nConServer::Toggle() { if (this->consoleOpen) { this->Close(); } else { this->Open(); } } //------------------------------------------------------------------------------ /** */ void nConServer::Watch(const char* pattern) { this->watchersOpen = true; this->watchPattern = pattern; } //------------------------------------------------------------------------------ /** */ void nConServer::Unwatch() { this->watchersOpen = false; } //------------------------------------------------------------------------------ /** Render the console to the gfx server. */ void nConServer::RenderConsole(int displayHeight, int fontHeight) { n_assert(this->consoleOpen); n_assert(fontHeight > 0); n_assert(displayHeight > 0); const vector4 textColor(1.0f, 0.69f, 0.43f, 1.0f); // get pointer to the kernel server's line buffer entries nLineBuffer* lineBuffer = kernelServer->GetLogHandler()->GetLineBuffer(); if (!lineBuffer) { // the current log handler supports no line buffer, so // there is nothing to render return; } const int maxLines = 512; const char* lineArray[maxLines]; const int safeBottom = 4; // 4 lines safety zone int numLines = lineBuffer->GetLines(lineArray, maxLines); // compute num lines fitting on screen, and the first and last visible line int maxLinesOnScreen = (displayHeight / fontHeight) - safeBottom; int firstLine = maxLinesOnScreen + this->scrollOffset; if (firstLine >= numLines) { firstLine = numLines - 1; this->scrollOffset = firstLine - maxLinesOnScreen; } int lastLine = firstLine - maxLinesOnScreen; if (lastLine < 0) { this->scrollOffset = 0; lastLine = 0; } // render buffer lines nGfxServer2* gfxServer = nGfxServer2::Instance(); char line[1024]; int i; float xPos = -1.0f; float yPos = -1.0f; float dy = 2.0f / (maxLinesOnScreen + safeBottom); int curLine; for (curLine = firstLine; curLine >= lastLine; curLine--) { n_strncpy2(line, lineArray[curLine], sizeof(line) - 3); n_strcat(line, "\n", sizeof(line)); gfxServer->Text(line, textColor, xPos, yPos); yPos += dy; } // start final line with prompt from script server nString cmdLine = this->refScriptServer->Prompt(); strcpy(line, cmdLine.Get()); char* to = line + strlen(line); const char* from = this->inputBuffer; // copy until cursor pos for (i = 0; i < this->cursorPos; i++) { *to++ = *from++; } // insert cursor *to++ = '|'; // copy the rest of the line while ( 0 != (*to++ = *from++)); // and render it gfxServer->Text(line, textColor, xPos, yPos); } //------------------------------------------------------------------------------ /** Render the watcher variables matching the watcher pattern. */ void nConServer::RenderWatchers(int displayHeight, int fontHeight) { n_assert(this->watchersOpen); n_assert(this->envClass); n_assert(fontHeight > 0); n_assert(displayHeight > 0); const vector4 textColor(0.43f, 0.69f, 1.0f, 1.0f); nRoot* watcherVars = kernelServer->Lookup("/sys/var"); if (watcherVars) { // compute num lines fitting on screen, and the first and last visible line int maxLinesOnScreen = displayHeight / fontHeight; // for each watcher variable nGfxServer2* gfxServer = nGfxServer2::Instance(); char line[N_MAXPATH]; float xPos = -1.0f; float yPos = -1.0f; float dy = 2.0f / float(maxLinesOnScreen); nEnv* curVar; for (curVar = (nEnv*) watcherVars->GetHead(); curVar; curVar = (nEnv*) curVar->GetSucc()) { if (curVar->IsA(this->envClass)) { const char* varName = curVar->GetName(); if (n_strmatch(varName, this->watchPattern.Get())) { switch (curVar->GetType()) { case nArg::Int: sprintf(line,"%s: %d\n", varName, curVar->GetI()); break; case nArg::Float: sprintf(line,"%s: %f\n", varName, curVar->GetF()); break; case nArg::String: sprintf(line,"%s: %s\n", varName, curVar->GetS()); break; case nArg::Bool: sprintf(line,"%s: %s\n", varName, curVar->GetB() ? "true" : "false"); break; case nArg::Float4: { const nFloat4& f4 = curVar->GetF4(); sprintf(line, "%s: %f %f %f %f\n", varName, f4.x, f4.y, f4.z, f4.w); } break; default: sprintf(line,"%s: <unknown data type>\n", varName); break; } gfxServer->Text(line, textColor, xPos, yPos); yPos += dy; } } } } } //------------------------------------------------------------------------------ /** Main render method of the console server. Render either nothing, the command console, or any active watcher variables. */ void nConServer::Render() { int displayHeight = nGfxServer2::Instance()->GetDisplayMode().GetHeight(); const int fontHeight = 16; if (this->consoleOpen) { this->RenderConsole(displayHeight, fontHeight); } else if (this->watchersOpen) { this->RenderWatchers(displayHeight, fontHeight); } } //------------------------------------------------------------------------------ /** Insert a char into the input buffer, and advance cursor position. */ void nConServer::EditInsertChar(char c) { const int inputBufferSize = sizeof(this->inputBuffer); if (this->overstrike) { // overstrike mode if ((0 == this->inputBuffer[this->cursorPos]) && (this->cursorPos < (inputBufferSize - 1))) { this->inputBuffer[this->cursorPos + 1] = 0; } this->inputBuffer[this->cursorPos] = c; } else { // insert mode char* moveFrom = this->inputBuffer + this->cursorPos; char* moveTo = moveFrom + 1; int moveCount = inputBufferSize - (this->cursorPos + 1); // preserve trailing 0 memmove(moveTo, moveFrom, moveCount); this->inputBuffer[this->cursorPos] = c; } this->cursorPos++; if (this->cursorPos >= inputBufferSize) { this->cursorPos = inputBufferSize - 1; this->inputBuffer[this->cursorPos] = 0; } } //------------------------------------------------------------------------------ /** Move the cursor position one to the left. */ void nConServer::EditCursorLeft() { this->cursorPos--; if (this->cursorPos < 0) { this->cursorPos = 0; } } //------------------------------------------------------------------------------ /** Move the cursor position one to the right. */ void nConServer::EditCursorRight() { this->cursorPos++; int len = static_cast<int>( strlen(this->inputBuffer) ); if (this->cursorPos > len) { this->cursorPos = len; } } //------------------------------------------------------------------------------ /** Move the cursor to the beginning of the previous word. */ void nConServer::EditWordLeft() { while ((--this->cursorPos >= 0) && this->inputBuffer[this->cursorPos] == ' '); while ((--this->cursorPos >= 0) && this->inputBuffer[this->cursorPos] != ' '); this->cursorPos++; if (this->cursorPos < 0) { this->cursorPos = 0; } } //------------------------------------------------------------------------------ /** Move the cursor to the beginning of the next word. */ void nConServer::EditWordRight() { int len = static_cast<int>( strlen(this->inputBuffer) ); while ((++this->cursorPos < len) && this->inputBuffer[this->cursorPos] == ' '); while ((++this->cursorPos < len) && this->inputBuffer[this->cursorPos] != ' '); while ((++this->cursorPos < len) && this->inputBuffer[this->cursorPos] == ' '); if (this->cursorPos > len) { this->cursorPos = len; } } //------------------------------------------------------------------------------ /** Delete the character to the right of the cursor. */ void nConServer::EditDeleteRight() { char* moveTo = this->inputBuffer + this->cursorPos; char* moveFrom = moveTo + 1; int moveCount = sizeof(this->inputBuffer) - (this->cursorPos + 1); memmove(moveTo, moveFrom, moveCount); } //------------------------------------------------------------------------------ /** Delete the character to the left of the cursor. */ void nConServer::EditDeleteLeft() { if (this->cursorPos > 0) { --this->cursorPos; this->EditDeleteRight(); } } //------------------------------------------------------------------------------ /** Return true if the given input key is in the kill set. If yes, the console server must "swallow" the input event, so that the application doesn't see it. */ bool nConServer::KeyIsInKillSet(int key) { int i = 0; while (keyKillSet[i] != N_KEY_NONE) { if (key == keyKillSet[i]) { return true; } ++i; } return false; } //------------------------------------------------------------------------------ /** Scroll up one line. */ void nConServer::EditScrollUp() { ++this->scrollOffset; } //------------------------------------------------------------------------------ /** Scroll down one line */ void nConServer::EditScrollDown() { --this->scrollOffset; } //------------------------------------------------------------------------------ /** Move cursor to beginning of line. */ void nConServer::EditHome() { this->cursorPos = 0; } //------------------------------------------------------------------------------ /** Move cursor to end of line. */ void nConServer::EditEnd() { this->cursorPos = static_cast<int>( strlen(this->inputBuffer) ); } //------------------------------------------------------------------------------ /** Execute the command in the line buffer. */ void nConServer::ExecuteCommand() { this->AddCommandToHistory(); // print to log nString line = this->refScriptServer->Prompt(); line.Append(this->inputBuffer); line.Append("\n"); n_printf(line.Get()); // execute the command if (this->inputBuffer[0]) { nString result; bool failOnError = this->refScriptServer->GetFailOnError(); this->refScriptServer->SetFailOnError(false); this->refScriptServer->Run(this->inputBuffer, result); this->refScriptServer->SetFailOnError(failOnError); if (false == result.IsEmpty()) { n_printf("%s\n", result.Get()); } } // reset edit parameters this->inputBuffer[0] = 0; this->cursorPos = 0; this->scrollOffset = 0; } //------------------------------------------------------------------------------ /** Takes one input event and edits the line. If the event has been processed, the method returns true, in this case, the event should be deleted so that the application doesn't see the event (this would confuse the the user when the console server is open). The line will be sent off to the script server for evaluation once the user hits the return key. */ bool nConServer::EditLine(nInputEvent* inputEvent) { bool killEvent = false; // handle alphanumeric characters if ((inputEvent->GetType() == N_INPUT_KEY_CHAR) && (inputEvent->GetChar() >= ' ')) { this->EditInsertChar( static_cast<char>( inputEvent->GetChar() ) ); killEvent = true; } // handle control keys if (inputEvent->GetType() == N_INPUT_KEY_DOWN) { if (this->KeyIsInKillSet(inputEvent->GetKey())) { killEvent = true; } switch (inputEvent->GetKey()) { case N_KEY_LEFT: if (this->ctrlDown) this->EditWordLeft(); else this->EditCursorLeft(); break; case N_KEY_RIGHT: if (this->ctrlDown) this->EditWordRight(); else this->EditCursorRight(); break; case N_KEY_BACK: this->EditDeleteLeft(); break; case N_KEY_DELETE: this->EditDeleteRight(); break; case N_KEY_INSERT: this->overstrike = !this->overstrike; break; case N_KEY_UP: if (this->ctrlDown) this->EditScrollUp(); else this->RecallPrevCmd(); break; case N_KEY_DOWN: if (this->ctrlDown) this->EditScrollDown(); else this->RecallNextCmd(); break; case N_KEY_RETURN: this->ExecuteCommand(); break; case N_KEY_CONTROL: this->ctrlDown = true; break; case N_KEY_HOME: this->EditHome(); break; case N_KEY_END: this->EditEnd(); break; default: break; } } else if (inputEvent->GetType() == N_INPUT_KEY_UP) { if (this->KeyIsInKillSet(inputEvent->GetKey())) { killEvent = true; } switch (inputEvent->GetKey()) { case N_KEY_CONTROL: this->ctrlDown = false; break; default: break; } } return killEvent; } //------------------------------------------------------------------------------ /** Add the command in the input buffer to the command history. */ void nConServer::AddCommandToHistory() { this->ResetHistory(); if (this->inputBuffer[0]) { this->historyBuffer.Put(this->inputBuffer); this->historyBuffer.Put("\n"); } } //------------------------------------------------------------------------------ /** Reset the command history position. */ void nConServer::ResetHistory() { this->historyIndex = 0; } //------------------------------------------------------------------------------ /** Recall the previous command from the history buffer. */ void nConServer::RecallPrevCmd() { ++this->historyIndex; int i; int actLine = this->historyBuffer.GetHeadLine(); for (i = 0; i < this->historyIndex; i++) { int prevLine = this->historyBuffer.GetPrevLine(actLine); if (-1 == prevLine) { --this->historyIndex; break; } actLine = prevLine; } const char* historyCommand = this->historyBuffer.GetLine(actLine); if (historyCommand) { strcpy(this->inputBuffer, historyCommand); this->EditEnd(); } } //------------------------------------------------------------------------------ /** Recall the next command from the history buffer. */ void nConServer::RecallNextCmd() { --this->historyIndex; if (this->historyIndex < 0) { this->historyIndex = 0; } int i; int actLine = this->historyBuffer.GetHeadLine(); for (i = 0; i < this->historyIndex; i++) { int prevLine = this->historyBuffer.GetPrevLine(actLine); if (-1 == prevLine) { ++this->historyIndex; break; } actLine = prevLine; } const char* historyCommand = this->historyBuffer.GetLine(actLine); if (historyCommand) { strcpy(this->inputBuffer, historyCommand); this->EditEnd(); } } //------------------------------------------------------------------------------ /** Trigger the console server. Due to a chicken-egg problem this method is called from inside nInputServer::Trigger(). Don't forget to actually render the console by calling nConServer::Render() somewhere between nGfxServer::BeginScene()/EndScene(). */ void nConServer::Trigger() { if (this->consoleOpen) { // parse input events... nInputServer* inputServer = this->refInputServer.get(); nInputEvent* inputEvent = inputServer->FirstEvent(); if (inputEvent) { nInputEvent* nextInputEvent; do { nextInputEvent = inputServer->NextEvent(inputEvent); if (this->EditLine(inputEvent)) { inputEvent->SetDisabled(true); } } while ( 0!= (inputEvent = nextInputEvent)); } } } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 789 ] ] ]
2cd61d6449f7a22e4c1c0951b2b359682ee7acb5
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
/src/video/animation.h
7d1f7a9f8c2e035a110ae5f8cf03073aba58c331
[]
no_license
renardchien/Eta-Chronicles
27ad4ffb68385ecaafae4f12b0db67c096f62ad1
d77d54184ec916baeb1ab7cc00ac44005d4f5624
refs/heads/master
2021-01-10T19:28:28.394781
2011-09-05T14:40:38
2011-09-05T14:40:38
1,914,623
1
2
null
null
null
null
UTF-8
C++
false
false
12,706
h
/*************************************************************************** * animation.h - header for the corresponding cpp file * * Copyright (C) 2003 - 2009 Florian Richter ***************************************************************************/ /* 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. 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 SMC_ANIMATION_H #define SMC_ANIMATION_H #include "../objects/animated_sprite.h" #include "../core/obj_manager.h" namespace SMC { /* *** *** *** *** *** *** *** Animation definitions *** *** *** *** *** *** *** *** *** *** */ enum AnimationEffect { ANIM_UNDEFINED, BLINKING_POINTS, FIRE_EXPLOSION, PARTICLE_EXPLOSION }; /* *** *** *** *** *** *** *** Particle blending definitions *** *** *** *** *** *** *** *** *** *** */ enum BlendingMode { BLEND_NONE, BLEND_ADD, BLEND_DRIVE // todo : more }; /* *** *** *** *** *** *** *** Base Animation class *** *** *** *** *** *** *** *** *** *** */ class cAnimation : public cAnimated_Sprite { public: cAnimation( float x = 0.0f, float y = 0.0f ); virtual ~cAnimation( void ); // initialize animation virtual void Init_Anim( void ); // update animation virtual void Update( void ); // draw animation virtual void Draw( cSurface_Request *request = NULL ); // Set time to live for Objects in seconds void Set_Time_to_Live( float time, float time_rand = 0.0f ); /* Set speed of fading out ( 0.01 - 100 ) * the lower the longer it takes * Note : only useful for non particle animation Objects */ void Set_Fading_Speed( float speed ); // set z position virtual void Set_Pos_Z( float pos, float pos_rand = 0.0f ); // Z random position float posz_rand; // fading out speed float fading_speed; // object time to live float time_to_live, time_to_live_rand; // animation type AnimationEffect animtype; }; /* *** *** *** *** *** *** *** *** Blinking points *** *** *** *** *** *** *** *** *** */ class cAnimation_Goldpiece : public cAnimation { public: cAnimation_Goldpiece( float posx, float posy, float height = 40.0f, float width = 20.0f ); virtual ~cAnimation_Goldpiece( void ); // initialize animation virtual void Init_Anim( void ); // update virtual void Update( void ); // draw virtual void Draw( cSurface_Request *request = NULL ); typedef vector<cSprite *> BlinkPointList; BlinkPointList objects; }; /* *** *** *** *** *** *** *** Fireball Animation *** *** *** *** *** *** *** *** *** *** */ class cAnimation_Fireball_Item : public cAnimated_Sprite { public: cAnimation_Fireball_Item( void ) : cAnimated_Sprite() { counter = 0.0f; } virtual ~cAnimation_Fireball_Item( void ) {} // lifetime float counter; }; class cAnimation_Fireball : public cAnimation { public: cAnimation_Fireball( float posx, float posy, unsigned int power = 5 ); virtual ~cAnimation_Fireball( void ); // initialize animation virtual void Init_Anim( void ); // update virtual void Update( void ); // draw virtual void Draw( cSurface_Request *request = NULL ); typedef vector<cAnimation_Fireball_Item *> FireAnimList; FireAnimList objects; }; /* *** *** *** *** *** *** *** Particle Emitter item *** *** *** *** *** *** *** *** *** *** */ // pre declare class cParticle_Emitter; // Particle Item class cParticle : public cMovingSprite { public: cParticle( cParticle_Emitter *parent ); virtual ~cParticle( void ); // update virtual void Update( void ); // draw virtual void Draw( cSurface_Request *request = NULL ); // set gravity void Set_Gravity( float x, float y ); // parent particle emitter cParticle_Emitter *m_parent; // time to live float time_to_live; // constant rotation float const_rotx, const_roty, const_rotz; // particle gravity float gravity_x, gravity_y; // fading position value float fade_pos; }; /* *** *** *** *** *** *** *** Particle Emitter *** *** *** *** *** *** *** *** *** *** */ class cParticle_Emitter : public cAnimation { public: // constructor cParticle_Emitter( void ); // create from stream cParticle_Emitter( CEGUI::XMLAttributes &attributes ); // destructor virtual ~cParticle_Emitter( void ); // create from stream virtual void Create_From_Stream( CEGUI::XMLAttributes &attributes ); // save to stream virtual void Save_To_Stream( ofstream &file ); // Init virtual void Init( void ); // copy virtual cParticle_Emitter *Copy( void ); // initialize animation virtual void Init_Anim( void ); // Emit Particles virtual void Emit( void ); // Clear Particles and Animation data virtual void Clear( void ); // Update given settings virtual void Update( void ); // Draw everything virtual void Draw( cSurface_Request *request = NULL ); // if update is valid for the current state virtual bool Is_Update_Valid( void ); // if draw is valid for the current state and position virtual bool Is_Draw_Valid( void ); // Set the Emitter rect void Set_Emitter_Rect( float x, float y, float w = 0, float h = 0 ); void Set_Emitter_Rect( const GL_rect &r ); /* Set time to live for the Emitter in seconds * set -1 for infinite */ void Set_Emitter_Time_to_Live( float time ); // Set time between Iterations void Set_Emitter_Iteration_Interval( float time ); // Set Particle Count/Quota void Set_Quota( unsigned int size ); // Set speed ( 0 - 100 ) void Set_Speed( float vel_base, float vel_random = 2 ); // Set start rotation z uses start direction void Set_Start_Rot_Z_Uses_Direction( bool enable ); // Set x constant rotation void Set_Const_Rotation_X( float rot, float rot_random = 0 ); // Set y constant rotation void Set_Const_Rotation_Y( float rot, float rot_random = 0 ); // Set z constant rotation void Set_Const_Rotation_Z( float rot, float rot_random = 0 ); /* Set direction range ( 0 - 360 ) * 0 : Right, 90 Down, 180 Left, 270 Up */ void Set_Direction_Range( float start, float range = 0 ); // Set image scale ( 0.01 - 100 ) virtual void Set_Scale( float nscale, float scale_random = 0 ); // Set horizontal gravity void Set_Horizontal_Gravity( float start, float random = 0 ); // Set vertical gravity void Set_Vertical_Gravity( float start, float random = 0 ); // Set the Color virtual void Set_Color( const Color &col, const Color &col_rand = Color( static_cast<Uint8>(0), 0, 0, 0 ) ); // Set fading type void Set_Fading_Size( bool enable ); void Set_Fading_Alpha( bool enable ); void Set_Fading_Color( bool enable ); // Set blending mode virtual void Set_Blending( BlendingMode mode ); // Set image virtual void Set_Image( cGL_Surface *img ); // Set the file name virtual void Set_Filename( const std::string &str_filename ); // editor activation virtual void Editor_Activate( void ); // position z base text changed event bool Editor_Pos_Z_Base_Text_Changed( const CEGUI::EventArgs &event ); // position z rand text changed event bool Editor_Pos_Z_Rand_Text_Changed( const CEGUI::EventArgs &event ); // editor filename text changed event bool Editor_Filename_Text_Changed( const CEGUI::EventArgs &event ); // emitter width text changed event bool Editor_Emitter_Width_Text_Changed( const CEGUI::EventArgs &event ); // emitter height text changed event bool Editor_Emitter_Height_Text_Changed( const CEGUI::EventArgs &event ); // emitter time to live text changed event bool Editor_Emitter_Time_To_Live_Text_Changed( const CEGUI::EventArgs &event ); // emitter interval text changed event bool Editor_Emitter_Interval_Text_Changed( const CEGUI::EventArgs &event ); // quota text changed event bool Editor_Quota_Text_Changed( const CEGUI::EventArgs &event ); // ttl base text changed event bool Editor_Ttl_Base_Text_Changed( const CEGUI::EventArgs &event ); // ttl rand text changed event bool Editor_Ttl_Rand_Text_Changed( const CEGUI::EventArgs &event ); // velocity base text changed event bool Editor_Velocity_Base_Text_Changed( const CEGUI::EventArgs &event ); // velocity rand text changed event bool Editor_Velocity_Rand_Text_Changed( const CEGUI::EventArgs &event ); // start rotation x base text changed event bool Editor_Rotation_X_Base_Text_Changed( const CEGUI::EventArgs &event ); // start rotation y base text changed event bool Editor_Rotation_Y_Base_Text_Changed( const CEGUI::EventArgs &event ); // start rotation z base text changed event bool Editor_Rotation_Z_Base_Text_Changed( const CEGUI::EventArgs &event ); // start rotation z uses start direction event bool Editor_Start_Rot_Z_Uses_Direction_Changed( const CEGUI::EventArgs &event ); // constant rotation x base text changed event bool Editor_Const_Rotation_X_Base_Text_Changed( const CEGUI::EventArgs &event ); // constant rotation x rand text changed event bool Editor_Const_Rotation_X_Rand_Text_Changed( const CEGUI::EventArgs &event ); // constant rotation y base text changed event bool Editor_Const_Rotation_Y_Base_Text_Changed( const CEGUI::EventArgs &event ); // constant rotation y rand text changed event bool Editor_Const_Rotation_Y_Rand_Text_Changed( const CEGUI::EventArgs &event ); // constant rotation z base text changed event bool Editor_Const_Rotation_Z_Base_Text_Changed( const CEGUI::EventArgs &event ); // constant rotation z rand text changed event bool Editor_Const_Rotation_Z_Rand_Text_Changed( const CEGUI::EventArgs &event ); // direction base text changed event bool Editor_Direction_Base_Text_Changed( const CEGUI::EventArgs &event ); // direction rand text changed event bool Editor_Direction_Rand_Text_Changed( const CEGUI::EventArgs &event ); // scale base text changed event bool Editor_Scale_Base_Text_Changed( const CEGUI::EventArgs &event ); // scale rand text changed event bool Editor_Scale_Rand_Text_Changed( const CEGUI::EventArgs &event ); // horizontal gravity base text changed event bool Editor_Horizontal_Gravity_Base_Text_Changed( const CEGUI::EventArgs &event ); // horizontal gravity rand text changed event bool Editor_Horizontal_Gravity_Rand_Text_Changed( const CEGUI::EventArgs &event ); // vertical gravity base text changed event bool Editor_Vertical_Gravity_Base_Text_Changed( const CEGUI::EventArgs &event ); // vertical gravity rand text changed event bool Editor_Vertical_Gravity_Rand_Text_Changed( const CEGUI::EventArgs &event ); // todo : start rotation x/y/z rand, color, color_rand // Particle items typedef vector<cParticle *> ParticleList; ParticleList objects; // filename of the particle std::string filename; // emitter time to live float emitter_time_to_live; // emitter iteration interval float emitter_iteration_interval; // emitter object quota unsigned int emitter_quota; // velocity float vel, vel_rand; // start rotation z uses start direction bool start_rot_z_uses_direction; // constant rotation float const_rotx, const_roty, const_rotz; // constant rotation random modifier float const_rotx_rand, const_roty_rand, const_rotz_rand; // direction range float angle_start, angle_range; // size scaling float size_scale, size_scale_rand; // gravity float gravity_x, gravity_x_rand; float gravity_y, gravity_y_rand; // color random Color color_rand; // fading types todo : dest-color bool fade_size, fade_alpha, fade_color; // blending mode BlendingMode blending; private: // time alive float emitter_living_time; // emit counter float emit_counter; }; /* *** *** *** *** *** *** *** Animation Manager *** *** *** *** *** *** *** *** *** *** */ class cAnimation_Manager : public cObject_Manager<cAnimation> { public: cAnimation_Manager( void ); virtual ~cAnimation_Manager( void ); // Add an animation object with the given settings virtual void Add( cAnimation *animation ); // Update the objects void Update( void ); // Draw the objects void Draw( void ); typedef vector<cAnimation *> AnimationList; }; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ // The Animation Manager extern cAnimation_Manager *pAnimation_Manager; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ [ [ 1, 383 ] ] ]
061501041124bc2c017d7c5aee0522d56c8213a6
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/listenersBranch/qrgui/models/details/modelsImplementation/graphicalModelItem.cpp
3229db61294bcac55802701c80948c0aae51c245
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include "graphicalModelItem.h" #include "../../kernel/exception/exception.h" using namespace qReal; using namespace models::details::modelsImplementation; GraphicalModelItem::GraphicalModelItem(Id const &id, Id const &logicalId, GraphicalModelItem *parent) : AbstractModelItem(id, parent), mLogicalId(logicalId) { } Id GraphicalModelItem::logicalId() const { return mLogicalId; }
[ [ [ 1, 16 ] ] ]
b7df34e91ba8bfab7e4488786ba35153c9d21b02
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/nv38box/Math/WmlGVector.cpp
8423ee21e94713ea7a10ef57eb526eacd818a2b8
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
10,735
cpp
#include "base.h" // precompiled headers support // Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlGVector.h" using namespace Wml; //---------------------------------------------------------------------------- template<class Real> GVector<Real>::GVector(int iSize) { if (iSize > 0) { m_iSize = iSize; m_afTuple = new Real[m_iSize]; memset(m_afTuple, 0, m_iSize * sizeof(Real)); } else { m_iSize = 0; m_afTuple = 0; } } //---------------------------------------------------------------------------- template<class Real> GVector<Real>::GVector(int iSize, const Real* afTuple) { if (iSize > 0) { m_iSize = iSize; m_afTuple = new Real[m_iSize]; memcpy(m_afTuple, afTuple, m_iSize * sizeof(Real)); } else { m_iSize = 0; m_afTuple = 0; } } //---------------------------------------------------------------------------- template<class Real> GVector<Real>::GVector(const GVector& rkV) { m_iSize = rkV.m_iSize; if (m_iSize > 0) { m_afTuple = new Real[m_iSize]; memcpy(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)); } else { m_afTuple = 0; } } //---------------------------------------------------------------------------- template<class Real> GVector<Real>::~GVector() { delete[] m_afTuple; } //---------------------------------------------------------------------------- template<class Real> void GVector<Real>::SetSize(int iSize) { delete[] m_afTuple; if (iSize > 0) { m_iSize = iSize; m_afTuple = new Real[m_iSize]; memset(m_afTuple, 0, m_iSize * sizeof(Real)); } else { m_iSize = 0; m_afTuple = 0; } } //---------------------------------------------------------------------------- template<class Real> int GVector<Real>::GetSize() const { return m_iSize; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> ::operator const Real*() const { return m_afTuple; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> ::operator Real*() { return m_afTuple; } //---------------------------------------------------------------------------- template<class Real> Real GVector<Real> ::operator[](int i) const { assert(0 <= i && i < m_iSize); return m_afTuple[i]; } //---------------------------------------------------------------------------- template<class Real> Real& GVector<Real> ::operator[](int i) { assert(0 <= i && i < m_iSize); return m_afTuple[i]; } //---------------------------------------------------------------------------- template<class Real> GVector<Real>& GVector<Real> ::operator=(const GVector& rkV) { if (rkV.m_iSize > 0) { if (m_iSize != rkV.m_iSize) { delete[] m_afTuple; m_iSize = rkV.m_iSize; m_afTuple = new Real[m_iSize]; } memcpy(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)); } else { delete[] m_afTuple; m_iSize = 0; m_afTuple = 0; } return *this; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator==(const GVector& rkV) const { return memcmp(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)) == 0; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator!=(const GVector& rkV) const { return memcmp(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)) != 0; } //---------------------------------------------------------------------------- template<class Real> int GVector<Real>::CompareArrays(const GVector& rkV) const { for (int i = 0; i < m_iSize; i++) { unsigned int uiTest0 = *(unsigned int *) &m_afTuple[i]; unsigned int uiTest1 = *(unsigned int *) &rkV.m_afTuple[i]; if (uiTest0 < uiTest1) return -1; if (uiTest0 > uiTest1) return +1; } return 0; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator<(const GVector& rkV) const { return CompareArrays(rkV) < 0; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator<=(const GVector& rkV) const { return CompareArrays(rkV) <= 0; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator>(const GVector& rkV) const { return CompareArrays(rkV) > 0; } //---------------------------------------------------------------------------- template<class Real> bool GVector<Real> ::operator>=(const GVector& rkV) const { return CompareArrays(rkV) >= 0; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> GVector<Real> ::operator+(const GVector& rkV) const { GVector<Real> kSum(m_iSize); for (int i = 0; i < m_iSize; i++) kSum.m_afTuple[i] = m_afTuple[i] + rkV.m_afTuple[i]; return kSum; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> GVector<Real> ::operator-(const GVector& rkV) const { GVector<Real> kDiff(m_iSize); for (int i = 0; i < m_iSize; i++) kDiff.m_afTuple[i] = m_afTuple[i] - rkV.m_afTuple[i]; return kDiff; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> GVector<Real> ::operator*(Real fScalar) const { GVector<Real> kProd(m_iSize); for (int i = 0; i < m_iSize; i++) kProd.m_afTuple[i] = fScalar * m_afTuple[i]; return kProd; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> GVector<Real> ::operator/(Real fScalar) const { GVector<Real> kQuot(m_iSize); int i; if (fScalar != (Real) 0.0) { Real fInvScalar = ((Real) 1.0) / fScalar; for (i = 0; i < m_iSize; i++) kQuot.m_afTuple[i] = fInvScalar * m_afTuple[i]; } else { for (i = 0; i < m_iSize; i++) kQuot.m_afTuple[i] = Math<Real>::MAX_REAL; } return kQuot; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> GVector<Real> ::operator-() const { GVector<Real> kNeg(m_iSize); for (int i = 0; i < m_iSize; i++) kNeg.m_afTuple[i] = -m_afTuple[i]; return kNeg; } //---------------------------------------------------------------------------- template<class Real> GVector<Real> Wml::operator*(Real fScalar, const GVector<Real>& rkV) { GVector<Real> kProd(rkV.GetSize()); for (int i = 0; i < rkV.GetSize(); i++) kProd[i] = fScalar * rkV[i]; return kProd; } //---------------------------------------------------------------------------- template<class Real> GVector<Real>& GVector<Real> ::operator+=(const GVector& rkV) { for (int i = 0; i < m_iSize; i++) m_afTuple[i] += rkV.m_afTuple[i]; return *this; } //---------------------------------------------------------------------------- template<class Real> GVector<Real>& GVector<Real> ::operator-=(const GVector& rkV) { for (int i = 0; i < m_iSize; i++) m_afTuple[i] -= rkV.m_afTuple[i]; return *this; } //---------------------------------------------------------------------------- template<class Real> GVector<Real>& GVector<Real> ::operator*=(Real fScalar) { for (int i = 0; i < m_iSize; i++) m_afTuple[i] *= fScalar; return *this; } //---------------------------------------------------------------------------- template<class Real> GVector<Real>& GVector<Real> ::operator/=(Real fScalar) { int i; if (fScalar != (Real) 0.0) { Real fInvScalar = ((Real) 1.0) / fScalar; for (i = 0; i < m_iSize; i++) m_afTuple[i] *= fInvScalar; } else { for (i = 0; i < m_iSize; i++) m_afTuple[i] = Math<Real>::MAX_REAL; } return *this; } //---------------------------------------------------------------------------- template<class Real> Real GVector<Real>::Length() const { Real fSqrLen = (Real) 0.0; for (int i = 0; i < m_iSize; i++) fSqrLen += m_afTuple[i] * m_afTuple[i]; return Math<Real>::Sqrt(fSqrLen); } //---------------------------------------------------------------------------- template<class Real> Real GVector<Real>::SquaredLength() const { Real fSqrLen = (Real) 0.0; for (int i = 0; i < m_iSize; i++) fSqrLen += m_afTuple[i] * m_afTuple[i]; return fSqrLen; } //---------------------------------------------------------------------------- template<class Real> Real GVector<Real>::Dot(const GVector& rkV) const { Real fDot = (Real) 0.0; for (int i = 0; i < m_iSize; i++) fDot += m_afTuple[i] * rkV.m_afTuple[i]; return fDot; } //---------------------------------------------------------------------------- template<class Real> Real GVector<Real>::Normalize() { Real fLength = Length(); int i; if (fLength > Math<Real>::EPSILON) { Real fInvLength = ((Real) 1.0) / fLength; for (i = 0; i < m_iSize; i++) m_afTuple[i] *= fInvLength; } else { fLength = (Real) 0.0; for (i = 0; i < m_iSize; i++) m_afTuple[i] = (Real) 0.0; } return fLength; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template class WML_ITEM GVector<float>; #ifdef WML_USING_VC6 template WML_ITEM GVector<float> operator * (float, const GVector<float>&); #else template WML_ITEM GVector<float> operator * <float>(float, const GVector<float>&); #endif template class WML_ITEM GVector<double>; #ifdef WML_USING_VC6 template WML_ITEM GVector<double> operator * (double, const GVector<double>&); #else template WML_ITEM GVector<double> operator * <double>(double, const GVector<double>&); #endif } //----------------------------------------------------------------------------
[ [ [ 1, 400 ] ] ]
6de4448033c53838669c7aa495523ae1e482b056
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/entropy_decoder_model.h
8e1b4e289a0e667519e5a6cc41d919f2a363ce01
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
3,921
h
// Copyright (C) 2004 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_ENTROPY_DECODER_MODEl_ #define DLIB_ENTROPY_DECODER_MODEl_ #include "entropy_decoder_model/entropy_decoder_model_kernel_1.h" #include "entropy_decoder_model/entropy_decoder_model_kernel_2.h" #include "entropy_decoder_model/entropy_decoder_model_kernel_3.h" #include "entropy_decoder_model/entropy_decoder_model_kernel_4.h" #include "entropy_decoder_model/entropy_decoder_model_kernel_5.h" #include "entropy_decoder_model/entropy_decoder_model_kernel_6.h" #include "conditioning_class.h" #include "memory_manager.h" namespace dlib { template < unsigned long alphabet_size, typename entropy_decoder > class entropy_decoder_model { entropy_decoder_model() {} typedef typename conditioning_class<alphabet_size+1>::kernel_1a cc1; typedef typename conditioning_class<alphabet_size+1>::kernel_2a cc2; typedef typename conditioning_class<alphabet_size+1>::kernel_3a cc3; typedef typename conditioning_class<alphabet_size+1>::kernel_4a cc4a; typedef typename conditioning_class<alphabet_size+1>::kernel_4b cc4b; typedef typename conditioning_class<alphabet_size+1>::kernel_4c cc4c; typedef typename conditioning_class<alphabet_size+1>::kernel_4d cc4d; public: //----------- kernels --------------- // kernel_1 typedef entropy_decoder_model_kernel_1<alphabet_size,entropy_decoder,cc1> kernel_1a; typedef entropy_decoder_model_kernel_1<alphabet_size,entropy_decoder,cc2> kernel_1b; typedef entropy_decoder_model_kernel_1<alphabet_size,entropy_decoder,cc3> kernel_1c; // -------------------- // kernel_2 typedef entropy_decoder_model_kernel_2<alphabet_size,entropy_decoder,cc1,cc1> kernel_2a; typedef entropy_decoder_model_kernel_2<alphabet_size,entropy_decoder,cc2,cc2> kernel_2b; typedef entropy_decoder_model_kernel_2<alphabet_size,entropy_decoder,cc3,cc3> kernel_2c; typedef entropy_decoder_model_kernel_2<alphabet_size,entropy_decoder,cc2,cc4b> kernel_2d; // -------------------- // kernel_3 typedef entropy_decoder_model_kernel_3<alphabet_size,entropy_decoder,cc1,cc4b> kernel_3a; typedef entropy_decoder_model_kernel_3<alphabet_size,entropy_decoder,cc2,cc4b> kernel_3b; typedef entropy_decoder_model_kernel_3<alphabet_size,entropy_decoder,cc3,cc4b> kernel_3c; // -------------------- // kernel_4 typedef entropy_decoder_model_kernel_4<alphabet_size,entropy_decoder,200000,4> kernel_4a; typedef entropy_decoder_model_kernel_4<alphabet_size,entropy_decoder,1000000,5> kernel_4b; // -------------------- // kernel_5 typedef entropy_decoder_model_kernel_5<alphabet_size,entropy_decoder,200000,4> kernel_5a; typedef entropy_decoder_model_kernel_5<alphabet_size,entropy_decoder,1000000,5> kernel_5b; typedef entropy_decoder_model_kernel_5<alphabet_size,entropy_decoder,2500000,7> kernel_5c; // -------------------- // kernel_6 typedef entropy_decoder_model_kernel_6<alphabet_size,entropy_decoder> kernel_6a; }; } #endif // DLIB_ENTROPY_DECODER_MODEl_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 108 ] ] ]
52c5b3e0ea74d295f84cf61bf28bae007262028d
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/include/TRTUniformGrid.h
5be0c2d13af04df2c0b24233c6327e8a3149d6eb
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
4,165
h
//===================================================================================================================== // // TRTUniformGrid.h // // Definition of class: TinyRT::UniformGrid // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2008 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== #ifndef _TRT_UNIFORMGRID_H_ #define _TRT_UNIFORMGRID_H_ namespace TinyRT { //===================================================================================================================== /// \ingroup TinyRT /// \brief A uniform grid data structure /// /// This class implements the UniformGrid_C concept /// /// \param ObjectSet_T Must implement the ObjectSet_C concept //===================================================================================================================== template< class ObjectSet_T > class UniformGrid { public: typedef typename ObjectSet_T::obj_id obj_count; typedef typename ObjectSet_T::obj_id obj_id; typedef const obj_id* CellIterator; typedef uint32 UnsignedCellIndex; typedef int32 SignedCellIndex; /// Returns the bounding box of the grid inline const AxisAlignedBox& GetBoundingBox() const { return m_boundingBox; }; /// Returns the number of grid cells along each axis inline const Vec3<uint32>& GetCellCounts() const { return m_cellCounts; }; /// Returns the number of objects in a cell inline size_t GetCellObjectCount( const Vec3<uint32>& rCell ) const { const size_t* pCell = &m_cellOffsets[AddressCell(rCell)]; return pCell[1] - pCell[0]; }; /// Retrieves iterators for the list of objects in a particular cell inline void GetCellObjectList( const Vec3<uint32>& rCell, CellIterator& hCellStart, CellIterator& hCellEnd ) const { // check the bit array first, before accessing the cell offset table // In big grids, most cells tend to be empty, so this results in less cache pollution size_t nCellAddr = AddressCell(rCell); if( m_cellMasks[nCellAddr/8] & (1<< (nCellAddr%8)) ) { const size_t* pCellOffs = &m_cellOffsets[nCellAddr]; hCellStart = m_objectList + pCellOffs[0]; hCellEnd = m_objectList + pCellOffs[1]; return; } hCellStart = 0; hCellEnd = 0; }; /// Rebuilds the grid from an object set void Build( ObjectSet_T* pObjects, float fLambda ); private: /// Computes the address of a cell given its 3D cell coordinates inline size_t AddressCell( const Vec3<uint32>& rCell ) const { TRT_ASSERT( rCell.x < m_cellCounts.x && rCell.y < m_cellCounts.y && rCell.z < m_cellCounts.z ); size_t nCell = rCell.z*m_nWH + rCell.y*m_cellCounts.x + rCell.x; return nCell; }; // The grid is represented by storing each cell's offset into the object list. The object count // for cell i is offset[i+1] - offset[i]. The cell offset array contains an extra (bogus) entry to avoid // the need to check boundary conditions ScopedArray< size_t > m_cellOffsets; ///< Offset of cell i's object references in the object list. ScopedArray< obj_id > m_objectList; ///< Global list of object references ScopedArray< uint8 > m_cellMasks; ///< Bit array indicating, for each cell, whether it actually has objects in it AxisAlignedBox m_boundingBox; Vec3<uint32> m_cellCounts; ///< Number of cells along each axis uint32 m_nWH; ///< cellCounts.x*cellCounts.y }; } #include "TRTUniformGrid.inl" #endif // _TRT_UNIFORMGRID_H_
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 105 ] ] ]
18186afbf3393ce7f7c99a37b5f541cec34e9c32
f8c4a7b2ed9551c01613961860115aaf427d3839
/src/cEnemy.h
06ed1c4196a157ac8d6576a73d17a64ca15b3ecb
[]
no_license
ifgrup/mvj-grupo5
de145cd57d7c5ff2c140b807d2d7c5bbc57cc5a9
6ba63d89b739c6af650482d9c259809e5042a3aa
refs/heads/master
2020-04-19T15:17:15.490509
2011-12-19T17:40:19
2011-12-19T17:40:19
34,346,323
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,092
h
#ifndef __ENEMY__H__ #define __ENEMY__H__ #include <windows.h> #include "cTrajectory.h" #include "cPath.h" #include "cScene.h" #include "cWalkabilityFunctor.h" #include "cWalkabilityFunctorFlalling.h" #include "cWalkabilityFunctorRandom.h" #include "cStrategyFunctor.h" #include "cStrategyPatrol.h" #include "cStrategyFolouDeCritter.h" typedef enum WalkingTypes{ FLALLING=1, RANDOM=2, GRIJANDER=3 }WalkingTypes; typedef enum StrategyTypes{ PATROL=1, FOLOU=2 }StrategyTypes; class cEnemy { public: cEnemy(int cx,int cy,WalkingTypes walkabilityType,StrategyTypes stype); //en función del tipo de walkability, crea el Functor correspondiente cWalkabilityFunctor* pWalkabilityFunctor; cStrategyFunctor* pStrategyFunctor; virtual ~cEnemy(void); void GoToCell(CTile2D **map,int destcx,int destcy); void Move(); void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectLife(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene); void GetRectRadar(RECT *rc,int *posx,int *posy); void SetPosition(int posx,int posy); void GetPosition(int *posx,int *posy); void SetCell(int cellx,int celly); void GetCell(int *cellx,int *celly); bool GetDestinyCell(int* cx, int* cy); //Devuelve el destino actual de la trayectoria del bicho bool HasDetectedPlayer(int x, int y); bool NextTarget(int CritterX, int CritterY,int* newx,int* newy); void RecargaWalkability(); private: int x,y; //Position in total map int cx,cy; //Cell position in total map int cxHome,cyHome; //Posiciones iniciales del enemigo, a las que vuelve cuando contacta con el critter. cPath* Trajectory; //Dinamic, with it's own walkeable function int seq; //Sequence animation control int delay; //Animation delay int filaTilesPersonaje; //Fila del fichero characters.png donde está su animación public: static bool IsThisTileWalkeableForMe(CTile2D*); void GetNextTarget(int* newcx,int*newcy); void GoHome(); //vuelve a la posición inicial }; #endif
[ "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c", "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c" ]
[ [ [ 1, 9 ], [ 11, 12 ], [ 14, 17 ], [ 20, 21 ], [ 27, 30 ], [ 33, 48 ], [ 52, 52 ], [ 55, 58 ], [ 60, 60 ], [ 65, 67 ], [ 69, 72 ] ], [ [ 10, 10 ], [ 13, 13 ], [ 18, 19 ], [ 22, 26 ], [ 31, 32 ], [ 49, 51 ], [ 53, 54 ], [ 59, 59 ], [ 61, 64 ], [ 68, 68 ] ] ]
6c3001935274295921e76c10a09e93934243078c
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Windows/include/idk_ut_Tracer.h
974676ea84b866ec3a0ac7fe29ee9cd37eeeee58
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
2,457
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: idk_ut_Tracer.h,v 1.4 2003/06/02 08:03:41 tomoto Exp $ */ #ifndef _IDK_UT_TRACER_H_ #define _IDK_UT_TRACER_H_ #include <idk_ut_Types.h> /** @file The definition of idk_ut_Tracer class. */ /** Interface of tracer which handles events occured in an execution of a program. By implementing this interface and registering its instance with cs_setTracer(), you can gather various information about program execution for any purpose, e.g. logging or performance measuring. @todo The current interface provides only minumum event handlers. */ class IDK_DECL idk_ut_Tracer : public idk_ut_RealObject { public: ~idk_ut_Tracer(); /** Closes the tracer. The implementation should gracefully finalize itself. */ virtual void closeTracer() = 0; /** Flushes the tracer. If the implementation has buffered events waiting for being processed, it should process them immediately. */ virtual void flushTracer() = 0; /** Called when a system call starts. @param name Name of the system call. */ virtual void startSystemCall(const char* name) = 0; /** Called when a system call ended. @param result Status code (errno) of the system call. */ virtual void endSystemCall(int result) = 0; /** Called when a system call ended. @param result Return value of the system call. */ virtual void endSystemCall(void* result); // default implementation is provided public: /** Sets an instance of tracer as the current tracer. The previous tracer will be discarded, if any. @param tracerPtr Tracer to be used. May pass NULL to simply cancel the previous tracer. */ static void cs_setTracer(const idk_ut_TracerPtr& tracerPtr); /** Calls closeTracer of the current tracer. */ static void cs_close(); /** Calls flushTracer of the current tracer. */ static void cs_flush(); /** Calls startSystemCall of the current tracer. */ static void cs_startSystemCall(const char* name); /** Calls endSystemCall of the current tracer. */ static void cs_endSystemCall(int result); /** Calls endSystemCall of the current tracer. */ static void cs_endSystemCall(void* result); }; IDK_UT_SHAREDPTR_DECL(idk_ut_Tracer); #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 88 ] ] ]
5a8dadeced42c0475fe5ea4a34298ceabf837564
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/MatrixShiftings.cpp
dc9f6813ffce1b3854f078a64a29a24485681fce
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
3,343
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "MatrixShiftings.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() class MatrixShiftings { public: int minimumShifts(vector <string> mat, int val) { vector <int> vm; vector <int> vn; int ret=100000; int cnt=0; int a=0; int b=0; int c=0; int d=0; int m = (int)mat.size(); int n = (int)mat[0].size(); forv(i,mat){ fors(j,mat[i]){ if(mat[i][j] == (val+48)){ vm.push_back(i); vn.push_back(j); cnt++; } } } if(cnt==0) return -1; forv(i,vm){ a = vm[i]+vn[i]; b = (m-1 + n-1) - (vm[i]+vn[i])+2; c = (n-1) + vm[i]-vn[i] +1; d = (m-1) - vm[i]+vn[i] +1; ret = min(ret,min(min(a,b),min(c,d))); } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"136", "427", "568", "309"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 2; verify_case(0, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"0000", "0000", "0099"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; int Arg2 = 2; verify_case(1, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"0123456789"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; int Arg2 = 3; verify_case(2, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"555", "555"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = -1; verify_case(3, Arg2, minimumShifts(Arg0, Arg1)); } void test_case_4() { string Arr0[] = {"12417727123", "65125691886", "55524912622", "12261288888"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; int Arg2 = 6; verify_case(4, Arg2, minimumShifts(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MatrixShiftings ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 97 ] ] ]
dd4d96c8e7c811d9a785ad0af72b9b91c7084fa1
5bd189ea897b10ece778fbf9c7a0891bf76ef371
/BasicEngine/bullet-2.78/Demos/OpenGL/DemoApplication.cpp
998451bd449ba9b336fb29bb7a735533dda3929f
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
boriel/masterullgrupo
c323bdf91f5e1e62c4c44a739daaedf095029710
81b3d81e831eb4d55ede181f875f57c715aa18e3
refs/heads/master
2021-01-02T08:19:54.413488
2011-12-14T22:42:23
2011-12-14T22:42:23
32,330,054
0
0
null
null
null
null
UTF-8
C++
false
false
36,778
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "DemoApplication.h" #include "LinearMath/btIDebugDraw.h" #include "BulletDynamics/Dynamics/btDynamicsWorld.h" #include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h"//picking #include "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h"//picking #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionShapes/btBoxShape.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/CollisionShapes/btUniformScalingShape.h" #include "BulletDynamics/ConstraintSolver/btConstraintSolver.h" #include "GL_ShapeDrawer.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btDefaultMotionState.h" #include "LinearMath/btSerializer.h" #include "GLDebugFont.h" static bool use6Dof = false; extern bool gDisableDeactivation; int numObjects = 0; const int maxNumObjects = 16384; btTransform startTransforms[maxNumObjects]; btCollisionShape* gShapePtr[maxNumObjects];//1 rigidbody has 1 shape (no re-use of shapes) #define SHOW_NUM_DEEP_PENETRATIONS 1 extern int gNumClampedCcdMotions; #ifdef SHOW_NUM_DEEP_PENETRATIONS extern int gNumDeepPenetrationChecks; extern int gNumSplitImpulseRecoveries; extern int gNumGjkChecks; extern int gNumAlignedAllocs; extern int gNumAlignedFree; extern int gTotalBytesAlignedAllocs; #endif // DemoApplication::DemoApplication() //see btIDebugDraw.h for modes : m_dynamicsWorld(0), m_pickConstraint(0), m_shootBoxShape(0), m_cameraDistance(15.0), m_debugMode(0), m_ele(20.f), m_azi(0.f), m_cameraPosition(0.f,0.f,0.f), m_cameraTargetPosition(0.f,0.f,0.f), m_mouseOldX(0), m_mouseOldY(0), m_mouseButtons(0), m_modifierKeys(0), m_scaleBottom(0.5f), m_scaleFactor(2.f), m_cameraUp(0,1,0), m_forwardAxis(2), m_glutScreenWidth(0), m_glutScreenHeight(0), m_frustumZNear(1.f), m_frustumZFar(10000.f), m_ortho(0), m_ShootBoxInitialSpeed(40.f), m_stepping(true), m_singleStep(false), m_idle(false), m_enableshadows(false), m_sundirection(btVector3(1,-2,1)*1000), m_defaultContactProcessingThreshold(BT_LARGE_FLOAT) { #ifndef BT_NO_PROFILE m_profileIterator = CProfileManager::Get_Iterator(); #endif //BT_NO_PROFILE m_shapeDrawer = new GL_ShapeDrawer (); m_shapeDrawer->enableTexture(true); m_enableshadows = false; } DemoApplication::~DemoApplication() { #ifndef BT_NO_PROFILE CProfileManager::Release_Iterator(m_profileIterator); #endif //BT_NO_PROFILE if (m_shootBoxShape) delete m_shootBoxShape; if (m_shapeDrawer) delete m_shapeDrawer; } void DemoApplication::overrideGLShapeDrawer (GL_ShapeDrawer* shapeDrawer) { shapeDrawer->enableTexture (m_shapeDrawer->hasTextureEnabled()); delete m_shapeDrawer; m_shapeDrawer = shapeDrawer; } void DemoApplication::myinit(void) { GLfloat light_ambient[] = { btScalar(0.2), btScalar(0.2), btScalar(0.2), btScalar(1.0) }; GLfloat light_diffuse[] = { btScalar(1.0), btScalar(1.0), btScalar(1.0), btScalar(1.0) }; GLfloat light_specular[] = { btScalar(1.0), btScalar(1.0), btScalar(1.0), btScalar(1.0 )}; /* light_position is NOT default value */ GLfloat light_position0[] = { btScalar(1.0), btScalar(10.0), btScalar(1.0), btScalar(0.0 )}; GLfloat light_position1[] = { btScalar(-1.0), btScalar(-10.0), btScalar(-1.0), btScalar(0.0) }; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position0); glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT1, GL_POSITION, light_position1); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glClearColor(btScalar(0.7),btScalar(0.7),btScalar(0.7),btScalar(0)); // glEnable(GL_CULL_FACE); // glCullFace(GL_BACK); } void DemoApplication::setCameraDistance(float dist) { m_cameraDistance = dist; } float DemoApplication::getCameraDistance() { return m_cameraDistance; } void DemoApplication::toggleIdle() { if (m_idle) { m_idle = false; } else { m_idle = true; } } void DemoApplication::updateCamera() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); btScalar rele = m_ele * btScalar(0.01745329251994329547);// rads per deg btScalar razi = m_azi * btScalar(0.01745329251994329547);// rads per deg btQuaternion rot(m_cameraUp,razi); btVector3 eyePos(0,0,0); eyePos[m_forwardAxis] = -m_cameraDistance; btVector3 forward(eyePos[0],eyePos[1],eyePos[2]); if (forward.length2() < SIMD_EPSILON) { forward.setValue(1.f,0.f,0.f); } btVector3 right = m_cameraUp.cross(forward); btQuaternion roll(right,-rele); eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos; m_cameraPosition[0] = eyePos.getX(); m_cameraPosition[1] = eyePos.getY(); m_cameraPosition[2] = eyePos.getZ(); m_cameraPosition += m_cameraTargetPosition; if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0) return; btScalar aspect; btVector3 extents; if (m_glutScreenWidth > m_glutScreenHeight) { aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); } else { aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth; extents.setValue(1.0f, aspect*1.f,0); } if (m_ortho) { // reset matrix glLoadIdentity(); extents *= m_cameraDistance; btVector3 lower = m_cameraTargetPosition - extents; btVector3 upper = m_cameraTargetPosition + extents; //gluOrtho2D(lower.x, upper.x, lower.y, upper.y); glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glTranslatef(100,210,0); } else { if (m_glutScreenWidth > m_glutScreenHeight) { // glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0); glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } else { // glFrustum (-1.0, 1.0, -aspect, aspect, 1.0, 10000.0); glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ()); } } const float STEPSIZE = 5; void DemoApplication::stepLeft() { m_azi -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera(); } void DemoApplication::stepRight() { m_azi += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera(); } void DemoApplication::stepFront() { m_ele += STEPSIZE; if (m_ele >= 360) m_ele -= 360; updateCamera(); } void DemoApplication::stepBack() { m_ele -= STEPSIZE; if (m_ele < 0) m_ele += 360; updateCamera(); } void DemoApplication::zoomIn() { m_cameraDistance -= btScalar(0.4); updateCamera(); if (m_cameraDistance < btScalar(0.1)) m_cameraDistance = btScalar(0.1); } void DemoApplication::zoomOut() { m_cameraDistance += btScalar(0.4); updateCamera(); } void DemoApplication::reshape(int w, int h) { GLDebugResetFont(w,h); m_glutScreenWidth = w; m_glutScreenHeight = h; glViewport(0, 0, w, h); updateCamera(); } void DemoApplication::keyboardCallback(unsigned char key, int x, int y) { (void)x; (void)y; m_lastKey = 0; #ifndef BT_NO_PROFILE if (key >= 0x31 && key <= 0x39) { int child = key-0x31; m_profileIterator->Enter_Child(child); } if (key==0x30) { m_profileIterator->Enter_Parent(); } #endif //BT_NO_PROFILE switch (key) { case 'q' : #ifdef BT_USE_FREEGLUT //return from glutMainLoop(), detect memory leaks etc. glutLeaveMainLoop(); #else exit(0); #endif break; case 'l' : stepLeft(); break; case 'r' : stepRight(); break; case 'f' : stepFront(); break; case 'b' : stepBack(); break; case 'z' : zoomIn(); break; case 'x' : zoomOut(); break; case 'i' : toggleIdle(); break; case 'g' : m_enableshadows=!m_enableshadows;break; case 'u' : m_shapeDrawer->enableTexture(!m_shapeDrawer->enableTexture(false));break; case 'h': if (m_debugMode & btIDebugDraw::DBG_NoHelpText) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_NoHelpText); else m_debugMode |= btIDebugDraw::DBG_NoHelpText; break; case 'w': //Yorman cambiando a modo debug if (m_debugMode & btIDebugDraw::DBG_DrawWireframe) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawWireframe); else m_debugMode |= btIDebugDraw::DBG_DrawWireframe; break; case 'p': if (m_debugMode & btIDebugDraw::DBG_ProfileTimings) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_ProfileTimings); else m_debugMode |= btIDebugDraw::DBG_ProfileTimings; break; case '=': { int maxSerializeBufferSize = 1024*1024*5; btDefaultSerializer* serializer = new btDefaultSerializer(maxSerializeBufferSize); //serializer->setSerializationFlags(BT_SERIALIZE_NO_DUPLICATE_ASSERT); m_dynamicsWorld->serialize(serializer); FILE* f2 = fopen("testFile.bullet","wb"); fwrite(serializer->getBufferPointer(),serializer->getCurrentBufferSize(),1,f2); fclose(f2); delete serializer; break; } case 'm': if (m_debugMode & btIDebugDraw::DBG_EnableSatComparison) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_EnableSatComparison); else m_debugMode |= btIDebugDraw::DBG_EnableSatComparison; break; case 'n': if (m_debugMode & btIDebugDraw::DBG_DisableBulletLCP) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DisableBulletLCP); else m_debugMode |= btIDebugDraw::DBG_DisableBulletLCP; break; case 't' : if (m_debugMode & btIDebugDraw::DBG_DrawText) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawText); else m_debugMode |= btIDebugDraw::DBG_DrawText; break; case 'y': if (m_debugMode & btIDebugDraw::DBG_DrawFeaturesText) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawFeaturesText); else m_debugMode |= btIDebugDraw::DBG_DrawFeaturesText; break; case 'a': if (m_debugMode & btIDebugDraw::DBG_DrawAabb) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawAabb); else m_debugMode |= btIDebugDraw::DBG_DrawAabb; break; case 'c' : if (m_debugMode & btIDebugDraw::DBG_DrawContactPoints) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawContactPoints); else m_debugMode |= btIDebugDraw::DBG_DrawContactPoints; break; case 'C' : if (m_debugMode & btIDebugDraw::DBG_DrawConstraints) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawConstraints); else m_debugMode |= btIDebugDraw::DBG_DrawConstraints; break; case 'L' : if (m_debugMode & btIDebugDraw::DBG_DrawConstraintLimits) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawConstraintLimits); else m_debugMode |= btIDebugDraw::DBG_DrawConstraintLimits; break; case 'd' : if (m_debugMode & btIDebugDraw::DBG_NoDeactivation) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_NoDeactivation); else m_debugMode |= btIDebugDraw::DBG_NoDeactivation; if (m_debugMode & btIDebugDraw::DBG_NoDeactivation) { gDisableDeactivation = true; } else { gDisableDeactivation = false; } break; case 'o' : { m_ortho = !m_ortho;//m_stepping = !m_stepping; break; } case 's' : clientMoveAndDisplay(); break; // case ' ' : newRandom(); break; case ' ': clientResetScene(); break; case '1': { if (m_debugMode & btIDebugDraw::DBG_EnableCCD) m_debugMode = m_debugMode & (~btIDebugDraw::DBG_EnableCCD); else m_debugMode |= btIDebugDraw::DBG_EnableCCD; break; } case '.': { shootBox(getRayTo(x,y));//getCameraTargetPosition()); break; } case '+': { m_ShootBoxInitialSpeed += 10.f; break; } case '-': { m_ShootBoxInitialSpeed -= 10.f; break; } default: // std::cout << "unused key : " << key << std::endl; break; } if (getDynamicsWorld() && getDynamicsWorld()->getDebugDrawer()) getDynamicsWorld()->getDebugDrawer()->setDebugMode(m_debugMode); } void DemoApplication::setDebugMode(int mode) { m_debugMode = mode; if (getDynamicsWorld() && getDynamicsWorld()->getDebugDrawer()) getDynamicsWorld()->getDebugDrawer()->setDebugMode(mode); } void DemoApplication::moveAndDisplay() { if (!m_idle) clientMoveAndDisplay(); else displayCallback(); } void DemoApplication::displayCallback() { } #define NUM_SPHERES_ON_DIAGONAL 9 void DemoApplication::setShootBoxShape () { if (!m_shootBoxShape) { btBoxShape* box = new btBoxShape(btVector3(.5f,.5f,.5f)); box->initializePolyhedralFeatures(); m_shootBoxShape = box; } } void DemoApplication::shootBox(const btVector3& destination) { if (m_dynamicsWorld) { float mass = 1.f; btTransform startTransform; startTransform.setIdentity(); btVector3 camPos = getCameraPosition(); startTransform.setOrigin(camPos); setShootBoxShape (); btRigidBody* body = this->localCreateRigidBody(mass, startTransform,m_shootBoxShape); body->setLinearFactor(btVector3(1,1,1)); //body->setRestitution(1); btVector3 linVel(destination[0]-camPos[0],destination[1]-camPos[1],destination[2]-camPos[2]); linVel.normalize(); linVel*=m_ShootBoxInitialSpeed; body->getWorldTransform().setOrigin(camPos); body->getWorldTransform().setRotation(btQuaternion(0,0,0,1)); body->setLinearVelocity(linVel); body->setAngularVelocity(btVector3(0,0,0)); body->setCcdMotionThreshold(0.5); body->setCcdSweptSphereRadius(0.9f); // printf("shootBox uid=%d\n", body->getBroadphaseHandle()->getUid()); // printf("camPos=%f,%f,%f\n",camPos.getX(),camPos.getY(),camPos.getZ()); // printf("destination=%f,%f,%f\n",destination.getX(),destination.getY(),destination.getZ()); } } int gPickingConstraintId = 0; btVector3 gOldPickingPos; btVector3 gHitPos(-1,-1,-1); float gOldPickingDist = 0.f; btRigidBody* pickedBody = 0;//for deactivation state btVector3 DemoApplication::getRayTo(int x,int y) { if (m_ortho) { btScalar aspect; btVector3 extents; if (m_glutScreenWidth > m_glutScreenHeight) { aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); } else { aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth; extents.setValue(1.0f, aspect*1.f,0); } extents *= m_cameraDistance; btVector3 lower = m_cameraTargetPosition - extents; btVector3 upper = m_cameraTargetPosition + extents; btScalar u = x / btScalar(m_glutScreenWidth); btScalar v = (m_glutScreenHeight - y) / btScalar(m_glutScreenHeight); btVector3 p(0,0,0); p.setValue((1.0f - u) * lower.getX() + u * upper.getX(),(1.0f - v) * lower.getY() + v * upper.getY(),m_cameraTargetPosition.getZ()); return p; } float top = 1.f; float bottom = -1.f; float nearPlane = 1.f; float tanFov = (top-bottom)*0.5f / nearPlane; float fov = btScalar(2.0) * btAtan(tanFov); btVector3 rayFrom = getCameraPosition(); btVector3 rayForward = (getCameraTargetPosition()-getCameraPosition()); rayForward.normalize(); float farPlane = 10000.f; rayForward*= farPlane; btVector3 rightOffset; btVector3 vertical = m_cameraUp; btVector3 hor; hor = rayForward.cross(vertical); hor.normalize(); vertical = hor.cross(rayForward); vertical.normalize(); float tanfov = tanf(0.5f*fov); hor *= 2.f * farPlane * tanfov; vertical *= 2.f * farPlane * tanfov; btScalar aspect; if (m_glutScreenWidth > m_glutScreenHeight) { aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight; hor*=aspect; } else { aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth; vertical*=aspect; } btVector3 rayToCenter = rayFrom + rayForward; btVector3 dHor = hor * 1.f/float(m_glutScreenWidth); btVector3 dVert = vertical * 1.f/float(m_glutScreenHeight); btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical; rayTo += btScalar(x) * dHor; rayTo -= btScalar(y) * dVert; return rayTo; } btScalar mousePickClamping = 30.f; void DemoApplication::mouseFunc(int button, int state, int x, int y) { if (state == 0) { m_mouseButtons |= 1<<button; } else { m_mouseButtons = 0; } m_mouseOldX = x; m_mouseOldY = y; updateModifierKeys(); if ((m_modifierKeys& BT_ACTIVE_ALT) && (state==0)) { return; } //printf("button %i, state %i, x=%i,y=%i\n",button,state,x,y); //button 0, state 0 means left mouse down btVector3 rayTo = getRayTo(x,y); switch (button) { case 2: { if (state==0) { shootBox(rayTo); } break; }; case 1: { if (state==0) { #if 0 //apply an impulse if (m_dynamicsWorld) { btCollisionWorld::ClosestRayResultCallback rayCallback(m_cameraPosition,rayTo); m_dynamicsWorld->rayTest(m_cameraPosition,rayTo,rayCallback); if (rayCallback.hasHit()) { btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); if (body) { body->setActivationState(ACTIVE_TAG); btVector3 impulse = rayTo; impulse.normalize(); float impulseStrength = 10.f; impulse *= impulseStrength; btVector3 relPos = rayCallback.m_hitPointWorld - body->getCenterOfMassPosition(); body->applyImpulse(impulse,relPos); } } } #endif } else { } break; } case 0: { if (state==0) { //add a point to point constraint for picking if (m_dynamicsWorld) { btVector3 rayFrom; if (m_ortho) { rayFrom = rayTo; rayFrom.setZ(-100.f); } else { rayFrom = m_cameraPosition; } btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo); m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback); if (rayCallback.hasHit()) { btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); if (body) { //other exclusions? if (!(body->isStaticObject() || body->isKinematicObject())) { pickedBody = body; pickedBody->setActivationState(DISABLE_DEACTIVATION); btVector3 pickPos = rayCallback.m_hitPointWorld; printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ()); btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos; if (use6Dof) { btTransform tr; tr.setIdentity(); tr.setOrigin(localPivot); btGeneric6DofConstraint* dof6 = new btGeneric6DofConstraint(*body, tr,false); dof6->setLinearLowerLimit(btVector3(0,0,0)); dof6->setLinearUpperLimit(btVector3(0,0,0)); dof6->setAngularLowerLimit(btVector3(0,0,0)); dof6->setAngularUpperLimit(btVector3(0,0,0)); m_dynamicsWorld->addConstraint(dof6); m_pickConstraint = dof6; dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,0); dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,1); dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,2); dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,3); dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,4); dof6->setParam(BT_CONSTRAINT_STOP_CFM,0.8,5); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,0); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,1); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,2); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,3); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,4); dof6->setParam(BT_CONSTRAINT_STOP_ERP,0.1,5); } else { btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body,localPivot); m_dynamicsWorld->addConstraint(p2p); m_pickConstraint = p2p; p2p->m_setting.m_impulseClamp = mousePickClamping; //very weak constraint for picking p2p->m_setting.m_tau = 0.001f; /* p2p->setParam(BT_CONSTRAINT_CFM,0.8,0); p2p->setParam(BT_CONSTRAINT_CFM,0.8,1); p2p->setParam(BT_CONSTRAINT_CFM,0.8,2); p2p->setParam(BT_CONSTRAINT_ERP,0.1,0); p2p->setParam(BT_CONSTRAINT_ERP,0.1,1); p2p->setParam(BT_CONSTRAINT_ERP,0.1,2); */ } use6Dof = !use6Dof; //save mouse position for dragging gOldPickingPos = rayTo; gHitPos = pickPos; gOldPickingDist = (pickPos-rayFrom).length(); } } } } } else { removePickingConstraint(); } break; } default: { } } } void DemoApplication::removePickingConstraint() { if (m_pickConstraint && m_dynamicsWorld) { m_dynamicsWorld->removeConstraint(m_pickConstraint); delete m_pickConstraint; //printf("removed constraint %i",gPickingConstraintId); m_pickConstraint = 0; pickedBody->forceActivationState(ACTIVE_TAG); pickedBody->setDeactivationTime( 0.f ); pickedBody = 0; } } void DemoApplication::mouseMotionFunc(int x,int y) { if (m_pickConstraint) { //move the constraint pivot if (m_pickConstraint->getConstraintType() == D6_CONSTRAINT_TYPE) { btGeneric6DofConstraint* pickCon = static_cast<btGeneric6DofConstraint*>(m_pickConstraint); if (pickCon) { //keep it at the same picking distance btVector3 newRayTo = getRayTo(x,y); btVector3 rayFrom; btVector3 oldPivotInB = pickCon->getFrameOffsetA().getOrigin(); btVector3 newPivotB; if (m_ortho) { newPivotB = oldPivotInB; newPivotB.setX(newRayTo.getX()); newPivotB.setY(newRayTo.getY()); } else { rayFrom = m_cameraPosition; btVector3 dir = newRayTo-rayFrom; dir.normalize(); dir *= gOldPickingDist; newPivotB = rayFrom + dir; } pickCon->getFrameOffsetA().setOrigin(newPivotB); } } else { btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_pickConstraint); if (pickCon) { //keep it at the same picking distance btVector3 newRayTo = getRayTo(x,y); btVector3 rayFrom; btVector3 oldPivotInB = pickCon->getPivotInB(); btVector3 newPivotB; if (m_ortho) { newPivotB = oldPivotInB; newPivotB.setX(newRayTo.getX()); newPivotB.setY(newRayTo.getY()); } else { rayFrom = m_cameraPosition; btVector3 dir = newRayTo-rayFrom; dir.normalize(); dir *= gOldPickingDist; newPivotB = rayFrom + dir; } pickCon->setPivotB(newPivotB); } } } float dx, dy; dx = btScalar(x) - m_mouseOldX; dy = btScalar(y) - m_mouseOldY; ///only if ALT key is pressed (Maya style) if (m_modifierKeys& BT_ACTIVE_ALT) { if(m_mouseButtons & 2) { btVector3 hor = getRayTo(0,0)-getRayTo(1,0); btVector3 vert = getRayTo(0,0)-getRayTo(0,1); btScalar multiplierX = btScalar(0.001); btScalar multiplierY = btScalar(0.001); if (m_ortho) { multiplierX = 1; multiplierY = 1; } m_cameraTargetPosition += hor* dx * multiplierX; m_cameraTargetPosition += vert* dy * multiplierY; } if(m_mouseButtons & (2 << 2) && m_mouseButtons & 1) { } else if(m_mouseButtons & 1) { m_azi += dx * btScalar(0.2); m_azi = fmodf(m_azi, btScalar(360.f)); m_ele += dy * btScalar(0.2); m_ele = fmodf(m_ele, btScalar(180.f)); } else if(m_mouseButtons & 4) { m_cameraDistance -= dy * btScalar(0.02f); if (m_cameraDistance<btScalar(0.1)) m_cameraDistance = btScalar(0.1); } } m_mouseOldX = x; m_mouseOldY = y; updateCamera(); } btRigidBody* DemoApplication::localCreateRigidBody(float mass, const btTransform& startTransform,btCollisionShape* shape) { btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE)); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) shape->calculateLocalInertia(mass,localInertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects #define USE_MOTIONSTATE 1 #ifdef USE_MOTIONSTATE btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia); btRigidBody* body = new btRigidBody(cInfo); body->setContactProcessingThreshold(m_defaultContactProcessingThreshold); #else btRigidBody* body = new btRigidBody(mass,0,shape,localInertia); body->setWorldTransform(startTransform); #endif// m_dynamicsWorld->addRigidBody(body); return body; } //See http://www.lighthouse3d.com/opengl/glut/index.php?bmpfontortho void DemoApplication::setOrthographicProjection() { // switch to projection mode glMatrixMode(GL_PROJECTION); // save previous matrix which contains the //settings for the perspective projection glPushMatrix(); // reset matrix glLoadIdentity(); // set a 2D orthographic projection gluOrtho2D(0, m_glutScreenWidth, 0, m_glutScreenHeight); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // invert the y axis, down is positive glScalef(1, -1, 1); // mover the origin from the bottom left corner // to the upper left corner glTranslatef(btScalar(0), btScalar(-m_glutScreenHeight), btScalar(0)); } void DemoApplication::resetPerspectiveProjection() { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); updateCamera(); } extern CProfileIterator * m_profileIterator; void DemoApplication::displayProfileString(int xOffset,int yStart,char* message) { glRasterPos3f(btScalar(xOffset),btScalar(yStart),btScalar(0)); GLDebugDrawString(xOffset,yStart,message); } void DemoApplication::showProfileInfo(int& xOffset,int& yStart, int yIncr) { #ifndef BT_NO_PROFILE static double time_since_reset = 0.f; if (!m_idle) { time_since_reset = CProfileManager::Get_Time_Since_Reset(); } { //recompute profiling data, and store profile strings char blockTime[128]; double totalTime = 0; int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset(); m_profileIterator->First(); double parent_time = m_profileIterator->Is_Root() ? time_since_reset : m_profileIterator->Get_Current_Parent_Total_Time(); { sprintf(blockTime,"--- Profiling: %s (total running time: %.3f ms) ---", m_profileIterator->Get_Current_Parent_Name(), parent_time ); displayProfileString(xOffset,yStart,blockTime); yStart += yIncr; sprintf(blockTime,"press (1,2...) to display child timings, or 0 for parent" ); displayProfileString(xOffset,yStart,blockTime); yStart += yIncr; } double accumulated_time = 0.f; for (int i = 0; !m_profileIterator->Is_Done(); m_profileIterator->Next()) { double current_total_time = m_profileIterator->Get_Current_Total_Time(); accumulated_time += current_total_time; double fraction = parent_time > SIMD_EPSILON ? (current_total_time / parent_time) * 100 : 0.f; sprintf(blockTime,"%d -- %s (%.2f %%) :: %.3f ms / frame (%d calls)", ++i, m_profileIterator->Get_Current_Name(), fraction, (current_total_time / (double)frames_since_reset),m_profileIterator->Get_Current_Total_Calls()); displayProfileString(xOffset,yStart,blockTime); yStart += yIncr; totalTime += current_total_time; } sprintf(blockTime,"%s (%.3f %%) :: %.3f ms", "Unaccounted", // (min(0, time_since_reset - totalTime) / time_since_reset) * 100); parent_time > SIMD_EPSILON ? ((parent_time - accumulated_time) / parent_time) * 100 : 0.f, parent_time - accumulated_time); displayProfileString(xOffset,yStart,blockTime); yStart += yIncr; sprintf(blockTime,"-------------------------------------------------"); displayProfileString(xOffset,yStart,blockTime); yStart += yIncr; } #endif//BT_NO_PROFILE } // void DemoApplication::renderscene(int pass) { btScalar m[16]; btMatrix3x3 rot;rot.setIdentity(); const int numObjects=m_dynamicsWorld->getNumCollisionObjects(); btVector3 wireColor(1,0,0); for(int i=0;i<numObjects;i++) { btCollisionObject* colObj=m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body=btRigidBody::upcast(colObj); if(body&&body->getMotionState()) { btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState(); myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(m); rot=myMotionState->m_graphicsWorldTrans.getBasis(); } else { colObj->getWorldTransform().getOpenGLMatrix(m); rot=colObj->getWorldTransform().getBasis(); } btVector3 wireColor(1.f,1.0f,0.5f); //wants deactivation if(i&1) wireColor=btVector3(0.f,0.0f,1.f); ///color differently for active, sleeping, wantsdeactivation states if (colObj->getActivationState() == 1) //active { if (i & 1) { wireColor += btVector3 (1.f,0.f,0.f); } else { wireColor += btVector3 (.5f,0.f,0.f); } } if(colObj->getActivationState()==2) //ISLAND_SLEEPING { if(i&1) { wireColor += btVector3 (0.f,1.f, 0.f); } else { wireColor += btVector3 (0.f,0.5f,0.f); } } btVector3 aabbMin,aabbMax; m_dynamicsWorld->getBroadphase()->getBroadphaseAabb(aabbMin,aabbMax); aabbMin-=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT); aabbMax+=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT); // printf("aabbMin=(%f,%f,%f)\n",aabbMin.getX(),aabbMin.getY(),aabbMin.getZ()); // printf("aabbMax=(%f,%f,%f)\n",aabbMax.getX(),aabbMax.getY(),aabbMax.getZ()); // m_dynamicsWorld->getDebugDrawer()->drawAabb(aabbMin,aabbMax,btVector3(1,1,1)); if (!(getDebugMode()& btIDebugDraw::DBG_DrawWireframe)) { switch(pass) { case 0: m_shapeDrawer->drawOpenGL(m,colObj->getCollisionShape(),wireColor,getDebugMode(),aabbMin,aabbMax);break; case 1: m_shapeDrawer->drawShadow(m,m_sundirection*rot,colObj->getCollisionShape(),aabbMin,aabbMax);break; case 2: m_shapeDrawer->drawOpenGL(m,colObj->getCollisionShape(),wireColor*btScalar(0.3),0,aabbMin,aabbMax);break; } } } } // void DemoApplication::renderme() { myinit(); updateCamera(); if (m_dynamicsWorld) { if(m_enableshadows) { glClear(GL_STENCIL_BUFFER_BIT); glEnable(GL_CULL_FACE); renderscene(0); glDisable(GL_LIGHTING); glDepthMask(GL_FALSE); glDepthFunc(GL_LEQUAL); glEnable(GL_STENCIL_TEST); glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE); glStencilFunc(GL_ALWAYS,1,0xFFFFFFFFL); glFrontFace(GL_CCW); glStencilOp(GL_KEEP,GL_KEEP,GL_INCR); renderscene(1); glFrontFace(GL_CW); glStencilOp(GL_KEEP,GL_KEEP,GL_DECR); renderscene(1); glFrontFace(GL_CCW); glPolygonMode(GL_FRONT,GL_FILL); glPolygonMode(GL_BACK,GL_FILL); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_LIGHTING); glDepthMask(GL_TRUE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); glDepthFunc(GL_LEQUAL); glStencilFunc( GL_NOTEQUAL, 0, 0xFFFFFFFFL ); glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP ); glDisable(GL_LIGHTING); renderscene(2); glEnable(GL_LIGHTING); glDepthFunc(GL_LESS); glDisable(GL_STENCIL_TEST); glDisable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); renderscene(0); } int xOffset = 10; int yStart = 20; int yIncr = 20; glDisable(GL_LIGHTING); glColor3f(0, 0, 0); if ((m_debugMode & btIDebugDraw::DBG_NoHelpText)==0) { setOrthographicProjection(); showProfileInfo(xOffset,yStart,yIncr); #ifdef USE_QUICKPROF if ( getDebugMode() & btIDebugDraw::DBG_ProfileTimings) { static int counter = 0; counter++; std::map<std::string, hidden::ProfileBlock*>::iterator iter; for (iter = btProfiler::mProfileBlocks.begin(); iter != btProfiler::mProfileBlocks.end(); ++iter) { char blockTime[128]; sprintf(blockTime, "%s: %lf",&((*iter).first[0]),btProfiler::getBlockTime((*iter).first, btProfiler::BLOCK_CYCLE_SECONDS));//BLOCK_TOTAL_PERCENT)); glRasterPos3f(xOffset,yStart,0); GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),blockTime); yStart += yIncr; } } #endif //USE_QUICKPROF resetPerspectiveProjection(); } glDisable(GL_LIGHTING); } updateCamera(); } #include "BulletCollision/BroadphaseCollision/btAxisSweep3.h" void DemoApplication::clientResetScene() { removePickingConstraint(); #ifdef SHOW_NUM_DEEP_PENETRATIONS gNumDeepPenetrationChecks = 0; gNumGjkChecks = 0; #endif //SHOW_NUM_DEEP_PENETRATIONS gNumClampedCcdMotions = 0; int numObjects = 0; int i; if (m_dynamicsWorld) { int numConstraints = m_dynamicsWorld->getNumConstraints(); for (i=0;i<numConstraints;i++) { m_dynamicsWorld->getConstraint(0)->setEnabled(true); } numObjects = m_dynamicsWorld->getNumCollisionObjects(); ///create a copy of the array, not a reference! btCollisionObjectArray copyArray = m_dynamicsWorld->getCollisionObjectArray(); for (i=0;i<numObjects;i++) { btCollisionObject* colObj = copyArray[i]; btRigidBody* body = btRigidBody::upcast(colObj); if (body) { if (body->getMotionState()) { btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState(); myMotionState->m_graphicsWorldTrans = myMotionState->m_startWorldTrans; body->setCenterOfMassTransform( myMotionState->m_graphicsWorldTrans ); colObj->setInterpolationWorldTransform( myMotionState->m_startWorldTrans ); colObj->forceActivationState(ACTIVE_TAG); colObj->activate(); colObj->setDeactivationTime(0); //colObj->setActivationState(WANTS_DEACTIVATION); } //removed cached contact points (this is not necessary if all objects have been removed from the dynamics world) if (m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()) m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(colObj->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher()); btRigidBody* body = btRigidBody::upcast(colObj); if (body && !body->isStaticObject()) { btRigidBody::upcast(colObj)->setLinearVelocity(btVector3(0,0,0)); btRigidBody::upcast(colObj)->setAngularVelocity(btVector3(0,0,0)); } } } ///reset some internal cached data in the broadphase m_dynamicsWorld->getBroadphase()->resetPool(getDynamicsWorld()->getDispatcher()); m_dynamicsWorld->getConstraintSolver()->reset(); } }
[ "yormanh@f2da8aa9-0175-0678-5dcd-d323193514b7" ]
[ [ [ 1, 1403 ] ] ]
e1bdbb1a911a96daa3309453fcbdaa87b1fdb06c
20cf43a2e1854d71696a6264dea4ea8cbfdb16f2
/WinNT/comm_nt_server/Utilities.cpp
8477d4b38fa54ae3e58d9f66911a8388fcacf90a
[]
no_license
thebruno/comm-nt
fb0ece0a8d36715a8f0199ba3ce9f37859170ee3
6ba36941b123c272efe8d81b55555d561d8842f4
refs/heads/master
2016-09-07T19:00:59.817929
2010-01-14T20:38:58
2010-01-14T20:38:58
32,205,785
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
#include "stdafx.h" #include "Utilities.h" std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); }
[ "konrad.balys@08f01046-b83b-11de-9b33-83dc4fd2bb11" ]
[ [ [ 1, 16 ] ] ]
fe5658f1dfa5fc8dbed7121a33fa0bde3e2661ed
5bd189ea897b10ece778fbf9c7a0891bf76ef371
/BasicEngine/BasicEngine/Character/Behaviour/patrol.cpp
33c87114f961cdf639efcc75f3c8ff07bf0c81b6
[]
no_license
boriel/masterullgrupo
c323bdf91f5e1e62c4c44a739daaedf095029710
81b3d81e831eb4d55ede181f875f57c715aa18e3
refs/heads/master
2021-01-02T08:19:54.413488
2011-12-14T22:42:23
2011-12-14T22:42:23
32,330,054
0
0
null
null
null
null
ISO-8859-3
C++
false
false
2,115
cpp
#include <stdlib.h> #include <cassert> #include "../../Lua/LuaManager.h" #include "BehaviourManager.h" #include "../CharacterManager.h" #include "../../Game/Game.h" #include "patrol.h" void cPatrol::Init(cCharacter *lpCharacter) { mpBehaviour = (cChaserWithOrientation *)cBehaviourManager::Get().CreateBehaviour(eCHASER_WITH_ORIENTATION); mpCharacter = lpCharacter; //mpCharacter->SetActiveBehaviour(mpBehaviour); mTargetWayPoint = mpCharacter->GetPosition(); mpBehaviour->Init(lpCharacter); mpBehaviour->SetTarget(mTargetWayPoint); miEnemyId = 0; // El 0 no existe como Id mfAwareRadius = 0; } void cPatrol::Deinit() { mpBehaviour->Deinit(); mpCharacter = NULL; } void cPatrol::Update(float lfTimestep) { cCharacter *lpEnemyCharacter = cCharacterManager::Get().GetCharacter(miEnemyId); float lfDistance; if (lpEnemyCharacter != NULL) { lfDistance = mpCharacter->GetPosition().DistanceTo(lpEnemyCharacter->GetPosition()); if (mfAwareRadius > lfDistance) // Está dentro del radio de acción? Pues lo perseguimos! SetTargetWayPoint(cCharacterManager::Get().GetCharacter(miEnemyId)->GetPosition()); else // Si no, seguimos con el circuito, preguntando a LUA el punto actual cLuaManager::Get().CallLua<int, int>("CurrentEndPoint", mpCharacter->GetId()); } if (!mpBehaviour->EndPointReached()) { mpBehaviour->Update(lfTimestep); } else { // Comprobamos si hemos alcanzado al jugador if (lpEnemyCharacter != NULL && mpCharacter->GetPosition() == lpEnemyCharacter->GetPosition()) { cGame::Get().SetFinished(true); return; } // Llamara función LUA que obtiene el nuevo punto cLuaManager::Get().CallLua<int, int>("NextEndPoint", mpCharacter->GetId()); } } void cPatrol::SetTargetWayPoint(const cVec3 &lTargetWayPoint) { mTargetWayPoint = lTargetWayPoint; mpBehaviour->SetTarget(mTargetWayPoint); } void cPatrol::SetAwareRadius(float lfAwareRadius) { if (lfAwareRadius >= 0) mfAwareRadius = lfAwareRadius; } void cPatrol::SetEnemyId(int liEnemyId) { miEnemyId = liEnemyId; }
[ "[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7" ]
[ [ [ 1, 75 ] ] ]
d8eab745b58fcf60e1d2a8fa42d02298900c7d2f
71b601e499aa3f2c18797cca5ec16ea312f5f61d
/BCB5_WinInetHTTP_2/conexiones.cpp
e49c7463aeda4a1f7ff2cdf0019595d576eec931
[]
no_license
jmnavarro/BCB_LosRinconesDelAPIWinInet
e9186b88bfe4266443a3fcf290cd10b214b0bd5c
b6b58658866370274ea0cbfb4facbcf03f682dec
refs/heads/master
2016-08-07T20:41:23.277852
2011-07-01T08:43:59
2011-07-01T08:43:59
1,982,567
0
0
null
null
null
null
ISO-8859-10
C++
false
false
2,164
cpp
//--------------------------------------------------------------------------- #pragma hdrstop #include "Conexiones.h" #include <assert.h> //--------------------------------------------------------------------------- TConexiones::TConexiones() { m_hInternet = NULL; } //--------------------------------------------------------------------------- TConexiones::~TConexiones() { this->DisconnectAll(); } //--------------------------------------------------------------------------- void TConexiones::SetInternet(const HINTERNET hInternet) { if ( hInternet != m_hInternet ) m_hInternet = hInternet; } //--------------------------------------------------------------------------- HINTERNET TConexiones::Connect(AnsiString &host) { // // primero hay que buscar // CONEXION conn; const unsigned int size = m_pool.size(); conn.handle = NULL; for (unsigned int i=0; i < size; i++) if ( m_pool[i].host == host ) { conn.handle = m_pool[i].handle; break; } // // Si no se ha encontrado, entonces se conecta y lo aņade al vector // if ( !conn.handle ) { conn.host = host.LowerCase(); conn.handle = InternetConnect( m_hInternet, // descriptor dado por InternetOpen host.c_str(), // servidor al que conectarse INTERNET_DEFAULT_HTTP_PORT, // puerto (80) "", "", // usuario y clave INTERNET_SERVICE_HTTP, // protocolo (http) 0, 0); // opciones y contexto m_pool.push_back(conn); assert(m_pool.size() == size + 1); } return (conn.handle); } //--------------------------------------------------------------------------- void TConexiones::DisconnectAll() { LPCONEXION conn; while ( !m_pool.empty() ) { conn = &m_pool.back(); InternetCloseHandle(conn->handle); m_pool.pop_back(); } }
[ [ [ 1, 82 ] ] ]
4216c71c6f65602c2ad714877a125254c40b46b7
c0bd82eb640d8594f2d2b76262566288676b8395
/src/shared/AsyncNet/AsyncWorkerThread.h
7b7b3e0fefc948151b46354e775582bf048b335b
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
6,002
h
/************************************************************************/ /* Copyright (C) 2006 WoWD */ /************************************************************************/ #ifndef __ASYNCWORKERTHREAD_H #define __ASYNCWORKERTHREAD_H #include "Common.h" #include "Timer.h" #include "../CrashHandler.h" #include "../game/WowdThreads.h" #include "../game/ThreadMgr.h" #include "AsyncDefines.h" #include "AsyncSocketHolder.h" #include <map> template <class TypeSocket, class ThreadingPolicy> class AsyncWorkerThread : public WowdThread { public: AsyncWorkerThread(HANDLE cp, AsyncSocketHolderBase *sh); ~AsyncWorkerThread() { } virtual void run(); void SafeRunner(); private: void HandleReadRequest(TypeSocket *s, int len); void HandleReadCompleted(TypeSocket *s, int len); void HandleWriteRequest(TypeSocket *s, int len); void HandleWriteCompleted(TypeSocket *s, int len); void HandleAccept(TypeSocket *s, int len); void HandleShutdownRequest(TypeSocket *s, int len); struct IOCall { std::string OpName; void (AsyncWorkerThread::*WorkerHandler)(TypeSocket *s, int len); }; IOCall m_handlers[6]; HANDLE m_completionPort; AsyncSocketHolder<TypeSocket, ThreadingPolicy> *m_socketHolder; }; template<class TypeSocket, class ThreadingPolicy> class DeadSocketCollector : public Singleton<DeadSocketCollector<TypeSocket, ThreadingPolicy> > { std::map<TypeSocket*, uint32> deletionQueue; ThreadingPolicy queueLock; bool shutdown; public: DeadSocketCollector() : shutdown(false) {} void QueueSocketDeletion(TypeSocket * Socket) { queueLock.Acquire(); deletionQueue[Socket] = time(NULL) + 15; queueLock.Release(); } void Update() { uint32 t = time(NULL); queueLock.Acquire(); map<TypeSocket*, uint32>::iterator itr = deletionQueue.begin(); map<TypeSocket*, uint32>::iterator it2; for(; itr != deletionQueue.end();) { it2 = itr; ++itr; if(it2->second <= t || shutdown) { it2->first->Delete(); deletionQueue.erase(it2); } } queueLock.Release(); } void Shutdown() { shutdown = true; while(deletionQueue.size()) Update(); } }; #define sDeadSocketCollector DeadSocketCollector<BaseSocket, Mutex>::getSingleton() template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleReadRequest(TypeSocket *s, int len) { if(s->_deleted == 0) s->UpdateRead(); } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleWriteRequest(TypeSocket *s, int len) { if(s->_deleted == 0) s->UpdateWrite(); } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleReadCompleted(TypeSocket *s, int len) { if(s->_deleted == 0) { if (len) { s->UseReadBuffer(len); s->OnReceive(len); s->PostCompletion(IOReadRequest); } else { s->Disconnect(); s->PostCompletion(IOShutdownRequest); } } } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleWriteCompleted(TypeSocket *s, int len) { if(s->_deleted == 0) { if (len) s->UseSendBuffer(len); if (s->HasSend() && s->IsConnected()) s->PostCompletion(IOWriteRequest); else s->DecWriteLock(); } } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleAccept(TypeSocket *s, int len) { m_socketHolder->AddSocket(s); s->OnConnect(); s->UpdateRead(); } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::HandleShutdownRequest(TypeSocket *s, int len) { m_socketHolder->DeleteSocket(s); s->PostDeletionCompletion(); } template <class TypeSocket, class ThreadingPolicy> AsyncWorkerThread<TypeSocket, ThreadingPolicy>::AsyncWorkerThread(HANDLE cp, AsyncSocketHolderBase *sh) { m_completionPort = cp; m_socketHolder = static_cast< AsyncSocketHolder<TypeSocket, ThreadingPolicy> *>(sh); m_handlers[0].WorkerHandler = &AsyncWorkerThread::HandleReadRequest; m_handlers[1].WorkerHandler = &AsyncWorkerThread::HandleReadCompleted; m_handlers[2].WorkerHandler = &AsyncWorkerThread::HandleWriteRequest; m_handlers[3].WorkerHandler = &AsyncWorkerThread::HandleWriteCompleted; m_handlers[4].WorkerHandler = &AsyncWorkerThread::HandleAccept; m_handlers[5].WorkerHandler = &AsyncWorkerThread::HandleShutdownRequest; } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::run() { SetThreadName("Network Worker Thread"); WOWD_THREAD_TRY_EXECUTION2 SafeRunner(); WOWD_THREAD_HANDLE_CRASH2 } template <class TypeSocket, class ThreadingPolicy> void AsyncWorkerThread<TypeSocket, ThreadingPolicy>::SafeRunner() { TypeSocket *ts; uint32 len; OverLapped *olclass; LPOVERLAPPED ol; IOCall * ioc; ThreadState = WOWD_THREADSTATE_BUSY; while(ThreadState != WOWD_THREADSTATE_TERMINATE) { if(!GetQueuedCompletionStatus(m_completionPort, &len , (LPDWORD) &ts, &ol, 5000)) continue; olclass = CONTAINING_RECORD(ol, OverLapped, m_ol); ioc = &m_handlers[olclass->m_io]; (this->*ioc->WorkerHandler)(ts, len); delete olclass; } } #endif
[ [ [ 1, 211 ] ] ]
48a32f3a7d9f0e144355476b577705a36106178c
a962a31939f7564ba161ee650e050898c88a5df1
/ODB/Reader/main.cpp
d5d37fd09d2adcbcf0f3679adc4ce7779c807a10
[]
no_license
MatiasNAmendola/project-odb
83cb4503197f1814546953ad395f709e6b130de5
9235e138c0af089b2a61f341906429f48cbc04d5
refs/heads/master
2021-01-18T13:20:13.964102
2011-10-16T01:46:01
2011-10-16T01:46:01
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
653
cpp
#include <iostream> #include <fstream> #include <iostream> #include <string> using std::fstream; using std::ofstream; using std::ifstream; using std::ios; using std::string; using namespace std; int main() { string line; ifstream arq; arq.open("C:/Users/vinicius/Documents/Visual Studio 2010/Projects/Laskera_Object_Database/project-odb/trunk laskeyra-project-odb/ODB/ODB/bin/Debug/test.txt",ios::in); if(arq.is_open()) { while(!arq.eof()) { getline(arq,line); cout << "\n" << line; } } else cout << "não abriu"; return 0; }
[ "notebord@notebord-PC.(none)" ]
[ [ [ 1, 33 ] ] ]
e6576b8674db5403e50c8d94d8983180db601ee0
4ecb7e18f351ee920a6847c7ebd9010b6a5d34ce
/HD/trunk/HuntingDragon/gametutor/source/CStateManagement.cpp
f17454e28f8939719eb123d6a2c60db1b2de1baf
[]
no_license
dogtwelve/bkiter08-gameloft-internship-2011
505141ea314c234d99652600db5165a22cf041c3
0efc9f009bf12fe4ed36e1abfeb34f346a8c4198
refs/heads/master
2021-01-10T12:16:51.540936
2011-10-27T13:30:50
2011-10-27T13:30:50
46,549,117
0
0
null
null
null
null
UTF-8
C++
false
false
632
cpp
#include "CStateManagement.h" namespace GameTutor { void CStateManagement::Update(bool isPause) { // check if need switch state if (m_pCurrentState != m_pNextState) { if (m_pCurrentState) { m_pCurrentState->Exit(); delete m_pCurrentState; } if (m_pNextState) { m_pNextState->Init(); } m_pCurrentState = m_pNextState; } //update state if (m_pCurrentState) { if (!isPause) { m_pCurrentState->Update(); } m_pCurrentState->Render(); } } void CStateManagement::SwitchState(CState* nextState) { m_pNextState = nextState; } }
[ [ [ 1, 37 ] ] ]
01baa7026c1189aaea530cbb561686847d46ee98
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/Scene/Object.h
a8e176f5a0021a336d3210420025d8a3cc284803
[]
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
907
h
#pragma once #include "Node.h" #include "ObjectFactory.h" #include <Depends/Entity/ComponentContainer.h> #include <Depends/Entity/ComponentFactory.h> #include <Engine/Events/IEvent.h> namespace Engine { namespace Scene { class Object : public Entity::ComponentContainer, public Node { protected: friend class ObjectFactory; public: virtual ~Object(); virtual CL_String getNodeType() { return "Object"; } virtual int kill(); virtual int update(double dt); virtual int interpolate(double dt); virtual void executeCommand(const CL_String &command, Engine::Player::IPlayer *player); virtual void executeEvent(const Engine::Events::IEvent &event, Engine::Player::IPlayer *player); protected: Object(unsigned int id, const CL_Vec4f &colorId, const CL_String &type, const CL_String &name, Core::CoreManager *coreMgr, Entity::ComponentFactory *factory); }; } }
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 36 ] ] ]
01b54ab1e2f8ab560ce35fad5bdc61f1ec6e0fa8
1e01b697191a910a872e95ddfce27a91cebc57dd
/BNFScanWindow.cpp
40385eb48ea8186eec6ee273c54096515831475d
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
5,257
cpp
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2003 CÚdric Lemaire This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifdef WIN32 #pragma warning (disable : 4786) #endif #include "UtlException.h" #include "ScpStream.h" #include "CppCompilerEnvironment.h" #include "CGRuntime.h" #include "DtaScriptVariable.h" #include "ExprScriptVariable.h" #include "DtaBNFScript.h" #include "BNFClause.h" #include "DtaVisitor.h" #include "BNFScanWindow.h" namespace CodeWorker { BNFScanWindow::BNFScanWindow(DtaBNFScript* pBNFScript, GrfBlock* pParent, bool bContinue) : _pBNFScript(pBNFScript), GrfBlock(pParent), _bContinue(bContinue), _pWindowSequence(NULL) {} BNFScanWindow::~BNFScanWindow() { delete _pWindowSequence; } void BNFScanWindow::accept(DtaVisitor& visitor, DtaVisitorEnvironment& env) { visitor.visitBNFScanWindow(*this, env); } bool BNFScanWindow::isABNFCommand() const { return true; } SEQUENCE_INTERRUPTION_LIST BNFScanWindow::executeInternal(DtaScriptVariable& visibility) { int iLocation = CGRuntime::getInputLocation(); int iImplicitCopyPosition = _pBNFScript->skipEmptyChars(visibility); SEQUENCE_INTERRUPTION_LIST result = _pWindowSequence->execute(visibility); if (result != CONTINUE_INTERRUPTION) { int iFinalLocation = CGRuntime::getInputLocation(); CGRuntime::setInputLocation(iLocation); if (iImplicitCopyPosition >= 0) CGRuntime::resizeOutputStream(iImplicitCopyPosition); if (iFinalLocation < iLocation) result = BREAK_INTERRUPTION; if (result == NO_INTERRUPTION) { ScpStream::SizeAttributes sizeAttrs(CGRuntime::_pInputStream->resize(iFinalLocation)); result = GrfBlock::executeInternal(visibility); CGRuntime::_pInputStream->restoreSize(sizeAttrs); if ((result == NO_INTERRUPTION) || (result == CONTINUE_INTERRUPTION)) { CGRuntime::setInputLocation(iFinalLocation); } else { BNF_SYMBOL_HAS_FAILED } } else { if (iFinalLocation < iLocation) throw UtlException("Left member of '" + CGRuntime::composeCLikeString(toString()) + "' shouldn't set the cursor back in the sentence"); if (_bContinue) CGRuntime::throwBNFExecutionError(toString()); } } return result; } void BNFScanWindow::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const { CPP_COMPILER_BNF_SYMBOL_BEGIN; _pWindowSequence->compileCpp(theCompilerEnvironment); CW_BODY_INDENT << "int _compilerClauseFinalLocation" << iCursor << " = CGRuntime::getInputLocation();";CW_BODY_ENDL; CW_BODY_INDENT << "CGRuntime::setInputLocation(" << tcLocation << ");";CW_BODY_ENDL; CW_BODY_INDENT << "if (" << tcImplicitCopy << " >= 0) CGRuntime::resizeOutputStream(" << tcImplicitCopy << ");";CW_BODY_ENDL; CW_BODY_INDENT << "if (_compilerClauseFinalLocation" << iCursor << " < " << tcLocation << ") _compilerClauseSuccess = false;";CW_BODY_ENDL; CW_BODY_INDENT << "if (_compilerClauseSuccess) {";CW_BODY_ENDL; theCompilerEnvironment.incrementIndentation(); CW_BODY_INDENT << "{";CW_BODY_ENDL; theCompilerEnvironment.incrementIndentation(); CW_BODY_INDENT << "CGBNFRuntimeResizeInput _compilerClauseSizeAttrs(_compilerClauseFinalLocation" << iCursor << ");";CW_BODY_ENDL; GrfBlock::compileCppBNFSequence(theCompilerEnvironment); theCompilerEnvironment.decrementIndentation(); CW_BODY_INDENT << "}";CW_BODY_ENDL; CW_BODY_INDENT << "if (_compilerClauseSuccess) {";CW_BODY_ENDL; CW_BODY_INDENT << "\tCGRuntime::setInputLocation(_compilerClauseFinalLocation" << iCursor << ");";CW_BODY_ENDL; CW_BODY_INDENT << "} else {";CW_BODY_ENDL; CPP_COMPILER_BNF_SYMBOL_HAS_FAILED; CW_BODY_INDENT << "}";CW_BODY_ENDL; theCompilerEnvironment.decrementIndentation(); CW_BODY_INDENT << "} else {";CW_BODY_ENDL; CW_BODY_INDENT << "\tif (_compilerClauseFinalLocation" << iCursor << " < " << tcLocation << ") throw UtlException(\"Left member of '" << CGRuntime::composeCLikeString(toString()) << "' shouldn't set the cursor back in the sentence\");";CW_BODY_ENDL; if (_bContinue) { CW_BODY_INDENT << "\tCGRuntime::throwBNFExecutionError("; CW_BODY_STREAM.writeString(toString()); CW_BODY_STREAM << ");"; CW_BODY_ENDL; } CW_BODY_INDENT << "}";CW_BODY_ENDL; } std::string BNFScanWindow::toString() const { std::string sText = "[" + _pWindowSequence->toString() + "] |> [" + getCommands()[0]->toString() + "]"; if (_bContinue) sText = "#continue " + sText; return sText; } }
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 114 ] ] ]
8b3469b5d694b4b927cb1d43f40db7e4170f7f81
f27e317f667ebe5979c9620deea865c2d411bed5
/Towerdefence/Network/include/RPC3.h
65a5a57bbf717935a74b88f12851e8c23a8831a1
[]
no_license
iijobs/argontd
8452450e90ced1e4e27766a3b18a32424fa04366
fa3dac21197deb85336efd3f3239929580b296e7
refs/heads/master
2020-06-05T08:47:27.055010
2009-09-27T16:12:44
2009-09-27T16:12:44
32,657,966
0
0
null
null
null
null
UTF-8
C++
false
false
32,704
h
/// \file /// \brief Automatically serializing and deserializing RPC system. Third generation of RPC. /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. #ifndef __RPC_3_H #define __RPC_3_H // Most of the internals of the boost code to make this work #include "RPC3_Boost.h" class RakPeerInterface; class NetworkIDManager; #include "raknet/PluginInterface2.h" #include "raknet/DS_Map.h" #include "raknet/PacketPriority.h" #include "raknet/RakNetTypes.h" #include "raknet/BitStream.h" #include "raknet/RakString.h" #ifdef _MSC_VER #pragma warning( push ) #endif /// \defgroup RPC_3_GROUP RPC3 /// \brief Remote procedure calls, powered by the 3rd party library Boost /// \details /// \ingroup PLUGINS_GROUP namespace RakNet { /// \ingroup RPC_3_GROUP #define RPC3_REGISTER_FUNCTION(RPC3Instance, _FUNCTION_PTR_ ) (RPC3Instance)->RegisterFunction((#_FUNCTION_PTR_), (_FUNCTION_PTR_)) /// \brief Error codes returned by a remote system as to why an RPC function call cannot execute /// \details Error code follows packet ID ID_RPC_REMOTE_ERROR, that is packet->data[1]<BR> /// Name of the function will be appended starting at packet->data[2] /// \ingroup RPC_3_GROUP enum RPCErrorCodes { /// RPC3::SetNetworkIDManager() was not called, and it must be called to call a C++ object member RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE, /// Cannot execute C++ object member call because the object specified by SetRecipientObject() does not exist on this system RPC_ERROR_OBJECT_DOES_NOT_EXIST, /// Internal error, index optimization for function lookup does not exist RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE, /// Named function was not registered with RegisterFunction(). Check your spelling. RPC_ERROR_FUNCTION_NOT_REGISTERED, /// Named function was registered, but later unregistered with UnregisterFunction() and can no longer be called. RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED, /// SetRecipientObject() was not called before Call(), but the registered pointer is a class member /// If you intended to call a class member function, call SetRecipientObject() with a valid object first. RPC_ERROR_CALLING_CPP_AS_C, /// SetRecipientObject() was called before Call(), but RegisterFunction() was called with isObjectMember=false /// If you intended to call a C function, call SetRecipientObject(UNASSIGNED_NETWORK_ID) first. RPC_ERROR_CALLING_C_AS_CPP, }; /// \brief The RPC3 plugin allows you to call remote functions as if they were local functions, using the standard function call syntax /// \details No serialization or deserialization is needed.<BR> /// Features:<BR> /// <LI>Pointers to classes that derive from NetworkID are automatically looked up using NetworkIDManager /// <LI>Types are written to BitStream, meaning built-in serialization operations are performed, including endian swapping /// <LI>Types can customize autoserialization by providing an implementation of operator << and operator >> to and from BitStream /// \ingroup RPC_3_GROUP class RPC3 : public PluginInterface2 { public: // Constructor RPC3(); // Destructor virtual ~RPC3(); /// Sets the network ID manager to use for object lookup /// Required to call C++ object member functions via SetRecipientObject() /// \param[in] idMan Pointer to the network ID manager to use void SetNetworkIDManager(NetworkIDManager *idMan); /// \param[in] uniqueIdentifier String identifying the function. Recommended that this is the name of the function /// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION /// \return True on success, false on uniqueIdentifier already used template<typename Function> bool RegisterFunction(const char *uniqueIdentifier, Function functionPtr) { if (IsFunctionRegistered(uniqueIdentifier)) return false; _RPC3::FunctionPointer fp; fp= _RPC3::GetBoundPointer(functionPtr); localFunctions.Insert(LocalRPCFunction(uniqueIdentifier,fp)); return true; } /// Unregisters a function pointer to be callable given an identifier for the pointer /// \param[in] uniqueIdentifier String identifying the function. /// \return True on success, false on function was not previously or is not currently registered. bool UnregisterFunction(const char *uniqueIdentifier); /// Returns if a function identifier was previously registered with RegisterFunction(), and not unregistered with UnregisterFunction() /// \param[in] uniqueIdentifier String identifying the function. /// \return True if the function was registered, false otherwise bool IsFunctionRegistered(const char *uniqueIdentifier); /// Send or stop sending a timestamp with all following calls to Call() /// Use GetLastSenderTimestamp() to read the timestamp. /// \param[in] timeStamp Non-zero to pass this timestamp using the ID_TIMESTAMP system. 0 to clear passing a timestamp. void SetTimestamp(RakNetTime timeStamp); /// Set parameters to pass to RakPeer::Send() for all following calls to Call() /// Deafults to HIGH_PRIORITY, RELIABLE_ORDERED, ordering channel 0 /// \param[in] priority See RakPeer::Send() /// \param[in] reliability See RakPeer::Send() /// \param[in] orderingChannel See RakPeer::Send() void SetSendParams(PacketPriority priority, PacketReliability reliability, char orderingChannel); /// Set system to send to for all following calls to Call() /// Defaults to UNASSIGNED_SYSTEM_ADDRESS, broadcast=true /// \param[in] systemAddress See RakPeer::Send() /// \param[in] broadcast See RakPeer::Send() void SetRecipientAddress(SystemAddress systemAddress, bool broadcast); /// Set the NetworkID to pass for all following calls to Call() /// Defaults to UNASSIGNED_NETWORK_ID (none) /// If set, the remote function will be considered a C++ function, e.g. an object member function /// If set to UNASSIGNED_NETWORK_ID (none), the remote function will be considered a C function /// If this is set incorrectly, you will get back either RPC_ERROR_CALLING_C_AS_CPP or RPC_ERROR_CALLING_CPP_AS_C /// \sa NetworkIDManager /// \param[in] networkID Returned from NetworkIDObject::GetNetworkID() void SetRecipientObject(NetworkID networkID); /// If the last received function call has a timestamp included, it is stored and can be retrieved with this function. /// \return 0 if the last call did not have a timestamp, else non-zero RakNetTime GetLastSenderTimestamp(void) const; /// Returns the system address of the last system to send us a received function call /// Equivalent to the old system RPCParameters::sender /// \return Last system to send an RPC call using this system SystemAddress GetLastSenderAddress(void) const; /// Returns the instance of RakPeer this plugin was attached to RakPeerInterface *GetRakPeer(void) const; /// Returns the currently running RPC call identifier, set from RegisterFunction::uniqueIdentifier /// Returns an empty string "" if none /// \return which RPC call is currently running const char *GetCurrentExecution(void) const; /// Calls a remote function, using as send parameters whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject() /// If you call a C++ class member function, don't forget to first call SetRecipientObject(). You can use CallExplicit() instead of Call() to force yourself not to forget. /// /// Parameters passed to Call are processed as follows: /// 1. If the parameter is not a pointer /// 2. - And you overloaded RakNet::BitStream& operator<<(RakNet::BitStream& out, MyClass& in) then that will be used to do the serialization /// 3. - Otherwise, it will use bitStream.Write(myClass); BitStream already defines specializations for NetworkIDObject, SystemAddress, other BitStreams /// 4. If the parameter is a pointer /// 5. - And the pointer can be converted to NetworkIDObject, then it will write bitStream.Write(myClass->GetNetworkID()); To make it also dereference the pointer, use RakNet::_RPC3::Deref(myClass) /// 6. - And the pointer can not be converted to NetworkID, but it is a pointer to RakNet::RPC3, then it is skipped /// 7. Otherwise, the pointer is dereferenced and written as in step 2 and 3. /// /// \note If you need endian swapping (Mac talking to PC for example), you pretty much need to define operator << and operator >> for all classes you want to serialize. Otherwise the member variables will not be endian swapped. /// \note If the call fails on the remote system, you will get back ID_RPC_REMOTE_ERROR. packet->data[1] will contain one of the values of RPCErrorCodes. packet->data[2] and on will contain the name of the function. /// /// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system bool Call(const char *uniqueIdentifier){ RakNet::BitStream bitStream; return SendCall(uniqueIdentifier, 0, &bitStream); } template <class P1> bool Call(const char *uniqueIdentifier, P1 &p1) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); return SendCall(uniqueIdentifier, 1, &bitStream); } template <class P1, class P2> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); return SendCall(uniqueIdentifier, 2, &bitStream); } template <class P1, class P2, class P3> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); return SendCall(uniqueIdentifier, 3, &bitStream); } template <class P1, class P2, class P3, class P4> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); return SendCall(uniqueIdentifier, 4, &bitStream); } template <class P1, class P2, class P3, class P4, class P5> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); return SendCall(uniqueIdentifier, 5, &bitStream); } template <class P1, class P2, class P3, class P4, class P5, class P6> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); _RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6); return SendCall(uniqueIdentifier, 6, &bitStream); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); _RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6); _RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7); return SendCall(uniqueIdentifier, 7, &bitStream); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); _RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6); _RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7); _RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8); return SendCall(uniqueIdentifier, 8, &bitStream); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); _RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6); _RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7); _RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8); _RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9); // bitStream.PrintBits(); return SendCall(uniqueIdentifier, 9, &bitStream); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10> bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10) { RakNet::BitStream bitStream; _RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1); _RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2); _RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3); _RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4); _RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5); _RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6); _RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7); _RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8); _RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9); _RPC3::SerializeCallParameterBranch<P10>::type::apply(bitStream, p10); // bitStream.PrintBits(); return SendCall(uniqueIdentifier, 10, &bitStream); } struct CallExplicitParameters { CallExplicitParameters( NetworkID _networkID=UNASSIGNED_NETWORK_ID, SystemAddress _systemAddress=UNASSIGNED_SYSTEM_ADDRESS, bool _broadcast=true, RakNetTime _timeStamp=0, PacketPriority _priority=HIGH_PRIORITY, PacketReliability _reliability=RELIABLE_ORDERED, char _orderingChannel=0 ) : networkID(_networkID), systemAddress(_systemAddress), broadcast(_broadcast), timeStamp(_timeStamp), priority(_priority), reliability(_reliability), orderingChannel(_orderingChannel) {} NetworkID networkID; SystemAddress systemAddress; bool broadcast; RakNetTime timeStamp; PacketPriority priority; PacketReliability reliability; char orderingChannel; }; /// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject() /// Passed parameter(s), if any, are serialized using operator << with RakNet::BitStream. If you provide an overload it will be used, otherwise the seriailzation is equivalent to memcpy except for native RakNet types (NetworkIDObject, SystemAddress, etc.) /// If the type is a pointer to a type deriving from NetworkIDObject, then only the NetworkID is sent, and the object looked up on the remote system. Otherwise, the pointer is dereferenced and the contents serialized as usual. /// \note The this pointer, for this instance of RPC3, is pushed as the last parameter on the stack. See RPC3Sample.cpp for an example of this /// \note If the call fails on the remote system, you will get back ID_RPC_REMOTE_ERROR. packet->data[1] will contain one of the values of RPCErrorCodes. packet->data[2] and on will contain the name of the function. /// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system /// \param[in] timeStamp See SetTimestamp() /// \param[in] priority See SetSendParams() /// \param[in] reliability See SetSendParams() /// \param[in] orderingChannel See SetSendParams() /// \param[in] systemAddress See SetRecipientAddress() /// \param[in] broadcast See SetRecipientAddress() /// \param[in] networkID See SetRecipientObject() bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters){ SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier); } template <class P1 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1); } template <class P1, class P2 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2); } template <class P1, class P2, class P3 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3); } template <class P1, class P2, class P3, class P4 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4); } template <class P1, class P2, class P3, class P4, class P5 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5); } template <class P1, class P2, class P3, class P4, class P5, class P6 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10 > bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10 ) { SetTimestamp(callExplicitParameters->timeStamp); SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel); SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast); SetRecipientObject(callExplicitParameters->networkID); return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } bool CallC(const char *uniqueIdentifier) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier);} template <class P1> bool CallC(const char *uniqueIdentifier, P1 &p1) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1);} template <class P1, class P2> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2);} template <class P1, class P2, class P3> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3);} template <class P1, class P2, class P3, class P4> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4);} template <class P1, class P2, class P3, class P4, class P5> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5);} template <class P1, class P2, class P3, class P4, class P5, class P6> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6);} template <class P1, class P2, class P3, class P4, class P5, class P6, class P7> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7);} template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8);} template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9);} template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10> bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10);} bool CallCPP(const char *uniqueIdentifier, NetworkID nid) { SetRecipientObject(nid); return Call(uniqueIdentifier); } template <class P1> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1); } template <class P1, class P2> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2); } template <class P1, class P2, class P3> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3); } template <class P1, class P2, class P3, class P4> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4); } template <class P1, class P2, class P3, class P4, class P5> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5); } template <class P1, class P2, class P3, class P4, class P5, class P6> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9); } template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10> bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10); } // ---------------------------- ALL INTERNAL AFTER HERE ---------------------------- /// \internal /// Identifies an RPC function, by string identifier and if it is a C or C++ function typedef RakString RPCIdentifier; /// \internal /// The RPC identifier, and a pointer to the function struct LocalRPCFunction { LocalRPCFunction() {} LocalRPCFunction(RPCIdentifier _identifier, _RPC3::FunctionPointer _functionPointer) {identifier=_identifier; functionPointer=_functionPointer;}; RPCIdentifier identifier; _RPC3::FunctionPointer functionPointer; }; /// \internal /// The RPC identifier, and the index of the function on a remote system struct RemoteRPCFunction { RPCIdentifier identifier; unsigned int functionIndex; }; /// \internal static int RemoteRPCFunctionComp( const RPCIdentifier &key, const RemoteRPCFunction &data ); /// \internal /// Sends the RPC call, with a given serialized function bool SendCall(RakString uniqueIdentifier, char parameterCount, RakNet::BitStream *serializedParameters); protected: // -------------------------------------------------------------------------------------------- // Packet handling functions // -------------------------------------------------------------------------------------------- void OnAttach(void); virtual PluginReceiveResult OnReceive(Packet *packet); virtual void OnRPC3Call(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes); virtual void OnRPCRemoteIndex(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes); virtual void OnClosedConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); virtual void OnShutdown(void); void Clear(void); void SendError(SystemAddress target, unsigned char errorCode, const char *functionName); unsigned GetLocalFunctionIndex(RPCIdentifier identifier); bool GetRemoteFunctionIndex(SystemAddress systemAddress, RPCIdentifier identifier, unsigned int *outerIndex, unsigned int *innerIndex); DataStructures::List<LocalRPCFunction> localFunctions; DataStructures::Map<SystemAddress, DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *> remoteFunctions; RakNetTime outgoingTimestamp; PacketPriority outgoingPriority; PacketReliability outgoingReliability; char outgoingOrderingChannel; SystemAddress outgoingSystemAddress; bool outgoingBroadcast; NetworkID outgoingNetworkID; RakNet::BitStream outgoingExtraData; RakNetTime incomingTimeStamp; SystemAddress incomingSystemAddress; RakNet::BitStream incomingExtraData; NetworkIDManager *networkIdManager; char currentExecution[512]; }; } // End namespace #endif #ifdef _MSC_VER #pragma warning( pop ) #endif
[ "[email protected]@1eb55710-98a1-11de-a05d-3bd73e269465" ]
[ [ [ 1, 561 ] ] ]
35b4f480f31ace71b067bbcf98a38d8333508d67
eed2b7a64bb1652b40f2a1de9d2b0e2f84153e6f
/AbstractGameState.cpp
53aabb1db0ecd69b5cd5788d3e36dbc225f46570
[]
no_license
pandabear41/GameTemplate
8a0ecbab72e984c23ef7ce7493276b833afaf800
23ec865bdee46e8eb006d2f83b48eba1d3bb0ae9
refs/heads/master
2016-09-05T16:07:22.888482
2011-07-13T03:09:26
2011-07-13T03:09:26
2,034,057
0
0
null
null
null
null
UTF-8
C++
false
false
625
cpp
#include "AbstractGameState.h" using namespace std; AbstractGameState::AbstractGameState() { this->done = false; this->reDraw = true; this->state = NULL; } AbstractGameState::~AbstractGameState() { SDL_FreeSurface(this->background); } void AbstractGameState::clockTick() { } void AbstractGameState::draw(SDL_Surface* surface) { } void AbstractGameState::keyPressed(SDLKey key) { } /** * Convert Int to String. */ const string AbstractGameState::intToString(const int number) { stringstream ss; string str; ss << number; ss >> str; return str; }
[ [ [ 1, 35 ] ] ]
4461f9e33920f06265785746eea9ebac56bec820
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/lighting/LightmapGrid.h
49f7bdf33c43f20f103ce520c9be326cbff724ad
[]
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,669
h
/*** * hesperus: LightmapGrid.h * Copyright Stuart Golodetz, 2008. All rights reserved. ***/ #ifndef H_HESP_LIGHTMAPGRID #define H_HESP_LIGHTMAPGRID #include <vector> #include <boost/shared_ptr.hpp> using boost::shared_ptr; #include <source/math/geom/Polygon.h> #include <source/math/geom/Plane.h> #include <source/math/vectors/TexCoords.h> #include <source/math/vectors/Vector2d.h> namespace hesp { //#################### FORWARD DECLARATIONS #################### typedef shared_ptr<class BSPTree> BSPTree_Ptr; struct Light; typedef shared_ptr<class Lightmap> Lightmap_Ptr; class LightmapGrid { //#################### ENUMERATIONS #################### private: enum AxisPlane { YZ_PLANE, XZ_PLANE, XY_PLANE }; //#################### NESTED CLASSES #################### private: struct GridPoint { Vector3d position; // where does the grid point lie in world space? bool withinPolygon; // is it within the polygon being lightmapped? (if not, we can skip some work when constructing a lightmap) GridPoint(const Vector3d& position_) : position(position_), withinPolygon(true) {} }; //#################### PRIVATE VARIABLES #################### private: std::vector<std::vector<GridPoint> > m_grid; Plane m_plane; //#################### CONSTRUCTORS #################### public: template <typename Vert, typename AuxData> LightmapGrid(const Polygon<Vert,AuxData>& poly, std::vector<TexCoords>& vertexLightmapCoords); //#################### PUBLIC METHODS #################### public: Lightmap_Ptr lightmap_from_light(const Light& light, const BSPTree_Ptr& tree) const; int lightmap_height() const; int lightmap_width() const; //#################### PRIVATE METHODS #################### private: static AxisPlane find_best_axis_plane(const Vector3d& n); void make_planar_grid(const std::vector<Vector2d>& projectedVertices, AxisPlane axisPlane, std::vector<TexCoords>& vertexLightmapCoords); static Vector3d planar_to_real(const Vector2d& v, AxisPlane axisPlane); template <typename Vert, typename AuxData> void project_grid_onto_polygon(const Polygon<Vert,AuxData>& poly, AxisPlane axisPlane); static Vector2d project_vertex_onto(const Vector3d& v, AxisPlane axisPlane); template <typename Vert, typename AuxData> static std::vector<Vector2d> project_vertices_onto(const Polygon<Vert,AuxData>& poly, AxisPlane axisPlane); }; //#################### TYPEDEFS #################### typedef shared_ptr<LightmapGrid> LightmapGrid_Ptr; typedef shared_ptr<const LightmapGrid> LightmapGrid_CPtr; } #include "LightmapGrid.tpp" #endif
[ [ [ 1, 86 ] ] ]
d6adde91c474291a41d56372ab9713b6aae29602
b2601dbc552b4ffa9b439dc17e5f18bb75b09379
/src/arm9/source/audio.h
1e3a703310c1715c00aa360be62b06f0a00d39da
[]
no_license
sgraham/twinisles
70e9989e47933c87aa66f43efdd9b03c2b4e9d64
e0086154fcc4f3be130d4c88b9af3a0aab490715
refs/heads/master
2021-01-18T13:53:55.740730
2010-10-13T06:59:12
2010-10-13T06:59:12
34,834,093
0
0
null
null
null
null
UTF-8
C++
false
false
313
h
#ifndef LG_INCLUDED_audio_H #define LG_INCLUDED_audio_H class Audio { static bool mMusic; static bool mSound; public: static void Init(); static bool MusicIsEnabled(); static bool SoundIsEnabled(); static void ToggleMusicEnabled(); static void ToggleSoundEnabled(); }; #endif
[ [ [ 1, 19 ] ] ]
96f10d577b4bdc666ac3b2b6f4efea87000cff45
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
/WinEdition/browser-lcc/jscc/src/v8/v8/src/.svn/text-base/property.h.svn-base
93ba9143d7f96f541001804503f80211428af097
[ "LicenseRef-scancode-public-domain", "Artistic-2.0", "BSD-3-Clause", "Artistic-1.0", "bzip2-1.0.6" ]
permissive
baxtree/OKBuzzer
c46c7f271a26be13adcf874d77a7a6762a8dc6be
a16e2baad145f5c65052cdc7c767e78cdfee1181
refs/heads/master
2021-01-02T22:17:34.168564
2011-06-15T02:29:56
2011-06-15T02:29:56
1,790,181
0
0
null
null
null
null
UTF-8
C++
false
false
11,059
// Copyright 2006-2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_PROPERTY_H_ #define V8_PROPERTY_H_ namespace v8 { namespace internal { // Abstraction for elements in instance-descriptor arrays. // // Each descriptor has a key, property attributes, property type, // property index (in the actual instance-descriptor array) and // optionally a piece of data. // class Descriptor BASE_EMBEDDED { public: static int IndexFromValue(Object* value) { return Smi::cast(value)->value(); } MUST_USE_RESULT MaybeObject* KeyToSymbol() { if (!StringShape(key_).IsSymbol()) { Object* result; { MaybeObject* maybe_result = HEAP->LookupSymbol(key_); if (!maybe_result->ToObject(&result)) return maybe_result; } key_ = String::cast(result); } return key_; } String* GetKey() { return key_; } Object* GetValue() { return value_; } PropertyDetails GetDetails() { return details_; } #ifdef OBJECT_PRINT void Print(FILE* out); #endif void SetEnumerationIndex(int index) { ASSERT(PropertyDetails::IsValidIndex(index)); details_ = PropertyDetails(details_.attributes(), details_.type(), index); } private: String* key_; Object* value_; PropertyDetails details_; protected: Descriptor() : details_(Smi::FromInt(0)) {} void Init(String* key, Object* value, PropertyDetails details) { key_ = key; value_ = value; details_ = details; } Descriptor(String* key, Object* value, PropertyDetails details) : key_(key), value_(value), details_(details) { } Descriptor(String* key, Object* value, PropertyAttributes attributes, PropertyType type, int index = 0) : key_(key), value_(value), details_(attributes, type, index) { } friend class DescriptorArray; }; // A pointer from a map to the new map that is created by adding // a named property. These are key to the speed and functioning of V8. // The two maps should always have the same prototype, since // MapSpace::CreateBackPointers depends on this. class MapTransitionDescriptor: public Descriptor { public: MapTransitionDescriptor(String* key, Map* map, PropertyAttributes attributes) : Descriptor(key, map, attributes, MAP_TRANSITION) { } }; class ExternalArrayTransitionDescriptor: public Descriptor { public: ExternalArrayTransitionDescriptor(String* key, Map* map, ExternalArrayType array_type) : Descriptor(key, map, PropertyDetails(NONE, EXTERNAL_ARRAY_TRANSITION, array_type)) { } }; // Marks a field name in a map so that adding the field is guaranteed // to create a FIELD descriptor in the new map. Used after adding // a constant function the first time, creating a CONSTANT_FUNCTION // descriptor in the new map. This avoids creating multiple maps with // the same CONSTANT_FUNCTION field. class ConstTransitionDescriptor: public Descriptor { public: explicit ConstTransitionDescriptor(String* key, Map* map) : Descriptor(key, map, NONE, CONSTANT_TRANSITION) { } }; class FieldDescriptor: public Descriptor { public: FieldDescriptor(String* key, int field_index, PropertyAttributes attributes, int index = 0) : Descriptor(key, Smi::FromInt(field_index), attributes, FIELD, index) {} }; class ConstantFunctionDescriptor: public Descriptor { public: ConstantFunctionDescriptor(String* key, JSFunction* function, PropertyAttributes attributes, int index = 0) : Descriptor(key, function, attributes, CONSTANT_FUNCTION, index) {} }; class CallbacksDescriptor: public Descriptor { public: CallbacksDescriptor(String* key, Object* proxy, PropertyAttributes attributes, int index = 0) : Descriptor(key, proxy, attributes, CALLBACKS, index) {} }; class LookupResult BASE_EMBEDDED { public: // Where did we find the result; enum { NOT_FOUND, DESCRIPTOR_TYPE, DICTIONARY_TYPE, INTERCEPTOR_TYPE, CONSTANT_TYPE } lookup_type_; LookupResult() : lookup_type_(NOT_FOUND), cacheable_(true), details_(NONE, NORMAL) {} void DescriptorResult(JSObject* holder, PropertyDetails details, int number) { lookup_type_ = DESCRIPTOR_TYPE; holder_ = holder; details_ = details; number_ = number; } void DescriptorResult(JSObject* holder, Smi* details, int number) { lookup_type_ = DESCRIPTOR_TYPE; holder_ = holder; details_ = PropertyDetails(details); number_ = number; } void ConstantResult(JSObject* holder) { lookup_type_ = CONSTANT_TYPE; holder_ = holder; details_ = PropertyDetails(static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE), CALLBACKS); number_ = -1; } void DictionaryResult(JSObject* holder, int entry) { lookup_type_ = DICTIONARY_TYPE; holder_ = holder; details_ = holder->property_dictionary()->DetailsAt(entry); number_ = entry; } void InterceptorResult(JSObject* holder) { lookup_type_ = INTERCEPTOR_TYPE; holder_ = holder; details_ = PropertyDetails(NONE, INTERCEPTOR); } void NotFound() { lookup_type_ = NOT_FOUND; } JSObject* holder() { ASSERT(IsFound()); return holder_; } PropertyType type() { ASSERT(IsFound()); return details_.type(); } PropertyAttributes GetAttributes() { ASSERT(IsFound()); return details_.attributes(); } PropertyDetails GetPropertyDetails() { return details_; } bool IsReadOnly() { return details_.IsReadOnly(); } bool IsDontDelete() { return details_.IsDontDelete(); } bool IsDontEnum() { return details_.IsDontEnum(); } bool IsDeleted() { return details_.IsDeleted(); } bool IsFound() { return lookup_type_ != NOT_FOUND; } // Is the result is a property excluding transitions and the null // descriptor? bool IsProperty() { return IsFound() && (type() < FIRST_PHANTOM_PROPERTY_TYPE); } // Is the result a property or a transition? bool IsPropertyOrTransition() { return IsFound() && (type() != NULL_DESCRIPTOR); } bool IsCacheable() { return cacheable_; } void DisallowCaching() { cacheable_ = false; } Object* GetLazyValue() { switch (type()) { case FIELD: return holder()->FastPropertyAt(GetFieldIndex()); case NORMAL: { Object* value; value = holder()->property_dictionary()->ValueAt(GetDictionaryEntry()); if (holder()->IsGlobalObject()) { value = JSGlobalPropertyCell::cast(value)->value(); } return value; } case CONSTANT_FUNCTION: return GetConstantFunction(); default: return Smi::FromInt(0); } } Map* GetTransitionMap() { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); ASSERT(type() == MAP_TRANSITION || type() == CONSTANT_TRANSITION || type() == EXTERNAL_ARRAY_TRANSITION); return Map::cast(GetValue()); } Map* GetTransitionMapFromMap(Map* map) { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); ASSERT(type() == MAP_TRANSITION); return Map::cast(map->instance_descriptors()->GetValue(number_)); } int GetFieldIndex() { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); ASSERT(type() == FIELD); return Descriptor::IndexFromValue(GetValue()); } int GetLocalFieldIndexFromMap(Map* map) { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); ASSERT(type() == FIELD); return Descriptor::IndexFromValue( map->instance_descriptors()->GetValue(number_)) - map->inobject_properties(); } int GetDictionaryEntry() { ASSERT(lookup_type_ == DICTIONARY_TYPE); return number_; } JSFunction* GetConstantFunction() { ASSERT(type() == CONSTANT_FUNCTION); return JSFunction::cast(GetValue()); } JSFunction* GetConstantFunctionFromMap(Map* map) { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); ASSERT(type() == CONSTANT_FUNCTION); return JSFunction::cast(map->instance_descriptors()->GetValue(number_)); } Object* GetCallbackObject() { if (lookup_type_ == CONSTANT_TYPE) { // For now we only have the __proto__ as constant type. return HEAP->prototype_accessors(); } return GetValue(); } #ifdef OBJECT_PRINT void Print(FILE* out); #endif Object* GetValue() { if (lookup_type_ == DESCRIPTOR_TYPE) { DescriptorArray* descriptors = holder()->map()->instance_descriptors(); return descriptors->GetValue(number_); } // In the dictionary case, the data is held in the value field. ASSERT(lookup_type_ == DICTIONARY_TYPE); return holder()->GetNormalizedProperty(this); } private: JSObject* holder_; int number_; bool cacheable_; PropertyDetails details_; }; } } // namespace v8::internal #endif // V8_PROPERTY_H_
[ [ [ 1, 355 ] ] ]
103d845908f4eb907fb57d14d06db05f99e539bf
8cb7e0602c79f0c946b791e5405defb9fc68faf1
/RapMath.cpp
5c900f4ea1746318da26647f52ea74a9b1c328ac
[]
no_license
dtbinh/rap3d
97db38c9d025e12d2b754ee5e5146b39c85a43ed
dfcb94d38bf3be3bb18b366d878be6ab43dd219f
refs/heads/master
2021-01-18T07:44:47.990016
2009-07-24T14:54:13
2009-07-24T14:54:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
#include "RapMath.h" #include <cstdlib> float random(float start, float end) { return start+(end-start)*rand()/(RAND_MAX + 1.0f); }
[ "[email protected]@9eece350-6645-11de-b007-7558a4ed3f48" ]
[ [ [ 1, 8 ] ] ]
9140f47d1d54fbb22361ab720acd37132b4d8397
fb7d4d40bf4c170328263629acbd0bbc765c34aa
/SpaceBattleModele/SpaceBattleModele/CaseVide.h
9ced629777cb2b7fbb2601e56e0296fc73004deb
[]
no_license
bvannier/SpaceBattle
e146cda9bac1608141ad8377620623514174c0cb
6b3e1a8acc5d765223cc2b135d2b98c8400adf06
refs/heads/master
2020-05-18T03:40:16.782219
2011-11-28T22:49:36
2011-11-28T22:49:36
2,659,535
0
1
null
null
null
null
UTF-8
C++
false
false
522
h
/** * \file CaseVide.h * \brief Classe CaseVide * \author Vannier */ #ifndef CASE_VIDE_H #define CASE_VIDE_H #pragma once #define WANTDLLEXP #ifdef WANTDLLEXP //exportation dll #define DLL __declspec( dllexport ) #define EXTERNC extern "C" #else #define DLL //standard #define EXTERNC #endif #include "Case.h" using namespace ModeleImplementation; #include<vector> namespace ModeleImplementation { class CaseVide : public Case { public : CaseVide(); }; } #endif
[ [ [ 1, 34 ] ] ]
3f845ebc9515b06e69f5b498d20d59a4602d93bd
fec97339b4f90ddcc8d49d39c048140f05b2db6e
/AnyAxisRotate/mainwindow.h
f8666b514bfd3299080d732f7007b0b3e58a341d
[]
no_license
SirEOF/geomdef
55ea012b898029baaf60fae8fc236ca8ab855cfb
0e9508539703b697882df82c84fb92d34a3e3dff
refs/heads/master
2021-05-29T06:43:54.986200
2010-02-01T11:24:21
2010-02-01T11:24:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class AxisRotate; class QGraphicsScene; class QImage; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void changeEvent(QEvent *e); private: Ui::MainWindow *ui; AxisRotate *ar; QGraphicsScene *scene; QImage *image; private slots: void setXAxis(int); void setYAxis(int); void setZAxis(int); }; #endif // MAINWINDOW_H
[ "grzesiek.kurek@e2a736ec-deac-11de-b357-fb893c5a43fa" ]
[ [ [ 1, 36 ] ] ]
62f3eb0588f397918b499fd8a37b679a1528c662
00c36cc82b03bbf1af30606706891373d01b8dca
/Amethyst/Amethyst_Label.h
a6f61c5615c1162aa49e9e24f25c47c9665fb705
[ "BSD-3-Clause" ]
permissive
VB6Hobbyst7/opengui
8fb84206b419399153e03223e59625757180702f
640be732a25129a1709873bd528866787476fa1a
refs/heads/master
2021-12-24T01:29:10.296596
2007-01-22T08:00:22
2007-01-22T08:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
h
// OpenGUI (http://opengui.sourceforge.net) // This source code is released under the BSD License // See LICENSE.TXT for details #ifndef Amethyst_Label_h__ #define Amethyst_Label_h__ #include "OpenGUI.h" #include "Amethyst_Exports.h" namespace OpenGUI { namespace Amethyst { //! Non interactive text label /*! Labels have no borders or backgrounds. They simply draw text where they are located. They will clip the text glyphs within their bounds, so you must use an appropriately sized Label if you want all of your text to be visible. \par Properties - Text - Font - FontColor - Wrap - Alignment */ class AMETHYST_API Label: public Control { public: Label(); virtual ~Label(); //! Set the text contents void setText( const String& text ); //! Retrieve the current text contents const String& getText() const; //! Set the font used for this label void setFont( const Font& fnt ); //! Get the font used for this label const Font& getFont() const; //! Sets the color of the font void setFontColor( const Color& color ); //! Gets the color of the font const Color& getFontColor() const; //! Sets the alignment of the text within the label void setAlignment( const TextAlignment& alignment ); //! Gets the current text alignment const TextAlignment& getAlignment() const; //! Sets text wrapping void setWrap( bool wrap ); //! Gets the current text wrapping bool getWrap() const; static Widget* createLabelFactory(); virtual ObjectAccessorList* getAccessors(); protected: virtual void onDraw( Object* sender, Draw_EventArgs& evtArgs ); private: String mText; Font mFont; TextAlignment mAlignment; bool mWrap; Color mColor; }; } // namespace Amethyst{ } // namespace OpenGUI{ #endif // Amethyst_Label_h__
[ "zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59", "mmanyen@2828181b-9a0d-0410-a8fe-e25cbdd05f59" ]
[ [ [ 1, 57 ], [ 59, 73 ] ], [ [ 58, 58 ] ] ]
44d7d0f4711a92c52e8434d2b5191ff543767734
9d6d89a97c85abbfce7e2533d133816480ba8e11
/src/GameType/Classic/Ending.cpp
b74bfcad24aae5f817a19b7f572b5b4cb2691011
[]
no_license
polycraft/Bomberman-like-reseau
1963b79b9cf5d99f1846a7b60507977ba544c680
27361a47bd1aa4ffea972c85b3407c3c97fe6b8e
refs/heads/master
2020-05-16T22:36:22.182021
2011-06-09T07:37:01
2011-06-09T07:37:01
1,564,502
1
2
null
null
null
null
UTF-8
C++
false
false
1,155
cpp
#include "Ending.h" #include "Classic.h" #include "../GameType.h" #include "../../Engine/util/Timer.h" #include "../../Type/Bomberman.h" namespace GameTypeSpace { using namespace ClassicSpace; Ending::Ending(GameTypeSpace::Classic *gameType,CollisionDetector *collision) : PhaseClassic(gameType,collision) { this->waitTime = 4000; } Ending::~Ending() { } void Ending::init() { Engine::Timer::getTimer()->addListener(this,this->waitTime); cout << "End Of Round ... Wait" << endl; //efface les bomberman for(vector<Bomberman*>::iterator it = this->gameType->getPlayerNetwork().begin() ; it < this->gameType->getPlayerNetwork().end() ; it++) { (*it)->destroy(); } this->gameType->getPlayerNetwork().clear(); this->nextEtat(); } void Ending::run() { } void Ending::updateTimer(unsigned int delay) { cout << "End of Ending.. Prepare to next Round" << endl; Engine::Timer::getTimer()->removeListener(this,this->waitTime); end(P_Next); } void Ending::executeAction(Engine::stateEvent &event) { } void Ending::updateRecv(Engine::Socket *,Engine::Paquet& paquet) { } }
[ [ [ 1, 11 ], [ 13, 44 ] ], [ [ 12, 12 ], [ 45, 56 ] ] ]
b027ec2de387c26c0d102bd49cc6a6676006995c
c440e6c62e060ee70b82fc07dfb9a93e4cc13370
/src/gui2/algorithmview.h
460b719a0fb85b889d7f6b47e48f7f5d259ac4cb
[]
no_license
BackupTheBerlios/pgrtsound-svn
2a3f2ae2afa4482f9eba906f932c30853c6fe771
d7cefe2129d20ec50a9e18943a850d0bb26852e1
refs/heads/master
2020-05-21T01:01:41.354611
2005-10-02T13:09:13
2005-10-02T13:09:13
40,748,578
0
0
null
null
null
null
UTF-8
C++
false
false
2,633
h
#ifndef ALGORITHMVIEW_H #define ALGORITHMVIEW_H #include "guimodulefactory.h" #include "guiconnection.h" #include "../debug.h" #include "../algorithm.h" #include <gtkmm/window.h> #include <gtkmm/layout.h> #include <gtkmm/menu.h> #include <gtkmm/messagedialog.h> #include <list> #include <string> #include <map> /** * Widok graficznych reprezentacji modulow. */ class AlgorithmView : public Gtk::Layout { public: AlgorithmView(); ~AlgorithmView(); void AddModule(string type, string name, int x, int y); void onMenuAddModule(string type); void DeleteConnection( GuiModule* module, int inpuitId ); void ConnectModules(GuiModule* from, int fomNumoutput, GuiModule* to, int toNuminput); void SelectGuiModule( GuiModule* guiMod ); void Clear(); GuiModule* GetModule( std::string name ); void RedrawConnections(); bool IsDraggingModule(); Algorithm* GetAlgorithm(); void LoadFromFile(string fileName); void SaveToFile(string fileName); //void SetParentWindow( Gtk::Window *window ); void DeleteModule( GuiModule* guiModule ); bool on_expose_event(GdkEventExpose* e); void on_realize(); bool on_motion_notify_event(GdkEventMotion* even); bool on_button_press_event(GdkEventButton* event); bool on_button_release_event(GdkEventButton* event); bool ChangeModuleName( ModuleId moduleId, string str ); // nowy sygnal typedef sigc::signal<void, Glib::ustring> type_signal_notify_xput; type_signal_notify_xput signal_notify_xput(); void InitAudioPorts(); void FindCurrentModule( int x, int y ); // No description GuiModule* GetGuiModule(string name); private: type_signal_notify_xput m_signal_notify_xput; bool isDraggingModule; bool isDraggingConnection; int width, height; GuiModule* currentGuiModule; // modul pod kursorem GuiModule* connSourceModule, * connDestModule; // moduly miedzy ktorymi chcemy polaczenie int connSourceNumber, connDestNumber; // numer wejscia i wyjscia dla tworzonego polaczenia int currentGuiModuleX, currentGuiModuleY; // gdzie byl kursor nad kliknietym widgecie po kliknieciu std::map<string, GuiModule*> name2GuiModuleMap; Gtk::Adjustment* adjh, * adjv; // zakresy scrollbarow std::list<GuiModule*> guiModules; std::list<GuiConnection*> connections; Algorithm algorithm; GuiModuleFactory guiFactory; Glib::RefPtr<Gdk::GC> fgGc, bgGc; Gdk::Color fgColor; Glib::RefPtr<Gdk::Window> window; GuiConnection connectionDrag; Gtk::Menu menuPopup; Gdk::Point lastClick; void UpdateConnections(); }; #endif // ALGORITHMVIEW_H
[ "ad4m@fa088095-53e8-0310-8a07-f9518708c3e6" ]
[ [ [ 1, 80 ] ] ]
875a7a93ebbf210945d68d59b683c7bc9d867a82
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/btnexgenipl/examples/Codecs/BTCEncoderYUV.h
85439ccce2e0ce260f9c1bb35e35b87b050d5566
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
UTF-8
C++
false
false
2,121
h
///////////////////////////////////////////////////////////////////////////// // // NexgenIPL - Next Generation Image Processing Library // Copyright (c) 1999-2004 Binary Technologies // All Rights Reserved. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. If // the source code in this file is used in any commercial application // then a simple email would be nice. // // THIS SOFTWARE IS PROVIDED BY BINARY TECHNOLOGIES ``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 BINARY TECHNOLOGIES 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. // // Binary Technologies // http://www.binary-technologies.com // [email protected] // ///////////////////////////////////////////////////////////////////////////// #ifndef BTCENCODERYUV_INCLUDED #define BTCENCODERYUV_INCLUDED #pragma once #include "BTICodec.h" class BTCEncoderYUV : public BTCEncoder { public: BTCEncoderYUV(); virtual ~BTCEncoderYUV(); virtual const bt_char *GetFormat(); virtual const bt_char *GetDescription(); virtual const bt_char *GetExtension(); virtual bool Save( BTCOStream* pOStream, BTCImageData* pImageData, BTINotification* pNotification, BTCEncoderOptions* pOptions); }; #endif // BTCENCODERYUV_INCLUDED
[ [ [ 1, 56 ] ] ]
ee259cddbc5b7f9214ff5e8a7e11e74a37cf9703
ccaf260884a5b378a4b4178a5489d18f022eaac0
/AI3/src/Model.cpp
7c6134ba6c67ed6bff4e02d8b6273da596054f55
[]
no_license
mmolignano/ai3
ac650a27434eeb74c5988217091dac458e72485a
0a2e9789ad268e06b7ceb0c627504d3e308e643d
refs/heads/master
2021-01-20T15:49:22.643334
2010-02-22T22:51:48
2010-02-22T22:51:48
33,311,395
0
0
null
null
null
null
UTF-8
C++
false
false
8,052
cpp
/* * Model.cpp * * Created on: Feb 10, 2010 * Author: jsandbrook */ #include "Model.h" Model::Model(char* test, char* train) { readTestFile(test); readTrainFile(train); } Model::~Model() { } /* * Reads in a file of single characters separated by commas. It ignores new line characters. */ bool Model::readTestFile(char* file) { FILE* hFile; std::cout << "Reading test file\n"; int ret = 0, len = 1, i = 0; // Open the file hFile = fopen(file, "r"); if(hFile == NULL) { std::cout << "Error opening file\n"; return false; } // Find how many characters there are while(ret != EOF) { ret = fgetc(hFile); if(ret == 44) {// If there's a comma len++; } } std::cout << "Found " << len << " characters\n"; freopen(file, "r", hFile); // Reopen the file to start from the beginning testArray = (int*)calloc(len, sizeof(int)); testLength = len; // Fill in the array of characters std::cout << "Filling array\n"; ret = fgetc(hFile); while(ret != EOF) { if(ret != 44) { testArray[i] = ret; i++; } ret = fgetc(hFile); } return true; } /* * Reads in a file of single characters separated by commas. It ignores new line characters. */ bool Model::readTrainFile(char* file) { FILE* hFile; int ret = 0, len = 1, i = 0; // Open the file hFile = fopen(file, "r"); if(hFile == NULL) { std::cout << "Error opening file\n"; return false; } // Find how many characters there are while(ret != EOF) { ret = fgetc(hFile); if(ret == 44) {// If there's a comma len++; } } freopen(file, "r", hFile); // Reopen the file to start from the beginning trainArray = (int*)calloc(len, sizeof(int)); trainLength = len; // Fill in the array of characters ret = fgetc(hFile); while(ret != EOF) { if(ret != 44) { trainArray[i] = ret; i++; } ret = fgetc(hFile); } return true; } /* * Prints the currently read files */ void Model::printModel() { std::cout << "Training data:\n"; for(int i = 0; i < trainLength; i++) { std::cout << trainArray[i] << ","; } std::cout << "\nTest data:\n"; for(int i = 0; i < testLength; i++) { std::cout << testArray[i] << ","; } std::cout << "\n\n"; analyzeUnigram(); charData* cur; cur = firstChar; while(cur != NULL) { std::cout << cur->character << " : " << cur->frequency << "\n"; cur = cur->next; } analyzeBigram(); bigram* curBi; charData* charBi; curBi = firstBi; while(curBi != NULL) { charBi = curBi->predictions; while(charBi != NULL) { std::cout << charBi->character << " | " << curBi->firstChar << " : " << charBi->frequency << "\n"; charBi = charBi->next; } curBi = curBi->next; } } /* * Analyzes the training data according to a unigram model */ void Model::analyzeUnigram() { charData* cur; char first = 0, second = 0; // Clear any current charData info and allocate data /* TODO: Iterate through list and actually delete stuff */ firstChar = NULL; firstChar = allocateCharData(); // Step through each character in the file and update our info for(int i = 0; i < trainLength; i++) { // Update for unigram cur = firstChar; while(cur != NULL) { if(cur->character == trainArray[i]) {// Update the frequency of the correct charData struct cur->frequency++; break;// We don't need to check the rest } else if(cur->character == 0) {// This is the first iteration cur->character = trainArray[i]; cur->frequency = 1; } else if(cur->next == NULL) {// Allocate a new charData struct cur->next = allocateCharData(); cur->next->character = trainArray[i]; cur->next->frequency = 1; cur->next->prev = cur; break; } cur = cur->next; } } // Sort the unigram data by most frequent firstChar = sortCharData(firstChar); } /* * Analyzes read data according to a bigram model */ void Model::analyzeBigram() { charData *curChar; bigram *cur; char known = 0; // Clear out old bigram info and allocate new space /* TODO: Actually delete any old bigram info */ firstBi = NULL; firstBi = allocateBigram(); // Step through each character in the file and update our info known = trainArray[0]; for(int i = 1; i < trainLength; i++) { cur = firstBi; while(cur != NULL) {// Loop through the bigram structs if(cur->firstChar == known) {// If we find a matching known character curChar = cur->predictions; while(curChar != NULL) {// Loop through this known character's predictions if(curChar->character == trainArray[i]) { curChar->frequency++; break;// No need to check the others } else if(curChar->next == NULL) {// No more predictions for this known character, this one's new curChar->next = allocateCharData(); curChar->next->character = trainArray[i]; curChar->next->prev = curChar; curChar->next->frequency++; break; } else { curChar = curChar->next; } } break; // Don't need to check the rest of the bigrams } else if(cur->firstChar == 0) {// This is the first iteration cur->firstChar = known; cur->predictions = allocateCharData(); cur->predictions->character = trainArray[i]; cur->predictions->frequency++; break;//Continue to the next character } else if(cur->next == NULL) {// If we didn't find a matching known character and we're at the end of the list, create a new bigram cur->next = allocateBigram(); cur->next->firstChar = known; cur->next->prev = cur; cur->next->predictions = allocateCharData(); cur->next->predictions->character = trainArray[i]; cur->next->predictions->frequency++; break; } else {// Else move on to the next stuct cur = cur->next; } } known = trainArray[i]; } // Sort each bigrams charData lists cur = firstBi; while(cur != NULL) { cur->predictions = sortCharData(cur->predictions); cur = cur->next; } } /* * Allocates memory for a charData structure */ charData* Model::allocateCharData() { charData *ret; ret = (charData*)malloc(sizeof(charData)); ret->character = 0; ret->prev = NULL; ret->next = NULL; ret->frequency = 0; return ret; } /* * Allocates memory for a bigram structure */ bigram* Model::allocateBigram() { bigram* ret; ret = (bigram*)malloc(sizeof(bigram)); ret->firstChar = 0; ret->next = NULL; ret->prev = NULL; ret->predictions = NULL; return ret; } /* * Allocates memory for a trigram structure */ trigram* Model::allocateTrigram() { trigram* ret; ret = (trigram*)malloc(sizeof(trigram)); ret->secondChar = 0; ret->firstChar = 0; ret->next = NULL; ret->prev = NULL; ret->predictions = NULL; return ret; } /* * Sorts a linked list of charData structs into descending order by their frequency */ charData* Model::sortCharData(charData* first) { bool sorted = false; int len = 0; charData *cur; // Determine the list length cur = first; while(cur != NULL) { len++; cur = cur->next; } // No need to sort if there's only one entry if(len == 1) { return first; } // Sort the list cur = first; while(sorted == false) { sorted = true; for(int i = 0; i < len - 1; i++) { if(cur->next->frequency > cur->frequency) { sorted = false; cur->next->prev = cur->prev; if(cur->prev != NULL) { cur->prev->next = cur->next; } cur->prev = cur->next; if(cur->next->next != NULL) { cur->next = cur->next->next; } else { cur->next = NULL; } cur->prev->next = cur; if(cur->next != NULL) { cur->next->prev = cur; } } else { cur = cur->next; } } // Find the new first struct while(cur->prev != NULL) { cur = cur->prev; } } return cur; } /* * Predicts the next letter in the test file */ char Model::predict() { }
[ "jsandbrook@c842427a-1736-11df-914e-2594af177612" ]
[ [ [ 1, 349 ] ] ]