blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
7fae950e12253834ca48d6e89deb6ab7e4cabb6d
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
/src/enemies/static.h
3bf5159cba6ddfc7e15e0c1ae796e51421fe6bb1
[]
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
4,154
h
/*************************************************************************** * static.h - headers for the corresponding cpp file * * Copyright (C) 2007 - 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_STATIC_ENEMY_H #define SMC_STATIC_ENEMY_H #include "../enemies/enemy.h" #include "../objects/path.h" namespace SMC { /* *** *** *** *** *** *** cStaticEnemy *** *** *** *** *** *** *** *** *** *** *** */ class cStaticEnemy : public cEnemy { /* Static enemies don't move but will * hit you if you touch them. */ public: // constructor cStaticEnemy( float x, float y ); // create from stream cStaticEnemy( CEGUI::XMLAttributes &attributes ); // destructor virtual ~cStaticEnemy( void ); // init defaults void Init( void ); /* late initialization * this needs linked objects to be already loaded */ virtual void Init_Links( void ); // copy virtual cStaticEnemy *Copy( void ); // create from stream virtual void Create_From_Stream( CEGUI::XMLAttributes &attributes ); // save to stream virtual void Save_To_Stream( ofstream &file ); // load from savegame virtual void Load_From_Savegame( cSave_Level_Object *save_object ); // save to savegame virtual cSave_Level_Object *Save_To_Savegame( void ); // Set the static image void Set_Static_Image( const std::string &filename ); // Set the rotation speed void Set_Rotation_Speed( float speed ); // Set the movement speed void Set_Speed( float speed ); // Set the path identifier void Set_Path_Identifier( const std::string &path ); /* downgrade state ( if already weakest state : dies ) * force : usually dies or a complete downgrade */ virtual void DownGrade( bool force = 0 ); // dying animation update virtual void Update_Dying( void ); // update virtual void Update( void ); // draw virtual void Draw( cSurface_Request *request /* = NULL */ ); // if update is valid for the current state virtual bool Is_Update_Valid( void ); /* Validate the given collision object * returns 0 if not valid * returns 1 if an internal collision with this object is valid * returns 2 if the given object collides with this object (blocking) */ virtual Col_Valid_Type Validate_Collision( cSprite *obj ); // collision from player virtual void Handle_Collision_Player( cObjectCollision *collision ); // collision from an enemy virtual void Handle_Collision_Enemy( cObjectCollision *collision ); // leveleditor activation virtual void Editor_Activate( void ); // editor image text changed event bool Editor_Image_Text_Changed( const CEGUI::EventArgs &event ); // editor rotation speed text changed event bool Editor_Rotation_Speed_Text_Changed( const CEGUI::EventArgs &event ); // editor path identifier text changed event bool Editor_Path_Identifier_Text_Changed( const CEGUI::EventArgs &event ); // editor speed text changed event bool Editor_Speed_Text_Changed( const CEGUI::EventArgs &event ); // editor fire resistant option selected event bool Editor_Fire_Resistant_Select( const CEGUI::EventArgs &event ); // editor ice resistance text changed event bool Editor_Ice_Resistance_Text_Changed( const CEGUI::EventArgs &event ); // image filename std::string m_img_filename; // rotation speed float m_rotation_speed; // movement speed if using path float m_speed; // path state if linked to a path cPath_State m_path_state; private: // Create the Name from the current settings void Create_Name( void ); }; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ [ [ 1, 127 ] ] ]
f90b904aef44f3f7892a410417bbea1bc5f18390
c86338cfb9a65230aa7773639eb8f0a3ce9d34fd
/MNStatContainer.h
69230499825f9fba77641fe316569edcfef7a996
[]
no_license
jonike/mnrt
2319fb48d544d58984d40d63dc0b349ffcbfd1dd
99b41c3deb75aad52afd0c315635f1ca9b9923ec
refs/heads/master
2021-08-24T05:52:41.056070
2010-12-03T18:31:24
2010-12-03T18:31:24
113,554,148
0
0
null
null
null
null
UTF-8
C++
false
false
17,965
h
//////////////////////////////////////////////////////////////////////////////////////////////////// // MNRT License //////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010 Mathias Neumann, www.maneumann.com. // 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. // // 3. Neither the name Mathias Neumann, nor the names of 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. //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// /// \file MNRT\MNStatContainer.h /// /// \brief Declares the MNStatContainer class and several StatEntry classes. /// \author Mathias Neumann /// \date 14.04.2010 /// \ingroup cpuutil //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __MN_STATCONTAINER_H__ #define __MN_STATCONTAINER_H__ #pragma once #include <map> #include <limits> // Forward decl. #ifndef DOXYGEN_IGNORE class StatEntry; enum cudaError; typedef cudaError cudaError_t; #endif //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class MNStatContainer /// /// \brief Statistics container class for MNRT. /// /// Inspired by \ref lit_pharr "[Pharr and Humphreys 2004]". This /// container holds a set of StatEntry objects, ordered by both category name and /// entry name. There is a simple way to print out the status of the container. /// /// Class is designed as singleton and might need optimizations for when used from /// multiple CPU-threads. /// /// \author Mathias Neumann /// \date 14.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// class MNStatContainer { // Singleton. Hide constructors. private: MNStatContainer(void); MNStatContainer(const MNStatContainer& other); public: ~MNStatContainer(void); // Attributes private: // Holds the stat counters. std::map<std::pair<std::string, std::string>, StatEntry*> m_Counters; // Whether timers are enabled. bool m_bTimersEnabled; // Class public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn static MNStatContainer& GetInstance() /// /// \brief Returns the only MNStatContainer instance. /// /// \warning Not thread-safe! /// /// \author Mathias Neumann /// \date 19.03.2010 /// /// \return The instance. //////////////////////////////////////////////////////////////////////////////////////////////////// static MNStatContainer& GetInstance(); // Operations public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void AddEntry(StatEntry* pEntry) /// /// \brief Adds a stat entry to the container. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param [in] pEntry The entry to add. //////////////////////////////////////////////////////////////////////////////////////////////////// void AddEntry(StatEntry* pEntry); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn StatEntry* FindEntry(const std::string& strCategory, const std::string& strName) /// /// \brief Searches for a stat entry. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param strCategory Category of stat entry. /// \param strName Name of stat entry. /// /// \return A pointer to the stat entry or \c NULL, if nothing found. //////////////////////////////////////////////////////////////////////////////////////////////////// StatEntry* FindEntry(const std::string& strCategory, const std::string& strName); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Reset() /// /// \brief Resets all stat entries using StatEntry::Reset(). /// /// \author Mathias Neumann /// \date 02.11.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Reset(); /// Sets whether timers should take times. Can be used to avoid timing overhead. void SetTimersEnabled(bool b); /// Gets whether timers are enabled. bool GetTimersEnabled() const { return m_bTimersEnabled; } // Reporting public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Print(FILE* fileTarget) /// /// \brief Prints all statistics to given file. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param [in] fileTarget The target file. //////////////////////////////////////////////////////////////////////////////////////////////////// void Print(FILE* fileTarget); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class StatEntry /// /// \brief Abstract entry base class for MNStatContainer entries. /// /// This class manages the basic properties of an entry, that is the stat category and it's /// name. Subclasses should provide factory methods that allow creation of stat entries /// \e and register the entry with the MNStatContainer instance. /// /// \author Mathias Neumann /// \date 14.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// class StatEntry { protected: /// Hidden constructor. Use factory methods. StatEntry(const std::string& strCategory, const std::string& strName); /// Hidden constructor. Use factory methods. StatEntry(const StatEntry& other); public: ~StatEntry(); // Attributes private: // Meta data std::string m_strCategory, m_strName; // Accessors public: /// Returns entry's category name. const std::string& GetCategory() { return m_strCategory; } /// Returns entry's name. const std::string& GetName() { return m_strName; } // Operations public: /// Resets this entry to it's initial state. virtual void Reset() = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn virtual void Print(FILE* fileTarget) = 0 /// /// \brief Prints this entry to the given file. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param [in] fileTarget The target file. //////////////////////////////////////////////////////////////////////////////////////////////////// virtual void Print(FILE* fileTarget) = 0; // Implementation protected: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void PrintHeading(FILE* fileTarget) /// /// \brief Prints entry heading to given file. /// /// The entry heading is basically the entry's name in a special format to ensure /// alignment and improve visual quality. Subclasses should call this method within /// their Print() implementation. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param [in] fileTarget The target file. //////////////////////////////////////////////////////////////////////////////////////////////////// void PrintHeading(FILE* fileTarget); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void PrintHeading(FILE* fileTarget, const std::string strExtra) /// /// \brief Prints entry heading to given file, including an extra string. /// /// The extra string is appended to the default entry heading. It can be used within /// subclasses to print out multiple, distinguishable stat lines. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param [in] fileTarget The target file. /// \param strExtra The extra string. //////////////////////////////////////////////////////////////////////////////////////////////////// void PrintHeading(FILE* fileTarget, const std::string strExtra); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class StatCounter /// /// \brief Counter entry for MNStatContainer. /// /// \author Mathias Neumann /// \date 14.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// class StatCounter : public StatEntry { protected: /// Hidden constructor. Use factory methods. StatCounter(const std::string& strCategory, const std::string& strName); /// Hidden constructor. Use factory methods. StatCounter(const StatCounter& other); public: ~StatCounter(); // Attributes private: // Counter long long m_nCounter; // Factory public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn static StatCounter& Create(const std::string& strCategory, const std::string& strName) /// /// \brief Creates a StatCounter object and registers it with the MNStatContainer instance. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param strCategory Entry's category name. /// \param strName Entry's name. /// /// \return The created counter. //////////////////////////////////////////////////////////////////////////////////////////////////// static StatCounter& Create(const std::string& strCategory, const std::string& strName); // Accessors public: /// Returns the current counter state. long long GetCounter() const { return m_nCounter; } /// Operator to get the current counter state. operator long long() { return m_nCounter; } /// Operator to get the current counter state as \c double. operator double() { return (double)m_nCounter; } // Operations public: /// Increments the counter by the given value \a val. void Increment(long long val = 1) { m_nCounter += val; } /// Ensures the counter's value is smaller or equal \a val. void Min(long long val) { if(val < m_nCounter) m_nCounter = val; } /// Ensures the counter's value is larger or equal \a val. void Max(long long val) { if(val > m_nCounter) m_nCounter = val; } /// Operator to add a given value \a val to the counter. void operator+=(long long val) { m_nCounter += val; } /// Increment operator. Increments counter by one. void operator++() { ++m_nCounter; } virtual void Reset() { m_nCounter = 0; } virtual void Print(FILE* fileTarget); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class StatRatio /// /// \brief Ratio entry for MNStatContainer. /// /// This entry has a basic counter and a step counter. The ratio is defined as the ratio of /// basic counter to step counter. If the step counter is zero, the ratio is \c FLT_MAX. /// /// \author Mathias Neumann /// \date 14.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// class StatRatio : public StatEntry { protected: /// Hidden constructor. Use factory methods. StatRatio(const std::string& strCategory, const std::string& strName); /// Hidden constructor. Use factory methods. StatRatio(const StatRatio& other); public: ~StatRatio(); // Attributes private: // Counter size_t m_nCounter; // Steps size_t m_nSteps; // Factory public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn static StatRatio& Create(const std::string& strCategory, const std::string& strName) /// /// \brief Creates a StatRatio object and registers it with the MNStatContainer instance. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param strCategory Entry's category name. /// \param strName Entry's name. /// /// \return The created ratio entry. //////////////////////////////////////////////////////////////////////////////////////////////////// static StatRatio& Create(const std::string& strCategory, const std::string& strName); // Accessors public: /// Returns the current ratio of base counter to step counter. float GetRatio() const { if(m_nSteps) return float(m_nCounter) / float(m_nSteps); else return FLT_MAX; } /// Operator to get the current ratio. operator float() { return GetRatio(); } // Operations public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Increment(size_t count = 1, size_t steps = 0) /// /// \brief Increments one or both counters. /// /// \author Mathias Neumann /// \date 14.04.2010 /// /// \param count Increment for base counter. /// \param steps Increment for step counter. //////////////////////////////////////////////////////////////////////////////////////////////////// void Increment(size_t count = 1, size_t steps = 0) { m_nCounter += count; m_nSteps += steps; } virtual void Reset() { m_nCounter = 0; m_nSteps = 0; } virtual void Print(FILE* fileTarget); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class StatTimer /// /// \brief Timer entry for MNStatContainer. /// /// Implemented using CUDA GPU timers. Provides means to measure timings for GPU /// execution by allowing synchronization before starting and stopping the timer. /// /// \author Mathias Neumann /// \date 15.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// class StatTimer : public StatEntry { protected: /// Hidden constructor. Use factory methods. StatTimer(const std::string& strCategory, const std::string& strName, bool hasSteps = false); /// Hidden constructor. Use factory methods. StatTimer(const StatTimer& other); public: ~StatTimer(); // Attributes private: // CUDA timer identifier. unsigned int m_Timer; // Whether we have steps and can display an average. bool m_hasSteps; // Factory public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn static StatTimer& Create(const std::string& strCategory, const std::string& strName, /// bool hasSteps = false) /// /// \brief Creates a StatTimer object and registers it with the MNStatContainer instance. /// /// \author Mathias Neumann /// \date 15.04.2010 /// /// \param strCategory Entry's category name. /// \param strName Entry's name. /// \param hasSteps Whether the timer has steps and can display an average. /// /// \return The created timer entry. //////////////////////////////////////////////////////////////////////////////////////////////////// static StatTimer& Create(const std::string& strCategory, const std::string& strName, bool hasSteps = false); // Accessors public: /// Returns total time in milliseconds. float GetTotal() const; /// Returns average time in milliseconds. Only valid for timer entries with steps. float GetAverage() const; // Operations public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn cudaError_t Start(bool cudaSynchronize = false) /// /// \brief Starts the timer. /// /// \author Mathias Neumann /// \date 15.04.2010 /// /// \param cudaSynchronize Pass \c true to synchronize CUDA threads before starting the timer. /// /// \return Error code returned from \c cudaThreadSynchronize(), or \c cudaSuccess. //////////////////////////////////////////////////////////////////////////////////////////////////// cudaError_t Start(bool cudaSynchronize = false); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn cudaError_t Stop(bool cudaSynchronize = false) /// /// \brief Stops the timer. /// /// \author Mathias Neumann /// \date 15.04.2010 /// /// \param cudaSynchronize Pass \c true to synchronize CUDA threads before stopping the timer. /// /// \return Error code returned from \c cudaThreadSynchronize(), or \c cudaSuccess. //////////////////////////////////////////////////////////////////////////////////////////////////// cudaError_t Stop(bool cudaSynchronize = false); virtual void Reset(); virtual void Print(FILE* fileTarget); }; #endif // __MN_STATCONTAINER_H__
[ [ [ 1, 481 ] ] ]
f7547cb0de496f0b4c745f6777c78f838ca36ef5
f246dc2a816ccd5acd0776a48c2c24cdb1f4178f
/include/PigletOpSys.h
7017a5794f36af22272a3558f2ac1d33377d6c60
[]
no_license
profcturner/pigletlib
3f2c4b1af000d73cf4a176a8463c16aaeefde99a
b2ccbb43270a5e8d3a0f8ae6bd3d3cb82a061fec
refs/heads/master
2021-07-24T07:23:10.577261
2007-08-26T22:36:47
2007-08-26T22:36:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
h
/** ** Piglet Productions ** ** FileName : OpSys.h ** ** Defines : Piglet_OpSys ** ** Description ** ** Operating System detection and time slicing. ** ** ** Initial Coding : Colin Turner ** ** Date : 3rd Febuary 1999 ** ** ** Copyright applies on this file, and distribution may be limited. ** Copyright 1999 Colin Turner */ /* ** Revision 1.00 ** */ #ifndef PigletOpSys_H #define PigletOpSys_H #include <i86.h> #include <string.h> class PigletOpSys { // Data private: int TimeSliceEnabled; int Enabled; int OpSysCode; // Unique operating system identifier unsigned short OpSysMajVer; unsigned short OpSysMinVer; char OpSysName[20]; char OpSysVersion[20]; // Services public: void TimeSlice(); void DisableMultiTasker(); void SetMultiTasker(); char * GetName(); char * GetVersion(); PigletOpSys(); // Implementation private: PigletOpSys(); //~PigletOpSys(); void DetectMultiTasker(); // Enumeration public: enum{ OS_None = 0, OS_DOS, OS_OS2, OS_Win16, OS_Win32, OS_WinNT, OS_DESQview, OS_DoubleDOS }; }; #endif // (PigletOpSys_H)
[ [ [ 1, 91 ] ] ]
2d3984aa15b46009d1a4e34f5e7f3ba75ed42e0d
16052d8fae72cecb6249372b80fe633251685e1d
/distances/complete_link.h
93fab641cb2977097c562a2cc40a7a523e596242
[]
no_license
istrandjev/hierarhical-clustering
7a9876c5c6124488162f4089d7888452a53595a6
adad22cce42d68b04cca747352d94df039e614a2
refs/heads/master
2021-01-19T14:59:08.593414
2011-06-29T06:07:41
2011-06-29T06:07:41
32,250,503
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
#ifndef FURTHEST_NEIGHBOUR_HPP #define FURTHEST_NEIGHBOUR_HPP #include "distance.h" class HierarchicalClustering; class Cluster; class CompleteLink: public Distance { public: virtual double mergedDistance(const Cluster& leftFromCluster, const Cluster& rightFromCluster, const Cluster& toCluster, HierarchicalClustering& hierarchicalClustering) const; virtual std::string getName() const; }; #endif //FURTHEST_NEIGHBOUR_HPP
[ "[email protected]@c0cadd32-5dbd-3e50-b098-144b922aa411", "[email protected]@c0cadd32-5dbd-3e50-b098-144b922aa411" ]
[ [ [ 1, 8 ], [ 10, 17 ] ], [ [ 9, 9 ] ] ]
2b42ed53c5baa89ae3c5d9f159692bf4b26df56a
2cc9dbb2786ff544a3604e1a9089692fea43af85
/include/taiju/memory-buf.h
9a6de588cabd75f4cc365cb8c1a1562a476dc4c2
[ "BSD-3-Clause" ]
permissive
pombredanne/taiju
eb2470693e91ad9ca852f91665e7248bdecf17f8
90f152d5e66b1741d35b9d871f7a5db68699d48d
refs/heads/master
2021-01-10T04:37:27.053375
2010-03-05T13:06:12
2010-03-05T13:06:12
47,940,472
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
#ifndef TAIJU_MEMORY_BUF_H #define TAIJU_MEMORY_BUF_H #include <streambuf> namespace taiju { class MemoryBuf : public std::streambuf { public: MemoryBuf(void *buf, std::size_t size); #ifdef _MSC_VER std::streamsize _Xsgetn_s(char *s, std::size_t, std::streamsize n); #else std::streamsize xsgetn(char *s, std::streamsize n); #endif std::streamsize xsputn(const char *s, std::streamsize n); private: // Disallows copies. MemoryBuf(const MemoryBuf &); MemoryBuf &operator=(const MemoryBuf &); }; } // namespace taiju #endif // TAIJU_MEMORY_BUF_H
[ "susumu.yata@d5d7bd1e-2453-11df-8055-cfab390f4384" ]
[ [ [ 1, 28 ] ] ]
a07a231c52228c917f9b5f3636c50eefe16e4aff
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGameNeedle/GameNeedleComponent/include/GameBaseComponent.h
6b25dd8f03b115811fd831b47bff3368886f246d
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
896
h
#ifndef __Orz_GameBaseComponent__ #define __Orz_GameBaseComponent__ #include "CGameBaseInterface.h" namespace Ogre { class SceneNode; class Entity; } namespace Orz { class CGameBaseInterface; class GameBaseComponent: public Component//ÍâȦ { public : GameBaseComponent(void); virtual ~GameBaseComponent(void); private: virtual ComponentInterface * _queryInterface(const TypeInfo & info); bool setColor(int id, CGameBaseInterface::LIGHT_COLOR color); boost::scoped_ptr<CGameBaseInterface> _baseInterface; bool load(int id, Ogre::SceneNode * node); Ogre::SceneNode * getSceneNode(int id); bool init(Ogre::SceneNode * node); Ogre::SceneNode * _node; boost::array<Ogre::SceneNode *, 24> _nodes; boost::array<Ogre::SceneNode *, 24> _nodes2; boost::array<Ogre::Entity *, 24> _entities; boost::array<Ogre::Entity *, 24> _entities2; }; } #endif
[ [ [ 1, 34 ] ] ]
215ec024f860eaf8c2dec23b89a4d769b1dc6009
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
/src/tools/RoofExtractor/main.cpp
6c3c035da1067bd65cd3f4838749d09beeb0ec30
[]
no_license
commel/opencombat2005
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
d72fc2b0be12367af34d13c47064f31d55b7a8e0
refs/heads/master
2023-05-19T05:18:54.728752
2005-12-01T05:11:44
2005-12-01T05:11:44
375,630,282
0
0
null
null
null
null
UTF-8
C++
false
false
7,269
cpp
#include <direct.h> #include <stdio.h> #include <misc\Array.h> /** * This file parses and extracts roof tile images from close combat * .rfm files. */ struct Point { int x, y; }; struct Roof { // A boundary for collision detection Array<Point> Boundary; // The upper left corner for rendering Point UpperLeft; // The lower right corner for rendering Point LowerRight; // The width and height of the graphic int Width, Height; // The location of the graphic data in the file long ExteriorDataStart; long InteriorDataStart; }; static void print_roof(Roof *roof, int roofNum); static void export_tga(char *fileName, unsigned char *data, int dataLength, int width, int height, int pad); int main(int argc, char *argv[]) { char fileName[256]; if(argc != 3) { printf("Usage: RoofExtractor <rfm file> <map name>\n"); return -1; } // Let's make a directory for the roof graphics _mkdir("building_graphics"); // The xml file that we are creating sprintf(fileName, "%s.buildings.xml", argv[2]); FILE *xml = fopen(fileName, "w"); fprintf(xml, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); fprintf(xml, "<Buildings>\n"); // The rfm file that we are reading FILE *fp = fopen(argv[1], "rb"); // Let's read the number of maps that are in this file fseek(fp, 4L, SEEK_SET); int numRoofs = 0; fread(&numRoofs, sizeof(int), 1, fp); for(int i = 0; i < numRoofs; ++i) { Roof *roof = new Roof(); // Seek to the beginning of our header section for this roof fseek(fp, 20 + i*132, SEEK_SET); // Read in the number of boundary points int numBoundaryPoints=0; fread(&numBoundaryPoints, sizeof(int), 1, fp); // Read in each of these points for(int j = 0; j < numBoundaryPoints; ++j) { Point *p = new Point(); fread(&(p->x), sizeof(p->x), 1, fp); fread(&(p->y), sizeof(p->y), 1, fp); roof->Boundary.Add(p); } // Now we need to read in our extents fseek(fp, 20 + i*132 + 100, SEEK_SET); // Read in the width of a scanline. The scanline's seem to be terminated // with 00 00 on DWORD boundaries, so let's eliminate that int scanlineWidth = 0; fread(&scanlineWidth, sizeof(scanlineWidth), 1, fp); // Let's read in the upper left and lower right corners fread(&(roof->UpperLeft.x), sizeof(roof->UpperLeft.x), 1, fp); fread(&(roof->UpperLeft.y), sizeof(roof->UpperLeft.y), 1, fp); fread(&(roof->LowerRight.x), sizeof(roof->LowerRight.x), 1, fp); fread(&(roof->LowerRight.y), sizeof(roof->LowerRight.y), 1, fp); // Let's read in the start and the end of the data segment for this roof fread(&(roof->ExteriorDataStart), sizeof(roof->ExteriorDataStart), 1, fp); fread(&(roof->InteriorDataStart), sizeof(roof->InteriorDataStart), 1, fp); // Set the width and the height of our graphic roof->Width = scanlineWidth >> 1; roof->Height = (roof->InteriorDataStart - roof->ExteriorDataStart) / scanlineWidth; // Let's export this roof to our xml file fprintf(xml, "\t<Building>\n"); // Do the Boundary first fprintf(xml, "\t\t<!-- Used for interior detection, in map coordinates -->\n"); fprintf(xml, "\t\t<Boundary>\n"); for(int j = 0; j < roof->Boundary.Count; ++j) { fprintf(xml, "\t\t\t<Point><X>%d</X><Y>%d</Y></Point>\n", roof->Boundary.Items[j]->x, roof->Boundary.Items[j]->y); } fprintf(xml, "\t\t</Boundary>\n"); // Now the upper left corner in map coordinates fprintf(xml, "\t\t<!-- The Upper Left Corner, in map coordinates -->\n"); fprintf(xml, "\t\t<Position><X>%d</X><Y>%d</Y></Position>\n", roof->UpperLeft.x, roof->UpperLeft.y); // Now the interior and exterior graphics sprintf(fileName, "%s\\roof_graphics\\exterior_%03d.tga", argv[2], i); fprintf(xml, "\t\t<ExteriorGraphic>%s</ExteriorGraphic>\n", fileName); sprintf(fileName, "%s\\roof_graphics\\interior_%03d.tga", argv[2], i); fprintf(xml, "\t\t<InteriorGraphic>%s</InteriorGraphic>\n", fileName); fprintf(xml, "\t</Building>\n"); // Let's export the interior and exterior grapics int dataLength = roof->InteriorDataStart - roof->ExteriorDataStart; unsigned char *graphicData = new unsigned char[dataLength]; // Exterior graphic int pad = 4 - ((roof->LowerRight.x-roof->UpperLeft.x)%4); pad = (pad == 4) ? 0 : pad; fseek(fp, roof->ExteriorDataStart, SEEK_SET); fread(graphicData, 1, dataLength, fp); sprintf(fileName, "roof_graphics\\exterior_%03d.tga", i); export_tga(fileName, graphicData, dataLength, roof->Width, roof->Height, pad); // Interior graphic fseek(fp, roof->InteriorDataStart, SEEK_SET); fread(graphicData, 1, dataLength, fp); sprintf(fileName, "roof_graphics\\interior_%03d.tga", i); export_tga(fileName, graphicData, dataLength, roof->Width, roof->Height, pad); delete graphicData; // Print out what we found print_roof(roof, i); } fprintf(xml, "</Buildings>\n"); fclose(fp); fclose(xml); return 0; } typedef struct { char idlength; char colourmaptype; char datatypecode; short int colourmaporigin; short int colourmaplength; char colourmapdepth; short int x_origin; short int y_origin; short width; short height; char bitsperpixel; char imagedescriptor; } TGAHeader; void export_tga(char *fileName, unsigned char *data, int dataLength, int width, int height, int pad) { TGAHeader header; memset(&header, 0, sizeof(TGAHeader)); header.datatypecode = 2; // RGB header.width = width-pad; header.height = height; header.bitsperpixel = 16; //header.imagedescriptor = 1; FILE *fp = fopen(fileName, "wb"); // Write the header fwrite(&header.idlength, 1, 1, fp); fwrite(&header.colourmaptype, 1, 1, fp); fwrite(&header.datatypecode, 1, 1, fp); fwrite(&header.colourmaporigin, 2, 1, fp); fwrite(&header.colourmaplength, 2, 1, fp); fwrite(&header.colourmapdepth, 1, 1, fp); fwrite(&header.x_origin, 2, 1, fp); fwrite(&header.y_origin, 2, 1, fp); fwrite(&header.width, 2, 1, fp); fwrite(&header.height, 2, 1, fp); fwrite(&header.bitsperpixel, 1, 1, fp); fwrite(&header.imagedescriptor, 1, 1, fp); // Now write the data. Remember, our stupid image has a 00 00 // at the end of each scanline that we do not want to include unsigned short *sdata = (unsigned short *)data; unsigned short pixel = 0; for(int j = height-1; j >= 0; --j) { for(int i = 0; i < width-pad; ++i) { pixel = sdata[j*width+i]; fwrite(&pixel, sizeof(short), 1, fp); } } fclose(fp); } void print_roof(Roof *roof, int roofNum) { printf("Roof %d:\n", roofNum); printf("\tWidth = %d\n", roof->Width); printf("\tHeight = %d\n", roof->Height); printf("\tExterior Start = %d\n", roof->ExteriorDataStart); printf("\tInterior End = %d\n", roof->InteriorDataStart); printf("\tUpper Left = {%d, %d}\n", roof->UpperLeft.x, roof->UpperLeft.y); printf("\tLower Right = {%d, %d}\n", roof->LowerRight.x, roof->LowerRight.y); printf("\tBoundary:\n"); for(int i = 0; i < roof->Boundary.Count; ++i) { printf("\t\t{%d, %d}\n", roof->Boundary.Items[i]->x, roof->Boundary.Items[i]->y); } }
[ "opencombat" ]
[ [ [ 1, 231 ] ] ]
9f439352d0df8a194ace40cf6b57b9f55a0dfc7a
23e9e5636c692364688bc9e4df59cb68e2447a58
/Dream/include/YGERenderer.h
e283bc2821d6dbb2292ac5941977ce092e95f9d2
[]
no_license
yestein/dream-of-idle
e492af2a4758776958b43e4bf0e4db859a224c40
4e362ab98f232d68535ea26f2fab7b3cbf7bc867
refs/heads/master
2016-09-09T19:49:18.215943
2010-04-23T07:24:19
2010-04-23T07:24:19
34,108,886
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
h
/************************************************************************ Copyright (c) Yu Lei. All rights reserved. filename: YGERender.h created: 2010/3/23 author: Yu Lei([email protected]) <change list> 1. create file (Yu Lei) purpose: Create a Render ************************************************************************/ #ifndef YGE_RENDER_H #define YGE_RENDER_H //----------------------------------------------------------------------- #include "YGEDirectX.h" //------------------------------------------------------------------------ class YGERenderer { public: YGERenderer( ); ~YGERenderer( ){ } virtual bool Initialise( void ) = 0; virtual bool DoRender( float timeElapse ) = 0; virtual void Release( void ) = 0; virtual bool BeginScene( void ) = 0; virtual void EndScene( void ) = 0; HWND GetWndOwner ( void ){ return m_wndOwner; } bool IsWindowed ( void ){ return m_bWindowed; } unsigned int GetScreenWidth ( void ){ return m_uScreenWidth; } unsigned int GetScreenHeight( void ){ return m_uScreenHeight; } unsigned int GetBitCount ( void ){ return m_uBitCount; } void SetWndOwner ( HWND hwnd ){ m_wndOwner = hwnd; } void SetWindowed ( bool windowed ){ m_bWindowed = windowed; } void SetScreenWidth ( unsigned int width ){ m_uScreenWidth = width; } void SetScreenHeight ( unsigned int height ){ m_uScreenHeight = height; } void SetBitCount ( unsigned int bitCount ){ m_uBitCount = bitCount; } protected: HWND m_wndOwner; bool m_bWindowed; unsigned int m_uScreenWidth; unsigned int m_uScreenHeight; unsigned int m_uBitCount; private: private: }; //------YGE_RENDER_H----------------------------------------------------- #endif
[ "yestein86@6bb0ce84-d3d1-71f5-47c4-2d9a3e80541b" ]
[ [ [ 1, 61 ] ] ]
3f50697fe7e498df376c1bdbeec06e86020e98ab
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/Practise_2005/dshow.texture.3d9/DShowTextures.h
483c37e95ce6d154fe181d15c57c0befae7a631b
[]
no_license
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
UTF-8
C++
false
false
1,725
h
//----------------------------------------------------------------------------- // File: DShowTextures.h // // Desc: DirectShow sample code - adds support for DirectShow videos playing // on a DirectX 8.0 texture surface. Turns the D3D texture tutorial into // a recreation of the VideoTex sample from previous versions of DirectX. // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #pragma once #include <streams.h> #include <d3d9.h> //----------------------------------------------------------------------------- // Define GUID for Texture Renderer // {71771540-2017-11cf-AE26-0020AFD79767} //----------------------------------------------------------------------------- struct __declspec(uuid("{71771540-2017-11cf-ae26-0020afd79767}")) CLSID_TextureRenderer; //----------------------------------------------------------------------------- // CTextureRenderer Class Declarations //----------------------------------------------------------------------------- class CTextureRenderer : public CBaseVideoRenderer { public: CTextureRenderer(LPUNKNOWN pUnk,HRESULT *phr); ~CTextureRenderer(); public: virtual HRESULT CheckMediaType(const CMediaType *pmt ); // Format acceptable? virtual HRESULT SetMediaType(const CMediaType *pmt ); // Video format notification virtual HRESULT DoRenderSample(IMediaSample *pMediaSample); // New video sample private: BOOL m_bUseDynamicTextures; LONG m_lVidWidth; // Video width LONG m_lVidHeight; // Video Height LONG m_lVidPitch; // Video Pitch D3DFORMAT mTextureFormat; // Texture format };
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 45 ] ] ]
cb9c0276a8ab140989e3841b4797334f20bd9168
1736474d707f5c6c3622f1cd370ce31ac8217c12
/Pseudo/Lock.hpp
bc5a3b652a4de5eb5c04e4a6f38edb2aca7868b5
[]
no_license
arlm/pseudo
6d7450696672b167dd1aceec6446b8ce137591c0
27153e50003faff31a3212452b1aec88831d8103
refs/heads/master
2022-11-05T23:38:08.214807
2011-02-18T23:18:36
2011-02-18T23:18:36
275,132,368
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
hpp
// Copyright (c) John Lyon-Smith. All rights reserved. #pragma once #include <Pseudo\Compiler.hpp> #include <Pseudo\Exception.hpp> namespace Pseudo { class Lock { public: Lock(int spinCount = 0) { if (!InitializeCriticalSectionAndSpinCount(&m_cs, (DWORD)spinCount)) throw Win32Exception(GetLastError()); } public: ~Lock() { DeleteCriticalSection(&m_cs); } public: void Enter() { EnterCriticalSection(&m_cs); } public: bool TryEnter() throw() { return TryEnterCriticalSection(&m_cs) == TRUE; } public: void Leave() throw() { LeaveCriticalSection(&m_cs); } public: class Auto { public: Auto(Lock& cs) throw() { m_pcs = &cs; m_pcs->Enter(); } public: ~Auto() throw() { m_pcs->Leave(); } private: Lock *m_pcs; // Make non-copyable private: Auto(Auto const &); private: int operator=(Auto const &); }; protected: CRITICAL_SECTION m_cs; private: Lock(Lock const &); private: int operator=(Lock const &); }; }
[ [ [ 1, 62 ] ] ]
82a5cb5ee0a9ef9204e9c9977fb84608dc0336e6
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/actor/erase_at_test.cpp
d5b52a797b6211d87e35eb0394f1dc240de26de2
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,704
cpp
/*============================================================================= Copyright (c) 2003 Jonathan de Halleux ([email protected]) http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // Test suite for push_front_actor, pop_front_actor /////////////////////////////////////////////////////////////////////////////// #include "action_tests.hpp" #include <boost/spirit/core.hpp> #include <boost/spirit/actor/erase_actor.hpp> #include <map> void erase_action_test() { using namespace boost::spirit; const char* cp = "one,two,three"; const char* cp_first = cp; const char* cp_last = cp + test_impl::string_length(cp); const char* cp_i[] = {"one","two","three"}; typedef std::map<std::string, int> map_string_type; map_string_type c; map_string_type::const_iterator it_find; scanner<char const*> scan(cp_first, cp_last); match<> hit; c["one"]=1; c["two"]=2; c["three"]=3; c["four"]=4; hit = (*((+alpha_p)[ erase_a(c) ] >> !ch_p(','))).parse(scan); BOOST_CHECK(hit); BOOST_CHECK_EQUAL(scan.first, scan.last); BOOST_CHECK_EQUAL( c.size(), static_cast<map_string_type::size_type>(1)); for (int i=0;i<3;++i) { it_find = c.find(cp_i[i]); BOOST_CHECK( it_find == c.end() ); } scan.first = cp; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 54 ] ] ]
edd29ce7ea189d7ab98e2fbfc3feec5fb0813fd0
d71665b4e115bbf0abc680bb1c7eb31e69d86a1d
/SpacescapePlugin/include/ticpprc.h
278297e77a31168313def8116b9847d353bd05ab
[ "MIT" ]
permissive
svenstaro/Spacescape
73c140d06fe4ae76ac1a613295f1e9f96cdda3bb
5a53ba43f8e4e78ca32ee5bb3d396ca7b0b71f7d
refs/heads/master
2021-01-02T09:08:59.624369
2010-04-05T04:28:57
2010-04-05T04:28:57
589,597
7
6
null
null
null
null
UTF-8
C++
false
false
3,155
h
/* http://code.google.com/p/ticpp/ Copyright (c) 2006 Ryan Pusztai, Ryan Mulder 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. */ #ifdef TIXML_USE_TICPP #ifndef TICPPRC_INCLUDED #define TICPPRC_INCLUDED #include <vector> // Forward declare ticpp::Node, so it can be made a friend of TiCppRC namespace ticpp { class Base; } // Forward declare TiCppRCImp so TiCppRC can hold a pointer to it class TiCppRCImp; /** Base class for reference counting functionality */ class TiCppRC { // Allow ticpp::Node to directly modify reference count friend class ticpp::Base; private: TiCppRCImp* m_tiRC; /**< Pointer to reference counter */ public: /** Constructor Spawns new reference counter with a pointer to this */ TiCppRC(); /** Destructor Nullifies the pointer to this held by the reference counter Decrements reference count */ virtual ~TiCppRC(); std::vector< ticpp::Base* > m_spawnedWrappers; /**< Remember all wrappers that we've created with 'new' - ( e.g. NodeFactory, FirstChildElement, etc. )*/ /** Delete all container objects we've spawned with 'new'. */ void DeleteSpawnedWrappers(); }; class TiCppRCImp { private: int m_count; /**< Holds reference count to me, and to the node I point to */ TiCppRC* m_tiCppRC; /**< Holds pointer to an object inheriting TiCppRC */ public: /** Initializes m_tiCppRC pointer, and set reference count to 1 */ TiCppRCImp( TiCppRC* tiCppRC ); /** Allows the TiCppRC object to set the pointer to itself ( m_tiCppRc ) to NULL when the TiCppRC object is deleted */ void Nullify(); /** Increment Reference Count */ void IncRef(); /** Decrement Reference Count */ void DecRef(); /** Set Reference Count to 1 - dangerous! - Use only if you are sure of the consequences */ void InitRef(); /** Get internal pointer to the TiCppRC object - not reference counted, use at your own risk */ TiCppRC* Get(); /** Returns state of internal pointer - will be null if the object was deleted */ bool IsNull(); }; #endif // TICPP_INCLUDED #endif // TIXML_USE_TICPP
[ [ [ 1, 122 ] ] ]
7ece752a44f8e3c589f3da61715b49855a527cf0
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/WORLDSERVER/MiniGameStopwatch.h
a912336117ec44c91212c3c9bff58899405b41bd
[]
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
501
h
#pragma once #if __VER >= 13 // __RAINBOW_RACE #include "minigamebase.h" class CMiniGameStopwatch : public CMiniGameBase { public: CMiniGameStopwatch(void); CMiniGameStopwatch( CMiniGameBase* pMiniGame ); virtual ~CMiniGameStopwatch(void); virtual BOOL Excute( CUser* pUser, __MINIGAME_PACKET* pMiniGamePacket ); private: int SetTargetTime(); // 소수점 2자리 까지 int GetTargetTime() { return m_nTargetTime; } int m_nTargetTime; }; #endif // __RAINBOW_RACE
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 22 ] ] ]
26e93b12d0d01e3f9476f4606e309cb08c75d69d
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/thread/src/recursive_mutex.cpp
c32c171ab7fdd2b8de5e00855e8fb671b1074944
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
22,836
cpp
// Copyright (C) 2001-2003 // William E. Kempf // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. William E. Kempf makes no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. #include <boost/thread/detail/config.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/xtime.hpp> #include <boost/thread/thread.hpp> #include <boost/limits.hpp> #include <string> #include <stdexcept> #include <cassert> #include "timeconv.inl" #if defined(BOOST_HAS_WINTHREADS) # include <new> # include <boost/thread/once.hpp> # include <windows.h> # include <time.h> # include "mutex.inl" #elif defined(BOOST_HAS_PTHREADS) # include <errno.h> #elif defined(BOOST_HAS_MPTASKS) # include <MacErrors.h> # include "safe.hpp" #endif namespace boost { #if defined(BOOST_HAS_WINTHREADS) recursive_mutex::recursive_mutex() : m_mutex(0) , m_critical_section(false) , m_count(0) { m_critical_section = true; if (m_critical_section) m_mutex = new_critical_section(); else m_mutex = new_mutex(0); } recursive_mutex::~recursive_mutex() { if (m_critical_section) delete_critical_section(m_mutex); else delete_mutex(m_mutex); } void recursive_mutex::do_lock() { if (m_critical_section) wait_critical_section_infinite(m_mutex); else wait_mutex(m_mutex, INFINITE); if (++m_count > 1) { if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } } void recursive_mutex::do_unlock() { if (--m_count == 0) { if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } } void recursive_mutex::do_lock(cv_state& state) { if (m_critical_section) wait_critical_section_infinite(m_mutex); else wait_mutex(m_mutex, INFINITE); m_count = state; } void recursive_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } recursive_try_mutex::recursive_try_mutex() : m_mutex(0) , m_critical_section(false) , m_count(0) { m_critical_section = has_TryEnterCriticalSection(); if (m_critical_section) m_mutex = new_critical_section(); else m_mutex = new_mutex(0); } recursive_try_mutex::~recursive_try_mutex() { if (m_critical_section) delete_critical_section(m_mutex); else delete_mutex(m_mutex); } void recursive_try_mutex::do_lock() { if (m_critical_section) wait_critical_section_infinite(m_mutex); else wait_mutex(m_mutex, INFINITE); if (++m_count > 1) { if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } } bool recursive_try_mutex::do_trylock() { bool res = false; if (m_critical_section) res = wait_critical_section_try(m_mutex); else res = wait_mutex(m_mutex, 0) == WAIT_OBJECT_0; if (res) { if (++m_count > 1) { if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } return true; } return false; } void recursive_try_mutex::do_unlock() { if (--m_count == 0) { if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } } void recursive_try_mutex::do_lock(cv_state& state) { if (m_critical_section) wait_critical_section_infinite(m_mutex); else wait_mutex(m_mutex, INFINITE); m_count = state; } void recursive_try_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; if (m_critical_section) release_critical_section(m_mutex); else release_mutex(m_mutex); } recursive_timed_mutex::recursive_timed_mutex() : m_mutex(0) , m_count(0) { m_mutex = new_mutex(0); } recursive_timed_mutex::~recursive_timed_mutex() { delete_mutex(m_mutex); } void recursive_timed_mutex::do_lock() { wait_mutex(m_mutex, INFINITE); if (++m_count > 1) release_mutex(m_mutex); } bool recursive_timed_mutex::do_trylock() { bool res = wait_mutex(m_mutex, 0) == WAIT_OBJECT_0; if (res) { if (++m_count > 1) release_mutex(m_mutex); return true; } return false; } bool recursive_timed_mutex::do_timedlock(const xtime& xt) { for (;;) { int milliseconds; to_duration(xt, milliseconds); unsigned int res = wait_mutex(m_mutex, milliseconds); if (res == WAIT_TIMEOUT) { xtime cur; xtime_get(&cur, TIME_UTC); if (xtime_cmp(xt, cur) > 0) continue; } if (res == WAIT_OBJECT_0) { if (++m_count > 1) release_mutex(m_mutex); return true; } return false; } } void recursive_timed_mutex::do_unlock() { if (--m_count == 0) release_mutex(m_mutex); } void recursive_timed_mutex::do_lock(cv_state& state) { wait_mutex(m_mutex, INFINITE); m_count = state; } void recursive_timed_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; release_mutex(m_mutex); } #elif defined(BOOST_HAS_PTHREADS) recursive_mutex::recursive_mutex() : m_count(0) # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) , m_valid_id(false) # endif { pthread_mutexattr_t attr; int res = pthread_mutexattr_init(&attr); assert(res == 0); # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); assert(res == 0); # endif res = pthread_mutex_init(&m_mutex, &attr); { int res = pthread_mutexattr_destroy(&attr); assert(res == 0); } if (res != 0) throw thread_resource_error(); # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_cond_init(&m_unlocked, 0); if (res != 0) { pthread_mutex_destroy(&m_mutex); throw thread_resource_error(); } # endif } recursive_mutex::~recursive_mutex() { int res = 0; res = pthread_mutex_destroy(&m_mutex); assert(res == 0); # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_cond_destroy(&m_unlocked); assert(res == 0); # endif } void recursive_mutex::do_lock() { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) if (++m_count > 1) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } # else pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) ++m_count; else { while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = tid; m_valid_id = true; m_count = 1; } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } void recursive_mutex::do_unlock() { # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) if (--m_count == 0) { int res = 0; res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } # else int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); pthread_t tid = pthread_self(); if (m_valid_id && !pthread_equal(m_thread_id, tid)) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); throw lock_error(); } if (--m_count == 0) { assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } void recursive_mutex::do_lock(cv_state& state) { # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) m_count = state.count; # else int res = 0; while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = pthread_self(); m_valid_id = true; m_count = state.count; res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } void recursive_mutex::do_unlock(cv_state& state) { # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); # endif state.pmutex = &m_mutex; state.count = m_count; m_count = 0; } recursive_try_mutex::recursive_try_mutex() : m_count(0) # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) , m_valid_id(false) # endif { pthread_mutexattr_t attr; int res = pthread_mutexattr_init(&attr); assert(res == 0); # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); assert(res == 0); # endif res = pthread_mutex_init(&m_mutex, &attr); { int res = pthread_mutexattr_destroy(&attr); assert(res == 0); } if (res != 0) throw thread_resource_error(); # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_cond_init(&m_unlocked, 0); if (res != 0) { pthread_mutex_destroy(&m_mutex); throw thread_resource_error(); } # endif } recursive_try_mutex::~recursive_try_mutex() { int res = 0; res = pthread_mutex_destroy(&m_mutex); assert(res == 0); # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) res = pthread_cond_destroy(&m_unlocked); assert(res == 0); # endif } void recursive_try_mutex::do_lock() { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) if (++m_count > 1) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } # else pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) ++m_count; else { while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = tid; m_valid_id = true; m_count = 1; } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } bool recursive_try_mutex::do_trylock() { # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) int res = 0; res = pthread_mutex_trylock(&m_mutex); assert(res == 0); if (res == 0) { if (++m_count > 1) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } return true; } return false; # else int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); bool ret = false; pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) { ++m_count; ret = true; } else if (!m_valid_id) { m_thread_id = tid; m_valid_id = true; m_count = 1; ret = true; } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); return ret; # endif } void recursive_try_mutex::do_unlock() { # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) if (--m_count == 0) { int res = 0; res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } # else int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); pthread_t tid = pthread_self(); if (m_valid_id && !pthread_equal(m_thread_id, tid)) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); throw lock_error(); } if (--m_count == 0) { assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } void recursive_try_mutex::do_lock(cv_state& state) { # if defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) m_count = state.count; # else int res = 0; while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = pthread_self(); m_valid_id = true; m_count = state.count; res = pthread_mutex_unlock(&m_mutex); assert(res == 0); # endif } void recursive_try_mutex::do_unlock(cv_state& state) { # if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE) int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); # endif state.pmutex = &m_mutex; state.count = m_count; m_count = 0; } recursive_timed_mutex::recursive_timed_mutex() : m_valid_id(false), m_count(0) { int res = 0; res = pthread_mutex_init(&m_mutex, 0); if (res != 0) throw thread_resource_error(); res = pthread_cond_init(&m_unlocked, 0); if (res != 0) { pthread_mutex_destroy(&m_mutex); throw thread_resource_error(); } } recursive_timed_mutex::~recursive_timed_mutex() { int res = 0; res = pthread_mutex_destroy(&m_mutex); assert(res == 0); res = pthread_cond_destroy(&m_unlocked); assert(res == 0); } void recursive_timed_mutex::do_lock() { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) ++m_count; else { while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = tid; m_valid_id = true; m_count = 1; } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } bool recursive_timed_mutex::do_trylock() { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); bool ret = false; pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) { ++m_count; ret = true; } else if (!m_valid_id) { m_thread_id = tid; m_valid_id = true; m_count = 1; ret = true; } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); return ret; } bool recursive_timed_mutex::do_timedlock(const xtime& xt) { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); bool ret = false; pthread_t tid = pthread_self(); if (m_valid_id && pthread_equal(m_thread_id, tid)) { ++m_count; ret = true; } else { timespec ts; to_timespec(xt, ts); while (m_valid_id) { res = pthread_cond_timedwait(&m_unlocked, &m_mutex, &ts); if (res == ETIMEDOUT) break; assert(res == 0); } if (!m_valid_id) { m_thread_id = tid; m_valid_id = true; m_count = 1; ret = true; } } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); return ret; } void recursive_timed_mutex::do_unlock() { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); pthread_t tid = pthread_self(); if (m_valid_id && !pthread_equal(m_thread_id, tid)) { res = pthread_mutex_unlock(&m_mutex); assert(res == 0); throw lock_error(); } if (--m_count == 0) { assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); } res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } void recursive_timed_mutex::do_lock(cv_state& state) { int res = 0; while (m_valid_id) { res = pthread_cond_wait(&m_unlocked, &m_mutex); assert(res == 0); } m_thread_id = pthread_self(); m_valid_id = true; m_count = state.count; res = pthread_mutex_unlock(&m_mutex); assert(res == 0); } void recursive_timed_mutex::do_unlock(cv_state& state) { int res = 0; res = pthread_mutex_lock(&m_mutex); assert(res == 0); assert(m_valid_id); m_valid_id = false; res = pthread_cond_signal(&m_unlocked); assert(res == 0); state.pmutex = &m_mutex; state.count = m_count; m_count = 0; } #elif defined(BOOST_HAS_MPTASKS) using threads::mac::detail::safe_enter_critical_region; recursive_mutex::recursive_mutex() : m_count(0) { } recursive_mutex::~recursive_mutex() { } void recursive_mutex::do_lock() { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } void recursive_mutex::do_unlock() { if (--m_count == 0) { OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } void recursive_mutex::do_lock(cv_state& state) { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); m_count = state; } void recursive_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } recursive_try_mutex::recursive_try_mutex() : m_count(0) { } recursive_try_mutex::~recursive_try_mutex() { } void recursive_try_mutex::do_lock() { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } bool recursive_try_mutex::do_trylock() { OSStatus lStatus = noErr; lStatus = MPEnterCriticalRegion(m_mutex, kDurationImmediate); assert(lStatus == noErr || lStatus == kMPTimeoutErr); if (lStatus == noErr) { if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } return true; } return false; } void recursive_try_mutex::do_unlock() { if (--m_count == 0) { OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } void recursive_try_mutex::do_lock(cv_state& state) { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); m_count = state; } void recursive_try_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } recursive_timed_mutex::recursive_timed_mutex() : m_count(0) { } recursive_timed_mutex::~recursive_timed_mutex() { } void recursive_timed_mutex::do_lock() { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } bool recursive_timed_mutex::do_trylock() { OSStatus lStatus = noErr; lStatus = MPEnterCriticalRegion(m_mutex, kDurationImmediate); assert(lStatus == noErr || lStatus == kMPTimeoutErr); if (lStatus == noErr) { if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } return true; } return false; } bool recursive_timed_mutex::do_timedlock(const xtime& xt) { int microseconds; to_microduration(xt, microseconds); Duration lDuration = kDurationMicrosecond * microseconds; OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, lDuration, m_mutex_mutex); assert(lStatus == noErr || lStatus == kMPTimeoutErr); if (lStatus == noErr) { if (++m_count > 1) { lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } return true; } return false; } void recursive_timed_mutex::do_unlock() { if (--m_count == 0) { OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } } void recursive_timed_mutex::do_lock(cv_state& state) { OSStatus lStatus = noErr; lStatus = safe_enter_critical_region(m_mutex, kDurationForever, m_mutex_mutex); assert(lStatus == noErr); m_count = state; } void recursive_timed_mutex::do_unlock(cv_state& state) { state = m_count; m_count = 0; OSStatus lStatus = noErr; lStatus = MPExitCriticalRegion(m_mutex); assert(lStatus == noErr); } #endif } // namespace boost // Change Log: // 8 Feb 01 WEKEMPF Initial version.
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 1043 ] ] ]
d11fb3bb5012d932ffbab9138106ba6382a66c22
bbc02822aeffdfaa8050907c1d9bd41ff4e9f3f3
/MinecraftPSP/MinecraftPSP/World.cpp
1d0f7fb7bb6a145082e10290cf0ee22d87d13ccb
[]
no_license
DragonNeos/minecraft-psp
5184361c0beab2a4a25d789ba24a5cf185ef18cf
fde4e012c8ecc94f52bf222738f29e5efac47d0e
refs/heads/master
2020-03-26T15:06:44.654834
2011-03-01T09:38:49
2011-03-01T09:38:49
40,795,370
0
0
null
null
null
null
UTF-8
C++
false
false
2,556
cpp
//Author: Mouhamad Abdallah //Date: Tuesday 8th February 2011 //Description: Loads and manages an entire world - The blocks of the world are created here #include <stdlib.h> //Header File for standard library #include "World.h" //Header File for 'World' class #include "GLLib.h" World::World() //Default/Empty Constructor { } void World::initialiseWorld(int worldLimit, int blockSide, short *&blockID) //Initialises the world creating and populating the 3D Array { this->worldSize = worldLimit; this->blockSize = blockSide; world = new Cube**[worldSize]; //Initialise the 1st Dimension for(int j = 0; j < worldSize; j++) { world[j] = new Cube*[worldSize]; //Initialise the 2nd Dimension for(int k = 0; k < worldSize; k ++) { world[j][k] = new Cube[worldSize]; //Initialise the 3rd Dimension } } for(int i = 0, y = 0, blockNumber = 0; i < worldSize; i++, y += blockSize) //Initialise and dynamically allocate a 3D PointerArray of new cube objects { for(int j = 0, z = 0; j < worldSize; j++, z+= blockSize) { for(int k = 0, x = 0; k < worldSize; k ++, x+=blockSize, blockNumber++) { world[i][j][k].initialise(blockSize, blockSize, blockSize); //Instantiate a new object and assign it via dynamic memory allocation world[i][j][k].createBlock(blockID[blockNumber]); //Create the block based off it's type ID world[i][j][k].position->set(x, y, z); //Position the cubes apart from each other in order of theyre relative co-ordinates in the array } } } } short World::returnBlock(int x, int y, int z) //Returns the block type at the given position { return world[x][y][z].returnBlockType(); } void World::changeBlock(int x, int y, int z, short blockType) //Changes the block type at the given position { world[x][y][z].createBlock(blockType); } void World::draw(float rotation, float xR, float yR, float zR) //Draw function of the entire world with rotation matrix included { for(int x = 0; x < worldSize; x++) { for(int y = 0; y < worldSize; y++) { for(int z = 0; z < worldSize; z ++) { world[x][y][z].draw(rotation, xR, yR, zR);// Draw the 'World' array of cubes with rotation applied } } } } void World::draw(GLbyte* indices) //Draw function of the entire world { for(int x = 0; x < worldSize; x++) { for(int y = 0; y < worldSize; y++) { for(int z = 0; z < worldSize; z ++) { world[x][y][z].draw(indices);// Draw the 'World' array of cubes } } } }
[ [ [ 1, 79 ] ] ]
0ef9b7d15033afd83c016e006b7fa48c44e9b38c
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/NumericalAnalysis/Wm4Minimize1.h
21a9fa853355763ec99d72228f0546f210115bc4
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,436
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4MINIMIZE1_H #define WM4MINIMIZE1_H #include "Wm4FoundationLIB.h" #include "Wm4System.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM Minimize1 { public: typedef Real (*Function)(Real,void*); Minimize1 (Function oFunction, int iMaxLevel, int iMaxBracket, void* pvData = 0); int& MaxLevel (); int& MaxBracket (); void*& UserData (); void GetMinimum (Real fT0, Real fT1, Real fTInitial, Real& rfTMin, Real& rfFMin); private: Function m_oFunction; int m_iMaxLevel, m_iMaxBracket; Real m_fTMin, m_fFMin; void* m_pvData; void GetMinimum (Real fT0, Real fF0, Real fT1, Real fF1, int iLevel); void GetMinimum (Real fT0, Real fF0, Real fTm, Real fFm, Real fT1, Real fF1, int iLevel); void GetBracketedMinimum (Real fT0, Real fF0, Real fTm, Real fFm, Real fT1, Real fF1, int iLevel); }; typedef Minimize1<float> Minimize1f; typedef Minimize1<double> Minimize1d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 56 ] ] ]
5b6dc2c5e2581c8e08391dc702bb0a3f6100cdd2
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/TileEngine/physics.h
4597337410a2992bb07d4159bc3670db0d44b7ed
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,760
h
#ifndef __PHYSICS_H #define __PHYSICS_H #include "phys math.h" #include "sgp.h" #include "worlddef.h" #include "items.h" #include "Soldier Control.h" extern UINT32 guiNumObjectSlots; class OLD_REAL_OBJECT_101 { public: BOOLEAN fAllocated; BOOLEAN fAlive; BOOLEAN fApplyFriction; BOOLEAN fColliding; BOOLEAN fZOnRest; BOOLEAN fVisible; BOOLEAN fInWater; BOOLEAN fTestObject; BOOLEAN fTestEndedWithCollision; BOOLEAN fTestPositionNotSet; real TestZTarget; real OneOverMass; real AppliedMu; vector_3 Position; vector_3 TestTargetPosition; vector_3 OldPosition; vector_3 Velocity; vector_3 OldVelocity; vector_3 InitialForce; vector_3 Force; vector_3 CollisionNormal; vector_3 CollisionVelocity; real CollisionElasticity; INT32 sGridNo; INT32 iID; LEVELNODE *pNode; LEVELNODE *pShadow; INT16 sConsecutiveCollisions; INT16 sConsecutiveZeroVelocityCollisions; INT32 iOldCollisionCode; FLOAT dLifeLength; FLOAT dLifeSpan; OLD_OBJECTTYPE_101 oldObj; BOOLEAN fFirstTimeMoved; INT32 sFirstGridNo; UINT8 ubOwner; UINT8 ubActionCode; UINT32 uiActionData; BOOLEAN fDropItem; UINT32 uiNumTilesMoved; BOOLEAN fCatchGood; BOOLEAN fAttemptedCatch; BOOLEAN fCatchAnimOn; BOOLEAN fCatchCheckDone; BOOLEAN fEndedWithCollisionPositionSet; vector_3 EndedWithCollisionPosition; BOOLEAN fHaveHitGround; BOOLEAN fPotentialForDebug; INT32 sLevelNodeGridNo; INT32 iSoundID; UINT8 ubLastTargetTakenDamage; UINT8 ubPadding[1]; }; class REAL_OBJECT { public: REAL_OBJECT () {initialize();}; REAL_OBJECT& operator=(OLD_REAL_OBJECT_101& src); BOOLEAN Load(HWFILE hFile); BOOLEAN Save(HWFILE hFile); void initialize(); BOOLEAN fAllocated; BOOLEAN fAlive; BOOLEAN fApplyFriction; BOOLEAN fColliding; BOOLEAN fZOnRest; BOOLEAN fVisible; BOOLEAN fInWater; BOOLEAN fTestObject; BOOLEAN fTestEndedWithCollision; BOOLEAN fTestPositionNotSet; real TestZTarget; real OneOverMass; real AppliedMu; vector_3 Position; vector_3 TestTargetPosition; vector_3 OldPosition; vector_3 Velocity; vector_3 OldVelocity; vector_3 InitialForce; vector_3 Force; vector_3 CollisionNormal; vector_3 CollisionVelocity; real CollisionElasticity; INT32 sGridNo; INT32 iID; LEVELNODE *pNode; LEVELNODE *pShadow; INT16 sConsecutiveCollisions; INT16 sConsecutiveZeroVelocityCollisions; INT32 iOldCollisionCode; FLOAT dLifeLength; FLOAT dLifeSpan; BOOLEAN fFirstTimeMoved; INT32 sFirstGridNo; UINT8 ubOwner; UINT8 ubActionCode; UINT32 uiActionData; BOOLEAN fDropItem; UINT32 uiNumTilesMoved; BOOLEAN fCatchGood; BOOLEAN fAttemptedCatch; BOOLEAN fCatchAnimOn; BOOLEAN fCatchCheckDone; BOOLEAN fEndedWithCollisionPositionSet; vector_3 EndedWithCollisionPosition; BOOLEAN fHaveHitGround; BOOLEAN fPotentialForDebug; INT32 sLevelNodeGridNo; INT32 iSoundID; UINT8 ubLastTargetTakenDamage; // OJW - 20091002 - mp explosives UINT8 mpTeam; // the intiating clients team INT32 mpRealObjectID; // ID from the initiating client bool mpIsFromRemoteClient; bool mpHaveClientResult; bool mpWasDud; char endOfPod; OBJECTTYPE Obj; }; #define SIZEOF_REAL_OBJECT_POD offsetof(REAL_OBJECT, endOfPod) #define NUM_OBJECT_SLOTS 50 extern REAL_OBJECT ObjectSlots[ NUM_OBJECT_SLOTS ]; // OBJECT LIST STUFF INT32 CreatePhysicalObject( OBJECTTYPE *pGameObj, real dLifeLength, real xPos, real yPos, real zPos, real xForce, real yForce, real zForce, UINT8 ubOwner, UINT8 ubActionCode, UINT32 uiActionData, BOOLEAN fTestObject ); BOOLEAN RemoveObjectSlot( INT32 iObject ); void RemoveAllPhysicsObjects( ); // OJW - 20091002 - mp explosives extern void HandleArmedObjectImpact( REAL_OBJECT *pObject ); FLOAT CalculateLaunchItemAngle( SOLDIERTYPE *pSoldier, INT32 sGridNo, UINT8 ubHeight, real dForce, OBJECTTYPE *pItem, INT32 *psGridNo ); BOOLEAN CalculateLaunchItemChanceToGetThrough( SOLDIERTYPE *pSoldier, OBJECTTYPE *pItem, INT32 sGridNo, UINT8 ubLevel, INT16 sEndZ, INT32 *psFinalGridNo, BOOLEAN fArmed, INT8 *pbLevel, BOOLEAN fFromUI ); void CalculateLaunchItemParamsForThrow( SOLDIERTYPE *pSoldier, INT32 sGridNo, UINT8 ubLevel, INT16 sZPos, OBJECTTYPE *pItem, INT8 bMissBy, UINT8 ubActionCode, UINT32 uiActionData ); // SIMULATE WORLD void SimulateWorld( ); BOOLEAN SavePhysicsTableToSaveGameFile( HWFILE hFile ); BOOLEAN LoadPhysicsTableFromSavedGameFile( HWFILE hFile ); #endif
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 185 ] ] ]
b3ca7b6dbd4f960d6619290711a309f8b5c94125
ffd731ace66892b070eac3abe27169bcb53cc989
/Rendering/Raytracer/raytrace/Accelerator.cpp
d807ccdfa1ecb9bc5624372de9b544daeb1356c0
[]
no_license
nical/DTU-school-projetcs
5496666a0de67312befc094ec070ce2897eaebc7
b9b4b6921838968e0f7370320f87244992f03989
refs/heads/master
2021-01-23T21:33:37.659374
2011-09-19T18:37:38
2011-09-19T18:37:38
2,361,393
0
0
null
null
null
null
UTF-8
C++
false
false
4,526
cpp
// 02562 Rendering Framework // Written by Jeppe Revall Frisvad, 2011 // Copyright (c) DTU Informatics 2011 #include <vector> #include <optix_world.h> #include "AccObj.h" #include "Object3D.h" #include "Plane.h" #include "HitInfo.h" #include "Accelerator.h" using namespace std; using namespace optix; Accelerator::~Accelerator() { for(unsigned int i = 0; i < primitives.size(); ++i) delete primitives[i]; } void Accelerator::init(const vector<Object3D*>& geometry, const vector<const Plane*>& scene_planes) { for(unsigned int i = 0; i < geometry.size(); ++i) { Object3D* obj = geometry[i]; unsigned int no_of_prims = primitives.size(); primitives.resize(no_of_prims + obj->get_no_of_primitives()); for(unsigned int j = 0; j < obj->get_no_of_primitives(); ++j) primitives[j + no_of_prims] = new AccObj(obj, j); } planes = scene_planes; } bool Accelerator::closest_hit(optix::Ray& r, HitInfo& hit) const { closest_plane(r, hit); // Use simple looping to find the closest intersection (if any). // Compute hit.position if the ray hit something. // // Input: r (the ray to be checked for intersection) // Output: hit (info about the ray-surface intersection) // Return: True if the ray intersects something, false otherwise // // Relevant data fields that are available (see Accelerator.h and OptiX math library reference) // primitives (array of primitive objects) // r.origin (ray origin) // r.direction (ray direction) // r.tmax (maximum intersection distance allowed) // // Hint: Call the intersect(...) function for each primitive // object in the scene. HitInfo tempHit; float closestDist = 99999999.0; //dirty :p if(hit.has_hit) { tempHit = hit; closestDist = hit.dist; } for( int i = 0; i < primitives.size(); ++i ) { //intersect(const optix::Ray& r, HitInfo& hit, unsigned int prim_idx) const; if( primitives[i]->geometry->intersect( r, tempHit, i ) ) { if( (tempHit.has_hit) && (tempHit.dist < closestDist) ) { hit = tempHit; closestDist = tempHit.dist; } } } return hit.has_hit; } bool Accelerator::any_hit(optix::Ray& r, HitInfo& hit) const { if(!any_plane(r, hit)) { // Loop over the primitive objects to check for intersection // until one or none is found. // // Input: r (the ray to be checked for intersection) // Output: hit (info about the ray-surface intersection) // Return: True if the ray intersects something, false otherwise // // Relevant data fields that are available (see Accelerator.h) // primitives (array of primitive objects) // // Hint: Use the intersect(...) function of the primitives. hit.has_hit = false; for ( int i = 0; i < primitives.size(); ++i) { if( primitives[i]->geometry->intersect( r, hit, i ) ) { hit.has_hit = true; return true; } } } return hit.has_hit; } void Accelerator::closest_plane(Ray& r, HitInfo& hit) const { // Call the intersect(...) function for all the planes separately. // // Input: r (the ray to be checked for intersection) // Output: hit (info about the ray-surface intersection) // // Relevant data fields that are available (see Accelerator.h) // planes (array of planes in the scene) HitInfo tempHit; float closestDist = 99999999.0; //dirty :p for( int i = 0; i < planes.size(); ++i ) { //intersect(const optix::Ray& r, HitInfo& hit, unsigned int prim_idx) const; if( planes[i]->intersect( r, tempHit, i ) ) { if( ( !tempHit.has_hit ) || (tempHit.dist < closestDist) ) { hit = tempHit; closestDist = tempHit.dist; } } } if( !tempHit.has_hit ) hit.has_hit = false; } bool Accelerator::any_plane(Ray& r, HitInfo& hit) const { // Check for intersection with planes separately. // // Input: r (the ray to be checked for intersection) // Output: hit (info about the ray-surface intersection) // Return: True if the ray intersects something, false otherwise // // Relevant data fields that are available (see Accelerator.h) // planes (array of planes in the scene) for( int i = 0; i < planes.size(); ++i ) { //intersect(const optix::Ray& r, HitInfo& hit, unsigned int prim_idx) const; if( planes[i]->intersect( r, hit, i ) ) { return true; } } return false; }
[ [ [ 1, 159 ] ] ]
0525d5c4babfd0c51dcd0c79c51db295dd2a9e5a
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/Matrix3x3.cpp
723100d2f1b5a9604f0494402d8195cea168227e
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,745
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: Matrix3x3.cpp Version: 0.01 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "Matrix3x3.h" #include "FuncSplit.h" namespace nGENE { // Initialize static members const Matrix3x3 Matrix3x3::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix3x3::Matrix3x3() { identity(); } //---------------------------------------------------------------------- Matrix3x3::Matrix3x3(float _m11, float _m12, float _m13, float _m21, float _m22, float _m23, float _m31, float _m32, float _m33) { set(_m11, _m12, _m13, _m21, _m22, _m23, _m31, _m32, _m33); } //---------------------------------------------------------------------- Matrix3x3::~Matrix3x3() { } //---------------------------------------------------------------------- void Matrix3x3::fromString(const string& _string) { vector <string> vecValues; FuncSplit <string> tokenizer; tokenizer(_string, vecValues, " ,;"); if(vecValues.size() == 9) { vector <string>::iterator iter = vecValues.begin(); for(uint i = 0; i < 9; ++i) m[i] = atof((iter++)->c_str()); } } //---------------------------------------------------------------------- string Matrix3x3::toString() { stringstream buffer; for(uint i = 0; i < 8; ++i) buffer << m[i] << " "; buffer << m[9]; return buffer.str(); } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 69 ] ] ]
69b6253fd02a63b498f1f6e237657ef76913e650
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qgridlayout.h
84dbd014ea91b2b17cbabdbadd0ddf14edf02e15
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,490
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGRIDLAYOUT_H #define QGRIDLAYOUT_H #include <QtGui/qlayout.h> #ifdef QT_INCLUDE_COMPAT #include <QtGui/qwidget.h> #endif #include <limits.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QGridLayoutPrivate; class Q_GUI_EXPORT QGridLayout : public QLayout { Q_OBJECT Q_DECLARE_PRIVATE(QGridLayout) QDOC_PROPERTY(int horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing) QDOC_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing) public: explicit QGridLayout(QWidget *parent); QGridLayout(); #ifdef QT3_SUPPORT QT3_SUPPORT_CONSTRUCTOR QGridLayout(QWidget *parent, int nRows , int nCols = 1, int border = 0, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QGridLayout(int nRows , int nCols = 1, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QGridLayout(QLayout *parentLayout, int nRows = 1, int nCols = 1, int spacing = -1, const char *name = 0); #endif ~QGridLayout(); QSize sizeHint() const; QSize minimumSize() const; QSize maximumSize() const; void setHorizontalSpacing(int spacing); int horizontalSpacing() const; void setVerticalSpacing(int spacing); int verticalSpacing() const; void setSpacing(int spacing); int spacing() const; void setRowStretch(int row, int stretch); void setColumnStretch(int column, int stretch); int rowStretch(int row) const; int columnStretch(int column) const; void setRowMinimumHeight(int row, int minSize); void setColumnMinimumWidth(int column, int minSize); int rowMinimumHeight(int row) const; int columnMinimumWidth(int column) const; int columnCount() const; int rowCount() const; QRect cellRect(int row, int column) const; #ifdef QT3_SUPPORT inline QT3_SUPPORT QRect cellGeometry(int row, int column) const {return cellRect(row, column);} #endif bool hasHeightForWidth() const; int heightForWidth(int) const; int minimumHeightForWidth(int) const; Qt::Orientations expandingDirections() const; void invalidate(); inline void addWidget(QWidget *w) { QLayout::addWidget(w); } void addWidget(QWidget *, int row, int column, Qt::Alignment = 0); void addWidget(QWidget *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = 0); void addLayout(QLayout *, int row, int column, Qt::Alignment = 0); void addLayout(QLayout *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = 0); void setOriginCorner(Qt::Corner); Qt::Corner originCorner() const; #ifdef QT3_SUPPORT inline QT3_SUPPORT void setOrigin(Qt::Corner corner) { setOriginCorner(corner); } inline QT3_SUPPORT Qt::Corner origin() const { return originCorner(); } #endif QLayoutItem *itemAt(int index) const; QLayoutItem *itemAtPosition(int row, int column) const; QLayoutItem *takeAt(int index); int count() const; void setGeometry(const QRect&); void addItem(QLayoutItem *item, int row, int column, int rowSpan = 1, int columnSpan = 1, Qt::Alignment = 0); void setDefaultPositioning(int n, Qt::Orientation orient); void getItemPosition(int idx, int *row, int *column, int *rowSpan, int *columnSpan); protected: #ifdef QT3_SUPPORT QT3_SUPPORT bool findWidget(QWidget* w, int *r, int *c); #endif void addItem(QLayoutItem *); private: Q_DISABLE_COPY(QGridLayout) #ifdef QT3_SUPPORT public: QT3_SUPPORT void expand(int rows, int cols); inline QT3_SUPPORT void addRowSpacing(int row, int minsize) { addItem(new QSpacerItem(0,minsize), row, 0); } inline QT3_SUPPORT void addColSpacing(int col, int minsize) { addItem(new QSpacerItem(minsize,0), 0, col); } inline QT3_SUPPORT void addMultiCellWidget(QWidget *w, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0) { addWidget(w, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); } inline QT3_SUPPORT void addMultiCell(QLayoutItem *l, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0) { addItem(l, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); } inline QT3_SUPPORT void addMultiCellLayout(QLayout *layout, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0) { addLayout(layout, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); } inline QT3_SUPPORT int numRows() const { return rowCount(); } inline QT3_SUPPORT int numCols() const { return columnCount(); } inline QT3_SUPPORT void setColStretch(int col, int stretch) {setColumnStretch(col, stretch); } inline QT3_SUPPORT int colStretch(int col) const {return columnStretch(col); } inline QT3_SUPPORT void setColSpacing(int col, int minSize) { setColumnMinimumWidth(col, minSize); } inline QT3_SUPPORT int colSpacing(int col) const { return columnMinimumWidth(col); } inline QT3_SUPPORT void setRowSpacing(int row, int minSize) {setRowMinimumHeight(row, minSize); } inline QT3_SUPPORT int rowSpacing(int row) const {return rowMinimumHeight(row); } #endif }; QT_END_NAMESPACE QT_END_HEADER #endif // QGRIDLAYOUT_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 176 ] ] ]
74386634e2c63c56270a026b1eea8880c070974f
b407e323eb85b469258b0c30892dc70b160ecdbc
/pinger/ping_result.h
59f5c591fd7dc06e35d510c5ba4f81cbad244c34
[]
no_license
vi-k/whoisalive.fromsvn
7f8acf1cc8f5573008327fb61b419ed0f1676f42
c77b9619d470291389c8938e7cab87674a09f654
refs/heads/master
2021-01-10T02:13:41.786614
2010-05-30T23:18:47
2010-05-30T23:18:47
44,526,121
0
0
null
null
null
null
UTF-8
C++
false
false
4,147
h
#ifndef PING_RESULT_H #define PING_RESULT_H #include "../common/my_time.h" #include "../common/my_http.h" #include "icmp_header.hpp" #include "ipv4_header.hpp" #include "string.h" #include <string> #include <sstream> #define PING_RESULT_VER 1 namespace pinger { /* Результат отдельного ping'а */ class ping_result { public: enum state_t {unknown, ok, timeout}; private: state_t state_; posix_time::ptime time_; posix_time::time_duration duration_; ipv4_header ipv4_hdr_; icmp_header icmp_hdr_; public: ping_result() : state_(unknown) {} ping_result(const std::wstring &str) { std::wstringstream in(str); in >> *this; if (!in) *this = ping_result(); } inline state_t state() const { return state_; } inline void set_state(state_t st) { state_ = st; } inline posix_time::ptime time() const { return time_; } inline void set_time(posix_time::ptime t) { time_ = t; } inline posix_time::time_duration duration() const { return duration_; } inline void set_duration(posix_time::time_duration d) { duration_ = d; } inline unsigned short sequence_number() const { return icmp_hdr_.sequence_number(); } inline void set_sequence_number(unsigned short n) { icmp_hdr_.sequence_number(n); } inline const ipv4_header& ipv4_hdr() const { return ipv4_hdr_; } inline void set_ipv4_hdr(const ipv4_header &ipv4_hdr) { ipv4_hdr_ = ipv4_hdr; } inline const icmp_header& icmp_hdr() const { return icmp_hdr_; } inline void set_icmp_hdr(const icmp_header &icmp_hdr) { icmp_hdr_ = icmp_hdr; } std::wstring to_wstring() const { std::wstringstream out; out << *this; return out.str(); } std::wstring winfo() const { std::wstringstream out; out << sequence_number() << L' ' << state_to_wstring() << L' ' << my::time::to_wstring(time_) << L' ' << duration_.total_milliseconds() << L"ms"; return out.str(); } std::wstring state_to_wstring() const { return state_ == ok ? L"ok" : state_ == timeout ? L"timeout" : L"unknown"; } inline bool operator ==(state_t st) const { return state_ == st; } inline bool operator !=(state_t st) const { return state_ != st; } friend std::wistream& operator>>(std::wistream& in, ping_result& pr) { int ver = 0; in >> ver; if (ver != PING_RESULT_VER) in.setstate(std::ios::failbit); std::wstring state_s; in >> state_s; if (state_s == L"ok") pr.state_ = ok; else if (state_s == L"timeout") pr.state_ = timeout; else in.setstate(std::ios::failbit); std::wstring time_s, time2_s; in >> time_s; in >> time2_s; time_s += std::wstring(L" ") + time2_s; pr.time_ = my::time::to_time(time_s); if (pr.time_.is_special()) in.setstate(std::ios::failbit); std::wstring dur_s; in >> dur_s; pr.duration_ = my::time::to_duration(dur_s); if (pr.duration_.is_special()) in.setstate(std::ios::failbit); std::wstring ipv4_s; in >> ipv4_s; std::string ipv4_s2 = my::str::from_hex(my::str::to_string(ipv4_s)); if (ipv4_s2.size() != sizeof(pr.ipv4_hdr_.rep_)) in.setstate(std::ios::failbit); else memcpy(pr.ipv4_hdr_.rep_, ipv4_s2.c_str(), sizeof(pr.ipv4_hdr_.rep_)); std::wstring icmp_s; in >> icmp_s; std::string icmp_s2( my::str::from_hex(my::str::to_string(icmp_s)) ); if (icmp_s2.size() != sizeof(pr.icmp_hdr_.rep_)) in.setstate(std::ios::failbit); else memcpy(pr.icmp_hdr_.rep_, icmp_s2.c_str(), sizeof(pr.icmp_hdr_.rep_)); return in; } friend std::wostream& operator<<(std::wostream& out, const ping_result &pr) { out << PING_RESULT_VER << L' ' << pr.state_to_wstring() << L' ' << my::time::to_wstring(pr.time_) << L' ' << my::time::to_wstring(pr.duration_) << L' ' << my::str::to_wstring( my::str::to_hex( (const char*)pr.ipv4_hdr_.rep_, sizeof(pr.ipv4_hdr_.rep_) ) ) << L' ' << my::str::to_wstring( my::str::to_hex( (const char*)pr.icmp_hdr_.rep_, sizeof(pr.icmp_hdr_.rep_) ) ); return out; } }; } #endif
[ "victor.dunaev@localhost" ]
[ [ [ 1, 173 ] ] ]
076a6966611131847e1db678119cfe81ed5f23ec
0ce35229d1698224907e00f1fdfb34cfac5db1a2
/voiture.h
0ce16999c317a0c50de997d72e9b449617d1df5f
[]
no_license
manudss/efreiloca
f7b1089b6ba74ff26e6320044f66f9401ebca21b
54e8c4af1aace11f35846e63880a893e412b3309
refs/heads/master
2020-06-05T17:34:02.234617
2007-06-04T19:12:15
2007-06-04T19:12:15
32,325,713
0
0
null
null
null
null
UTF-8
C++
false
false
148
h
#pragma once #include "vehicule.h" class voiture : public vehicule { public: voiture(void); public: ~voiture(void); private: };
[ "pootoonet@65b228c9-682f-0410-abd1-c3b8cf015911" ]
[ [ [ 1, 14 ] ] ]
71d9ff4afd2200d89904849620f3b0a2fe43a631
b22c254d7670522ec2caa61c998f8741b1da9388
/FinalClient/LogHandler.cpp
4cd4d51a47067c157c3db676df3f3fd2bd157a4e
[]
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
2,613
cpp
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #include "LogHandler.h" #include <boost/date_time/posix_time/posix_time.hpp> LogHandler* LogHandler::_singletonInstance = NULL; /*********************************************************** singleton pattern ***********************************************************/ LogHandler * LogHandler::getInstance() { if(!_singletonInstance) _singletonInstance = new LogHandler(); return _singletonInstance; } /*********************************************************** Constructor ***********************************************************/ LogHandler::LogHandler() : _logfile("LBAClient.log", std::ios::app) { _logfile<<std::endl<<std::endl<<"**********************************"<<std::endl; _logfile<<boost::posix_time::second_clock::local_time()<<" - Starting new game."<<std::endl; } /*********************************************************** Destructor ***********************************************************/ LogHandler::~LogHandler() { } /*********************************************************** log a text into file ***********************************************************/ void LogHandler::LogToFile(const std::string text, int category) { boost::mutex::scoped_lock lock(m_mutex); _logfile<<boost::posix_time::second_clock::local_time()<<","<<category<<","<<text<<std::endl; } /*********************************************************** inform the use of something ***********************************************************/ void LogHandler::InformUser(const std::string text) { boost::mutex::scoped_lock lock(m_mutex); std::cout<<text<<std::endl; }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 88 ] ] ]
7c480534b75e45828eeed2333e26dad4888f0ca0
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Graphics/WmlTriMesh.cpp
bc0e4e3a2f36e4963f306e13186d8d77581f5f47
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
11,695
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlRenderer.h" #include "WmlTriMesh.h" using namespace Wml; using namespace std; WmlImplementRTTI(TriMesh,Geometry); WmlImplementStream(TriMesh); //---------------------------------------------------------------------------- TriMesh::TriMesh (int iVertexQuantity, Vector3f* akVertex, Vector3f* akNormal, ColorRGB* akColor, Vector2f* akTexture, int iTriangleQuantity, int* aiConnect, Vector2f* akTexture1, Vector2f* akTexture2, Vector2f* akTexture3, Vector2f* akTextureBump, VertexShader* pkVertexShader, PixelShader* pkPixelShader) : Geometry(iVertexQuantity,akVertex,akNormal,akColor,akTexture,akTexture1, akTexture2,akTexture3,akTextureBump, pkVertexShader, pkPixelShader) { m_iTriangleQuantity = iTriangleQuantity; m_aiConnect = aiConnect; } //---------------------------------------------------------------------------- TriMesh::TriMesh () { m_iTriangleQuantity = 0; m_aiConnect = NULL; } //---------------------------------------------------------------------------- TriMesh::~TriMesh () { delete[] m_aiConnect; } //---------------------------------------------------------------------------- void TriMesh::Reconstruct (int iVertexQuantity, int iTriangleQuantity) { Geometry::Reconstruct(iVertexQuantity); m_iTriangleQuantity = iTriangleQuantity; delete[] m_aiConnect; if ( m_iTriangleQuantity > 0 ) m_aiConnect = new int[3*m_iTriangleQuantity]; } //---------------------------------------------------------------------------- void TriMesh::Reconstruct (int iVertexQuantity, Vector3f* akVertex, Vector3f* akNormal, ColorRGB* akColor, Vector2f* akTexture, int iTriangleQuantity, int* aiConnect, Vector2f* akTexture1, Vector2f* akTexture2, Vector2f* akTexture3, Vector2f* akTextureBump) { Geometry::Reconstruct(iVertexQuantity,akVertex,akNormal,akColor, akTexture,akTexture1,akTexture2,akTexture3,akTextureBump); if ( m_aiConnect != aiConnect ) { delete[] m_aiConnect; m_aiConnect = aiConnect; } m_iTriangleQuantity = iTriangleQuantity; } //---------------------------------------------------------------------------- void TriMesh::GetTriangle (int i, int& riV0, int& riV1, int& riV2) const { assert( i < m_iTriangleQuantity ); int iBase = 3*i; riV0 = m_aiConnect[iBase++]; riV1 = m_aiConnect[iBase++]; riV2 = m_aiConnect[iBase]; } //---------------------------------------------------------------------------- void TriMesh::GetTriangle (int i, Vector3f& rkV0, Vector3f& rkV1, Vector3f& rkV2) const { assert( i < m_iTriangleQuantity ); int iBase = 3*i; rkV0 = m_akVertex[m_aiConnect[iBase++]]; rkV1 = m_akVertex[m_aiConnect[iBase++]]; rkV2 = m_akVertex[m_aiConnect[iBase]]; } //---------------------------------------------------------------------------- void TriMesh::UpdateModelNormals () { // Calculate normals from vertices by weighted averages of facet planes // that contain the vertices. TO DO. Replace by algorithm that computes // axis of minimum cone containing the normals. if ( !m_akNormal ) m_akNormal = new Vector3f[m_iVertexQuantity]; memset(m_akNormal,0,m_iVertexQuantity*sizeof(Vector3f)); int* aiConnect = m_aiConnect; int i; for (i = 0; i < m_iTriangleQuantity; i++) { // get vertex indices int iV0 = *aiConnect++; int iV1 = *aiConnect++; int iV2 = *aiConnect++; // get vertices Vector3f& rkV0 = m_akVertex[iV0]; Vector3f& rkV1 = m_akVertex[iV1]; Vector3f& rkV2 = m_akVertex[iV2]; // compute the normal (length provides the weighted sum) Vector3f kEdge1 = rkV1 - rkV0; Vector3f kEdge2 = rkV2 - rkV0; Vector3f kNormal = kEdge1.Cross(kEdge2); m_akNormal[iV0] += kNormal; m_akNormal[iV1] += kNormal; m_akNormal[iV2] += kNormal; } for (i = 0; i < m_iVertexQuantity; i++) m_akNormal[i].Normalize(); } //---------------------------------------------------------------------------- void TriMesh::Draw (Renderer& rkRenderer) { Geometry::Draw(rkRenderer); rkRenderer.Draw(*this); } //---------------------------------------------------------------------------- TriMesh::PickRecord::PickRecord (TriMesh* pkObject, float fRayT, int iTriangle, float fBary0, float fBary1, float fBary2) : Geometry::PickRecord(pkObject,fRayT) { m_iTriangle = iTriangle; m_fBary0 = fBary0; m_fBary1 = fBary1; m_fBary2 = fBary2; } //---------------------------------------------------------------------------- void TriMesh::DoPick (const Vector3f& rkOrigin, const Vector3f& rkDirection, PickArray& rkResults) { if ( m_kWorldBound.TestIntersection(rkOrigin,rkDirection) ) { // convert the ray to model-space coordinates Vector3f kDiff = rkOrigin - m_kWorldTranslate; float fInvScale = 1.0f/m_fWorldScale; Vector3f kMOrigin = fInvScale*(kDiff*m_kWorldRotate); Vector3f kMDirection = fInvScale*(rkDirection*m_kWorldRotate); // compute intersections with the model-space triangles int* aiConnect = m_aiConnect; for (int i = 0; i < m_iTriangleQuantity; i++) { int iV0 = *aiConnect++; int iV1 = *aiConnect++; int iV2 = *aiConnect++; float fBary0, fBary1, fBary2, fRayT; if ( GetRayTriangleIntersection(kMOrigin,kMDirection, m_akVertex[iV0],m_akVertex[iV1],m_akVertex[iV2],fBary0, fBary1,fBary2,fRayT) ) { rkResults.push_back(new PickRecord(this,fRayT,i,fBary0,fBary1, fBary2)); } } } } //---------------------------------------------------------------------------- bool TriMesh::GetRayTriangleIntersection (const Vector3f& rkModelOrigin, const Vector3f& rkModelDirection, const Vector3f& rkV0, const Vector3f& rkV1, const Vector3f& rkV2, float& rfBary0, float& rfBary1, float& rfBary2, float& rfRayT) { // compute the offset origin, edges, and normal Vector3f kDiff = rkModelOrigin - rkV0; Vector3f kEdge1 = rkV1 - rkV0; Vector3f kEdge2 = rkV2 - rkV0; Vector3f kNormal = kEdge1.Cross(kEdge2); // Solve Q + t*D = s1*E1 + s2*E2 (Q = kDiff, D = kMDirection, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*s1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*s2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) const float fEpsilon = 1e-06f; float fDdN = rkModelDirection.Dot(kNormal); float fSign; if ( fDdN > fEpsilon ) { fSign = 1.0f; } else if ( fDdN < -fEpsilon ) { fSign = -1.0f; fDdN = -fDdN; } else { // Ray and triangle are parallel, call it a "no intersection" // even if the ray does intersect. return false; } float fDdQxE2 = fSign*rkModelDirection.Dot(kDiff.Cross(kEdge2)); if ( fDdQxE2 >= 0.0f ) { float fDdE1xQ = fSign*rkModelDirection.Dot(kEdge1.Cross(kDiff)); if ( fDdE1xQ >= 0.0f ) { if ( fDdQxE2 + fDdE1xQ <= fDdN ) { // line intersects triangle, check if ray does float fQdN = -fSign*kDiff.Dot(kNormal); if ( fQdN >= 0.0f ) { // ray intersects triangle float fInv = 1.0f/fDdN; rfBary1 = fDdQxE2*fInv; rfBary2 = fDdE1xQ*fInv; rfBary0 = 1.0f - rfBary1 - rfBary2; rfRayT = fQdN*fInv; return true; } // else: t < 0, no intersection } // else: s1+s2 > 1, no intersection } // else: s2 < 0, no intersection } // else: s1 < 0, no intersection return false; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // streaming //---------------------------------------------------------------------------- Object* TriMesh::Factory (Stream& rkStream) { TriMesh* pkObject = new TriMesh; Stream::Link* pkLink = new Stream::Link(pkObject); pkObject->Load(rkStream,pkLink); return pkObject; } //---------------------------------------------------------------------------- void TriMesh::Load (Stream& rkStream, Stream::Link* pkLink) { Geometry::Load(rkStream,pkLink); // native data StreamRead(rkStream,m_iTriangleQuantity); int iQuantity = 3*m_iTriangleQuantity; m_aiConnect = new int[iQuantity]; StreamRead(rkStream,m_aiConnect,iQuantity); } //---------------------------------------------------------------------------- void TriMesh::Link (Stream& rkStream, Stream::Link* pkLink) { Geometry::Link(rkStream,pkLink); } //---------------------------------------------------------------------------- bool TriMesh::Register (Stream& rkStream) { return Geometry::Register(rkStream); } //---------------------------------------------------------------------------- void TriMesh::Save (Stream& rkStream) { Geometry::Save(rkStream); // native data StreamWrite(rkStream,m_iTriangleQuantity); StreamWrite(rkStream,m_aiConnect,3*m_iTriangleQuantity); } //---------------------------------------------------------------------------- StringTree* TriMesh::SaveStrings () { StringTree* pkTree = new StringTree(2,0,2,0); // strings pkTree->SetString(0,MakeString(&ms_kRTTI,GetName())); pkTree->SetString(1,MakeString("triangle quantity =", m_iTriangleQuantity)); // children pkTree->SetChild(0,Geometry::SaveStrings()); StringTree* pkTriTree = new StringTree(m_iTriangleQuantity+1,0,0,0); pkTriTree->SetString(0,MakeString("triangles")); int* piConnect = m_aiConnect; char acDummy[64]; for (int i = 0; i < m_iTriangleQuantity; i++) { int iI0 = *piConnect++; int iI1 = *piConnect++; int iI2 = *piConnect++; sprintf(acDummy,"<%5d,%5d,%5d>",iI0,iI1,iI2); pkTriTree->SetString(i+1,MakeString(acDummy)); } pkTree->SetChild(1,pkTriTree); return pkTree; } //---------------------------------------------------------------------------- int TriMesh::GetMemoryUsed () const { int iBaseSize = sizeof(TriMesh) - sizeof(Geometry); int iDynaSize = 3*m_iTriangleQuantity*sizeof(int); int iTotalSize = iBaseSize + iDynaSize + Geometry::GetMemoryUsed(); return iTotalSize; } //---------------------------------------------------------------------------- int TriMesh::GetDiskUsed () const { return Geometry::GetDiskUsed() + sizeof(m_iTriangleQuantity) + 3*m_iTriangleQuantity*sizeof(m_aiConnect[0]); } //----------------------------------------------------------------------------
[ [ [ 1, 332 ] ] ]
cc80c02d1575a890473b7ffd67bd6fe55fadd5e2
59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02
/src/SkinResEditor_Old/SkinResMenuView.h
e44dd0bf701a9ad2b6f3905d9e6ded7d046e38f2
[]
no_license
fingomajom/skinengine
444a89955046a6f2c7be49012ff501dc465f019e
6bb26a46a7edac88b613ea9a124abeb8a1694868
refs/heads/master
2021-01-10T11:30:51.541442
2008-07-30T07:13:11
2008-07-30T07:13:11
47,892,418
0
0
null
null
null
null
GB18030
C++
false
false
15,507
h
#pragma once #include "SkinItemIdMgt.h" class SkinResMenuView : public CDialogImpl<SkinResMenuView>, public SkinTreeItemControl, public SkinPropertyView::PropertyEditNotify { public: enum { IDD = IDD_EDITMENU_DIALOG }; SkinResMenuView() { } ~SkinResMenuView() { } virtual void InitResult(HTREEITEM hTreeItem) { SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); if (m_hWnd == NULL) { Create(ControlsMgt.m_piSkinFrame->GetResultParentWnd()); } m_wndMenuTree.DeleteAllItems(); m_wndMenuList.DeleteAllItems(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; for (size_t idx = 0; idx < vtMenuList.size(); idx++) { m_wndMenuList.InsertItem(idx, vtMenuList[idx].strIdName, 4); } } virtual void ShowResult(HTREEITEM hTreeItem, LPARAM lParam) { SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); ShowWindow(SW_SHOW); ControlsMgt.m_piSkinFrame->SetActiveResultWindow(m_hWnd); } virtual void HideResult(HTREEITEM hTreeItem, LPARAM lParam) { SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); ControlsMgt.m_skinResPropertyView.Clear(); ControlsMgt.m_skinResPropertyView.SetPropertyEditNotify(NULL); ShowWindow(SW_HIDE); } public: CListViewCtrl m_wndMenuList; CTreeViewCtrl m_wndMenuTree; CImageList m_imagelist; BEGIN_MSG_MAP(SkinResDialogListView) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_ADD_MENU , BN_CLICKED, OnAddMenu) COMMAND_HANDLER(IDC_DEL_MENU , BN_CLICKED, OnDelMenu) COMMAND_HANDLER(IDC_ADD_MENUITEM , BN_CLICKED, OnAddMenuItem) COMMAND_HANDLER(IDC_DEL_MENUITEM , BN_CLICKED, OnDelMenuItem) NOTIFY_HANDLER(IDC_MENU_LIST, LVN_ENDLABELEDIT, OnLvnEndlabeleditMenuList) NOTIFY_HANDLER(IDC_MENU_LIST, LVN_ITEMCHANGED, OnLvnItemchangedMenuList) NOTIFY_HANDLER(IDC_MENU_TREE, TVN_SELCHANGED, OnTvnSelchangedMenuTree) END_MSG_MAP() BOOL IsExistMenuName( LPCTSTR pszName ) { SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; for (size_t idx = 0; idx < vtMenuList.size(); idx++) { if (!vtMenuList[idx].strIdName.CompareNoCase(pszName)) return TRUE; } return FALSE; } LRESULT OnAddMenu(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; SkinMenuItem newMenuItem; newMenuItem.strIsPopupMenu = _T("False"); static int newMenuId = 1; while (true) { newMenuItem.strIdName.Format(_T("IDM_NEWMENU%d"), newMenuId++); if (!IsExistMenuName(newMenuItem.strIdName)) break; } m_wndMenuList.InsertItem(0xFFFFF, newMenuItem.strIdName, 4); vtMenuList.push_back(newMenuItem); ControlsMgt.m_resDocument.Modify(TRUE); return 1L; } LRESULT OnDelMenu(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int nIdx = m_wndMenuList.GetSelectedIndex(); if (nIdx < 0) return 1L; SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; m_wndMenuList.DeleteItem( nIdx ); vtMenuList.erase(vtMenuList.begin() + nIdx); m_wndMenuList.SelectItem( nIdx == m_wndMenuList.GetItemCount() ? nIdx - 1 : nIdx); ControlsMgt.m_resDocument.Modify(TRUE); return 1L; } LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { m_wndMenuList = GetDlgItem(IDC_MENU_LIST); m_wndMenuTree = GetDlgItem(IDC_MENU_TREE); m_wndMenuList.InsertColumn(0, _T(""), 0, 150); CBitmap bmp; bmp.LoadBitmap(IDB_RESTYPE_BITMAP); m_imagelist.Create(16, 16, ILC_COLOR24 | ILC_MASK, 3, 1); m_imagelist.Add(bmp, RGB(255, 0, 255)); m_wndMenuList.SetImageList(m_imagelist, LVSIL_SMALL); m_wndMenuTree.SetImageList(m_imagelist); m_wndMenuList.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT); return TRUE; } LRESULT SkinResMenuView::OnLvnEndlabeleditMenuList(int /*idCtrl*/, LPNMHDR pNMHDR, BOOL& /*bHandled*/) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); KSGUI::CString strNewIdName = pDispInfo->item.pszText; if (strNewIdName.GetLength() <= 0) return 0L; int idx = pDispInfo->item.iItem; if (idx < 0) return 0L; if ( _tcslen(strNewIdName) <= _tcslen(_T("IDM_")) || _tcsncmp(strNewIdName, _T("IDM_"), _tcslen(_T("IDM_")) ) ) // 不合法的项名 { KSGUI::CString strMsg; strMsg.Format( _T("[%s]不是合法的项名\n必顺以 IDM_ 开头的字符串。"), strNewIdName); MessageBox(strMsg, _T("错误")); return 0L; } ATLASSERT( idx < m_wndMenuList.GetItemCount() ); SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; m_wndMenuList.SetItemText(idx, 0, strNewIdName); vtMenuList[idx].strIdName = strNewIdName; m_wndMenuTree.SetItemText(m_wndMenuTree.GetRootItem(), strNewIdName); ControlsMgt.m_resDocument.Modify(TRUE); return 1L; } void ShowMenu( int idx ) { m_wndMenuTree.DeleteAllItems(); SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; if (idx >= 0 && idx < (int)vtMenuList.size()) { HTREEITEM hItemInsert = m_wndMenuTree.InsertItem( vtMenuList[idx].strIdName, 4, 4, TVI_ROOT, TVI_LAST); ShowMenu(hItemInsert, vtMenuList[idx]); m_wndMenuTree.Expand(hItemInsert); } m_wndMenuTree.SelectItem(m_wndMenuTree.GetRootItem()); } void ShowMenu( HTREEITEM hTreeItemParent, SkinMenuItem& MenuItemInfo ) { for (size_t idx = 0; idx < MenuItemInfo.m_vtChildPopupMenu.size(); idx++) { HTREEITEM hItemInsert = m_wndMenuTree.InsertItem( MenuItemInfo.m_vtChildPopupMenu[idx].strItemText, 4, 4, hTreeItemParent, TVI_LAST); if (MenuItemInfo.m_vtChildPopupMenu[idx].m_vtChildPopupMenu.size() > 0) ShowMenu(hItemInsert, MenuItemInfo.m_vtChildPopupMenu[idx]); } } LRESULT OnLvnItemchangedMenuList(int /*idCtrl*/, LPNMHDR pNMHDR, BOOL& /*bHandled*/) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); int idx = m_wndMenuList.GetSelectedIndex(); if (idx < 0) m_wndMenuTree.DeleteAllItems(); else ShowMenu(idx); return 0; } BOOL GetMenuItem(HTREEITEM hTreeItem, SkinMenuItem*& pParentItem, SkinMenuItem*& pMenuItemInfo, int* pidx = NULL ) { std::vector<int> vtpos; HTREEITEM hTreeItemParent = hTreeItem; while (hTreeItemParent != NULL && hTreeItemParent != m_wndMenuTree.GetRootItem()) { hTreeItemParent = m_wndMenuTree.GetParentItem(hTreeItem); int npos = -1; while ( hTreeItem != NULL ) { hTreeItem = m_wndMenuTree.GetPrevSiblingItem(hTreeItem); npos++; } vtpos.insert(vtpos.begin(), npos); hTreeItem = hTreeItemParent; } SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); std::vector<SkinMenuItem>& vtMenuList = ControlsMgt.m_resDocument.m_resMenuDoc.m_vtMenuList; int nIdx = m_wndMenuList.GetSelectedIndex(); if (nIdx < 0) return FALSE; pParentItem = &vtMenuList[nIdx]; pMenuItemInfo = pParentItem; for (size_t idx = 0; idx < vtpos.size(); idx++) { pParentItem = pMenuItemInfo; pMenuItemInfo = &pMenuItemInfo->m_vtChildPopupMenu[vtpos[idx]]; if (pidx != NULL) *pidx = vtpos[idx]; } return TRUE; } LRESULT OnTvnSelchangedMenuTree(int /*idCtrl*/, LPNMHDR pNMHDR, BOOL& /*bHandled*/) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); HTREEITEM hSelItem = m_wndMenuTree.GetSelectedItem(); ControlsMgt.m_skinResPropertyView.Clear(); ControlsMgt.m_skinResPropertyView.SetPropertyEditNotify(NULL); if (hSelItem == NULL || hSelItem == m_wndMenuTree.GetRootItem()) { } else { SkinMenuItem* pParentItem = NULL; SkinMenuItem* pMenuItemInfo = NULL; GetMenuItem(hSelItem, pParentItem, pMenuItemInfo); ATLASSERT(pParentItem != NULL); ATLASSERT(pMenuItemInfo != NULL); if (pMenuItemInfo != NULL) { ControlsMgt.m_skinResPropertyView.SetPropertyEditNotify(this); ControlsMgt.m_skinResPropertyView.AppendProperty( _T("Caption"), pMenuItemInfo->strItemText ); ControlsMgt.m_skinResPropertyView.AppendProperty( _T("IdName"), pMenuItemInfo->strIdName ); ControlsMgt.m_skinResPropertyView.AppendProperty( _T("ItemId"), pMenuItemInfo->strItemId ); } } return 0; } int GetNextMenuIdName() { static int nnextid = 5000; return nnextid++; } LRESULT OnAddMenuItem(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { HTREEITEM hSelItem = m_wndMenuTree.GetSelectedItem(); if (hSelItem == NULL) return 0L; SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); SkinMenuItem* pParentItem = NULL; SkinMenuItem* pMenuItemInfo = NULL; GetMenuItem(hSelItem, pParentItem, pMenuItemInfo); ATLASSERT(pParentItem != NULL); ATLASSERT(pMenuItemInfo != NULL); if (pMenuItemInfo != NULL) { SkinMenuItem newMenuItem; newMenuItem.strItemText = _T("NewMenuItem"); newMenuItem.strItemId.Format(_T("%d"), GetNextMenuIdName()); newMenuItem.strIdName.Format(_T("IDC_MENUID_%s"), newMenuItem.strItemId); SkinItemIdMgt::instance().UsedItemId( newMenuItem.strIdName, newMenuItem.strItemId ); pMenuItemInfo->m_vtChildPopupMenu.push_back(newMenuItem); m_wndMenuTree.InsertItem( newMenuItem.strItemText, 4, 4, hSelItem, TVI_LAST); m_wndMenuTree.Expand(hSelItem); ControlsMgt.m_resDocument.Modify(TRUE); } return 0; } void OnDelUsedItemId( SkinMenuItem& MenuItemInfo ) { SkinItemIdMgt::instance().DelItemId( MenuItemInfo.strIdName ); for (size_t idx = 0; idx < MenuItemInfo.m_vtChildPopupMenu.size(); idx++) { OnDelUsedItemId( MenuItemInfo.m_vtChildPopupMenu[idx] ); } } LRESULT OnDelMenuItem(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { HTREEITEM hSelItem = m_wndMenuTree.GetSelectedItem(); if (hSelItem == NULL || hSelItem == m_wndMenuTree.GetRootItem()) return 0L; SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); SkinMenuItem* pParentItem = NULL; SkinMenuItem* pMenuItemInfo = NULL; int idx = 0; GetMenuItem(hSelItem, pParentItem, pMenuItemInfo, &idx); ATLASSERT(pParentItem != NULL); ATLASSERT(pMenuItemInfo != NULL); if (pMenuItemInfo != NULL) { OnDelUsedItemId(*pMenuItemInfo); pParentItem->m_vtChildPopupMenu.erase( pParentItem->m_vtChildPopupMenu.begin() + idx); m_wndMenuTree.DeleteItem(hSelItem); ControlsMgt.m_resDocument.Modify(TRUE); } return 0; } virtual void OnValueChange ( LPCTSTR pszPropertyName, LPCTSTR pszOldValue, LPCTSTR pszNewValue) { HTREEITEM hSelItem = m_wndMenuTree.GetSelectedItem(); if (hSelItem == NULL || hSelItem == m_wndMenuTree.GetRootItem()) return; SkinControlsMgt& ControlsMgt = SkinControlsMgt::Instance(); SkinMenuItem* pParentItem = NULL; SkinMenuItem* pMenuItemInfo = NULL; GetMenuItem(hSelItem, pParentItem, pMenuItemInfo); ATLASSERT(pParentItem != NULL); ATLASSERT(pMenuItemInfo != NULL); if (!_tcscmp(pszPropertyName, _T("Caption"))) { m_wndMenuTree.SetItemText(hSelItem, pszNewValue); pMenuItemInfo->strItemText = pszNewValue; } else if (!_tcscmp(pszPropertyName, _T("IdName"))) { if ( _tcslen(pszNewValue) <= _tcslen(_T("IDC_")) || _tcsncmp(pszNewValue, _T("IDC_"), _tcslen(_T("IDC_")) ) ) // 不合法的项名 { ControlsMgt.m_skinResPropertyView.SetProperty(_T("IdName"), pszOldValue); KSGUI::CString strMsg; strMsg.Format( _T("[%s]不是合法的项名\n必顺以 IDC_ 开头的字符串。"), pszNewValue); MessageBox(strMsg, _T("错误")); return ; } pMenuItemInfo->strIdName = pszNewValue; SkinItemIdMgt::instance().UsedItemId( pMenuItemInfo->strIdName, pMenuItemInfo->strItemId ); SkinItemIdMgt::instance().DelItemId( pszOldValue ); ControlsMgt.m_skinResPropertyView.SetProperty(_T("ItemId"), pMenuItemInfo->strItemId); } else if (!_tcscmp(pszPropertyName, _T("ItemId"))) { pMenuItemInfo->strItemId = pszNewValue; SkinItemIdMgt::instance().ChangeItemId( pMenuItemInfo->strIdName, pMenuItemInfo->strItemId ); } } virtual void OnButtonClieck(LPCTSTR pszPropertyName) { } };
[ [ [ 1, 522 ] ] ]
8801036d7486d8be8c4c9dcc0b1949370446c378
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/Platform/WorkItem.h
02a50736dbff241566564006461a97ee4daa4e70
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,525
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WorkItem_h #define WorkItem_h #include <wtf/PassOwnPtr.h> class WorkItem { public: template<typename C> static PassOwnPtr<WorkItem> create(C*, void (C::*)()); template<typename C, typename T0> static PassOwnPtr<WorkItem> create(C*, void (C::*)(T0), T0); template<typename C, typename T0, typename T1> static PassOwnPtr<WorkItem> create(C*, void (C::*)(T0, T1), T0, T1); virtual ~WorkItem() { } virtual void execute() = 0; protected: WorkItem() { } private: WorkItem(const WorkItem&); WorkItem& operator=(const WorkItem&); }; template <typename C> class MemberFunctionWorkItem0 : private WorkItem { // We only allow WorkItem to create this. friend class WorkItem; typedef void (C::*FunctionType)(); MemberFunctionWorkItem0(C* ptr, FunctionType function) : m_ptr(ptr) , m_function(function) { m_ptr->ref(); } ~MemberFunctionWorkItem0() { m_ptr->deref(); } void execute() { (m_ptr->*m_function)(); } C* m_ptr; FunctionType m_function; }; template<typename C, typename T0> class MemberFunctionWorkItem1 : private WorkItem { // We only allow WorkItem to create this. friend class WorkItem; typedef void (C::*FunctionType)(T0); MemberFunctionWorkItem1(C* ptr, FunctionType function, T0 t0) : m_ptr(ptr) , m_function(function) , m_t0(t0) { m_ptr->ref(); } ~MemberFunctionWorkItem1() { m_ptr->deref(); } void execute() { (m_ptr->*m_function)(m_t0); } C* m_ptr; FunctionType m_function; T0 m_t0; }; template<typename C, typename T0, typename T1> class MemberFunctionWorkItem2 : private WorkItem { // We only allow WorkItem to create this. friend class WorkItem; typedef void (C::*FunctionType)(T0, T1); MemberFunctionWorkItem2(C* ptr, FunctionType function, T0 t0, T1 t1) : m_ptr(ptr) , m_function(function) , m_t0(t0) , m_t1(t1) { m_ptr->ref(); } ~MemberFunctionWorkItem2() { m_ptr->deref(); } void execute() { (m_ptr->*m_function)(m_t0, m_t1); } C* m_ptr; FunctionType m_function; T0 m_t0; T1 m_t1; }; template<typename C> PassOwnPtr<WorkItem> WorkItem::create(C* ptr, void (C::*function)()) { return adoptPtr(static_cast<WorkItem*>(new MemberFunctionWorkItem0<C>(ptr, function))); } template<typename C, typename T0> PassOwnPtr<WorkItem> WorkItem::create(C* ptr, void (C::*function)(T0), T0 t0) { return adoptPtr(static_cast<WorkItem*>(new MemberFunctionWorkItem1<C, T0>(ptr, function, t0))); } template<typename C, typename T0, typename T1> PassOwnPtr<WorkItem> WorkItem::create(C* ptr, void (C::*function)(T0, T1), T0 t0, T1 t1) { return adoptPtr(static_cast<WorkItem*>(new MemberFunctionWorkItem2<C, T0, T1>(ptr, function, t0, t1))); } #endif // WorkItem_h
[ [ [ 1, 161 ] ] ]
2559d78d636c3a72c014a42c1b3a0de01fe5c91e
29f0a6c56e3c4528f64c3a1ad18fc5f074ae1146
/Praktikum Info2/Aufgabenblock_3/Fahrrad.h
bcca28c8c498ca33b2eade672b3fa1bfb734cc97
[]
no_license
JohN-D/Info-2-Praktikum
8ccb0348bedf38a619a39b17b0425d6b4c16a72d
c11a274e9c4469a31f40d0abec2365545344b534
refs/heads/master
2021-01-01T18:34:31.347062
2011-10-19T20:18:47
2011-10-19T20:18:47
2,608,736
0
0
null
null
null
null
UTF-8
C++
false
false
638
h
#pragma once #include "fahrzeug.h" #include <math.h> #include <iostream> #include <iomanip> class Weg; using namespace std; class Fahrrad : public Fahrzeug { public: Fahrrad(void) : Fahrzeug() {} Fahrrad(string sName) : Fahrzeug(sName) {} Fahrrad(string sName, double dMaxGeschwindigkeit) : Fahrzeug(sName, dMaxGeschwindigkeit) {} Fahrrad(const Fahrrad& objekt) : Fahrzeug(objekt) {} virtual ~Fahrrad(void); virtual double dGeschwindigkeit(void); virtual ostream& ostreamAusgabe(ostream& Ausgabe); virtual istream& istreamEingabe(istream& Eingabe); virtual void vZeichnen(Weg* pWeg); protected: };
[ [ [ 1, 27 ] ] ]
205d3f6ecf44c40a14226e830e54d1485ca34fe8
e5ded38277ec6db30ef7721a9f6f5757924e130e
/Cpp/SoSe10/Blatt02.Aufgabe01/stdafx.cpp
9dcebecf3fb874f14edbe91f4870fbd3bf1ce5c4
[]
no_license
TetsuoCologne/sose10
67986c8a014c4bdef19dc52e0e71e91602600aa0
67505537b0eec497d474bd2d28621e36e8858307
refs/heads/master
2020-05-27T04:36:02.620546
2010-06-22T20:47:08
2010-06-22T20:47:08
32,480,813
0
0
null
null
null
null
ISO-8859-1
C++
false
false
324
cpp
// stdafx.cpp : Quelldatei, die nur die Standard-Includes einbindet. // Blatt02.Aufgabe01.pch ist der vorkompilierte Header. // stdafx.obj enthält die vorkompilierten Typinformationen. #include "stdafx.h" // TODO: Auf zusätzliche Header verweisen, die in STDAFX.H // und nicht in dieser Datei erforderlich sind.
[ "[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec" ]
[ [ [ 1, 8 ] ] ]
b6e8809584c85b3459a82ff15cbf8a8c4d534803
925e7b0a9f5757cad97981b37c6af180c30b2f6e
/nntpServer/nntpServerDataAccess/OpenDs/LdapWrapper/Ldap.cpp
b2ad247799f92b7018a1e2633b9cc3bd83181c9d
[]
no_license
jmg/nttp-server
08c2b6be2183b00989c8e4ea35dffaef3947385a
0308abe74e793fe0c16676e797ae16150566e1d6
refs/heads/master
2016-09-05T10:53:25.116857
2011-07-16T01:28:32
2011-07-16T01:28:32
2,739,107
0
0
null
null
null
null
UTF-8
C++
false
false
3,928
cpp
/* Api que actua de wrapper sobre la api original de openLDAP */ #include <stdio.h> #include "LdapWrapper.h" /* Esta funcion muestra como insertar una nueva entry con nuevos atributos y valores */ void insertEntry(PLDAP_SESSION session, PLDAP_SESSION_OP sessionOp, PLDAP_ENTRY_OP entryOp, PLDAP_ATTRIBUTE_OP attribOp) { /* Creo una nueva entry y le agrego los parametros correspondientes */ PLDAP_ENTRY entry = entryOp->createEntry(); entry->dn = "utnArticleID=12345,ou=so,dn=utn,dn=edu"; entryOp->addAttribute(entry, attribOp->createAttribute("objectclass", 2, "top", "utnArticle")); entryOp->addAttribute(entry, attribOp->createAttribute("utnArticleID", 1, "12345")); entryOp->addAttribute(entry, attribOp->createAttribute("utnArticleHead", 1, "Head del articulo")); entryOp->addAttribute(entry, attribOp->createAttribute("utnArticleBody", 1, "Body del articulo")); entryOp->addAttribute(entry, attribOp->createAttribute( "utnArticleGroupName", 1, "Group del articulo")); sessionOp->addEntry(session, entry); } /* Eliminamos una entrada existente a partir de un dn conocido. */ void delEntry(PLDAP_SESSION session, PLDAP_SESSION_OP sessionOp, PLDAP_ENTRY_OP entryOp, PLDAP_ATTRIBUTE_OP attribOp) { /* creo una nueva entry y le agrego los parametros correspondientes */ PLDAP_ENTRY entry = entryOp->createEntry(); entry->dn = "utnArticleID=12345,ou=so,dn=utn,dn=edu"; /* Se puede eliminar una entry pasando un objeto entry como parametro */ sessionOp->deleteEntryObj(session, entry); /* O se puede eliminar una entry pasando el dn correspondiente */ sessionOp->deleteEntryDn(session, "utnArticleID=12345,ou=so,dn=utn,dn=edu"); } /* Modificamos el valor de un atributo en una entry. Es necesario conocer el dn. */ void modifyEntry(PLDAP_SESSION session, PLDAP_SESSION_OP sessionOp, PLDAP_ENTRY_OP entryOp, PLDAP_ATTRIBUTE_OP attribOp) { PLDAP_ENTRY entry = entryOp->createEntry(); entry->dn = "utnArticleID=12345,ou=so,dn=utn,dn=edu"; /* agregamos el atributo a la entry en modo delete */ entryOp->editAttribute(entry, attribOp->createAttribute("utnurlTitle", 1, "Pagina de Prueba para LDAP")); sessionOp->editEntry(session, (PLDAP_ENTRY)"utnArticleID=12345,ou=so,dn=utn,dn=edu"); } /** Realizamos una consulta al directorio en una determinada rama. Para iterar sobre los resultados se utiliza un patron Iterator que recorre cada una de las entries */ void selectEntries(PLDAP_SESSION session, PLDAP_SESSION_OP sessionOp, PLDAP_ENTRY_OP entryOp, PLDAP_ATTRIBUTE_OP attribOp) { /* Hacemos una consulta en una determinada rama aplicando la siguiente condicion */ PLDAP_RESULT_SET resultSet = sessionOp->searchEntry(session, "ou=so,dn=utn,dn=edu", "utnArticleID=*"); PLDAP_ITERATOR iterator = NULL; PLDAP_RECORD_OP recordOp = newLDAPRecordOperations(); /* iteramos sobre los registros obtenidos a traves de un iterador que conoce la implementacion del recordset */ for (iterator = resultSet->iterator; iterator->hasNext(resultSet);) { PLDAP_RECORD record = iterator->next(resultSet); printf("dn: %s\n", record->dn); /* Iteramos sobre los campos de cada uno de los records */ while (recordOp->hasNextField(record)) { PLDAP_FIELD field = recordOp->nextField(record); INT index = 0; printf(" attribute: %s - values: %l\n", field->name, field->valuesSize); for (; index < field->valuesSize; index++) { printf(" Value[%d]: %s\n", index, field->values[index]); } /* liberamos la memoria utilizada por el field si este ya no es necesario. */ freeLDAPField(field); } /* liberamos los recursos consumidos por el record */ freeLDAPRecord(record); } /* liberamos los recursos */ freeLDAPIterator(iterator); freeLDAPRecordOperations(recordOp); }
[ "jmg.utn@208282a9-e914-21dd-f66b-6e6d9519d739" ]
[ [ [ 1, 128 ] ] ]
04ab3614fc4cd6a10e3dace351295a9bd066d287
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/src/common/OgreTypes/OgrePlane.cpp
6a8cd342db2494b76acc2d1b7fbb2f7954493eb1
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,480
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #include "OgrePlane.h" namespace Ogre { //----------------------------------------------------------------------- Plane::Plane () { normal = Vector3::ZERO; d = 0.0; } //----------------------------------------------------------------------- Plane::Plane (const Plane& rhs) { normal = rhs.normal; d = rhs.d; } //----------------------------------------------------------------------- Plane::Plane (const Vector3& rkNormal, Real fConstant) { normal = rkNormal; d = -fConstant; } //----------------------------------------------------------------------- Plane::Plane (const Vector3& rkNormal, const Vector3& rkPoint) { normal = rkNormal; d = -rkNormal.dotProduct(rkPoint); } //----------------------------------------------------------------------- Plane::Plane (const Vector3& rkPoint0, const Vector3& rkPoint1, const Vector3& rkPoint2) { redefine(rkPoint0, rkPoint1, rkPoint2); } //----------------------------------------------------------------------- Real Plane::getDistance (const Vector3& rkPoint) const { return normal.dotProduct(rkPoint) + d; } //----------------------------------------------------------------------- Plane::Side Plane::getSide (const Vector3& rkPoint) const { Real fDistance = getDistance(rkPoint); if ( fDistance < 0.0 ) return Plane::NEGATIVE_SIDE; if ( fDistance > 0.0 ) return Plane::POSITIVE_SIDE; return Plane::NO_SIDE; } //----------------------------------------------------------------------- void Plane::redefine(const Vector3& rkPoint0, const Vector3& rkPoint1, const Vector3& rkPoint2) { Vector3 kEdge1 = rkPoint1 - rkPoint0; Vector3 kEdge2 = rkPoint2 - rkPoint0; normal = kEdge1.crossProduct(kEdge2); normal.normalise(); d = -normal.dotProduct(rkPoint0); } //----------------------------------------------------------------------- std::ostream& operator<< (std::ostream& o, Plane& p) { o << "Plane(normal=" << p.normal << ", d=" << p.d << ")"; return o; } } // namespace Ogre
[ [ [ 1, 92 ] ] ]
60a98d05d2da95a21814576e8827985502804a9d
a8e78ee1cae74946b8b68aaaf0447d745d6fbaf3
/CPPUnitBCB6/samples/Multicaster/MulticasterTest.cpp
dfbbd93579cdd4cb26badf0d5436b578054fd8d8
[]
no_license
jmnavarro/BCB_CPPUnit
66c155026bd8445ca016e1327b0d222e3f4a10ad
7de1560d537db56d265fde482420bc6f66f01c32
refs/heads/master
2021-01-23T13:58:57.815624
2011-07-01T08:47:23
2011-07-01T08:47:23
1,982,570
0
0
null
null
null
null
UTF-8
C++
false
false
5,239
cpp
#include "MulticasterTest.h" #include "TestSuite.h" MulticasterTest::MulticasterTest (std::string name) : TestCase (name) { } MulticasterTest::~MulticasterTest() { } void MulticasterTest::setUp () { m_multicaster = new Multicaster; m_o1 = new Observer; m_o2 = new Observer; m_o3 = new Observer; m_o4 = new Observer; } void MulticasterTest::tearDown () { delete m_o4; delete m_o3; delete m_o2; delete m_o1; delete m_multicaster; } void MulticasterTest::testSinglePublish () { // Make sure we can subscribe and publish to an address Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->publish (NULL, "alpha", value)); assert (*m_o1 == Observer ("alpha", 1)); } void MulticasterTest::testMultipleHomogenousPublish () { // Make sure we can multicast to an address Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o2, "alpha")); assert (m_multicaster->subscribe (m_o3, "alpha")); assert (m_multicaster->subscribe (m_o4, "alpha")); assert (m_multicaster->publish (NULL, "alpha", value)); assert (*m_o1 == Observer ("alpha", 1)); assert (*m_o2 == Observer ("alpha", 1)); assert (*m_o3 == Observer ("alpha", 1)); assert (*m_o4 == Observer ("alpha", 1)); } void MulticasterTest::testMultipleHeterogenousPublish () { // Make sure we can multicast to several addresses at once Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o2, "beta")); assert (m_multicaster->subscribe (m_o3, "alpha")); assert (m_multicaster->subscribe (m_o4, "beta")); assert (m_multicaster->publish (NULL, "alpha", value)); assert (*m_o1 == Observer ("alpha", 1)); assert (*m_o2 == Observer ()); assert (*m_o3 == Observer ("alpha", 1)); assert (*m_o4 == Observer ()); } void MulticasterTest::testSingleUnsubscribe () { // Make sure we can unsubscribe one of two observers on the same address Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o2, "alpha")); assert (m_multicaster->unsubscribe (m_o1, "alpha")); assert (m_multicaster->publish (NULL, "alpha", value)); assert (*m_o1 == Observer ()); assert (*m_o2 == Observer ("alpha", 1)); } void MulticasterTest::testMultipleUnsubscribe () { // Make sure we unsubscribe all occurrences of an observer on the same address Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->unsubscribe (m_o1, "alpha")); assert (m_multicaster->publish (NULL, "alpha", value)); assert (*m_o1 == Observer ()); } void MulticasterTest::testSimpleUnsubscribeAll () { // Make sure we unsubscribe all occurrences of an observer on all addresses Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o1, "beck")); assert (m_multicaster->subscribe (m_o1, "gamma")); m_multicaster->unsubscribeFromAll (m_o1); assert (m_multicaster->publish (NULL, "alpha", value)); assert (m_multicaster->publish (NULL, "beck", value)); assert (m_multicaster->publish (NULL, "gamma", value)); assert (*m_o1 == Observer ()); } void MulticasterTest::testComplexUnsubscribeAll () { // Make sure we unsubscribe all occurrences of an observer on all addresses // in the presence of many observers Value value; assert (m_multicaster->subscribe (m_o1, "alpha")); assert (m_multicaster->subscribe (m_o1, "beck")); assert (m_multicaster->subscribe (m_o1, "gamma")); assert (m_multicaster->subscribe (m_o2, "beck")); assert (m_multicaster->subscribe (m_o2, "gamma")); assert (m_multicaster->subscribe (m_o2, "demeter")); m_multicaster->unsubscribeFromAll (m_o2); assert (m_multicaster->publish (NULL, "alpha", value)); assert (m_multicaster->publish (NULL, "beck", value)); assert (m_multicaster->publish (NULL, "gamma", value)); assert (m_multicaster->publish (NULL, "demeter", value)); assert (*m_o1 == Observer ("gamma", 3)); assert (*m_o2 == Observer ()); } Test *MulticasterTest::suite () { TestSuite *suite = new TestSuite ("Multicaster"); TestSuite *single = new TestSuite ("Single"); TestSuite *multi = new TestSuite ("Multi"); single->addTest (new MulticasterTest("testSinglePublish")); single->addTest (new MulticasterTest("testSingleUnsubscribe")); single->addTest (new MulticasterTest("testSimpleUnsubscribeAll")); multi->addTest (new MulticasterTest("testMultipleHomogenousPublish")); multi->addTest (new MulticasterTest("testMultipleHeterogenousPublish")); multi->addTest (new MulticasterTest("testMultipleUnsubscribe")); suite->addTest (single); suite->addTest (multi); suite->addTest (new MulticasterTest("testComplexUnsubscribeAll")); return suite; }
[ [ [ 1, 181 ] ] ]
85e9466b00797b69aab026437df61dd9bd5cbf65
68bfdfc18f1345d1ff394b8115681110644d5794
/Examples/Example01/ModelLoader.h
f22ffd3844ee548ab73b543812c6fcf5a3925f67
[]
no_license
y-gupta/glwar3
43afa1efe475d937ce0439464b165c745e1ec4b1
bea5135bd13f9791b276b66490db76d866696f9a
refs/heads/master
2021-05-28T12:20:41.532727
2010-12-09T07:52:12
2010-12-09T07:52:12
32,911,819
1
0
null
null
null
null
UTF-8
C++
false
false
952
h
#pragma once //+----------------------------------------------------------------------------- //| Included files //+----------------------------------------------------------------------------- #include "Model.h" //+----------------------------------------------------------------------------- //| Model loader class //+----------------------------------------------------------------------------- class MODEL_LOADER { public: CONSTRUCTOR MODEL_LOADER(); DESTRUCTOR ~MODEL_LOADER(); virtual BOOL Save(MODEL& Model, CONST std::string& FileName, BUFFER& Buffer) = 0; virtual BOOL Load(MODEL& Model, CONST std::string& FileName, BUFFER& Buffer) = 0; protected: static std::string CurrentFileName; }; //+----------------------------------------------------------------------------- //| Post-included files //+----------------------------------------------------------------------------- #include "ModelLoaderMdx.h"
[ "sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83" ]
[ [ [ 1, 30 ] ] ]
cbed16de4d9b05854b2233ee1cb403a256430ab5
61bcb936a14064e2a819269d25b5c09b92dad45f
/Reference/EDK_project/code/GUI/HIO/HIO.cpp
ae771292debe0dc4bd761355bfb5d31de80f6449
[]
no_license
lanxinwoaini/robotic-vision-631
47fe73588a5b51296b9ac7fbacd4a553e4fd8e34
fdb160a8498ec668a32116c655368d068110aba7
refs/heads/master
2021-01-10T08:06:58.829618
2011-04-20T15:19:06
2011-04-20T15:19:06
47,861,917
1
0
null
null
null
null
UTF-8
C++
false
false
3,641
cpp
// HIO.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "HIO.h" #include "MainFrm.h" #include "HIODoc.h" #include "HIOView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CHIOApp BEGIN_MESSAGE_MAP(CHIOApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CHIOApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) END_MESSAGE_MAP() // CHIOApp construction CHIOApp::CHIOApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CHIOApp object CHIOApp theApp; // CHIOApp initialization BOOL CHIOApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; //InitCommonControlsEx(&InitCtrls); //Added to allow the use of WinXP style controls (i.e. newer looking buttons) InitCommonControls(); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("HIO")); LoadStdProfileSettings(0); // Load standard INI file options (including MRU) // User Initialization Code Here // Load up the Helios Library HInit(); HStart(); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CHIODoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CHIOView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(): CDialog(CAboutDlg::IDD){} enum { IDD = IDD_ABOUTBOX }; }; // App command to run the dialog void CHIOApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CHIOApp message handlers int CHIOApp::ExitInstance() { //Exiting Application. Need to close down Background threads HStop(); return CWinApp::ExitInstance(); }
[ [ [ 1, 144 ] ] ]
6d7cbdb8c1ab32c998268649d77cc9dea2debf17
ef25bd96604141839b178a2db2c008c7da20c535
/src/src/AIToolkit/AStar.h
5156739a9adb9bc4d7be76fc316248f390cb491b
[]
no_license
OtterOrder/crock-rising
fddd471971477c397e783dc6dd1a81efb5dc852c
543dc542bb313e1f5e34866bd58985775acf375a
refs/heads/master
2020-12-24T14:57:06.743092
2009-07-15T17:15:24
2009-07-15T17:15:24
32,115,272
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,681
h
#ifndef _ASTAR_H_ #define _ASTAR_H_ #include "AIMap.h" #include <map> #include <math.h> #include <iostream> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; //----------------------------------- struct node { pair<int,int> parent; // Son node parent... float costG; // Cout pour aller du départ au node considéré float costH; // Cout pour aller du node considéré à l'arrivé float costF; // Somme des node précédents }; struct point { int x, y; }; typedef map< pair<int, int>, node > listNode; //----------------------------------- class AStar { public: AStar(); ~AStar(void); pair<int,int> findWay( int debutX, int debutY, int finX, int finY ); pair<int,int> randomSpawn(); protected: pair<int,int> bestNode(listNode& l); // Retourne le meilleur node de la liste ouverte int distance( int x1, int y1, int x2, int y2 ); // Calcul de la distance euclidienne entre 2 points bool isInList(pair<int,int> n, listNode& l); // Retour true si un node est déja présent dans une liste void addSquareAdjacent(pair <int,int>& n); // Recupere les node et les ajoutes ou non a la liste ouverte void addToBlackList(pair<int,int>& p); // Passe un node de la liste ouverte a la liste fermée void findCompleteWay(); // Retrouve le chemin quand la destination est atteinte point pointEnd; node pointStart; listNode listOpen; listNode blackList; vector<point> chemin; int maxIteration; int cptChemin; static const int MAX_TAB = 256; int tabChemin[MAX_TAB][MAX_TAB]; pair<int,int> lastWayPoint; vector<pair<int,int>> listSpawn; }; #endif
[ "olivier.levaque@7c6770cc-a6a4-11dd-91bf-632da8b6e10b" ]
[ [ [ 1, 66 ] ] ]
f436fdb81261732ef928a8b25b2624f0a38a4ae0
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/SLB/src/Hybrid.cpp
7b77aca92039f7a631f88e711ba47b97c353e66c
[]
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
13,620
cpp
/* SLB - Simple Lua Binder Copyright (C) 2007 Jose L. Hidalgo Valiño (PpluX) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Jose L. Hidalgo (www.pplux.com) [email protected] */ #include <SLB/Hybrid.hpp> #include <SLB/lua.hpp> #include <SLB/Manager.hpp> #include <sstream> #include <iostream> namespace SLB { /*--- Invalid Method (exception) ----------------------------------------------*/ InvalidMethod::InvalidMethod(const HybridBase *obj, const char *c) { SLB_DEBUG_CALL; lua_State *L = obj->getLuaState(); const ClassInfo *CI = obj->getClassInfo(); std::ostringstream out; lua_Debug debug; out << "Invalid Method '" << CI->getName() << "::" << c << "' NOT FOUND!" << std::endl; out << "TraceBack:" << std::endl; for ( int level = 0; lua_getstack(L, level, &debug ); level++) { if (lua_getinfo(L, "Sln", &debug) ) { //TODO use debug.name and debug.namewhat //make this more friendly out << "\t [ " << level << " (" << debug.what << ") ] "; if (debug.currentline > 0 ) { out << debug.short_src << ":" << debug.currentline; if (debug.name) out << " @ " << debug.name << "(" << debug.namewhat << ")"; } out << std::endl; } else { out << "[ERROR using Lua DEBUG INTERFACE]" << std::endl; } } out << "Current Stack:" << std::endl; for(int i = 1; i < lua_gettop(L); ++i) { out << "\t ["<<i<<"] " << lua_typename(L, lua_type(L,i)) << " : "<< lua_tostring(L,i) ; ClassInfo *ci = Manager::getInstance().getClass(L,i); if (ci) out << "->" << ci->getName(); out << std::endl; } _what = out.str(); } /*--- Invalid Method (exception) ----------------------------------------------*/ /*--- HybridBase::AutoLock ----------------------------------------------------*/ HybridBase::AutoLock::AutoLock(const HybridBase *hconst) { SLB_DEBUG_CALL; //TODO: Review this! (should be const?) _hybrid = const_cast<HybridBase*>(hconst); SLB_DEBUG(6, "Lock state %p to access hybrid method (%p)", _hybrid->_L, (void*) _hybrid); _hybrid->lockBegin( _hybrid->_L ); } HybridBase::AutoLock::~AutoLock() { SLB_DEBUG_CALL; SLB_DEBUG(6, "Unlock state %p to access hybrid method (%p)", _hybrid->_L, (void*) _hybrid); _hybrid->lockEnd( _hybrid->_L); } /*--- HybridBase::AutoLock -------------------------------------*/ /*--- Internal Hybrid Subclasses ---------------------------------------*/ struct InternalHybridSubclass : public Table { InternalHybridSubclass(ClassInfo *ci) : _CI(ci) { SLB_DEBUG_CALL; assert("Invalid ClassInfo" && _CI.valid()); } int __newindex(lua_State *L) { SLB_DEBUG_CALL; SLB_DEBUG_CLEAN_STACK(L,-2); SLB_DEBUG_STACK(6,L, "Call InternalHybridSubclass(%p)::__nexindex", this); //1 = table //2 = string //3 = function luaL_checkstring(L,2); if (lua_type(L,3) != LUA_TFUNCTION) { luaL_error(L, "Only functions can be added to hybrid classes" " (invalid %s of type %s)", lua_tostring(L,2), lua_typename(L, 3)); } SLB_DEBUG(4, "Added method to an hybrid-subclass:%s", lua_tostring(L,2)); lua_pushcclosure(L, HybridBase::call_lua_method, 1); // replaces setCache(L); return 0; } int __call(lua_State *L) { SLB_DEBUG_CALL; SLB_DEBUG_STACK(6,L, "Call InternalHybridSubclass(%p)::__call", this); // create new instance: ref_ptr<FuncCall> fc = _CI->getConstructor(); assert("Invalid Constructor!" && fc.valid()); fc->push(L); lua_replace(L,1); // table of metamethod __call lua_call(L, lua_gettop(L) -1 , LUA_MULTRET); { SLB_DEBUG_CLEAN_STACK(L,0); // at 1 we should have an HybridBase instance... HybridBase *obj = SLB::get<HybridBase*>(L,1); if (obj == 0) luaL_error(L, "Output(1) of constructor should be an HybridBase instance"); // now our table... to find methods obj->_subclassMethods = this; } return lua_gettop(L); } private: ref_ptr<ClassInfo> _CI; }; /*--- Internal Hybrid Subclasses ----------------------------------------------*/ HybridBase::HybridBase() : _L(0), _global_environment(0) { SLB_DEBUG_CALL; } HybridBase::~HybridBase() { SLB_DEBUG_CALL; unAttach(); } void HybridBase::attach(lua_State *L) { SLB_DEBUG_CALL; //TODO allow reattaching... if (_L) throw std::runtime_error("Trying to reattach an Hybrid instance"); if (L) { SLB_DEBUG_CLEAN_STACK(L,0); _L = L; lua_newtable(_L); // [+1] //TODO this can be improved a little bit... by storing this metatable //somewhere.... lua_newtable(_L); // [+1] metatable lua_pushvalue(_L, LUA_GLOBALSINDEX); // [+1] globals _G lua_setfield(_L, -2, "__index"); // [-1] metatable.__index = _G lua_setmetatable(L,-2); // [-1] // done _global_environment = luaL_ref(_L, LUA_REGISTRYINDEX); // [-1] } } void HybridBase::unAttach() { SLB_DEBUG_CALL; clearMethodMap(); _subclassMethods = 0; if (_L && _global_environment ) { luaL_unref(_L, LUA_REGISTRYINDEX, _global_environment); _global_environment = 0; _L = 0; } } void HybridBase::clearMethodMap() { SLB_DEBUG_CALL; // delete the list of _methods for(MethodMap::iterator i = _methods.begin(); i != _methods.end(); i++ ) { delete i->second; } _methods.clear(); } bool HybridBase::getMethod(const char *name) const { SLB_DEBUG_CALL; if (_L == 0) throw std::runtime_error("Hybrid instance not attached");\ SLB_DEBUG_STACK(5,_L, "HybridBase(%p)::getMethod '%s' (_L = %p)", this, name, _L); int top = lua_gettop(_L); // first try to find in _subclassMethods if (_subclassMethods.valid()) { //TODO: NEED DEBUG... // ---- why not: // Object *m = obj->_subclassMethods->get(key); // if (m) // { // SLB_DEBUG(5, "Hybrid subclassed instance, looking for '%s' method [OK]", key); // m->push(L); // return 1; // } // else SLB_DEBUG(5, "Hybrid subclassed instance, looking for '%s' method [FAIL!]", key); // ---- instead of: (even though this is quicker) but code above should work lua_pushstring(_L,name); // [+1] _subclassMethods->getCache(_L); // [-1, +1] will pop key's copy and return the cache if (!lua_isnil(_L,-1)) { assert("Invalid Stack" && (lua_gettop(_L) == top+1)); return true; } lua_pop(_L,1); // [-1] remove nil assert("Invalid Stack" && (lua_gettop(_L) == top)); //end TODO------------------------------------------------------------------------------- } ClassInfo *ci = getClassInfo(); ci->push(_L); lua_getmetatable(_L,-1); lua_getfield(_L,-1, "__hybrid"); if (!lua_isnil(_L,-1)) { lua_pushstring(_L,name); lua_rawget(_L,-2); if (!lua_isnil(_L,-1)) { lua_replace(_L,top+1); lua_settop(_L,top+1); SLB_DEBUG(6, "HybridBase(%p-%s)::getMethod '%s' (_L = %p) -> FOUND", this, ci->getName().c_str(),name, _L); assert("Invalid Stack" && (lua_gettop(_L) == top+1)); return true; } else SLB_DEBUG(6, "HybridBase(%p-%s)::getMethod '%s' (_L = %p) -> *NOT* FOUND", this,ci->getName().c_str(), name, _L); } else SLB_DEBUG(4, "HybridBase(%p-%s) do not have any hybrid methods", this, ci->getName().c_str()); // anyway... if not found: lua_settop(_L,top); return false; } void HybridBase::setMethod(lua_State *L, ClassInfo *ci) { SLB_DEBUG_CALL; SLB_DEBUG_CLEAN_STACK(L,-2); // key // value [top] int top = lua_gettop(L); // checks key, value assert( "Invalid key for method" && lua_type(L,top-1) == LUA_TSTRING); assert( "Invalid type of method" && lua_type(L,top) == LUA_TFUNCTION); ci->push(L); // top +1 lua_getmetatable(L,-1); // top +2 lua_getfield(L,-1, "__hybrid"); // top +3 // create if not exists if (lua_isnil(L,-1)) { lua_pop(L,1); // remove nil lua_newtable(L); // top +3 lua_pushstring(L, "__hybrid"); lua_pushvalue(L,-2); // a copy for ClassInfo lua_rawset(L, top+2); // set to he metatable } lua_insert(L,top-2); // put the __hybrid table below key,value lua_settop(L, top+1); // table, key, and value lua_rawset(L,top-2); // set elements lua_settop(L, top-2); // remove everything :) } void HybridBase::registerAsHybrid(ClassInfo *ci) { SLB_DEBUG_CALL; //TODO: Check first if the class already has __index, __newindex //Maybe this should be a feature at ClassInfo to warn in case //the user sets these functions more than once. ci->setClass__newindex( FuncCall::create(class__newindex) ); ci->setClass__index( FuncCall::create(class__index) ); ci->setObject__index( FuncCall::create(object__index) ); ci->setHybrid(); } const HybridBase* get_hybrid(lua_State *L, int pos) { SLB_DEBUG_CALL; //TODO: Generalize this to be used in all SLB const HybridBase *obj = get<const HybridBase*>(L,pos); if (!obj) { if (lua_type(L,pos) == LUA_TUSERDATA) { void *dir = lua_touserdata(L,pos); // try to get the class info: ClassInfo *ci = Manager::getInstance().getClass(L,pos); if (ci == 0) { luaL_error(L, "Invalid Hybrid object (index=%d) " "'%s' %p", pos, ci->getName().c_str(), dir); } else { luaL_error(L, "Invalid Hybrid object (index=%d) " "userdata (NOT REGISTERED WITH SLB) %p", pos, dir); } } else { luaL_error(L, "Invalid Hybrid object (index=%d) found %s", pos, luaL_typename(L,pos)); } } return obj; } int HybridBase::call_lua_method(lua_State *L) { SLB_DEBUG_CALL; const HybridBase *hb = get_hybrid( L, 1 ); if (hb->_L == 0) luaL_error(L, "Instance(%p) not attached to any lua_State...", hb); if (hb->_L != L) luaL_error(L, "This instance(%p) is attached to another lua_State(%p)", hb, hb->_L); // get the real function to call lua_pushvalue(L, lua_upvalueindex(1)); // get the environment (from object) and set it lua_rawgeti(L, LUA_REGISTRYINDEX, hb->_global_environment); lua_setfenv(L,-2); lua_insert(L,1); //put the target function at 1 SLB_DEBUG_STACK(10, L, "Hybrid(%p)::call_lua_method ...", hb); lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); return lua_gettop(L); } int HybridBase::class__newindex(lua_State *L) { SLB_DEBUG_CALL; SLB_DEBUG_CLEAN_STACK(L,-2); // 1 - obj (table with classInfo) ClassInfo *ci = Manager::getInstance().getClass(L,1); if (ci == 0) luaL_error(L, "Invalid Class at #1"); // 2 - key (string) const int key = 2; // 3 - value (func) const int value = 3; if (lua_isstring(L,key) && lua_isfunction(L,value)) { // create a closure with the function to call lua_pushcclosure(L, HybridBase::call_lua_method, 1); // replaces [value] setMethod(L, ci); } else { luaL_error(L, "hybrid instances can only have new methods (functions) " "indexed by strings ( called with: class[ (%s) ] = (%s) )", lua_typename(L, lua_type(L,key)), lua_typename(L, lua_type(L,value)) ); } return 0; } int HybridBase::object__index(lua_State *L) { SLB_DEBUG_CALL; SLB_DEBUG_CLEAN_STACK(L,+1); SLB_DEBUG(4, "HybridBase::object__index"); // 1 - obj (table with classInfo) HybridBase* obj = get<HybridBase*>(L,1); if (obj == 0) luaL_error(L, "Invalid instance at #1"); if (!obj->_L) luaL_error(L, "Hybrid instance not attached or invalid method"); if (obj->_L != L) luaL_error(L, "Can not use that object outside its lua_state(%p)", obj->_L); // 2 - key (string) (at top) const char *key = lua_tostring(L,2); // call getMethod of hybrid (basic) if(!obj->getMethod(key)) luaL_error(L, "Invalid method %s", key); assert("Invalid stored function" && (lua_type(L,-1) == LUA_TFUNCTION) ); return 1; } int HybridBase::class__index(lua_State *L) { SLB_DEBUG_CALL; SLB_DEBUG_CLEAN_STACK(L,+1); SLB_DEBUG_STACK(6, L, "Call class__index"); // trying to traverse the class... create a new InternalHybridSubclass ClassInfo *ci = Manager::getInstance().getClass(L,1); if (ci == 0) luaL_error(L, "Expected a valid class."); luaL_checkstring(L,2); // only valid with strings if (!ci->hasConstructor()) { luaL_error(L, "Hybrid Class(%s) doesn't have constructor." " You can not subclass(%s) from it", ci->getName().c_str(), lua_tostring(L,2)); } ref_ptr<InternalHybridSubclass> subc = new InternalHybridSubclass(ci); subc->push(L); // -- set cache... lua_pushvalue(L,2); // [+1] key lua_pushvalue(L,-2); // [+1] copy of new InternalHybrid... ci->setCache(L); // [-2] keep a copy in the cache // -- set cache done return 1; } }
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 441 ] ] ]
a6f0986b3e267b0fac625d1fce908c59a00b9f60
82afdf1a0de48235b75a9b6ca61c9dbcfefcfafa
/ParseLiteral.h
9ecf59897ff508abfdd4b6f0c0876df48fe4c1de
[]
no_license
shilrobot/shilscript_plus_plus
eec85d01074ec379da63abe00562d7663c664398
09dbdbdadc28d131fa3c8026b14015336a55ed62
refs/heads/master
2021-01-25T00:17:10.004698
2009-12-16T22:45:52
2009-12-16T22:45:52
2,589,159
0
0
null
null
null
null
UTF-8
C++
false
false
239
h
#ifndef SS_PARSELITERAL_H #define SS_PARSELITERAL_H #include "Prereqs.h" namespace SS { i4 ParseDecimal(const String& str); i4 ParseHex(const String& str); i4 ParseOctal(const String& str); } #endif // SS_PARSELITERAL_H
[ "shilbert@6dcb506c-49f4-8c44-b148-53dce8eab73e" ]
[ [ [ 1, 14 ] ] ]
525f672171138eb14844e4da5c63360bcaefa5ec
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGameNeedle/GameNeedleComponent/src/RotationComponent.cpp
217dfbaabce86b0c5104fd860cc71809d6660913
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,507
cpp
#include "GameNeedleComponentStableHeaders.h" #include "RotationComponent.h" #include "CRotationInterface.h" #include <orz/View_OGRE3D/OgreRenderingQueuedListener.h> namespace Orz { class _UpdateInOgreRenderingQueued : public OgreRenderingQueuedListener { public: _UpdateInOgreRenderingQueued(RotationComponent * animation):_animation(animation),_enable(false) { _frameDurationHistory.push_back(WORLD_UPDATE_INTERVAL); } virtual ~_UpdateInOgreRenderingQueued(void) { } inline bool run(void) { Orz::OgreGraphicsManager::getSingleton().addRenderingQueuedListener(this); _enable = true; return true; } inline TimeType getExactLastFrameDuration(TimeType t) { if (t > 0.200f) { t = _frameDurationHistory.back(); } return t; } inline TimeType getPredictedFrameDuration () const { TimeType totalFrameTime = 0; std::deque<TimeType>::const_iterator it; for (it = _frameDurationHistory.begin(); it != _frameDurationHistory.end(); ++it) totalFrameTime += *it; return totalFrameTime/_frameDurationHistory.size(); } void addToFrameHistory (TimeType t) { _frameDurationHistory.push_back (t); if (_frameDurationHistory.size () > (unsigned int) 20) _frameDurationHistory.pop_front (); } virtual bool update(TimeType interval) { TimeType t = getExactLastFrameDuration(interval); addToFrameHistory(t); TimeType pt = getPredictedFrameDuration(); _enable = _animation->_implUpdate(pt); return true; } inline bool isEnable(void) { return _enable; } inline void stop(void) { Orz::OgreGraphicsManager::getSingleton().removeRenderingQueuedListener(this); } private: RotationComponent * _animation; bool _enable; std::deque<TimeType> _frameDurationHistory; }; } using namespace Orz; inline float sub360(float value) { while(value>=360.f) { value-=360.f; } return value; } inline float getAll(float start, float end) { start = sub360(start); if(start >= end) { return end +360 - start; }else return end - start; } std::pair<float, float> RotationComponent::getStartAll(float start, float end) { return std::make_pair(sub360(start), getAll(start,end)); } void RotationComponent::_play2(std::pair<float, float> & startAllDegree, TimeType allTime) { play(startAllDegree.first, startAllDegree.second, allTime); } bool RotationComponent::update(TimeType interval) { bool ret = _update->isEnable(); if(!ret) { if(_rotationInterface->_callback) _rotationInterface->_callback(_curAngle, true); _update->stop(); } return ret; } bool RotationComponent::_implUpdate(TimeType interval) { static TimeType at = 0.f; at += interval; if(at > (3600.f *24.f)) { _curTime+=interval; } _curTime += interval; setAngle(time2Degree(_curTime)); return _curTime < _allTime; } //_enableUpdate(void); //_disableUpdate(void); void RotationComponent::reset(float angle) { _startDegree = angle; _endDegree = angle; setAngle(angle); } //float RotateAnimation::getAngle(void) //{ // return _animState->getTimePosition(); //} void RotationComponent::setAngle(float angle) { using namespace Ogre; _curAngle = angle; Quaternion q; q.FromAngleAxis( Ogre::Radian(Degree(angle * _direction)),Vector3::UNIT_Y); if(_rotationInterface->_callback) _rotationInterface->_callback(angle, false); _node->setOrientation(q); } float RotationComponent::getAngle(void) const { return _curAngle + _offsetAngle; } void RotationComponent::_play(float allDegree, TimeType allTime) { play(_endDegree, allDegree, allTime); } void RotationComponent::play(float startDegree, float allDegree, TimeType allTime) { _startDegree = startDegree; _endDegree = startDegree + allDegree; _allTime = allTime; _curTime = 0; _angle = startDegree; _update->run(); //_timer->start(0.01f); //_enableUpdate(); } float RotationComponent::interpolation(float value) { float newvalue = (value * Ogre::Math::PI) - (Ogre::Math::PI/2); return (Ogre::Math::Sin(newvalue) +1.f)/2.f; } float RotationComponent::time2Degree(TimeType time) { if(time > _allTime || _allTime == 0) return _endDegree; return interpolation(time/_allTime) * (_endDegree - _startDegree) +_startDegree; } RotationComponent::RotationComponent(void):_rotationInterface(new CRotationInterface),_node(NULL),_angle(0),_curAngle(0.f),_direction(1),_offsetAngle(0.f) { _update.reset(new _UpdateInOgreRenderingQueued(this)); _rotationInterface->init = boost::bind(&RotationComponent::init, this, _1, _2, _3); _rotationInterface->reset = boost::bind(&RotationComponent::reset, this, _1); _rotationInterface->update = boost::bind(&RotationComponent::update, this, _1); _rotationInterface->play = boost::bind(&RotationComponent::_play, this, _1, _2); _rotationInterface->play2 = boost::bind(&RotationComponent::_play2, this, _1, _2); } RotationComponent::~RotationComponent(void) { } bool RotationComponent::init(Ogre::SceneNode * node, CRotationInterface::DIRECTION direction, float offset) { _offsetAngle = offset; _node = node; _direction = (direction == CRotationInterface::Clockwise)? -1: 1; return true; } ComponentInterface * RotationComponent::_queryInterface(const TypeInfo & info) { if(info == TypeInfo(typeid(CRotationInterface))) return _rotationInterface.get(); return NULL; }
[ [ [ 1, 234 ] ] ]
d8dbbac783893709e190710bd52d8779b91e070b
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/skin_lite/include/SkinLite/ReceiveFilesFrame.h
701388755777ebe84285dfd26fa9be42236d786b
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
4,782
h
///////////////////////////////////////////////////////////////////////////// // Name: ReceiveFilesFrame.h // Purpose: // Author: // Modified by: // Created: 20/05/2008 10:01:06 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// #ifndef _RECEIVEFILESFRAME_H_ #define _RECEIVEFILESFRAME_H_ /*! * Includes */ #include "wx/frame.h" #include "wx/animate.h" #include "AppInterface.h" /*! * Forward declarations */ class wxBoxSizer; /*! * Control identifiers */ enum{ ID_RECEIVEFILESFRAME = 800, ID_RECEIVEFILESFRAME_MAINPANEL, ID_RECEIVEFILESFRAME_GAUGE_RECEIVEDFILE, ID_RECEIVEFILESFRAME_TXT_FILENAME, ID_RECEIVEFILESFRAME_BTN_SAVE, ID_RECEIVEFILESFRAME_BTN_ACCEPT, ID_RECEIVEFILESFRAME_BTN_CANCEL }; #define SYMBOL_RECEIVEFILESFRAME_STYLE wxCAPTION|wxSYSTEM_MENU//|wxCLOSE_BOX|wxFRAME_NO_TASKBAR|wxRESIZE_BORDER #define SYMBOL_RECEIVEFILESFRAME_TITLE _("Receive Files") #define SYMBOL_RECEIVEFILESFRAME_IDNAME ID_RECEIVEFILESFRAME #define SYMBOL_RECEIVEFILESFRAME_SIZE wxDefaultSize #define SYMBOL_RECEIVEFILESFRAME_POSITION wxDefaultPosition #define TIMER_INTERVAL 1000 // in miliseconds /** @brief Class thats implements receive files window. * * When a user thats have voice send a file, the others users receiving this window informing the status of file download. */ class ReceiveFilesFrame: public wxFrame { private: DECLARE_CLASS( ReceiveFilesFrame ) DECLARE_EVENT_TABLE() bool m_renameFile; AppInterface* m_appInterface; long m_mediaId; wxString m_fileName; wxString m_tempFilePath; wxString m_senderNick; unsigned long m_fileSize; unsigned m_packetSize; bool m_receptionFinished; unsigned long m_lastPacket; unsigned long m_currentPacket; wxTimer m_timer; wxBoxSizer* m_mainVertSizer; wxPanel* m_mainPanel; wxBoxSizer* m_mainPanelVertSizer; wxStaticBox* m_groupBoxReceiveFileTransferSizer; wxStaticText* m_lblReceivingFileInf; wxStaticText* m_lblSizeCaption; wxStaticText* m_lblSizeLength; wxStaticText* m_lblReceivedCaption; wxStaticText* m_lblReceivedPercentual; wxStaticText* m_lblBytesReceivedCaption; wxStaticText* m_lblBytesReceived; wxStaticText* m_lblRemainingTimeCaption; wxStaticText* m_lblRemainingTime; wxStaticText* m_lblBitrateCaption; wxStaticText* m_lblBitrateLength; wxGauge* m_gaugeReceivedFile; wxBoxSizer* m_recoverInfSizer; wxStaticText* m_lblPackagesToRecoverCaption; wxStaticText* m_lblPackagesToRecoverCount; wxBoxSizer* m_ctrlSizer; wxButton* m_btnAccept; wxButton* m_btnCancel; wxAnimation m_animatedGif; wxAnimationCtrl *m_receiveAnimatedGif; void SizeToSizeLabel(unsigned long size, wxString &label); public: /// Constructors ReceiveFilesFrame(); ReceiveFilesFrame( wxWindow* parent, AppInterface* iface, wxWindowID id = SYMBOL_RECEIVEFILESFRAME_IDNAME, const wxString& caption = SYMBOL_RECEIVEFILESFRAME_TITLE, const wxPoint& pos = SYMBOL_RECEIVEFILESFRAME_POSITION, const wxSize& size = SYMBOL_RECEIVEFILESFRAME_SIZE, long style = SYMBOL_RECEIVEFILESFRAME_STYLE ); bool Create( wxWindow* parent, wxWindowID id = SYMBOL_RECEIVEFILESFRAME_IDNAME, const wxString& caption = SYMBOL_RECEIVEFILESFRAME_TITLE, const wxPoint& pos = SYMBOL_RECEIVEFILESFRAME_POSITION, const wxSize& size = SYMBOL_RECEIVEFILESFRAME_SIZE, long style = SYMBOL_RECEIVEFILESFRAME_STYLE ); // Destructor ~ReceiveFilesFrame(); // Initialises member variables void Init(); // Creates the controls and sizers void CreateControls(); void OnFileTransferReceptionBegin( long mediaId, const wxString &fileName, const wxString &tempFilePath, const wxString &senderNick, unsigned long fileSize, unsigned packetSize, bool renameFile); void OnFileTransferReceptionProgress(unsigned long currentPacketIndex, unsigned long lastPacketIndex); void OnFileTransferReceptionLostPacket(unsigned long lostPackets); void OnFileTransferReceptionSuccess(); void OnFileTransferReceptionError(); void OnBtnSaveClick( wxCommandEvent& event ); void OnBtnAcceptClick( wxCommandEvent& event ); void OnBtnCancelClick( wxCommandEvent& event ); void OnTimer( wxTimerEvent& event ); void OnClose(wxCloseEvent &event); // Retrieves bitmap resources wxBitmap GetBitmapResource( const wxString& name ); // Retrieves icon resources wxIcon GetIconResource( const wxString& name ); // Should we show tooltips? static bool ShowToolTips(); }; #endif // _RECEIVEFILESFRAME_H_
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 150 ] ] ]
a90e5dafcc5a8dc4924d3f66fe43ddecee4df13c
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/ibgeneratoreditor.hpp
856b5c5574b2fd75987d069123b68ca030d71a56
[]
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
2,607
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IBGeneratorEditor.pas' rev: 6.00 #ifndef IBGeneratorEditorHPP #define IBGeneratorEditorHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <ExtCtrls.hpp> // Pascal unit #include <StdCtrls.hpp> // Pascal unit #include <Dialogs.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Ibgeneratoreditor { //-- type declarations ------------------------------------------------------- class DELPHICLASS TfrmGeneratorEditor; class PASCALIMPLEMENTATION TfrmGeneratorEditor : public Forms::TForm { typedef Forms::TForm inherited; __published: Stdctrls::TLabel* Label1; Stdctrls::TLabel* Label2; Stdctrls::TButton* OKBtn; Stdctrls::TButton* CancelBtn; Stdctrls::TComboBox* cbxGenerators; Stdctrls::TComboBox* cbxFields; Extctrls::TRadioGroup* grpApplyEvent; Stdctrls::TButton* HelpBtn; Stdctrls::TLabel* Label3; Stdctrls::TEdit* edtIncrement; public: #pragma option push -w-inl /* TCustomForm.Create */ inline __fastcall virtual TfrmGeneratorEditor(Classes::TComponent* AOwner) : Forms::TForm(AOwner) { } #pragma option pop #pragma option push -w-inl /* TCustomForm.CreateNew */ inline __fastcall virtual TfrmGeneratorEditor(Classes::TComponent* AOwner, int Dummy) : Forms::TForm(AOwner, Dummy) { } #pragma option pop #pragma option push -w-inl /* TCustomForm.Destroy */ inline __fastcall virtual ~TfrmGeneratorEditor(void) { } #pragma option pop public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TfrmGeneratorEditor(HWND ParentWindow) : Forms::TForm(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE TfrmGeneratorEditor* frmGeneratorEditor; } /* namespace Ibgeneratoreditor */ using namespace Ibgeneratoreditor; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IBGeneratorEditor
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 76 ] ] ]
b6fb3eb56771da6396f167420768c889d11d74fd
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Animation/Animation/Deform/Skinning/Fpu/hkaFPUSkinningDeformer.h
d3213886104481f9264a744e0711cd7bd3bcd427
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,377
h
/* * * 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-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_FPU_SKINNING_DEFORMER_H #define HK_FPU_SKINNING_DEFORMER_H #include <Animation/Animation/Deform/Skinning/hkaSkinningDeformer.h> class hkxVertexBuffer; /// The derived reference counted class for a FPU based implementation of weighted vertex deformation. /// Applies to both indexed and non indexed skinning. /// This is a pure, normal floating point only deformer. If neither your input /// or you output is hkVector4 aligned and you are not using a SIMD enabled /// hkMath library, then this relatively slow float version is at least better /// than using the simd ones when there is no simd ops enabled. /// N.B. It is important to note that these deformers are here to be used by Havok's demos but are not production quality. /// It is assumed that deforming will be done most commonly by your graphics engine, usually in hardware on GPUs or VUs. /// That hardware deformation is usually performed at the same time as per vertex lighting operations, so Havok cannot /// provide optimized deformers for all such game specific usage. class hkaFPUSkinningDeformer : public hkReferencedObject, public hkaSkinningDeformer { public: /// Constructs an unbound deformer hkaFPUSkinningDeformer(); /// Bind this deformer to input and output buffers. /// The input format is assumed to have (at least) vertex weights. /// The output buffer should be preallocated. /// Returns false if the deformer does not support the input or output buffer format. hkBool bind( const hkaVertexDeformerInput& input, const hkxVertexBuffer* inputBuffer, hkxVertexBuffer* outputBuffer ); /// Deform the input buffer into the output buffer using the array of matrices specified. /// The deformer must first be bound and the output buffer locked before deforming. virtual void deform( const hkTransform* m_worldCompositeMatrices ); struct hkaFloatBinding { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME, hkaFPUSkinningDeformer::hkaFloatBinding ); // Input buffer const float* m_iPosBase; const float* m_iNormBase; const float* m_iBinormBase; const float* m_iTangentBase; const hkUint8* m_iWeightBase; const hkUint8* m_iIndexBase; hkUint8 m_iPosStride; // in num floats hkUint8 m_iNormStride; // in num floats hkUint8 m_iBinormStride; // in num floats hkUint8 m_iTangentStride;// in num floats hkUint8 m_iWeightStride; // in num bytes hkUint8 m_iIndexStride; // in num bytes hkUint8 m_bonesPerVertex; // Output Buffer float* m_oPosBase; float* m_oNormBase; float* m_oBinormBase; float* m_oTangentBase; hkUint8 m_oPosStride; // ALL STRIDES IN NUM FLOATS hkUint8 m_oNormStride; hkUint8 m_oBinormStride; hkUint8 m_oTangentStride; hkUint32 m_numVerts; }; /// Static version of the virtual deform, takes an explicit binding /// so you can use this if you don't have hkxVertexBuffer style data static void HK_CALL deform( const hkTransform* m_worldCompositeMatrices, const hkaFloatBinding& binding ); protected: struct hkaFloatBinding m_binding; }; #endif // HK_FLOAT_SKINNING_DEFORMER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * 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. * */
[ [ [ 1, 99 ] ] ]
774face7dd467b5c91ab1f835023e43ca876abf3
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/IlmImf/ImfTiledOutputFile.cpp
e670086864b2b192473862aeecead979d01cf0c9
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
43,756
cpp
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledOutputFile // //----------------------------------------------------------------------------- #include <ImfTiledOutputFile.h> #include <ImfTiledInputFile.h> #include <ImfInputFile.h> #include <ImfTileDescriptionAttribute.h> #include <ImfPreviewImageAttribute.h> #include <ImfChannelList.h> #include <ImfMisc.h> #include <ImfTiledMisc.h> #include <ImfStdIO.h> #include <ImfCompressor.h> #include "ImathBox.h" #include <ImfArray.h> #include <ImfXdr.h> #include <ImfVersion.h> #include <ImfTileOffsets.h> #include <ImfThreading.h> #include "IlmThreadPool.h" #include "IlmThreadSemaphore.h" #include "IlmThreadMutex.h" #include "Iex.h" #include <string> #include <vector> #include <fstream> #include <assert.h> #include <map> namespace Imf { using Imath::Box2i; using Imath::V2i; using std::string; using std::vector; using std::ofstream; using std::map; using std::min; using std::max; using std::swap; using IlmThread::Mutex; using IlmThread::Lock; using IlmThread::Semaphore; using IlmThread::Task; using IlmThread::TaskGroup; using IlmThread::ThreadPool; namespace { struct TOutSliceInfo { PixelType type; const char * base; size_t xStride; size_t yStride; bool zero; int xTileCoords; int yTileCoords; TOutSliceInfo (PixelType type = HALF, const char *base = 0, size_t xStride = 0, size_t yStride = 0, bool zero = false, int xTileCoords = 0, int yTileCoords = 0); }; TOutSliceInfo::TOutSliceInfo (PixelType t, const char *b, size_t xs, size_t ys, bool z, int xtc, int ytc) : type (t), base (b), xStride (xs), yStride (ys), zero (z), xTileCoords (xtc), yTileCoords (ytc) { // empty } struct TileCoord { int dx; int dy; int lx; int ly; TileCoord (int xTile = 0, int yTile = 0, int xLevel = 0, int yLevel = 0) : dx (xTile), dy (yTile), lx (xLevel), ly (yLevel) { // empty } bool operator < (const TileCoord &other) const { return (ly < other.ly) || (ly == other.ly && lx < other.lx) || ((ly == other.ly && lx == other.lx) && ((dy < other.dy) || (dy == other.dy && dx < other.dx))); } bool operator == (const TileCoord &other) const { return lx == other.lx && ly == other.ly && dx == other.dx && dy == other.dy; } }; struct BufferedTile { char * pixelData; int pixelDataSize; BufferedTile (const char *data, int size): pixelData (0), pixelDataSize(size) { pixelData = new char[pixelDataSize]; memcpy (pixelData, data, pixelDataSize); } ~BufferedTile() { delete [] pixelData; } }; typedef map <TileCoord, BufferedTile *> TileMap; struct TileBuffer { Array<char> buffer; const char * dataPtr; int dataSize; Compressor * compressor; TileCoord tileCoord; bool hasException; string exception; TileBuffer (Compressor *comp); ~TileBuffer (); inline void wait () {_sem.wait();} inline void post () {_sem.post();} protected: Semaphore _sem; }; TileBuffer::TileBuffer (Compressor *comp): dataPtr (0), dataSize (0), compressor (comp), hasException (false), exception (), _sem (1) { // empty } TileBuffer::~TileBuffer () { delete compressor; } } // namespace struct TiledOutputFile::Data: public Mutex { Header header; // the image header int version; // file format version TileDescription tileDesc; // describes the tile layout FrameBuffer frameBuffer; // framebuffer to write into Int64 previewPosition; LineOrder lineOrder; // the file's lineorder int minX; // data window's min x coord int maxX; // data window's max x coord int minY; // data window's min y coord int maxY; // data window's max x coord int numXLevels; // number of x levels int numYLevels; // number of y levels int * numXTiles; // number of x tiles at a level int * numYTiles; // number of y tiles at a level TileOffsets tileOffsets; // stores offsets in file for // each tile Compressor::Format format; // compressor's data format vector<TOutSliceInfo> slices; // info about channels in file OStream * os; // file stream to write to bool deleteStream; size_t maxBytesPerTileLine; // combined size of a tile line // over all channels vector<TileBuffer*> tileBuffers; size_t tileBufferSize; // size of a tile buffer Int64 tileOffsetsPosition; // position of the tile index Int64 currentPosition; // current position in the file TileMap tileMap; TileCoord nextTileToWrite; Data (bool del, int numThreads); ~Data (); inline TileBuffer * getTileBuffer (int number); // hash function from tile // buffer coords into our // vector of tile buffers TileCoord nextTileCoord (const TileCoord &a); }; TiledOutputFile::Data::Data (bool del, int numThreads): numXTiles(0), numYTiles(0), os (0), deleteStream (del), tileOffsetsPosition (0) { // // We need at least one tileBuffer, but if threading is used, // to keep n threads busy we need 2*n tileBuffers // tileBuffers.resize (max (1, 2 * numThreads)); } TiledOutputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; if (deleteStream) delete os; // // Delete all the tile buffers, if any still happen to exist // for (TileMap::iterator i = tileMap.begin(); i != tileMap.end(); ++i) delete i->second; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; } TileBuffer* TiledOutputFile::Data::getTileBuffer (int number) { return tileBuffers[number % tileBuffers.size()]; } TileCoord TiledOutputFile::Data::nextTileCoord (const TileCoord &a) { TileCoord b = a; if (lineOrder == INCREASING_Y) { b.dx++; if (b.dx >= numXTiles[b.lx]) { b.dx = 0; b.dy++; if (b.dy >= numYTiles[b.ly]) { // // the next tile is in the next level // b.dy = 0; switch (tileDesc.mode) { case ONE_LEVEL: case MIPMAP_LEVELS: b.lx++; b.ly++; break; case RIPMAP_LEVELS: b.lx++; if (b.lx >= numXLevels) { b.lx = 0; b.ly++; #ifdef DEBUG assert (b.ly <= numYLevels); #endif } break; } } } } else if (lineOrder == DECREASING_Y) { b.dx++; if (b.dx >= numXTiles[b.lx]) { b.dx = 0; b.dy--; if (b.dy < 0) { // // the next tile is in the next level // switch (tileDesc.mode) { case ONE_LEVEL: case MIPMAP_LEVELS: b.lx++; b.ly++; break; case RIPMAP_LEVELS: b.lx++; if (b.lx >= numXLevels) { b.lx = 0; b.ly++; #ifdef DEBUG assert (b.ly <= numYLevels); #endif } break; } if (b.ly < numYLevels) b.dy = numYTiles[b.ly] - 1; } } } return b; } namespace { void writeTileData (TiledOutputFile::Data *ofd, int dx, int dy, int lx, int ly, const char pixelData[], int pixelDataSize) { // // Store a block of pixel data in the output file, and try // to keep track of the current writing position the file, // without calling tellp() (tellp() can be fairly expensive). // Int64 currentPosition = ofd->currentPosition; ofd->currentPosition = 0; if (currentPosition == 0) currentPosition = ofd->os->tellp(); ofd->tileOffsets (dx, dy, lx, ly) = currentPosition; #ifdef DEBUG assert (ofd->os->tellp() == currentPosition); #endif // // Write the tile header. // Xdr::write <StreamIO> (*ofd->os, dx); Xdr::write <StreamIO> (*ofd->os, dy); Xdr::write <StreamIO> (*ofd->os, lx); Xdr::write <StreamIO> (*ofd->os, ly); Xdr::write <StreamIO> (*ofd->os, pixelDataSize); ofd->os->write (pixelData, pixelDataSize); // // Keep current position in the file so that we can avoid // redundant seekg() operations (seekg() can be fairly expensive). // ofd->currentPosition = currentPosition + 5 * Xdr::size<int>() + pixelDataSize; } void bufferedTileWrite (TiledOutputFile::Data *ofd, int dx, int dy, int lx, int ly, const char pixelData[], int pixelDataSize) { // // Check if a tile with coordinates (dx,dy,lx,ly) has already been written. // if (ofd->tileOffsets (dx, dy, lx, ly)) { THROW (Iex::ArgExc, "Attempt to write tile " "(" << dx << ", " << dy << ", " << lx << "," << ly << ") " "more than once."); } // // If tiles can be written in random order, then don't buffer anything. // if (ofd->lineOrder == RANDOM_Y) { writeTileData (ofd, dx, dy, lx, ly, pixelData, pixelDataSize); return; } // // If the tiles cannot be written in random order, then check if a // tile with coordinates (dx,dy,lx,ly) has already been buffered. // TileCoord currentTile = TileCoord(dx, dy, lx, ly); if (ofd->tileMap.find (currentTile) != ofd->tileMap.end()) { THROW (Iex::ArgExc, "Attempt to write tile " "(" << dx << ", " << dy << ", " << lx << "," << ly << ") " "more than once."); } // // If all the tiles before this one have already been written to the file, // then write this tile immediately and check if we have buffered tiles // that can be written after this tile. // // Otherwise, buffer the tile so it can be written to file later. // if (ofd->nextTileToWrite == currentTile) { writeTileData (ofd, dx, dy, lx, ly, pixelData, pixelDataSize); ofd->nextTileToWrite = ofd->nextTileCoord (ofd->nextTileToWrite); TileMap::iterator i = ofd->tileMap.find (ofd->nextTileToWrite); // // Step through the tiles and write all successive buffered tiles after // the current one. // while(i != ofd->tileMap.end()) { // // Write the tile, and then delete the tile's buffered data // writeTileData (ofd, i->first.dx, i->first.dy, i->first.lx, i->first.ly, i->second->pixelData, i->second->pixelDataSize); delete i->second; ofd->tileMap.erase (i); // // Proceed to the next tile // ofd->nextTileToWrite = ofd->nextTileCoord (ofd->nextTileToWrite); i = ofd->tileMap.find (ofd->nextTileToWrite); } } else { // // Create a new BufferedTile, copy the pixelData into it, and // insert it into the tileMap. // ofd->tileMap[currentTile] = new BufferedTile ((const char *)pixelData, pixelDataSize); } } void convertToXdr (TiledOutputFile::Data *ofd, Array<char>& tileBuffer, int numScanLines, int numPixelsPerScanLine) { // // Convert the contents of a TiledOutputFile's tileBuffer from the // machine's native representation to Xdr format. This function is called // by writeTile(), below, if the compressor wanted its input pixel data // in the machine's native format, but then failed to compress the data // (most compressors will expand rather than compress random input data). // // Note that this routine assumes that the machine's native representation // of the pixel data has the same size as the Xdr representation. This // makes it possible to convert the pixel data in place, without an // intermediate temporary buffer. // // // Set these to point to the start of the tile. // We will write to toPtr, and read from fromPtr. // char *writePtr = tileBuffer; const char *readPtr = writePtr; // // Iterate over all scan lines in the tile. // for (int y = 0; y < numScanLines; ++y) { // // Iterate over all slices in the file. // for (unsigned int i = 0; i < ofd->slices.size(); ++i) { const TOutSliceInfo &slice = ofd->slices[i]; // // Convert the samples in place. // convertInPlace (writePtr, readPtr, slice.type, numPixelsPerScanLine); } } #ifdef DEBUG assert (writePtr == readPtr); #endif } // // A TileBufferTask encapsulates the task of copying a tile from // the user's framebuffer into a LineBuffer and compressing the data // if necessary. // class TileBufferTask: public Task { public: TileBufferTask (TaskGroup *group, TiledOutputFile::Data *ofd, int number, int dx, int dy, int lx, int ly); virtual ~TileBufferTask (); virtual void execute (); private: TiledOutputFile::Data * _ofd; TileBuffer * _tileBuffer; }; TileBufferTask::TileBufferTask (TaskGroup *group, TiledOutputFile::Data *ofd, int number, int dx, int dy, int lx, int ly) : Task (group), _ofd (ofd), _tileBuffer (_ofd->getTileBuffer (number)) { // // Wait for the tileBuffer to become available // _tileBuffer->wait (); _tileBuffer->tileCoord = TileCoord (dx, dy, lx, ly); } TileBufferTask::~TileBufferTask () { // // Signal that the tile buffer is now free // _tileBuffer->post (); } void TileBufferTask::execute () { try { // // First copy the pixel data from the frame buffer // into the tile buffer // // Convert one tile's worth of pixel data to // a machine-independent representation, and store // the result in _tileBuffer->buffer. // char *writePtr = _tileBuffer->buffer; Box2i tileRange = Imf::dataWindowForTile (_ofd->tileDesc, _ofd->minX, _ofd->maxX, _ofd->minY, _ofd->maxY, _tileBuffer->tileCoord.dx, _tileBuffer->tileCoord.dy, _tileBuffer->tileCoord.lx, _tileBuffer->tileCoord.ly); int numScanLines = tileRange.max.y - tileRange.min.y + 1; int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1; // // Iterate over the scan lines in the tile. // for (int y = tileRange.min.y; y <= tileRange.max.y; ++y) { // // Iterate over all image channels. // for (unsigned int i = 0; i < _ofd->slices.size(); ++i) { const TOutSliceInfo &slice = _ofd->slices[i]; // // These offsets are used to facilitate both absolute // and tile-relative pixel coordinates. // int xOffset = slice.xTileCoords * tileRange.min.x; int yOffset = slice.yTileCoords * tileRange.min.y; // // Fill the tile buffer with pixel data. // if (slice.zero) { // // The frame buffer contains no data for this channel. // Store zeroes in _data->tileBuffer. // fillChannelWithZeroes (writePtr, _ofd->format, slice.type, numPixelsPerScanLine); } else { // // The frame buffer contains data for this channel. // const char *readPtr = slice.base + (y - yOffset) * slice.yStride + (tileRange.min.x - xOffset) * slice.xStride; const char *endPtr = readPtr + (numPixelsPerScanLine - 1) * slice.xStride; copyFromFrameBuffer (writePtr, readPtr, endPtr, slice.xStride, _ofd->format, slice.type); } } } // // Compress the contents of the tileBuffer, // and store the compressed data in the output file. // _tileBuffer->dataSize = writePtr - _tileBuffer->buffer; _tileBuffer->dataPtr = _tileBuffer->buffer; if (_tileBuffer->compressor) { const char *compPtr; int compSize = _tileBuffer->compressor->compressTile (_tileBuffer->dataPtr, _tileBuffer->dataSize, tileRange, compPtr); if (compSize < _tileBuffer->dataSize) { _tileBuffer->dataSize = compSize; _tileBuffer->dataPtr = compPtr; } else if (_ofd->format == Compressor::NATIVE) { // // The data did not shrink during compression, but // we cannot write to the file using native format, // so we need to convert the lineBuffer to Xdr. // convertToXdr (_ofd, _tileBuffer->buffer, numScanLines, numPixelsPerScanLine); } } } catch (std::exception &e) { if (!_tileBuffer->hasException) { _tileBuffer->exception = e.what (); _tileBuffer->hasException = true; } } catch (...) { if (!_tileBuffer->hasException) { _tileBuffer->exception = "unrecognized exception"; _tileBuffer->hasException = true; } } } } // namespace TiledOutputFile::TiledOutputFile (const char fileName[], const Header &header, int numThreads) : _data (new Data (true, numThreads)) { try { header.sanityCheck (true); _data->os = new StdOFStream (fileName); initialize (header); } catch (Iex::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << fileName << "\". " << e); throw; } catch (...) { delete _data; throw; } } TiledOutputFile::TiledOutputFile (OStream &os, const Header &header, int numThreads) : _data (new Data (false, numThreads)) { try { header.sanityCheck(true); _data->os = &os; initialize (header); } catch (Iex::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << os.fileName() << "\". " << e); throw; } catch (...) { delete _data; throw; } } void TiledOutputFile::initialize (const Header &header) { _data->header = header; _data->lineOrder = _data->header.lineOrder(); // // Check that the file is indeed tiled // _data->tileDesc = _data->header.tileDescription(); // // Save the dataWindow information // const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; // // Precompute level and tile information to speed up utility functions // precalculateTileInfo (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, _data->numXTiles, _data->numYTiles, _data->numXLevels, _data->numYLevels); // // Determine the first tile coordinate that we will be writing // if the file is not RANDOM_Y. // _data->nextTileToWrite = (_data->lineOrder == INCREASING_Y)? TileCoord (0, 0, 0, 0): TileCoord (0, _data->numYTiles[0] - 1, 0, 0); _data->maxBytesPerTileLine = calculateBytesPerPixel (_data->header) * _data->tileDesc.xSize; _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize; // // Create all the TileBuffers and allocate their internal buffers // for (size_t i = 0; i < _data->tileBuffers.size(); i++) { _data->tileBuffers[i] = new TileBuffer (newTileCompressor (_data->header.compression(), _data->maxBytesPerTileLine, _data->tileDesc.ySize, _data->header)); _data->tileBuffers[i]->buffer.resizeErase(_data->tileBufferSize); } _data->format = defaultFormat (_data->tileBuffers[0]->compressor); _data->tileOffsets = TileOffsets (_data->tileDesc.mode, _data->numXLevels, _data->numYLevels, _data->numXTiles, _data->numYTiles); _data->previewPosition = _data->header.writeTo (*_data->os, true); _data->tileOffsetsPosition = _data->tileOffsets.writeTo (*_data->os); _data->currentPosition = _data->os->tellp(); } TiledOutputFile::~TiledOutputFile () { if (_data) { { if (_data->tileOffsetsPosition > 0) { try { _data->os->seekp (_data->tileOffsetsPosition); _data->tileOffsets.writeTo (*_data->os); } catch (...) { // // We cannot safely throw any exceptions from here. // This destructor may have been called because the // stack is currently being unwound for another // exception. // } } } delete _data; } } const char * TiledOutputFile::fileName () const { return _data->os->fileName(); } const Header & TiledOutputFile::header () const { return _data->header; } void TiledOutputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_data); // // Check if the new frame buffer descriptor // is compatible with the image file header. // const ChannelList &channels = _data->header.channels(); for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) { FrameBuffer::ConstIterator j = frameBuffer.find (i.name()); if (j == frameBuffer.end()) continue; if (i.channel().type != j.slice().type) THROW (Iex::ArgExc, "Pixel type of \"" << i.name() << "\" channel " "of output file \"" << fileName() << "\" is " "not compatible with the frame buffer's " "pixel type."); if (j.slice().xSampling != 1 || j.slice().ySampling != 1) THROW (Iex::ArgExc, "All channels in a tiled file must have" "sampling (1,1)."); } // // Initialize slice table for writePixels(). // vector<TOutSliceInfo> slices; for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) { FrameBuffer::ConstIterator j = frameBuffer.find (i.name()); if (j == frameBuffer.end()) { // // Channel i is not present in the frame buffer. // In the file, channel i will contain only zeroes. // slices.push_back (TOutSliceInfo (i.channel().type, 0, // base 0, // xStride, 0, // yStride, true)); // zero } else { // // Channel i is present in the frame buffer. // slices.push_back (TOutSliceInfo (j.slice().type, j.slice().base, j.slice().xStride, j.slice().yStride, false, // zero (j.slice().xTileCoords)? 1: 0, (j.slice().yTileCoords)? 1: 0)); } } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; } const FrameBuffer & TiledOutputFile::frameBuffer () const { Lock lock (*_data); return _data->frameBuffer; } void TiledOutputFile::writeTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly) { try { Lock lock (*_data); if (_data->slices.size() == 0) throw Iex::ArgExc ("No frame buffer specified " "as pixel data source."); if (!isValidTile (dx1, dy1, lx, ly) || !isValidTile (dx2, dy2, lx, ly)) throw Iex::ArgExc ("Tile coordinates are invalid."); // // Determine the first and last tile coordinates in both dimensions // based on the file's lineOrder // if (dx1 > dx2) swap (dx1, dx2); if (dy1 > dy2) swap (dy1, dy2); int dyStart = dy1; int dyStop = dy2 + 1; int dY = 1; if (_data->lineOrder == DECREASING_Y) { dyStart = dy2; dyStop = dy1 - 1; dY = -1; } int numTiles = (dx2 - dx1 + 1) * (dy2 - dy1 + 1); int numTasks = min ((int)_data->tileBuffers.size(), numTiles); // // Create a task group for all tile buffer tasks. When the // task group goes out of scope, the destructor waits until // all tasks are complete. // { TaskGroup taskGroup; // // Add in the initial compression tasks to the thread pool // int nextCompBuffer = 0; int dxComp = dx1; int dyComp = dyStart; while (nextCompBuffer < numTasks) { ThreadPool::addGlobalTask (new TileBufferTask (&taskGroup, _data, nextCompBuffer++, dxComp, dyComp, lx, ly)); dxComp++; if (dxComp > dx2) { dxComp = dx1; dyComp += dY; } } // // Write the compressed buffers and add in more compression // tasks until done // int nextWriteBuffer = 0; int dxWrite = dx1; int dyWrite = dyStart; while (nextWriteBuffer < numTiles) { // // Wait until the nextWriteBuffer is ready to be written // TileBuffer* writeBuffer = _data->getTileBuffer (nextWriteBuffer); writeBuffer->wait(); // // Write the tilebuffer // bufferedTileWrite (_data, dxWrite, dyWrite, lx, ly, writeBuffer->dataPtr, writeBuffer->dataSize); // // Release the lock on nextWriteBuffer // writeBuffer->post(); // // If there are no more tileBuffers to compress, then // only continue to write out remaining tileBuffers, // otherwise keep adding compression tasks. // if (nextCompBuffer < numTiles) { // // add nextCompBuffer as a compression Task // ThreadPool::addGlobalTask (new TileBufferTask (&taskGroup, _data, nextCompBuffer, dxComp, dyComp, lx, ly)); } nextWriteBuffer++; dxWrite++; if (dxWrite > dx2) { dxWrite = dx1; dyWrite += dY; } nextCompBuffer++; dxComp++; if (dxComp > dx2) { dxComp = dx1; dyComp += dY; } } // // finish all tasks // } // // Exeption handling: // // TileBufferTask::execute() may have encountered exceptions, but // those exceptions occurred in another thread, not in the thread // that is executing this call to TiledOutputFile::writeTiles(). // TileBufferTask::execute() has caught all exceptions and stored // the exceptions' what() strings in the tile buffers. // Now we check if any tile buffer contains a stored exception; if // this is the case then we re-throw the exception in this thread. // (It is possible that multiple tile buffers contain stored // exceptions. We re-throw the first exception we find and // ignore all others.) // const string *exception = 0; for (size_t i = 0; i < _data->tileBuffers.size(); ++i) { TileBuffer *tileBuffer = _data->tileBuffers[i]; if (tileBuffer->hasException && !exception) exception = &tileBuffer->exception; tileBuffer->hasException = false; } if (exception) throw Iex::IoExc (*exception); } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Failed to write pixel data to image " "file \"" << fileName() << "\". " << e); throw; } } void TiledOutputFile::writeTiles (int dx1, int dxMax, int dyMin, int dyMax, int l) { writeTiles (dx1, dxMax, dyMin, dyMax, l, l); } void TiledOutputFile::writeTile (int dx, int dy, int lx, int ly) { writeTiles (dx, dx, dy, dy, lx, ly); } void TiledOutputFile::writeTile (int dx, int dy, int l) { writeTile(dx, dy, l, l); } void TiledOutputFile::copyPixels (TiledInputFile &in) { Lock lock (*_data); // // Check if this file's and and the InputFile's // headers are compatible. // const Header &hdr = _data->header; const Header &inHdr = in.header(); if (!hdr.hasTileDescription() || !inHdr.hasTileDescription()) THROW (Iex::ArgExc, "Cannot perform a quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\". The " "output file is tiled, but the input file is not. " "Try using OutputFile::copyPixels() instead."); if (!(hdr.tileDescription() == inHdr.tileDescription())) THROW (Iex::ArgExc, "Quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\" failed. " "The files have different tile descriptions."); if (!(hdr.dataWindow() == inHdr.dataWindow())) THROW (Iex::ArgExc, "Cannot copy pixels from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\". The " "files have different data windows."); if (!(hdr.lineOrder() == inHdr.lineOrder())) THROW (Iex::ArgExc, "Quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\" failed. " "The files have different line orders."); if (!(hdr.compression() == inHdr.compression())) THROW (Iex::ArgExc, "Quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\" failed. " "The files use different compression methods."); if (!(hdr.channels() == inHdr.channels())) THROW (Iex::ArgExc, "Quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << fileName() << "\" " "failed. The files have different channel " "lists."); // // Verify that no pixel data have been written to this file yet. // if (!_data->tileOffsets.isEmpty()) THROW (Iex::LogicExc, "Quick pixel copy from image " "file \"" << in.fileName() << "\" to image " "file \"" << _data->os->fileName() << "\" " "failed. \"" << fileName() << "\" " "already contains pixel data."); // // Calculate the total number of tiles in the file // int numAllTiles = 0; switch (levelMode ()) { case ONE_LEVEL: case MIPMAP_LEVELS: for (int i_l = 0; i_l < numLevels (); ++i_l) numAllTiles += numXTiles (i_l) * numYTiles (i_l); break; case RIPMAP_LEVELS: for (int i_ly = 0; i_ly < numYLevels (); ++i_ly) for (int i_lx = 0; i_lx < numXLevels (); ++i_lx) numAllTiles += numXTiles (i_lx) * numYTiles (i_ly); break; default: throw Iex::ArgExc ("Unknown LevelMode format."); } for (int i = 0; i < numAllTiles; ++i) { const char *pixelData; int pixelDataSize; int dx = _data->nextTileToWrite.dx; int dy = _data->nextTileToWrite.dy; int lx = _data->nextTileToWrite.lx; int ly = _data->nextTileToWrite.ly; in.rawTileData (dx, dy, lx, ly, pixelData, pixelDataSize); writeTileData (_data, dx, dy, lx, ly, pixelData, pixelDataSize); } } void TiledOutputFile::copyPixels (InputFile &in) { copyPixels (*in.tFile()); } unsigned int TiledOutputFile::tileXSize () const { return _data->tileDesc.xSize; } unsigned int TiledOutputFile::tileYSize () const { return _data->tileDesc.ySize; } LevelMode TiledOutputFile::levelMode () const { return _data->tileDesc.mode; } LevelRoundingMode TiledOutputFile::levelRoundingMode () const { return _data->tileDesc.roundingMode; } int TiledOutputFile::numLevels () const { if (levelMode() == RIPMAP_LEVELS) THROW (Iex::LogicExc, "Error calling numLevels() on image " "file \"" << fileName() << "\" " "(numLevels() is not defined for RIPMAPs)."); return _data->numXLevels; } int TiledOutputFile::numXLevels () const { return _data->numXLevels; } int TiledOutputFile::numYLevels () const { return _data->numYLevels; } bool TiledOutputFile::isValidLevel (int lx, int ly) const { if (lx < 0 || ly < 0) return false; if (levelMode() == MIPMAP_LEVELS && lx != ly) return false; if (lx >= numXLevels() || ly >= numYLevels()) return false; return true; } int TiledOutputFile::levelWidth (int lx) const { try { int retVal = levelSize (_data->minX, _data->maxX, lx, _data->tileDesc.roundingMode); return retVal; } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Error calling levelWidth() on image " "file \"" << fileName() << "\". " << e); throw; } } int TiledOutputFile::levelHeight (int ly) const { try { return levelSize (_data->minY, _data->maxY, ly, _data->tileDesc.roundingMode); } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Error calling levelHeight() on image " "file \"" << fileName() << "\". " << e); throw; } } int TiledOutputFile::numXTiles (int lx) const { if (lx < 0 || lx >= _data->numXLevels) THROW (Iex::LogicExc, "Error calling numXTiles() on image " "file \"" << _data->os->fileName() << "\" " "(Argument is not in valid range)."); return _data->numXTiles[lx]; } int TiledOutputFile::numYTiles (int ly) const { if (ly < 0 || ly >= _data->numYLevels) THROW (Iex::LogicExc, "Error calling numXTiles() on image " "file \"" << _data->os->fileName() << "\" " "(Argument is not in valid range)."); return _data->numYTiles[ly]; } Box2i TiledOutputFile::dataWindowForLevel (int l) const { return dataWindowForLevel (l, l); } Box2i TiledOutputFile::dataWindowForLevel (int lx, int ly) const { try { return Imf::dataWindowForLevel (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, lx, ly); } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForLevel() on image " "file \"" << fileName() << "\". " << e); throw; } } Box2i TiledOutputFile::dataWindowForTile (int dx, int dy, int l) const { return dataWindowForTile (dx, dy, l, l); } Box2i TiledOutputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { try { if (!isValidTile (dx, dy, lx, ly)) throw Iex::ArgExc ("Arguments not in valid range."); return Imf::dataWindowForTile (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, dx, dy, lx, ly); } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForTile() on image " "file \"" << fileName() << "\". " << e); throw; } } bool TiledOutputFile::isValidTile (int dx, int dy, int lx, int ly) const { return ((lx < _data->numXLevels && lx >= 0) && (ly < _data->numYLevels && ly >= 0) && (dx < _data->numXTiles[lx] && dx >= 0) && (dy < _data->numYTiles[ly] && dy >= 0)); } void TiledOutputFile::updatePreviewImage (const PreviewRgba newPixels[]) { Lock lock (*_data); if (_data->previewPosition <= 0) THROW (Iex::LogicExc, "Cannot update preview image pixels. " "File \"" << fileName() << "\" does not " "contain a preview image."); // // Store the new pixels in the header's preview image attribute. // PreviewImageAttribute &pia = _data->header.typedAttribute <PreviewImageAttribute> ("preview"); PreviewImage &pi = pia.value(); PreviewRgba *pixels = pi.pixels(); int numPixels = pi.width() * pi.height(); for (int i = 0; i < numPixels; ++i) pixels[i] = newPixels[i]; // // Save the current file position, jump to the position in // the file where the preview image starts, store the new // preview image, and jump back to the saved file position. // Int64 savedPosition = _data->os->tellp(); try { _data->os->seekp (_data->previewPosition); pia.writeValueTo (*_data->os, _data->version); _data->os->seekp (savedPosition); } catch (Iex::BaseExc &e) { REPLACE_EXC (e, "Cannot update preview image pixels for " "file \"" << fileName() << "\". " << e); throw; } } void TiledOutputFile::breakTile (int dx, int dy, int lx, int ly, int offset, int length, char c) { Lock lock (*_data); Int64 position = _data->tileOffsets (dx, dy, lx, ly); if (!position) THROW (Iex::ArgExc, "Cannot overwrite tile " "(" << dx << ", " << dy << ", " << lx << "," << ly << "). " "The tile has not yet been stored in " "file \"" << fileName() << "\"."); _data->currentPosition = 0; _data->os->seekp (position + offset); for (int i = 0; i < length; ++i) _data->os->write (&c, 1); } } // namespace Imf
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 1692 ] ] ]
84507050eb9743dd705c6f3c7f757f399802c043
c3531ade6396e9ea9c7c9a85f7da538149df2d09
/Param/src/Param/ParamDrawer.h
644b9cd595d2838a971c3723e584441d809da44b
[]
no_license
feengg/MultiChart-Parameterization
ddbd680f3e1c2100e04c042f8f842256f82c5088
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
refs/heads/master
2020-03-28T16:43:51.242114
2011-04-19T17:18:44
2011-04-19T17:18:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,237
h
#ifndef PARAMDRAWER_H_ #define PARAMDRAWER_H_ #include "../Common/BasicDataType.h" #include "Barycentric.h" namespace PARAM { class Parameter; class SurfaceCoord; class ParamDrawer { public: enum DrawMode { DRAWNOTHING = 0x00000000, //! draw patch info DRAWLAYOUT = 0x00000001, DRAWPATCHCONNER = 0x00000011, DRAWPATCHEDGE = 0x000000021, DRAWPATCHFACE = 0x000000041, //! draw distortion info DRAWDISTORTION = 0x00000002, DRAWFACEHARMONICDISTORTION = 0x00000012, DRAWVERTEXHARMONICDISTORTION = 0x00000022, //! Draw texture DRAWFACETEXTURE = 0x00000004, //! Draw Corresponding DRAWCORRESPONGING = 0x00000008, DRAWSELECTION = 0x000000018 }; public: void SetUnCorrespondingVertArray(const std::vector<int>& uncorresponding_vert_array) { m_uncorrespondnig_vert_array = uncorresponding_vert_array; } void SetSelectedVertCoord(const Coord& select_coord); void SetSelectedVertCoord(const SurfaceCoord& select_coord); void SetSelectedPatchCoord(const Coord& select_coord); int FindSelectedVertId(const Coord& select_coord); SurfaceCoord FindSelectedSurfaceCoord(const Coord& select_coord); int GetSelectedVertID() const { return m_selected_vert_id; } SurfaceCoord GetSelectedSurfaceCorod() const { return m_selected_surface_coord; } public: void SetDrawMode(DrawMode mode){ m_draw_mode = mode;} void SetDrawPatchConner(bool is_draw) { m_draw_patch_conner = is_draw; } void SetDrawPatchEdge(bool is_draw) { m_draw_patch_edge = is_draw; } void SetDrawPatchFace(bool is_draw) { m_draw_patch_face = is_draw; } void SetDrawOutRangeVertices(bool is_draw) { m_draw_out_range_vertices = is_draw; } void SetDrawSelectedPatch(bool is_draw) { m_draw_select_patch = is_draw; } void SetDrawFlipFace(bool is_draw) { m_draw_flip_face = is_draw; } void SetDrawSelectedVertex(bool is_draw) { m_draw_selected_vertex = is_draw; } void SetDrawUnCorresponding(bool is_draw) { m_draw_uncorrespoinding = is_draw; } public: ParamDrawer(const Parameter& quad_param); ~ParamDrawer(); void Draw() const; private: void DrawPatchConner() const; void DrawPatchEdge() const; void DrawPatchFace() const; void DrawBaseDomain() const; void DrawOutRangeVertex() const; void DrawUnSetFace() const; void DrawFlipedFace() const; void DrawFaceDistortion() const; void DrawFaceTexture() const; void DrawCorresponding() const; void DrawUnCorrespondingVertex() const; void DrawSelectedPatch() const; void DrawSelectedVert() const; void DrawSphere(const Coord& center, double point_size = 1.0) const; private: const Parameter& m_parameter; std::vector<int> m_uncorrespondnig_vert_array; int m_selected_vert_id; Coord m_selected_vert_coord; SurfaceCoord m_selected_surface_coord; DrawMode m_draw_mode; bool m_draw_patch_conner; bool m_draw_patch_edge; bool m_draw_patch_face; bool m_draw_out_range_vertices; bool m_draw_flip_face; bool m_draw_selected_vertex; bool m_draw_select_patch; bool m_draw_uncorrespoinding; int m_selected_patch_id; }; } #endif // PARAMDRAWER_H_
[ [ [ 1, 117 ] ] ]
b21e1fa4c8a3196ffdcbf17284660545cf0f505c
2fb8c63d1ee7108c00bc9af656cd6ecf7174ae1b
/src/decomp/lzham_platform.cpp
ef2d4fbc3f679127ad5a6576f1eee7746f10f096
[ "MIT" ]
permissive
raedwulf/liblzham
542aca151a21837c14666f1d16957e61ba9c095d
01ce0ec2d78f4fda767122baa02ba612ed966440
refs/heads/master
2021-01-10T19:58:22.981658
2011-08-24T11:55:26
2011-08-24T11:55:26
2,227,012
3
0
null
null
null
null
UTF-8
C++
false
false
3,182
cpp
// File: platform.cpp // See Copyright Notice and license at the end of include/lzham.h #include "lzham_core.h" #include "lzham_timer.h" #if LZHAM_PLATFORM_X360 #include <xbdm.h> #endif #ifndef _MSC_VER int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...) { if (!sizeOfBuffer) return 0; va_list args; va_start(args, format); int c = vsnprintf(buffer, sizeOfBuffer, format, args); va_end(args); buffer[sizeOfBuffer - 1] = '\0'; if (c < 0) return sizeOfBuffer - 1; return LZHAM_MIN(c, (int)sizeOfBuffer - 1); } int vsprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, va_list args) { if (!sizeOfBuffer) return 0; int c = vsnprintf(buffer, sizeOfBuffer, format, args); buffer[sizeOfBuffer - 1] = '\0'; if (c < 0) return sizeOfBuffer - 1; return LZHAM_MIN(c, (int)sizeOfBuffer - 1); } #endif // __GNUC__ bool lzham_is_debugger_present(void) { #if LZHAM_PLATFORM_X360 return DmIsDebuggerPresent() != 0; #elif LZHAM_USE_WIN32_API return IsDebuggerPresent() != 0; #else return false; #endif } void lzham_debug_break(void) { #if LZHAM_USE_WIN32_API DebugBreak(); #endif } void lzham_output_debug_string(const char* p) { p; #if LZHAM_USE_WIN32_API OutputDebugStringA(p); #endif } #if LZHAM_BUFFERED_PRINTF // This stuff was a quick hack only intended for debugging/development. namespace lzham { struct buffered_str { enum { cBufSize = 256 }; char m_buf[cBufSize]; }; static lzham::vector<buffered_str> g_buffered_strings; static volatile long g_buffered_string_locked; static void lock_buffered_strings() { while (atomic_exchange32(&g_buffered_string_locked, 1) == 1) { lzham_yield_processor(); lzham_yield_processor(); lzham_yield_processor(); lzham_yield_processor(); } LZHAM_MEMORY_IMPORT_BARRIER } static void unlock_buffered_strings() { LZHAM_MEMORY_EXPORT_BARRIER atomic_exchange32(&g_buffered_string_locked, 0); } } // namespace lzham void lzham_buffered_printf(const char *format, ...) { format; char buf[lzham::buffered_str::cBufSize]; va_list args; va_start(args, format); vsnprintf_s(buf, sizeof(buf), sizeof(buf), format, args); va_end(args); buf[sizeof(buf) - 1] = '\0'; lzham::lock_buffered_strings(); if (!lzham::g_buffered_strings.capacity()) { lzham::g_buffered_strings.try_reserve(2048); } if (lzham::g_buffered_strings.try_resize(lzham::g_buffered_strings.size() + 1)) { memcpy(lzham::g_buffered_strings.back().m_buf, buf, sizeof(buf)); } lzham::unlock_buffered_strings(); } void lzham_flush_buffered_printf() { lzham::lock_buffered_strings(); for (lzham::uint i = 0; i < lzham::g_buffered_strings.size(); i++) { printf("%s", lzham::g_buffered_strings[i].m_buf); } lzham::g_buffered_strings.try_resize(0); lzham::unlock_buffered_strings(); } #endif
[ [ [ 1, 146 ] ] ]
caa7d4e6b8018adec9ed2ca62423487c3d42cee3
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/GameNode.inl
7e6f41c271b59271c65da84e1bc71254334ed409
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
846
inl
namespace Halak { template <typename T> T* GameNode::CreateAndAttachChild() { T* component = new T(); AttachChild(component); return component; } template <typename T> T* GameNode::FindChild(bool searchAllChildren) const { return static_cast<T*>(FindChildByClassID(T::ClassID, searchAllChildren)); } GameComponent* GameNode::GetComponent() const { return component; } GameNode* GameNode::GetParnet() const { return parent; } const GameNode::NodeCollection& GameNode::GetChildren() const { return children; } GameStructure* GameNode::GetStructure() const { return structure; } bool GameNode::IsRoot() const { return parent != nullptr; } }
[ [ [ 1, 40 ] ] ]
e1b83f11842e40c97eb10143661ff3d0c1f90787
5acd6b1bc0becbf091304800765644058b047899
/airplay/PartitionMain.cpp
150b9ba1e70bd1622c60fa376bfaad253367f699
[]
no_license
malfmalf/partition_old
0c53e6642aa512e411f580a2c8b88085f9483887
bb0dd7a3f362313e319da75fd2f13805ddae5db0
refs/heads/master
2022-11-08T18:36:52.830760
2011-02-14T14:55:07
2011-02-14T14:55:07
276,804,239
0
0
null
null
null
null
UTF-8
C++
false
false
4,035
cpp
/* * This file is part of the Airplay SDK Code Samples. * * Copyright (C) 2001-2010 Ideaworks3D Ltd. * All Rights Reserved. * * This source code is intended only as a supplement to Ideaworks Labs * Development Tools and/or on-line documentation. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ #include "s3e.h" #include "IwUtil.h" #include "Iw2D.h" #include "IwUI.h" #include <stdlib.h> #include <stdio.h> #include <string> #include <vector> #include "Ball.h" #include "Geometry.h" #include "Game.h" CIwSVec2 toscreen(const point2d_t& p){ return CIwSVec2(int(p.x),int(p.y)); } std::string gMessage; void fillScreen(const cGame& game,cLine* drawing_line =NULL){ Iw2DSurfaceClear(0); Iw2DSetColour(0xffffffff); for(size_t i = 0;i<game.lines().size();++i){ Iw2DDrawLine(toscreen(game.lines()[i].p1()),toscreen(game.lines()[i].p2())); } if(drawing_line){ if(game.collidingWithBalls(*drawing_line)) Iw2DSetColour(0xff0000ff); else Iw2DSetColour(0xffff00ff); Iw2DDrawLine(toscreen(drawing_line->p1()),toscreen(drawing_line->p2())); } Iw2DSetColour(0xff00ff00); for(size_t i = 0;i<game.balls().size();++i){ Iw2DDrawArc(toscreen(game.balls()[i].position()),toscreen(point2d_t(game.balls()[i].radius(),game.balls()[i].radius())),-IW_ANGLE_PI,IW_ANGLE_PI); } for(size_t i = 0;i<game.polygonScores().size();++i){ const cGame::PolygonScore& sc = game.polygonScores()[i]; char sc_text[100]; sprintf(sc_text,"%d",sc.score); Iw2DDrawString(sc_text,toscreen(sc.center),CIwSVec2(30,30),IW_2D_FONT_ALIGN_LEFT,IW_2D_FONT_ALIGN_TOP); } char text[300]; sprintf(text,"l:%d , s:%d",game.linesLeft(),game.score()); Iw2DDrawString(text,CIwSVec2(10,10),CIwSVec2(200,200),IW_2D_FONT_ALIGN_LEFT,IW_2D_FONT_ALIGN_TOP); Iw2DDrawString(game.message().c_str(),CIwSVec2(10,20),CIwSVec2(200,200),IW_2D_FONT_ALIGN_LEFT,IW_2D_FONT_ALIGN_TOP); Iw2DDrawString(gMessage.c_str(),CIwSVec2(10,30),CIwSVec2(300,600),IW_2D_FONT_ALIGN_LEFT,IW_2D_FONT_ALIGN_TOP); Iw2DSurfaceShow(); } int main(){ // Initialise Iw2DInit(); IwResManagerInit(); // Load the group containing the "arial14" font IwGetResManager()->LoadGroup("Iw2DStrings.group"); // Prepare the iwgxfont resource for rendering using Iw2D CIw2DFont* font = Iw2DCreateFontResource("trebuchet"); Iw2DSetFont(font); cGame game(s3eSurfaceGetInt(S3E_SURFACE_DEVICE_WIDTH),s3eSurfaceGetInt(S3E_SURFACE_DEVICE_HEIGHT)); game.reset(15,40.0); int64 last_time = s3eTimerGetMs(); bool drawing = false; point2d_t start_point; while (!s3eDeviceCheckQuitRequest()) { int64 t = s3eTimerGetMs(); int delta = t-last_time; last_time = t; if(game.step(delta/1000.0)!=cGame::RUNNING) break; s3eDeviceYield(0); s3eKeyboardUpdate(); s3ePointerUpdate(); point2d_t touch_point(s3ePointerGetX(),s3ePointerGetY()); if(s3ePointerGetState(S3E_POINTER_BUTTON_SELECT)==S3E_POINTER_STATE_DOWN){ if(!drawing){ start_point = touch_point; drawing = true; fillScreen(game); } else{ cLine line(start_point,touch_point); game.clipLine(line); fillScreen(game,&line); } } else{ if(drawing){ game.addLine(cLine(start_point,touch_point)); drawing = false; } fillScreen(game); } if (s3eKeyboardAnyKey()) break; } Iw2DTerminate(); return 0; }
[ [ [ 1, 123 ] ] ]
d8ad3303c18c4e8356aac9246c36f012b2701ac6
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kcore/mem/impl/LowFragHeap/LowFragHeap.h
9b1c3f1da11daabfc4883a773cadef7c462a34e6
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
1,397
h
#pragma once #include <new> namespace gk { /** * @class LowFragHeap * * @brief Allocator implementation that makes use of Low-fragmentation Heap * available on Windows XP & 2003 Server. */ class LowFragHeap { public: LowFragHeap(); void* Alloc(size_t size); void Free(void* p); private: HANDLE procHeap_; }; inline LowFragHeap::LowFragHeap() { ULONG HeapFragValue = 2; procHeap_ = GetProcessHeap(); HeapSetInformation( procHeap_ , HeapCompatibilityInformation , &HeapFragValue , sizeof(HeapFragValue) ); HeapQueryInformation( procHeap_ , HeapCompatibilityInformation , &HeapFragValue , sizeof(HeapFragValue) , NULL ); if (HeapFragValue != 2) { // Windows Low-fragment Heap won't work under a debugger! } } inline void* LowFragHeap::Alloc(size_t size) { void* p = HeapAlloc(procHeap_, 0, size); if (!p) { throw std::bad_alloc(); // ANSI/ISO compliant behavior } return p; } inline void LowFragHeap::Free(void* p) { if (!p) { return; } // may not pass a NULL pointer to HeapFree HeapFree(procHeap_, 0, p); } } // gk
[ "darkface@localhost" ]
[ [ [ 1, 67 ] ] ]
4fc4718d9b3e3546cfbbeb421d910c22aacb242b
028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32
/src/drivers/pooyan.cpp
a2d2f19a00afd84689384b1cda24e922abb486aa
[]
no_license
neonichu/iMame4All-for-iPad
72f56710d2ed7458594838a5152e50c72c2fb67f
4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611
refs/heads/master
2020-04-21T07:26:37.595653
2011-11-26T12:21:56
2011-11-26T12:21:56
2,855,022
4
0
null
null
null
null
UTF-8
C++
false
false
12,630
cpp
#include "../vidhrdw/pooyan.cpp" /*************************************************************************** Notes: - Several people claim that colors are wrong, but the way the color PROMs are used seems correct. Pooyan memory map (preliminary) driver by Allard Van Der Bas Thanks must go to Mike Cuddy for providing information on this one. Sound processor memory map. 0x3000-0x33ff RAM. AY-8910 #1 : reg 0x5000 wr 0x4000 rd 0x4000 AY-8910 #2 : reg 0x7000 wr 0x6000 rd 0x6000 Main processor memory map. 0000-7fff ROM 8000-83ff color RAM 8400-87ff video RAM 8800-8fff RAM 9000-97ff sprite RAM (only areas 0x9010 and 0x9410 are used). memory mapped ports: read: 0xA000 Dipswitch 2 adddbtll a = attract mode ddd = difficulty 0=easy, 7=hardest. b = bonus setting (easy/hard) t = table / upright ll = lives: 11=3, 10=4, 01=5, 00=255. 0xA0E0 llllrrrr l == left coin mech, r = right coinmech. 0xA080 IN0 Port 0xA0A0 IN1 Port 0xA0C0 IN2 Port write: 0xA100 command for the audio CPU. 0xA180 NMI enable. (0xA180 == 1 = deliver NMI to CPU). 0xA181 interrupt trigger on audio CPU. 0xA183 maybe reset sound cpu? 0xA184 ???? 0xA187 Flip screen interrupts: standard NMI at 0x66 ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" WRITE_HANDLER( pooyan_flipscreen_w ); void pooyan_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom); void pooyan_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); /* defined in sndhrdw/timeplt.c */ extern struct MemoryReadAddress timeplt_sound_readmem[]; extern struct MemoryWriteAddress timeplt_sound_writemem[]; extern struct AY8910interface timeplt_ay8910_interface; WRITE_HANDLER( timeplt_sh_irqtrigger_w ); static struct MemoryReadAddress readmem[] = { { 0x0000, 0x7fff, MRA_ROM }, { 0x8000, 0x8fff, MRA_RAM }, /* color and video RAM */ { 0xa000, 0xa000, input_port_4_r }, /* DSW2 */ { 0xa080, 0xa080, input_port_0_r }, /* IN0 */ { 0xa0a0, 0xa0a0, input_port_1_r }, /* IN1 */ { 0xa0c0, 0xa0c0, input_port_2_r }, /* IN2 */ { 0xa0e0, 0xa0e0, input_port_3_r }, /* DSW1 */ { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x0000, 0x7fff, MWA_ROM }, { 0x8000, 0x83ff, colorram_w, &colorram }, { 0x8400, 0x87ff, videoram_w, &videoram, &videoram_size }, { 0x8800, 0x8fff, MWA_RAM }, { 0x9010, 0x903f, MWA_RAM, &spriteram, &spriteram_size }, { 0x9410, 0x943f, MWA_RAM, &spriteram_2 }, { 0xa000, 0xa000, MWA_NOP }, /* watchdog reset? */ { 0xa100, 0xa100, soundlatch_w }, { 0xa180, 0xa180, interrupt_enable_w }, { 0xa181, 0xa181, timeplt_sh_irqtrigger_w }, { 0xa187, 0xa187, pooyan_flipscreen_w }, { -1 } /* end of table */ }; INPUT_PORTS_START( pooyan ) PORT_START /* IN0 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* IN1 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_2WAY ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_2WAY ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* IN2 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_2WAY | IPF_COCKTAIL ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_2WAY | IPF_COCKTAIL ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* DSW0 */ PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x02, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x09, DEF_STR( 1C_7C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x00, "Attract Mode - No Play" ) PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x50, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x40, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 4C_3C ) ) PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x30, DEF_STR( 3C_4C ) ) PORT_DIPSETTING( 0x70, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x60, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0xa0, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x90, DEF_STR( 1C_7C ) ) PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPSETTING( 0x01, "5" ) PORT_BITX( 0, 0x00, IPT_DIPSWITCH_SETTING | IPF_CHEAT, "255", IP_KEY_NONE, IP_JOY_NONE ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x08, "50000 80000" ) PORT_DIPSETTING( 0x00, "30000 70000" ) PORT_DIPNAME( 0x70, 0x70, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x70, "Easiest" ) PORT_DIPSETTING( 0x60, "Easier" ) PORT_DIPSETTING( 0x50, "Easy" ) PORT_DIPSETTING( 0x40, "Normal" ) PORT_DIPSETTING( 0x30, "Medium" ) PORT_DIPSETTING( 0x20, "Difficult" ) PORT_DIPSETTING( 0x10, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 4, /* 4 bits per pixel */ { 0x1000*8+4, 0x1000*8+0, 4, 0 }, { 0, 1, 2, 3, 8*8+0,8*8+1,8*8+2,8*8+3 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 16*8 /* every char takes 16 consecutive bytes */ }; static struct GfxLayout spritelayout = { 16,16, /* 16*16 sprites */ 64, /* 64 sprites */ 4, /* 4 bits per pixel */ { 0x1000*8+4, 0x1000*8+0, 4, 0 }, { 0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8 }, 64*8 /* every sprite takes 64 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 0, 16 }, { REGION_GFX2, 0, &spritelayout, 16*16, 16 }, { -1 } /* end of array */ }; static struct MachineDriver machine_driver_pooyan = { /* basic machine hardware */ { { CPU_Z80, 3072000, /* 3.072 Mhz (?) */ readmem,writemem,0,0, nmi_interrupt,1 }, { CPU_Z80 | CPU_AUDIO_CPU, 14318180/8, /* 1.789772727 MHz */ \ timeplt_sound_readmem,timeplt_sound_writemem,0,0, ignore_interrupt,1 /* interrupts are triggered by the main CPU */ } }, 60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 }, gfxdecodeinfo, 32,16*16+16*16, pooyan_vh_convert_color_prom, VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY, 0, generic_vh_start, generic_vh_stop, pooyan_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_AY8910, &timeplt_ay8910_interface } } }; /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( pooyan ) ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */ ROM_LOAD( "1.4a", 0x0000, 0x2000, 0xbb319c63 ) ROM_LOAD( "2.5a", 0x2000, 0x2000, 0xa1463d98 ) ROM_LOAD( "3.6a", 0x4000, 0x2000, 0xfe1a9e08 ) ROM_LOAD( "4.7a", 0x6000, 0x2000, 0x9e0f9bcc ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU */ ROM_LOAD( "xx.7a", 0x0000, 0x1000, 0xfbe2b368 ) ROM_LOAD( "xx.8a", 0x1000, 0x1000, 0xe1795b3d ) ROM_REGION( 0x2000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "8.10g", 0x0000, 0x1000, 0x931b29eb ) ROM_LOAD( "7.9g", 0x1000, 0x1000, 0xbbe6d6e4 ) ROM_REGION( 0x2000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "6.9a", 0x0000, 0x1000, 0xb2d8c121 ) ROM_LOAD( "5.8a", 0x1000, 0x1000, 0x1097c2b6 ) ROM_REGION( 0x0220, REGION_PROMS ) ROM_LOAD( "pooyan.pr1", 0x0000, 0x0020, 0xa06a6d0e ) /* palette */ ROM_LOAD( "pooyan.pr2", 0x0020, 0x0100, 0x82748c0b ) /* sprites */ ROM_LOAD( "pooyan.pr3", 0x0120, 0x0100, 0x8cd4cd60 ) /* characters */ ROM_END ROM_START( pooyans ) ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */ ROM_LOAD( "ic22_a4.cpu", 0x0000, 0x2000, 0x916ae7d7 ) ROM_LOAD( "ic23_a5.cpu", 0x2000, 0x2000, 0x8fe38c61 ) ROM_LOAD( "ic24_a6.cpu", 0x4000, 0x2000, 0x2660218a ) ROM_LOAD( "ic25_a7.cpu", 0x6000, 0x2000, 0x3d2a10ad ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU */ ROM_LOAD( "xx.7a", 0x0000, 0x1000, 0xfbe2b368 ) ROM_LOAD( "xx.8a", 0x1000, 0x1000, 0xe1795b3d ) ROM_REGION( 0x2000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "ic13_g10.cpu", 0x0000, 0x1000, 0x7433aea9 ) ROM_LOAD( "ic14_g9.cpu", 0x1000, 0x1000, 0x87c1789e ) ROM_REGION( 0x2000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "6.9a", 0x0000, 0x1000, 0xb2d8c121 ) ROM_LOAD( "5.8a", 0x1000, 0x1000, 0x1097c2b6 ) ROM_REGION( 0x0220, REGION_PROMS ) ROM_LOAD( "pooyan.pr1", 0x0000, 0x0020, 0xa06a6d0e ) /* palette */ ROM_LOAD( "pooyan.pr2", 0x0020, 0x0100, 0x82748c0b ) /* sprites */ ROM_LOAD( "pooyan.pr3", 0x0120, 0x0100, 0x8cd4cd60 ) /* characters */ ROM_END ROM_START( pootan ) ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */ ROM_LOAD( "poo_ic22.bin", 0x0000, 0x2000, 0x41b23a24 ) ROM_LOAD( "poo_ic23.bin", 0x2000, 0x2000, 0xc9d94661 ) ROM_LOAD( "3.6a", 0x4000, 0x2000, 0xfe1a9e08 ) ROM_LOAD( "poo_ic25.bin", 0x6000, 0x2000, 0x8ae459ef ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU */ ROM_LOAD( "xx.7a", 0x0000, 0x1000, 0xfbe2b368 ) ROM_LOAD( "xx.8a", 0x1000, 0x1000, 0xe1795b3d ) ROM_REGION( 0x2000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "poo_ic13.bin", 0x0000, 0x1000, 0x0be802e4 ) ROM_LOAD( "poo_ic14.bin", 0x1000, 0x1000, 0xcba29096 ) ROM_REGION( 0x2000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "6.9a", 0x0000, 0x1000, 0xb2d8c121 ) ROM_LOAD( "5.8a", 0x1000, 0x1000, 0x1097c2b6 ) ROM_REGION( 0x0220, REGION_PROMS ) ROM_LOAD( "pooyan.pr1", 0x0000, 0x0020, 0xa06a6d0e ) /* palette */ ROM_LOAD( "pooyan.pr2", 0x0020, 0x0100, 0x82748c0b ) /* sprites */ ROM_LOAD( "pooyan.pr3", 0x0120, 0x0100, 0x8cd4cd60 ) /* characters */ ROM_END GAME( 1982, pooyan, 0, pooyan, pooyan, 0, ROT270, "Konami", "Pooyan" ) GAME( 1982, pooyans, pooyan, pooyan, pooyan, 0, ROT270, "[Konami] (Stern license)", "Pooyan (Stern)" ) GAME( 1982, pootan, pooyan, pooyan, pooyan, 0, ROT270, "bootleg", "Pootan" )
[ [ [ 1, 370 ] ] ]
d387c207714645391fd8e46756945905351317c8
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/LayoutEditor/PanelUserData.cpp
ea3cc34b113d5106762c3500fa326aa46c8ac1b1
[]
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
5,743
cpp
/*! @file @author Georgiy Evmenov @date 09/2008 */ #include "precompiled.h" #include "Common.h" #include "Localise.h" #include "PanelUserData.h" #include "EditorWidgets.h" #include "UndoManager.h" namespace tools { PanelUserData::PanelUserData() : BasePanelViewItem("PanelUserData.layout"), mEditKey(nullptr), mEditValue(nullptr), mButtonAdd(nullptr), mButtonDelete(nullptr), mMultilist(nullptr), mCurrentWidget(nullptr), mEditLeft(0), mEditRight(0), mEditSpace(0), mButtonLeft(0), mButtonRight(0), mButtonSpace(0) { } void PanelUserData::initialise() { mPanelCell->setCaption("UserData"); assignWidget(mEditKey, "editKey"); assignWidget(mEditValue, "editValue"); assignWidget(mButtonAdd, "buttonAdd"); assignWidget(mButtonDelete, "buttonDelete"); assignWidget(mMultilist, "multilist"); mButtonAdd->eventMouseButtonClick += MyGUI::newDelegate(this, &PanelUserData::notifyAddUserData); mButtonDelete->eventMouseButtonClick += MyGUI::newDelegate(this, &PanelUserData::notifyDeleteUserData); mEditKey->eventEditSelectAccept += MyGUI::newDelegate(this, &PanelUserData::notifyUpdateUserData); mEditValue->eventEditSelectAccept += MyGUI::newDelegate(this, &PanelUserData::notifyUpdateUserData); mMultilist->eventListChangePosition += MyGUI::newDelegate(this, &PanelUserData::notifySelectUserDataItem); mMultilist->addColumn(replaceTags("Key"), 1); mMultilist->addColumn(replaceTags("Value"), 1); mEditLeft = mEditKey->getLeft(); mEditRight = mMainWidget->getWidth() - mEditValue->getRight(); mEditSpace = mEditValue->getLeft() - mEditKey->getRight(); mButtonLeft = mButtonAdd->getLeft(); mButtonRight = mMainWidget->getWidth() - mButtonDelete->getRight(); mButtonSpace = mButtonDelete->getLeft() - mButtonAdd->getRight(); } void PanelUserData::shutdown() { } void PanelUserData::update(MyGUI::Widget* _currentWidget) { mCurrentWidget = _currentWidget; WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(_currentWidget); mMultilist->removeAllItems(); for (MyGUI::VectorStringPairs::iterator iterProperty = widgetContainer->mUserString.begin(); iterProperty != widgetContainer->mUserString.end(); ++iterProperty) { mMultilist->addItem(iterProperty->first); mMultilist->setSubItemNameAt(1, mMultilist->getItemCount() - 1, iterProperty->second); } } void PanelUserData::notifyChangeWidth(int _width) { const MyGUI::IntSize& size = mMultilist->getClientCoord().size(); mMultilist->setColumnWidthAt(0, size.width / 2); mMultilist->setColumnWidthAt(1, size.width - (size.width / 2)); int width = mMainWidget->getClientCoord().width; int half_width = (width - (mEditLeft + mEditRight + mEditSpace)) / 2; mEditKey->setSize(half_width, mEditKey->getHeight()); mEditValue->setCoord(mEditKey->getRight() + mEditSpace, mEditValue->getTop(), width - (mEditKey->getRight() + mEditSpace + mEditRight), mEditValue->getHeight()); half_width = (width - (mButtonLeft + mButtonRight + mButtonSpace)) / 2; mButtonAdd->setSize(half_width, mButtonAdd->getHeight()); mButtonDelete->setCoord(mButtonAdd->getRight() + mButtonSpace, mButtonDelete->getTop(), width - (mButtonAdd->getRight() + mButtonSpace + mButtonRight), mButtonDelete->getHeight()); } void PanelUserData::notifyAddUserData(MyGUI::Widget* _sender) { std::string key = mEditKey->getOnlyText(); std::string value = mEditValue->getOnlyText(); WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget); if (utility::mapFind(widgetContainer->mUserString, key) == widgetContainer->mUserString.end()) { mMultilist->addItem(key); } mMultilist->setSubItemNameAt(1, mMultilist->findSubItemWith(0, key), value); utility::mapSet(widgetContainer->mUserString, key, value); UndoManager::getInstance().addValue(); } void PanelUserData::notifyDeleteUserData(MyGUI::Widget* _sender) { size_t item = mMultilist->getIndexSelected(); if (MyGUI::ITEM_NONE == item) return; WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget); utility::mapErase(widgetContainer->mUserString, mMultilist->getItemNameAt(item)); mMultilist->removeItemAt(item); UndoManager::getInstance().addValue(); } void PanelUserData::notifyUpdateUserData(MyGUI::Edit* _widget) { size_t item = mMultilist->getIndexSelected(); if (MyGUI::ITEM_NONE == item) { notifyAddUserData(); return; } std::string key = mEditKey->getOnlyText(); std::string value = mEditValue->getOnlyText(); std::string lastkey = mMultilist->getItemNameAt(item); WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget); mMultilist->removeItemAt(mMultilist->findSubItemWith(0, lastkey)); utility::mapErase(widgetContainer->mUserString, lastkey); if (utility::mapFind(widgetContainer->mUserString, key) == widgetContainer->mUserString.end()) { mMultilist->addItem(key); } mMultilist->setSubItemNameAt(1, mMultilist->findSubItemWith(0, key), value); mMultilist->setIndexSelected(mMultilist->findSubItemWith(0, key)); utility::mapSet(widgetContainer->mUserString, key, value); UndoManager::getInstance().addValue(); } void PanelUserData::notifySelectUserDataItem(MyGUI::MultiList* _widget, size_t _index) { size_t item = mMultilist->getIndexSelected(); if (MyGUI::ITEM_NONE == item) return; std::string key = mMultilist->getSubItemNameAt(0, item); std::string value = mMultilist->getSubItemNameAt(1, item); mEditKey->setOnlyText(key); mEditValue->setOnlyText(value); } } // namespace tools
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 156 ] ] ]
4fa1c71a565e99440e8cde78d776bb05a104cf49
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Material/D3D9Metal.cpp
74107e2f17fa7f6cc672c69f94d399e93f057d6e
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
3,807
cpp
#include "D3D9Metal.h" #include "../Main/DataCenter.h" #include "../Main/ResourceManager.h" #include "../Renderer/D3D9RenderWindow.h" #include "../Renderer/D3D9Renderer.h" #include "../Renderer/D3D9Effect.h" #include "../Renderer/D3D9RenderCubeTexture.h" namespace Flagship { D3D9Metal::D3D9Metal() { m_mParamMap.clear(); m_mTechniqueMap.clear(); // 材质类型 m_iClassType = Base::Material_RenderTexture; } D3D9Metal::~D3D9Metal() { SAFE_DELETE( m_pEffect ); SAFE_DELETE( m_pRenderCubeTexture ); } bool D3D9Metal::Initialize() { // 创建D3D9Effect对象 wchar_t szPath[MAX_PATH]; GetCurrentDirectory( MAX_PATH, szPath ); wstring szEffectPath = szPath; szEffectPath += L"\\Effect\\D3D9Metal.fx"; D3D9EffectHandle hEffectHandle; hEffectHandle.SetPath( szEffectPath ); m_pEffect = hEffectHandle.GetImpliment(); // 建立渲染贴图 m_pRenderCubeTexture = new D3D9RenderCubeTexture; // 获取后备缓冲格式 LPDIRECT3DSURFACE9 pRenderTarget = ( (D3D9RenderWindow *) RenderWindow::GetActiveRenderWindow() )->GetRenderTarget(); D3DSURFACE_DESC kRenderTargetDesc; pRenderTarget->GetDesc( &kRenderTargetDesc ); m_pRenderCubeTexture->Initialize( 256, kRenderTargetDesc.Format ); m_pRenderCubeTexture->GetCamera()->SetProjection( 3.14f / 2.0f, 1.0f, 1.0f, 100.0f ); m_pRenderCubeTexture->GetRenderer()->SetRenderType( Renderer::RenderType_NoReflect ); return true; } void D3D9Metal::BuildParamMap() { // 建立参数表 Key kWorld( wstring( L"g_matWorld" ) ); Key kView( wstring( L"g_matView" ) ); Key kProj( wstring( L"g_matProj" ) ); Key kWorldI( wstring( L"g_matWorldI" ) ); Key kViewI( wstring( L"g_matViewI" ) ); Key kSkinnedMatrix( wstring( L"g_matSkinnedMatrix" ) ); Key kLightDir( wstring( L"g_vLightDir" ) ); m_kRenderCubeTexture.SetName( wstring( L"g_CubeTexture" ) ); m_mParamMap[Material::Entity_WorldMatrix] = kWorld; m_mParamMap[Material::Entity_ViewMatrix] = kView; m_mParamMap[Material::Entity_ProjMatrix] = kProj; m_mParamMap[Material::Entity_WorldIMatrix] = kWorldI; m_mParamMap[Material::Entity_ViewIMatrix] = kViewI; m_mParamMap[Material::AnimEntity_SkinnedMatrix] = kSkinnedMatrix; m_mParamMap[Material::Light_Direction] = kLightDir; m_pEffect->AddParamHandle( Effect::Param_Matrix, kWorld ); m_pEffect->AddParamHandle( Effect::Param_Matrix, kView ); m_pEffect->AddParamHandle( Effect::Param_Matrix, kProj ); m_pEffect->AddParamHandle( Effect::Param_Matrix, kWorldI ); m_pEffect->AddParamHandle( Effect::Param_Matrix, kViewI ); m_pEffect->AddParamHandle( Effect::Param_MatrixArray, kSkinnedMatrix ); m_pEffect->AddParamHandle( Effect::Param_Vector, kLightDir ); m_pEffect->AddParamHandle( Effect::Param_Texture, m_kRenderCubeTexture ); // 建立科技表 Key kLight( wstring( L"Light" ) ); Key kColor( wstring( L"Color" ) ); m_mTechniqueMap[Material::Technique_Light] = kLight; m_mTechniqueMap[Material::Technique_Color] = kColor; m_pEffect->AddParamHandle( Effect::Param_Technique, kLight ); m_pEffect->AddParamHandle( Effect::Param_Technique, kColor ); } void D3D9Metal::Update( Renderable * pParent ) { Material::Update( pParent ); // 更新渲染贴图 Matrix4f * pWorld = DataCenter::GetSingleton()->GetMatrixData( pParent, pParent->GetClassType(), RenderableData::Matrix4_World )->Get(); Matrix4f matWorld = * pWorld; Vector4f vPos = matWorld.GetColumn( 3 ); m_pRenderCubeTexture->GetCamera()->SetPosition( vPos ); m_pRenderCubeTexture->Update(); m_pEffect->SetTexture( m_kRenderCubeTexture, m_pRenderCubeTexture->GetRenderTarget() ); } void D3D9Metal::Update( Resource * pParent ) { } }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 111 ] ] ]
4502e87b013a78481c27d68bbe0e3a3a3ecb9001
5b3221bdc6edd8123287b2ace0a971eb979d8e2d
/Fiew/Tool.h
a4dafe4d555ec215cc9d30cdb270b9cfd3a2df0b
[]
no_license
jackiejohn/fedit-image-editor
0a4b67b46b88362d45db6a2ba7fa94045ad301e2
fd6a87ed042e8adf4bf88ddbd13f2e3b475d985a
refs/heads/master
2021-05-29T23:32:39.749370
2009-02-25T21:01:11
2009-02-25T21:01:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,135
h
class FwCHAR; class ChildCore; class Tool { protected: Core *core; // application Core ChildCore *chicore; // current Tool owner FwCHAR *name; // Tool name HCURSOR cursor, // publicly accessible Tool cursor cursorBackup; // private backup cursor UINT id; // Tool id (same as the Tool icon id in resource) HWND hdocktool; // Tool dock content handle POINT mouse; // current mouse position bool isAlt, // is Alt pressed isCtrl, // is Ctrl pressed isShift; // is Shift pressed public: Tool(FwCHAR *name, HCURSOR cursor, UINT id); virtual ~Tool(); // Process windows messages LRESULT processMessages( Core *core, ChildCore *chicore, HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, int area ); UINT getId(); FwCHAR *getName(); HCURSOR getCursor(); // Tool activation triggered when the tool is set virtual void activate(); // Tool dock content activation void activateDock(); // Assign dock content to the application Dock Window void submitDock(); // Fill dock content with interface controls virtual void fillDock(); // Update the dock contents with the current state of Workspace virtual void updateDock(); // Tool deactivation triggered before the new tool is set virtual void deactivate(); // Notification from the Tool's dock content id - control's id that triggered the notify virtual void notify(int id); // Calculate mouse position in Workspace coordinates static POINT getWorkspaceMousePos(ChildCore *chicore, LPARAM lParam); // Create cursor from tool icon static HCURSOR createToolCursor(int hotXspot, int hotYspot, int toolId); // Process mouse messages virtual void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseWheel(WPARAM wParam, LPARAM lParam); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); // Process keyboard messages virtual void capKeyDown(WPARAM wParam, LPARAM lParam); virtual void capKeyUp(WPARAM wParam, LPARAM lParam); // Get mouse position virtual POINT getMousePos(LPARAM lParam); // Get additional keys pressed when clicking processing mouse messages void getKeyStatus(WPARAM wParam); virtual void updateInterface(WPARAM wParam, LPARAM lParam); protected: // Update Tool Windows void updateToolws(WPARAM wParam, LPARAM lParam); void setMouseCapture(); void setMouseRelease(); // Is current Workspace Frame ready for applying Tool actions bool isLayerReady(); // Set Tool cursor as current mouse cursor bool loadCursor(); }; /* Menu Tools - activate only */ struct RGBCOLOR { UINT R,G,B,A; }; class ToolMerge : public Tool { public: ToolMerge(); ~ToolMerge(); }; class ToolRaster : public Tool { public: ToolRaster(); ~ToolRaster(); }; class ToolFilter : public Tool { private: int lastFilterId, lastFilterValue; bool lastActivate, isLastActivate, lastBw, lastAlpha; public: struct Matrix { int **matrix, // matrix 2 dimensional array mxw, // matrix width mxh; // matrix height double division, bias; } lastCustomMatrix; // matrix structure struct Info { // [in] Bitmap *bmpSource; bool edgeTrace, // edge trace filter flag smooth, // preview filtering flag bw, // black & white only flag bwalpha, // use alpha channel flag filterByValue; // use filterValue or load custom matrix flag int filterId, filterValue, minVal, maxVal; // [in][out] ToolFilter::Matrix matrix; // [out] Bitmap *bmpEffect; } filterInfo; // filter info structure ToolFilter(); ~ToolFilter(); void activate(); // try to activate recently applied filtering again void activateAgain(); bool canActivateAgain(); void setFilterId(int id); int getFilterId(); static double calcMatrixWeight(ToolFilter::Matrix *matrix); // main filtering routine static Rect applyFilter(ToolFilter::Info *fi, Rect *clip = NULL, bool once = false); // get an average value from the color static INT scalePixel(RGBCOLOR color, bool alpha = true); // get the color from the bitmap at specified point static UINT getPixel(BitmapData *bmp, int x, int y); // return pixel color value after applying matrix values onto the specified pixel // fi - ToolFilter::Info structure with all filtering data // bmp - source bitmap // x - pixel x coordinate // y - pixel y coordinate // w - floored half width of applied matrix // h - floored half height of applied matrix static UINT filterPixel(ToolFilter::Info *fi, BitmapData *bmp, int x, int y, int w, int h); // allocate int** matrix array static int **allocMatrix(int mxw, int mxh, int set = 0); // allocate ToolFilter::Matrix structure static ToolFilter::Matrix allocateMatrix(int filterId, int value); static ToolFilter::Matrix allocMatrixGeneric(); // allocate specified filters' Matrixes static ToolFilter::Matrix allocMatrixBlur(int value); static ToolFilter::Matrix allocMatrixBlurGauss(int value); static ToolFilter::Matrix allocMatrixSharpen(int value); static ToolFilter::Matrix allocMatrixEdgetrace(int value, int mode = NULL); static ToolFilter::Matrix allocMatrixEmboss(int value, int mode); static ToolFilter::Matrix allocMatrixHighlight(int value); static ToolFilter::Matrix allocMatrixDefocus(int value); static ToolFilter::Matrix allocMatrixOldstone(int value); static WCHAR *getFilterName(int filterId); }; class ToolCopy : public Tool { private: int mode; bool noclipboard; public: ToolCopy(int mode); ~ToolCopy(); void activate(); void setNoclipboard(); }; class ToolFill : public Tool { public: ToolFill(); ~ToolFill(); void activate(); }; class ToolStroke : public Tool { public: ToolStroke(); ~ToolStroke(); void activate(); }; /* Control Center Tools */ class ToolHand : public Tool { private: POINT mouseLast; HWND dlgAll; bool mouseMoving, isAll; public: ToolHand(); ~ToolHand(); void fillDock(); void notify(int id); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); }; class ToolSampleColor : public Tool { private: bool isMoving; int button; public: ToolSampleColor(); ~ToolSampleColor(); bool getPixel(POINT pixel, Bitmap *scene, Color *color); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); void pickColor(); }; /* Selecting Tools ToolSelecting class is inherited by selecting Tools */ class ToolSelecting : public Tool { protected: int rectmargin; bool isSelecting, isMoving, isAA; GraphicsPath *currentPath, *oldPath; public: ToolSelecting(FwCHAR *name, HCURSOR cursor, UINT id); virtual ~ToolSelecting(); void beginPaint(); void endPaint(); virtual void activate(); virtual void deactivate(); virtual void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseWheel(WPARAM wParam, LPARAM lParam); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); virtual void capKeyDown(WPARAM wParam, LPARAM lParam); virtual void capKeyUp(WPARAM wParam, LPARAM lParam); protected: POINT getMousePos(LPARAM lParam); // can the selection be moved bool getSelectionMoveState(int x, int y); // set selection on the Workspace // path - selection path // final - if true create a HistoryElement // shiftJoin - if true connect the new path with the old void setSelection(GraphicsPath *path, bool final = false, bool shiftJoin = false); void setSelection(List<Point> *poly, bool close, bool clip, bool final = false); void setSelection(RECT rect, int mode = SELRECT, bool final = false); void setOldPath(); void resetOldPath(bool final = true); void setUpdate(GraphicsPath *path); void move(int x, int y); void update(); }; // Rectangle type of selection (Rectangle, Ellipse, 1px lines) class ToolSelectRect : public ToolSelecting { private: RECT selection; int mode; public: ToolSelectRect(int mode = SELRECT); ~ToolSelectRect(); void setSelectAll(); void deselect(); void setSelectInverse(); private: virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); }; // Polygonal type of selection (Polygonal Lasso, Free Lasso) class ToolSelectPoly : public ToolSelecting { private: List<Point> *poly; int mode; public: ToolSelectPoly(int mode); ~ToolSelectPoly(); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); bool isEnd(); void endPoly(); }; // Magic Wand class ToolSelectWand : public ToolSelecting { private: Bitmap *selectBmp, *sourceBmp; HWND dlgTolerance, dlgSlider; int tolerance; public: ToolSelectWand(); ~ToolSelectWand(); void fillDock(); void notify(int id); // magic color recognition static GraphicsPath *doMagic(Bitmap *sourceBmp, Bitmap *select, int x, int y, int shx, int shy, int tol); // magic shape vectorisation static GraphicsPath *doMagicSelection(Bitmap *source); // magic color comparison // pick - original color // trick - matching color // tolerance - matching tolerance static bool doMagicComparison(UINT pick, UINT trick, UINT tolerance); private: virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); static bool isonStack(List<Point> *stack, int x, int y); }; // Cropping Tool class ToolCrop : public ToolSelecting { private: RECT selection; POINT lastmouse; List<RectF> *cropctrl; double ratio; int ctrl; public: ToolCrop(); ~ToolCrop(); void deactivate(); void finalize(bool prompt = false, bool isyes = true); private: void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); void capKeyDown(WPARAM wParam, LPARAM lParam); void capKeyUp(WPARAM wParam, LPARAM lParam); void setCropctrls(); void setCropath(); int getHoverCtrl(); void boundRect(RECT *rect); void limitRect(RECT *rect); }; class ToolText : public ToolSelecting { private: HWND hEdit, hPane, dlgFonts, dlgSize, dlgAA, dlgBold, dlgItalic, dlgUline, dlgColor; FrameText *editFrame; HFONT editFont; INT currentFontStyle; Unit currentFontUnit; FwCHAR *currentFontName; FontFamily *currentFontFamily; POINT pointScreen, pointWorkspace; Color color; REAL currentFontSize; bool isFontAA; public: ToolText(); ~ToolText(); void fillDock(); void updateDock(); void deactivate(); void notify(int id); // editing methods void editText(FrameText *owner); void createEdit(WCHAR *string, int x, int y, int w, int h); static int getFontPxAscent(FontFamily *fontFamily, INT fontStyle, REAL fontSize); static int getFontPxSize(FontFamily *fontFamily, INT fontStyle, REAL fontSize); // calculate text bounding box static Rect stringToBox(int fsize, int wsize, int lsize); // window procedures for in-place edit controls static LRESULT CALLBACK editProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK paneProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void loadFonts(); int getCurrentFontIndex(); int getCurrentFontPxSize(); int getCurrentFontPxAscent(); WCHAR *getCurrentFontName(); void setCurrentFont(); void setEditFont(); protected: void finalize(); void locate(); }; // Zoom Tool class ToolZoom : public ToolSelecting { private: HWND dlgAll; RECT selection; Point lastPin; bool isAll; public: ToolZoom(); ~ToolZoom(); void fillDock(); void notify(int id); void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); void capKeyDown(WPARAM wParam, LPARAM lParam); void capKeyUp(WPARAM wParam, LPARAM lParam); void setDrawpath(); double calcZoom(double sw, double sh, double zm); double calcFit(double sw, double sh); }; /* Drawing Tools ToolDrawing class is inherited by all drawing Tools */ class ToolDrawing : public Tool { protected: SolidBrush *brushColor; Pen *penColor; int size, rectmargin; bool isDraw, isAA; HWND dlgSize, dlgAA, dlgSlider; POINT drawmouse; RECT drawrect, srcrect; Rect cliprect; Graphics *drawgfx; Bitmap *drawbmp, *sceneAbove, *sceneBelow, *sceneBetween; public: ToolDrawing(FwCHAR *name, HCURSOR cursor, UINT id); virtual ~ToolDrawing(); // prepare for drawing, create neccessary objects void beginPaint(); // end drawing, apply the draw onto the selected Frame void endPaint(); // update the MDI child scene void update(Rect rect, int mode = INVDEF); virtual void activate(); virtual void deactivate(); virtual void notify(int id); virtual void fillDock(); virtual void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseWheel(WPARAM wParam, LPARAM lParam); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); virtual void capKeyDown(WPARAM wParam, LPARAM lParam); virtual void capKeyUp(WPARAM wParam, LPARAM lParam); virtual Rect getDrawrect(); Rect getSrcrect(int margin); void updateInterface(WPARAM wParam, LPARAM lParam); protected: void destroy(); // change the size of the rectangle that stores the drawn area void setDrawrectDown(int mode = INFLATE); void setDrawrectMove(int mode = INFLATE); void setDrawrectUp(int mode = INFLATE); virtual POINT getMousePos(LPARAM lParam); }; /* ToolDrawingLinear is inherited by line drawing Toools */ class ToolDrawingLinear : public ToolDrawing { protected: GraphicsPath *drawpath; POINT startLinear; POINT mouseLinear; public: ToolDrawingLinear(FwCHAR *name, HCURSOR cursor, UINT id); virtual ~ToolDrawingLinear(); virtual void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseWheel(WPARAM wParam, LPARAM lParam); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); virtual void capKeyDown(WPARAM wParam, LPARAM lParam); virtual void capKeyUp(WPARAM wParam, LPARAM lParam); virtual Rect getDrawrect(); POINT getMousePos(LPARAM lParam); protected: // prepare for creating a GraphicsPath void beginPath(); // update the path void updatePath(); // apply the path onto the temporary drawing bitmap void endPath(); }; /* ToolDrawingStrict differs in the way it calculates the mouse position and is used when ToolDrawing and ToolDrawingLinear cannot be used */ class ToolDrawingStrict : public ToolDrawing { public: ToolDrawingStrict(FwCHAR *name, HCURSOR cursor, UINT id); virtual ~ToolDrawingStrict(); virtual void capMouseDblClk(WPARAM wParam, LPARAM lParam, int button); private: virtual void capMouseClientDlbClk(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseWheel(WPARAM wParam, LPARAM lParam); virtual void capMouseDown(WPARAM wParam, LPARAM lParam, int button); virtual void capMouseMove(WPARAM wParam, LPARAM lParam); virtual void capMouseUp(WPARAM wParam, LPARAM lParam, int button); virtual void capKeyDown(WPARAM wParam, LPARAM lParam); virtual void capKeyUp(WPARAM wParam, LPARAM lParam); POINT getMousePos(LPARAM lParam); protected: void beginPaint(); //void endPaint(); }; class ToolPencil : public ToolDrawing { private: List<PointF> *curve; int counter, mode; public: ToolPencil(int mode = PENPEN); ~ToolPencil(); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); Rect getDrawrect(); }; class ToolBucket : public ToolDrawingStrict { private: Color colorPick; Bitmap *sourceBmp; bool isPreselect; public: ToolBucket(); ~ToolBucket(); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); // call Magic Wand functionality void callMagic(WPARAM wParam, LPARAM lParam); void callColor(Color *color); }; class ToolLine : public ToolDrawingLinear { private: POINT start; Rect prevRect, drawRect; int mode, rrcRound; public: ToolLine(int mode); ~ToolLine(); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); void setDrawrect(); Rect getDrawrect(); void drawLine(); }; class ToolMove : public Tool { private: POINT mouseLast, frameStart, frameEnd; bool mouseMoving, keyMoving; public: ToolMove(); ~ToolMove(); private: void capMouseDown(WPARAM wParam, LPARAM lParam, int button); void capMouseMove(WPARAM wParam, LPARAM lParam); void capMouseUp(WPARAM wParam, LPARAM lParam, int button); void capKeyDown(WPARAM wParam, LPARAM lParam); void capKeyUp(WPARAM wParam, LPARAM lParam); };
[ [ [ 1, 755 ] ] ]
de9de218e68141aaa0f853b4dc413f5fc59dff86
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/dialog/src/AimlNodeImplXerces.cpp
3ba3a3f02caede05d1c72af00c9cac75f5971ef7
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,745
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 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 Perl 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 * Perl Artistic License for more details. * * You should have received a copy of the Perl Artistic License * along with this program; if not you can get it here * http://www.perldoc.com/perl5.6/Artistic.html. */ //#include <xercesc/sax2/SAX2XMLReader.hpp> //#include <xercesc/sax2/XMLReaderFactory.hpp> //#include <xercesc/parsers/XercesDOMParser.hpp> //#include <xercesc/framework/MemBufInputSource.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/XMLString.hpp> #include "AimlNodeImplXerces.h" namespace rl { AimlNodeImplXerces::AimlNodeImplXerces(AimlNode* parent, DOMNode* node) : AimlNode(parent), mNode(node) { mNode = node; for(node = node->getFirstChild(); node != NULL; node->getNextSibling()) { mChildNodes.push_back(new AimlNodeImplXerces(this, node)); } } AimlNodeImplXerces::~AimlNodeImplXerces(void) { /* std::vector<AimlNode*>::iterator iter = mChilNodes.begin(); for(; iter != mChildNodes.end(); ++iter) { delete (*iter); } mChildNodes.clear(); */ } AimlNode* AimlNodeImplXerces::getFirstChild() { return mChildNodes[0]; } AimlNode* AimlNodeImplXerces::getNextSibling() { // return (new AimlNodeImplXerces(mNode->getNextSibling())); return NULL; } }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 61 ] ] ]
d8329abf3be32b84cf9e8b4ddc2cc95545ad65a1
480c44ff4e052723caa9326457921ea1eada5b25
/judge/src/JudgeSubmission.cpp
09b6fcc0fcf9c86bf238d5fba9b8f4bf362791df
[]
no_license
kevinhs1150/open-online-judge
cd898329cf039e0d07835eb98f45b8bd87cff609
979e3bffd2965eb21904a73e84cd5bb12a48dbb8
refs/heads/master
2020-12-25T18:17:15.013425
2011-07-16T13:15:49
2011-07-16T13:15:49
32,213,625
0
0
null
null
null
null
UTF-8
C++
false
false
6,811
cpp
#include "JudgeMain.h" #include "JudgeSubmission.h" #include "JudgeCompare.h" #include "JudgementConfirm.h" #include "judge_tool.h" extern "C" { #include "judgeproto.h" } JudgeCompareFrame *compareFrame; JudgementConfirmFrame *confirmFrame; extern JudgeSubmissionFrame *submissionFrame; JudgeSubmissionFrame::JudgeSubmissionFrame(wxFrame *frame) : JudgeSubmissionGUI(frame) { IP_set(); setResultChoice(); m_buttonShowInputData->Enable(false); m_buttonShowSource->Enable(false); m_buttonStop->Enable(false); } JudgeSubmissionFrame::~JudgeSubmissionFrame() { } void JudgeSubmissionFrame::IP_set() { FILE *fptr1; fptr1=fopen("ip.txt","r"); fscanf (fptr1, "%s", IP); fclose(fptr1); } void JudgeSubmissionFrame::setRunProblemID(unsigned int run_id,unsigned int problem_id, wchar_t *coding_language, wchar_t *problem_name, unsigned int time_limit) { wxString submissionNO; wxString problemNO; this->run_id = run_id; this->problem_id = problem_id; this->coding_language = (wchar_t *) malloc( (wcslen(coding_language) +1 ) * sizeof(wchar_t)); wcscpy(this->coding_language,coding_language); this->problem_name = (wchar_t *) malloc( (wcslen(problem_name) +1 ) * sizeof(wchar_t)); wcscpy(this->problem_name,problem_name); this->time_limit = time_limit; submissionNO.Printf(wxT("%u"), run_id); problemNO.Printf(wxT("%u %s"), problem_id, problem_name); m_staticTextSubmissionValue->SetLabel(submissionNO); m_staticTextProblemNumberValue->SetLabel(problemNO); } unsigned int JudgeSubmissionFrame::getTimeLimit() { return this->time_limit; } void JudgeSubmissionFrame::OnButtonClickShowInput( wxCommandEvent& event ) /**SKIP**/ { } void JudgeSubmissionFrame::OnButtonClickShowSource( wxCommandEvent& event )/**SKIP**/ { } void JudgeSubmissionFrame::OnButtonClickRun( wxCommandEvent& event ) { wchar_t file_name[50]; wchar_t type[20]; int errtyp; wcscpy(type, this->coding_language); if(!(wcscmp(type, L"c"))){ wsprintf(file_name,L"%u.c",this->run_id); } else if(!(wcscmp(type, L"c++"))){ wsprintf(file_name,L"%u.cpp",this->run_id); } else{ errtyp = TYPE_ERROR; } m_staticTextRunStatus->SetLabel(wxT("Compile...")); errtyp = compile(file_name, type); if(errtyp == SUCCESS || errtyp == SUCCESS_WITH_WARNING){ m_staticTextRunStatus->SetLabel(wxT("File execute...")); if(execute( getTimeLimit() ) == 0){ if(judge(this->problem_id) != 0){ errtyp = OUTPUT_ERROR; m_staticTextRunStatus->SetLabel(wxT("Wrong answer.")); } } else{ errtyp = TIME_OUT; } } if(errtyp == SUCCESS){ m_staticTextRunStatus->SetLabel(wxT("Compile success.")); } else if(errtyp == SUCCESS_WITH_WARNING){ m_staticTextRunStatus->SetLabel(wxT("Compile success, but has warning.")); } else if(errtyp == COMPILE_ERROR){ m_staticTextRunStatus->SetLabel(wxT("Compile error.")); } else if(errtyp == OUTPUT_ERROR){ m_staticTextRunStatus->SetLabel(wxT("Output error.")); } else if(errtyp == TYPE_ERROR){ m_staticTextRunStatus->SetLabel(wxT("Submission file type error.")); } else if(errtyp == FILE_OPEN_ERROR){ m_staticTextRunStatus->SetLabel(wxT("Submission file open error.")); } else if(errtyp == OUTPUT_OPEN_ERROR){ m_staticTextRunStatus->SetLabel(wxT("Compile result file open error.")); } else if(errtyp == TIME_OUT){ m_staticTextRunStatus->SetLabel(wxT("Execute time out.")); } else{ m_staticTextRunStatus->SetLabel(wxT("Other unexpected error.")); } } void JudgeSubmissionFrame::OnButtonClickStop( wxCommandEvent& event ) /**SKIP**/ { } void JudgeSubmissionFrame::OnButtonClickShowOutput( wxCommandEvent& event ) { compareFrame = new JudgeCompareFrame(0L); compareFrame->setProblemID(this->problem_id); compareFrame->Show(); } void JudgeSubmissionFrame::OnButtonClickJudge( wxCommandEvent& event ) { int column = m_choiceJudgement->GetSelection(); wchar_t result_string[20]; if(column == 0){ this->result = YES; } else if(column == 1){ this->result = COMPILE_ERROR; } else if(column == 2){ this->result = WRONG_ANSWER; } else if(column == 3){ this->result = TIME_LIMIT_EXCEED; } else if(column == 4){ this->result = RUN_TIME_ERROR; } confirmFrame = new JudgementConfirmFrame(0L); confirmFrame->setJudgementVal(this->result); if(confirmFrame->ShowModal() == 0){ if(this->result == YES){ swprintf(result_string,L"yes"); } else if(this->result == COMPILE_ERROR){ swprintf(result_string,L"compile error"); } else if(this->result == WRONG_ANSWER){ swprintf(result_string,L"wrong answer"); } else if(this->result == TIME_LIMIT_EXCEED){ swprintf(result_string,L"time limit exceed"); } else if(this->result == RUN_TIME_ERROR){ swprintf(result_string,L"runtime error"); } else{ swprintf(result_string,L"YOU SHALL NOT PASS!!!!"); //this should never occur?? } if(judgeproto_judge_result(this->IP,this->run_id,result_string) != 0){ wxMessageBox(wxT("Judgement Submission Error.\nPromble: Socket error."),wxT("Judgement Submission Error"),wxOK|wxICON_EXCLAMATION); } else{ EndModal(0); } } confirmFrame->Destroy(); } void JudgeSubmissionFrame::OnButtonClickCancel( wxCommandEvent& event ) { EndModal(-1); } void JudgeSubmissionFrame::setResultChoice() { wxString choice; choice.Printf(wxT("yes")); m_choiceJudgement->Append(choice); choice.Printf(wxT("compile error")); m_choiceJudgement->Append(choice); choice.Printf(wxT("wrong answer")); m_choiceJudgement->Append(choice); choice.Printf(wxT("time-limit exceed")); m_choiceJudgement->Append(choice); choice.Printf(wxT("run-time error")); m_choiceJudgement->Append(choice); } void JudgeSubmissionFrame::showStatus() { wxString status; FILE *fptr1; char filename[50]; sprintf(filename,"problem/%u_input.txt",this->problem_id); fptr1 = fopen(filename,"r"); if(fptr1 != NULL){ m_staticTextInputStatusValue->SetLabel(wxT("OK")); } else{ m_buttonRun->Enable(false); m_buttonShowOutput->Enable(false); m_staticTextInputStatusValue->SetLabel(wxT("Not Exist")); } if( !wcscmp(this->coding_language, L"c") ) { sprintf(filename, "%u.c", run_id); } else if(!wcscmp(this->coding_language,L"c++")) { sprintf(filename, "%u.cpp", run_id); } fptr1 = fopen(filename,"r"); if(fptr1 != NULL){ m_staticTextSourceStatusValue->SetLabel(wxT("OK")); } else{ m_staticTextSourceStatusValue->SetLabel(wxT("Not Exist")); m_buttonRun->Enable(false); m_buttonShowOutput->Enable(false); } m_staticTextRunStatus->SetLabel(wxT("Not start")); }
[ "h85164@e3896563-57da-0129-da3f-310c26432eee", "[email protected]@e3896563-57da-0129-da3f-310c26432eee" ]
[ [ [ 1, 4 ], [ 7, 95 ], [ 97, 112 ], [ 114, 125 ], [ 127, 155 ], [ 157, 163 ], [ 167, 171 ], [ 173, 173 ], [ 176, 177 ], [ 185, 186 ], [ 188, 210 ], [ 212, 212 ], [ 214, 216 ], [ 219, 258 ] ], [ [ 5, 6 ], [ 96, 96 ], [ 113, 113 ], [ 126, 126 ], [ 156, 156 ], [ 164, 166 ], [ 172, 172 ], [ 174, 175 ], [ 178, 184 ], [ 187, 187 ], [ 211, 211 ], [ 213, 213 ], [ 217, 218 ] ] ]
130dc713b865459dca13c23ec579a6cc7c4cbf52
7ba7440b6a7b6068c900d561ad03c3ff86439c09
/GalDemo/GalDemo/Action.cpp
893a5049e1d34bdaa2545d9e6dc78748cb968646
[]
no_license
weimingtom/gal-demo
96dc06f8f02b4c767412aac7fcf050e241b40c04
f2b028591a195516af3ce33d084b7b29cbea84aa
refs/heads/master
2021-01-20T11:47:07.598476
2011-08-10T23:48:43
2011-08-10T23:48:43
42,379,726
2
0
null
null
null
null
UTF-8
C++
false
false
42
cpp
#include "stdafx.h" #include "Action.h"
[ [ [ 1, 2 ] ] ]
79db6022a29583be6b9db49c3eb4d5d3f3c07ec4
353bd39ba7ae46ed521936753176ed17ea8546b5
/src/layer1_system/raster_gl/test/axrt_test.cpp
2047984b89acd0d3a6d70afe8e17579fccaa69bd
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
/** * @file * Axe 'raster' test code * @see axe_raster.h */ #include "axrt_test.h" #define AXRT_NO_AUTOLINK #include "axe_raster.h" /// Version of this test code #define AXE_RASTER_TEST_VERSION 1 // Use proper library -------- #ifdef _DEBUG #pragma comment( lib, "../../../output_debug/lib/axe_raster.lib" ) #else #pragma comment( lib, "../../../output_release/lib/axe_raster.lib" ) #endif /** * Checks for the current 'error' state of the library */ void error( int num, const char* file, long line ) { printf( "\n\n\n*** ERROR in %s(%u): %s\n", file, line, axrt_get_error_message(num) ); getchar(); } /** * Checks if this code and the lib have the same version */ int check_versions() { printf( "\nGetting lib version ... " ); int lib_version = axrt_get( AXRT_VERSION ); if( lib_version != AXE_RASTER_TEST_VERSION ) { printf( "This test program and the library versions differ! Lib:%d Test:%d\n", lib_version, AXE_RASTER_TEST_VERSION ); getchar(); return( 0 ); } printf( "Library Version: %d - This testing program: %d\n\n", lib_version, AXE_RASTER_TEST_VERSION ); return( 1 ); } /** * Simple code to test all functionality of the library */ int main() { printf( "Axe 'raster' library test STARTED\n" ); // Check versions ------------------------------------ if( check_versions() == 0 ) { return( 0 ); } // Start --------------------------------------------- getchar(); // Finish -------------------------------------------- printf( "\nAxe 'raster' library test FINISHED\n" ); return( 1 ); } /* $Id: axpl_test.cpp,v 1.1 2004/07/27 22:42:49 doneval Exp $ */
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 76 ] ] ]
66f99ae24910ede1e71ea85caa23939629714bcc
00c36cc82b03bbf1af30606706891373d01b8dca
/OpenGUI/OpenGUI_ObjectAccessor.h
adc32e0fafeb2c2ebbb8969a5edcc806ce05425e
[ "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
3,755
h
// OpenGUI (http://opengui.sourceforge.net) // This source code is released under the BSD License // See LICENSE.TXT for details #ifndef E278D21F_0B04_437C_8A77_E84A74699F89 #define E278D21F_0B04_437C_8A77_E84A74699F89 #include "OpenGUI_PreRequisites.h" #include "OpenGUI_Exports.h" #include "OpenGUI_String.h" #include "OpenGUI_Value.h" #include "OpenGUI_Object.h" namespace OpenGUI { //############################################################################ //! Base class for Accessor system /*! This is an internal abstract base class. All accessors must be derived from either ObjectProperty or ObjectMethod. */ class OPENGUI_API ObjectAccessor { public: ObjectAccessor() {} virtual ~ObjectAccessor() {} //! Returns the name of the group of this accessor, default is "General" virtual const char* getAccessorGroup(); //! Returns the name of this accessor virtual const char* getAccessorName() = 0; //! \internal Accessor type identification enum ObjectAccessorType { TYPE_PROPERTY, TYPE_METHOD }; //! \internal Returns the type of Accessor /*! \internal This is automatically handled when you inherit from ObjectProperty or ObjectMethod */ virtual ObjectAccessorType _getAccessorType() = 0; }; //############################################################################ //! Base class for Property Accessors /*! Object Properties that applications wish to expose should inherit this class. */ class OPENGUI_API ObjectProperty : public ObjectAccessor { public: virtual ~ObjectProperty() {} //! \internal Returns TYPE_PROPERTY. Do not override! virtual ObjectAccessorType _getAccessorType() { return TYPE_PROPERTY; } //! Called to retrieve the current value virtual void get( Object& objectRef, Value& valueOut ) = 0; //! Called to set the current value virtual void set( Object& objectRef, Value& valueIn ) = 0; //! Needs to return the expected Value type virtual Value::ValueType getPropertyType() = 0; //! Used by ObjectAccessorList to determine if this property is write protected. Default returns \c TRUE ( property can be \c get and \c set ) virtual bool getPermSettable(); }; //############################################################################ //! Base class for Method Accessors /*! Object Method that applications wish to expose should inherit this class. */ class OPENGUI_API ObjectMethod : public ObjectAccessor { public: virtual ~ObjectMethod() {} //! \internal Returns TYPE_METHOD. Do not override! virtual ObjectAccessorType _getAccessorType() { return TYPE_METHOD; } //! Called when the method is invoked. virtual void invoke( Object& objectRef, ValueList& paramIn, ValueList& returnOut ) = 0; }; //############################################################################ /*! \brief The ObjectAccessorList is a inheritance capable string -> ObjectAccessor mapping. */ class OPENGUI_API ObjectAccessorList { public: //! constructor ObjectAccessorList(); //! destructor ~ObjectAccessorList(); //! Sets the parent of this ObjectAccessorList. void setParent( ObjectAccessorList* parent ); //! Retrieves the current parent of this ObjectAccessorList. ObjectAccessorList* getParent(); //! Adds a new ObjectAccessor void addAccessor( ObjectAccessor* accessor ); //! Gets the ObjectAccessor by \c accessorName ObjectAccessor* getAccessor( const String& accessorName, bool recursive = true ); private: ObjectAccessorList* mParent; typedef std::map<String, ObjectAccessor*> ObjectAccessorMap; ObjectAccessorMap mObjectAccessorMap; }; }//namespace OpenGUI{ #endif
[ "zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59" ]
[ [ [ 1, 111 ] ] ]
f24c61ae8ea02383ec7c09ca100c5ae4b603ef1f
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Agent/hkpProcessCollisionData.h
bddc56f2c8082b275c8057eb4da80eb6023a9bb1
[]
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
4,625
h
/* * * 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. * */ #ifndef HK_COLLIDE2_PROCESS_COLLISION_DATA_H #define HK_COLLIDE2_PROCESS_COLLISION_DATA_H #include <Physics/Collide/Agent/hkpProcessCdPoint.h> #include <Common/Base/Types/Physics/ContactPoint/hkContactPointMaterial.h> #include <Physics/Internal/Collide/Gjk/hkpGskCache.h> #include <Physics/ConstraintSolver/Constraint/Contact/hkpContactPointProperties.h> /// An array of collision contact points. This class is used internally by hkdynamics to pass collision detection /// information from the collision detector to the constraint solver. #if defined(HK_PLATFORM_HAS_SPU) enum {HK_MAX_CONTACT_POINT = 64 }; #else enum {HK_MAX_CONTACT_POINT = 256 }; #endif struct hkpAgentEntry; #ifndef hkCollisionConstraintOwner class hkpConstraintOwner; # define hkCollisionConstraintOwner hkpConstraintOwner #endif /// This is the output data of the collision detector (plus the contact point added/removed events). /// This class holds all contact points as well as continuous information (TOI = Time Of Impact) /// As the hkContactPointInfo or hkpContactPointProperties are part of hkDynamics they can't be part of this structure. struct hkpProcessCollisionData { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_AGENT, hkpProcessCollisionData); /// Get the number of contact points inline int getNumContactPoints() const; /// Get the contact point at index i inline hkpProcessCdPoint& getContactPoint( int i ); /// Get a pointer to the first contact point of the contact point array inline hkpProcessCdPoint* getFirstContactPoint(); /// Get a pointer to the end of the used contact point array inline hkpProcessCdPoint* getEnd(); /// returns true if there are no contact points inline hkBool isEmpty() const; /// returns true if a toi was created between this pair of objects inline hkBool hasToi() const; /// get access to the toi contact point inline hkContactPoint& getToiContactPoint(); /// returns the toi inline hkTime getToi() const; /// returns access to the toi contact point properties inline hkpContactPointProperties& getToiProperties(); public: /// A pointer to the first point in the m_contactPoints which is not used yet hkPadSpu<hkpProcessCdPoint*> m_firstFreeContactPoint; hkPadSpu<hkCollisionConstraintOwner*> m_constraintOwner; /// A buffer for all contact points, used up to m_firstFreeContactPoint hkpProcessCdPoint m_contactPoints[HK_MAX_CONTACT_POINT]; // // toi info // struct ToiInfo { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpProcessCollisionData::ToiInfo ); inline ToiInfo(); // exchanges A-B inline void flip(); public: /// An optional toi contact point, valid if m_toi < HK_REAL_MAX hkContactPoint m_contactPoint; /// The toi hkPadSpu<hkReal> m_time; /// The separating velocity of the objects at the toi hkPadSpu<hkReal> m_seperatingVelocity; hkGskCache16 m_gskCache; /// The material which is going to be used by the toi handler hkContactPointPropertiesWithExtendedUserData16 m_properties; }; struct ToiInfo m_toi; inline hkpProcessCollisionData( hkCollisionConstraintOwner* owner ); }; #include <Physics/Collide/Agent/hkpProcessCollisionData.inl> #endif // HK_COLLIDE2_PROCESS_COLLISION_DATA_H /* * 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, 128 ] ] ]
becf0dc555b2768e0b51a77a0e22f2e40aa84c23
bd37f7b494990542d0d9d772368239a2d44e3b2d
/client/src/SalidaPacMan.cpp
66206b2262d050db1b8d586f0428ea8f310c62d7
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
/////////////////////////////////////////////////////////// // SalidaPacMan.cpp // Implementation of the Class SalidaPacMan // Created on: 21-Nov-2007 23:40:21 /////////////////////////////////////////////////////////// #include "SalidaPacMan.h" SalidaPacMan::SalidaPacMan( int posicion, Orientacion orientacion ):Elemento( posicion, orientacion ) { } SalidaPacMan::SalidaPacMan( int posicion, Coordenada coord, Orientacion orientacion ):Elemento( posicion, coord, orientacion ) { } SalidaPacMan::~SalidaPacMan(){ } tipoElemento SalidaPacMan:: getTipo()const { return tSalidaPacman; } /** * Metodo que pertmite renderizar el objeto en la pantalla */ void SalidaPacMan::renderizar(){ } bool SalidaPacMan::operator==( tipoElemento tipo) const { return tipo == tSalidaPacman; }
[ "nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 40 ] ] ]
825c3ef20776c00264cdbc465bdab4389f765e9d
dbd5275ab1172bcc6693b0e39bdb9cac9a8aa654
/src/mainwindow.cpp
b3419886956076af9933518f671b8d8ff3cdd50f
[]
no_license
aarontc/acdj
bb6d148a3c75abad97dd5b0a3d55f628694cea13
f0166dee780833f7cde1703265676322268fcc21
refs/heads/master
2016-09-10T18:51:13.291503
2010-08-16T17:32:32
2010-08-16T17:32:32
32,116,033
0
0
null
null
null
null
UTF-8
C++
false
false
1,140
cpp
#include "mainwindow.h" #include "musicmodewidget.h" #include <QtGui> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { musicMode = new MusicModeWidget; setCentralWidget(musicMode); CreateActions(); CreateMenu(); } void MainWindow::AddFile() { QStringList files = QFileDialog::getOpenFileNames(this, QString("Select Music Files"), QDesktopServices::storageLocation(QDesktopServices::MusicLocation)); if(!files.isEmpty()) { // Phonon::MediaObject *music = // Phonon::createPlayer(Phonon::MusicCategory, // Phonon::MediaSource(files.at(0))); // music->play(); musicMode->AddSong(files.first()); } } void MainWindow::CreateActions() { addFileAct = new QAction(QString("Add &File to Playlist"), this); exitAct = new QAction(QString("E&xit"), this); } void MainWindow::CreateMenu() { QMenu * fileMenu = menuBar()->addMenu(QString("&File")); fileMenu->addAction(addFileAct); fileMenu->addAction(exitAct); connect(addFileAct, SIGNAL(triggered()), this, SLOT(AddFile())); connect(exitAct, SIGNAL(triggered()), this, SLOT(close()) ); }
[ "[email protected]@e443b260-af5b-3101-41d7-9d022bc9ec3b", "jazzguitarfreak@e443b260-af5b-3101-41d7-9d022bc9ec3b" ]
[ [ [ 1, 1 ], [ 3, 6 ], [ 49, 49 ] ], [ [ 2, 2 ], [ 7, 48 ] ] ]
14c93155d772cff7ba053e8f9ffac40406cc9127
b2b90e37fbf0e11a04c52ab695fda35fa466904f
/Whiteboard/GUI/whiteboard.cpp
d270b7c358f6c2119960d6dc04fb0ddba82af8f8
[]
no_license
robalan11/teamwhiteboard
670733682fdf0559a719e69f6e576ff8476bddd2
d428a33c62709f7c0bbb9907f70d67aa26a7aeca
refs/heads/master
2021-01-01T19:34:58.977424
2009-04-26T16:34:47
2009-04-26T16:34:47
32,401,000
0
0
null
null
null
null
UTF-8
C++
false
false
3,088
cpp
#include "whiteboard.h" // ISA whiteboard window WhiteboardWindow::WhiteboardWindow(const wxString& title, TextWindow* parent) : wxFrame(NULL, -1, title, wxPoint(650, 50), wxSize(640, 480), wxMINIMIZE_BOX | wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN) { mpParent = parent; CreateStatusBar(2); SetStatusText(_T("Welcome to the Whiteboard!")); mMapMode = wxMM_TEXT; mXUserScale = 1.0; mYUserScale = 1.0; mXLogicalOrigin = 0; mYLogicalOrigin = 0; mXAxisReversed = mYAxisReversed = false; mBackgroundMode = wxSOLID; mColourForeground = *wxBLACK; mColourBackground = *wxWHITE; mTextureBackground = false; mActiveTool = ""; mpCanvas = new MyCanvas( this ); mpCanvas->Show(); //Buttons! wxButton* butt_clear = new wxButton(); butt_clear->Create(this, 0, "Clear", wxDefaultPosition, wxSize(32,32)); wxButton* butt_line = new wxButton(); butt_line->Create(this, 1, "Line", wxPoint(0,32), wxSize(32,32)); wxButton* butt_rect = new wxButton(); butt_rect->Create(this, 2, "Rect", wxPoint(0,64), wxSize(32,32)); wxButton* butt_circ = new wxButton(); butt_circ->Create(this, 3, "Circle", wxPoint(0,96), wxSize(32,32)); //wxButton *butt_free = new wxButton(); //butt_free->Create(this, 4, "Free\nDraw", wxPoint(0,128), wxSize(32,32)); wxButton* butt_undo = new wxButton(); butt_undo->Create(this, 5, "Undo", wxPoint(0,128), wxSize(32,32)); } void WhiteboardWindow::PrepareDC(wxDC& dc) { dc.SetLogicalOrigin( mXLogicalOrigin, mYLogicalOrigin ); dc.SetAxisOrientation( !mXAxisReversed, mYAxisReversed ); dc.SetUserScale( mXUserScale, mYUserScale ); dc.SetMapMode( mMapMode ); } void WhiteboardWindow::Clear(wxCommandEvent& WXUNUSED(event)) { SetStatusText(_T("Clear")); mActiveTool = "clear"; } void WhiteboardWindow::Line(wxCommandEvent& WXUNUSED(event)) { SetStatusText(_T("Click and drag to draw a line.")); mActiveTool = "line"; } void WhiteboardWindow::Rect(wxCommandEvent& WXUNUSED(event)) { SetStatusText(_T("Click and drag to draw a rectangle.")); mActiveTool = "rect"; } void WhiteboardWindow::Circ(wxCommandEvent& WXUNUSED(event)) { SetStatusText(_T("Click and drag to draw a circle.")); mActiveTool = "circ"; } /*void WhiteboardWindow::Free(wxCommandEvent& WXUNUSED(event)) { SetStatusText(_T("Click and drag to draw freely.")); mActiveTool = "free"; }*/ void WhiteboardWindow::Undo(wxCommandEvent& WXUNUSED(event)) { if (mpParent->IsServer()) { if (mpCanvas->objects.size() > 0) { SetStatusText(_T("Last command undone.")); mActiveTool = "undo"; mpCanvas->objects.pop_back(); mpCanvas->Refresh(); } else { mActiveTool = ""; } } } BEGIN_EVENT_TABLE(WhiteboardWindow, wxFrame) //Buttons EVT_BUTTON (0, WhiteboardWindow::Clear) EVT_BUTTON (1, WhiteboardWindow::Line) EVT_BUTTON (2, WhiteboardWindow::Rect) EVT_BUTTON (3, WhiteboardWindow::Circ) //EVT_BUTTON (4, WhiteboardWindow::Free) EVT_BUTTON (5, WhiteboardWindow::Undo) END_EVENT_TABLE()
[ "robalan@ab1a795a-e8e4-11dd-9059-71fac19e68c6", "[email protected]@ab1a795a-e8e4-11dd-9059-71fac19e68c6" ]
[ [ [ 1, 3 ], [ 5, 85 ], [ 87, 89 ], [ 92, 92 ], [ 94, 105 ] ], [ [ 4, 4 ], [ 86, 86 ], [ 90, 91 ], [ 93, 93 ] ] ]
155a5686623388ef46c79c2fb01a74fc743ca9ca
27b8c57bef3eb26b5e7b4b85803a8115e5453dcb
/branches/flatRL/lib/include/Utility/PhysicsDebug.h
8e087bfd72fdb518275432cac8ea57f16b525b93
[]
no_license
BackupTheBerlios/walker-svn
2576609a17eab7a08bb2437119ef162487444f19
66ae38b2c1210ac2f036e43b5f0a96013a8e3383
refs/heads/master
2020-05-30T11:30:48.193275
2011-03-24T17:10:17
2011-03-24T17:10:17
40,819,670
0
0
null
null
null
null
UTF-8
C++
false
false
409
h
#ifndef __WALKER_YARD_UTILITY_PHYSICS_DEBUG_H__ #define __WALKER_YARD_UTILITY_PHYSICS_DEBUG_H__ #include <slon/Scene/Visitors/NodeVisitor.h> using namespace slon; class PhysicsDebugVisitor : public scene::NodeVisitor { public: typedef scene::NodeVisitor base_type; public: void visitTransform(scene::Transform& transform); }; #endif // __WALKER_YARD_UTILITY_PHYSICS_DEBUG_H__
[ "red-haired@9454499b-da03-4d27-8628-e94e5ff957f9" ]
[ [ [ 1, 18 ] ] ]
f24dc0ed2c8465d5f793114158c32dbedd10c68e
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/tools/nimagetool.cc
0e73684144ce2225ce49756f104b1a1a38cdf0ac
[]
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
13,711
cc
#include "precompiled/pchntoollib.h" //------------------------------------------------------------------------------ /** @page NebulaToolsnimagetool nimagetool nimagetool Nebula image processing tool. <dl> <dt>-in</dt> <dd>filename of input file</dd> <dt>-out</dt> <dd>filename of output file (extension must be @c .tga or @c .ntx)</dd> <dt>-mipmap</dt> <dd>generate mipmaps (only for @c .ntx output)</dd> <dt>-cubemap</dt> <dd>generate a cubemap</dd> <dt>-w</dt> <dd>target width</dd> <dt>-h</dt> <dd>target height</dd> <dt>-smalleronly</dt> <dd>only scale image if target size is smaller</dd> <dt>-flip</dt> <dd>flip image vertically</dd> <dt>-normcubemap</dt> <dd>generate a normalization cube map</dd> <dt>-specmap</dt> <dd>generate a specular map</dd> </dl> (C) 2003 RadonLabs GmbH */ #include <assert.h> #include "il/il.h" #include "il/ilu.h" #include "kernel/nkernelserver.h" #include "tools/ncmdlineargs.h" #include "mathlib/vector.h" const int numImages = 6; const int posXIndex = 0; const int negXIndex = 1; const int posYIndex = 2; const int negYIndex = 3; const int posZIndex = 4; const int negZIndex = 5; //------------------------------------------------------------------------------ /** Create a new black 1x1 pixel RGB image. */ ILuint CreateImage(bool white) { unsigned char fillPixel[3] = { 0, 0, 0 }; if (white) { fillPixel[0] = fillPixel[1] = fillPixel[2] = 0xff; } ILuint image = iluGenImage(); ilBindImage(image); ilTexImage(1, 1, 1, 3, IL_BGR, IL_UNSIGNED_BYTE, &fillPixel); return image; } //------------------------------------------------------------------------------ /** Convert a vector3 to bgr and write to cube map face */ void writeCubePixel(uchar* data, int width, int x, int y, float vx, float vy, float vz) { int r = int(((vx * 0.5f) + 0.5f) * 255.0f); int g = int(((vy * 0.5f) + 0.5f) * 255.0f); int b = int(((vz * 0.5f) + 0.5f) * 255.0f); uchar* ptr = data + (((width * y) + x) * 3); ptr[0] = r; ptr[1] = g; ptr[2] = b; } //------------------------------------------------------------------------------ /** Create a normalization cube map. */ bool CreateNormCubeMap(ILuint image[numImages], int size) { // configure the 6 images and get pointer to image data uchar* dataPtr[numImages]; int i; for (i = 0; i < numImages; i++) { ilBindImage(image[i]); ilTexImage(size, size, 1, 3, IL_RGB, IL_UNSIGNED_BYTE, 0); dataPtr[i] = ilGetData(); } int ix, iy; vector3 vec; float d = 2.0f / float(size); for (iy = 0; iy < size; iy++) { for (ix = 0; ix < size; ix++) { float y = 1.0f - float(iy) * d; float z = 1.0f - float(ix) * d; vec.set(1.0f, y, z); vec.norm(); writeCubePixel(dataPtr[posXIndex], size, ix, iy, +vec.x, +vec.y, +vec.z); writeCubePixel(dataPtr[negXIndex], size, ix, iy, -vec.x, +vec.y, -vec.z); writeCubePixel(dataPtr[posYIndex], size, ix, iy, -vec.z, +vec.x, -vec.y); writeCubePixel(dataPtr[negYIndex], size, ix, iy, -vec.z, -vec.x, +vec.y); writeCubePixel(dataPtr[posZIndex], size, ix, iy, -vec.z, +vec.y, +vec.x); writeCubePixel(dataPtr[negZIndex], size, ix, iy, +vec.z, +vec.y, -vec.x); } } return true; } //------------------------------------------------------------------------------ /** Creates a specular lookup table. */ bool CreateSpecularMap(ILuint image, int width, int height) { // bind and resize empty source image ilBindImage(image); ilTexImage(width, height, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, 0); unsigned char* data = ilGetData(); // fill image data int x, y; float dx = 1.0f / float(width - 1); float dy = 1.0f / float(height - 1); double fy = 0.0; for (y = 0; y < height; y++, fy += dy) { double fx = 0.0; for (x = 0; x < width; x++, fx += dx) { uchar* ptr = data + (((width * y) + x) * 4); double val = pow(fx, double((height - 1) - y)); int c = int(val * 255.0f); ptr[0] = c; ptr[1] = c; ptr[2] = c; ptr[3] = 255; } } return true; } //------------------------------------------------------------------------------ /** Load image from a file. */ bool LoadImage(ILuint image, const char* filename) { assert(filename); ilBindImage(image); if (!ilLoadImage((const ILstring) filename)) { printf("nimagetool ERROR: could not load image file '%s'\n", filename); return false; } // convert to bgr byte order if ((ilGetInteger(IL_IMAGE_FORMAT) != IL_BGR) && (ilGetInteger(IL_IMAGE_FORMAT) != IL_BGRA)) { if (ilGetInteger(IL_IMAGE_FORMAT) == IL_RGB) { ilConvertImage(IL_BGR, IL_UNSIGNED_BYTE); } else { ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE); } } return true; } //------------------------------------------------------------------------------ /** Scale an image. Will not scale if target size is identical to current size, or the smallerOnly flag is true, and the target size is smaller then the current size. */ void ScaleImage(ILuint image, int width, int height, bool smallerOnly) { ilBindImage(image); int curWidth = ilGetInteger(IL_IMAGE_WIDTH); int curHeight = ilGetInteger(IL_IMAGE_HEIGHT); // do not scale if sizes are identical if ((curWidth == width) && (curHeight == height)) { return; } // do not scale if target width smaller and smallerOnly is set if (smallerOnly && (curWidth < width) && (curHeight < height)) { return; } // select filter based on current size (use a simple and // fast filter if current size is 1, which is the case if // the image is still in its default state after creation) if ((curWidth == 1) && (curHeight == 1)) { iluImageParameter(ILU_FILTER, ILU_NEAREST); } else { iluImageParameter(ILU_FILTER, ILU_BILINEAR); } // do the actual scale iluScale(width, height, 1); } //------------------------------------------------------------------------------ /** Flip an image vertically. */ void FlipImage(ILuint image) { ilBindImage(image); iluFlipImage(); } //------------------------------------------------------------------------------ /** Generate mipmaps for an image. */ void GenerateMipmaps(ILuint image) { ilBindImage(image); iluImageParameter(ILU_FILTER, ILU_BILINEAR); iluBuildMipmaps(); } //------------------------------------------------------------------------------ /** Save an image as TGA file. */ bool SaveImageTGA(ILuint image, const char* filename) { assert(filename); ilBindImage(image); ilEnable(IL_FILE_OVERWRITE); ILboolean success = ilSave(IL_TGA, (const ILstring) filename); if (0 == success) { printf("nimagetool ERROR: Failed to save image '%s' as tga file!\n", filename); return false; } return true; } //------------------------------------------------------------------------------ /** Main function. */ int main(int argc, const char** argv) { nCmdLineArgs args(argc, argv); // get cmd line args const char* inFileArg[numImages]; bool helpArg = args.GetBoolArg("-help"); inFileArg[0] = args.GetStringArg("-in", 0); const char* outFileArg = args.GetStringArg("-out", 0); inFileArg[posXIndex] = args.GetStringArg("-inposx", inFileArg[0]); inFileArg[negXIndex] = args.GetStringArg("-innegx", 0); inFileArg[posYIndex] = args.GetStringArg("-inposy", 0); inFileArg[negYIndex] = args.GetStringArg("-innegy", 0); inFileArg[posZIndex] = args.GetStringArg("-inposz", 0); inFileArg[negZIndex] = args.GetStringArg("-innegz", 0); bool cubeMapArg = args.GetBoolArg("-cubemap"); bool mipMapArg = args.GetBoolArg("-mipmap"); int widthArg = args.GetIntArg("-w", 0); int heightArg = args.GetIntArg("-h", 0); bool smallerOnlyArg = args.GetBoolArg("-smalleronly"); bool flipArg = args.GetBoolArg("-flip"); bool normCubeMapArg = args.GetBoolArg("-normcubemap"); bool specMapArg = args.GetBoolArg("-specmap"); bool whiteArg = args.GetBoolArg("-white"); // show help? if (helpArg) { printf("(C) 2003 RadonLabs GmbH\n" "nimagetool - Nebula2 image processing tool\n" "Command line args:\n" "------------------\n" "-help show this help\n" "-in [filename] name of input image file (preferably tga)\n" "-out [filename] name of output image file (.tga extension)\n" "-inposx [filename] optional input file for +x side of cube map\n" "-innegx [filename] optional input file for -x side of cube map\n" "-inposy [filename] optional input file for +y side of cube map\n" "-innegy [filename] optional input file for -y side of cube map\n" "-inposz [filename] optional input file for +z side of cube map\n" "-innegz [filename] optional input file for -z side of cube map\n" "-w target width in pixels\n" "-h target height in pixels\n" "-smalleronly only scale if target image is smaller\n" "-flip flip image vertically\n" "-specmap generate a specular lookup map\n" "-white fill uninitialized images with white instead of black\n"); return 5; } // check for arg errors if (0 == outFileArg) { printf("Error: no output file defined!\n"); return 10; } // initialize Nebula runtime nKernelServer* kernelServer = new nKernelServer; // startup IL and ILU ilInit(); iluInit(); ilEnable(IL_CONV_PAL); // generate 6 empty images ILuint images[numImages]; int i; for (i = 0; i < numImages; i++) { images[i] = CreateImage(whiteArg); } // generate source images bool success = false; if (normCubeMapArg) { n_assert(widthArg == heightArg); success = CreateNormCubeMap(images, widthArg); } else if (specMapArg) { success = CreateSpecularMap(images[0], widthArg, heightArg); } else if (cubeMapArg) { success = true; for (i = 0; i < numImages; i++) { if (inFileArg[i]) { success &= LoadImage(images[i], inFileArg[i]); } } } else if (inFileArg[0]) { success = LoadImage(images[0], inFileArg[0]); } // error during creation? if (!success) { return 10; } // scale images? if ((!normCubeMapArg) && (!specMapArg)) { // If no target width and height is defined, set the size to the size of the first valid // image in the image array. This takes care of any leftover 1x1 images in // the cube maps (which are then scaled to the correct size) int width = widthArg; int height = heightArg; for (i = 0; i < numImages; i++) { ilBindImage(images[i]); int curWidth = ilGetInteger(IL_IMAGE_WIDTH); int curHeight = ilGetInteger(IL_IMAGE_HEIGHT); if ((curWidth > 1) && (curHeight > 1)) { width = curWidth; height = curHeight; break; } } for (i = 0; i < numImages; i++) { ScaleImage(images[i], width, height, smallerOnlyArg); } } // flip vertically? if (flipArg) { for (i = 0; i < numImages; i++) { FlipImage(images[i]); } } // generate mipmaps? this only works for non-cubemaps if (mipMapArg && (!normCubeMapArg) && (!cubeMapArg)) { GenerateMipmaps(images[0]); } // save out target image success = false; if (cubeMapArg || normCubeMapArg) { // success = SaveCubeMapNTX(kernelServer, images, outFileArg); } else { nString path(outFileArg); if (path.CheckExtension("tga")) { success = SaveImageTGA(images[0], outFileArg); } else { printf("nimagetool ERROR: invalid file extension in out filename '%s'\n", outFileArg); return 10; } } // delete images for (i = 0; i < numImages; i++) { iluDeleteImage(images[i]); } ilShutDown(); delete kernelServer; return 0; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 461 ] ] ]
e470adf6d50db7dd03bdd31e874fb28020809abe
bdb1e38df8bf74ac0df4209a77ddea841045349e
/CapsuleSortor/ImageCard/SimularCard.cpp
490ac08fe753ebcc4b7a95b3c3bf6d3ced404e75
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
GB18030
C++
false
false
3,134
cpp
// A simple tool for Simular Image card. #include "SimularCard.h" SimularCard::SimularCard() : RegisteredFunc(0), m_regFuncParam(0), m_grabTimeout(10000), m_frameInterval(1500) { m_thread.SetThreadFunc(SimularCard::CreateImage, this); } SimularCard::~SimularCard() { Close(); } bool SimularCard::Open() { if(m_opened) return m_opened; m_roi.width = 1024; m_roi.height = 500; m_roi.bytesPerPixel = 1; m_roi.bitsPerPixel = m_roi.bytesPerPixel * 8; m_roi.bytesPerRow = m_roi.bytesPerPixel * m_roi.width; m_pixelMem = TAlloc<PixelMem>(m_roi.bytesPerRow * m_roi.height, e16ByteAlign); m_opened = true; return m_opened; } bool SimularCard::Close() { if(m_opened) { StopLive(); m_opened = false; } return !m_opened; } bool SimularCard::FrameRate(float fps) { float realFPS = (fps<0.1f)? 0.1f : (fps>100.0f)? 100.0f : fps; m_frameInterval = (unsigned int)(1000.0f/realFPS); return true; } size_t SimularCard::FrameInterval( ) { return m_frameInterval; } bool SimularCard::GrabTimeout(size_t ms) { m_grabTimeout = ms; return true; } bool SimularCard::StartLive() { if(!m_living) { if(!m_opened) { return m_living; } m_living = true; if(!m_thread.Start()) { m_living = false; } } return m_living; } bool SimularCard::StopLive() { if(m_living) { m_living = false; if(!m_thread.Wait(m_frameInterval*2)) { m_thread.Stop(); } } return !m_living; } void SimularCard::CreateImage(void *param) { static size_t frameIndex = 0; SimularCard* pThis = (SimularCard*)(param); while(pThis->m_living) { if(pThis->GetGrabMode() == TImageCard::SOFTTRG) { pThis->m_trigEvent.Wait(); pThis->m_trigEvent.ResetEvent(); } pThis->m_imageSrc.GoNextFrame(); //调用注册的处理函数或设置事件 if(pThis->RegisteredFunc) { //pThis->RegisteredFunc(pThis->m_regFuncParam); pThis->m_imageSignal.PulseEvent(); } else { memcpy( (pThis->m_pixelMem).Base(), (pThis->m_imageSrc).CurrentFrameData(), (pThis->m_imageSrc).FrameBytes()); pThis->m_grabEvent.SetEvent(); } Sleep(pThis->m_frameInterval); } } TAlloc<TImageCard::PixelMem> SimularCard::GetPixelMem() { bool ok = m_grabEvent.Wait(); m_grabEvent.ResetEvent(); if(ok) { return m_pixelMem; } else { return m_pixelMem.NullObject(); } } bool SimularCard::SetRawImage(const TImgBuffer& rawImage) { m_imageSrc = rawImage; m_roi = rawImage.Dimension(); m_pixelMem = TAlloc<PixelMem>(m_roi.bytesPerRow * m_roi.height, e16ByteAlign); return true; } bool SimularCard::SetGrabMode (EnumGrabMode eMode) { m_eGrabMode = eMode; return true; } bool SimularCard::SoftTriggering( ) { m_trigEvent.SetEvent(); return true; } bool SimularCard::RegisterProcFunc(REGCallbackFunc* func, void *param) { RegisteredFunc = func; m_regFuncParam = param; return true; } void* SimularCard::GetPixelMemBase() const { return m_imageSrc.CurrentFrameData(); }
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 185 ] ] ]
1847c868ba090c0aaf0132b3e8ff292345a148e5
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/include/ULDC.h
be8c3c2b1bb428f329d21466de235c3a5bd499f1
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
15,193
h
///\file ULDC.h ///\brief Заголовочный файл классов контекстов(08.10.2007) #include <windows.h> #pragma once #ifndef __ULDC__H_ #define __ULDC__H_ namespace ULGDI { ///\namespace ULGDI::ULDC ///\brief пространство имён классов контекстов(08.10.2007) namespace ULDC { ///\class CULDC ///\brief Класс контекста class CULDC { public: ///\brief контекст HDC m_hDC; ///\brief окно владелец HWND m_hWndOwner; ///\brief режим фона ///\param bmOPAQUE - заливка будет производиться текущий BkColor(SetBkColor) ///\param bmTRANSPARENT - прозрачный фон enum enBkMode { bmOPAQUE =OPAQUE, bmTRANSPARENT =TRANSPARENT }; public: ///\brief Конструктор CULDC():m_hDC(NULL),m_hWndOwner(NULL){}; ///\brief Конструктор копирования CULDC(HDC& hDC):m_hDC(hDC),m_hWndOwner(NULL){} ///\brief Конструктор копирования CULDC(CULDC& DC):m_hDC(DC),m_hWndOwner(NULL){} ///\brief Деструктор virtual ~CULDC(){DeleteDC();} ///\brief Сохраняетвыбранную область контекста в память ///\param pszFile - путь к фаилу ///\param rcSize - область подлежащая заиси в фаил ///\param dwComp - тип компрессии (BI_RGB,BI_RLE8,BI_RLE4,BI_BITFIELDS,BI_JPEG,BI_PNG) ///\param wBitCount - битность сохраняемого изображения ///\return TRUE в случае успеха, иначе FALSE BOOL ULGDI::ULDC::CULDC::CreateBMPFile(LPCTSTR pszFile, RECT rcSize, DWORD dwComp, WORD wBitCount); //==================inline functions============================ ///\brief Функция создания контекста(никогда не пользовался :D) inline BOOL CreateDC(LPCTSTR lpszDriver, LPCTSTR lpszDevice, LPCTSTR lpszOutput,CONST DEVMODE* lpInitData) {return ((m_hDC=::CreateDC(lpszDriver,lpszDevice,lpszOutput,lpInitData))!=NULL);} ///\brief Создает совместимый контекст на основе входнрого ///\param hDC - входной контекст ///\return TRUE в случае успеха, иначе FALSE inline BOOL CreateCompatibleDC(HDC hDC) {return ((m_hDC=::CreateCompatibleDC(hDC))!=NULL);} ///\brief Для подстановки объекта класса там где требуется /// только хендл DC inline operator HDC() const{return m_hDC;}; inline BOOL BitBlt(int nXDest,int nYDest,int nWidth,int nHeight, HDC hdcSrc,int nXSrc,int nYSrc,DWORD dwRop) {return ::BitBlt(*this,nXDest,nYDest,nWidth,nHeight, hdcSrc,nXSrc,nYSrc,dwRop);}; ///\brief устанавливает цвет текста ///\param crColor - цвет ///\return предыдущий цвет inline COLORREF SetTextColor(COLORREF crColor) {return ::SetTextColor(*this,crColor);} ///\brief Возвращает цвет текста ///\return цвет inline COLORREF GetTextColor() {return ::GetTextColor(*this);} ///\brief устанавливает цвет фона текста ///\param crColor - цвет ///\return предыдущий цвет inline COLORREF SetBkColor(COLORREF crColor) {return ::SetBkColor(*this,crColor);}; ///\brief устанавливает режим отрисовки текста ///\param bm - режим ///\return предыдущий цвет inline int SetBkMode(enBkMode bm) {return ::SetBkMode(*this,bm);}; ///\brief отрисовывает текст ///\param lpString - текст ///\param nCount - длина текста ///\param lpRect - прямоугольник в котором отрисовывать ///\param uFormat - формат отрисовки(по МСДН) ///\return в случае успеза вернёт высоту текста в логическихединицах, иначе 0 inline int DrawText(LPCTSTR lpString,int nCount,LPRECT lpRect,UINT uFormat) {return ::DrawText(*this,lpString,nCount,lpRect,uFormat);}; ///\brief для получения размера текста в контексте при заданном шрифте ///\param lpString - строка ///\param cbString - длина строки ///\param lpSize - размер текста ///\return TRUE в случае успеха inline BOOL GetTextExtentPoint(LPCTSTR lpString,int cbString,LPSIZE lpSize) {return ::GetTextExtentPoint(*this,lpString,cbString,lpSize);}; ///\brief выбирает инструмент рисования в контекст ///\param hgdiobj - инструмент рисования ///\return предыдущий инструмент рисования inline HGDIOBJ SelectObject(HGDIOBJ hgdiobj) {return ::SelectObject(*this,hgdiobj);}; ///\brief удаляет контекст ///\return TRUE в случае успеха inline BOOL DeleteDC() {if(m_hDC!=NULL)return ::DeleteDC(*this);else return FALSE;} ///\brief отсоединяет контекст от класса ///\return контекст inline HDC Detach() {HDC hRetDC=m_hDC;m_hDC=NULL;return hRetDC;} ///\brief Рисует прямоугольник ///\param nLeftRect,nTopRect,nRightRect,nBottomRect - координаты ///\return TRUE в случае успеха inline BOOL Rectangle(int nLeftRect,int nTopRect,int nRightRect,int nBottomRect) {return ::Rectangle(*this,nLeftRect,nTopRect,nRightRect,nBottomRect);} ///\brief Рисует текст ///\param nXStart,nYStart - координаты ///\param nXStart,nYStart - координаты ///\param lpString - строка ///\param cbString - длина строки ///\return TRUE в случае успеха inline BOOL TextOut(int nXStart,int nYStart,LPCTSTR lpString,int cbString) {return ::TextOut(*this,nXStart,nYStart,lpString,cbString);} ///\brief Рисует контур по заданному региону ///\param hrgn - регион ///\param hbr - кисть, которой будет выполнена отрисовка ///\param nWidth,nHeight - размеры региона ///\return TRUE в случае успеха, иначе FALSE inline BOOL FrameRgn(HRGN hrgn,HBRUSH hbr,int nWidth,int nHeight) {return ::FrameRgn(*this,hrgn,hbr,nWidth,nHeight);}; ///\brief выполняет градиентную закраску заданной области ///\param pVertex - массив TRIVERTEX структур ///\param dwNumVertex - число TRIVERTEX структур в массиве pVertex ///\param pMesh - массив GRADIENT_TRIANGLE структур для режима треугольника /// или массив GRADIENT_RECT структур для режима прямоугольника ///\param dwNumMesh - число элементов в pMesh ///\param dwMode - режим /// GRADIENT_FILL_RECT_H горизонтальный градиент /// GRADIENT_FILL_RECT_V вертикальный градиент /// GRADIENT_FILL_TRIANGLE градиент по треугольнку(не пробовал) inline BOOL GradientFill(PTRIVERTEX pVertex,ULONG dwNumVertex,PVOID pMesh,ULONG dwNumMesh,ULONG dwMode) {return ::GradientFill(*this,pVertex,dwNumVertex,pMesh,dwNumMesh,dwMode);}; ///\brief возвращает информацию о контексте ///\param index - ID поля ///\return значение virtual int GetDeviceCaps(int index) {return ::GetDeviceCaps(*this,index);} ///\brief Возвращает выбранный графический объект ///\param type - тип объекта ///\return графический объект в слечае удачи, иначе NULL inline HGDIOBJ GetCurrentObject(UINT type) {return ::GetCurrentObject(*this,type);} ///\brief рисует линию начиная с текущей точки ///\param nXEnd, nYEnd - координаты конечной точки ///\return TRUE в случае успеха, иначе FALSE inline BOOL LineTo(int nXEnd,int nYEnd) {return ::LineTo(*this,nXEnd,nYEnd);} ///\brief устанавливает значение текущей точки ///\param X, Y - Координата новой устанавливаемой точки ///\param lpPoint - Координата предыдущей точки ///\return TRUE в случае успеха, иначе FALSE inline BOOL MoveTo(int X,int Y,LPPOINT lpPoint=NULL) {return ::MoveToEx(*this,X,Y,lpPoint);} ///\brief Копирует биты в заданый буфер, преобразуя их определенным образом ///\param hbmp - хендл на битмап ///\param uStartScan - номер первой линии для копирования ///\param cScanLines - число копируемых линий ///\param lpvBits - выходной буфер для скопированных данных ///\param lpbi - информация о битмапе ///\param uUsage -цветовой формат(DIB_PAL_COLORS,DIB_RGB_COLORS) ///\return число скопированных линий в буфер inline int GetDIBits(HBITMAP hbmp, UINT uStartScan,UINT cScanLines,LPVOID lpvBits,LPBITMAPINFO lpbi,UINT uUsage) {return ::GetDIBits(*this,hbmp, uStartScan,cScanLines,lpvBits,lpbi,uUsage); } ///\brief ресует закрашеный прямоугольник ///\param lprc - указатель на структуру прямоугольника ///\param hbr - хендл кисти, которой будет осуществлено закрашивание ///\return TRUE в случае успеха inline int FillRect(CONST RECT *lprc,HBRUSH hbr) {return (0!=::FillRect(*this,lprc,hbr));}; ///\brief ресует закрашеный прямоугольник ///\param hrgn - хендл закрашиваемого региона ///\param hbr - хендл кисти, которой будет осуществлено закрашивание ///\return TRUE в случае успеха inline int FillRgn(HRGN hrgn,HBRUSH hbr) {return (0!=::FillRgn(*this,hrgn,hbr));}; ///\brief функция сохраняет текущее состояние контекста ///\return TRUE в случае успеха BOOL SaveDC(); ///\brief функция востанавливает сохранённое состояние контекста ///\param nSavedDC - состояние для востановления ///\return TRUE в случае успеха BOOL RestoreDC(int nSavedDC); ///\brief функция рисует полигон ///\param lpPoints - указатель на массив точек полигона ///\param nCount - число точек в массиве ///\return TRUE в случае успеха BOOL Polygon(CONST POINT *lpPoints,int nCount); ///\brief функция для получения цвета по указанной координате ///\param nXPos,nYPos - координата ///\return цвет в случае успеха, иначе CLR_INVALID COLORREF GetPixel(int nXPos,int nYPos); ///\brief функция для установке цвета по указанной координате ///\param nXPos,nYPos - координата ///\param crColor - устанавливаемый цвет ///\return TRUE в случае успеха BOOL SetPixel(int nXPos,int nYPos,COLORREF crColor); ///\brief функция рисует иконку ///\param X,Y - координаты верхнего левого угла иконки ///\param hIcon - хендл иконки ///\return TRUE в случае успеха BOOL DrawIcon(int X,int Y,HICON hIcon); ///\brief функция рисует иконку ///\param xLeft,yTop - координаты верхнего левого угла иконки ///\param hIcon - хендл иконки ///\param cxWidth,cyWidth - размеры иконки ///\param istepIfAniCur - индекс фрейма, если иконка - анимированный курсор ///\param hbrFlickerFreeDraw - хендл на кисть, может быть NULL ///\param diFlags - флаг отрисовки ///\return TRUE в случае успеха BOOL DrawIconEx(int xLeft,int yTop,HICON hIcon,int cxWidth,int cyWidth, UINT istepIfAniCur,HBRUSH hbrFlickerFreeDraw,UINT diFlags); ///\brief функция устанавливает режим комбинирования \n /// рисоввания кистью или карандашом с текущим уже \n /// нарисованным изображением ///\param fnDrawMode режим комбинирования ///\return в случае успеха вернет предыдущий режим комбинирования, \n /// в случае неудачи вернёт 0 int SetROP2(int fnDrawMode); }; ///\class CULWindowDC ///\brief Класс контекста окна(10.09.2007) class CULWindowDC:public CULDC { public: ///\Конструктор inline explicit CULWindowDC(HWND hWndOwner):CULDC() { m_hWndOwner=hWndOwner; m_hDC=::GetWindowDC(hWndOwner); }; ///\brief деструктор ~CULWindowDC(){if(m_hDC!=NULL)::ReleaseDC(m_hWndOwner,*this);m_hDC=NULL;}; }; ///\class CULClientDC ///\brief Класс контекста клиентской области окна(10.09.2007) class CULClientDC:public CULDC { public: ///\Конструктор inline explicit CULClientDC(HWND hWndOwner):CULDC() { m_hWndOwner=hWndOwner; m_hDC=::GetDC(hWndOwner); }; ///\brief деструктор ~CULClientDC(){if(m_hDC!=NULL)::ReleaseDC(m_hWndOwner,*this);m_hDC=NULL;}; }; ///\class CULPaintDC ///\brief Класс контекста клиентской области окна(10.09.2007) ///применяется только в обработчиках WM_PAINT class CULPaintDC:public CULDC { public: PAINTSTRUCT m_PaintStruct; public: ///\Конструктор inline explicit CULPaintDC(HWND hWndOwner):CULDC() { m_hWndOwner=hWndOwner; m_hDC=::BeginPaint(hWndOwner,&m_PaintStruct); }; ///\brief деструктор ~CULPaintDC(){::EndPaint(m_hWndOwner,&m_PaintStruct);m_hDC=NULL;}; }; } } #endif//__ULDC__H_
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 276 ] ] ]
5a2d58ab383ace6352c47c671e480a56ce326930
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/AIHumanStateObstruct.h
0b3085642b6ffefca24e227ff93db369ffdb9de8
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
3,048
h
//---------------------------------------------------------------------------- // // MODULE: AIHumanStateObstruct.h // // PURPOSE: CAIHumanStateObstruct declaration // // CREATED: 12.12.2001 // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // // COMMENTS: - // // //---------------------------------------------------------------------------- #ifndef __AIHUMANSTATEOBSTRUCT_H__ #define __AIHUMANSTATEOBSTRUCT_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Includes #include "AIHumanState.h" #include "AINode.h" // Forward declarations class AINodeObstruct; // Globals // Statics //---------------------------------------------------------------------------- // // CLASS: CAIHumanStateObstruct // // PURPOSE: State for characters to use Obstruct nodes. Characters use // Obstruct nodes to imped progress along a vector. For example, // an obstruct goal may result in a character running in front of // the player, entering a defensive stance, and waiting for any // of a number of things to time out of the stance. // //---------------------------------------------------------------------------- class CAIHumanStateObstruct : public CAIHumanState { typedef CAIHumanState super; public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CAIHumanStateObstruct, kState_HumanObstruct); CAIHumanStateObstruct( ); ~CAIHumanStateObstruct( ); // Ctors/dtors/etc virtual LTBOOL Init(CAIHuman* pAIHuman); virtual void Load(ILTMessage_Read *pMsg); virtual void Save(ILTMessage_Write *pMsg); virtual void Update(void); virtual void UpdateAnimation(void); virtual CMusicMgr::Mood GetMusicMood(void) { return CMusicMgr::eMoodAggressive; } // Simple acccessors void SetNode(AINodeObstruct& pUseNode); void SetObjectToObstruct(HOBJECT); void SetAcceptableDistanceToNode(float fDist); enum eStateTerminationConditions { kDC_Invalid = 0, kDC_Time = 1, kDC_Event = 2, kDC_Message = 3, kDC_Damage = 3, }; protected: private: void MaybePlayFirstUpdateSound(); void ClearObstructObject(); void SetPathNode(AINodeObstruct& ObstructNode); void InitPath(CAIHuman* pAIHuman); bool IsValidObstructNode(AINodeObstruct& Node); bool IsAICloseEnoughToNode(void); bool IsNodeStillValid(void); bool AttemptSetPathToNode(AINodeObstruct& Node); bool CanUpdatePath(void); HOBJECT GetObjectToObstruct(void); // Pointer to the node to do the obstruction from. ie, the // AI will run to this point and do the obstruction either here // or in some proximity to here. LTObjRef m_hNodeToDoObstructAt; // How close is close enough to the obstruction node? float m_fCloseEnoughDistSqr; // Object we are trying to block/obstruct at this node LTObjRef m_hObjectToObstruct; }; #endif // __AIHUMANSTATESENTRYCHALLENGE_H__
[ [ [ 1, 111 ] ] ]
ea1479c880a8718607e2a1276e3904b3dd067e17
448ef6f020ff51ef3c4266e2504a49e18c032d04
/CppTest/CppTest/AsFoo.cpp
5153875e6c9307f8c06cdea7c330b749d2435187
[]
no_license
weeeBox/oldies-cpp-template
f0990a1832e0f441db8523932a19a6addf16d620
00223721d33f95b396dc698a5596199224291e8b
refs/heads/master
2020-05-20T07:33:33.792823
2011-12-09T16:45:10
2011-12-09T16:45:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
#include "AsFoo.h" #include "AsFoo.h" AsFoo_ref AsFoo::__createAsFoo(int value) { AsFoo_ref __reference(new AsFoo()); __reference->__internalConstructAsFoo(value); return __reference; } void AsFoo::__internalConstructAsFoo(int value) { __internalConstructAsObject(); __internalInitialiseAsFoo(); this->value = value; } void AsFoo::__internalInitialiseAsFoo() { } StaticInit AsFoo::__internalStaticInitializerAsFoo(&AsFoo::__internalStaticInit); BOOL AsFoo::__internalStaticInitializedAsFoo = false; void AsFoo::__internalStaticInit() { if (!__internalStaticInitializedAsFoo) { __internalStaticInitializedAsFoo = true; AsObject::__internalStaticInit(); } } AsFoo::AsFoo() : value(0) { }
[ "[email protected]@29e91505-0bf5-f861-a13c-499aeb2b9760" ]
[ [ [ 1, 38 ] ] ]
30e8ab165a9402554ea37b4e0aae65b8156b5704
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/tests/729/sft/TalkDll/MixOut.h
9b2bca6b96011dbe83e1c07e65d594687985264c
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
GB18030
C++
false
false
1,551
h
/*------------------------------------------------------------------------------*\ [模块名称] CMixOut [文件名称] MixOut.h [相关文件] MixOut.cpp [目的] 控制混音输出 [描述] 封装 mixer api [注意] 你只应该使用本类一次,是由于窗口消息引起的 设置,获取音量没有做 数据质量为 1 channel,16bit,8000 sample [依赖性] winmm.lib [版权] 2002.12 胡斌 版权所有 [修改记录] 版本: 1.01.01 日期: 02-12-20 作者: 胡斌 Mial: [email protected] 备注: \*------------------------------------------------------------------------------*/ #ifndef _MIXOUT_H_ #define _MIXOUT_H_ #include <mmsystem.h> class CMixOut { public: virtual void OnControlChanged(int iValue); BOOL UnIni(); BOOL Ini(); virtual DWORD GetMinimalVolume(); virtual DWORD GetMaximalVolume(); virtual DWORD GetCurrentVolume(); virtual void SetCurrentVolume( DWORD dwValue ); inline MMRESULT GetLastMMError(); CString GetLastErrorString(); CMixOut(); virtual ~CMixOut(); protected: BOOL CloseMixer(); BOOL OpenMixer(); BOOL Initialize(); static LRESULT CALLBACK MixerWndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); protected: int m_iDevNum; HMIXER m_hMixer; UINT m_uiMixerId; DWORD m_dwMinimalVolume; DWORD m_dwMaximalVolume; BOOL m_bIni; MMRESULT m_mmr; HWND m_hWnd; }; #endif
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 83 ] ] ]
f9abff227ee46bb760fb0d1b10f88c8f6446202b
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/MathLib/flx_plane.h
44c0fb5b0135f1d9aa96a3c0b2408aa1e428723f
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
2,016
h
/*--------------------------------------------------------------------------- This source file is part of the FluxEngine. Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin) This program is free software. ---------------------------------------------------------------------------*/ #ifndef PLANE_H #define PLANE_H #include "../Core/flx_core.h" #include "flx_math.h" #include "flx_vector3.h" enum location_to_plane { P_NEGATIVE, P_POSITIVE, P_ONPLANE }; class Plane { public: inline Plane() { m_v3PositionVector = Vector3(0, 0, 0); m_v3Normal = Vector3(0, 1, 0); m_bOk = true; } inline Plane(const Vector3& v3Point, const Vector3& v3Normal) : m_v3PositionVector(v3Point), m_v3Normal(v3Normal) { m_fDist = dot(m_v3Normal, v3Point); if(m_v3Normal.isZero()) { m_bOk = false; return; } m_bOk = true; m_v3Normal.normalize(); m_fDist /= m_v3Normal.fMag; } inline Plane(const Vector3& v3Point1, const Vector3& v3Point2, const Vector3& v3Point3) : m_v3PositionVector(v3Point1) { Vector3 v3Vector1(v3Point2 - v3Point1); Vector3 v3Vector2(v3Point3 - v3Point1); m_v3Normal = v3Vector1.cross(v3Vector2); if(m_v3Normal.isZero()) { m_bOk = false; return; } m_bOk = true; m_v3Normal.normalize(); } virtual ~Plane() {} inline Vector3 GetNormal() { return m_v3Normal; } inline void normalize() { float mag = sqrt(a*a + b*b + c*c); mag = 1.0f/mag; a *= mag; b *= mag; c *= mag; d *= mag; } inline float distance(const Vector3& point) const { return (a*point.x + b*point.y + c * point.z + d); } inline location_to_plane classifyPoint(const Vector3& point) const { float td = distance(point); if(td < 0.0f) return P_NEGATIVE; else return P_POSITIVE; } public: bool m_bOk; float m_fDist; Vector3 m_v3Normal; float a, b, c, d; Vector3 m_v3PositionVector; private: }; #endif
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 115 ] ] ]
b2b7319a5f2fa9ac9fa27ad640d0428d8462716d
6eef3e34d3fe47a10336a53df1a96a591b15cd01
/ASearch/Config/ConfigBase.cpp
65c6807c05102734590e6446e4615735ed6d3731
[]
no_license
praveenmunagapati/alkaline
25013c233a80b07869e0fdbcf9b8dfa7888cc32e
7cf43b115d3e40ba48854f80aca8d83b67f345ce
refs/heads/master
2021-05-27T16:44:12.356701
2009-10-29T11:23:09
2009-10-29T11:23:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,657
cpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved _____________________________________________________ written by Daniel Doubrovkine - [email protected] */ #include <alkaline.hpp> #include "ConfigBase.hpp" CConfigBase :: CConfigBase(void) : m_pConfigurationOptions(NULL), m_nConfigurationOptions(0) { } CConfigBase :: CConfigBase(const CConfigBase& /* Other */) : m_pConfigurationOptions(NULL), m_nConfigurationOptions(0) { } CConfigBase :: ~CConfigBase(void) { if (m_pConfigurationOptions) delete[] m_pConfigurationOptions; } CConfigBase& CConfigBase :: Copy(const CConfigBase& Other) { CStringTable::operator=(Other); return * this; } bool CConfigBase :: BooleanEval(const CString& _Value) { CString Value(_Value); Value.Trim32(); if (!Value.GetLength()) return false; if (Value.Same("Y")) return true; else if (Value.Same("N")) return false; else if (CString::StrToInt(Value) == 1) return true; else if (Value.Same("YES")) return true; else if (Value.Same("NO")) return false; else return false; } int CConfigBase :: TranslateSize(CString iStr, int Default) { if (iStr.GetLength()) { iStr.Trim32(); int l_Multiplier = 1; if (iStr.EndsWith("MB")) { l_Multiplier = 1000000; iStr.Delete(iStr.GetLength() - strlen("MB"), iStr.GetLength()); iStr.Trim32(); } else if (iStr.EndsWith("M")) { l_Multiplier = 1000000; iStr.Delete(iStr.GetLength() - strlen("M"), iStr.GetLength()); iStr.Trim32(); } else if (iStr.EndsWith("KB")) { l_Multiplier = 1000; iStr.Delete(iStr.GetLength() - strlen("KB"), iStr.GetLength()); iStr.Trim32(); } else if (iStr.EndsWith("K")) { l_Multiplier = 1000; iStr.Delete(iStr.GetLength() - strlen("K"), iStr.GetLength()); iStr.Trim32(); } if (iStr.GetLength() && (iStr[0] == '-')) { l_Multiplier = - l_Multiplier; iStr.Delete(0, 1); } for (int i=0;i<(int) iStr.GetLength();i++) { if (!isdigit(iStr[i])) { cout << " [ignoring invalid size setting: " << iStr << "]" << endl; return Default; } } if (iStr.GetLength()) { return (CString::StrToInt(iStr) * l_Multiplier); } else { cout << " [ignoring invalid size setting: " << iStr << "]" << endl; return Default; } } else return Default; } void CConfigBase :: DumpVirtual(CConfigOption& /* ConfigurationOption */) const { cout << "virtual unknown type"; } void CConfigBase :: DumpOptions(void) const { for (int i = 0; i < m_nConfigurationOptions; i++) { cout << m_pConfigurationOptions[i].csName << ": "; switch(m_pConfigurationOptions[i].ccoType) { // simple digit with optional boundaries case ccoDigit: cout << "number, default=" << * (int *) m_pConfigurationOptions[i].pOption; if (m_pConfigurationOptions[i].lArg1 != -1) cout << ", reset=" << m_pConfigurationOptions[i].lArg1; break; case ccoDigitBound: cout << "number, default=" << * (int *) m_pConfigurationOptions[i].pOption; cout << ", min=" << m_pConfigurationOptions[i].lArg1; cout << ", max=" << m_pConfigurationOptions[i].lArg2; break; // positive digit with a default value case ccoDigitPos: cout << "positive number, default=" << * (int *) m_pConfigurationOptions[i].pOption; if (m_pConfigurationOptions[i].lArg1 != -1) cout << ", reset=" << m_pConfigurationOptions[i].lArg1; break; case ccoTranslateSet: cout << "size, default=" << * (int *) m_pConfigurationOptions[i].pOption; break; case ccoBool: cout << "boolean, default=" << CString::BoolToStr(* (bool *) m_pConfigurationOptions[i].pOption); break; case ccoBoolInverted: // inverted boolean options depricated // cout << "inverted boolean, default=" << CString::BoolToStr(!(* (bool *) m_pConfigurationOptions[i].pOption)); break; case ccoVirtual: DumpVirtual(m_pConfigurationOptions[i]); break; case ccoString: cout << "string, default=" << ((* (CString *) m_pConfigurationOptions[i].pOption).GetLength() ? (* (CString *) m_pConfigurationOptions[i].pOption).GetBuffer() : "(not set)"); break; case ccoStringPos: cout << "non-empty string, default=" << ((* (CString *) m_pConfigurationOptions[i].pOption).GetLength() ? (* (CString *) m_pConfigurationOptions[i].pOption).GetBuffer() : "(not set)"); break; case ccoArray: cout << "array, default="; if (((CVector<CString> *) m_pConfigurationOptions[i].pOption)->GetSize()) { for (int j=0; j< (int) ((CVector<CString> *) m_pConfigurationOptions[i].pOption)->GetSize(); j++) { if (j) cout << ", "; cout << (* (CVector<CString> *) m_pConfigurationOptions[i].pOption)[j]; } } else cout << "(not set)"; break; case ccoEvalPair: cout << "complex pair"; break; } cout << endl << " [" << m_pConfigurationOptions[i].csDescription << "]" << endl; } } bool CConfigBase :: FinalizeDigitSetting(int& Value, const CString& Name, int Default) const { // cout << "FinalizeDigitSetting for " << Value << " / " << Name << endl; CString LocalValue(GetValue(Name)); LocalValue.Trim32(); if ((LocalValue.IsInt(&Value))&&(Value < Default)) { Value = Default; cout << " [ignoring invalid " << Name << " setting: " << GetValue(Name) << ", defaulting to " << Value << "]" << endl; return false; } return true; } bool CConfigBase :: FinalizeDigitValue(int& Value, const CString& Setting, int LowerLimit, int Default) const { if (Value < LowerLimit) { Value = Default; cout << " [adjusting " << Setting << "=" << Value << "]" << endl; return true; } else return false; } void CConfigBase :: CreateConfigurationOptions(void) { } void CConfigBase :: CreateConfigurationOptions( CConfigOption * LocalConfigurationOptions, int nConfigurationOptions) { assert(m_pConfigurationOptions == NULL); if (! nConfigurationOptions) return; m_nConfigurationOptions = nConfigurationOptions; m_pConfigurationOptions = new CConfigOption[m_nConfigurationOptions]; for (int i = 0; i < m_nConfigurationOptions; i++) { m_pConfigurationOptions[i].csName = LocalConfigurationOptions[i].csName; m_pConfigurationOptions[i].ccoType = LocalConfigurationOptions[i].ccoType; m_pConfigurationOptions[i].pOption = LocalConfigurationOptions[i].pOption; m_pConfigurationOptions[i].lArg1 = LocalConfigurationOptions[i].lArg1; m_pConfigurationOptions[i].lArg2 = LocalConfigurationOptions[i].lArg2; m_pConfigurationOptions[i].csDescription = LocalConfigurationOptions[i].csDescription; } } void CConfigBase :: FinalizeVirtual(CConfigOption& /* ConfigurationOption */) { } void CConfigBase :: Finalize(void) { CString TmpString; for (int i = 0; i < m_nConfigurationOptions; i++) { // cout << "Looking at " << m_pConfigurationOptions[i].csName << endl; switch(m_pConfigurationOptions[i].ccoType) { // simple digit with optional boundaries case ccoDigit: FinalizeDigitSetting( * (int *) (m_pConfigurationOptions[i].pOption), m_pConfigurationOptions[i].csName, (int) m_pConfigurationOptions[i].lArg1); break; case ccoDigitBound: FinalizeDigitSetting( * (int *) m_pConfigurationOptions[i].pOption, m_pConfigurationOptions[i].csName); if (m_pConfigurationOptions[i].lArg1 != m_pConfigurationOptions[i].lArg2) { FinalizeDigitValue( * (int *) m_pConfigurationOptions[i].pOption, m_pConfigurationOptions[i].csName, (int) m_pConfigurationOptions[i].lArg1, (int) m_pConfigurationOptions[i].lArg2); } break; // positive digit with a default value case ccoDigitPos: FinalizeDigitSetting( * (int *) m_pConfigurationOptions[i].pOption, m_pConfigurationOptions[i].csName); if (* (int *) m_pConfigurationOptions[i].pOption < 0) { * (int *) m_pConfigurationOptions[i].pOption = m_pConfigurationOptions[i].lArg1; cout << " [adjusting " << m_pConfigurationOptions[i].csName << " to " << * (int *) m_pConfigurationOptions[i].pOption << "]" << endl; } break; case ccoTranslateSet: * (int *) m_pConfigurationOptions[i].pOption = TranslateSize( GetValue(m_pConfigurationOptions[i].csName), * (int *) m_pConfigurationOptions[i].pOption); Set(m_pConfigurationOptions[i].csName, CString::IntToStr(* (int *) m_pConfigurationOptions[i].pOption)); break; case ccoBool: TmpString = GetValue(m_pConfigurationOptions[i].csName); TmpString.Trim32(); if (TmpString.GetLength()) * (bool *) m_pConfigurationOptions[i].pOption = BooleanEval(TmpString); break; case ccoBoolInverted: TmpString = GetValue(m_pConfigurationOptions[i].csName); TmpString.Trim32(); if (TmpString.GetLength()) * (bool *) m_pConfigurationOptions[i].pOption = ! BooleanEval(TmpString); break; case ccoVirtual: FinalizeVirtual(m_pConfigurationOptions[i]); break; case ccoString: (* (CString *) m_pConfigurationOptions[i].pOption) = GetValue(m_pConfigurationOptions[i].csName); (* (CString *) m_pConfigurationOptions[i].pOption).Trim32(); break; case ccoStringPos: TmpString = GetValue(m_pConfigurationOptions[i].csName); TmpString.Trim32(); if (TmpString.GetLength()) { (* (CString *) m_pConfigurationOptions[i].pOption) = TmpString; } break; case ccoArray: TmpString = GetValue(m_pConfigurationOptions[i].csName); TmpString.Trim32(); if (TmpString.GetLength()) { CVector<CString> * pVector = (CVector<CString> *) m_pConfigurationOptions[i].pOption; CString::StrToVector( TmpString, ',', pVector); if (pVector && pVector->GetSize()) { for (register int j = (int) pVector->GetSize() - 1; j >= 0; j--) { (* pVector)[j].Trim32(); if (! (* pVector)[j].GetLength()) { pVector->RemoveAt(j); } } } } break; case ccoEvalPair: break; } } }
[ [ [ 1, 345 ] ] ]
ae27fb8172c6b1ecc9ac1f8aec78d04aabf5b755
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/ScriptVM.cpp
fd0eb1cf51ed0c9959cc0c7eb670046527a58708
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
GB18030
C++
false
false
11,970
cpp
#include "engpch.h" #include ".\scriptvm.h" extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "tolua++.h" #include "log_t.h" #define DEBUG_STACK 0 //end of tolua bind declare extern KVOID tolua_open_binding(lua_State * L); static KVOID stackDump(lua_State *L); //error_msg handling function static KVOID error_msg(KBOOL bUseAssert, KCCHAR * pacFmt, ...) { #if defined(_DEBUG) KCHAR acTemp[2048]; va_list args; va_start(args, pacFmt); vsprintf_s(acTemp, pacFmt, args); va_end(args); // if(bUseAssert) // SP_ASSERT(false, acTemp); syslog->error(acTemp); #endif } static KVOID report_last_error(lua_State *L, KBOOL bUseAssert) { lua_getglobal(L, "_ALERT"); error_msg(bUseAssert, "%s\n", lua_tostring(L, -2)); error_msg(bUseAssert, "%s\n", lua_tostring(L, -1)); lua_pop(L, 2); /* remove error_msg message and _ALERT */ } static KVOID stackDump (lua_State *L) { KINT i; KINT top = lua_gettop(L); for (i = 1; i <= top; i++) { /* repeat for each level */ KINT t = lua_type(L, i); switch (t) { case LUA_TSTRING: /* strings */ printf("`%s'", lua_tostring(L, i)); break; case LUA_TBOOLEAN: /* booleans */ printf(lua_toboolean(L, i) ? "true" : "false"); break; case LUA_TNUMBER: /* numbers */ printf("%g", lua_tonumber(L, i)); break; default: /* other values */ printf("%s", lua_typename(L, t)); break; } printf(" "); /* put a separator */ } printf("\n"); /* end the listing */ } namespace Kylin { ScriptVM::ScriptVM(KVOID) { } ScriptVM::~ScriptVM(KVOID) { } static KINT PrintStringList ( lua_State * L ){ KINT n = lua_gettop(L); /* number of arguments */ KINT i; lua_getglobal(L, "tostring"); string out; for (i=1; i<=n; i++) { KCCHAR *s; lua_pushvalue(L, -1); /* function to be called */ lua_pushvalue(L, i); /* value to print */ lua_call(L, 1, 1); s = lua_tostring(L, -1); /* get result */ if (s == NULL) return luaL_error(L, "`tostring' must return a string to `print'"); if (i>1) { out+="\t"; out+=s; } else out+=s; lua_pop(L, 1); /* pop result */ } out+="\n"; syslog->debug("%s",out.c_str()); return 0; } KBOOL ScriptVM::Init(KVOID) { L = lua_open(); luaL_openlibs(L); // luaopen_base(L); // luaopen_io(L); // luaopen_table(L); // luaopen_math(L); // luaopen_string(L); // luaopen_debug(L); lua_gc(L,LUA_GCCOLLECT, 200);//lua_setgcthreshold(L, 200); //200k garbage collection threshold lua_register(L,"print",PrintStringList); return true; } KVOID ScriptVM::Destroy(KVOID) { lua_close(L); } KVOID ScriptVM::ExecuteScriptFile(KCCHAR * sScriptName, KBOOL bForceReload /* = false*/, KBOOL bAssertOnError /*= true*/) { KINT nSize1 = lua_gettop(L); //get chunk name as modified script name KSTR sChunkName(sScriptName); for(KUINT i=0; i< sChunkName.length(); i++) { if(sChunkName[i] == '/' || sChunkName[i] == '.') sChunkName[i] = '_'; } //get the chunk global lua_getglobal(L, sChunkName.c_str()); if( bForceReload || !lua_isfunction(L, -1) )//if force reload or not found { luaL_loadfile(L, sScriptName); lua_setglobal(L, sChunkName.c_str()); lua_getglobal(L, sChunkName.c_str()); } if( lua_pcall(L, 0, 0, 0) != 0) { error_msg(bAssertOnError, "error executing script file %s: ", sScriptName); report_last_error(L, bAssertOnError); } failed: lua_settop(L, nSize1); } KVOID ScriptVM::ExecuteScript(KCCHAR * sScript, KBOOL bAssertOnError) { KINT status=luaL_loadbuffer(L,sScript,strlen(sScript),sScript); if(status) { report_last_error(L, bAssertOnError); } else { status = lua_pcall(L, 0, LUA_MULTRET, 0); /* call main */ if(status) report_last_error(L, bAssertOnError); } } /* * Execute Script Function func in the script. copy/pasted from the book "programming in LUA" */ KVOID ScriptVM::ExecuteScriptFunc(const std::vector<KCCHAR *>&modules, KCCHAR * func, KBOOL bAllowNonexist, KCCHAR * sig, ...) { KINT nSize1 = lua_gettop(L); va_list vl; KINT narg, nres; /* number of arguments and results */ va_start(vl, sig); //get the actual function if(modules.empty()) //func is global { lua_getglobal(L, func); } else { //trace down the modules std::vector<KCCHAR *>::const_iterator it = modules.begin(); //get the global module name or the actual function name if there is no module lua_getglobal(L, *it); if(!lua_istable(L, -1)) { if(!bAllowNonexist) error_msg(true, "ExecuteScriptFunc: Invalid table name: %s\n", *it ); goto failed; } for( ++it; it != modules.end(); ++it) { lua_pushstring(L, *it); lua_gettable(L, -2); if(!lua_istable(L, -1)) { if(!bAllowNonexist) error_msg(true, "ExecuteScriptFunc: Invalid table name: %s\n", *it ); goto failed; } } //get the func lua_pushstring(L, func); lua_gettable(L, -2); if(!lua_isfunction(L, -1)) { if(!bAllowNonexist) error_msg(true, "ExecuteScriptFunc: Invalid function name: %s\n", func); goto failed; } } /* push arguments */ narg = 0; while (*sig){ /* push arguments */ switch (*sig++){ case 'd': /* KDOUBLE argument */ lua_pushnumber(L, va_arg(vl, KDOUBLE)); break; case 'i': /* KINT argument */ lua_pushnumber(L, va_arg(vl, KINT)); break; case 's': /* string argument */ lua_pushstring(L, va_arg(vl, KCHAR *)); break; case 'b': /* boolean argument */ lua_pushboolean(L, va_arg(vl, KBOOL)); break; case 'u': /* light user data */ lua_pushlightuserdata(L, va_arg(vl, KVOID *)); break; case '>': goto endwhile; default: error_msg(true, "invalid option (%c)\n", *(sig - 1)); goto failed; } narg++; luaL_checkstack(L, 1, "too many arguments"); }endwhile: /* do the call */ nres = strlen(sig); /* number of expected results */ if (lua_pcall(L, narg, nres, 0) != 0) /* do the call */ { report_last_error(L, true); goto failed; } /* retrieve results */ nres = -nres; /* stack index of first result */ while (*sig) { /* get results */ switch (*sig++) { case 'd': /* KDOUBLE result */ if (!lua_isnumber(L, nres)) error_msg(true, "wrong result type\n"); *va_arg(vl, KDOUBLE *) = lua_tonumber(L, nres); break; case 'i': /* KINT result */ if (!lua_isnumber(L, nres)) error_msg(true, "wrong result type\n"); *va_arg(vl, KINT *) = (KINT)lua_tonumber(L, nres); break; case 's': /* string result */ if (!lua_isstring(L, nres)) error_msg(true, "wrong result type\n"); *va_arg(vl, KCCHAR **) = lua_tostring(L, nres); break; case 'b': /* boolean argument */ if (!lua_isboolean(L, nres)) error_msg(true, "wrong result type\n"); *va_arg(vl, KBOOL *) = ( 0 != lua_toboolean(L, nres)); break; case 'u': /* light user data */ if (!lua_isuserdata(L, nres)) error_msg(true, "wrong result type\n"); *va_arg(vl, KVOID **) = lua_touserdata(L, nres); break; default: error_msg(true, "invalid option (%c)\n", *(sig - 1)); } nres++; } failed: va_end(vl); //clear the stack lua_settop(L, nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); if(nSize1 != nSize2) stackDump(L); #endif } KVOID ScriptVM::ExposeGlobalUserdata( KVOID * va, KCCHAR * name, KCCHAR * type) { KINT nSize1 = lua_gettop(L); #if DEBUG_STACK //debug printf("debug lua: stack size before ExposeGlobalUserdata = %d\n", nSize1); #endif tolua_pushusertype(L, va, type); lua_setglobal(L, name); //clear the stack lua_settop(L, nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); printf("debug lua: stack size after ExposeGlobalUserdata = %d\n", nSize2); if(nSize1 != nSize2) stackDump(L); #endif } KVOID * ScriptVM::GetGlobalUserdata(KCCHAR * name, KCCHAR * verify_type /*= NULL*/) { KINT nSize1 = lua_gettop(L); #if DEBUG_STACK //debug printf("debug lua: stack size before GetGlobalUserdata = %d\n", nSize1); #endif lua_getglobal(L, name); //verify type if(verify_type) { tolua_Error tolua_err; if ( !tolua_isusertype(L,1,verify_type,0,&tolua_err) || !tolua_isnoobj(L,2,&tolua_err) ) { tolua_error(L,"#ferror in function 'ScriptVM::GetGlobalUserdata'.",&tolua_err); goto failed; } } KVOID * pRet = tolua_tousertype(L, -1, 0); //clear the stack lua_settop(L, nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); printf("debug lua: stack size after GetGlobalUserdata = %d\n", nSize2); if(nSize1 != nSize2) stackDump(L); #endif return pRet; failed: //lua_settop(L,0); lua_settop(L, nSize1); return NULL; } KDOUBLE ScriptVM::GetGlobalNumber(KCCHAR * name) { KINT nSize1 = lua_gettop(L); #if DEBUG_STACK //debug printf("debug lua: stack size before GetGlobalUserdata = %d\n", nSize1); #endif lua_getglobal(L, name); KDOUBLE ret = tolua_tonumber(L, -1, 0); //clear the stack lua_settop(L, nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); printf("debug lua: stack size after GetGlobalUserdata = %d\n", nSize2); if(nSize1 != nSize2) stackDump(L); #endif return ret; } KVOID * ScriptVM::GetUserdata(const std::vector<KCCHAR *>& modules, KCCHAR * name, KCCHAR * verify_type/*= NULL*/) { KINT nSize1 = lua_gettop(L); #if DEBUG_STACK printf("debug lua: stack size before GetUserdata = %d\n", nSize1); #endif if(modules.empty()) //userdata is global { lua_getglobal(L, name); } else { //trace down the modules std::vector<KCCHAR *>::const_iterator it = modules.begin(); //get the global module name or the actual function name if there is no module lua_getglobal(L, *it); if(!lua_istable(L, -1)) { error_msg(true, "GetUserdata: Invalid table name: %s\n", *it ); goto failed; } for( ++it; it != modules.end(); ++it) { lua_pushstring(L, *it); lua_gettable(L, -2); if(!lua_istable(L, -1)) { error_msg(true, "GetUserdata: Invalid table name: %s\n", *it ); goto failed; } } //get the data lua_pushstring(L, name); lua_gettable(L, -2); } KVOID * pRet = tolua_tousertype(L, -1, 0); //clear the stack lua_settop(L, nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); printf("debug lua: stack size after GetUserdata = %d\n", nSize2); if(nSize1 != nSize2) stackDump(L); #endif return pRet; failed: lua_settop(L, nSize1); return NULL; } //由tolua注册过的类名创建对象 KVOID * ScriptVM::CreateObjectByTypeName(KCCHAR * sTypeName) { //处理lua脚本 KINT nSize = (KINT)strlen(sTypeName)+20; KBYTE* buffer = KNEW KBYTE[nSize]; sprintf((KCHAR*)buffer,"pMyCreatedObj=%s:KNEW()",sTypeName); //执行脚本 ExecuteScript((KCHAR*)buffer); KVOID* ret=GetGlobalUserdata("pMyCreatedObj"); return ret; } //获得全局表中常量 KDOUBLE ScriptVM::GetGlobalTableNumber(KCCHAR *sTableName,KCCHAR* key) { KINT nSize1 = lua_gettop(L); #if DEBUG_STACK //debug printf("debug lua: stack size before GetGlobalUserdata = %d\n", nSize1); #endif lua_getglobal(L,sTableName); if(!lua_istable(L,-1)) { error_msg(true, "GetGlobalTableNumber: %s isn't a Lua Table.",sTableName); goto failed; } lua_pushstring(L,key); lua_gettable(L,-2); if(!lua_isnumber(L,-1)) { error_msg(true, "GetGlobalTableNumber: %s isn't a number.",key); goto failed; } KDOUBLE ret = lua_tonumber(L,-1); lua_settop(L,nSize1); #if DEBUG_STACK //debug KINT nSize2 = lua_gettop(L); printf("debug lua: stack size after GetUserdata = %d\n", nSize2); if(nSize1 != nSize2) stackDump(L); #endif return ret; failed: lua_settop(L,nSize1); return 0; } }
[ [ [ 1, 510 ] ] ]
79ca8837f501a86ff61cfff8d3e2084ed35fc974
314fa4d6839de9abfdedb72a521a156c06522761
/neckGirthTest/neckGirthTest/stdafx.cpp
c178c3f76521d8bbb410a9046fc6a60e616bea28
[]
no_license
moonjuice/moonjuice
7b87f5a36cc696dc232cb8257e91aa60a0b5cca8
262bbf8e3e487191160566adf0f28771bccb375e
refs/heads/master
2021-01-10T20:33:50.474152
2011-11-24T00:52:29
2011-11-24T00:52:29
32,118,070
0
0
null
null
null
null
BIG5
C++
false
false
194
cpp
// stdafx.cpp : 僅包含標準 Include 檔的原始程式檔 // neckGirthTest.pch 會成為先行編譯標頭檔 // stdafx.obj 會包含先行編譯型別資訊 #include "stdafx.h"
[ "[email protected]@8026b7c3-d9ae-87c5-0fde-12bd377d1155" ]
[ [ [ 1, 8 ] ] ]
b7c39f1de340a235d06bef3f410e1d1e2c0514a7
5210c96be32e904a51a0f32019d6be4abdb62a6d
/LinkedList.h
65e0f6edb2db023df78e4adac2e70673659f0aac
[]
no_license
Russel-Root/knot-trying-FTL
699cec27fcf3f2b766a4beef6a58176c3cbab33e
2c1a7992855927689ad1570dd7c5998a73728504
refs/heads/master
2021-01-15T13:18:35.661929
2011-04-02T07:51:51
2011-04-02T07:51:51
1,554,271
1
0
null
null
null
null
IBM852
C++
false
false
4,813
h
#ifndef __LinkedList_h__ #define __LinkedList_h__ #ifndef NULL #define NULL 0 #endif // NULL // MyLinkedList, MyLinkedListIterator, ListNode╗ą╬¬friend class template<typename T> class MyLinkedList; template<typename T> class MyLinkedListIterator; template<typename T> class ListNode{ public: ListNode(){ node = 0; next = 0; previous = 0; } public: T* node; ListNode* next; ListNode* previous; }; template<typename T> class MyLinkedList{ public: MyLinkedList(); ~MyLinkedList(); public: int size() const; bool add(T* node); bool remove(T* node); bool remove(int index); T* get(int index) const; T* getFirst() const; T* getLast() const; T* getPrevious(T* currentNode) const; T* getNext(T* currentNode) const; ListNode<T>* head; ListNode<T>* tail; int n; }; template<typename T> class MyLinkedListIterator{ public: MyLinkedListIterator(const MyLinkedList<T>* lList); ~MyLinkedListIterator(); void rewind(); bool hasNext(); bool hasPrevius(); T* next(); T* previous(); private: ListNode<T>* current; const MyLinkedList<T>* list; }; template<typename T> MyLinkedList<T>::MyLinkedList(){ head = new ListNode<T>(); tail = new ListNode<T>(); head->next = head->previous = tail; tail->next = tail->previous = head; n = 0; } template<typename T> MyLinkedList<T>::~MyLinkedList(){ ListNode<T>* current = this->head->next; ListNode<T>* temp; while ( current != tail ){ temp = current; current = current->next; delete temp; } delete head; delete tail; } template<typename T> int MyLinkedList<T>::size() const{ return this->n; } template<typename T> bool MyLinkedList<T>::add(T* node){ if (node == 0) return false; ListNode<T>* newNode = new ListNode<T>(); newNode->node = node; newNode->next = tail; newNode->previous = tail->previous; tail->previous->next = newNode; tail->previous = newNode; n++; return true; } template<typename T> bool MyLinkedList<T>::remove(T* node){ if ( !node ) return false; ListNode<T>* current = this->head->next; while( current != this->tail ){ if ( current->node == node ){ current->previous->next = current->next; current->next->previous = current->previous; delete current; n++; return true; } else current = current->next; } return false; } template<typename T> T* MyLinkedList<T>::get(int index) const{ if ( index < 0 || index >= n ) return 0; ListNode<T>* current = this->head->next; int i = 0; while( current != this->tail && i < index ){ i++; current = current->next; } return current->node; } template<typename T> bool MyLinkedList<T>::remove(int index){ if ( index < 0 || index >= n ) return false; ListNode<T>* current = this->head->next; int i = 0; while( i < index ){ i++; current = current->next; } current->previous->next = current->next; current->next->previous = current->previous; delete current; return true; } template<typename T> T* MyLinkedList<T>::getFirst() const{ if ( this->head->next != this->tail ) return this->head->next->node; else return 0; } template<typename T> T* MyLinkedList<T>::getLast() const{ if (this->head != this->tail->previous) return this->tail->previous->node; else return 0; } template<typename T> T* MyLinkedList<T>::getNext(T* currentNode) const { if ( currentNode->next != this->tail ) return currentNode->next->node; else return 0; } template<typename T> T* MyLinkedList<T>::getPrevious(T* currentNode) const { if ( currentNode->previous != head ) return currentNode->previous->node; else return 0; } template<typename T> MyLinkedListIterator<T>::MyLinkedListIterator(const MyLinkedList<T>* _list):list(_list){ this->current = NULL; } template<typename T> MyLinkedListIterator<T>::~MyLinkedListIterator(){} template<typename T> void MyLinkedListIterator<T>::rewind(){ if ( this->list->n > 0 ) this->current = this->list->head->next; else this->current = NULL; } template<typename T> bool MyLinkedListIterator<T>::hasNext(){ return (this->current != NULL) && (this->current != this->list->tail); } template<typename T> T* MyLinkedListIterator<T>::next(){ if ( !this->hasNext() ) return NULL; this->current = this->current->next; return this->current->previous->node; } template<typename T> bool MyLinkedListIterator<T>::hasPrevius(){ return (this->current != NULL) && (this->current != this->list->head); } template<typename T> T* MyLinkedListIterator<T>::previous(){ if ( !this->hasPrevius() ) return NULL; this->current = this->current->previous; return this->current->next->node; } #endif // __LinkedList_h__
[ [ [ 1, 215 ] ] ]
08d0524377f6f92acd7a6f063e087cc51aac19cd
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/direct3d10/drawcommandexecuted3d10_3.cpp
2b7778ae3070f14efaa3a4c9632fe2433e849a5e
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
cpp
#include"drawcommandexecuted3d10.h" #include"deviced3d10_0.h" #include"bufferd3d10.h" #include"texture2dd3d10.h" #include"rendertargetd3d10.h" #include"depthstencild3d10.h" #include"materiald3d10.h" #include"inputlayoutd3d10.h" #include"rasterizerstated3d10.h" #include"samplerstated3d10.h" #include"blendstated3d10.h" #include"vertexshaderd3d10.h" #include"pixelshaderd3d10.h" #include"debug.h" // ここは各種Drawを書く namespace Maid { namespace Graphics { void DrawCommandExecuteD3D10::Draw( size_t UseVertexCount, size_t StartVertex ) { GetDevice()->Draw( UseVertexCount, StartVertex ); } void DrawCommandExecuteD3D10::DrawIndexed( size_t UseIndexCount, size_t StartIndex, size_t OffsetVertex ) { GetDevice()->DrawIndexed( UseIndexCount, StartIndex, OffsetVertex ); } ID3D10Resource* DrawCommandExecuteD3D10::GetResource( const SPRESOURCE& pResource ) { ID3D10Resource* pRet = NULL; switch( pResource->GetType() ) { case IResource::TYPE_BUFFER: { BufferD3D10* pBuffer = static_cast<BufferD3D10*>( pResource.get() ); pRet = pBuffer->pBuffer.get(); }break; case IResource::TYPE_TEXTURE2D: { Texture2DD3D10* pBuffer = static_cast<Texture2DD3D10*>( pResource.get() ); pRet = pBuffer->pTexture.get(); }break; } return pRet; } void DrawCommandExecuteD3D10::CopyResource( const SPRESOURCE& pDstResource, const SPRESOURCE& pSrcResource ) { ID3D10Resource* pDst = GetResource(pDstResource); ID3D10Resource* pSrc = GetResource(pSrcResource); GetDevice()->CopyResource( pDst, pSrc ); } void DrawCommandExecuteD3D10::GenerateMips( const SPMATERIAL& pMaterial ) { ID3D10ShaderResourceView* pView = static_cast<MaterialD3D10*>(pMaterial.get())->pView.get(); GetDevice()->GenerateMips( pView ); } }}
[ "[email protected]", "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 63 ], [ 71, 72 ] ], [ [ 64, 70 ] ] ]
0c582d47f67a60719c25f3275ae36f4869de7178
a9afa168fac234c3b838dd29af4a5966a6acb328
/CppUTest/tests/TestHarness_cTest.cpp
bb1187355cb059c67964f6fffa44509f088ad24d
[]
no_license
unclebob/tddrefcpp
38a4170c38f612c180a8b9e5bdb2ec9f8971832e
9124a6fad27349911658606392ba5730ff0d1e15
refs/heads/master
2021-01-25T07:34:57.626817
2010-05-10T20:01:39
2010-05-10T20:01:39
659,579
8
5
null
null
null
null
UTF-8
C++
false
false
4,989
cpp
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ extern "C" { #define _WCHART #include "CppUTest/TestHarness_c.h" } #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" TEST_GROUP(TestHarness_c) { TestTestingFixture* fixture; TEST_SETUP() { fixture = new TestTestingFixture(); } TEST_TEARDOWN() { delete fixture; } }; void _failIntMethod() { CHECK_EQUAL_C_INT(1, 2); } TEST(TestHarness_c, checkInt) { CHECK_EQUAL_C_INT(2, 2); fixture->setTestFunction(_failIntMethod); fixture->runAllTests(); fixture->assertPrintContains("expected <1>\n but was <2>"); fixture->assertPrintContains("arness_c"); } void _failRealMethod() { CHECK_EQUAL_C_REAL(1.0, 2.0, 0.5); } TEST(TestHarness_c, checkReal) { CHECK_EQUAL_C_REAL(1.0, 1.1, 0.5); fixture->setTestFunction(_failRealMethod); fixture->runAllTests(); fixture->assertPrintContains("expected <1.000000>\n but was <2.000000>"); fixture->assertPrintContains("arness_c"); } void _failCharMethod() { CHECK_EQUAL_C_CHAR('a', 'c'); } TEST(TestHarness_c, checkChar) { CHECK_EQUAL_C_CHAR('a', 'a'); fixture->setTestFunction(_failCharMethod); fixture->runAllTests(); fixture->assertPrintContains("expected <a>\n but was <c>"); fixture->assertPrintContains("arness_c"); } void _failStringMethod() { CHECK_EQUAL_C_STRING("Hello", "World"); } TEST(TestHarness_c, checkString) { CHECK_EQUAL_C_STRING("Hello", "Hello"); fixture->setTestFunction(_failStringMethod); fixture->runAllTests(); fixture->assertPrintContains("expected <Hello>\n but was <World>"); fixture->assertPrintContains("arness_c"); } void _failTextMethod() { FAIL_TEXT_C("Booo"); } TEST(TestHarness_c, checkFailText) { fixture->setTestFunction(_failTextMethod); fixture->runAllTests(); fixture->assertPrintContains("Booo"); fixture->assertPrintContains("arness_c"); } void _failMethod() { FAIL_C(); } TEST(TestHarness_c, checkFail) { fixture->setTestFunction(_failMethod); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); fixture->assertPrintContains("arness_c"); } void _CheckMethod() { CHECK_C(false); } TEST(TestHarness_c, checkCheck) { CHECK_C(true); fixture->setTestFunction(_CheckMethod); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); } TEST(TestHarness_c, cpputest_malloc_out_of_memory) { cpputest_malloc_set_out_of_memory(); CHECK(0 == cpputest_malloc(100)); cpputest_malloc_set_not_out_of_memory(); void * mem = cpputest_malloc(100); CHECK(0 != mem); cpputest_free(mem); } TEST(TestHarness_c, cpputest_calloc) { void * mem = cpputest_calloc(10, 10); CHECK(0 != mem); cpputest_free(mem); } TEST(TestHarness_c, cpputest_realloc_larger) { const char* number_string = "123456789"; char* mem1 = (char*) cpputest_malloc(10); PlatformSpecificStrCpy(mem1, number_string); CHECK(mem1 != 0); char* mem2 = (char*) cpputest_realloc(mem1, 1000); CHECK(mem2 != 0); STRCMP_EQUAL(number_string, mem2) cpputest_free(mem2); } TEST(TestHarness_c, macros) { void* mem1 = malloc(10); void* mem2 = calloc(10, 20); void* mem3 = realloc(mem2, 100); free(mem1); free(mem3); }
[ [ [ 1, 190 ] ] ]
5c8c97ab692ad60ba421f39e97310aac9b5d797b
2ddfcde074b05e9a154c2ddecf172c2633902ee9
/CMPSC458Raytracer/triangle.cpp
256748f97fb8f742d7ca1ef62f348168d37362e8
[]
no_license
dtbinh/OpenGL-RayTracer
ad044b4c05738679dba6204f81a9fe10a7cc5b3f
bb504f61488698b9449409e17e23a4ccd03ebf4d
refs/heads/master
2020-04-05T19:00:17.399706
2011-12-23T03:17:53
2011-12-23T03:17:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
#include "triangle.h" //constructor given center, radius, and material triangle::triangle(Vec3f p0, Vec3f p1, Vec3f p2, float tx0, float tx1, float tx2, float ty0, float ty1, float ty2, int m, scene* s) : rtObject(s) { point0 = p0; point1 = p1; point2 = p2; texX0 = tx0; texX1 = tx1; texX2 = tx2; texY0 = ty0; texY1 = ty1; texY2 = ty2; matIndex = m; myScene = s; } float triangle::testIntersection(Vec3f eye, Vec3f dir) { //see the book/slides for a description of how to use Cramer's rule to solve //for the intersection(s) of a line and a plane, implement it here and //return the minimum distance (if barycentric coordinates indicate it hit //the triangle) otherwise 9999999 return 9999999; } Vec3f triangle::getNormal(Vec3f eye, Vec3f dir) { //construct the barycentric coordinates for the plane Vec3f bary1 = point1-point0; Vec3f bary2 = point2-point0; //cross them to get the normal to the plane //note that the normal points in the direction given by right-hand rule //(this can be important for refraction to know whether you are entering or leaving a material) Vec3f normal; Vec3f::Cross3(normal,bary1,bary2); normal.Normalize(); return normal; } Vec3f triangle::getTextureCoords(Vec3f eye, Vec3f dir) { //find alpha and beta (parametric distance along barycentric coordinates) //use these in combination with the known texture surface location of the vertices //to find the texture surface location of the point you are seeing Vec3f coords; return coords; }
[ [ [ 1, 53 ] ] ]
f0d2c81a26620bd3b9bf632678060196394744b8
45901972d53b88c968dc09e88d8241bf18fcba7a
/tools/rospack/include/rospack/rospack.h
621832d13494e2a173c8ef9cd5e406ade40412df
[]
no_license
lubosz/rosstacks
d5a99b7794b265cb981a6873074dabdbf4de5ff8
67ca37234eaba02ca05d1d0136d7023711d16e34
refs/heads/master
2021-01-19T12:58:32.411499
2011-11-07T20:43:00
2011-11-07T20:43:00
2,735,039
0
0
null
null
null
null
UTF-8
C++
false
false
12,761
h
/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * 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 names of Stanford University or Willow Garage, 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 ROSPACK_ROSPACK_H #define ROSPACK_ROSPACK_H /* Author: Morgan Quigley, Brian Gerkey */ /** \mainpage \htmlinclude manifest.html \section overview Overview \b %rospack is the ROS package management tool. The %rospack package contains a single binary, called \b %rospack. - Jump to \ref Usage "command-line usage". %rospack is part dpkg, part pkg-config. The main function of %rospack is to crawl through the packages in ROS_ROOT and ROS_PACKAGE_PATH, read and parse the \b manifest.xml for each package, and assemble a complete dependency tree for all packages. Using this tree, %rospack can answer a number of queries about packages and their dependencies. Common queries include: - find : return the absolute path to a package - depends : return a list of all of a package's dependencies - depends-on : return a list of packages that depend on the given package - export : return flags necessary for building and linking against a package %rospack is intended to be cross-platform. \subsection crawling Crawling algorithm %rospack crawls in the following order: the directory ROS_ROOT, followed by the colon-separated list of directories ROS_PACKAGE_PATH, in the order they are listed. During the crawl, %rospack examines the contents of each directory, looking for a file called @b manifest.xml. If such a file is found, the directory containing it is considered to be a ROS package, with the package name equal to the directory name. The crawl does not descend further once a manifest is found (i.e., packages cannot be nested inside one another). If a manifest.xml file is not found in a given directory, each subdirectory is searched. This subdirectory search is prevented if a file called @b rospack_nosubdirs is found. The directory itself is still searched for a manifest, but its subdirectories are not crawled. If multiple packages by the same name exist within the search path, the first one found wins. It is strongly recommended that you keep packages by the same name in separate trees, each having its own element within ROS_PACKAGE_PATH. That way, you can deterministically control the search order by the way that you specify ROS_PACKAGE_PATH. The search order within a given element of ROS_PACKAGE_PATH can be unpredictably affected by the details of how files are laid out on disk. \subsection efficiency Efficiency considerations %rospack re-parses the manifest.xml files and rebuilds the dependency tree on each execution. However, it maintains a cache of package directories in ROS_ROOT/.rospack_cache. This cache is updated whenever there is a cache miss, or when the cache is 60 seconds old. You can change this timeout by setting the environment variable ROS_CACHE_TIMEOUT, in seconds. Set it to 0.0 to force a cache rebuild on every invocation of %rospack. %rospack's performance can be adversely affected by the presence of very broad and/or deep directory structures that don't contain manifest files. If such directories are in %rospack's search path, it can spend a lot of time crawling them only to discover that there are no packages to be found. You can prevent this latency by creating a @b rospack_nosubdirs file in such directories. If rospack seems to be running annoyingly slowly, you can use the profile command, which will print out the 20 slowest trees to crawl (or use profile --length=N to print the slowest N trees). \subsection dependencies No dependencies Because %rospack is the tool that determines dependencies, it cannot depend on anything else. Thus %rospack contains a copy of the TinyXML library, instead of using the copy available in 3rdparty. For the same reason, unit tests for %rospack, which require gtest, are in a separate package, called rospack_test. \section codeapi Code API %rospack is used entirely as a command-line tool. While the main functionality within %rospack is built as a library for testing purposes, it is not intended for use in writing other applications. Should this change, the %rospack library API should be cleaned up and better documented. For now, the user-visible API is: - rospack::ROSPack::ROSPack() - rospack::ROSPack::run() See main.cpp for example usage \section rosapi ROS API %rospack does not expose a ROS API. \section commandline Command-line tools \subsection rospack rospack %rospack is the command-line tool that provides package management services. %rospack crawls the directory ROS_ROOT and the colon-separated directories in ROS_PACKAGE_PATH, determining a directory to be package if it contains a file called @b manifest.xml. */ #if defined(WIN32) #if defined(ROS_STATIC) #define ROSPACK_EXPORT #elif defined(rospack_EXPORTS) #define ROSPACK_EXPORT __declspec(dllexport) #else #define ROSPACK_EXPORT __declspec(dllimport) #endif #else #define ROSPACK_EXPORT #endif #include <string> #include <vector> #include <list> #include "tinyxml-2.5.3/tinyxml.h" namespace rospack { class Package; // global helper functions void string_split(const std::string &s, std::vector<std::string> &t, const std::string &d); bool file_exists(const std::string &fname); extern const char *fs_delim; Package *g_get_pkg(const std::string &name); typedef std::vector<Package *> VecPkg; typedef std::list<Package*> Acc; typedef std::list<Acc> AccList; /** * The Package class contains information about a single package */ class ROSPACK_EXPORT Package { public: enum traversal_order_t { POSTORDER, PREORDER }; std::string name, path; // These will cause warnings on Windows when compiling the DLL because they // are static. They should more correctly be accessed via accessor functions // that are exported from the class, rather than directly, in order to // "prevent data corruption." Since main.cpp is currently the only known // client and it doesn't use them, I'm not caring about the warnings yet. static std::vector<Package *> pkgs; static std::vector<Package *> deleted_pkgs; Package(std::string _path); static bool is_package(std::string path); static bool is_no_subdirs(std::string path); const VecPkg &deps1(); const VecPkg &deps(traversal_order_t order, int depth=0); std::string manifest_path(); std::string flags(std::string lang, std::string attrib); std::string rosdep(); std::string versioncontrol(); std::vector<std::pair<std::string, std::string> > plugins(); VecPkg descendants1(); const std::vector<Package *> &descendants(int depth=0); rospack_tinyxml::TiXmlElement *manifest_root(); void accumulate_deps(AccList& acc_list, Package* to); /** * \brief Returns the message flags for this package. If the path/msg or path/srv directories exist, * adds appropriate compile/link flags depending on what is requested * \param cflags Whether or not to include compile flags * \param lflags Whether or not to include link flags */ std::string cpp_message_flags(bool cflags, bool lflags); private: bool deps_calculated, direct_deps_calculated, descendants_calculated; std::vector<Package *> _deps, _direct_deps, _descendants; rospack_tinyxml::TiXmlDocument manifest; bool manifest_loaded; Package(const Package &p) { } // just override the default public one bool has_parent(std::string pkg); const std::vector<Package *> &direct_deps(bool missing_pkg_as_warning=false); std::string direct_flags(std::string lang, std::string attrib); void load_manifest(); }; /** * The ROSPack class contains information the entire package dependency * tree. */ class ROSPACK_EXPORT ROSPack { public: static const char* usage(); char *ros_root; ROSPack(); ~ROSPack(); Package *get_pkg(std::string pkgname); int cmd_depends_on(bool include_indirect); int cmd_depends_why(); int cmd_find(); int cmd_deps(); int cmd_depsindent(Package* pkg, int indent); int cmd_deps_manifests(); int cmd_deps_msgsrv(); int cmd_deps1(); /* int cmd_predeps(char **args, int args_len); */ std::string snarf_libs(std::string flags, bool invert=false); std::string snarf_flags(std::string flags, std::string token, bool invert=false); int cmd_libs_only(std::string token); int cmd_cflags_only(std::string token); int cmd_make(char **args, int args_len); void export_flags(std::string pkg, std::string lang, std::string attrib); int cmd_versioncontrol(int depth); int cmd_rosdep(int depth); int cmd_export(); int cmd_plugins(); /** @brief The method that does the work. * * Call the run() method with argc and argv to crawl for packages, build * the tree, and answer the query in the command-line arguments. * * @throws std::runtime_error */ int run(int argc, char **argv); // Another form of run, which takes the arguments as a single string. // WARNING: this method does naive string-splitting on spaces. int run(const std::string& cmd); // Get the accumulated output std::string getOutput() { return output_acc; } // is -q (quiet) provided ? bool is_quiet() { return opt_quiet; } int cmd_print_package_list(bool print_path); int cmd_list_duplicates(); int cmd_print_langs_list(); void crawl_for_packages(bool force_crawl = false); VecPkg partial_crawl(const std::string &path); // Exposed for testing purposes only std::string deduplicate_tokens(const std::string& s); // Storage for --foo options // --deps-only bool opt_deps_only; // --lang= std::string opt_lang; // --attrib= std::string opt_attrib; // --length= std::string opt_length; // --top= std::string opt_top; // The package name std::string opt_package; // --target= std::string opt_target; // the number of entries to list in the profile table int opt_profile_length; // only display zombie directories in profile? bool opt_profile_zombie_only; // display warnings about missing dependencies? bool opt_warn_on_missing_deps; // display pairs of duplicate packages? bool opt_display_duplicate_pkgs; private: // is quiet bool opt_quiet; bool cache_lock_failed; bool crawled; std::string getCachePath(); // Storage for list of path components, used in add_package. We keep it // here to avoid reallocation in every run of add_package. std::vector<std::string> path_components; // Add package, filtering out duplicates. Package* add_package(std::string path); /** tests if the cache exists, is new enough, and is valid */ bool cache_is_good(); /** returns a double representing the seconds since the Epoch */ static double time_since_epoch(); /** remove trailing slashes */ void sanitize_rppvec(std::vector<std::string> &rppvec); // Output accumulates here std::string output_acc; // A place to store heap-allocated argv, in case we were passed a // std::string in run(). It'll be freed on destruction. int my_argc; char** my_argv; void freeArgv(); // Total number of packages found, including duplicates. Used in // determining whether a directory is a zombie. int total_num_pkgs; // Were there any duplicate pkgs found in the crawl? bool duplicate_packages_found; }; } #endif
[ "kwc@61973afe-1cd6-434e-a0a9-934cb0052259", "gerkey@61973afe-1cd6-434e-a0a9-934cb0052259", "jfaust@61973afe-1cd6-434e-a0a9-934cb0052259", "mquigley@61973afe-1cd6-434e-a0a9-934cb0052259" ]
[ [ [ 1, 134 ], [ 147, 148 ], [ 150, 163 ], [ 166, 169 ], [ 171, 174 ], [ 180, 194 ], [ 206, 209 ], [ 211, 224 ], [ 226, 239 ], [ 242, 248 ], [ 250, 283 ], [ 291, 291 ], [ 295, 296 ], [ 299, 302 ], [ 331, 331 ], [ 334, 336 ], [ 343, 345 ], [ 360, 364 ] ], [ [ 135, 146 ], [ 149, 149 ], [ 164, 165 ], [ 170, 170 ], [ 175, 179 ], [ 195, 197 ], [ 210, 210 ], [ 225, 225 ], [ 240, 241 ], [ 284, 290 ], [ 292, 294 ], [ 297, 298 ], [ 303, 330 ], [ 332, 333 ], [ 337, 342 ], [ 348, 359 ] ], [ [ 198, 205 ], [ 249, 249 ] ], [ [ 346, 347 ] ] ]
cc455ac18edc821817d78b4222c338c02b83bdfe
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/03.Code/UI/SmsPassConfirmWnd.h
cb73d5cc03ea2787354cc7be9884b871c55a0929
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
UTF-8
C++
false
false
766
h
#ifndef __SMSPASSCONFIRMWND_h__ #define __SMSPASSCONFIRMWND_h__ #include "UiEditControl.h" #include "NewSmsWnd.h" #include "EasySmsUiCtrl.h" #include "EasySmsWndBase.h" class CSmsPassConfirmWnd : public CEasySmsWndBase { MZ_DECLARE_DYNAMIC( CSmsPassConfirmWnd ); public: CSmsPassConfirmWnd(void); virtual ~CSmsPassConfirmWnd(void); public: virtual BOOL OnInitDialog(); virtual void OnMzCommand( WPARAM wParam, LPARAM lParam ); BOOL SubInitialize(); wchar_t* GetPassWord(); private: protected: private: UiSingleLineEdit m_PassInput; UiPicture m_Picture; CEasySmsUiCtrl m_clCEasySmsUiCtrl; int m_modeIndex; wchar_t *m_pwPassWord; }; #endif
[ [ [ 1, 47 ] ] ]
ed01ae8c6eca402b6755ff2e802cacf6ea90bacd
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/envvar_table.h
0478f4616f7c76ccfe0b940666f9d61284b04be5
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,512
h
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version May 5 2007) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #ifndef __envvar_table__ #define __envvar_table__ #include <wx/wx.h> #include <wx/listctrl.h> #include <wx/statline.h> #include <wx/button.h> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Class EnvVarsTableDlg /////////////////////////////////////////////////////////////////////////////// class EnvVarsTableDlg : public wxDialog { private: void InitVars(); void ConnectEvents(); protected: void OnNewVar(wxCommandEvent &event); void OnEditVar(wxCommandEvent &event); void OnDeleteVar(wxCommandEvent &event); void OnItemSelected(wxListEvent &event); void OnItemActivated(wxListEvent &event); protected: wxListCtrl* m_listVarsTable; wxStaticLine* m_staticline4; wxButton* m_buttonDelete; wxButton* m_buttonCancel; wxButton* m_buttonNew; wxString m_selectedVarName; wxString m_selectedVarValue; public: EnvVarsTableDlg( wxWindow* parent, int id = wxID_ANY, wxString title = wxT("Environment Variables"), wxPoint pos = wxDefaultPosition, wxSize size = wxSize( 552,330 ), int style = wxDEFAULT_DIALOG_STYLE ); }; #endif //__envvar_table__
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 50 ] ] ]
abd6e6173067565f526c134fd25e554a44cee692
567dddbf32b225a4b9e9c74a87ebcaf93731abc4
/Compo_Caracoles/KeyConfig_Menu.h
a4ced7e17ec526b7b6747e33e2eb3b50ffe05111
[]
no_license
miguelSantirso/AlertaCaracol2
be1ce518602386e59a72139fe19154000a022266
b25dc09d103a974d10e624483867eb03629369d7
refs/heads/master
2020-03-30T19:18:18.405213
2007-10-20T15:32:29
2007-10-20T15:32:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
787
h
#pragma once #include <string> #include <vector> struct BITMAP; class KeyBox_Menu; class Menu; class KeyConfig_Menu { public: /* struct Key_Struct { std::string Nombre; std::string Label; int Id_Tecla; };*/ struct Key_Struct { char Nombre[50]; char Label[200]; int Id_Tecla; }; KeyConfig_Menu(int _x, int _y, int _Ancho, int _Alto, Menu *_Puntero_Menu); ~KeyConfig_Menu(void); void Dibujar(BITMAP *bmp); void Actualizar(); bool Validar_Tecla(std::string Clave, int Nuevo_Valor); protected: void Lee_Configuracion(); void Escribe_Configuracion(); int x, y; int Ancho, Alto; Menu *Puntero_Menu; std::vector<Key_Struct> Config_Teclas; KeyBox_Menu * KeyBoxes; // Array de keyboxes int Numero_KeyBoxes; };
[ "TiRSO!@df780914-b739-dc11-ac19-00188b745eb1" ]
[ [ [ 1, 46 ] ] ]
8e4276e259b6eafb576202a02d8baa8f2e4029d1
022d2957a29fe5054263a406bbdd85289cf17ee0
/GontrolPC/ConfigMgr/stdafx.h
249805598acb64d77fb7b76b38f24c321ada8478
[]
no_license
amanuelg3/remote-control-with-android
aa6705da5c76311515ef6c4c972b7e64745be76d
5e51aff7d1727608c615a0027c746592ebc4ba92
refs/heads/master
2016-09-03T01:07:29.047261
2011-06-11T16:25:32
2011-06-11T16:25:32
35,783,127
1
0
null
null
null
null
UTF-8
C++
false
false
723
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 #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #include <errno.h> #include <direct.h> #include <string> #include <map> #ifdef _DEBUG #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__) #else #define DEBUG_CLIENTBLOCK #endif #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #ifdef _DEBUG #define new DEBUG_CLIENTBLOCK #endif // TODO: reference additional headers your program requires here
[ "wzmvictor@5d9a875e-b1a7-14b0-4603-314cddc6b85c" ]
[ [ [ 1, 30 ] ] ]
6df3b2513fa857fbb062ee7a498166908bffcd25
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/051101b/dingus/dingus/visibility/VisibilityLeaf.cpp
6ed7c0e5565aed8197a4f6a4f5d73f467b67e730
[]
no_license
BackupTheBerlios/dingus-svn
331d7546a6e7a5a3cb38ffb106e57b224efbf5df
1223efcf4c2079f58860d7fa685fa5ded8f24f32
refs/heads/master
2016-09-05T22:15:57.658243
2006-09-02T10:10:47
2006-09-02T10:10:47
40,673,143
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "VisibilityLeaf.h" using namespace dingus; DEFINE_POOLED_ALLOC(dingus::CVisibilityLeaf,256,false); DEFINE_POOLED_ALLOC(dingus::CAABBVisibilityLeaf,256,false); // -------------------------------------------------------------------------- bool CAABBVisibilityLeaf::testVisible( const SMatrix4x4& viewProj ) const { assert( mWorldMatrix ); bool outside = mAABB.frustumCull( *mWorldMatrix, viewProj ); return !outside; }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 21 ] ] ]
2f9c3069fefdb739375d74abd7cc4f83d864930b
cdd119cd2a3c24982bf5f75197e5da1258924478
/mq/src/queue.cpp
205536d194396af7140c7ee01f923310c0b3ba49
[]
no_license
xuxiandi/DOMQ
12bbbd477ce75152c1b5acb8731ddb1833067c62
3a28ebed6323292a1e264b80d969cd94324538b8
refs/heads/master
2020-12-31T02:33:22.791616
2011-05-17T06:01:01
2011-05-17T06:01:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,114
cpp
#include "queue.h" #include "msg/msgqueuemsg.h" #include <string> #include <sstream> std::string Queue::ToString() const { std::stringstream st; st << "queuename:[" << option.msgQueueName <<"]," << "msgType:[" << option.msgType << "]," << "duration:[" << option.duration << "]," << "redisAddr:[" << redisAddr.ToString() << "]," << "lastVisit:[" << lastVisit << "]" << "maxCount:[" << option.maxCount << "]" << "msgCount:[" << msgCount << "]"; if (option.msgType == SUB2PUB) { st << "client:["; for (std::vector<SubQueue>::const_iterator it = clients.begin(); it != clients.end(); ++it) { st << "(" << it->client << ',' << it->lastVisit << ',' << it->msgCount << ")"; } st <<"]"; } return st.str(); } std::string QueueClient::ToString() const { std::stringstream st; st << "msgQueueCode:[" << msgQueueCode << "]," << "clientName:[" << clientName << "]," << "queueName:[" << queueName << "]"; return st.str(); }
[ [ [ 1, 36 ] ] ]
ae499890769dd7ca24679fd0f4831f4268357ade
5819b1347738ccba8330a63b993cc9de5b155cf3
/lasvm-source/la_svm.cpp
0c310715c86f379fdeb1f430767f47e65794b01f
[]
no_license
claytontey/libmachinelearning
7cf667725507251c1773085a89f1f2413765e123
613771bcf736d82cceba93d2e8204ccd3f703a1b
refs/heads/master
2021-01-10T19:22:16.031001
2010-11-12T11:12:25
2010-11-12T11:12:25
39,838,615
1
0
null
null
null
null
UTF-8
C++
false
false
25,571
cpp
// -*- Mode: c++; c-file-style: "stroustrup"; -*- using namespace std; #include <stdio.h> #include <vector> #include <cmath> #include <ctime> #include <cstring> #include <iostream> #include <fstream> #include <algorithm> #include "OPF.h" #include "vector.h" #include "lasvm.h" #define LINEAR 0 #define POLY 1 #define RBF 2 #define SIGMOID 3 #define ONLINE 0 #define ONLINE_WITH_FINISHING 1 #define RANDOM 0 #define GRADIENT 1 #define MARGIN 2 #define ITERATIONS 0 #define SVS 1 #define TIME 2 const char *kernel_type_table[] = {"linear","polynomial","rbf","sigmoid"}; class stopwatch { public: stopwatch() : start(std::clock()){} //start counting time ~stopwatch(); double get_time() { clock_t total = clock()-start;; return double(total)/CLOCKS_PER_SEC; }; private: std::clock_t start; }; stopwatch::~stopwatch() { clock_t total = clock()-start; //get elapsed time cout<<"Time(secs): "<<double(total)/CLOCKS_PER_SEC<<endl; } class ID // class to hold split file indices and labels { public: int x; int y; ID() : x(0), y(0) {} ID(int x1,int y1) : x(x1), y(y1) {} }; // IDs will be sorted by index, not by label. bool operator<(const ID& x, const ID& y) { return x.x < y.x; } /* Data and model */ int m=0; // training set size vector <lasvm_sparsevector_t*> X; // feature vectors vector <int> Y; // labels vector <double> kparam; // kernel parameters vector <double> alpha; // alpha_i, SV weights double b0; // threshold /* Hyperparameters */ int kernel_type=RBF; // LINEAR, POLY, RBF or SIGMOID kernels double degree=3,kgamma=-1,coef0=0;// kernel params int use_b0=1; // use threshold via constraint \sum a_i y_i =0 int selection_type=RANDOM; // RANDOM, GRADIENT or MARGIN selection strategies int optimizer=ONLINE_WITH_FINISHING; // strategy of optimization double C=1; // C, penalty on errors double C_neg=1; // C-Weighting for negative examples double C_pos=1; // C-Weighting for positive examples int epochs=1; // epochs of online learning int candidates=50; // number of candidates for "active" selection process double deltamax=1000; // tolerance for performing reprocess step, 1000=1 reprocess only vector <double> select_size; // Max number of SVs to take with selection strategy (for early stopping) vector <double> x_square; // norms of input vectors, used for RBF /* Programm behaviour*/ int verbosity=1; // verbosity level, 0=off int saves=1; char report_file_name[1024]; // filename for the training report char split_file_name[1024]="\0"; // filename for the splits int cache_size=256; // 256Mb cache size as default double epsgr=1e-3; // tolerance on gradients long long kcalcs=0; // number of kernel evaluations int binary_files=0; vector <ID> splits; int max_index=0; vector <int> iold, inew; // sets of old (already seen) points + new (unseen) points int termination_type=0; void exit_with_help() { fprintf(stdout, "Usage: la_svm [options] training_set_file [model_file]\n" "options:\n" "-B file format : files are stored in the following format:\n" " 0 -- libsvm ascii format (default)\n" " 1 -- binary format\n" " 2 -- split file format\n" "-o optimizer: set the type of optimization (default 1)\n" " 0 -- online \n" " 1 -- online with finishing step \n" "-t kernel_type : set type of kernel function (default 2)\n" " 0 -- linear: u'*v\n" " 1 -- polynomial: (gamma*u'*v + coef0)^degree\n" " 2 -- radial basis function: exp(-gamma*|u-v|^2)\n" " 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n" "-s selection: set the type of selection strategy (default 0)\n" " 0 -- random \n" " 1 -- gradient-based \n" " 2 -- margin-based \n" "-T termination: set the type of early stopping strategy (default 0)\n" " 0 -- number of iterations \n" " 1 -- number of SVs \n" " 2 -- time-based \n" "-l sample: number of iterations/SVs/seconds to sample for early stopping (default all)\n" " if a list of numbers is given a model file is saved for each element of the set\n" "-C candidates : set number of candidates to search for selection strategy (default 50)\n" "-d degree : set degree in kernel function (default 3)\n" "-g gamma : set gamma in kernel function (default 1/k)\n" "-r coef0 : set coef0 in kernel function (default 0)\n" "-c cost : set the parameter C of C-SVC\n" "-m cachesize : set cache memory size in MB (default 256)\n" "-wi weight: set the parameter C of class i to weight*C (default 1)\n" "-b bias: use a bias or not i.e. no constraint sum alpha_i y_i =0 (default 1=on)\n" "-e epsilon : set tolerance of termination criterion (default 0.001)\n" "-p epochs : number of epochs to train in online setting (default 1)\n" "-D deltamax : set tolerance for reprocess step, 1000=1 call to reprocess >1000=no calls to reprocess (default 1000)\n" ); exit(1); } void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name) { int i; int clss; double weight; // parse options for(i=1;i<argc;i++) { if(argv[i][0] != '-') break; ++i; switch(argv[i-1][1]) { case 'o': optimizer = atoi(argv[i]); break; case 't': kernel_type = atoi(argv[i]); break; case 's': selection_type = atoi(argv[i]); break; case 'l': while(1) { select_size.push_back(atof(argv[i])); ++i; if((argv[i][0]<'0') || (argv[i][0]>'9')) break; } i--; break; case 'd': degree = atof(argv[i]); break; case 'g': kgamma = atof(argv[i]); break; case 'r': coef0 = atof(argv[i]); break; case 'm': cache_size = (int) atof(argv[i]); break; case 'c': C = atof(argv[i]); break; case 'w': clss= atoi(&argv[i-1][2]); weight = atof(argv[i]); if (clss>=1) C_pos=weight; else C_neg=weight; break; case 'b': use_b0=atoi(argv[i]); break; case 'B': binary_files=atoi(argv[i]); break; case 'e': epsgr = atof(argv[i]); break; case 'p': epochs = atoi(argv[i]); break; case 'D': deltamax = atoi(argv[i]); break; case 'C': candidates = atoi(argv[i]); break; case 'T': termination_type = atoi(argv[i]); break; default: fprintf(stderr,"unknown option\n"); exit_with_help(); } } saves=select_size.size(); if(saves==0) select_size.push_back(100000000); // determine filenames if(i>=argc) exit_with_help(); strcpy(input_file_name, argv[i]); if(i<argc-1) strcpy(model_file_name,argv[i+1]); else { char *p = strrchr(argv[i],'/'); if(p==NULL) p = argv[i]; else ++p; sprintf(model_file_name,"%s.model",p); } } int split_file_load(char *f) { int binary_file=0,labs=0,inds=0; FILE *fp; fp=fopen(f,"r"); if(fp==NULL) {printf("[couldn't load split file: %s]\n",f); exit(1);} char dummy[100],dummy2[100]; unsigned int i,j=0; for(i=0;i<strlen(f);i++) if(f[i]=='/') j=i+1; fscanf(fp,"%s %s",dummy,dummy2); strcpy(&(f[j]),dummy2); fscanf(fp,"%s %d",dummy,&binary_file); fscanf(fp,"%s %d",dummy,&inds); fscanf(fp,"%s %d",dummy,&labs); printf("[split file: load:%s binary:%d new_indices:%d new_labels:%d]\n",dummy2,binary_file,inds,labs); //printf("[split file:%s binary=%d]\n",dummy2,binary_file); if(!inds) return binary_file; while(1) { int i,j; int c=fscanf(fp,"%d",&i); if(labs) c=fscanf(fp,"%d",&j); if(c==-1) break; if (labs) splits.push_back(ID(i-1,j)); else splits.push_back(ID(i-1,0)); } sort(splits.begin(),splits.end()); return binary_file; } int libsvm_load_data(char *filename) // loads the same format as LIBSVM { int index; double value; int elements, i; FILE *fp = fopen(filename,"r"); lasvm_sparsevector_t* v; if(fp == NULL) { fprintf(stderr,"Can't open input file \"%s\"\n",filename); exit(1); } else printf("loading \"%s\".. \n",filename); int splitpos=0; int msz = 0; elements = 0; while(1) { int c = fgetc(fp); switch(c) { case '\n': if(splits.size()>0) { if(splitpos<(int)splits.size() && splits[splitpos].x==msz) { v=lasvm_sparsevector_create(); X.push_back(v); splitpos++; } } else { v=lasvm_sparsevector_create(); X.push_back(v); } ++msz; //printf("%d\n",m); elements=0; break; case ':': ++elements; break; case EOF: goto out; default: ; } } out: rewind(fp); max_index = 0;splitpos=0; for(i=0;i<msz;i++) { int write=0; if(splits.size()>0) { if(splitpos<(int)splits.size() && splits[splitpos].x==i) { write=2;splitpos++; } } else write=1; int label; fscanf(fp,"%d",&label); // printf("%d %d\n",i,label); if(write) { if(splits.size()>0) { if(splits[splitpos-1].y!=0) Y.push_back(splits[splitpos-1].y); else Y.push_back(label); } else Y.push_back(label); } while(1) { int c; do { c = getc(fp); if(c=='\n') goto out2; } while(isspace(c)); ungetc(c,fp); fscanf(fp,"%d:%lf",&index,&value); if (write==1) lasvm_sparsevector_set(X[m+i],index,value); if (write==2) lasvm_sparsevector_set(X[splitpos-1],index,value); if (index>max_index) max_index=index; } out2: label=1; // dummy } fclose(fp); msz=X.size()-m; printf("examples: %d features: %d\n",msz,max_index); return msz; } int binary_load_data(char *filename) { int msz,i=0,j; lasvm_sparsevector_t* v; int nonsparse=0; ifstream f; f.open(filename,ios::in|ios::binary); // read number of examples and number of features int sz[2]; f.read((char*)sz,2*sizeof(int)); if (!f) { printf("File writing error in line %d.\n",i); exit(1);} msz=sz[0]; max_index=sz[1]; vector <float> val; vector <int> ind; val.resize(max_index); if(max_index>0) nonsparse=1; int splitpos=0; for(i=0;i<msz;i++) { int mwrite=0; if(splits.size()>0) { if(splitpos<(int)splits.size() && splits[splitpos].x==i) { mwrite=1;splitpos++; v=lasvm_sparsevector_create(); X.push_back(v); } } else { mwrite=1; v=lasvm_sparsevector_create(); X.push_back(v); } if(nonsparse) // non-sparse binary file { f.read((char*)sz,1*sizeof(int)); // get label if(mwrite) { if(splits.size()>0 && splits[splitpos-1].y!=0) Y.push_back(splits[splitpos-1].y); else Y.push_back(sz[0]); } f.read((char*)(&val[0]),max_index*sizeof(float)); if(mwrite) for(j=0;j<max_index;j++) // set features for each example lasvm_sparsevector_set(v,j,val[j]); } else // sparse binary file { f.read((char*)sz,2*sizeof(int)); // get label & sparsity of example i if(mwrite) { if(splits.size()>0 && splits[splitpos-1].y!=0) Y.push_back(splits[splitpos-1].y); else Y.push_back(sz[0]); } val.resize(sz[1]); ind.resize(sz[1]); f.read((char*)(&ind[0]),sz[1]*sizeof(int)); f.read((char*)(&val[0]),sz[1]*sizeof(float)); if(mwrite) for(j=0;j<sz[1];j++) // set features for each example { lasvm_sparsevector_set(v,ind[j],val[j]); //printf("%d=%g\n",ind[j],val[j]); if(ind[j]>max_index) max_index=ind[j]; } } } f.close(); msz=X.size()-m; printf("examples: %d features: %d\n",msz,max_index); return msz; } void load_data_file(char *filename) { int msz,i,ft; splits.resize(0); int bin=binary_files; if(bin==0) // if ascii, check if it isn't a split file.. { FILE *f=fopen(filename,"r"); if(f == NULL) { fprintf(stderr,"Can't open input file \"%s\"\n",filename); exit(1); } char c; fscanf(f,"%c",&c); if(c=='f') bin=2; // found split file! } switch(bin) // load diferent file formats { case 0: // libsvm format msz=libsvm_load_data(filename); break; case 1: msz=binary_load_data(filename); break; case 2: ft=split_file_load(filename); if(ft==0) {msz=libsvm_load_data(filename); break;} else {msz=binary_load_data(filename); break;} default: fprintf(stderr,"Illegal file type '-B %d'\n",bin); exit(1); } if(kernel_type==RBF) { x_square.resize(m+msz); for(i=0;i<msz;i++) x_square[i+m]=lasvm_sparsevector_dot_product(X[i+m],X[i+m]); } if(kgamma==-1) kgamma=1.0/ ((double) max_index); // same default as LIBSVM m+=msz; } int sv1,sv2; double max_alpha,alpha_tol; int count_svs() { int i; max_alpha=0; sv1=0;sv2=0; for(i=0;i<m;i++) // Count svs.. { if(alpha[i]>max_alpha) max_alpha=alpha[i]; if(-alpha[i]>max_alpha) max_alpha=-alpha[i]; } alpha_tol=max_alpha/1000.0; for(i=0;i<m;i++) { if(Y[i]>0) { if(alpha[i] >= alpha_tol) sv1++; } else { if(-alpha[i] >= alpha_tol) sv2++; } } return sv1+sv2; } int libsvm_save_model(const char *model_file_name) // saves the model in the same format as LIBSVM { FILE *fp = fopen(model_file_name,"w"); if(fp==NULL) return -1; count_svs(); // printf("nSV=%d\n",sv1+sv2); fprintf(fp,"svm_type c_svc\n"); fprintf(fp,"kernel_type %s\n", kernel_type_table[kernel_type]); if(kernel_type == POLY) fprintf(fp,"degree %g\n", degree); if(kernel_type == POLY || kernel_type == RBF || kernel_type == SIGMOID) fprintf(fp,"gamma %g\n", kgamma); if(kernel_type == POLY || kernel_type == SIGMOID) fprintf(fp,"coef0 %g\n", coef0); fprintf(fp, "nr_class %d\n",2); fprintf(fp, "total_sv %d\n",sv1+sv2); { fprintf(fp, "rho %g\n",b0); } fprintf(fp, "label 1 -1\n"); fprintf(fp, "nr_sv"); fprintf(fp," %d %d",sv1,sv2); fprintf(fp, "\n"); fprintf(fp, "SV\n"); for(int j=0;j<2;j++) for(int i=0;i<m;i++) { if (j==0 && Y[i]==-1) continue; if (j==1 && Y[i]==1) continue; if (alpha[i]*Y[i]< alpha_tol) continue; // not an SV fprintf(fp, "%.16g ",alpha[i]); lasvm_sparsevector_pair_t *p1 = X[i]->pairs; while (p1) { fprintf(fp,"%d:%.8g ",p1->index,p1->data); p1 = p1->next; } fprintf(fp, "\n"); } fclose(fp); return 0; } double kernel(int i, int j, void *kparam) { double dot; kcalcs++; dot=lasvm_sparsevector_dot_product(X[i],X[j]); // sparse, linear kernel switch(kernel_type) { case LINEAR: return dot; case POLY: return pow(kgamma*dot+coef0,degree); case RBF: return exp(-kgamma*(x_square[i]+x_square[j]-2*dot)); case SIGMOID: return tanh(kgamma*dot+coef0); } return 0; } void finish(lasvm_t *sv) { int i,l; if (optimizer==ONLINE_WITH_FINISHING) { fprintf(stdout,"..[finishing]"); int iter=0; do { iter += lasvm_finish(sv, epsgr); } while (lasvm_get_delta(sv)>epsgr); } l=(int) lasvm_get_l(sv); int *svind,svs; svind= new int[l]; svs=lasvm_get_sv(sv,svind); alpha.resize(m); for(i=0;i<m;i++) alpha[i]=0; double *svalpha; svalpha=new double[l]; lasvm_get_alpha(sv,svalpha); for(i=0;i<svs;i++) alpha[svind[i]]=svalpha[i]; b0=lasvm_get_b(sv); } void make_old(int val) // move index <val> from new set into old set { int i,ind=-1; for(i=0;i<(int)inew.size();i++) { if(inew[i]==val) {ind=i; break;} } if (ind>=0) { inew[ind]=inew[inew.size()-1]; inew.pop_back(); iold.push_back(val); } } int select(lasvm_t *sv) // selection strategy { int s=-1; int t,i,r,j; double tmp,best; int ind=-1; switch(selection_type) { case RANDOM: // pick a random candidate s=rand() % inew.size(); break; case GRADIENT: // pick best gradient from 50 candidates j=candidates; if((int)inew.size()<j) j=inew.size(); r=rand() % inew.size(); s=r; best=1e20; for(i=0;i<j;i++) { r=inew[s]; tmp=lasvm_predict(sv, r); tmp*=Y[r]; //printf("%d: example %d grad=%g\n",i,r,tmp); if(tmp<best) {best=tmp;ind=s;} s=rand() % inew.size(); } s=ind; break; case MARGIN: // pick closest to margin from 50 candidates j=candidates; if((int)inew.size()<j) j=inew.size(); r=rand() % inew.size(); s=r; best=1e20; for(i=0;i<j;i++) { r=inew[s]; tmp=lasvm_predict(sv, r); if (tmp<0) tmp=-tmp; //printf("%d: example %d grad=%g\n",i,r,tmp); if(tmp<best) {best=tmp;ind=s;} s=rand() % inew.size(); } s=ind; break; } t=inew[s]; inew[s]=inew[inew.size()-1]; inew.pop_back(); iold.push_back(t); //printf("(%d %d)\n",iold.size(),inew.size()); return t; } void train_online(char *model_file_name) { int t1,t2=0,i,s,l,j,k; double timer=0; stopwatch *sw; // start measuring time after loading is finished sw=new stopwatch; // save timing information char t[1000]; strcpy(t,model_file_name); strcat(t,".time"); lasvm_kcache_t *kcache=lasvm_kcache_create(kernel, NULL); lasvm_kcache_set_maximum_size(kcache, cache_size*1024*1024); lasvm_t *sv=lasvm_create(kcache,use_b0,C*C_pos,C*C_neg); printf("set cache size %d\n",cache_size); // everything is new when we start for(i=0;i<m;i++) inew.push_back(i); // first add 5 examples of each class, just to balance the initial set int c1=0,c2=0; for(i=0;i<m;i++) { if(Y[i]==1 && c1<5) {lasvm_process(sv,i,(double) Y[i]); c1++; make_old(i);} if(Y[i]==-1 && c2<5){lasvm_process(sv,i,(double) Y[i]); c2++; make_old(i);} if(c1==5 && c2==5) break; } for(j=0;j<epochs;j++) { for(i=0;i<m;i++) { if(inew.size()==0) break; // nothing more to select s=select(sv); // selection strategy, select new point t1=lasvm_process(sv,s,(double) Y[s]); if (deltamax<=1000) // potentially multiple calls to reprocess.. { //printf("%g %g\n",lasvm_get_delta(sv),deltamax); t2=lasvm_reprocess(sv,epsgr);// at least one call to reprocess while (lasvm_get_delta(sv)>deltamax && deltamax<1000) { t2=lasvm_reprocess(sv,epsgr); } } if (verbosity==2) { l=(int) lasvm_get_l(sv); printf("l=%d process=%d reprocess=%d\n",l,t1,t2); } else if(verbosity==1) if( (i%100)==0){ fprintf(stdout, "..%d",i); fflush(stdout); } l=(int) lasvm_get_l(sv); for(k=0;k<(int)select_size.size();k++) { if ( (termination_type==ITERATIONS && i==select_size[k]) || (termination_type==SVS && l>=select_size[k]) || (termination_type==TIME && sw->get_time()>=select_size[k]) ) { if(saves>1) // if there is more than one model to save, give a new name { // save current version before potential finishing step int save_l,*save_sv; double *save_g, *save_alpha; save_l=(int)lasvm_get_l(sv); save_alpha= new double[l];lasvm_get_alpha(sv,save_alpha); save_g= new double[l];lasvm_get_g(sv,save_g); save_sv= new int[l];lasvm_get_sv(sv,save_sv); finish(sv); char tmp[1000]; timer+=sw->get_time(); //f << i << " " << count_svs() << " " << kcalcs << " " << timer << endl; if(termination_type==TIME) { sprintf(tmp,"%s_%dsecs",model_file_name,i); fprintf(stdout,"..[saving model_%d secs]..",i); } else { fprintf(stdout,"..[saving model_%d pts]..",i); sprintf(tmp,"%s_%dpts",model_file_name,i); } libsvm_save_model(tmp); // get back old version //fprintf(stdout, "[restoring before finish]"); fflush(stdout); lasvm_init(sv, save_l, save_sv, save_alpha, save_g); delete save_alpha; delete save_sv; delete save_g; delete sw; sw=new stopwatch; // reset clock } select_size[k]=select_size[select_size.size()-1]; select_size.pop_back(); } } if(select_size.size()==0) break; // early stopping, all intermediate models saved } inew.resize(0);iold.resize(0); // start again for next epoch.. for(i=0;i<m;i++) inew.push_back(i); } if(saves<2) { finish(sv); // if haven't done any intermediate saves, do final save timer+=sw->get_time(); //f << m << " " << count_svs() << " " << kcalcs << " " << timer << endl; } if(verbosity>0) printf("\n"); l=count_svs(); printf("nSVs=%d\n",l); printf("||w||^2=%g\n",lasvm_get_w2(sv)); printf("kcalcs="); cout << kcalcs << endl; //f.close(); lasvm_destroy(sv); lasvm_kcache_destroy(kcache); } int main(int argc, char **argv) { printf("\n"); printf("la SVM\n"); printf("______\n"); char input_file_name[1024]; char model_file_name[1024]; char trainingtimefilename[256]; float trainingtime; timer tic, toc; FILE *f = NULL; size_t result; parse_command_line(argc, argv, input_file_name, model_file_name); load_data_file(input_file_name); gettimeofday(&tic,NULL); train_online(model_file_name); gettimeofday(&toc,NULL); trainingtime = ((toc.tv_sec-tic.tv_sec)*1000.0 + (toc.tv_usec-tic.tv_usec)*0.001)/1000.0; result = fprintf(stdout, "\nTraining time: %f seconds", trainingtime); fflush(stdout); libsvm_save_model(model_file_name); sprintf(trainingtimefilename,"%s.time",argv[1]); f = fopen(trainingtimefilename,"a"); result = fprintf(f,"%f\n",trainingtime); fclose(f); }
[ "papa.joaopaulo@ab71ce65-3dec-350d-c851-0c893010dbb2" ]
[ [ [ 1, 905 ] ] ]
e2a02db464b1f6c6883b10362bb7aa3db299111f
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/qwt/qwt_knob.cpp
7419b13fe9809481c1838ec3d43edc1f2791b867
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,467
cpp
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include <qpainter.h> #if QT_VERSION >= 0x040000 #include <qpaintengine.h> #endif #include <qpalette.h> #include <qstyle.h> #include <qevent.h> #include "qwt_round_scale_draw.h" #include "qwt_knob.h" #include "qwt_math.h" #include "qwt_painter.h" #include "qwt_paint_buffer.h" class QwtKnob::PrivateData { public: PrivateData() { angle = 0.0; nTurns = 0.0; borderWidth = 2; borderDist = 4; totalAngle = 270.0; scaleDist = 4; symbol = Line; maxScaleTicks = 11; knobWidth = 50; dotWidth = 8; } int borderWidth; int borderDist; int scaleDist; int maxScaleTicks; int knobWidth; int dotWidth; Symbol symbol; double angle; double totalAngle; double nTurns; QRect knobRect; // bounding rect of the knob without scale }; /*! \brief Constructor \param parent Parent widget */ QwtKnob::QwtKnob(QWidget* parent): QwtAbstractSlider(Qt::Horizontal, parent) { #if QT_VERSION < 0x040000 setWFlags(Qt::WNoAutoErase); #endif d_data = new PrivateData; setScaleDraw(new QwtRoundScaleDraw()); setUpdateTime(50); setTotalAngle( 270.0 ); recalcAngle(); setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); setRange(0.0, 10.0, 1.0); setValue(0.0); } //! Destructor QwtKnob::~QwtKnob() { delete d_data; } /*! \brief Set the symbol of the knob \sa QwtKnob::symbol() */ void QwtKnob::setSymbol(QwtKnob::Symbol s) { if ( d_data->symbol != s ) { d_data->symbol = s; update(); } } /*! \return symbol of the knob \sa QwtKnob::setSymbol() */ QwtKnob::Symbol QwtKnob::symbol() const { return d_data->symbol; } /*! \brief Set the total angle by which the knob can be turned \param angle Angle in degrees. The default angle is 270 degrees. It is possible to specify an angle of more than 360 degrees so that the knob can be turned several times around its axis. */ void QwtKnob::setTotalAngle (double angle) { if (angle < 10.0) d_data->totalAngle = 10.0; else d_data->totalAngle = angle; scaleDraw()->setAngleRange( -0.5 * d_data->totalAngle, 0.5 * d_data->totalAngle); layoutKnob(); } //! Return the total angle double QwtKnob::totalAngle() const { return d_data->totalAngle; } /*! Change the scale draw of the knob For changing the labels of the scales, it is necessary to derive from QwtRoundScaleDraw and overload QwtRoundScaleDraw::label(). \sa scaleDraw() */ void QwtKnob::setScaleDraw(QwtRoundScaleDraw *scaleDraw) { setAbstractScaleDraw(scaleDraw); } /*! \return the scale draw of the knob \sa setScaleDraw() */ const QwtRoundScaleDraw *QwtKnob::scaleDraw() const { return (QwtRoundScaleDraw *)abstractScaleDraw(); } /*! \return the scale draw of the knob \sa setScaleDraw() */ QwtRoundScaleDraw *QwtKnob::scaleDraw() { return (QwtRoundScaleDraw *)abstractScaleDraw(); } /*! \brief Draw the knob \param painter painter \param r Bounding rectangle of the knob (without scale) */ void QwtKnob::drawKnob(QPainter *painter, const QRect &r) { #if QT_VERSION < 0x040000 const QBrush buttonBrush = colorGroup().brush(QColorGroup::Button); const QColor buttonTextColor = colorGroup().buttonText(); const QColor lightColor = colorGroup().light(); const QColor darkColor = colorGroup().dark(); #else const QBrush buttonBrush = palette().brush(QPalette::Button); const QColor buttonTextColor = palette().color(QPalette::ButtonText); const QColor lightColor = palette().color(QPalette::Light); const QColor darkColor = palette().color(QPalette::Dark); #endif const int bw2 = d_data->borderWidth / 2; const int radius = (qwtMin(r.width(), r.height()) - bw2) / 2; const QRect aRect( r.center().x() - radius, r.center().y() - radius, 2 * radius, 2 * radius); // // draw button face // painter->setBrush(buttonBrush); painter->drawEllipse(aRect); // // draw button shades // QPen pn; pn.setWidth(d_data->borderWidth); pn.setColor(lightColor); painter->setPen(pn); painter->drawArc(aRect, 45*16, 180*16); pn.setColor(darkColor); painter->setPen(pn); painter->drawArc(aRect, 225*16, 180*16); // // draw marker // if ( isValid() ) drawMarker(painter, d_data->angle, buttonTextColor); } /*! \brief Notify change of value Sets the knob's value to the nearest multiple of the step size. */ void QwtKnob::valueChange() { recalcAngle(); update(); QwtAbstractSlider::valueChange(); } /*! \brief Determine the value corresponding to a specified position Called by QwtAbstractSlider \param p point */ double QwtKnob::getValue(const QPoint &p) { const double dx = double((rect().x() + rect().width() / 2) - p.x() ); const double dy = double((rect().y() + rect().height() / 2) - p.y() ); const double arc = atan2(-dx,dy) * 180.0 / M_PI; double newValue = 0.5 * (minValue() + maxValue()) + (arc + d_data->nTurns * 360.0) * (maxValue() - minValue()) / d_data->totalAngle; const double oneTurn = fabs(maxValue() - minValue()) * 360.0 / d_data->totalAngle; const double eqValue = value() + mouseOffset(); if (fabs(newValue - eqValue) > 0.5 * oneTurn) { if (newValue < eqValue) newValue += oneTurn; else newValue -= oneTurn; } return newValue; } /*! \brief Set the scrolling mode and direction Called by QwtAbstractSlider \param p Point in question */ void QwtKnob::getScrollMode(const QPoint &p, int &scrollMode, int &direction) { const int r = d_data->knobRect.width() / 2; const int dx = d_data->knobRect.x() + r - p.x(); const int dy = d_data->knobRect.y() + r - p.y(); if ( (dx * dx) + (dy * dy) <= (r * r)) // point is inside the knob { scrollMode = ScrMouse; direction = 0; } else // point lies outside { scrollMode = ScrTimer; double arc = atan2(double(-dx),double(dy)) * 180.0 / M_PI; if ( arc < d_data->angle) direction = -1; else if (arc > d_data->angle) direction = 1; else direction = 0; } } /*! \brief Notify a change of the range Called by QwtAbstractSlider */ void QwtKnob::rangeChange() { if (autoScale()) rescale(minValue(), maxValue()); layoutKnob(); recalcAngle(); } /*! \brief Qt Resize Event */ void QwtKnob::resizeEvent(QResizeEvent *) { layoutKnob( false ); } //! Recalculate the knob's geometry and layout based on // the current rect and fonts. // \param update_geometry notify the layout system and call update // to redraw the scale void QwtKnob::layoutKnob( bool update_geometry ) { const QRect r = rect(); const int radius = d_data->knobWidth / 2; d_data->knobRect.setWidth(2 * radius); d_data->knobRect.setHeight(2 * radius); d_data->knobRect.moveCenter(r.center()); scaleDraw()->setRadius(radius + d_data->scaleDist); scaleDraw()->moveCenter(r.center()); if ( update_geometry ) { updateGeometry(); update(); } } /*! \brief Repaint the knob */ void QwtKnob::paintEvent(QPaintEvent *e) { const QRect &ur = e->rect(); if ( ur.isValid() ) { #if QT_VERSION < 0x040000 QwtPaintBuffer paintBuffer(this, ur); draw(paintBuffer.painter(), ur); #else QPainter painter(this); if ( paintEngine()->hasFeature(QPaintEngine::Antialiasing) ) painter.setRenderHint(QPainter::Antialiasing); draw(&painter, ur); #endif } } /*! \brief Repaint the knob */ void QwtKnob::draw(QPainter *painter, const QRect& ur) { if ( !d_data->knobRect.contains( ur ) ) // event from valueChange() { #if QT_VERSION < 0x040000 scaleDraw()->draw( painter, colorGroup() ); #else scaleDraw()->draw( painter, palette() ); #endif } drawKnob( painter, d_data->knobRect ); if ( hasFocus() ) QwtPainter::drawFocusRect(painter, this); } /*! \brief Draw the marker at the knob's front \param p Painter \param arc Angle of the marker \param c Marker color */ void QwtKnob::drawMarker(QPainter *p, double arc, const QColor &c) { const double rarc = arc * M_PI / 180.0; const double ca = cos(rarc); const double sa = - sin(rarc); int radius = d_data->knobRect.width() / 2 - d_data->borderWidth; if (radius < 3) radius = 3; const int ym = d_data->knobRect.y() + radius + d_data->borderWidth; const int xm = d_data->knobRect.x() + radius + d_data->borderWidth; switch (d_data->symbol) { case Dot: { p->setBrush(c); p->setPen(Qt::NoPen); const double rb = double(qwtMax(radius - 4 - d_data->dotWidth / 2, 0)); p->drawEllipse(xm - qRound(sa * rb) - d_data->dotWidth / 2, ym - qRound(ca * rb) - d_data->dotWidth / 2, d_data->dotWidth, d_data->dotWidth); break; } case Line: { p->setPen(QPen(c, 2)); const double rb = qwtMax(double((radius - 4) / 3.0), 0.0); const double re = qwtMax(double(radius - 4), 0.0); p->drawLine ( xm - qRound(sa * rb), ym - qRound(ca * rb), xm - qRound(sa * re), ym - qRound(ca * re)); break; } } } /*! \brief Change the knob's width. The specified width must be >= 5, or it will be clipped. \param w New width */ void QwtKnob::setKnobWidth(int w) { d_data->knobWidth = qwtMax(w,5); layoutKnob(); } //! Return the width of the knob int QwtKnob::knobWidth() const { return d_data->knobWidth; } /*! \brief Set the knob's border width \param bw new border width */ void QwtKnob::setBorderWidth(int bw) { d_data->borderWidth = qwtMax(bw, 0); layoutKnob(); } //! Return the border width int QwtKnob::borderWidth() const { return d_data->borderWidth; } /*! \brief Recalculate the marker angle corresponding to the current value */ void QwtKnob::recalcAngle() { // // calculate the angle corresponding to the value // if (maxValue() == minValue()) { d_data->angle = 0; d_data->nTurns = 0; } else { d_data->angle = (value() - 0.5 * (minValue() + maxValue())) / (maxValue() - minValue()) * d_data->totalAngle; d_data->nTurns = floor((d_data->angle + 180.0) / 360.0); d_data->angle = d_data->angle - d_data->nTurns * 360.0; } } /*! Recalculates the layout \sa QwtKnob::layoutKnob() */ void QwtKnob::scaleChange() { layoutKnob(); } /*! Recalculates the layout \sa QwtKnob::layoutKnob() */ void QwtKnob::fontChange(const QFont &f) { QwtAbstractSlider::fontChange( f ); layoutKnob(); } /*! \return QwtKnob::minimumSizeHint() */ QSize QwtKnob::sizeHint() const { return minimumSizeHint(); } /*! \brief Return a minimum size hint \warning The return value of QwtKnob::minimumSizeHint() depends on the font and the scale. */ QSize QwtKnob::minimumSizeHint() const { // Add the scale radial thickness to the knobWidth const int sh = scaleDraw()->extent( QPen(), font() ); const int d = 2 * sh + 2 * d_data->scaleDist + d_data->knobWidth; return QSize( d, d ); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 524 ] ] ]
ce88f35533843b015282e1ed325e4a27e25f2688
11da90929ba1488c59d25c57a5fb0899396b3bb2
/Src/FormGadget.hpp
3a7b0a6296207c234d82f9531d9021cfe0707387
[]
no_license
danste/ars-framework
5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6
90f99d43804d3892432acbe622b15ded6066ea5d
refs/heads/master
2022-11-11T15:31:02.271791
2005-10-17T15:37:36
2005-10-17T15:37:36
263,623,421
0
0
null
2020-05-13T12:28:22
2020-05-13T12:28:21
null
UTF-8
C++
false
false
1,947
hpp
#ifndef ARSLEXIS_FORM_GADGET_HPP__ #define ARSLEXIS_FORM_GADGET_HPP__ #include <FormObject.hpp> class Graphics; class FormGadget: public FormObjectWrapper<FormGadgetType> { static Boolean gadgetHandler(FormGadgetTypeInCallback* gadget, UInt16 cmd, void* param); void setupGadget(FormType* form, UInt16 index); bool visible_; bool usable_; bool doubleBuffer_; protected: virtual void drawProxy(); virtual void drawFocusRing() {} virtual void removeFocusRing(); virtual void handleDraw(Graphics& graphics); virtual bool handleEvent(EventType& event); virtual bool handleGadgetCommand(UInt16 command, void* param); virtual bool handleEnter(const EventType& event); virtual bool handleMiscEvent(const EventType& event); virtual void notifyHide(); virtual void notifyShow(); void setDoubleBuffer(bool val) {doubleBuffer_=val;} enum FocusChange { focusTaking, focusLosing }; virtual void handleFocusChange(FocusChange change); void fireDrawCompleted() { form()->afterGadgetDraw(); } public: bool visible() const {return visible_;} bool usable() const {return usable_;} explicit FormGadget(Form& form, UInt16 id=frmInvalidObjectId); ~FormGadget(); //! Warning! this function overwrites non-virtual FormObject::attach(). //! Take care not to call it through FormObject pointer or reference. void attach(UInt16 id); //! Warning! this function overwrites non-virtual FormObject::attachByIndex(). //! Take care not to call it through FormObject pointer or reference. void attachByIndex(UInt16 index); friend class Form; friend class Application; friend class FormObject; }; #endif
[ "andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9", "kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9" ]
[ [ [ 1, 5 ], [ 7, 7 ], [ 17, 17 ], [ 19, 19 ], [ 39, 39 ], [ 53, 53 ], [ 56, 56 ], [ 66, 66 ], [ 70, 70 ], [ 79, 80 ] ], [ [ 6, 6 ], [ 8, 16 ], [ 18, 18 ], [ 20, 38 ], [ 40, 52 ], [ 54, 55 ], [ 57, 65 ], [ 67, 69 ], [ 71, 78 ] ] ]
90c69323b96ef34314bc1de05a3f33d6a5a8dc4f
e3ac0562b84b5bd135c5d94157167f3982875858
/Laig3/MenuS.h
467583ac9ecda9075b6556202f80a3b7de53fee4
[]
no_license
marcoamador/LAIGP3
505851170ff71a037468cfd3bde44dc8bf751116
85fce3aadd2d9c348b9344d634d5dcdc4d5d93ff
refs/heads/master
2016-09-06T06:23:35.290290
2011-12-20T18:06:40
2011-12-20T18:06:40
2,932,026
0
0
null
null
null
null
UTF-8
C++
false
false
539
h
#pragma once #ifdef __APPLE__ #include <GLUI/GLUI.h> #else #include <gl/glui.h> #endif #include <string> #include <vector> #include <iostream> using namespace std; #ifndef Laig3_menu_h #define Laig3_menu_h class MenuS { vector<string> menu_strings; int tex_id; int height, width; public: MenuS(void); void draw(GLenum mode); void draw2(GLenum mode); void setTexture(int tex_id); void setMenuStrings(vector<std::string> strings); void drawStrings(); void setDimensions(int,int); }; #endif
[ [ [ 1, 33 ] ] ]
0dd9f9217a128f626aa95df38fe34c628042ffd0
cd1ae676922aee247543ce364b4ec59b2750fdef
/Externals/dolphin-emu/Source/Blob.h
780029a57a4952c6190af665302f8b410c8383d9
[]
no_license
jordan-woyak/wii-banner-player
18dc4e3877a1ea3f76f3a5af0967063716eacf58
64587570f2ee70999ac880a2fab085a34f67cb01
refs/heads/master
2021-01-10T09:59:51.321166
2011-11-09T12:20:44
2011-11-09T12:20:44
44,923,314
1
1
null
null
null
null
UTF-8
C++
false
false
3,142
h
// Copyright (C) 2003 Dolphin Project. // 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, version 2.0. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License 2.0 for more details. // A copy of the GPL 2.0 should have been included with the program. // If not, see http://www.gnu.org/licenses/ // Official SVN repository and contact information can be found at // http://code.google.com/p/dolphin-emu/ #ifndef _BLOB_H #define _BLOB_H // BLOB // Blobs in Dolphin are read only Binary Large OBjects. For example, a typical DVD image. // Often, you may want to store these things in a highly compressed format, but still // allow random access. Or you may store them on an odd device, like raw on a DVD. // Always read your BLOBs using an interface returned by CreateBlobReader(). It will // detect whether the file is a compressed blob, or just a big hunk of data, or a drive, and // automatically do the right thing. #include "CommonTypes.h" namespace DiscIO { class IBlobReader { public: virtual ~IBlobReader() {} virtual u64 GetRawSize() const = 0; virtual u64 GetDataSize() const = 0; // NOT thread-safe - can't call this from multiple threads. virtual bool Read(u64 offset, u64 size, u8* out_ptr) = 0; protected: IBlobReader() {} }; // Provides caching and split-operation-to-block-operations facilities. // Used for compressed blob reading and direct drive reading. // Currently only uses a single entry cache. // Multi-block reads are not cached. class SectorReader : public IBlobReader { private: enum { CACHE_SIZE = 32 }; int m_blocksize; u8* cache[CACHE_SIZE]; u64 cache_tags[CACHE_SIZE]; int cache_age[CACHE_SIZE]; protected: void SetSectorSize(int blocksize); virtual void GetBlock(u64 block_num, u8 *out) = 0; // This one is uncached. The default implementation is to simply call GetBlockData multiple times and memcpy. virtual bool ReadMultipleAlignedBlocks(u64 block_num, u64 num_blocks, u8 *out_ptr); public: virtual ~SectorReader(); // A pointer returned by GetBlockData is invalidated as soon as GetBlockData, Read, or ReadMultipleAlignedBlocks is called again. const u8 *GetBlockData(u64 block_num); virtual bool Read(u64 offset, u64 size, u8 *out_ptr); friend class DriveReader; }; // Factory function - examines the path to choose the right type of IBlobReader, and returns one. IBlobReader* CreateBlobReader(const char *filename); typedef void (*CompressCB)(const char *text, float percent, void* arg); bool CompressFileToBlob(const char *infile, const char *outfile, u32 sub_type = 0, int sector_size = 16384, CompressCB callback = 0, void *arg = 0); bool DecompressBlobToFile(const char *infile, const char *outfile, CompressCB callback = 0, void *arg = 0); } // namespace #endif
[ [ [ 1, 92 ] ] ]
bc74e070f738373a5e66670fc0e4256c9a1129c2
f6a8ffe1612a9a39fc1daa4e7849cad56ec351f0
/ChromaKeyer/trunk/ChromaKeyer/Form1.h
88922a5adeeb8bbf47d9c676800fed54af427b7c
[]
no_license
comebackfly/c-plusplus-programming
03e097ec5b85a4bf1d8fdd47041a82d7b6ca0753
d9b2fb3caa60459fe459cacc5347ccc533b4b1ec
refs/heads/master
2021-01-01T18:12:09.667814
2011-07-18T22:30:31
2011-07-18T22:30:31
35,753,632
0
0
null
null
null
null
UTF-8
C++
false
false
35,334
h
#pragma once #include "graphlibHTW.h" #include <windows.h> #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "User32.lib") #include <WinDef.h> #include <iostream> #include <string> #include "ImageLoader.h" #include "ChromaKey.h" #include "HTWStringConverter.h" namespace ChromaKeyer { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for Form1 /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::PictureBox^ pictureBoxBild1; private: System::Windows::Forms::PictureBox^ pictureBoxBild2; private: System::Windows::Forms::GroupBox^ grpBild1; private: System::Windows::Forms::GroupBox^ grpBild2; private: System::Windows::Forms::OpenFileDialog^ openFile1; private: System::Windows::Forms::OpenFileDialog^ openFile2; private: System::Windows::Forms::Button^ btnOpenFile1; private: System::Windows::Forms::Button^ btnOpenFile2; private: System::Windows::Forms::TextBox^ tbxTest; private: System::Windows::Forms::ColorDialog^ colorDialog1; private: System::Windows::Forms::GroupBox^ grpColorCtrl; private: System::Windows::Forms::Button^ btnColor; private: System::Windows::Forms::Label^ lblColB; private: System::Windows::Forms::Label^ lblColG; private: System::Windows::Forms::Label^ lblColR; private: System::Windows::Forms::TextBox^ txtColB; private: System::Windows::Forms::TextBox^ txtColG; private: System::Windows::Forms::TextBox^ txtColR; private: System::Windows::Forms::ColorDialog^ colDialog; private: System::Windows::Forms::GroupBox^ grpColorTol; private: System::Windows::Forms::TrackBar^ trbColTol; private: System::Windows::Forms::TextBox^ txtColTol; private: System::Windows::Forms::Label^ lblTol; private: System::Windows::Forms::GroupBox^ grpErgebnis; private: System::Windows::Forms::Button^ btnSpeichern; private: System::Windows::Forms::PictureBox^ pictureBoxErgebnis; private: System::Windows::Forms::GroupBox^ grpKeying; private: System::Windows::Forms::Button^ btnKeying; private: System::Windows::Forms::ToolTip^ ttHelp; private: System::Windows::Forms::Label^ lblColHelp; private: System::Windows::Forms::Label^ lblBild1Help; private: System::Windows::Forms::Label^ lblBild2Help; private: System::Windows::Forms::Label^ lblErgebnisHelp; private: System::Windows::Forms::Label^ lblKeyingHelp; private: System::Windows::Forms::PictureBox^ pictureBoxCol; private: System::ComponentModel::IContainer^ components; ImageObject* discharge; ImageObject* background; private: System::Windows::Forms::SaveFileDialog^ saveFileErgebnis; ImageObject* final; protected: protected: private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid)); this->pictureBoxBild1 = (gcnew System::Windows::Forms::PictureBox()); this->pictureBoxBild2 = (gcnew System::Windows::Forms::PictureBox()); this->grpBild1 = (gcnew System::Windows::Forms::GroupBox()); this->lblBild1Help = (gcnew System::Windows::Forms::Label()); this->btnOpenFile1 = (gcnew System::Windows::Forms::Button()); this->grpBild2 = (gcnew System::Windows::Forms::GroupBox()); this->lblBild2Help = (gcnew System::Windows::Forms::Label()); this->btnOpenFile2 = (gcnew System::Windows::Forms::Button()); this->openFile1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->openFile2 = (gcnew System::Windows::Forms::OpenFileDialog()); this->tbxTest = (gcnew System::Windows::Forms::TextBox()); this->grpColorCtrl = (gcnew System::Windows::Forms::GroupBox()); this->pictureBoxCol = (gcnew System::Windows::Forms::PictureBox()); this->lblColHelp = (gcnew System::Windows::Forms::Label()); this->grpColorTol = (gcnew System::Windows::Forms::GroupBox()); this->lblTol = (gcnew System::Windows::Forms::Label()); this->trbColTol = (gcnew System::Windows::Forms::TrackBar()); this->txtColTol = (gcnew System::Windows::Forms::TextBox()); this->btnColor = (gcnew System::Windows::Forms::Button()); this->lblColB = (gcnew System::Windows::Forms::Label()); this->lblColG = (gcnew System::Windows::Forms::Label()); this->lblColR = (gcnew System::Windows::Forms::Label()); this->txtColB = (gcnew System::Windows::Forms::TextBox()); this->txtColG = (gcnew System::Windows::Forms::TextBox()); this->txtColR = (gcnew System::Windows::Forms::TextBox()); this->colDialog = (gcnew System::Windows::Forms::ColorDialog()); this->grpErgebnis = (gcnew System::Windows::Forms::GroupBox()); this->lblErgebnisHelp = (gcnew System::Windows::Forms::Label()); this->btnSpeichern = (gcnew System::Windows::Forms::Button()); this->pictureBoxErgebnis = (gcnew System::Windows::Forms::PictureBox()); this->grpKeying = (gcnew System::Windows::Forms::GroupBox()); this->lblKeyingHelp = (gcnew System::Windows::Forms::Label()); this->btnKeying = (gcnew System::Windows::Forms::Button()); this->ttHelp = (gcnew System::Windows::Forms::ToolTip(this->components)); this->saveFileErgebnis = (gcnew System::Windows::Forms::SaveFileDialog()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxBild1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxBild2))->BeginInit(); this->grpBild1->SuspendLayout(); this->grpBild2->SuspendLayout(); this->grpColorCtrl->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxCol))->BeginInit(); this->grpColorTol->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbColTol))->BeginInit(); this->grpErgebnis->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxErgebnis))->BeginInit(); this->grpKeying->SuspendLayout(); this->SuspendLayout(); // // pictureBoxBild1 // this->pictureBoxBild1->Enabled = false; this->pictureBoxBild1->Location = System::Drawing::Point(6, 46); this->pictureBoxBild1->Name = L"pictureBoxBild1"; this->pictureBoxBild1->Size = System::Drawing::Size(296, 198); this->pictureBoxBild1->TabIndex = 0; this->pictureBoxBild1->TabStop = false; this->ttHelp->SetToolTip(this->pictureBoxBild1, L"Waehlen Sie den Keying Farbwert in dem Sie im Bild auf die Farbe klicken."); this->pictureBoxBild1->MouseClick += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::pictureBoxBild1_MouseClick); // // pictureBoxBild2 // this->pictureBoxBild2->Enabled = false; this->pictureBoxBild2->Location = System::Drawing::Point(6, 48); this->pictureBoxBild2->Name = L"pictureBoxBild2"; this->pictureBoxBild2->Size = System::Drawing::Size(296, 198); this->pictureBoxBild2->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBoxBild2->TabIndex = 1; this->pictureBoxBild2->TabStop = false; this->pictureBoxBild2->Click += gcnew System::EventHandler(this, &Form1::pictureBoxBild2_Click); // // grpBild1 // this->grpBild1->Controls->Add(this->lblBild1Help); this->grpBild1->Controls->Add(this->btnOpenFile1); this->grpBild1->Controls->Add(this->pictureBoxBild1); this->grpBild1->Location = System::Drawing::Point(12, 12); this->grpBild1->Name = L"grpBild1"; this->grpBild1->Size = System::Drawing::Size(353, 250); this->grpBild1->TabIndex = 4; this->grpBild1->TabStop = false; this->grpBild1->Text = L"Vordergrund Bild"; this->grpBild1->Enter += gcnew System::EventHandler(this, &Form1::groupBox1_Enter); // // lblBild1Help // this->lblBild1Help->AutoSize = true; this->lblBild1Help->Cursor = System::Windows::Forms::Cursors::Help; this->lblBild1Help->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblBild1Help->ForeColor = System::Drawing::SystemColors::ControlText; this->lblBild1Help->Location = System::Drawing::Point(326, 16); this->lblBild1Help->Margin = System::Windows::Forms::Padding(0); this->lblBild1Help->Name = L"lblBild1Help"; this->lblBild1Help->Size = System::Drawing::Size(24, 16); this->lblBild1Help->TabIndex = 9; this->lblBild1Help->Text = L" \? "; this->ttHelp->SetToolTip(this->lblBild1Help, L"Vordergrund Bild:\r\n\r\nWaehlen Sie mit \"Bild laden\" das Vordergrund-Bild aus,\r\nwelc" L"hes fuer das Keying benutzt wird. Das Bild sollte einen \r\neinheitlichen Hintergr" L"und (Blue/Green/Screen) haben."); // // btnOpenFile1 // this->btnOpenFile1->Location = System::Drawing::Point(6, 18); this->btnOpenFile1->Name = L"btnOpenFile1"; this->btnOpenFile1->Size = System::Drawing::Size(75, 23); this->btnOpenFile1->TabIndex = 3; this->btnOpenFile1->Text = L"Bild laden"; this->btnOpenFile1->UseVisualStyleBackColor = true; this->btnOpenFile1->Click += gcnew System::EventHandler(this, &Form1::btnOpenFile1_Click); // // grpBild2 // this->grpBild2->Controls->Add(this->lblBild2Help); this->grpBild2->Controls->Add(this->btnOpenFile2); this->grpBild2->Controls->Add(this->pictureBoxBild2); this->grpBild2->Enabled = false; this->grpBild2->Location = System::Drawing::Point(12, 268); this->grpBild2->Name = L"grpBild2"; this->grpBild2->Size = System::Drawing::Size(353, 250); this->grpBild2->TabIndex = 5; this->grpBild2->TabStop = false; this->grpBild2->Text = L"Hintergrund Bild"; // // lblBild2Help // this->lblBild2Help->AutoSize = true; this->lblBild2Help->Cursor = System::Windows::Forms::Cursors::Help; this->lblBild2Help->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblBild2Help->ForeColor = System::Drawing::SystemColors::ControlText; this->lblBild2Help->Location = System::Drawing::Point(326, 16); this->lblBild2Help->Margin = System::Windows::Forms::Padding(0); this->lblBild2Help->Name = L"lblBild2Help"; this->lblBild2Help->Size = System::Drawing::Size(24, 16); this->lblBild2Help->TabIndex = 10; this->lblBild2Help->Text = L" \? "; this->ttHelp->SetToolTip(this->lblBild2Help, L"Hintergrund Bild:\r\n\r\nWaehlen Sie hier das Bild, welches als Hintergrund \r\nfuer da" L"s Ergebnis-Bild dient. Die Vordergrund-Elemente\r\nwerden aus dem Vordergrund Bild" L" uebernommen."); // // btnOpenFile2 // this->btnOpenFile2->Location = System::Drawing::Point(6, 19); this->btnOpenFile2->Name = L"btnOpenFile2"; this->btnOpenFile2->Size = System::Drawing::Size(75, 23); this->btnOpenFile2->TabIndex = 2; this->btnOpenFile2->Text = L"Bild laden"; this->btnOpenFile2->UseVisualStyleBackColor = true; this->btnOpenFile2->Click += gcnew System::EventHandler(this, &Form1::btnOpenFile2_Click); // // openFile1 // this->openFile1->FileName = L"File1"; this->openFile1->FileOk += gcnew System::ComponentModel::CancelEventHandler(this, &Form1::openFile1_FileOk); // // openFile2 // this->openFile2->FileName = L"File2"; this->openFile2->FileOk += gcnew System::ComponentModel::CancelEventHandler(this, &Form1::openFile2_FileOk); // // tbxTest // this->tbxTest->Location = System::Drawing::Point(388, 21); this->tbxTest->Name = L"tbxTest"; this->tbxTest->ReadOnly = true; this->tbxTest->Size = System::Drawing::Size(353, 20); this->tbxTest->TabIndex = 6; this->tbxTest->Text = L"test-Ausgabe"; this->tbxTest->TextChanged += gcnew System::EventHandler(this, &Form1::tbxTest_TextChanged); // // grpColorCtrl // this->grpColorCtrl->Controls->Add(this->pictureBoxCol); this->grpColorCtrl->Controls->Add(this->lblColHelp); this->grpColorCtrl->Controls->Add(this->grpColorTol); this->grpColorCtrl->Controls->Add(this->btnColor); this->grpColorCtrl->Controls->Add(this->lblColB); this->grpColorCtrl->Controls->Add(this->lblColG); this->grpColorCtrl->Controls->Add(this->lblColR); this->grpColorCtrl->Controls->Add(this->txtColB); this->grpColorCtrl->Controls->Add(this->txtColG); this->grpColorCtrl->Controls->Add(this->txtColR); this->grpColorCtrl->Enabled = false; this->grpColorCtrl->Location = System::Drawing::Point(388, 58); this->grpColorCtrl->Name = L"grpColorCtrl"; this->grpColorCtrl->Size = System::Drawing::Size(353, 141); this->grpColorCtrl->TabIndex = 7; this->grpColorCtrl->TabStop = false; this->grpColorCtrl->Text = L"Farbe bestimmen"; // // pictureBoxCol // this->pictureBoxCol->Location = System::Drawing::Point(98, 98); this->pictureBoxCol->Name = L"pictureBoxCol"; this->pictureBoxCol->Size = System::Drawing::Size(21, 21); this->pictureBoxCol->TabIndex = 9; this->pictureBoxCol->TabStop = false; // // lblColHelp // this->lblColHelp->AutoSize = true; this->lblColHelp->Cursor = System::Windows::Forms::Cursors::Help; this->lblColHelp->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblColHelp->ForeColor = System::Drawing::SystemColors::ControlText; this->lblColHelp->Location = System::Drawing::Point(326, 16); this->lblColHelp->Margin = System::Windows::Forms::Padding(0); this->lblColHelp->Name = L"lblColHelp"; this->lblColHelp->Size = System::Drawing::Size(24, 16); this->lblColHelp->TabIndex = 8; this->lblColHelp->Text = L" \? "; this->ttHelp->SetToolTip(this->lblColHelp, resources->GetString(L"lblColHelp.ToolTip")); // // grpColorTol // this->grpColorTol->Controls->Add(this->lblTol); this->grpColorTol->Controls->Add(this->trbColTol); this->grpColorTol->Controls->Add(this->txtColTol); this->grpColorTol->Location = System::Drawing::Point(187, 19); this->grpColorTol->Name = L"grpColorTol"; this->grpColorTol->Size = System::Drawing::Size(115, 100); this->grpColorTol->TabIndex = 7; this->grpColorTol->TabStop = false; this->grpColorTol->Text = L"Farbtoleranz"; // // lblTol // this->lblTol->AutoSize = true; this->lblTol->Location = System::Drawing::Point(91, 22); this->lblTol->Name = L"lblTol"; this->lblTol->Size = System::Drawing::Size(15, 13); this->lblTol->TabIndex = 2; this->lblTol->Text = L"%"; this->ttHelp->SetToolTip(this->lblTol, L"Geben Sie die Farbtoleranz in Prozent an."); // // trbColTol // this->trbColTol->Location = System::Drawing::Point(6, 49); this->trbColTol->Maximum = 100; this->trbColTol->Name = L"trbColTol"; this->trbColTol->Size = System::Drawing::Size(104, 45); this->trbColTol->TabIndex = 1; this->ttHelp->SetToolTip(this->trbColTol, L"Stellen Sie die Farbtoleranz mit dem Slider ein."); this->trbColTol->Scroll += gcnew System::EventHandler(this, &Form1::trbColTol_Scroll); // // txtColTol // this->txtColTol->Location = System::Drawing::Point(6, 19); this->txtColTol->MaxLength = 3; this->txtColTol->Name = L"txtColTol"; this->txtColTol->Size = System::Drawing::Size(79, 20); this->txtColTol->TabIndex = 0; this->txtColTol->Text = L"0"; this->ttHelp->SetToolTip(this->txtColTol, L"Geben Sie die Farbtoleranz in Prozent an."); this->txtColTol->TextChanged += gcnew System::EventHandler(this, &Form1::txtColTol_TextChanged); // // btnColor // this->btnColor->Location = System::Drawing::Point(6, 97); this->btnColor->Name = L"btnColor"; this->btnColor->Size = System::Drawing::Size(86, 23); this->btnColor->TabIndex = 6; this->btnColor->Text = L"Farbe waehlen"; this->ttHelp->SetToolTip(this->btnColor, L"Waehlen Sie die Farbe im Color-Picker"); this->btnColor->UseVisualStyleBackColor = true; this->btnColor->Click += gcnew System::EventHandler(this, &Form1::btnColor_Click); // // lblColB // this->lblColB->AutoSize = true; this->lblColB->Location = System::Drawing::Point(78, 74); this->lblColB->Name = L"lblColB"; this->lblColB->Size = System::Drawing::Size(28, 13); this->lblColB->TabIndex = 5; this->lblColB->Text = L"Blau"; this->ttHelp->SetToolTip(this->lblColB, L"Geben Sie einen RGB-Farbwert fuer Blau ein (0-255)"); // // lblColG // this->lblColG->AutoSize = true; this->lblColG->Location = System::Drawing::Point(78, 48); this->lblColG->Name = L"lblColG"; this->lblColG->Size = System::Drawing::Size(36, 13); this->lblColG->TabIndex = 4; this->lblColG->Text = L"Gruen"; this->ttHelp->SetToolTip(this->lblColG, L"Geben Sie einen RGB-Farbwert fuer Gruen ein (0-255)"); // // lblColR // this->lblColR->AutoSize = true; this->lblColR->Location = System::Drawing::Point(79, 25); this->lblColR->Name = L"lblColR"; this->lblColR->Size = System::Drawing::Size(24, 13); this->lblColR->TabIndex = 3; this->lblColR->Text = L"Rot"; this->ttHelp->SetToolTip(this->lblColR, L"Geben Sie einen RGB-Farbwert fuer Rot ein (0-255)\r\n"); // // txtColB // this->txtColB->Location = System::Drawing::Point(6, 71); this->txtColB->MaxLength = 3; this->txtColB->Name = L"txtColB"; this->txtColB->Size = System::Drawing::Size(66, 20); this->txtColB->TabIndex = 2; this->ttHelp->SetToolTip(this->txtColB, L"Geben Sie einen RGB-Farbwert fuer Blau ein (0-255)"); this->txtColB->TextChanged += gcnew System::EventHandler(this, &Form1::txtColB_TextChanged); // // txtColG // this->txtColG->Location = System::Drawing::Point(6, 45); this->txtColG->MaxLength = 3; this->txtColG->Name = L"txtColG"; this->txtColG->Size = System::Drawing::Size(66, 20); this->txtColG->TabIndex = 1; this->ttHelp->SetToolTip(this->txtColG, L"Geben Sie einen RGB-Farbwert fuer Gruen ein (0-255)"); this->txtColG->TextChanged += gcnew System::EventHandler(this, &Form1::txtColG_TextChanged); // // txtColR // this->txtColR->Location = System::Drawing::Point(6, 19); this->txtColR->MaxLength = 3; this->txtColR->Name = L"txtColR"; this->txtColR->Size = System::Drawing::Size(66, 20); this->txtColR->TabIndex = 0; this->ttHelp->SetToolTip(this->txtColR, L"Geben Sie einen RGB-Farbwert fuer Rot ein (0-255)\r\n"); this->txtColR->TextChanged += gcnew System::EventHandler(this, &Form1::txtColR_TextChanged); // // grpErgebnis // this->grpErgebnis->Controls->Add(this->lblErgebnisHelp); this->grpErgebnis->Controls->Add(this->btnSpeichern); this->grpErgebnis->Controls->Add(this->pictureBoxErgebnis); this->grpErgebnis->Enabled = false; this->grpErgebnis->Location = System::Drawing::Point(388, 268); this->grpErgebnis->Name = L"grpErgebnis"; this->grpErgebnis->Size = System::Drawing::Size(353, 250); this->grpErgebnis->TabIndex = 6; this->grpErgebnis->TabStop = false; this->grpErgebnis->Text = L"Ergebnis Bild"; // // lblErgebnisHelp // this->lblErgebnisHelp->AutoSize = true; this->lblErgebnisHelp->Cursor = System::Windows::Forms::Cursors::Help; this->lblErgebnisHelp->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblErgebnisHelp->ForeColor = System::Drawing::SystemColors::ControlText; this->lblErgebnisHelp->Location = System::Drawing::Point(326, 16); this->lblErgebnisHelp->Margin = System::Windows::Forms::Padding(0); this->lblErgebnisHelp->Name = L"lblErgebnisHelp"; this->lblErgebnisHelp->Size = System::Drawing::Size(24, 16); this->lblErgebnisHelp->TabIndex = 11; this->lblErgebnisHelp->Text = L" \? "; this->ttHelp->SetToolTip(this->lblErgebnisHelp, resources->GetString(L"lblErgebnisHelp.ToolTip")); // // btnSpeichern // this->btnSpeichern->Location = System::Drawing::Point(6, 19); this->btnSpeichern->Name = L"btnSpeichern"; this->btnSpeichern->Size = System::Drawing::Size(86, 23); this->btnSpeichern->TabIndex = 2; this->btnSpeichern->Text = L"Bild speichern"; this->btnSpeichern->UseVisualStyleBackColor = true; this->btnSpeichern->Click += gcnew System::EventHandler(this, &Form1::btnSpeichern_Click); // // pictureBoxErgebnis // this->pictureBoxErgebnis->Enabled = false; this->pictureBoxErgebnis->Location = System::Drawing::Point(6, 48); this->pictureBoxErgebnis->Name = L"pictureBoxErgebnis"; this->pictureBoxErgebnis->Size = System::Drawing::Size(296, 198); this->pictureBoxErgebnis->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBoxErgebnis->TabIndex = 1; this->pictureBoxErgebnis->TabStop = false; // // grpKeying // this->grpKeying->Controls->Add(this->lblKeyingHelp); this->grpKeying->Controls->Add(this->btnKeying); this->grpKeying->Enabled = false; this->grpKeying->Location = System::Drawing::Point(388, 209); this->grpKeying->Name = L"grpKeying"; this->grpKeying->Size = System::Drawing::Size(353, 53); this->grpKeying->TabIndex = 8; this->grpKeying->TabStop = false; this->grpKeying->Text = L"Keying Control"; // // lblKeyingHelp // this->lblKeyingHelp->AutoSize = true; this->lblKeyingHelp->Cursor = System::Windows::Forms::Cursors::Help; this->lblKeyingHelp->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblKeyingHelp->ForeColor = System::Drawing::SystemColors::ControlText; this->lblKeyingHelp->Location = System::Drawing::Point(326, 16); this->lblKeyingHelp->Margin = System::Windows::Forms::Padding(0); this->lblKeyingHelp->Name = L"lblKeyingHelp"; this->lblKeyingHelp->Size = System::Drawing::Size(24, 16); this->lblKeyingHelp->TabIndex = 12; this->lblKeyingHelp->Text = L" \? "; this->ttHelp->SetToolTip(this->lblKeyingHelp, resources->GetString(L"lblKeyingHelp.ToolTip")); // // btnKeying // this->btnKeying->Location = System::Drawing::Point(7, 20); this->btnKeying->Name = L"btnKeying"; this->btnKeying->Size = System::Drawing::Size(85, 23); this->btnKeying->TabIndex = 0; this->btnKeying->Text = L"Starte Keying"; this->btnKeying->UseVisualStyleBackColor = true; this->btnKeying->Click += gcnew System::EventHandler(this, &Form1::btnKeying_Click); // // ttHelp // this->ttHelp->ToolTipTitle = L"Help"; this->ttHelp->Popup += gcnew System::Windows::Forms::PopupEventHandler(this, &Form1::ttHelp_Popup); // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(769, 537); this->Controls->Add(this->grpKeying); this->Controls->Add(this->grpErgebnis); this->Controls->Add(this->grpColorCtrl); this->Controls->Add(this->tbxTest); this->Controls->Add(this->grpBild2); this->Controls->Add(this->grpBild1); this->Name = L"Form1"; this->Text = L"Form1"; (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxBild1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxBild2))->EndInit(); this->grpBild1->ResumeLayout(false); this->grpBild1->PerformLayout(); this->grpBild2->ResumeLayout(false); this->grpBild2->PerformLayout(); this->grpColorCtrl->ResumeLayout(false); this->grpColorCtrl->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxCol))->EndInit(); this->grpColorTol->ResumeLayout(false); this->grpColorTol->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trbColTol))->EndInit(); this->grpErgebnis->ResumeLayout(false); this->grpErgebnis->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBoxErgebnis))->EndInit(); this->grpKeying->ResumeLayout(false); this->grpKeying->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void openFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { } private: System::Void pictureBox1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e) { } private: System::Void btnOpenFile1_Click(System::Object^ sender, System::EventArgs^ e) { if(openFile1->ShowDialog() == System::Windows::Forms::DialogResult::OK) { System::IO::StreamReader ^ sr = gcnew System::IO::StreamReader(openFile1->FileName); //MessageBox::Show(sr->ReadToEnd()); sr->Close(); pictureBoxBild1->Enabled = "True"; // load image into picture box pictureBoxBild1->Image = Image::FromFile(openFile1->FileName); discharge = ImageLoader::loadImage(Image::FromFile(openFile1->FileName)->Width,Image::FromFile(openFile1->FileName)->Height,3,HTWStringConverter::Sys2Std(openFile1->FileName)); grpBild2->Enabled = "True"; grpColorCtrl->Enabled = "True"; } } private: System::Void btnOpenFile2_Click(System::Object^ sender, System::EventArgs^ e) { if(openFile2->ShowDialog() == System::Windows::Forms::DialogResult::OK) { System::IO::StreamReader ^ sr = gcnew System::IO::StreamReader(openFile2->FileName); //MessageBox::Show(sr->ReadToEnd()); sr->Close(); pictureBoxBild2->Enabled = "True"; // load image into picture box pictureBoxBild2->Image = Image::FromFile(openFile2->FileName); System::String^ testStr = ""; testStr += openFile2->FileName; testStr += ", "; testStr += Image::FromFile(openFile2->FileName)->Width; testStr += " x "; testStr += Image::FromFile(openFile2->FileName)->Height; // Image::loadImage(Image::FromFile(openFile2->FileName)->Width,Image::FromFile(openFile2->FileName)->Height,3,HTWStringConverter::Sys2Std(openFile2->FileName)); background = ImageLoader::loadImage(Image::FromFile(openFile2->FileName)->Width,Image::FromFile(openFile2->FileName)->Height,3,HTWStringConverter::Sys2Std(openFile2->FileName)); grpKeying->Enabled = "True"; } } private: System::Void openFile2_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { } private: System::Void openFile1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { } private: System::Void tbxTest_TextChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void pictureBoxBild2_Click(System::Object^ sender, System::EventArgs^ e) { } // Choose the keying color with mouse click on pictureBox private: System::Void pictureBoxBild1_MouseClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { // get Cursor Position POINT pos; GetCursorPos(&pos); // Position anpassen an pictureBox Pos. links oben ist 0,0 pos.x-=126; pos.y-=188; if(pos.x < 0) { pos.x = 0; } if(pos.y < 0) { pos.y = 0; } // generate Bitmap from Image to get color with GetPixel(x,y) Bitmap^ bm = gcnew Bitmap(pictureBoxBild1->Image); // Color -> RGBA with A = Alpha (ignore) Color col = bm->GetPixel(pos.x,pos.y); pictureBoxCol->BackColor = col; // Testausgaben in Test-Textbox System::String^ testStr2 =""; testStr2+= pos.x; testStr2+=", "; testStr2+= pos.y; testStr2+= " "; testStr2+= col; tbxTest->Text = testStr2; System::String^ colR = ""; System::String^ colG = ""; System::String^ colB = ""; colR += col.R; colG += col.G; colB += col.B; txtColR->Text = colR; txtColG->Text = colG; txtColB->Text = colB; } private: System::Void btnColor_Click(System::Object^ sender, System::EventArgs^ e) { colDialog->ShowDialog(); System::String^ colorR = ""; System::String^ colorG = ""; System::String^ colorB = ""; colorR += colDialog->Color.R; colorG += colDialog->Color.G; colorB += colDialog->Color.B; txtColR->Text = colorR; txtColG->Text = colorG; txtColB->Text = colorB; pictureBoxCol->BackColor = colDialog->Color; } private: System::Void txtColTol_TextChanged(System::Object^ sender, System::EventArgs^ e) { int tol; // pruefen ob Wert eine Zahl ist if(!Int32::TryParse(txtColTol->Text, tol)) { // keine Zahl System::Windows::Forms::MessageBox::Show("Wert zwischen 0 und 100 %"); //default wert txtColTol->Text = "0"; } else { // pruefen ob > 255 oder <0 if(System::Convert::ToInt32(txtColTol->Text)>100) { System::Windows::Forms::MessageBox::Show("Wert zwischen 0 und 100 %"); txtColTol->Text= "100"; } else if(System::Convert::ToInt32(txtColTol->Text)<0) { System::Windows::Forms::MessageBox::Show("Wert zwischen 0 und 100 %"); txtColTol->Text= "0"; } else { trbColTol->Value = System::Convert::ToInt32(txtColTol->Text); } } } private: System::Void trbColTol_Scroll(System::Object^ sender, System::EventArgs^ e) { txtColTol->Text = System::Convert::ToString(trbColTol->Value); } private: System::Void ttHelp_Popup(System::Object^ sender, System::Windows::Forms::PopupEventArgs^ e) { } private: System::Void txtColR_TextChanged(System::Object^ sender, System::EventArgs^ e) { int test; // pruefen ob Wert eine Zahl ist if(!Int32::TryParse(txtColR->Text, test)) { // keine Zahl System::Windows::Forms::MessageBox::Show("Zahlenwert von 0-255!"); txtColR->Text = "0"; } else { // pruefen ob > 255 oder <0 if(System::Convert::ToInt32(txtColR->Text)>255) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht groesser als 255 sein!"); txtColR->Text= "255"; } else if(System::Convert::ToInt32(txtColR->Text)<0) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht kleiner als 0 sein!"); txtColR->Text= "0"; } else { // alle pruefen ob Werte drin stehen if((txtColR->Text != "") && (txtColG->Text != "") && (txtColB->Text != "")) { Color col = Color::FromArgb(255,System::Convert::ToInt32(txtColR->Text),System::Convert::ToInt32(txtColG->Text),System::Convert::ToInt32(txtColB->Text)); pictureBoxCol->BackColor = col; } } } } private: System::Void txtColG_TextChanged(System::Object^ sender, System::EventArgs^ e) { int test; // pruefen ob Wert eine Zahl ist if(!Int32::TryParse(txtColG->Text, test)) { // keine Zahl System::Windows::Forms::MessageBox::Show("Wert von 0-255!"); txtColG->Text = "0"; } else { // pruefen ob > 255 oder <0 if(System::Convert::ToInt32(txtColG->Text)>255) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht groesser als 255 sein!"); txtColG->Text= "255"; } else if(System::Convert::ToInt32(txtColG->Text)<0) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht kleiner als 0 sein!"); txtColG->Text= "0"; } else { // alle pruefen ob Werte drin stehen if((txtColR->Text != "") && (txtColG->Text != "") && (txtColB->Text != "")) { Color col = Color::FromArgb(255,System::Convert::ToInt32(txtColR->Text),System::Convert::ToInt32(txtColG->Text),System::Convert::ToInt32(txtColB->Text)); pictureBoxCol->BackColor = col; } } } } private: System::Void txtColB_TextChanged(System::Object^ sender, System::EventArgs^ e) { int test; // pruefen ob Wert eine Zahl ist if(!Int32::TryParse(txtColB->Text, test)) { // keine Zahl System::Windows::Forms::MessageBox::Show("Wert von 0-255!"); txtColB->Text = "0"; } else { // pruefen ob > 255 oder <0 if(System::Convert::ToInt32(txtColB->Text)>255) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht groesser als 255 sein!"); txtColB->Text= "255"; } else if(System::Convert::ToInt32(txtColB->Text)<0) { System::Windows::Forms::MessageBox::Show("Zahl darf nicht kleiner als 0 sein!"); txtColB->Text= "0"; } else { // alle pruefen ob Werte drin stehen if((txtColR->Text != "") && (txtColG->Text != "") && (txtColB->Text != "")) { Color col = Color::FromArgb(255,System::Convert::ToInt32(txtColR->Text),System::Convert::ToInt32(txtColG->Text),System::Convert::ToInt32(txtColB->Text)); pictureBoxCol->BackColor = col; } } } } private: System::Void btnKeying_Click(System::Object^ sender, System::EventArgs^ e) { // Keying starten // Farbwerte und Toleranz an Keying Klasse uebergeben grpErgebnis->Enabled = "True"; btnKeying->Enabled = "False"; ChromaKey keyer; final = keyer.keyImage(discharge,background,pictureBoxCol->BackColor.B, pictureBoxCol->BackColor.G, pictureBoxCol->BackColor.R); //System::Windows::Forms::MessageBox::Show(System::Convert::ToString(final->getHeight())); if(htwSaveImage("F:\\temp.jpg",final->getImageContent(),final->getWidth(), final->getHeight(),final->getBytesPerPixel())) { pictureBoxErgebnis->Image = Image::FromFile("F:\\temp.jpg"); //pictureBoxErgebnis->Image = Image::FromStream((System::IO::Stream)(final->getImageContent())); } } private: System::Void btnSpeichern_Click(System::Object^ sender, System::EventArgs^ e) { //System::IO::Stream^ myStream ; //System::IO::Stream fs = saveFileErgebnis->OpenFile(); //fs->Close(); } }; }
[ "[email protected]@5f9f56c3-fb77-04ef-e3c5-e71eb3e36737" ]
[ [ [ 1, 802 ] ] ]
a3127c355f9fd6a86e8b36ba49f939727a43c52b
b04f65deafef481d6e0f22c26085735a3c275d3a
/mod/applications/mod_cari_ccp_server/CModule_NEManager.cpp
19eac14199e9059445a2782a2eabf72691c05181
[]
no_license
gujun/sscore
d28d374f09d40aa426282538416ae16023d8a7a6
295d613473a554e4de9f8c203fae961f587555ac
refs/heads/master
2021-01-02T22:57:21.404133
2011-06-21T06:19:57
2011-06-21T06:19:57
1,927,509
2
0
null
null
null
null
GB18030
C++
false
false
51,581
cpp
#include "CModule_NEManager.h" #include "mod_cari_ccp_server.h" #include "cari_net_event_process.h" #define MIN_NEID 1 #define MAX_NEID 1000 //不同类型的设备名称 #define CCP "CCP" //cari core platform #define SW "SW" //switch #define AP "AP" //access point #define GATEWAY "GATEWAY" //gateway //网元简单的xml内容 #define NE_XML_SIMPLE_CONTEXT "<ne id=\"%s\" type = \"%s\" ip = \"%s\" desc = \"%s\"/>" #define OPUSER_XML_SIMPLE_CONTEXT "<opuser name=\"%s\" pwd = \"%s\" priority = \"%s\"/>" #define SUPER_USER "admin" CModule_NEManager::CModule_NEManager() : CBaseModule() { const char *errmsg[1]={ 0 }; bool bRes = false; //ne的xml文件 char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); //char *neContext = "<include></include>"; //如果此文件不存在,则重新创建,并且只需要创建一次即可 if (!cari_common_isExistedFile(nefile)){ char *neContext = switch_mprintf("%s%s", "<include>", "</include>" ); bRes = cari_common_creatXMLFile(nefile,neContext,errmsg); switch_safe_free(neContext); } if (!bRes){ //打印日志??? } //操作用户的xml文件 char *opuserfile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); //如果此文件不存在,则重新创建,并且只需要创建一次即可 if (!cari_common_isExistedFile(opuserfile)){ //创建初始登录的默认操作用户 char *opuserContext = switch_mprintf("%s%s%s", "<include>", "<opuser name=\"admin\" pwd = \"123456\" priority = \"0\"/>", //用户操作的优先级从0开始,最大 "</include>" ); bRes = cari_common_creatXMLFile(opuserfile,opuserContext,errmsg); switch_safe_free(opuserContext); } if (!bRes){ //打印日志??? } //释放内存 switch_safe_free(nefile); switch_safe_free(opuserfile); } CModule_NEManager::~CModule_NEManager() { } /*根据接收到的帧,处理具体的命令,分发到具体的处理函数 */ int CModule_NEManager::receiveReqMsg(inner_CmdReq_Frame *&inner_reqFrame, inner_ResultResponse_Frame *&inner_RespFrame) { if (NULL == inner_reqFrame) { //帧为空 return CARICCP_ERROR_STATE_CODE; } //请求帧的"源模块"号则是响应帧的"目的模块"号 //请求帧的"目的模块"号则是响应帧的"源模块"号,可逆的 inner_RespFrame->sSourceModuleID = inner_reqFrame->sDestModuleID; inner_RespFrame->sDestModuleID = inner_reqFrame->sSourceModuleID; int iFunRes = CARICCP_SUCCESS_STATE_CODE; bool bRes = true; //判断命令码来判断命令(命令码是惟一的),也可以根据命令名进行设置 int iCmdCode = inner_reqFrame->body.iCmdCode; switch (iCmdCode) { case CARICCP_ADD_EQUIP_NE: iFunRes = addEquipNE(inner_reqFrame, inner_RespFrame); break; case CARICCP_DEL_EQUIP_NE: iFunRes = delEquipNE(inner_reqFrame, inner_RespFrame); break; case CARICCP_MOD_EQUIP_NE: iFunRes = modEquipNE(inner_reqFrame, inner_RespFrame); break; case CARICCP_LST_EQUIP_NE: iFunRes = lstEquipNE(inner_reqFrame, inner_RespFrame); break; case CARICCP_ADD_OP_USER: iFunRes = addOPUser(inner_reqFrame, inner_RespFrame); break; case CARICCP_DEL_OP_USER: iFunRes = delOPUser(inner_reqFrame, inner_RespFrame); break; case CARICCP_MOD_OP_USER: iFunRes = modOPUser(inner_reqFrame, inner_RespFrame); break; case CARICCP_LST_OP_USER: iFunRes = lstOPUser(inner_reqFrame, inner_RespFrame); break; default: break; }; //命令执行不成功 if (CARICCP_SUCCESS_STATE_CODE != iFunRes) { inner_RespFrame->header.bNotify = false; } else { inner_RespFrame->header.bNotify = inner_reqFrame->body.bNotify; } /*--------------------------------------------------------------------------------------------*/ //将处理的结果发送给对应的客户端 //在命令的接收入口函数中 //打印日志 //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "proc cmd %s end.\n", inner_reqFrame->body.strCmdName); return iFunRes; } /*发送信息给对应的客户端 */ int CModule_NEManager::sendRespMsg(common_ResultResponse_Frame *&respFrame) { int iFunRes = CARICCP_SUCCESS_STATE_CODE; return iFunRes; } int CModule_NEManager::cmdPro(const inner_CmdReq_Frame *&reqFrame) { return CARICCP_SUCCESS_STATE_CODE; } /*增加设备网元,需要通知其他注册的client */ int CModule_NEManager::addEquipNE(inner_CmdReq_Frame *&reqFrame, inner_ResultResponse_Frame *&inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL,*pNotifyNode = NULL; bool bRes = true; //涉及到通知类型的处理 :命令属于通知类型,需要广播通知其他客户端 switch_event_t *notifyInfoEvent = NULL; int notifyCode = CARICCP_NOTIFY_ADD_EQUIP_NE; char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); switch_xml_t x_NEs=NULL,x_newNE=NULL; char *newNEContext=NULL,*nesContext=NULL; //涉及到参数 string strParamName, strValue, strChinaName; string strID,strType,strIP,strDesc; string strTmp; int neid=0; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"neid" strParamName = "neid";//neid strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //neid号必须是有效数字 if (!isNumber(strValue)){ strReturnDesc = getValueOfDefinedVar("PARAM_NUMBER_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //范围限制 neid = stringToInt(strValue.c_str()); if (MIN_NEID>neid || MAX_NEID < neid){ strReturnDesc = getValueOfDefinedVar("PARAM_RANGE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(),MIN_NEID,MAX_NEID); goto end_flag; } strID = strValue; //"NEType" strParamName = "netype";//网元类型 strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //NEType类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if(!isEqualStr(strValue,AP) && !isEqualStr(strValue,GATEWAY) && !isEqualStr(strValue,"else")){ strReturnDesc = getValueOfDefinedVar("NE_TYPE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } strType = strValue; //ip地址 strParamName = "ip";//ip strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //ip类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //地址必须有效 if (!isValidIPV4(strValue)){ strReturnDesc = getValueOfDefinedVar("PARAM_IP_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } strIP = strValue; //desc strParamName = "desc";//desc strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); strDesc = strValue; ////////////////////////////////////////////////////////////////////////// //判断此网元是否已经存在??? if (isExistedNE(neid)){ strReturnDesc = getValueOfDefinedVar("NE_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); goto end_flag; } //开始增加网元//////////////////////////////////////////////////////////// //将内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), nefile); goto end_flag; } //先构建xml的内存结构 newNEContext = NE_XML_SIMPLE_CONTEXT; newNEContext = switch_mprintf(newNEContext, strID.c_str(), strType.c_str(), strIP.c_str(), strDesc.c_str()); x_newNE = switch_xml_parse_str(newNEContext, strlen(newNEContext)); if (!x_newNE) { strReturnDesc = getValueOfDefinedVar("STR_TO_XML_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //将新增的网元的结构添加进来 if (!switch_xml_insert(x_newNE, x_NEs, INSERT_INTOXML_POS)) { strReturnDesc = getValueOfDefinedVar("INNER_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //将全部网元的内存结构转换成字串 nesContext = switch_xml_toxml(x_NEs, SWITCH_FALSE); if (!nesContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } ////////////////////////////////////////////////////////////////////////// //重新创建网元的文件 bRes = cari_common_creatXMLFile(nefile,nesContext,err); if (!bRes){ strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("ADD_NE_SUCCESS"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); /************************************************************************/ /* 发送通知 */ /************************************************************************/ //涉及到通知类型的处理 :命令属于通知类型,需要广播通知所有注册的client //if (SWITCH_STATUS_SUCCESS != switch_event_create(&notifyInfoEvent, CARICCP_EVENT_STATE_NOTIFY)) { if (SWITCH_STATUS_SUCCESS != switch_event_create_subclass(&notifyInfoEvent, SWITCH_EVENT_CUSTOM, CARI_CCP_EVENT_NAME)) { //此时还是按照成功处理 goto end_flag; } //通知码 notifyCode = CARICCP_NOTIFY_ADD_EQUIP_NE; //结果码和结果集 pNotifyNode = switch_mprintf("%d", notifyCode); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_NOTIFY, "1"); //通知标识 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_RETURNCODE, pNotifyNode); //返回码=通知码 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "neid", strID.c_str()); //通知的结果数据 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "netype", strType.c_str()); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "ip", strIP.c_str()); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "desc", strDesc.c_str()); //发送通知---------------------- cari_net_event_notify(notifyInfoEvent); //释放内存 switch_event_destroy(&notifyInfoEvent); switch_safe_free(pNotifyNode); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); //释放xml结构 switch_xml_free(x_NEs); switch_safe_free(nefile); switch_safe_free(pDesc); return iFunRes; } /*删除网元,需要通知其他注册的client */ int CModule_NEManager::delEquipNE(inner_CmdReq_Frame *&reqFrame, inner_ResultResponse_Frame *&inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL,*pNotifyCode = NULL; bool bRes = true; //涉及到通知类型的处理 :命令属于通知类型,需要广播通知其他客户端 switch_event_t *notifyInfoEvent = NULL; int notifyCode = CARICCP_NOTIFY_DEL_EQUIP_NE; char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); switch_xml_t x_NEs,x_delNE; char *newNEContext =NULL,*nesContext=NULL; //涉及到参数 string strParamName, strValue, strChinaName; string strID; string strTmp; int neid=0; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"neid" strParamName = "neid";//neid strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //id号必须是有效数字 if (!isNumber(strValue)){ strReturnDesc = getValueOfDefinedVar("PARAM_NUMBER_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } neid = stringToInt(strValue.c_str()); strID = strValue; //网元是否存在 if (!isExistedNE(neid)){ strReturnDesc = getValueOfDefinedVar("NE_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); goto end_flag; } //删除掉此网元的相关信息 //将内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), nefile); goto end_flag; } x_delNE = switch_xml_find_child(x_NEs, "ne", "id", strID.c_str()); if (!x_delNE) { strReturnDesc = getValueOfDefinedVar("NE_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); goto end_flag; } /************************************************************************/ //动态更改内存的结构 switch_xml_remove(x_delNE); /************************************************************************/ //重新写文件 nesContext = switch_xml_toxml(x_NEs, SWITCH_FALSE); if (!nesContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } bRes = cari_common_creatXMLFile(nefile, nesContext, err); if (!bRes) { strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); //是否考虑恢复以前的模板结构!!!!!!!!!!!!!!! //如果出现错误,不一定会是写内容的时候出现,此处不再考虑回退问题. goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("DEL_NE_SUCCESS"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); /************************************************************************/ /* 发送通知 */ /************************************************************************/ //涉及到通知类型的处理 :命令属于通知类型,需要广播通知所有注册的client //if (SWITCH_STATUS_SUCCESS != switch_event_create(&notifyInfoEvent, CARICCP_EVENT_STATE_NOTIFY)) { if (SWITCH_STATUS_SUCCESS != switch_event_create_subclass(&notifyInfoEvent, SWITCH_EVENT_CUSTOM, CARI_CCP_EVENT_NAME)) { //此时还是按照成功处理 goto end_flag; } //通知码 notifyCode = CARICCP_NOTIFY_DEL_EQUIP_NE; //结果码和结果集 pNotifyCode = switch_mprintf("%d", notifyCode); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_NOTIFY, "1"); //通知标识 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_RETURNCODE, pNotifyCode); //返回码=通知码 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "neid", strID.c_str()); //通知的结果数据 //发送通知---------------------- cari_net_event_notify(notifyInfoEvent); //释放内存 switch_event_destroy(&notifyInfoEvent); switch_safe_free(pNotifyCode); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); switch_safe_free(nefile); switch_safe_free(pDesc); return iFunRes; } /*修改网元操作,需要通知其他注册的client */ int CModule_NEManager::modEquipNE(inner_CmdReq_Frame *&reqFrame, inner_ResultResponse_Frame *&inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL,*pNotifyCode = NULL; bool bRes = true,bMod=false; //涉及到通知类型的处理 :命令属于通知类型,需要广播通知其他客户端 switch_event_t *notifyInfoEvent = NULL; int notifyCode = CARICCP_NOTIFY_MOD_EQUIP_NE; char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); switch_xml_t x_NEs = NULL,x_modNE= NULL; char *newNEContext = NULL,*nesContext=NULL; //涉及到参数 string strParamName,strValue,strVar,strChinaName; string strID,strType,strIP,strDesc; string strTmp; int neid = 0; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"neid" strParamName = "neid";//neid strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //id号必须是有效数字 if (!isNumber(strValue)){ strReturnDesc = getValueOfDefinedVar("PARAM_NUMBER_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //范围限制 neid = stringToInt(strValue.c_str()); if (MIN_NEID>neid || MAX_NEID < neid){ strReturnDesc = getValueOfDefinedVar("PARAM_RANGE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(),MIN_NEID,MAX_NEID); goto end_flag; } strID = strValue; //"NEType" strParamName = "netype";//网元类型 strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //NEType类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if(!isEqualStr(strValue,AP) && !isEqualStr(strValue,GATEWAY) && !isEqualStr(strValue,"else")){ strReturnDesc = getValueOfDefinedVar("NE_TYPE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } strType = strValue; //ip地址 strParamName = "ip";//ip strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //ip类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } //地址必须有效 if (!isValidIPV4(strValue)){ strReturnDesc = getValueOfDefinedVar("PARAM_IP_ERROR"); strReturnDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } strIP = strValue; //desc strParamName = "desc";//desc strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); strDesc = strValue; ////////////////////////////////////////////////////////////////////////// //判断此网元是否已经存在??? if (!isExistedNE(neid)){ strReturnDesc = getValueOfDefinedVar("NE_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); goto end_flag; } ////////////////////////////////////////////////////////////////////////// //开始修改网元的属性 x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), nefile); goto end_flag; } x_modNE = switch_xml_find_child(x_NEs, "ne", "id", strID.c_str()); if (!x_modNE) { strReturnDesc = getValueOfDefinedVar("NE_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strID.c_str()); goto end_flag; } //设置名-值对,如: <ne id="1" type = "AP" ip = "127.0.0.1" desc = "ap1"/> //根据"网元类型"或"网元ip"或"描述信息"判断是否和以前的相同,另:id号不能进行修改 strVar = switch_xml_attr(x_modNE, "type"); if (!isEqualStr(strVar,strType)){ switch_xml_set_attr(x_modNE, "type", strType.c_str()); bMod = true; } strVar = switch_xml_attr(x_modNE, "ip"); if (!isEqualStr(strVar,strIP)){ switch_xml_set_attr(x_modNE, "ip", strIP.c_str()); bMod = true; } strVar = switch_xml_attr(x_modNE, "desc"); if (!isEqualStr(strVar,strDesc)){ switch_xml_set_attr(x_modNE, "desc", strDesc.c_str()); bMod = true; } //如果属性真正的进行了修改,则需要修改配置文件,如果修改的值和以前保存的值相同,此处直接返回成功信息即可 //也不需要再进行广播通知 if (bMod){ //重新写文件 nesContext = switch_xml_toxml(x_NEs, SWITCH_FALSE); if (!nesContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } bRes = cari_common_creatXMLFile(nefile, nesContext, err); if (!bRes) { strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); //是否考虑恢复以前的模板结构!!!!!!!!!!!!!!! //如果出现错误,不一定会是写内容的时候出现,此处不再考虑回退问题. goto end_flag; } } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("MOD_NE_SUCCESS"); pDesc = switch_mprintf(strReturnDesc.c_str(),strID.c_str()); /************************************************************************/ /* 发送通知 */ /************************************************************************/ //涉及到通知类型的处理 :命令属于通知类型,需要广播通知所有注册的client if (bMod){ //if (SWITCH_STATUS_SUCCESS != switch_event_create(&notifyInfoEvent, CARICCP_EVENT_STATE_NOTIFY)) { if (SWITCH_STATUS_SUCCESS != switch_event_create_subclass(&notifyInfoEvent, SWITCH_EVENT_CUSTOM, CARI_CCP_EVENT_NAME)) { //此时还是按照成功处理 goto end_flag; } //通知码 notifyCode = CARICCP_NOTIFY_MOD_EQUIP_NE; //结果码和结果集 pNotifyCode = switch_mprintf("%d", notifyCode); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_NOTIFY, "1"); //通知标识 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, CARICCP_RETURNCODE, pNotifyCode); //返回码=通知码 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "neid", strID.c_str()); //通知的结果数据 switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "netype", strType.c_str()); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "ip", strIP.c_str()); switch_event_add_header_string(notifyInfoEvent, SWITCH_STACK_BOTTOM, "desc", strDesc.c_str()); //发送通知---------------------- cari_net_event_notify(notifyInfoEvent); //释放内存 switch_event_destroy(&notifyInfoEvent); switch_safe_free(pNotifyCode); } /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); switch_xml_free(x_NEs); switch_safe_free(nefile); switch_safe_free(pDesc); return iFunRes; } /*查询设备NE的信息,主要查询对应的id号,类型,已经ip地址 */ int CModule_NEManager::lstEquipNE(inner_CmdReq_Frame *&reqFrame, inner_ResultResponse_Frame *&inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strSeq,strRecord; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL,*pNotifyCode = NULL; bool bRes = true; string tableHeader[5] = { getValueOfDefinedVar("SEQUENCE"), getValueOfDefinedVar("NEID"), getValueOfDefinedVar("NETYPE"), getValueOfDefinedVar("IP"), getValueOfDefinedVar("DESC") }; int iRecordCout = 0;//记录数量 char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); switch_xml_t x_NEs=NULL,x_ne=NULL; char *newNEContext=NULL,*nesContext=NULL,*strTableName=NULL; //将网元的xml内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //遍历查找所有的网元 x_ne = switch_xml_child(x_NEs, "ne"); for (; x_ne; x_ne = x_ne->next) { const char *neID = switch_xml_attr(x_ne, "id"); const char *netype = switch_xml_attr(x_ne, "type"); const char *neip = switch_xml_attr(x_ne, "ip"); const char *neDesc = switch_xml_attr(x_ne, "desc"); if (neID && netype && neip){ char *singleRecord = switch_mprintf("%s%s%s%s%s%s%s%s", neID, CARICCP_SPECIAL_SPLIT_FLAG, netype, CARICCP_SPECIAL_SPLIT_FLAG, neip, CARICCP_SPECIAL_SPLIT_FLAG, neDesc, CARICCP_ENTER_KEY ); //mod by xxl 2010-5-27 :增加序号的显示 iRecordCout++;//序号递增 strRecord = ""; strSeq = intToString(iRecordCout); strRecord.append(strSeq); strRecord.append(CARICCP_SPECIAL_SPLIT_FLAG); strRecord.append(singleRecord); //存放记录 inner_RespFrame->m_vectTableValue.push_back(/*singleRecord*/strRecord); //mod by xxl 2010-5-27 end switch_safe_free(singleRecord); } } //当前记录为空 if (0 ==inner_RespFrame->m_vectTableValue.size()){ strReturnDesc = getValueOfDefinedVar("NO_NE_RECORD"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; strReturnDesc = getValueOfDefinedVar("NE_RECORD"); //设置表头字段 strTableName = switch_mprintf("%s%s%s%s%s%s%s%s%s", tableHeader[0].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[1].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[2].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[3].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[4].c_str()); myMemcpy(inner_RespFrame->strTableName, strTableName, sizeof(inner_RespFrame->strTableName)); switch_safe_free(strTableName); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, strReturnDesc.c_str(), sizeof(inner_RespFrame->header.strResuleDesc)); switch_xml_free(x_NEs); switch_safe_free(pDesc); switch_safe_free(nefile); return iFunRes; } /*增加操作用户 */ int CModule_NEManager::addOPUser(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL,*pNotifyNode = NULL; bool bRes = true; char *opuserfile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); switch_xml_t x_opusers=NULL,x_newOpuser=NULL; char *newOpuserContext=NULL,*opusersContext=NULL; //涉及到参数 string strParamName, strValue, strChinaName; string strUserName,strPwd; string strTmp; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"opusername" strParamName = "opusername"; strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //用户超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strUserName = strValue; //"opuserpwd" strParamName = "opuserpwd"; strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strPwd = strValue; ////////////////////////////////////////////////////////////////////////// //判断此"操作用户"是否已经存在??? if (isExistedOpUser(strUserName)){ strReturnDesc = getValueOfDefinedVar("OPUSER_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strUserName.c_str()); goto end_flag; } ////////////////////////////////////////////////////////////////////////// //开始增加操作用户 //将内容转换成xml的结构(注意:中文字符问题) x_opusers = cari_common_parseXmlFromFile(opuserfile); if (!x_opusers){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), opuserfile); goto end_flag; } //先构建xml的内存结构 newOpuserContext = OPUSER_XML_SIMPLE_CONTEXT; newOpuserContext = switch_mprintf(newOpuserContext,strUserName.c_str(), strPwd.c_str(),"0");//默认为超级用户 x_newOpuser = switch_xml_parse_str(newOpuserContext, strlen(newOpuserContext)); if (!x_newOpuser) { strReturnDesc = getValueOfDefinedVar("STR_TO_XML_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //将新增的操作用户的结构添加进来 if (!switch_xml_insert(x_newOpuser, x_opusers, INSERT_INTOXML_POS)) { strReturnDesc = getValueOfDefinedVar("INNER_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //将全部操作用户的内存结构转换成字串 opusersContext = switch_xml_toxml(x_opusers, SWITCH_FALSE); if (!opusersContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //重新创建网元的文件 bRes = cari_common_creatXMLFile(opuserfile,opusersContext,err); if (!bRes){ strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("ADD_OPUSER_SUCCESS"); pDesc = switch_mprintf(strReturnDesc.c_str(), strUserName.c_str()); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); switch_xml_free(x_opusers);//释放 switch_safe_free(opuserfile); switch_safe_free(pDesc); return iFunRes; } /*删除操作用户 */ int CModule_NEManager::delOPUser(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL; bool bRes = true; char *opuserfile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); switch_xml_t x_opusers=NULL,x_deOpuser=NULL; char *newOpuserContext=NULL,*opusersContext=NULL; //涉及到参数 string strParamName, strValue, strChinaName; string strUserName; string strTmp; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"opusername" strParamName = "opusername";//opusername strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strUserName = strValue; //判断此"操作用户"是否已经存在??? if (!isExistedOpUser(strUserName)){ strReturnDesc = getValueOfDefinedVar("OPUSER_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strUserName.c_str()); goto end_flag; } //特殊判断一下,如果登录用户相同,则不允许 if (isEqualStr(strUserName,reqFrame->header.strLoginUserName)){ strReturnDesc = getValueOfDefinedVar("DEL_OPUSER_FAILED"); pDesc = switch_mprintf(strReturnDesc.c_str()); goto end_flag; } //如果为固定用户admin,则一定不能删除 if (isEqualStr(strUserName,SUPER_USER)){ strReturnDesc = getValueOfDefinedVar("DEL_ADMIN_OPUSER_FAILED"); pDesc = switch_mprintf(strReturnDesc.c_str(),SUPER_USER); goto end_flag; } //删除掉此操作的相关信息 //将内容转换成xml的结构(注意:中文字符问题) x_opusers = cari_common_parseXmlFromFile(opuserfile); if (!x_opusers){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), opuserfile); goto end_flag; } x_deOpuser = switch_xml_find_child(x_opusers, "opuser", "name", strUserName.c_str()); if (!x_deOpuser) { strReturnDesc = getValueOfDefinedVar("OPUSER_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strUserName.c_str()); goto end_flag; } /************************************************************************/ //动态更改内存的结构 switch_xml_remove(x_deOpuser); /************************************************************************/ //重新写文件 opusersContext = switch_xml_toxml(x_opusers, SWITCH_FALSE); if (!opusersContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } bRes = cari_common_creatXMLFile(opuserfile, opusersContext, err); if (!bRes) { strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); //是否考虑恢复以前的模板结构!!!!!!!!!!!!!!! //如果出现错误,不一定会是写内容的时候出现,此处不再考虑回退问题. goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("DEL_OPUSER_SUCCESS"); pDesc = switch_mprintf(strReturnDesc.c_str(), strUserName.c_str()); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); switch_xml_free(x_opusers);//释放 switch_safe_free(opuserfile); switch_safe_free(pDesc); return iFunRes; } /*修改操作用户 */ int CModule_NEManager::modOPUser(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strNotifyCode; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL; bool bRes = true,bMod=false; char *opuserfile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); switch_xml_t x_opusers=NULL,x_modOpuser=NULL; char *newOpuserContext=NULL,*opusersContext=NULL; //涉及到参数 string strParamName,strValue,strVar,strChinaName; string strOldName,strNewName,strPwd; string strTmp; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"oldopusername" strParamName = "oldopusername";//oldopusername strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strOldName = strValue; //"newopusername" strParamName = "newopusername";//newopusername strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strNewName = strValue; //"opuserpwd" strParamName = "opuserpwd";//opuserpwd strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { //id类型是必选参数 strReturnDesc = getValueOfDefinedVar("PARAM_NULL_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str()); goto end_flag; } if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } strPwd = strValue; //检查oldname是否存在 if (!isExistedOpUser(strOldName)){ strReturnDesc = getValueOfDefinedVar("OPUSER_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strOldName.c_str()); goto end_flag; } //oldname和newname不相同 if (!isEqualStr(strOldName,strNewName)){ if (isEqualStr(strOldName,SUPER_USER)){//admin用户,不能修改为其他用户 strReturnDesc = getValueOfDefinedVar("MOD_SUPERUSER_FAILED_1"); pDesc = switch_mprintf(strReturnDesc.c_str(), strOldName.c_str()); goto end_flag; } if (isEqualStr(strNewName,SUPER_USER)){//修改的新用户为admin,不允许 strReturnDesc = getValueOfDefinedVar("MOD_SUPERUSER_FAILED_2"); pDesc = switch_mprintf(strReturnDesc.c_str(), strNewName.c_str(),strOldName.c_str()); goto end_flag; } //检查newname是否存在 if (isExistedOpUser(strNewName)){ strReturnDesc = getValueOfDefinedVar("OPUSER_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strNewName.c_str()); goto end_flag; } } ////////////////////////////////////////////////////////////////////////// //开始修改操作用户的属性 x_opusers = cari_common_parseXmlFromFile(opuserfile); if (!x_opusers){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), opuserfile); goto end_flag; } x_modOpuser = switch_xml_find_child(x_opusers, "opuser", "name", strOldName.c_str()); if (!x_modOpuser) { strReturnDesc = getValueOfDefinedVar("OPUSER_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strOldName.c_str()); goto end_flag; } //设置名-值对,如: <opuser name=\"%s\" pwd = \"%s\" priority = \"%s\"/> switch_xml_set_attr(x_modOpuser, "name", strNewName.c_str()); switch_xml_set_attr(x_modOpuser, "pwd", strPwd.c_str()); //重新写文件 opusersContext = switch_xml_toxml(x_opusers, SWITCH_FALSE); if (!opusersContext) { strReturnDesc = getValueOfDefinedVar("XML_TO_STR_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } bRes = cari_common_creatXMLFile(opuserfile, opusersContext, err); if (!bRes) { strReturnDesc = *err; pDesc = switch_mprintf("%s",strReturnDesc.c_str()); //是否考虑恢复以前的模板结构!!!!!!!!!!!!!!! //如果出现错误,不一定会是写内容的时候出现,此处不再考虑回退问题. goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; //描述信息再重新封装一下 strReturnDesc = getValueOfDefinedVar("MOD_OPUSER_SUCCESS"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); switch_xml_free(x_opusers);//释放 switch_safe_free(opuserfile); switch_safe_free(pDesc); return iFunRes; } /*查询操作用户 */ int CModule_NEManager::lstOPUser(inner_CmdReq_Frame*& reqFrame, inner_ResultResponse_Frame*& inner_RespFrame) { int iFunRes = CARICCP_ERROR_STATE_CODE; int iCmdReturnCode = CARICCP_ERROR_STATE_CODE; string strReturnDesc = "",strUserName,strParamName,strValue,strChinaName,strSeq,strRecord; const char *errArry[1] = { 0 }; const char **err = errArry; char *pDesc = NULL; bool bRes = true,bAllOrOne=true; string tableHeader[3] = { getValueOfDefinedVar("SEQUENCE"), getValueOfDefinedVar("USER_NAME"), getValueOfDefinedVar("USER_PWD") }; int iRecordCout = 0;//记录数量 char *opuserfile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); switch_xml_t x_opusers=NULL,x_opuser=NULL; char *newOpuserContext=NULL,*opusersContext=NULL,*strTableName=NULL; ////////////////////////////////////////////////////////////////////////// //对参数进行解析 //"opusername" strParamName = "opusername"; strChinaName = getValueOfDefinedVar(strParamName); strValue = getValue(strParamName, reqFrame); trim(strValue); if (0 == strValue.size()) { bAllOrOne = true; } else{//查询有个具体的操作用户信息 if (CARICCP_STRING_LENGTH_32 < strValue.length()) { //用户超长,返回错误信息 strReturnDesc = getValueOfDefinedVar("PARAM_MAXLENGTH_ERROR"); pDesc = switch_mprintf(strReturnDesc.c_str(), strChinaName.c_str(), CARICCP_STRING_LENGTH_32); goto end_flag; } //判断此"操作用户"是否存在 if (!isExistedOpUser(strValue)){ strReturnDesc = getValueOfDefinedVar("OPUSER_NO_EXIST"); pDesc = switch_mprintf(strReturnDesc.c_str(), strValue.c_str()); goto end_flag; } bAllOrOne = false; } strUserName = strValue; //将网元的xml内容转换成xml的结构(注意:中文字符问题) x_opusers = cari_common_parseXmlFromFile(opuserfile); if (!x_opusers){ strReturnDesc = getValueOfDefinedVar("PARSE_XML_FILE_ERROR"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //遍历查找所有的操作用户 x_opuser = switch_xml_child(x_opusers, "opuser"); for (; x_opuser; x_opuser = x_opuser->next) { const char *name = switch_xml_attr(x_opuser, "name"); const char *pwd = switch_xml_attr(x_opuser, "pwd"); if (name && pwd){ if (!bAllOrOne){ if (isEqualStr(strUserName.c_str(),name)){ goto next; } continue; } next: char *singleRecord = switch_mprintf("%s%s%s%s", name, CARICCP_SPECIAL_SPLIT_FLAG, pwd, CARICCP_ENTER_KEY ); //mod by xxl 2010-5-27 :增加序号的显示 iRecordCout++;//序号递增 strRecord = ""; strSeq = intToString(iRecordCout); strRecord.append(strSeq); strRecord.append(CARICCP_SPECIAL_SPLIT_FLAG); strRecord.append(singleRecord); //存放记录 inner_RespFrame->m_vectTableValue.push_back(/*singleRecord*/strRecord); //mod by xxl 2010-5-27 end switch_safe_free(singleRecord); } } //当前记录为空 if (0 ==inner_RespFrame->m_vectTableValue.size()){ strReturnDesc = getValueOfDefinedVar("RECORD_NULL"); pDesc = switch_mprintf("%s",strReturnDesc.c_str()); goto end_flag; } //成功 iFunRes = CARICCP_SUCCESS_STATE_CODE; iCmdReturnCode = CARICCP_SUCCESS_STATE_CODE; strReturnDesc = getValueOfDefinedVar("OPUSER_RECORD"); pDesc = switch_mprintf(strReturnDesc.c_str()); //设置表头字段 strTableName = switch_mprintf("%s%s%s%s%s", tableHeader[0].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[1].c_str(), CARICCP_SPECIAL_SPLIT_FLAG, tableHeader[2].c_str()); myMemcpy(inner_RespFrame->strTableName, strTableName, sizeof(inner_RespFrame->strTableName)); switch_safe_free(strTableName); /*-----*/ end_flag : inner_RespFrame->header.iResultCode = iCmdReturnCode; myMemcpy(inner_RespFrame->header.strResuleDesc, pDesc, sizeof(inner_RespFrame->header.strResuleDesc)); //释放xml结构 switch_xml_free(x_opusers); switch_safe_free(pDesc); switch_safe_free(opuserfile); return iFunRes; } /************************************************************************/ /* */ /************************************************************************/ /*根据id号进行判断,是否存在此网元 */ bool CModule_NEManager::isExistedNE(int id) { //临时方案:目前根据文件读取 bool bRes = false; switch_xml_t x_NEs=NULL,x_ne=NULL; const char *errmsg[1]={ 0 }; const char *neID = NULL; string strID = intToString(id); char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); if (!cari_common_isExistedFile(nefile)){ //char *neContext = "<include></include>"; ////重新创建此文件 //cari_common_creatXMLFile(nefile,neContext,errmsg); goto end; } //将内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ goto end; } //遍历查找 x_ne = switch_xml_child(x_NEs, "ne"); for (; x_ne; x_ne = x_ne->next) { neID = switch_xml_attr(x_ne, "id"); if (isEqualStr(strID.c_str(),neID)){ bRes = true; break; } } end: switch_xml_free(x_NEs); switch_safe_free(nefile); return bRes; } /*网元是否存在,根据ip地址进行判断 */ bool CModule_NEManager::isExistedNE(string ip) { //临时方案:目前根据文件读取 bool bRes = false; switch_xml_t x_NEs=NULL,x_ne=NULL; const char *errmsg[1]={ 0 }; const char *neIP=NULL; char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_NE_XML_FILE ); if (!cari_common_isExistedFile(nefile)){ //char *neContext = "<include></include>"; ////重新创建此文件 //cari_common_creatXMLFile(nefile,neContext,errmsg); goto end; } //将内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ goto end; } //遍历查找 x_ne = switch_xml_child(x_NEs, "ne"); for (; x_ne; x_ne = x_ne->next) { neIP = switch_xml_attr(x_ne, "ip"); if (isEqualStr(ip.c_str(),neIP)){ bRes = true; break; } } end: switch_xml_free(x_NEs); switch_safe_free(nefile); return bRes; } /*是否存在此操作用户 */ bool CModule_NEManager::isExistedOpUser(string username) { //临时方案:目前根据文件读取 bool bRes = false; switch_xml_t x_NEs,x_ne; const char *errmsg[1]={ 0 }; const char *name=NULL; char *nefile = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, CARI_CCP_OPUSER_XML_FILE ); if (!cari_common_isExistedFile(nefile)){ goto end; } //将内容转换成xml的结构(注意:中文字符问题) x_NEs = cari_common_parseXmlFromFile(nefile); if (!x_NEs){ goto end; } //遍历查找 x_ne = switch_xml_child(x_NEs, "opuser"); for (; x_ne; x_ne = x_ne->next) { name = switch_xml_attr(x_ne, "name"); if (isEqualStr(username.c_str(),name)){ bRes = true; break; } } end: switch_safe_free(nefile); return bRes; }
[ "pub@cariteledell.(none)" ]
[ [ [ 1, 1584 ] ] ]
2bbf58221b6cadaf684f1a34a557fda7d3f89785
cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0
/http/parsers/media_type.hpp
272d89221a929f6701bea229ff1558c701ec54e4
[ "BSL-1.0" ]
permissive
ssiloti/http
a15fb43c94c823779f11fb02e147f023ca77c932
9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e
refs/heads/master
2021-01-01T19:10:36.886248
2011-11-07T19:29:22
2011-11-07T19:29:22
1,021,325
0
1
null
null
null
null
UTF-8
C++
false
false
1,937
hpp
// // media_type.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2011 Steven Siloti ([email protected]) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_PARSERS_MEDIA_TYPE_HPP #define HTTP_PARSERS_MEDIA_TYPE_HPP #include <http/media_type.hpp> #include <http/parsers/basic_rules.hpp> #include <boost/spirit/home/qi/operator.hpp> #include <boost/spirit/home/qi/nonterminal/rule.hpp> #include <boost/spirit/home/qi/nonterminal/grammar.hpp> #include <boost/spirit/home/qi/parse.hpp> #include <boost/fusion/include/std_pair.hpp> #include <exception> namespace http { namespace parsers { template <typename Iterator> struct media_type : boost::spirit::qi::grammar<Iterator, http::media_type()> { media_type() : media_type::base_type(start, "media_type") { start %= b.token >> '/' >> b.token >> parameters; parameters %= *(b.ows >> ';' >> b.ows >> parameter); // q is not allowed as a media type parameter because it is used // as a separator in the Accept header parameter %= (b.token - 'q') >> '=' >> b.word; } basic_rules<Iterator> b; // start rule of grammar boost::spirit::qi::rule<Iterator, http::media_type()> start; boost::spirit::qi::rule<Iterator, std::map<std::string, std::string>()> parameters; boost::spirit::qi::rule<Iterator, std::pair<std::string, std::string>()> parameter; }; } // namespace parsers inline media_type& media_type::operator=(const std::string& str) { std::string::const_iterator begin(str.begin()); if (!boost::spirit::qi::parse(begin, str.end(), parsers::media_type<std::string::const_iterator>(), *this)) throw std::invalid_argument(str + " is not a valid media type"); return *this; } } // namespace http #endif
[ [ [ 1, 19 ], [ 21, 33 ], [ 37, 60 ] ], [ [ 20, 20 ], [ 34, 36 ] ] ]
c25461f405fc95afaaf3e71a2fb6e78ad3ccf352
979297bfdce893c7e656c406a8a522c079fe0291
/TuioListener.h
0b5c2f421acbc62084e26e9930dd588fa8cf5a8a
[]
no_license
berkus/tuiobleep
709134c95e7d17da58b071db9136f256c6d8161e
baab983d87c0d7f842090170437cf5d33472f009
refs/heads/master
2023-07-11T00:00:21.357510
2006-12-16T03:14:12
2006-12-16T03:14:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,951
h
/* TUIO C++ backend - part of the reacTIVision project http://www.iua.upf.es/mtg/reacTable Copyright (c) 2006 Martin Kaltenbrunner <[email protected]> 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. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. 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 INCLUDED_TUIOLISTENER_H #define INCLUDED_TUIOLISTENER_H class TuioListener { public: virtual ~TuioListener(){}; virtual void addTuioObj(unsigned int s_id, unsigned int f_id)=0; virtual void updateTuioObj(unsigned int s_id, unsigned int f_id, float xpos, float ypos, float angle, float x_speed, float y_speed, float r_speed, float m_accel, float r_accel)=0; virtual void removeTuioObj(unsigned int s_id, unsigned int f_id)=0; virtual void refresh()=0; }; #endif /* INCLUDED_TUIOLISTENER_H */
[ [ [ 1, 44 ] ] ]
d5c2967a3a938ba0fe0fcc5c50afae78cf8335d3
3971d26cbdfd1ca41e84754bdf21ff6fbc53182e
/trunk/include/BitmapDistance.h
21310ecf5359edfbc408afefc122396897688dad
[]
no_license
ppershing/mosaic-from-images
bd998004de1555f76777047000ac0642ace0c860
54a2f6c9cd3c37f118a133d4fce1eaf5678581d2
refs/heads/master
2020-04-25T00:26:40.707089
2011-01-06T17:59:11
2011-01-06T17:59:11
32,278,829
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
// created and maintained by ppershing // please report any bug or suggestion to ppershing<>fks<>sk #ifndef H_BITMAP_DISTANCE #define H_BITMAP_DISTANCE #include "Bitmap.h" #include "ColorAdjust.h" class BitmapDistance { public: double distance(Bitmap* b1, Bitmap* b2, ColorAdjust* adjust); }; #endif
[ "ppershing@967e5cf6-af39-6869-9469-1a2409c1b03c" ]
[ [ [ 1, 14 ] ] ]
e893620f78bbb0f6453c0f2a8b05d142b6c7a90d
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/API/Core/XML/xml_writer.h
f5af45d0d7d073d732ae07e0bdad6f710689b142
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
2,302
h
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ /// \addtogroup clanCore_XML clanCore XML /// \{ #pragma once #include "../api_core.h" #include "../System/sharedptr.h" class CL_IODevice; class CL_XMLToken; class CL_XMLWriter_Generic; /// \brief The XML Writer writes a XML file based on XML tokens. /// /// \xmlonly !group=Core/XML! !header=core.h! \endxmlonly class CL_API_CORE CL_XMLWriter { /// \name Construction /// \{ public: CL_XMLWriter(); /// \brief Constructs a XMLWriter /// /// \param copy = XMLWriter CL_XMLWriter(const CL_XMLWriter &copy); /// \brief Constructs a XMLWriter /// /// \param output = IODevice CL_XMLWriter(CL_IODevice &output); virtual ~CL_XMLWriter(); /// \} /// \name Attributes /// \{ public: /// \brief Returns the insert whitespace flag. bool get_insert_whitespace() const; /// \brief Inserts whitespace between tags if enabled. void set_insert_whitespace(bool enable); /// \} /// \name Operations /// \{ public: /// \brief Write token to file. void write(const CL_XMLToken &token); /// \} /// \name Implementation /// \{ private: CL_SharedPtr<CL_XMLWriter_Generic> impl; /// \} }; /// \}
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 92 ] ] ]
7c7c368631c328ea74ad55613ba3b01838e3909b
e028013b5dfe8262af326be861b344e36752b4a3
/Intf/SerialConnection.h
9a2593374319ff47bd8081f5452fc072f3ecee68
[]
no_license
HappyHunter/LD130
3a769300e331213da8a64d341e30269dd0afb961
60a2a25c4f4388915814f59d9c47930b39f4d10d
refs/heads/master
2019-01-02T04:34:29.521971
2011-08-15T12:37:30
2011-08-15T12:37:30
1,172,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
//////////////////////////////////////////////////////////////////// // // Alexandr Filenkov 2010 // //////////////////////////////////////////////////////////////////// #ifndef SerialConMan_201012141650 #define SerialConMan_201012141650 #include "CommonCmd.h" #include "Parser.h" /* * NOT THREAD SAFE CLASS */ typedef void (*TSerialOnLogEvent)(const void* anObject, const char* pCmd, const char* pLogStr); class TSerialConMan { public: TSerialConMan(); ~TSerialConMan(); bool isConnected() const; TCommandErrorOutput send(const char* pCmd) const; TCommandErrorOutput init(int aComPort, int aSpeed = 9600, TSerialOnLogEvent pLogEvent = 0, const void* anObject=0); void close(); const char * GetValueByName(const char * pName) const; const char * GetCmdName() const; private: HANDLE m_hComPort; int m_UartID; mutable OVERLAPPED m_overlappedOut; mutable OVERLAPPED m_overlappedIn; TSerialOnLogEvent m_pLogEvent; const void* m_onLogObject; TCMDParser* m_pParser; static bool m_bParserInitialized; }; #endif
[ [ [ 1, 50 ] ] ]
4a50112880d64c660a4c481aae98517a15f7b827
5927f0908f05d3f58fe0adf4d5d20c27a4756fbe
/examples/chrome/tab_strip_model.h
46010af67233fbeea0a0660afb5333abdf25f17f
[]
no_license
seasky013/x-framework
b5585505a184a7d00d229da8ab0f556ca0b4b883
575e29de5840ede157e0348987fa188b7205f54d
refs/heads/master
2016-09-16T09:41:26.994686
2011-09-16T06:16:22
2011-09-16T06:16:22
41,719,436
0
1
null
null
null
null
UTF-8
C++
false
false
28,731
h
#ifndef __tab_strip_model_h__ #define __tab_strip_model_h__ #pragma once #include <vector> #include "base/observer_list.h" #include "tab_strip_model_observer.h" #include "tab_strip_selection_model.h" class NavigationController; class TabContents; class TabContentsWrapper; class TabStripModelDelegate; class TabStripModelOrderController; //////////////////////////////////////////////////////////////////////////////// // // TabStripModel // // A model & low level controller of a Browser Window tabstrip. Holds a vector // of TabContents, and provides an API for adding, removing and shuffling // them, as well as a higher level API for doing specific Browser-related // tasks like adding new Tabs from just a URL, etc. // // Each tab may be any one of the following states: // . Mini-tab. Mini tabs are locked to the left side of the tab strip and // rendered differently (small tabs with only a favicon). The model makes // sure all mini-tabs are at the beginning of the tab strip. For example, // if a non-mini tab is added it is forced to be with non-mini tabs. Requests // to move tabs outside the range of the tab type are ignored. For example, // a request to move a mini-tab after non-mini-tabs is ignored. // You'll notice there is no explcit api for making a tab a mini-tab, rather // there are two tab types that are implicitly mini-tabs: // . App. Corresponds to an extension that wants an app tab. App tabs are // identified by TabContentsWrapper::extension_tab_helper()::is_app(). // App tabs are always pinneded (you can't unpin them). // . Pinned. Any tab can be pinned. Non-app tabs whose pinned state is changed // are moved to be with other mini-tabs or non-mini tabs. // // A TabStripModel has one delegate that it relies on to perform certain tasks // like creating new TabStripModels (probably hosted in Browser windows) when // required. See TabStripDelegate above for more information. // // A TabStripModel also has N observers (see TabStripModelObserver above), // which can be registered via Add/RemoveObserver. An Observer is notified of // tab creations, removals, moves, and other interesting events. The // TabStrip implements this interface to know when to create new tabs in // the View, and the Browser object likewise implements to be able to update // its bookkeeping when such events happen. // //////////////////////////////////////////////////////////////////////////////// class TabStripModel { public: // Policy for how new tabs are inserted. enum InsertionPolicy { // Newly created tabs are created after the selection. This is the default. INSERT_AFTER, // Newly created tabs are inserted before the selection. INSERT_BEFORE, }; // Used to specify what should happen when the tab is closed. enum CloseTypes { CLOSE_NONE = 0, // Indicates the tab was closed by the user. If true, // TabContents::set_closed_by_user_gesture(true) is invoked. CLOSE_USER_GESTURE = 1 << 0, // If true the history is recorded so that the tab can be reopened later. // You almost always want to set this. CLOSE_CREATE_HISTORICAL_TAB = 1 << 1, }; // Constants used when adding tabs. enum AddTabTypes { // Used to indicate nothing special should happen to the newly inserted // tab. ADD_NONE = 0, // The tab should be active. ADD_ACTIVE = 1 << 0, // If not set the insertion index of the TabContents is left up to the Order // Controller associated, so the final insertion index may differ from the // specified index. Otherwise the index supplied is used. ADD_FORCE_INDEX = 1 << 2, // If set the newly inserted tab inherits the group of the currently // selected tab. If not set the tab may still inherit the group under // certain situations. ADD_INHERIT_GROUP = 1 << 3, // If set the newly inserted tab's opener is set to the active tab. If not // set the tab may still inherit the group/opener under certain situations. // NOTE: this is ignored if ADD_INHERIT_GROUP is set. ADD_INHERIT_OPENER = 1 << 4, }; static const int kNoTab = -1; // Construct a TabStripModel with a delegate to help it do certain things // (See TabStripModelDelegate documentation). |delegate| cannot be NULL. TabStripModel(TabStripModelDelegate* delegate); virtual ~TabStripModel(); // Retrieves the TabStripModelDelegate associated with this TabStripModel. TabStripModelDelegate* delegate() const { return delegate_; } // Add and remove observers to changes within this TabStripModel. void AddObserver(TabStripModelObserver* observer); void RemoveObserver(TabStripModelObserver* observer); // Retrieve the number of TabContentses/emptiness of the TabStripModel. int count() const { return static_cast<int>(contents_data_.size()); } bool empty() const { return contents_data_.empty(); } // Retrieve the index of the currently active TabContents. int active_index() const { return selection_model_.active(); } // Returns true if the tabstrip is currently closing all open tabs (via a // call to CloseAllTabs). As tabs close, the selection in the tabstrip // changes which notifies observers, which can use this as an optimization to // avoid doing meaningless or unhelpful work. bool closing_all() const { return closing_all_; } // Access the order controller. Exposed only for unit tests. TabStripModelOrderController* order_controller() const { return order_controller_; } // Sets the insertion policy. Default is INSERT_AFTER. void SetInsertionPolicy(InsertionPolicy policy); InsertionPolicy insertion_policy() const; // Returns true if |observer| is in the list of observers. This is intended // for debugging. bool HasObserver(TabStripModelObserver* observer); // Basic API ///////////////////////////////////////////////////////////////// // Determines if the specified index is contained within the TabStripModel. bool ContainsIndex(int index) const; // Adds the specified TabContents in the default location. Tabs opened in the // foreground inherit the group of the previously active tab. void AppendTabContents(TabContentsWrapper* contents, bool foreground); // Adds the specified TabContents at the specified location. |add_types| is a // bitmask of AddTypes; see it for details. // // All append/insert methods end up in this method. // // NOTE: adding a tab using this method does NOT query the order controller, // as such the ADD_FORCE_INDEX AddType is meaningless here. The only time the // |index| is changed is if using the index would result in breaking the // constraint that all mini-tabs occur before non-mini-tabs. // See also AddTabContents. void InsertTabContentsAt(int index, TabContentsWrapper* contents, int add_types); // Closes the TabContents at the specified index. This causes the TabContents // to be destroyed, but it may not happen immediately (e.g. if it's a // TabContents). |close_types| is a bitmask of CloseTypes. // Returns true if the TabContents was closed immediately, false if it was not // closed (we may be waiting for a response from an onunload handler, or // waiting for the user to confirm closure). bool CloseTabContentsAt(int index, uint32 close_types); // Replaces the entire state of a the tab at index by switching in a // different NavigationController. This is used through the recently // closed tabs list, which needs to replace a tab's current state // and history with another set of contents and history. // // The old NavigationController is deallocated and this object takes // ownership of the passed in controller. // XXXPINK This API is weird and wrong. Remove it or change it or rename it? void ReplaceNavigationControllerAt(int index, TabContentsWrapper* contents); // Replaces the tab contents at |index| with |new_contents|. The // TabContentsWrapper that was at |index| is returned and ownership returns // to the caller. TabContentsWrapper* ReplaceTabContentsAt(int index, TabContentsWrapper* new_contents); // Detaches the TabContents at the specified index from this strip. The // TabContents is not destroyed, just removed from display. The caller is // responsible for doing something with it (e.g. stuffing it into another // strip). TabContentsWrapper* DetachTabContentsAt(int index); // Makes the tab at the specified index the active tab. |user_gesture| is true // if the user actually clicked on the tab or navigated to it using a keyboard // command, false if the tab was activated as a by-product of some other // action. void ActivateTabAt(int index, bool user_gesture); // Move the TabContents at the specified index to another index. This method // does NOT send Detached/Attached notifications, rather it moves the // TabContents inline and sends a Moved notification instead. // If |select_after_move| is false, whatever tab was selected before the move // will still be selected, but it's index may have incremented or decremented // one slot. // NOTE: this does nothing if the move would result in app tabs and non-app // tabs mixing. void MoveTabContentsAt(int index, int to_position, bool select_after_move); // Moves the selected tabs to |index|. |index| is treated as if the tab strip // did not contain any of the selected tabs. For example, if the tabstrip // contains [A b c D E f] (upper case selected) and this is invoked with 1 the // result is [b A D E c f]. // This method maintains that all mini-tabs occur before non-mini-tabs. When // mini-tabs are selected the move is processed in two chunks: first mini-tabs // are moved, then non-mini-tabs are moved. If the index is after // (mini-tab-count - selected-mini-tab-count), then the index the non-mini // selected tabs are moved to is (index + selected-mini-tab-count). For // example, if the model consists of [A b c D E f] (A b c are mini) and this // is inokved with 2, the result is [b c A D E f]. In this example nothing // special happened because the target index was <= (mini-tab-count - // selected-mini-tab-count). If the target index were 3, then the result would // be [b c A f D F]. A, being mini, can move no further than index 2. The // non-mini-tabs are moved to the target index + selected-mini-tab-count (3 + // 1) void MoveSelectedTabsTo(int index); // Returns the currently active TabContents, or NULL if there is none. TabContentsWrapper* GetActiveTabContents() const; // Returns the TabContentsWrapper at the specified index, or NULL if there is // none. TabContentsWrapper* GetTabContentsAt(int index) const; // Returns the index of the specified TabContents wrapper, or // TabStripModel::kNoTab if the TabContents is not in this TabStripModel. int GetIndexOfTabContents(const TabContentsWrapper* contents) const; // Returns the index of the specified TabContents wrapper given its raw // TabContents, or TabStripModel::kNoTab if the TabContents is not in this // TabStripModel. Note: This is only needed in rare cases where the wrapper // is not already present (such as implementing TabContentsDelegate methods, // which don't know about the wrapper. Returns NULL if |contents| is not // associated with any wrapper in the model. int GetWrapperIndex(const TabContents* contents) const; // Returns the index of the specified NavigationController, or kNoTab if it is // not in this TabStripModel. int GetIndexOfController(const NavigationController* controller) const; // Notify any observers that the TabContents at the specified index has // changed in some way. See TabChangeType for details of |change_type|. void UpdateTabContentsStateAt( int index, TabStripModelObserver::TabChangeType change_type); // Make sure there is an auto-generated New Tab tab in the TabStripModel. // If |force_create| is true, the New Tab will be created even if the // preference is set to false (used by startup). void EnsureNewTabVisible(bool force_create); // Close all tabs at once. Code can use closing_all() above to defer // operations that might otherwise by invoked by the flurry of detach/select // notifications this method causes. void CloseAllTabs(); // Returns true if there are any TabContents that are currently loading. bool TabsAreLoading() const; // Returns the controller controller that opened the TabContents at |index|. NavigationController* GetOpenerOfTabContentsAt(int index); // Returns the index of the next TabContents in the sequence of TabContentses // spawned by the specified NavigationController after |start_index|. // If |use_group| is true, the group property of the tab is used instead of // the opener to find the next tab. Under some circumstances the group // relationship may exist but the opener may not. int GetIndexOfNextTabContentsOpenedBy(const NavigationController* opener, int start_index, bool use_group) const; // Returns the index of the first TabContents in the model opened by the // specified opener. int GetIndexOfFirstTabContentsOpenedBy(const NavigationController* opener, int start_index) const; // Returns the index of the last TabContents in the model opened by the // specified opener, starting at |start_index|. int GetIndexOfLastTabContentsOpenedBy(const NavigationController* opener, int start_index) const; // Called by the Browser when a navigation is about to occur in the specified // TabContents. Depending on the tab, and the transition type of the // navigation, the TabStripModel may adjust its selection and grouping // behavior. void TabNavigating(TabContentsWrapper* contents); // Forget all Opener relationships that are stored (but _not_ group // relationships!) This is to reduce unpredictable tab switching behavior // in complex session states. The exact circumstances under which this method // is called are left up to the implementation of the selected // TabStripModelOrderController. void ForgetAllOpeners(); // Forgets the group affiliation of the specified TabContents. This should be // called when a TabContents that is part of a logical group of tabs is // moved to a new logical context by the user (e.g. by typing a new URL or // selecting a bookmark). This also forgets the opener, which is considered // a weaker relationship than group. void ForgetGroup(TabContentsWrapper* contents); // Returns true if the group/opener relationships present for |contents| // should be reset when _any_ selection change occurs in the model. bool ShouldResetGroupOnSelect(TabContentsWrapper* contents) const; // Changes the blocked state of the tab at |index|. void SetTabBlocked(int index, bool blocked); // Is the tab a mini-tab? // See description above class for details on this. bool IsMiniTab(int index) const; // Returns true if the tab at |index| is blocked by a tab modal dialog. bool IsTabBlocked(int index) const; // Returns the index of the first tab that is not a mini-tab. This returns // |count()| if all of the tabs are mini-tabs, and 0 if none of the tabs are // mini-tabs. int IndexOfFirstNonMiniTab() const; // Returns a valid index for inserting a new tab into this model. |index| is // the proposed index and |mini_tab| is true if inserting a tab will become // mini (pinned or app). If |mini_tab| is true, the returned index is between // 0 and IndexOfFirstNonMiniTab. If |mini_tab| is false, the returned index // is between IndexOfFirstNonMiniTab and count(). int ConstrainInsertionIndex(int index, bool mini_tab); // Extends the selection from the anchor to |index|. void ExtendSelectionTo(int index); // Toggles the selection at |index|. This does nothing if |index| is selected // and there are no other selected tabs. void ToggleSelectionAt(int index); // Makes sure the tabs from the anchor to |index| are selected. This only // adds to the selection. void AddSelectionFromAnchorTo(int index); // Returns true if the tab at |index| is selected. bool IsTabSelected(int index) const; // Sets the selection to match that of |source|. void SetSelectionFromModel(const TabStripSelectionModel& source); const TabStripSelectionModel& selection_model() const { return selection_model_; } // Command level API ///////////////////////////////////////////////////////// // Adds a TabContents at the best position in the TabStripModel given the // specified insertion index, transition, etc. |add_types| is a bitmask of // AddTypes; see it for details. This method ends up calling into // InsertTabContentsAt to do the actual inertion. void AddTabContents(TabContentsWrapper* contents, int index, int add_types); // Closes the selected tabs. void CloseSelectedTabs(); // Select adjacent tabs void SelectNextTab(); void SelectPreviousTab(); // Selects the last tab in the tab strip. void SelectLastTab(); // Swap adjacent tabs. void MoveTabNext(); void MoveTabPrevious(); // Notifies the observers that the active/foreground tab at |index| was // reselected (ie - it was already active and was clicked again). void ActiveTabClicked(int index); // View API ////////////////////////////////////////////////////////////////// // Context menu functions. enum ContextMenuCommand { CommandFirst = 0, CommandNewTab, CommandReload, CommandDuplicate, CommandCloseTab, CommandCloseOtherTabs, CommandCloseTabsToRight, CommandRestoreTab, CommandBookmarkAllTabs, CommandUseVerticalTabs, CommandUseCompactNavigationBar, CommandSelectByDomain, CommandSelectByOpener, CommandLast }; // Returns true if the specified command is enabled. If |context_index| is // selected the response applies to all selected tabs. bool IsContextMenuCommandEnabled(int context_index, ContextMenuCommand command_id) const; // Returns true if the specified command is checked. bool IsContextMenuCommandChecked(int context_index, ContextMenuCommand command_id) const; // Performs the action associated with the specified command for the given // TabStripModel index |context_index|. If |context_index| is selected the // command applies to all selected tabs. void ExecuteContextMenuCommand(int context_index, ContextMenuCommand command_id); // Returns a vector of indices of the tabs that will close when executing the // command |id| for the tab at |index|. The returned indices are sorted in // descending order. std::vector<int> GetIndicesClosedByCommand(int index, ContextMenuCommand id) const; // Convert a ContextMenuCommand into a browser command. Returns true if a // corresponding browser command exists, false otherwise. static bool ContextMenuCommandToBrowserCommand(int cmd_id, int* browser_cmd); private: // Gets the set of tab indices whose domain matches the tab at |index|. void GetIndicesWithSameDomain(int index, std::vector<int>* indices); // Gets the set of tab indices that have the same opener as the tab at // |index|. void GetIndicesWithSameOpener(int index, std::vector<int>* indices); // If |index| is selected all the selected indices are returned, otherwise a // vector with |index| is returned. This is used when executing commands to // determine which indices the command applies to. std::vector<int> GetIndicesForCommand(int index) const; // Returns true if the specified TabContents is a New Tab at the end of the // TabStrip. We check for this because opener relationships are _not_ // forgotten for the New Tab page opened as a result of a New Tab gesture // (e.g. Ctrl+T, etc) since the user may open a tab transiently to look up // something related to their current activity. bool IsNewTabAtEndOfTabStrip(TabContentsWrapper* contents) const; // Closes the TabContents at the specified indices. This causes the // TabContents to be destroyed, but it may not happen immediately. If the // page in question has an unload event the TabContents will not be destroyed // until after the event has completed, which will then call back into this // method. // // Returns true if the TabContents were closed immediately, false if we are // waiting for the result of an onunload handler. bool InternalCloseTabs(const std::vector<int>& in_indices, uint32 close_types); // Invoked from InternalCloseTabs and when an extension is removed for an app // tab. Notifies observers of TabClosingAt and deletes |contents|. If // |create_historical_tabs| is true, CreateHistoricalTab is invoked on the // delegate. // // The boolean parameter create_historical_tab controls whether to // record these tabs and their history for reopening recently closed // tabs. void InternalCloseTab(TabContentsWrapper* contents, int index, bool create_historical_tabs); TabContentsWrapper* GetContentsAt(int index) const; // Notifies the observers if the active tab has changed. If |old_contents| is // non-null a TabDeactivated notification is sent right before sending // ActiveTabChanged notification. void NotifyIfActiveTabChanged(TabContentsWrapper* old_contents, bool user_gesture); // Notifies the observers if the active tab or the tab selection has changed. // If |old_contents| is non-null a TabDeactivated notification is sent right // before sending ActiveTabChanged notification. |old_model| is a snapshot of // |selection_model_| before the change. // Note: This function might end up sending 0 to 3 notifications in the // following order: TabDeactivated, ActiveTabChanged, TabSelectionChanged. void NotifyIfActiveOrSelectionChanged( TabContentsWrapper* old_contents, bool user_gesture, const TabStripSelectionModel& old_model); // Returns the number of New Tab tabs in the TabStripModel. int GetNewTabCount() const; // Selects either the next tab (|foward| is true), or the previous tab // (|forward| is false). void SelectRelativeTab(bool forward); // Does the work of MoveTabContentsAt. This has no checks to make sure the // position is valid, those are done in MoveTabContentsAt. void MoveTabContentsAtImpl(int index, int to_position, bool select_after_move); // Implementation of MoveSelectedTabsTo. Moves |length| of the selected tabs // starting at |start| to |index|. See MoveSelectedTabsTo for more details. void MoveSelectedTabsToImpl(int index, size_t start, size_t length); // Returns true if the tab represented by the specified data has an opener // that matches the specified one. If |use_group| is true, then this will // fall back to check the group relationship as well. struct TabContentsData; static bool OpenerMatches(const TabContentsData* data, const NavigationController* opener, bool use_group); // Sets the group/opener of any tabs that reference |tab| to NULL. void ForgetOpenersAndGroupsReferencing(const NavigationController* tab); // Our delegate. TabStripModelDelegate* delegate_; // A hunk of data representing a TabContents and (optionally) the // NavigationController that spawned it. This memory only sticks around while // the TabContents is in the current TabStripModel, unless otherwise // specified in code. struct TabContentsData { explicit TabContentsData(TabContentsWrapper* a_contents) : contents(a_contents), reset_group_on_select(false), blocked(false) { SetGroup(NULL); } // Create a relationship between this TabContents and other TabContentses. // Used to identify which TabContents to select next after one is closed. void SetGroup(NavigationController* a_group) { group = a_group; opener = a_group; } // Forget the opener relationship so that when this TabContents is closed // unpredictable re-selection does not occur. void ForgetOpener() { opener = NULL; } TabContentsWrapper* contents; // We use NavigationControllers here since they more closely model the // "identity" of a Tab, TabContents can change depending on the URL loaded // in the Tab. // The group is used to model a set of tabs spawned from a single parent // tab. This value is preserved for a given tab as long as the tab remains // navigated to the link it was initially opened at or some navigation from // that page (i.e. if the user types or visits a bookmark or some other // navigation within that tab, the group relationship is lost). This // property can safely be used to implement features that depend on a // logical group of related tabs. NavigationController* group; // The owner models the same relationship as group, except it is more // easily discarded, e.g. when the user switches to a tab not part of the // same group. This property is used to determine what tab to select next // when one is closed. NavigationController* opener; // True if our group should be reset the moment selection moves away from // this Tab. This is the case for tabs opened in the foreground at the end // of the TabStrip while viewing another Tab. If these tabs are closed // before selection moves elsewhere, their opener is selected. But if // selection shifts to _any_ tab (including their opener), the group // relationship is reset to avoid confusing close sequencing. bool reset_group_on_select; // Is the tab interaction blocked by a modal dialog? bool blocked; }; // The TabContents data currently hosted within this TabStripModel. typedef std::vector<TabContentsData*> TabContentsDataVector; // TODO(eroman): Temporary for investigating 93747. class Padding { public: Padding(); void CheckValid() const; private: char bytes_[32]; }; // Surround contents_data_ with some extra bytes to try and catch external // mutation of this memory. This is temporary for debugging 93747. Padding padding1_; TabContentsDataVector contents_data_; Padding padding2_; // This is temporary for debugging 93747. void CheckIsAliveAndWell() const; // True if all tabs are currently being closed via CloseAllTabs. bool closing_all_; // An object that determines where new Tabs should be inserted and where // selection should move when a Tab is closed. TabStripModelOrderController* order_controller_; // Our observers. typedef ObserverList<TabStripModelObserver> TabStripModelObservers; TabStripModelObservers observers_; TabStripSelectionModel selection_model_; uint32 magic_id_; DISALLOW_IMPLICIT_CONSTRUCTORS(TabStripModel); }; #endif //__tab_strip_model_h__
[ [ [ 1, 635 ] ] ]
3da99187d1a4fdf9932a4f232c7b8d31a40da650
17558c17dbc37842111466c43add5b31e3f1b29b
/device/serialgps.cpp
bd193f515f6dfc33440e8a042a3d119ac9da066c
[]
no_license
AeroWorks/inav
5c61b6c7a5af1a3f99009de8e177a2ceff3447b0
5a97aaca791026d9a09c2273c37e237b18b9cb35
refs/heads/master
2020-09-05T23:45:11.561252
2011-04-24T01:53:22
2011-04-24T01:53:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
56
cpp
#include "serialgps.h" SerialGPS::SerialGPS() { }
[ [ [ 1, 5 ] ] ]
d1e05389f1d48f2f464a233d217cb011d052632b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/Memory/Allocator/FreeList/FixedMemoryBlockServer/hkFixedMemoryBlockServer.h
73eaef5a286c8f5394c0c3834c24fa22681e9d76
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,155
h
/* * * 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-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_FIXED_MEMORY_BLOCK_SERVER_H #define HK_FIXED_MEMORY_BLOCK_SERVER_H #include <Common/Base/Memory/Allocator/FreeList/hkLargeBlockAllocator.h> /// Supplies memory to the hkLargeBlockAllocator from a single large block. class hkFixedMemoryBlockServer : public hkMemoryBlockServer { public: HK_DECLARE_PLACEMENT_ALLOCATOR(); /// Give it a block of memory you want it to use. Will automatically align in ctor - but that means /// m_start may not be the start you passed in if it wasn't aligned. hkFixedMemoryBlockServer(void* start,hk_size_t size, hkMemoryAllocator* critical); /// implementing hkMemoryBlockServer virtual hkBool isSingleBlockServer() { return true; } virtual hk_size_t recommendSize(hk_size_t size); virtual void* allocate(hk_size_t size,hk_size_t& sizeOut); virtual void free(void* data,hk_size_t size); virtual hkBool resize(void* data,hk_size_t oldSize,hk_size_t newSize,hk_size_t& sizeOut); /// Returns the total amount of memory available from this allocator. In this case that will just be the memory remaining /// from the break to the end virtual hk_size_t getTotalAvailableMemory(); /// Get the memory limit virtual hk_size_t getMemoryLimit(); /// Set the memory limit virtual hkBool setMemoryLimit(hk_size_t size); virtual void* criticalAlloc(hk_size_t size); virtual void criticalFree(void* data,hk_size_t size); /// Is 16 byte aligned char* m_start; /// The end address in bytes char* m_end; /// Where the limit is currently set to char* m_limit; /// The current break point (the boundary between allocated and unallocated) char* m_break; /// Where critical allocations are routed to. hkMemoryAllocator* m_critical; }; #endif // HK_FIXED_MEMORY_BLOCK_SERVER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * 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. * */
[ [ [ 1, 68 ] ] ]
9bb9ebc31a7f6731b4d65c5975fe89b9c2820338
aa5491d8b31750da743472562e85dd4987f1258a
/Main/server/vehiclepool.h
39882acd1b292934e366b16f8ba9df997ddffa5c
[]
no_license
LBRGeorge/jmnvc
d841ad694eaa761d0a45ab95b210758c50750d17
064402f0a9f1536229b99cf45f6e7536e1ae7bb5
refs/heads/master
2016-08-04T03:12:18.402941
2009-05-31T18:40:42
2009-05-31T18:40:42
39,416,169
2
0
null
null
null
null
UTF-8
C++
false
false
1,964
h
//---------------------------------------------------- // // GPL code license: // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // //---------------------------------------------------- // // VC:MP Multiplayer Modification For GTA:VC // Copyright 2004-2005 SA:MP team // // File Author: kyeman // //---------------------------------------------------- #pragma once //---------------------------------------------------- class CVehiclePool { private: BOOL m_bVehicleSlotState[MAX_VEHICLES]; CVehicle *m_pVehicles[MAX_VEHICLES]; public: CVehiclePool(); ~CVehiclePool(); BOOL New(BYTE byteVehicleID, BYTE byteVehicleType, VECTOR * vecPos, float fRotation, int iColor1, int iColor2); BOOL Delete(BYTE byteVehicleID); // Retrieve a vehicle by id CVehicle* GetAt(BYTE byteVehicleID) { if(byteVehicleID > MAX_VEHICLES) { return NULL; } return m_pVehicles[byteVehicleID]; }; int GetTotal(void) { return sizeof(m_pVehicles); }; // Find out if the slot is inuse. BOOL GetSlotState(BYTE byteVehicleID) { if(byteVehicleID > MAX_VEHICLES) { return FALSE; } return m_bVehicleSlotState[byteVehicleID]; }; BOOL InitialiseFromConfig(CConfig *pConfig); void Process(); }; //----------------------------------------------------
[ "jacks.mini.net@45e629aa-34f5-11de-82fb-7f665ef830f7" ]
[ [ [ 1, 66 ] ] ]
6f8695707b2aa3b437992a8071a45691410a830d
86ba0e8b9e5cc221460413e6efdc9cfcd4e8b618
/lista_pokazivaci.cpp
667d03fac9ea6de048a4e3012dfb4f46c9221426
[]
no_license
program/Programski-kod
f1398e3e9bc6c8e74460bc1dc0e88071b0473e69
6a3bcc10bd88e1b8e8a1001fc4e541d0fc41338e
refs/heads/master
2016-09-05T14:31:24.208963
2010-10-22T19:24:19
2010-10-22T19:24:19
1,015,787
0
1
null
null
null
null
UTF-8
C++
false
false
4,595
cpp
#include<iostream> #include<cstring> #include<iomanip> using namespace std; typedef int element; struct lista{ char maticni[14]; char iprez[30]; int godina; lista *sljedeci; }; typedef lista *liste; int br=0; liste FirstL(lista *L){ L=new lista; L->sljedeci=NULL; return (L->sljedeci); } liste EndL(lista *L){ lista *list; list=L; while(list->sljedeci) list=list->sljedeci; return list; } int LocateL(char x[],int p,lista *L){ L->sljedeci=NULL; if(p>0){ L->sljedeci=NULL; lista *tekuci; tekuci=L->sljedeci; while(tekuci){ if(strcmp(tekuci->maticni,x)==0)return 0; else tekuci=tekuci->sljedeci; } }} int InsertL(char x[],int y,char iprez[],element p, lista *L){ if(p==0) L->sljedeci=NULL; lista *novi,*zadnji; zadnji=L; while(zadnji->sljedeci) zadnji=zadnji->sljedeci; novi=new lista; zadnji->sljedeci=novi; novi->sljedeci=NULL; strcpy(novi->maticni,x); strcpy(novi->iprez,iprez); novi->godina=y; } liste RetrieveL(int p,lista *L){ lista *prethodni,*tekuci,*dalje; int zamjena; do{ zamjena=0; prethodni=L; tekuci=L->sljedeci; while(tekuci->sljedeci){ dalje=tekuci->sljedeci; if(strcmp((tekuci->maticni),(dalje->maticni))==1){ prethodni->sljedeci=dalje; tekuci->sljedeci=dalje->sljedeci; dalje->sljedeci=tekuci; zamjena=1; } prethodni=prethodni->sljedeci; tekuci=prethodni->sljedeci; } }while(zamjena==1); lista *ispis=L->sljedeci; while(ispis){ cout << ispis->maticni << "\t\t" << ispis->iprez << "\t\t" << ispis->godina << endl; ispis=ispis->sljedeci; } cout << endl; } liste DeleteL(int p,char mat[], lista *L){ lista *novi,*zadnji; zadnji=L; lista *prethodni=L; lista *brisi=L->sljedeci; while(brisi){ if(strcmp(brisi->maticni,mat)==0){ prethodni->sljedeci=brisi->sljedeci; delete brisi; cout << "Uspjesno izbrisano..." << endl; return 0; } prethodni=brisi; brisi=brisi->sljedeci; } if(brisi==0)cout << "Pacijent nije jos uveden!" << endl; } liste Retrieve_18(int p, lista *L){ lista *prethodni,*tekuci,*sljedeci; int zamjena; do{ zamjena=0; prethodni=L; tekuci=prethodni->sljedeci; while(tekuci->sljedeci){ sljedeci=tekuci->sljedeci; if(tekuci->maticni>sljedeci->maticni){ prethodni->sljedeci=sljedeci; tekuci->sljedeci=sljedeci->sljedeci; sljedeci->sljedeci=tekuci; zamjena=1; } prethodni=prethodni->sljedeci; tekuci=prethodni->sljedeci;} }while(zamjena==1); lista *ispis=L->sljedeci; while(ispis){ if((ispis->godina)<18){ cout << ispis->maticni<< "\t\t" << ispis->iprez << "\t\t" << ispis->godina<<endl; } ispis=ispis->sljedeci; } }
[ [ [ 1, 126 ] ] ]
57a71147f5bd9ec0918aaa62d54790a51595ef05
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/System/Error/hkError.h
5d68c8895a1e6df2274a2c9fb3d2b08a3f4f8cf5
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
11,759
h
/* * * 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-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKBASE_HKERROR_H #define HKBASE_HKERROR_H /// Class with static methods to provide hooks to error reporting functions /// You can redirect all asserts, errors and warnings by setting the handlers /// at run time. Asserts and Warnings are only compiled into debug builds. /// Errors are compiled in all builds. See hkDefaultError.h for a sample implementation /// of the handlers. class hkError : public hkReferencedObject, public hkSingleton<hkError> { public: enum Message { MESSAGE_REPORT, MESSAGE_WARNING, MESSAGE_ASSERT, MESSAGE_ERROR }; /// Return value indicates whether or not to trigger an HK_BREAKPOINT for errors and asserts. virtual int message(Message m, int id, const char* description, const char* file, int line) = 0; /// Enables/disables diagnostic by id. virtual void setEnabled( int id, hkBool enabled ) = 0; /// Enables/disables diagnostic by id. virtual hkBool isEnabled( int id ) = 0; /// Force all diagnostics to be enabled. virtual void enableAll() = 0; /// Begin a new report section virtual void sectionBegin(int id, const char* sectionName) {} /// End the current report section virtual void sectionEnd() {} }; #if !defined(HK_PLATFORM_PS3_SPU) class hkErrStream : public hkOstream { public: hkErrStream( void* buf, int bufSize ); }; typedef void (HK_CALL *hkErrorReportFunction)(const char* s, void* errorReportObject); #endif namespace hkCompileError { // Generic compile time failure template <bool b> struct COMPILE_ASSERTION_FAILURE; template <> struct COMPILE_ASSERTION_FAILURE<true>{ }; // The reflection parser and the compile time check disagree about whether a class has a vtable. // The script may not have detected that a class has a vtable. e.g. no virtual methods // declared in the body. In this case add //+virtual(true) at the start of the class definition. // Otherwise, the compile time vtable check may have failed if the object does not inherit from hkBaseObject. // In this case, you can mark the base class as virtual by adding the declaration // "hkBool::YesType hkIsVirtual(MyClass*);" after the class definition. A function body is not needed. template <bool b> struct REFLECTION_PARSER_VTABLE_DETECTION_FAILED; template <> struct REFLECTION_PARSER_VTABLE_DETECTION_FAILED<true>{ }; } /// Cause a compile error if the assert fails. /// Note: Use this only in c++ files, not header files as this macro introduces a symbol based on the line number. #define HK_COMPILE_TIME_ASSERT(a) enum { HK_PREPROCESSOR_JOIN_TOKEN(compile_time_assert_, __LINE__) \ = sizeof(hkCompileError::COMPILE_ASSERTION_FAILURE<bool(a)>) } /// Compile time assert with an error message. /// The MSG argument should give a hint about why the assert failed as the cause may not be apparent /// from the compile error. MSG should be defined in the hkCompileError namespace /// Note: Use this only in c++ files, not header files as this macro introduces a symbol based on the line number. #define HK_COMPILE_TIME_ASSERT2(a,MSG) enum { HK_PREPROCESSOR_JOIN_TOKEN(compile_time_assert_, __LINE__) \ = sizeof(hkCompileError::MSG<bool(a)>) } #define HK_REPORT_SECTION_BEGIN(id, name) hkError::getInstance().sectionBegin(id, name); #define HK_REPORT_SECTION_END() hkError::getInstance().sectionEnd(); // asserts and warnings may be compiled out #if !defined (HK_PLATFORM_PS3_SPU) # define HK_WARN_ALWAYS(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ char assertBuf[512]; \ hkErrStream ostr(assertBuf, sizeof(assertBuf)); \ ostr << TEXT; \ hkError::getInstance().message(hkError::MESSAGE_WARNING, id, assertBuf, __FILE__, __LINE__); \ HK_MULTILINE_MACRO_END # define HK_ERROR(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ char assertBuf[512]; \ hkErrStream ostr(assertBuf,sizeof(assertBuf)); \ ostr << TEXT; \ if ( hkError::getInstance().message(hkError::MESSAGE_ERROR, id, assertBuf, __FILE__, __LINE__) ) \ { \ HK_BREAKPOINT(id); \ } \ HK_MULTILINE_MACRO_END # define HK_REPORT(TEXT) HK_MULTILINE_MACRO_BEGIN \ char reportBuf[512]; \ hkErrStream ostr(reportBuf,sizeof(reportBuf)); \ ostr << TEXT; \ hkError::getInstance().message(hkError::MESSAGE_REPORT, -1, reportBuf, __FILE__, __LINE__); \ HK_MULTILINE_MACRO_END # define HK_REPORT2(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ char reportBuf[512]; \ hkErrStream ostr(reportBuf,sizeof(reportBuf)); \ ostr << TEXT; \ hkError::getInstance().message(hkError::MESSAGE_REPORT, id, reportBuf, __FILE__, __LINE__); \ HK_MULTILINE_MACRO_END # if defined HK_DEBUG // NOSPU + DEBUG # define HK_ASSERT(id, a) HK_MULTILINE_MACRO_BEGIN \ if ( !(a) ) \ { \ if( hkError::getInstance().message(hkError::MESSAGE_ASSERT, id, #a,__FILE__,__LINE__) ) \ { \ HK_BREAKPOINT(0); \ } \ } \ HK_MULTILINE_MACRO_END # define HK_ASSERT2(id, a, TEXT) HK_MULTILINE_MACRO_BEGIN \ if ( !(a) ) \ { \ char assertBuf[512]; \ hkErrStream ostr(assertBuf, sizeof(assertBuf)); \ ostr << #a << "\n"; \ ostr << TEXT; \ if( hkError::getInstance().message(hkError::MESSAGE_ASSERT, id, assertBuf,__FILE__, __LINE__) ) \ { \ HK_BREAKPOINT(0); \ } \ } \ HK_MULTILINE_MACRO_END # define HK_WARN(id, TEXT) HK_WARN_ALWAYS (id, TEXT) # define HK_WARN_ONCE(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ if ( hkError::getInstance().isEnabled(id) ) \ { \ char assertBuf[512]; \ hkErrStream ostr( assertBuf, sizeof(assertBuf) ); \ ostr << TEXT; \ hkError::getInstance().getInstance().message(hkError::MESSAGE_WARNING, id, assertBuf, __FILE__, __LINE__); \ hkError::getInstance().setEnabled(id, false); \ } \ HK_MULTILINE_MACRO_END # else // NOSPU + RELEASE # define HK_WARN(id, a) //nothing # define HK_WARN_ONCE(id, a) //nothing # define HK_ASSERT(id, a) //nothing # define HK_ASSERT2(id, a, TEXT) //nothing # endif #else // defined (HK_PLATFORM_PS3_SPU) # include <sys/spu_event.h> # define HK_ERROR_FORWARD(what,id,text) sys_spu_thread_send_event( 31+what, hkUlong(0), id ) # define HK_WARN_ALWAYS(id, TEXT) HK_ERROR_FORWARD( hkError::MESSAGE_WARNING, id, hkUlong(0) ) # define HK_ERROR(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ HK_ERROR_FORWARD( hkError::MESSAGE_ERROR, id, hkUlong(0) ); \ HK_BREAKPOINT(id); \ HK_MULTILINE_MACRO_END # define HK_REPORT(TEXT) HK_ERROR_FORWARD( hkError::MESSAGE_REPORT, 0, hkUlong(TEXT) ) # define HK_REPORT2(id, TEXT) HK_ERROR_FORWARD( hkError::MESSAGE_REPORT, id, hkUlong(TEXT) ) # if defined (HK_DEBUG) // SPU+DEBUG # define HK_ASSERT(id, a) HK_MULTILINE_MACRO_BEGIN \ if ( !(a) ) \ { \ HK_ERROR_FORWARD( hkError::MESSAGE_ASSERT, id, hkUlong(0) ); \ HK_BREAKPOINT(id); \ } \ HK_MULTILINE_MACRO_END # define HK_ASSERT2(id, a, TEXT) HK_ASSERT(id,a) # define HK_WARN(id, TEXT) HK_ERROR_FORWARD( hkError::MESSAGE_WARNING, id, hkUlong(0) ) # define HK_WARN_ONCE(id, TEXT) HK_MULTILINE_MACRO_BEGIN \ static hkBool shown = false; \ if ( !shown ) \ { \ HK_WARN(id,TEXT); \ } \ HK_MULTILINE_MACRO_END # else // SPU+RELEASE # define HK_WARN(id, a) //nothing # define HK_WARN_ONCE(id, a) //nothing # define HK_ASSERT(id, a) //nothing # define HK_ASSERT2(id, a, TEXT) //nothing # endif #endif // Critical asserts - these will trigger breakpoints on the SPU. Additionally, they show up as comments in the assembly file. // On non-SPU platforms, they revert to normal asserts. #ifdef HK_PLATFORM_PS3_SPU # ifdef HK_DEBUG_SPU # define HK_CRITICAL_ASSERT2(id, a, msg) HK_MULTILINE_MACRO_BEGIN \ if ( !(a) ) \ { \ HK_ASM_SEP("\tHK_CRITICAL_ASSERT2(" #id ", " #a ", " #msg ");" ); \ HK_BREAKPOINT(id); \ } \ HK_MULTILINE_MACRO_END # define HK_CRITICAL_ASSERT(id, a) HK_MULTILINE_MACRO_BEGIN \ if ( !(a) ) \ { \ HK_ASM_SEP("\tHK_CRITICAL_ASSERT(" #id ", " #a ");" ); \ HK_BREAKPOINT(id); \ } \ HK_MULTILINE_MACRO_END # else // SPU HK_DEBUG_SPU # define HK_CRITICAL_ASSERT2(id, a, msg) # define HK_CRITICAL_ASSERT(id, a) # endif // SPU HK_DEBUG_SPU #else # define HK_CRITICAL_ASSERT HK_ASSERT # define HK_CRITICAL_ASSERT2 HK_ASSERT2 #endif #define HK_CHECK_ALIGN16(ADDR) HK_ASSERT(0xff00ff00, (hkUlong(ADDR) & 0xf) == 0 ) #define HK_WARN_IF(check,id,TEXT) HK_ON_DEBUG(if (check) HK_WARN(id,TEXT)) #define HK_WARN_ONCE_IF(check,id,TEXT) HK_ON_DEBUG(if (check) HK_WARN_ONCE(id,TEXT)) #endif // HKBASE_HKERROR_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * 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. * */
[ [ [ 1, 273 ] ] ]
8b8f5fc2e9f5a53a5f1623a814ed305c60e25f69
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/Dll.cpp
bc5c3cd0c9090aa4fd7b6336b03a959fc506aaf4
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <windows.h> #include <stdio.h> #include <tchar.h> #include <BWAPI.h> #include <BWTA.h> #include "UAlbertaBotModule.h" namespace BWAPI { Game* Broodwar; } BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: BWAPI::BWAPI_init(); break; case DLL_PROCESS_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule(BWAPI::Game* game) { BWAPI::Broodwar=game; return new UAlbertaBotModule(); }
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 35 ] ] ]