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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b55f1e184ae35b885caba05c8b47b4c3278b2d1
|
7b379862f58f587d9327db829ae4c6493b745bb1
|
/Source/NetworkReceiver.h
|
759f8baa86cc323cbeb9d4f9b213170ca949451a
|
[] |
no_license
|
owenvallis/Nomestate
|
75e844e8ab68933d481640c12019f0d734c62065
|
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
|
refs/heads/master
| 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,040 |
h
|
/*
==============================================================================
NetworkReceiver.h
Created: 10 Oct 2011 10:02:34pm
Author: Dimitri Diakopoulos
==============================================================================
*/
#ifndef __NETWORKRECEIVER_H_A93D66C4__
#define __NETWORKRECEIVER_H_A93D66C4__
#include "../JuceLibraryCode/JuceHeader.h"
#include "OSCListener.h"
#include "Signal.h"
#include <iostream>
//forward declaration resolves the circular dependancy
class MessageCenter;
class NetworkReceiver : public OSCListener,
public ValueListener
{
public:
NetworkReceiver(MessageCenter ¢er);
~NetworkReceiver();
void handleOSC();
void oscToSignal(OSCMessage msg);
void valueChanged(Value& value);
private:
Value serverListenPort;
MessageCenter *_mCenter;
JUCE_LEAK_DETECTOR(NetworkReceiver);
};
#endif // __NETWORKRECEIVER_H_A93D66C4__
|
[
"ow3nskip",
"[email protected]"
] |
[
[
[
1,
37
],
[
39,
46
]
],
[
[
38,
38
]
]
] |
fc35687c539acb71572a29633f5880f2e9229f77
|
74c8da5b29163992a08a376c7819785998afb588
|
/NetAnimal/Game/Hunter/NewGameComponent/NewGameSceneComponent/include/DotSceneLoader.h
|
67d41f4b84823bae26d050caa089960ef4724b0d
|
[] |
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 | 3,087 |
h
|
#ifndef DOT_SCENELOADER_H
#define DOT_SCENELOADER_H
#include <tinyxml/tinyxml.h>
// Includes
// Forward declarations
class TiXmlElement;
namespace Ogre
{
// Forward declarations
class SceneManager;
class SceneNode;
class nodeProperty
{
public:
String nodeName;
String propertyNm;
String valueName;
String typeName;
nodeProperty(const String &node, const String &propertyName, const String &value, const String &type)
: nodeName(node), propertyNm(propertyName), valueName(value), typeName(type) {}
};
class DotSceneLoader
{
public:
DotSceneLoader() : mSceneMgr(0) {}
virtual ~DotSceneLoader() {}
void parseDotScene(const String &SceneName, const String &groupName, SceneManager *yourSceneMgr, SceneNode *pAttachNode = NULL, const String &sPrependNode = "");
String getProperty(const String &ndNm, const String &prop);
std::vector<nodeProperty> nodeProperties;
std::vector<String> staticObjects;
std::vector<String> dynamicObjects;
protected:
void processScene(TiXmlElement *XMLRoot);
void processNodes(TiXmlElement *XMLNode);
void processExternals(TiXmlElement *XMLNode);
void processEnvironment(TiXmlElement *XMLNode);
void processTerrain(TiXmlElement *XMLNode);
void processUserDataReference(TiXmlElement *XMLNode, SceneNode *pParent = 0);
void processUserDataReference(TiXmlElement *XMLNode, Entity *pEntity);
void processOctree(TiXmlElement *XMLNode);
void processLight(TiXmlElement *XMLNode, SceneNode *pParent = 0);
void processCamera(TiXmlElement *XMLNode, SceneNode *pParent = 0);
void processNode(TiXmlElement *XMLNode, SceneNode *pParent = 0);
void processLookTarget(TiXmlElement *XMLNode, SceneNode *pParent);
void processTrackTarget(TiXmlElement *XMLNode, SceneNode *pParent);
void processEntity(TiXmlElement *XMLNode, SceneNode *pParent);
void processParticleSystem(TiXmlElement *XMLNode, SceneNode *pParent);
void processBillboardSet(TiXmlElement *XMLNode, SceneNode *pParent);
void processPlane(TiXmlElement *XMLNode, SceneNode *pParent);
void processFog(TiXmlElement *XMLNode);
void processSkyBox(TiXmlElement *XMLNode);
void processSkyDome(TiXmlElement *XMLNode);
void processSkyPlane(TiXmlElement *XMLNode);
void processClipping(TiXmlElement *XMLNode);
void processLightRange(TiXmlElement *XMLNode, Light *pLight);
void processLightAttenuation(TiXmlElement *XMLNode, Light *pLight);
String getAttrib(TiXmlElement *XMLNode, const String ¶meter, const String &defaultValue = "");
Real getAttribReal(TiXmlElement *XMLNode, const String ¶meter, Real defaultValue = 0);
bool getAttribBool(TiXmlElement *XMLNode, const String ¶meter, bool defaultValue = false);
Vector3 parseVector3(TiXmlElement *XMLNode);
Quaternion parseQuaternion(TiXmlElement *XMLNode);
ColourValue parseColour(TiXmlElement *XMLNode);
SceneManager *mSceneMgr;
SceneNode *mAttachNode;
String m_sGroupName;
String m_sPrependNode;
};
}
#endif // DOT_SCENELOADER_H
|
[
"[email protected]"
] |
[
[
[
1,
87
]
]
] |
c9d4b2168a0fc26512c90b6cfb4348a2f7df88a2
|
8daa399363892041aa491fac8403fb0f2c94d44f
|
/Apriori.cpp
|
6942c5f5d1e574d07d3fc5ba0779a6155b3ebb53
|
[] |
no_license
|
kumagi/merdy-mp
|
867428a4f2935bd437b93c548618de03cfc6c062
|
c4fa8daff4bc1ad08983b43fc84d9ef0d1db11c3
|
refs/heads/master
| 2021-01-22T20:08:46.344442 | 2010-07-09T13:27:12 | 2010-07-09T13:27:12 | 642,369 | 1 | 0 | null | null | null | null |
SHIFT_JIS
|
C++
| false | false | 5,024 |
cpp
|
#include "Apriori.h"
//output
std::ostream& operator<<(std::ostream& os, AprioriAlgorithm& a)
{
os << "<attribute name>\n";
for(int i=0; i<a.AttributeNum_; ++i){
os << a.AttributeName_[i] << " ";
}
os << "\n\n";
os << "<data> \n";
for(int i=0; i<a.TupleNum_; ++i){
for(int j=0; j<a.AttributeNum_; ++j){
os << a.Database_(i,j) << " ";
}
os << "\n";
}
os << "\n<min support>\n" << a.MinSupport_ << "\n";
return os;
}
bool AprioriAlgorithm::run(){
//cout << "TupleNum, AttributeNum = " << TupleNum_ << ", " << AttributeNum_ << endl;
// initialize
int c_col = 0;
int c_row = 0;
matrix<int> C; // candidates of frequent itemsets
int l_col = 0;
int l_row = 1;
L_.resize(1); // frequent itemsets
Sup_.resize(1); // support
//cout << "==========<1-terate>==========" << endl;
/* 1 - frequent itemsets */
for(int i=0; i<AttributeNum_; ++i){
// calculate support
stringstream ss;
ss << RULE_GET_COUNT << " " << AttributeName_[i] << " > 0";
//cout << ss.str().c_str() << endl;
//int count = Database.count(ss.str()); // カウント ***
int count = 0; //ここから5行は一時的なカウント kesu
for(int j=0; j<TupleNum_; ++j){
if(Database_(j,i) == 1){
++count;
}
}
// if support is greater than minsup -> frequent itemsets
double sup = (double)count/TupleNum_; //一時的
if(sup - MinSupport_ > -TOL){
++l_col;
L_[0].resize(l_col,l_row);
L_[0](l_col-1, 0) = i;
Sup_[0].resize(l_col);
Sup_[0][l_col-1] = sup;
}
//cout << "sup(" << i << ") = " << (double)count/TupleNum_ << endl;
}
//cout << "-----L(1)-----\n" << L_(0) << endl;
//cout<< "L size = " << l_col << " * " << l_row << endl;
for(int k=2; l_col>1; ++k){
//cout << "==========<" << k << "-iterate>==========" << endl;
// C init
c_col = 0;
c_row = k;
C.resize(c_col,c_row);
/* k - candidates */ // k-候補アイテム集合から計算(support)
for(int i=0; i<l_col; ++i){
for(int j=i+1; j<l_col; ++j){
for(int p=0; p<l_row; ++p){
if(p != l_row-1){ //最後以外は一致していて
if(L_[k-2](i,p)!=L_[k-2](j,p)) break;
}else{ //最後だけ違う場合、候補となる
++c_col;
C.resize(c_col,c_row);
for(int q=0; q<l_row; ++q) //まず、L(i,:)をコピー
C(c_col-1, q) = L_[k-2](i,q);
C(c_col-1, c_row-1) = L_[k-2](j,l_row-1); //そんで最後にL(j,:)の最後のアイテム
//今追加した部分集合が全て存在するか確認
int id_L = 0;
ublas::vector<int> subsetC(c_row-1); // Cの部分集合
for(int r=c_row-1; r>=0; --r){
for(int q=0; q<c_row-1; ++q){ // r番目がない部分集合
subsetC[q] = C(c_col-1, r<=q?q+1:q);
}
//cout << "subset " << subsetC << endl;
for(; id_L<l_col; ++id_L){ // (k-1)-LにsubsetCがあるかどうか
int q;
for(q=0; q<l_row; ++q){if(subsetC[q] != L_[k-2](id_L,q)) break;}
if(q==l_row){break;} //一致していたら次のsubset
}
}
if(id_L==l_col){ // (k-1)-Lに存在しないsubsetがある
//cout << "not find subset..." << subsetC << endl;
--c_col;
C.resize(c_col,c_row); //今追加したのを消す
}
}
}
}
}
//cout << "-----C("<< k <<")-----\n" << C << endl;
//cout<< "C size = " << c_col << " * " << c_row << endl;
// L init
l_col = 0;
l_row = c_row;
L_.resize(k);
L_[k-1].resize(l_col,l_row);
Sup_.resize(k);
/* k - frequent itemsets */ // k-候補アイテム集合から計算(support)
for(int j=0; j<c_col; ++j){ // 全C
// calculate support
stringstream ss;
ss << RULE_GET_COUNT;
for(int i=0; i<c_row; ++i){
if(i!=0) ss << " &";
ss << " " << AttributeName_[C(j,i)] << " > 0";
}
//cout << ss.str().c_str() << endl;
//int count = Database.count(ss.str()); // カウント
int count = TupleNum_; // カウントは最大から減らす
for(int p=0; p<TupleNum_; ++p){ // 全タプル
for(int i=0; i<c_row; ++i){ // Cの全要素
if(Database_(p,C(j,i)) == 0){ //指定されたアイテムがないならカウントを減らす
--count;
break;
}
}
}
//cout << "sup(" << j << ") = " << (double)count/TupleNum_ << endl;
//minsupより大きいなら頻出アイテム
double sup = (double)count/TupleNum_;
//cout<< sup<< endl;
if(sup - MinSupport_ > -TOL){
++l_col;
L_[k-1].resize(l_col,l_row);
for(int p=0; p<c_row; ++p){
L_[k-1](l_col-1, p) = C(j,p);
}
Sup_[k-1].resize(l_col);
Sup_[k-1][l_col-1] = sup;
}
}
//cout << "-----L("<< k <<")-----\n" << L_[k-1] << endl;
//cout<< "L size = " << l_col << " * " << l_row << endl;
// 頻出アイテム集合がないなら戻す
if(l_col==0){
L_.pop_back();
Sup_.pop_back();
}
}
return true;
}
|
[
"[email protected]"
] |
[
[
[
1,
173
]
]
] |
47ccdbe77c2501a53d7558bc1b41fbda398f715c
|
77aa13a51685597585abf89b5ad30f9ef4011bde
|
/dep/src/boost/boost/detail/spinlock_nt.hpp
|
05d9d516bc206047b639d80549b339b13ed5e89c
|
[] |
no_license
|
Zic/Xeon-MMORPG-Emulator
|
2f195d04bfd0988a9165a52b7a3756c04b3f146c
|
4473a22e6dd4ec3c9b867d60915841731869a050
|
refs/heads/master
| 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,523 |
hpp
|
#ifndef BOOST_DETAIL_SPINLOCK_NT_HPP_INCLUDED
#define BOOST_DETAIL_SPINLOCK_NT_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// Copyright (c) 2008 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/assert.hpp>
namespace boost
{
namespace detail
{
class spinlock
{
public:
bool locked_;
public:
inline bool try_lock()
{
if( locked_ )
{
return false;
}
else
{
locked_ = true;
return true;
}
}
inline void lock()
{
BOOST_ASSERT( !locked_ );
locked_ = true;
}
inline void unlock()
{
BOOST_ASSERT( locked_ );
locked_ = false;
}
public:
class scoped_lock
{
private:
spinlock & sp_;
scoped_lock( scoped_lock const & );
scoped_lock & operator=( scoped_lock const & );
public:
explicit scoped_lock( spinlock & sp ): sp_( sp )
{
sp.lock();
}
~scoped_lock()
{
sp_.unlock();
}
};
};
} // namespace detail
} // namespace boost
#define BOOST_DETAIL_SPINLOCK_INIT { false }
#endif // #ifndef BOOST_DETAIL_SPINLOCK_NT_HPP_INCLUDED
|
[
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] |
[
[
[
1,
89
]
]
] |
d1d2dc3169b8eff2b68cc42b34101e178a8e6806
|
39f755afd5f4f3abe91a24342746774781704fa7
|
/cob_sdh/common/include/cob_sdh/sdhbase.h
|
a22b66e92759240614e3c906a1773118bd1492ea
|
[] |
no_license
|
attilaachenbach/cob_driver
|
b1e280259521a47a07838a13fd35f218ae0c0f24
|
46acb2fe8114f04ce9909ef9488b6302d2530f9e
|
refs/heads/master
| 2021-01-15T20:48:35.405544 | 2011-04-29T17:28:25 | 2011-04-29T17:28:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,454 |
h
|
//======================================================================
/*!
\file
\section sdhlibrary_cpp_sdhbase_h_general General file information
\author Dirk Osswald
\date 2007-02-19
\brief
Interface of class #SDH::cSDHBase.
\section sdhlibrary_cpp_sdhbase_h_copyright Copyright
- Copyright (c) 2007 SCHUNK GmbH & Co. KG
<HR>
\internal
\subsection sdhlibrary_cpp_sdhbase_h_details SVN related, detailed file specific information:
$LastChangedBy: Osswald2 $
$LastChangedDate: 2009-06-17 10:55:45 +0200 (Mi, 17 Jun 2009) $
\par SVN file revision:
$Id: sdhbase.h 4605 2009-06-17 08:55:45Z Osswald2 $
\subsection sdhlibrary_cpp_sdhbase_h_changelog Changelog of this file:
\include sdhbase.h.log
*/
//======================================================================
#ifndef SDHBASE_H_
#define SDHBASE_H_
#include "sdhlibrary_settings.h"
#if SDH_USE_VCC
# pragma warning(disable : 4290)
#endif
//----------------------------------------------------------------------
// System Includes - include with <>
//----------------------------------------------------------------------
#include "iostream"
//----------------------------------------------------------------------
// Project Includes - include with ""
//----------------------------------------------------------------------
#include "dbg.h"
#include "sdhexception.h"
#include "simplevector.h"
//----------------------------------------------------------------------
// Defines, enums, unions, structs,
//----------------------------------------------------------------------
NAMESPACE_SDH_START
//----------------------------------------------------------------------
// Global variables
//----------------------------------------------------------------------
extern std::ostream* g_sdh_debug_log;
//----------------------------------------------------------------------
// Function declarations
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Class declarations
//----------------------------------------------------------------------
/*!
\brief Derived exception class for exceptions related to invalid parameters.
*/
class cSDHErrorInvalidParameter: public cSDHLibraryException
{
public:
cSDHErrorInvalidParameter( cMsg const & _msg )
: cSDHLibraryException( "cSDHErrorInvalidParameter", _msg )
{}
};
//======================================================================
/*!
\brief The base class to control the SCHUNK Dexterous Hand.
End-Users should \b NOT use this class directly, as it only provides
some common settings and no function interface.
End users should use the class cSDH instead, as it provides the
end-user functions to control the %SDH.
<hr>
*/
class cSDHBase
{
public:
//! Anonymous enum (instead of define like macros)
enum {
All = -1 //!< A meta-value that means "access all possible values"
};
/*!
The error codes of the %SDH firmware
\internal
In the %SDH firmware these enums are of type DSA_STAT
*/
enum eErrorCode
{
eEC_SUCCESS = 0,
eEC_NOT_AVAILABLE = 1,
eEC_NO_SENSOR = 2,
eEC_NOT_INITIALIZED = 3,
eEC_ALREADY_RUNNING = 4,
eEC_FEATURE_NOT_SUPPORTED = 5,
eEC_INCONSISTENT_DATA = 6,
eEC_TIMEOUT = 7,
eEC_READ_ERROR = 8,
eEC_WRITE_ERROR = 9,
eEC_INSUFFICIENT_RESOURCES = 10,
eEC_CHECKSUM_ERROR = 11,
eEC_NOT_ENOUGH_PARAMS = 12 ,
eEC_NO_PARAMS_EXPECTED = 13,
eEC_CMD_UNKNOWN = 14,
eEC_CMD_FORMAT_ERROR = 15,
eEC_ACCESS_DENIED = 16,
eEC_ALREADY_OPEN = 17,
eEC_CMD_FAILED = 18,
eEC_CMD_ABORTED = 19,
eEC_INVALID_HANDLE = 20,
eEC_DEVICE_NOT_FOUND = 21,
eEC_DEVICE_NOT_OPENED = 22,
eEC_IO_ERROR = 23,
eEC_INVALID_PARAMETER = 24,
eEC_RANGE_ERROR = 25,
eEC_NO_DATAPIPE = 26,
eEC_INDEX_OUT_OF_BOUNDS = 27,
eEC_HOMING_ERROR = 28,
eEC_AXIS_DISABLED = 29,
eEC_OVER_TEMPERATURE = 30,
eEC_DIMENSION //!< Endmarker and dimension
};
/*!
\brief The enum values of the known grasps
\internal
In the %SDH firmware these enums are of type TGRIP
*/
enum eGraspId
{
// ??? fehlt e vor enums:
eGID_INVALID = -1, //!< invalid grasp id
eGID_CENTRICAL = 0, //!< centrical grasp: ???
eGID_PARALLEL = 1, //!< parallel grasp: ???
eGID_CYLINDRICAL = 2, //!< cylindrical grasp: ???
eGID_SPHERICAL = 3, //!< spherecial grasp: ???
eGID_DIMENSION //!< Endmarker and dimension
};
//! An enum for all possible %SDH internal controller types (order must match that in the %SDH firmware in inc/sdh2.h)
enum eControllerType
{
eCT_INVALID = -1, //!< invalid controller_type (needed for cSDHSerial::con() to indicate "read current controller type")
eCT_POSE = 0, //!< coordinated position controller (position per axis => "pose controller"), all axes start and stop moving at the same time
eCT_VELOCITY, //!< velocity controller, velocities of axes are controlled independently (not implemented in %SDH firmwares up to and including 0.0.2.5)
eCT_VELOCITY_ACCELERATION, //!< velocity controller with acceleration ramp, velocities and accelerations of axes are controlled independently (not implemented in %SDH firmwares up to and including 0.0.2.5)
// TODO: not implemented yet
// eCT_POSITION, //!< position controller, positions of axes are controlled independently (not implemented in %SDH firmwares up to and including 0.0.2.5)
eCT_DIMENSION //!< Endmarker and dimension
};
//! An enum for all possible %SDH internal velocity profile types
enum eVelocityProfile
{
eVP_INVALID = -1, //!< not a valid velocity profile, used to make #SDH::cSDHSerial::vp() read the velocity profile from the %SDH firmware
eVP_SIN_SQUARE, //!< sin square velocity profile
eVP_RAMP, //!< ramp velocity profile
eVP_DIMENSION //!< endmarker and dimension
};
//-----------------------------------------------------------------
/*!
Constructor of cSDHBase class, initilize internal variables and settings
\param debug_level : debug level of the created object.
If the \a debug_level of an object is > 0 then
it will output debug messages.
- (Subclasses of cSDHBase like cSDH or cSDHSerial use additional settings, see there.)
*/
cSDHBase( int debug_level );
//-----------------------------------------------------------------
/*!
virtual destructor to make compiler happy
*/
virtual ~cSDHBase()
{}
//! Check if \a index is in [0 .. \a maxindex-1] or All. Throw a cSDHErrorInvalidParameter exception if not.
void CheckIndex( int index, int maxindex, char const* name="" )
throw (cSDHErrorInvalidParameter*);
//! Check if \a value is in [\a minvalue .. \a maxvalue]. Throw a cSDHErrorInvalidParameter exception if not.
void CheckRange( double value, double minvalue, double maxvalue, char const* name="" )
throw (cSDHErrorInvalidParameter*);
//! Check if any value[i] in array \a values is in [\a minvalue[i] .. \a maxvalue[i]]. Throw a cSDHErrorInvalidParameter exception if not.
void CheckRange( double* values, double* minvalues, double* maxvalues, char const* name="" )
throw (cSDHErrorInvalidParameter*);
//! Return a ptr to a (static) string describing error code \a error_code
static char const* GetStringFromErrorCode( eErrorCode error_code );
//! Return a ptr to a (static) string describing grasp id \a grasp_id
static char const* GetStringFromGraspId( eGraspId grasp_id );
//! Return a ptr to a (static) string describing controller type \a controller_Type
static char const* GetStringFromControllerType( eControllerType controller_type );
//! Return the number of axes of the %SDH
int GetNumberOfAxes( void );
//! Return the number of fingers of the %SDH
int GetNumberOfFingers( void );
//! Return the number of temperature sensors of the %SDH
int GetNumberOfTemperatureSensors( void );
//! Return the last known state of the %SDH firmware
eErrorCode GetFirmwareState( void );
//! Return the #eps value
double GetEps( void );
//! Return simple vector of number of axes epsilon values
cSimpleVector const & GetEpsVector( void );
//! Return true if connection to %SDH firmware/hardware is open
virtual bool IsOpen( void ) = 0;
//! change the stream to use for debug messages
virtual void SetDebugOutput( std::ostream* debuglog )
{
cdbg.SetOutput( debuglog );
}
protected:
//! debug stream to print colored debug messages
cDBG cdbg;
//! debug level of this object
int debug_level;
//! A mapping from #eErrorCode error code enums to strings with human readable error messages
static char const* firmware_error_codes[];
//! A mapping from #eGraspId grasp id enums to strings with human readable grasp id names
static char const* grasp_id_name[];
//! A mapping from #eControllerType controller type enums to strings with human readable controller type names
static char const* controller_type_name[];
//---------------------
//! The number of axes
int NUMBER_OF_AXES;
//! The number of fingers
int NUMBER_OF_FINGERS;
//! The number of temperature sensors
int NUMBER_OF_TEMPERATURE_SENSORS;
//! Bit field with the bits for all axes set
int all_axes_used;
//! the last known state of the %SDH firmware
eErrorCode firmware_state;
/*!
\brief epsilon value (max absolute deviation of reported values from actual hardware values)
(needed since %SDH firmware limits number of digits reported)
*/
double eps;
//! simple vector of 7 epsilon values
cSimpleVector eps_v;
//! simple vector of 7 0 values ???
//cSimpleVector zeros_v;
//! simple vector of 7 1 values ???
//cSimpleVector ones_v;
//! Minimum allowed axis angles (in internal units (degrees))
cSimpleVector min_angle_v;
//! Maximum allowed axis angles (in internal units (degrees))
cSimpleVector max_angle_v;
};
// end of class cSDHBase
//=====================================================================
NAMESPACE_SDH_END
#endif
//======================================================================
/*
Here are some settings for the emacs/xemacs editor (and can be safely ignored):
(e.g. to explicitely set C++ mode for *.h header files)
Local Variables:
mode:C++
mode:ELSE
End:
*/
//======================================================================
|
[
"[email protected]",
"wmb@cob3-2-pc1.(none)"
] |
[
[
[
1,
20
],
[
22,
22
],
[
24,
92
],
[
94,
107
],
[
109,
109
],
[
111,
152
],
[
154,
167
],
[
169,
170
],
[
178,
182
],
[
184,
185
],
[
187,
240
],
[
242,
244
],
[
246,
248
],
[
250,
252
],
[
254,
264
],
[
266,
276
],
[
279,
303
],
[
305,
308
],
[
310,
348
]
],
[
[
21,
21
],
[
23,
23
],
[
93,
93
],
[
108,
108
],
[
110,
110
],
[
153,
153
],
[
168,
168
],
[
171,
177
],
[
183,
183
],
[
186,
186
],
[
241,
241
],
[
245,
245
],
[
249,
249
],
[
253,
253
],
[
265,
265
],
[
277,
278
],
[
304,
304
],
[
309,
309
]
]
] |
445b903b584670bfa04c467b2b1c97d9b1e6782e
|
25f79693b806edb9041e3786fa3cf331d6fd4b97
|
/include/core/cal/IBuffer.h
|
29dc49bd69ea9ef59d7412c3ed7148bf1d51110f
|
[] |
no_license
|
ouj/amd-spl
|
ff3c9faf89d20b5d6267b7f862c277d16aae9eee
|
54b38e80088855f5e118f0992558ab88a7dea5b9
|
refs/heads/master
| 2016-09-06T03:13:23.993426 | 2009-08-29T08:55:02 | 2009-08-29T08:55:02 | 32,124,284 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 877 |
h
|
#ifndef AMDSPL_BUFFER_INTERFACE_H
#define AMDSPL_BUFFER_INTERFACE_H
namespace amdspl
{
namespace core
{
namespace cal
{
class Event;
class IBuffer
{
public:
virtual CALresource getResHandle() = 0;
virtual CALformat getFormat() = 0;
virtual unsigned int getWidth() = 0;
virtual unsigned int getHeight() = 0;
virtual bool setInputEvent(Event* e) = 0;
virtual bool setOutputEvent(Event* e) = 0;
virtual void waitInputEvent() = 0;
virtual void waitOutputEvent() = 0;
virtual bool isGlobal() = 0;
};
}
}
}
#endif //AMDSPL_BUFFER_INTERFACE_H
|
[
"jiawei.ou@1960d7c4-c739-11dd-8829-37334faa441c",
"probing@1960d7c4-c739-11dd-8829-37334faa441c"
] |
[
[
[
1,
27
]
],
[
[
28,
28
]
]
] |
9fccfea814d52cad1dc7a963bec0162434bab802
|
b230ac713508aa4ca17a2d57d8b7c4103e865f53
|
/TestSocket/TestClient/TestClient.cpp
|
d1303e6d876843bd509507fa46176bee3732bb06
|
[] |
no_license
|
KiraiChang/c-socket-lib
|
48716298d04e7e689b749a219f765d9d85dbbdfb
|
7e3f40777c907e20de8c846bc08c8396d9e351af
|
refs/heads/master
| 2016-09-06T21:31:48.036041 | 2010-05-25T15:09:17 | 2010-05-25T15:09:17 | 32,337,095 | 0 | 1 | null | null | null | null |
BIG5
|
C++
| false | false | 606 |
cpp
|
// TestClient.cpp : 定義主控台應用程式的進入點。
//
#include "stdafx.h"
#include<iostream>
#include "..\CSocket\CSocket.h"
#include "..\TestSocket\Packet.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CSocket c1;
Packet p1;
//p1.size = 100;
//strcpy_s(p1.message,sizeof("Hello"), "Hello");
c1.StartConnect("127.0.0.1", 5500);
while(c1.IsConnect())
{
//if(c1.ProcSend(&p1, sizeof(p1)))
// break;
cin>>p1.message;
c1.ProcSend(&p1, sizeof(p1));
if(strcmp(p1.message, "quit") == 0)
break;
p1.Init();
}
return 0;
}
|
[
"[email protected]@b409c5e8-2b4b-11df-b850-2185049e3855"
] |
[
[
[
1,
34
]
]
] |
e3775f3a19c72304f13c76cea52c8deade902a15
|
216ae2fd7cba505c3690eaae33f62882102bd14a
|
/utils/nxogre/include/NxOgreVisualDebugger.h
|
4f4f8e7c2297bd0622161be9899ce2e2465be554
|
[] |
no_license
|
TimelineX/balyoz
|
c154d4de9129a8a366c1b8257169472dc02c5b19
|
5a0f2ee7402a827bbca210d7c7212a2eb698c109
|
refs/heads/master
| 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 2,570 |
h
|
/** File: NxOgreXXX.h
Created on: X-XXX-XX
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NxOgre is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_VISUALDEBUGGER_H
#define NXOGRE_VISUALDEBUGGER_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
namespace NxOgre_Namespace
{
/** \brief VisualDebugger is an NxOgre implementation of the PhysX NxDebugRenderable and NX_VISUALIZE properties.
*/
class NxOgrePublicClass VisualDebugger
{
public: // Functions
/** \brief Text
*/
VisualDebugger(World*);
/** \brief Text
*/
~VisualDebugger(void);
/** \brief Text
*/
void setRenderable(Renderable*);
/** \brief Text
*/
Renderable* getRenderable(void);
void setVisualisationMode(NxOgre::Enums::VisualDebugger);
/** \brief Draw the scene.
*/
void draw();
protected: // Variables
Renderable* mRenderable;
World* mWorld;
VisualDebuggerMeshData* mMeshData;
}; // class ClassName
} // namespace NxOgre_Namespace
#endif
|
[
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
] |
[
[
[
1,
84
]
]
] |
ae7756a81fec74109ae02e6a901de00c5bb4fcb2
|
909e422494d7c012c2bc89c79eabdceb53c721a5
|
/icpcLibrary/Bellman-Ford.cpp
|
681601f59f44751a615598db17ad3c9bdd01a902
|
[] |
no_license
|
aviramagen/menglin-icpc-code-library
|
f14cc303a3fd05992a1a40b9bcd7a0b09657f21c
|
c8375f39ed13312f705fb42c20ce83f5194bd297
|
refs/heads/master
| 2021-01-10T14:00:32.605726 | 2011-12-03T11:39:50 | 2011-12-03T11:39:50 | 54,555,734 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,324 |
cpp
|
/*======================================================
单源最短路径
Bellman-Ford 算法
适用条件:所有情况,边权可以为负
G为图,n为图的节点数目,s,t分别为源点和终点,
success用来标示该函数是否成功,
如果存在一个从源点可达的权为负的回路则success=false;
返回值为s,t之间的最短路径长度;
!!注意:
1.顶点标号从0开始
2.当i,j不相邻时G[i,j]=infinity
=============================================================*/
int Bellman_Ford ( Graph G, int n, int s, int t, int path[], int success )
{
int i, j, k, d[max_vertexes];
for ( i = 0; i < n; i++ )
{
d[i] = infinity;
path[i] = 0;
}
d[s] = 0;
for ( k = 1; k < n; k++ )
for ( i = 0; i < n; i++ )
for ( j = 0; j < n; j++ )
if ( d[j] > d[i] + G[i][j] )
{
d[j] = d[i] + G[i][j];
path[j] = i;
}
success = 0;
for ( i = 0; i < n; i++ )
for ( j = 0; j < n; j++ )
if ( d[j] > d[i] + G[i][j] ) return 0;
success = 1;
return d[t];
}
|
[
"bluebird498@localhost"
] |
[
[
[
1,
83
]
]
] |
8b5ca9900b88d221637ee02d1781d0f30ee079f4
|
3276915b349aec4d26b466d48d9c8022a909ec16
|
/数据结构/图/图的深度优先遍历--矩阵存储.cpp
|
cd3c251f7431849b22cb70f2f9307660c5f6cd48
|
[] |
no_license
|
flyskyosg/3dvc
|
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
|
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
|
refs/heads/master
| 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 2,363 |
cpp
|
#include<iostream.h> // 图的邻接矩阵存储结构
#define max 50
typedef char datatype;
typedef struct node
{
int number; //节点要存储其编号及内容
datatype inf;
}node;
typedef struct graph
{
int n,e;
node vex[max]; //存储节点的信息
int edge[max][max]; //存储边的信息
}G;
void creatgraph(G & l)
{
int i=0,j=0,b=0,t=0,w=0;
cout<<"收入图的顶点数与边数:";
cin>>l.n>>l.e;
cout<<"该图有"<<l.n<<"个顶点"<<l.e<<"条边"<<endl;
for(;i<l.n;i++)
{
cout<<"请输入第"<<i<<"个节点的信息,输入序号_节点内容:";
cin>>l.vex[i].number>>l.vex[i].inf;
}
for(i=0;i<l.n;i++)
for(j=0;j<l.n;j++)
l.edge[i][j]=0;
for(j=0;j<l.e;j++)
{
cout<<"输入边的信息,起点序号_终点_权值:";
cin>>b>>t>>w;
if(b<0||b>=l.n) cout<<"起点不在搜索范围内."<<endl;
if(t<0||t>=l.n) cout<<"终点不在搜索范围内."<<endl;
l.edge[b][t]=w;
}
cout<<"建立矩阵完毕."<<endl;
}
void disp(G l) //输出建立好的图的邻接矩阵
{
int i=0,j=0;
for(i;i<l.n;i++)
{
for(j=0;j<l.n;j++)
cout<<" "<<l.edge[i][j];
cout<<endl;
}
}
//**********************遍历*************************//
int visited[max]; //全局数组,用来存放各个节点的标记,标记节点是否被访问过,
void DFS(G t,int i) //递归函数
{
cout<<t.vex[i].inf<<" "; //首先将节点内容输出
visited[i]=1; //节点输出后将对应的visited数组的对应标记为设置为1;
for(int j=0;j<t.n;j++)
if(t.edge[i][j]!=0&&visited[j]==0) DFS(t,j); //在节点存在邻接点并且该邻接点没有被访问过的情况下从新该节点开始遍
}
void DFSthread(G t)
{
for(int i=0;i<t.n;i++) //初始化标记数组,全部设置为0;未被访问。
visited[i]=0;
for(int j=0;j<t.n;j++) //为了保证连通图和非连通图中的每个节点都访问到,这里把每个节点都做为起始点一次开始访问。
{
if(visited[j]==0) DFS(t,j); //在该节点未被访问的情况下对该节点遍历
}
}
void main()
{
G l;
cout<<"创建图:"<<endl;
creatgraph(l);
cout<<"输出图:"<<endl;
disp(l);
cout<<"遍历图:";
DFSthread(l);
}
|
[
"[email protected]"
] |
[
[
[
1,
100
]
]
] |
f8d0190865450d8e1c34f8feb51f345e40e485a8
|
986d745d6a1653d73a497c1adbdc26d9bef48dba
|
/oldnewthing/472_accessibility.cpp
|
e394d68f9934928f9c89b269960ba3afaf5fe122
|
[] |
no_license
|
AnarNFT/books-code
|
879f75327c1dad47a13f9c5d71a96d69d3cc7d3c
|
66750c2446477ac55da49ade229c21dd46dffa99
|
refs/heads/master
| 2021-01-20T23:40:30.826848 | 2011-01-17T11:14:34 | 2011-01-17T11:14:34 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,445 |
cpp
|
#define STRICT
#include <windows.h>
#include <windowsx.h>
#include <ole2.h>
#include <commctrl.h>
#include <shlwapi.h>
#include <oleacc.h>
HINSTANCE g_hinst; /* This application's HINSTANCE */
HWND g_hwndChild; /* Optional child window */
class BaseAccessible : public IAccessible
{
public:
// *** IUnknown ***
STDMETHODIMP QueryInterface(REFIID riid, void **ppv)
{
IUnknown *punk = NULL;
if (riid == IID_IUnknown) {
punk = static_cast<IUnknown*>(this);
} else if (riid == IID_IDispatch) {
punk = static_cast<IDispatch*>(this);
} else if (riid == IID_IAccessible) {
punk = static_cast<IAccessible*>(this);
}
*ppv = punk;
if (punk) {
punk->AddRef();
return S_OK;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_cRef); }
STDMETHODIMP_(ULONG) Release()
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if (cRef == 0) delete this;
return cRef;
}
// *** IDispatch ***
STDMETHODIMP GetTypeInfoCount(UINT *pctinfo)
{
return m_paccStd->GetTypeInfoCount(pctinfo);
}
STDMETHODIMP GetTypeInfo(UINT iTInfo, LCID lcid,
ITypeInfo **ppTInfo)
{
return m_paccStd->GetTypeInfo(iTInfo, lcid, ppTInfo);
}
STDMETHODIMP GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames,
UINT cNames, LCID lcid, DISPID *rgDispId)
{
return m_paccStd->GetIDsOfNames(riid, rgszNames, cNames,
lcid, rgDispId);
}
STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid,
WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo,
UINT *puArgErr)
{
return m_paccStd->Invoke(dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
// *** IAccessible ***
STDMETHODIMP get_accParent(IDispatch **ppdispParent)
{
return m_paccStd->get_accParent(ppdispParent);
}
STDMETHODIMP get_accChildCount(long *pcountChildren)
{
return m_paccStd->get_accChildCount(pcountChildren);
}
STDMETHODIMP get_accChild(VARIANT varChild,
IDispatch **ppdispChild)
{
return m_paccStd->get_accChild(varChild, ppdispChild);
}
STDMETHODIMP get_accName(VARIANT varChild, BSTR *pbsName)
{
return m_paccStd->get_accName(varChild, pbsName);
}
STDMETHODIMP get_accValue(VARIANT varChild, BSTR *pbsValue)
{
return m_paccStd->get_accValue(varChild, pbsValue);
}
STDMETHODIMP get_accDescription(VARIANT varChild, BSTR *pbsDesc)
{
return m_paccStd->get_accDescription(varChild, pbsDesc);
}
STDMETHODIMP get_accRole(VARIANT varChild, VARIANT *pvarRole)
{
return m_paccStd->get_accRole(varChild, pvarRole);
}
STDMETHODIMP get_accState(VARIANT varChild, VARIANT *pvarState)
{
return m_paccStd->get_accState(varChild, pvarState);
}
STDMETHODIMP get_accHelp(VARIANT varChild, BSTR *pbsHelp)
{
return m_paccStd->get_accHelp(varChild, pbsHelp);
}
STDMETHODIMP get_accHelpTopic(BSTR *pbsHelpFile,
VARIANT varChild, long *pidTopic)
{
return m_paccStd->get_accHelpTopic(pbsHelpFile, varChild,
pidTopic);
}
STDMETHODIMP get_accKeyboardShortcut(VARIANT varChild,
BSTR *pbsKey)
{
return m_paccStd->get_accKeyboardShortcut(varChild, pbsKey);
}
STDMETHODIMP get_accFocus(VARIANT *pvarChild)
{
return m_paccStd->get_accFocus(pvarChild);
}
STDMETHODIMP get_accSelection(VARIANT *pvarChildren)
{
return m_paccStd->get_accSelection(pvarChildren);
}
STDMETHODIMP get_accDefaultAction(VARIANT varChild,
BSTR *pbsDefAction)
{
return m_paccStd->get_accDefaultAction(varChild, pbsDefAction);
}
STDMETHODIMP accSelect(long flagsSelect, VARIANT varChild)
{
return m_paccStd->accSelect(flagsSelect, varChild);
}
STDMETHODIMP accLocation(long *pxLeft, long *pyTop,
long *pcxWidth, long *pcyHeight,
VARIANT varChild)
{
return m_paccStd->accLocation(pxLeft, pyTop, pcxWidth,
pcyHeight, varChild);
}
STDMETHODIMP accNavigate(long navDir, VARIANT varStart,
VARIANT *pvarEndUpAt)
{
return m_paccStd->accNavigate(navDir, varStart, pvarEndUpAt);
}
STDMETHODIMP accHitTest(long xLeft, long yTop,
VARIANT *pvarChild)
{
return m_paccStd->accHitTest(xLeft, yTop, pvarChild);
}
STDMETHODIMP accDoDefaultAction(VARIANT varChild)
{
return m_paccStd->accDoDefaultAction(varChild);
}
STDMETHODIMP put_accName(VARIANT varChild, BSTR bsName)
{
return m_paccStd->put_accName(varChild, bsName);
}
STDMETHODIMP put_accValue(VARIANT varChild, BSTR bsValue)
{
return m_paccStd->put_accValue(varChild, bsValue);
}
protected:
BaseAccessible(IAccessible *paccStd)
: m_cRef(1), m_paccStd(paccStd)
{
m_paccStd->AddRef();
}
~BaseAccessible() { m_paccStd->Release(); }
private:
LONG m_cRef;
protected:
IAccessible *m_paccStd;
};
class ScratchAccessible : public BaseAccessible
{
public:
static HRESULT Create(HWND hwnd, LONG idObject,
REFIID riid, void **ppv)
{
*ppv = NULL;
IAccessible *paccStd;
HRESULT hr = CreateStdAccessibleObject(hwnd, idObject,
IID_IAccessible, (void **)&paccStd);
if (SUCCEEDED(hr)) {
// note: uses non-throwing "new"
ScratchAccessible *psa = new ScratchAccessible(paccStd);
if (psa) {
hr = psa->QueryInterface(riid, ppv);
psa->Release();
} else {
hr = E_OUTOFMEMORY;
}
paccStd->Release();
}
return hr;
}
// Selective overriding of IAccessible
STDMETHODIMP get_accName(VARIANT varChild, BSTR *pbsName)
{
if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
*pbsName = SysAllocString(L"Current time");
return *pbsName ? S_OK : E_OUTOFMEMORY;
}
return m_paccStd->get_accName(varChild, pbsName);
}
STDMETHODIMP get_accValue(VARIANT varChild, BSTR *pbsValue)
{
if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
WCHAR szTime[100];
if (GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL,
szTime, 100)) {
*pbsValue = SysAllocString(szTime);
return *pbsValue ? S_OK : E_OUTOFMEMORY;
}
}
return m_paccStd->get_accValue(varChild, pbsValue);
}
private:
ScratchAccessible(IAccessible *paccStd)
: BaseAccessible(paccStd) { }
};
void
OnSize(HWND hwnd, UINT state, int cx, int cy)
{
if (g_hwndChild) {
MoveWindow(g_hwndChild, 0, 0, cx, cy, TRUE);
}
}
BOOL
OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
{
return TRUE;
}
void
OnDestroy(HWND hwnd)
{
PostQuitMessage(0);
}
void
PaintContent(HWND hwnd, PAINTSTRUCT *pps)
{
TCHAR szTime[100];
if (GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,
szTime, 100)) {
TextOut(pps->hdc, 0, 0, szTime, lstrlen(szTime));
}
}
void CALLBACK
InvalidateAndKillTimer(HWND hwnd, UINT uMsg,
UINT_PTR idTimer, DWORD dwTime)
{
KillTimer(hwnd, idTimer);
InvalidateRect(hwnd, NULL, TRUE);
NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, hwnd,
OBJID_CLIENT, CHILDID_SELF);
}
void
OnPaint(HWND hwnd)
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
PaintContent(hwnd, &ps);
EndPaint(hwnd, &ps);
}
void
OnPrintClient(HWND hwnd, HDC hdc)
{
PAINTSTRUCT ps;
ps.hdc = hdc;
GetClientRect(hwnd, &ps.rcPaint);
ps.fErase = FALSE;
PaintContent(hwnd, &ps);
}
LRESULT OnGetObject(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
if (lParam == OBJID_CLIENT) {
IAccessible *pacc;
HRESULT hr = ScratchAccessible::Create(hwnd,
(LONG)lParam, IID_IAccessible, (void**)&pacc);
if (FAILED(hr)) return hr;
LRESULT lr = LresultFromObject(IID_IAccessible, wParam, pacc);
pacc->Release();
return lr;
}
return DefWindowProc(hwnd, WM_GETOBJECT, wParam, lParam);
}
LRESULT CALLBACK
WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch (uiMsg) {
HANDLE_MSG(hwnd, WM_CREATE, OnCreate);
HANDLE_MSG(hwnd, WM_SIZE, OnSize);
HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);
HANDLE_MSG(hwnd, WM_PAINT, OnPaint);
case WM_PRINTCLIENT: OnPrintClient(hwnd, (HDC)wParam); return 0;
case WM_GETOBJECT: return OnGetObject(hwnd, wParam, lParam);
}
return DefWindowProc(hwnd, uiMsg, wParam, lParam);
}
BOOL
InitApp(void)
{
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = g_hinst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("Scratch");
if (!RegisterClass(&wc)) return FALSE;
InitCommonControls(); /* In case we use a common control */
return TRUE;
}
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
LPSTR lpCmdLine, int nShowCmd)
{
MSG msg;
HWND hwnd;
g_hinst = hinst;
if (!InitApp()) return 0;
if (SUCCEEDED(CoInitialize(NULL))) {/* In case we use COM */
hwnd = CreateWindow(
TEXT("Scratch"), /* Class Name */
TEXT("Scratch"), /* Title */
WS_OVERLAPPEDWINDOW, /* Style */
CW_USEDEFAULT, CW_USEDEFAULT, /* Position */
CW_USEDEFAULT, CW_USEDEFAULT, /* Size */
NULL, /* Parent */
NULL, /* No menu */
hinst, /* Instance */
0); /* No special parameters */
ShowWindow(hwnd, nShowCmd);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
CoUninitialize();
}
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
372
]
]
] |
56c702ea8f63247073da10b6afb67c2e67e3c321
|
cd1ae676922aee247543ce364b4ec59b2750fdef
|
/Externals/dolphin-emu/Source/Volume.h
|
237836e486816241d745580fb0bd61602e1ae036
|
[] |
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 | 1,844 |
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 _VOLUME_H
#define _VOLUME_H
#include <string>
#include <vector>
#include "CommonTypes.h"
namespace DiscIO
{
class IVolume
{
public:
IVolume() {}
virtual ~IVolume() {}
virtual bool Read(u64 _Offset, u64 _Length, u8* _pBuffer) const = 0;
virtual bool RAWRead(u64 _Offset, u64 _Length, u8* _pBuffer) const = 0;
virtual bool GetTitleID(u8*) const { return false; }
virtual void GetTMD(u8*, u32 *_sz) const { *_sz=0; }
virtual std::string GetUniqueID() const = 0;
virtual std::string GetMakerID() const = 0;
virtual std::string GetName() const = 0;
virtual u32 GetFSTSize() const = 0;
virtual std::string GetApploaderDate() const = 0;
enum ECountry
{
COUNTRY_EUROPE = 0,
COUNTRY_FRANCE,
COUNTRY_RUSSIA,
COUNTRY_USA,
COUNTRY_JAPAN,
COUNTRY_KOREA,
COUNTRY_ITALY,
COUNTRY_TAIWAN,
COUNTRY_SDK,
COUNTRY_UNKNOWN,
NUMBER_OF_COUNTRIES
};
virtual ECountry GetCountry() const = 0;
virtual u64 GetSize() const = 0;
};
// Generic Switch function for all volumes
IVolume::ECountry CountrySwitch(u8 CountryCode);
} // namespace
#endif
|
[
"[email protected]"
] |
[
[
[
1,
68
]
]
] |
7cee257f11469b3898e1a950d5d0053f7f271b53
|
08fe7d2be6b5c933d5e3223f726c34d38e56d332
|
/programas/congrua/pre-congrua.cpp
|
cccebb71f8501b98fdec5dc9c4a486a01a6728b8
|
[] |
no_license
|
ivancrneto/fesc
|
5adcfb7acb78ed7d2690fcaabb707bb93adcd52a
|
9fd0dcc019374f65b835b6a5363ad65d4abca25d
|
refs/heads/master
| 2020-04-06T06:43:30.803037 | 2009-10-06T04:56:58 | 2009-10-06T04:56:58 | 102,975 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,630 |
cpp
|
# include <iostream>
# include <cstdlib>
# include <cstring>
using namespace std;
// acetyl.dat e udp.dat sao os arquivos de 0's e 1's que sao saida do programa
// congtabin.cpp. o congtabin imprime os binarios de a, g, h, p e u, em ordem.
// ./congrua acetyl.dat 12 (numero de comunidades da acetyl)
// ./congrua udp.dat 7 (numero de comunidades da udp)
//
int main(int argc, char **argv) {
FILE *arq = fopen(argv[1], "r");
if (arq != NULL) {
string str = "", str2 = "";
char *tok;
int counter = 1;
tok = strtok(argv[1], ".");
str2 += tok;
str2 += "_2.txt";
FILE *out = fopen(str2.c_str(), "w");
while(!feof(arq)) {
if(counter == 383) break;
int d = 0;
for(int i = 0; i < atoi(argv[2]); i++) {
fscanf(arq, "%d", &d);
if(d != 0) {
fprintf(out, "%d\t%d\n", counter, i + 1);
for(int j = i + 1; j < atoi(argv[2]); j++) {
fscanf(arq, "%d", &d);
}
d = 1;
break;
}
}
if(d == 0) {
fprintf(out, "%d\t%d\n", counter, d);
}
counter++;
}
fclose(arq);
fclose(out);
}else {
exit(0);
}
}
|
[
"ivan@ivan-warrior.(none)"
] |
[
[
[
1,
47
]
]
] |
c3228c418acb06c9ac51d260f2fe8fdedcb18c15
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMChildNode.hpp
|
d4770aa76dbe9d1e99c67931cf1a8635dab1d47f
|
[] |
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 | 2,089 |
hpp
|
#ifndef DOMChildNode_HEADER_GUARD_
#define DOMChildNode_HEADER_GUARD_
/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOMChildNode.hpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/DOM.hpp> for the entire
// DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
/**
* ChildNode adds to NodeImpl the capability of being a child, this is having
* siblings.
**/
#include <xercesc/util/XercesDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class DOMDocument;
class DOMNode;
class CDOM_EXPORT DOMChildNode {
public:
DOMNode *previousSibling;
DOMNode *nextSibling;
DOMChildNode();
DOMChildNode(const DOMChildNode &other);
~DOMChildNode();
DOMNode * getNextSibling() const;
DOMNode * getParentNode(const DOMNode *thisNode) const;
DOMNode * getPreviousSibling(const DOMNode *thisNode) const;
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
DOMChildNode & operator = (const DOMChildNode &);
};
XERCES_CPP_NAMESPACE_END
#endif
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
71
]
]
] |
cd86c8ac1a080086056f3c2dbeed3cacbbe4b5c0
|
dd007771e947dbed60fe6a80d4f325c4ed006f8c
|
/UISelectFaceMode.cpp
|
4aea6d90c170cd29e10c84105047f47d99a36f67
|
[] |
no_license
|
chenzhi/CameraGame
|
fccea24426ea5dacbe140b11adc949e043e84ef7
|
914e1a2b8bb45b729e8d55b4baebc9ba18989b55
|
refs/heads/master
| 2016-09-05T20:06:11.694787 | 2011-09-09T09:09:39 | 2011-09-09T09:09:39 | 2,005,632 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 12,646 |
cpp
|
#include "pch.h"
#include "UISelectFaceMode.h"
#include "Application.h"
#include "Config.h"
#include "Widget.h"
#include "UILLayout.h"
/**************************************************************/
//----------------------------------------------------------
UserSelectMode::UserSelectMode(const Ogre::String& faceMesh,const Ogre::String&headMesh)
:m_currentTime(0.0f),m_isRoll(false),m_pNode(NULL),m_pFaceEntity(NULL),m_pHeadEntity(NULL),m_pAnimation(NULL)
{
Ogre::SceneManager* pSceneMrg=Application::getSingletonPtr()->getMainSceneManager();
m_pNode=pSceneMrg->getRootSceneNode()->createChildSceneNode();
m_pFaceEntity=pSceneMrg->createEntity(faceMesh);
m_pHeadEntity=pSceneMrg->createEntity(headMesh);
m_pFaceEntity->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAX);
m_pHeadEntity->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAX);
if(m_pFaceEntity->hasSkeleton()&&m_pHeadEntity->hasSkeleton())
{
m_pHeadEntity->shareSkeletonInstanceWith(m_pFaceEntity);
}
const Ogre::String& userImage=g_userInformation.getUserImage();
if(userImage.empty()==false)
{
Ogre::MaterialPtr pMaterial=m_pFaceEntity->getSubEntity(0)->getMaterial();
if(pMaterial.isNull()==false)
{
pMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(userImage);
}
}
m_pNode->attachObject(m_pFaceEntity);
m_pNode->attachObject(m_pHeadEntity);
m_pAnimation=m_pFaceEntity->getAnimationState(g_idleAni);
if(m_pAnimation!=NULL)
{
m_pAnimation->setLoop(true);
m_pAnimation->setEnabled(true);
m_pAnimation->setTimePosition(0);
}
///去除特效贴图
Ogre::MaterialPtr pMaterial=m_pFaceEntity->getSubEntity(0)->getMaterial();
int textureNumber=pMaterial->getTechnique(0)->getPass(0)->getNumTextureUnitStates();
if(textureNumber>0)
{
pMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(textureNumber-1)->setTextureName("");
}
}
//----------------------------------------------------------
UserSelectMode::~UserSelectMode()
{
Ogre::SceneManager* pSceneMrg=Application::getSingletonPtr()->getMainSceneManager();
m_pNode->detachAllObjects();
pSceneMrg->getRootSceneNode()->removeAndDestroyChild(m_pNode->getName());
m_pNode=NULL;
pSceneMrg->destroyEntity(m_pHeadEntity);
pSceneMrg->destroyEntity(m_pFaceEntity);
m_pHeadEntity=NULL;
m_pFaceEntity=NULL;
m_pAnimation=NULL;
return ;
}
//----------------------------------------------------------
void UserSelectMode::update(float time)
{
updateOrientation();
if(m_pAnimation!=NULL)
{
m_pAnimation->addTime(time);
}
///如果不需要移动返回
if(m_isRoll==false)
return ;
m_currentTime+=time;
updatePos(m_currentTime);
if(m_currentTime>=1.0f)
{
reset();
}
return ;
}
//----------------------------------------------------------
void UserSelectMode::setFaceMesh(const Ogre::String& faceMesh)
{
Ogre::SceneManager* pSceneMrg=Application::getSingletonPtr()->getMainSceneManager();
if(m_pFaceEntity!=NULL)
{
m_pNode->detachObject(m_pFaceEntity);
pSceneMrg->destroyEntity(m_pFaceEntity);
}
m_pFaceEntity=pSceneMrg->createEntity(faceMesh);
}
//----------------------------------------------------------
void UserSelectMode::setHeadMesh(const Ogre::String& headMesh)
{
Ogre::SceneManager* pSceneMrg=Application::getSingletonPtr()->getMainSceneManager();
if(m_pHeadEntity!=NULL)
{
m_pNode->detachObject(m_pHeadEntity);
pSceneMrg->destroyEntity(m_pHeadEntity);
}
m_pHeadEntity=pSceneMrg->createEntity(headMesh);
}
//----------------------------------------------------------------
bool UserSelectMode::getFaceMeshName(Ogre::String& meshName)const
{
if(m_pFaceEntity!=NULL)
{
Ogre::MeshPtr pMesh=m_pFaceEntity->getMesh();
if(pMesh.isNull()==false)
{
meshName=pMesh->getName();
return true;
}
}
return false;
}
//----------------------------------------------------------------
bool UserSelectMode::getHeadMeshName(Ogre::String& meshName)const
{
if(m_pHeadEntity!=NULL)
{
Ogre::MeshPtr pMesh=m_pHeadEntity->getMesh();
if(pMesh.isNull()==false)
{
meshName=pMesh->getName();
return true;
}
}
return false;
}
//----------------------------------------------------------
bool UserSelectMode::isIntersect(const Ogre::Ray& ray)
{
const Ogre::AxisAlignedBox& box=m_pNode->_getWorldAABB();
float d1=0,d2=0;
return Ogre::Math::intersects(ray,box,&d1,&d2);
}
void UserSelectMode::reset()
{
m_orginPos=m_pNode->getPosition();
m_targetPos=m_orginPos;
m_currentTime=0.0f;
m_isRoll=false;
}
///移动到指定位置
void UserSelectMode::translate(const Ogre::Vector3& pos)
{
m_targetPos=pos;
m_currentTime=0.0f;
m_isRoll=true;
}
void UserSelectMode::updatePos(float precent)
{
if(precent>=1.0f)
{
m_pNode->setPosition(m_targetPos);
return ;
}
Ogre::Vector3 temPos=m_orginPos+(m_targetPos-m_orginPos)*precent;
m_pNode->setPosition(temPos);
}
void UserSelectMode::setVisible(bool b)
{
m_pNode->setVisible(b);
}
//-------------------------------------------------------------------------
void UserSelectMode::setPosition(float x,float y,float z)
{
m_pNode->setPosition(Ogre::Vector3(x,y,z));
updateOrientation();
}
//-------------------------------------------------------------------------
void UserSelectMode::updateOrientation()
{
if(m_pNode==NULL)
return ;
//m_pNode->rotate(Ogre::Vector3::UNIT_Y,Ogre::Radian(0.01f));
//return ;
Ogre::Camera* pCamera=Application::getSingleton().getMainCamera();
Ogre::Vector3 camPos= pCamera->getParentNode()->getPosition();
Ogre::Vector3 facePos=m_pNode->getPosition();
Ogre::Vector3 dir=camPos-facePos;
dir.normalise();
//dir=-dir;
Ogre::Vector3 up(0.0f,1.0f,0.0f);
Ogre::Vector3 right=dir.crossProduct(up);
m_pNode->lookAt(camPos,Ogre::Node::TS_WORLD,Ogre::Vector3::UNIT_Z);
return ;
}
/***********************************************************/
//----------------------------------------------------------
UISelectFaceMode::UISelectFaceMode()
:UILayout("lianxingxuze")
{
}
//----------------------------------------------------------
UISelectFaceMode::~UISelectFaceMode()
{
destroyAllFaceMode();
}
//----------------------------------------------------------
/*
void UISelectFaceMode::init()
{
UIBase::init();
initBackEntity();
///返回按钮
///返回上一层按钮
m_pReturnButton=new ImageButton("UISelectFaceModeReturnButton,","moshi_fanhui_release.png","moshi_fanhui_press.png");
registerWidget(m_pReturnButton);
m_pReturnButton->setHorizontalAlignment(Ogre::GHA_LEFT);
m_pReturnButton->setLeft(10);
m_pReturnButton->setVerticalAlignment(Ogre::GVA_BOTTOM);
m_pReturnButton->setTop(-100);
m_pReturnButton->setWidth(80);
m_pReturnButton->setHeight(80);
return ;
}
//*/
//----------------------------------------------------------
void UISelectFaceMode::setVisible(bool b)
{
UIBase::setVisible(b);
if(b)
{
destroyAllFaceMode();
initAllFaceMode();
}
setUserSelctModeVisible(b);
return ;
}
//----------------------------------------------------------
void UISelectFaceMode::setUserSelctModeVisible(bool b)
{
FaceModeCollect::iterator it=m_FaceModeCollect.begin();
FaceModeCollect::iterator endit=m_FaceModeCollect.end();
for(;it!=endit;++it)
{
(*it)->setVisible(b);
}
return ;
}
void UISelectFaceMode::onEndTouch(int x,int y)
{
UIBase::onEndTouch(x,y);
///判断是否有拾取一个模型
Ogre::Camera* pCamera=Application::getSingleton().getMainCamera();
Ogre::Ray pickRay;
float w = Application::getSingleton().getRenderWindows()->getViewport(0)->getActualWidth();
float h= Application::getSingleton().getRenderWindows()->getViewport(0)->getActualHeight();
pCamera->getCameraToViewportRay(x/w,y/h,&pickRay);
FaceModeCollect::iterator it=m_FaceModeCollect.begin();
FaceModeCollect::iterator endit=m_FaceModeCollect.end();
for(;it!=endit;++it)
{
if( (*it)->isIntersect(pickRay))
{
Ogre::String meshName;
bool b=(*it)->getFaceMeshName(meshName);
assert(b);
g_userInformation.setFaceMode(meshName);
b=(*it)->getHeadMeshName(meshName);
g_userInformation.setHeadMode(meshName);
Application::getSingleton().getCurrentActive()->setNextStateType(ST_WAR);
return ;
}
}
}
///销毁所有脸部模型
void UISelectFaceMode::destroyAllFaceMode()
{
FaceModeCollect::iterator it=m_FaceModeCollect.begin();
FaceModeCollect::iterator itend=m_FaceModeCollect.end();
for(;it!=itend;++it)
{
delete (*it);
}
m_FaceModeCollect.clear();
}
void UISelectFaceMode::initAllFaceMode()
{
/**创建三个模型用来做为不同脸型的选择*/
///创建所有选择的脸
unsigned int FaceSize= m_FaceModeSource.getFaceModeCount();
const Ogre::String& headMode=g_userInformation.getHeadMode();
Ogre::Vector3 pos(-2.0f,0.0f,0.0f);
for(unsigned int i=0;i<FaceSize;++i)
{
const Ogre::String& faceMesh=m_FaceModeSource.getFaceMode(i);
UserSelectMode* pMode=new UserSelectMode(faceMesh,headMode);
m_FaceModeCollect.push_back(pMode);
pMode->setPosition(pos.x,pos.y,pos.z);
pos.x+=2.0f;
}
}
//---------------------------------------------------------------------
void UISelectFaceMode::update(float time)
{
UILayout::update(time);
FaceModeCollect::iterator it=m_FaceModeCollect.begin();
FaceModeCollect::iterator itend=m_FaceModeCollect.end();
for(;it!=itend;++it)
{
(*it)->update(time);
}
}
///初始背景
/*
void UISelectFaceMode::initBackEntity()
{
///如果已经创建了直接返回
if(m_BackGround!=NULL)
return ;
Ogre::SceneNode* m_pCameraNode=Application::getSingleton().getMainCamera()->getParentSceneNode();
float distance=1.0f;
float width=0,height=0;
Ogre::Vector3 camPos=m_pCameraNode->getPosition();
float fovy= Application::getSingleton().getMainCamera()->getFOVy().valueRadians()*0.5f;
height=Ogre::Math::Tan(fovy)*distance*2.0f;
width=Application::getSingleton().getMainCamera()->getAspectRatio()*height;
float videowidth=480;
float videoheight=360;
float textWidth=512;
float texheight=512;
float v=1.0f;
float u=1.0f;
UIImageSet * pImageset=UIImagesetManager::getSingleton().getImagesetByName("gongyong0_21");
if(pImageset!=NULL)
{
Image* pImage=pImageset->getImageByName("beijing");
if(pImage!=NULL)
{
const Ogre::Vector4& uv=pImage->getUV();
v=uv.w;
u=uv.z;
}
}
Ogre::Plane plane(Ogre::Vector3(0.0f,0.0f,1.0f),Ogre::Vector3(0.0f,0.0f,0.0f));
Ogre::MeshPtr pMesh= Ogre::MeshManager::getSingleton().
createPlane("backVideo", "General", plane,1,1,1,1,false,1,0.5f,0.75f);
Ogre::SceneManager* pSceneMrg=Application::getSingleton().getMainSceneManager();
m_BackGround=pSceneMrg->createEntity("UISelectFaceModeBackGround", pMesh->getName());
Ogre::SceneNode* pBackNode=m_pCameraNode->createChildSceneNode();
pBackNode->attachObject(m_BackGround);
pBackNode->setPosition(0,0,-distance);
pBackNode->setScale(Ogre::Vector3(width,height,1.0f));
Ogre::MaterialPtr pBackGroundMaterial=Ogre::MaterialManager::getSingleton().create("UISelectFaceModeBackGround", "General");
Ogre::Pass*pPass=pBackGroundMaterial->getTechnique(0)->getPass(0);
pPass->createTextureUnitState()->setTextureName(pImageset->getTextureName());
m_BackGround->getSubEntity(0)->setMaterialName(pBackGroundMaterial->getName());
}
//*/
///消毁背景
/*
void UISelectFaceMode::destroyBackEnetiy()
{
Ogre::SceneNode* pParentNode=m_BackGround->getParentSceneNode();
pParentNode->getParentSceneNode()->removeAndDestroyChild(pParentNode->getName());
Ogre::SceneManager* pSceneMrg=Application::getSingleton().getMainSceneManager();
pSceneMrg->destroyEntity(m_BackGround);
m_BackGround=NULL;
}
//*/
///鼠标事件
void UISelectFaceMode::buttonHit(Widget* pButton)
{
if(pButton==NULL)
return ;
if(pButton->getName()=="lianxingxuanze/lianxingxuanzefanhui")
{
///返回到选脸界面
setVisible(false);
UIBase* pSelectFaceImage=Application::getSingleton().getUIByName("toutaoxuanzejiemian");
assert(pSelectFaceImage);
pSelectFaceImage->setVisible(true);
}
return ;
}
|
[
"chenzhi@aee8fb6d-90e1-2f42-9ce8-abdac5710353",
"zhangxiaotian@aee8fb6d-90e1-2f42-9ce8-abdac5710353"
] |
[
[
[
1,
298
],
[
300,
303
],
[
305,
549
]
],
[
[
299,
299
],
[
304,
304
]
]
] |
c2857544f38414b8b51f3f5414a36ca43bc98e58
|
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
|
/svoip/src/VoP2pPlugInFactory.cpp
|
dfd31cc4283e65e65bd4d7060a946583044d40b2
|
[] |
no_license
|
jcloudpld/srpc
|
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
|
f2483c8177d03834552053e8ecbe788e15b92ac0
|
refs/heads/master
| 2021-01-10T08:54:57.140800 | 2010-02-08T07:03:00 | 2010-02-08T07:03:00 | 44,454,693 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 380 |
cpp
|
#include "stdafx.h"
#include "svoip/VoP2pPlugInFactory.h"
#include "svoip/Recorder.h"
#include "svoip/Player.h"
#include "VoP2pPlugInImpl.h"
namespace svoip
{
VoP2pPlugInPtr VoP2pPlugInFactory::create(
std::auto_ptr<Recorder> recorder, std::auto_ptr<Player> player)
{
return VoP2pPlugInPtr(new VoP2pPlugInImpl(recorder, player));
}
} // namespace svoip
|
[
"kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4"
] |
[
[
[
1,
16
]
]
] |
59503512e0061c5aa37b76a206efbafb8d502364
|
0b1111e870b496aae0d6210806eebf1c942c9d3a
|
/LinearAlgebra/MatrixOps.h
|
8ea21e64d8d8fb1f2df33279f5a9c1d560c56f1b
|
[
"WTFPL"
] |
permissive
|
victorliu/Templated-Numerics
|
8ca3fabd79435fa40e95e9c8c944ecba42a0d8db
|
35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9
|
refs/heads/master
| 2016-09-05T16:32:22.250276 | 2009-12-30T07:48:03 | 2009-12-30T07:48:03 | 318,857 | 3 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 29,085 |
h
|
#ifndef _MATRIX_OPS_H_
#define _MATRIX_OPS_H_
// Preprocessor flags:
// USE_MATRIX_OPS_CHECKS - If not turned on, always returns OK
// USE_MATRIX_ASSERTS - Turn on assertion checking
// USE_MATRIX_OPS_TBLAS - Use optimized BLAS routines when possible
// USE_COMPLEX_MATRICES
// USE_ADVANCED_MATRIX_OPS
// These are fully generic matrix operations. Particular routines for
// different classes are contained in their respective headers.
#include "TMatrix.h"
#include "MatrixViews.h"
#include "TDiagonalMatrix.h"
#ifdef USE_MATRIX_ASSERTS
# include <cassert>
#endif
#ifdef USE_COMPLEX_MATRICES
# include <complex>
#endif
#ifdef USE_MATRIX_OPS_TBLAS
# include "TBLAS/tblas.hpp"
#endif
#ifndef MATRIX_OP_STATUS_DEFINED
#define MATRIX_OP_STATUS_DEFINED
enum MatrixOpStatus{
OK,
DIMENSION_MISMATCH,
SINGULAR_MATRIX,
UNKNOWN_ERROR
};
#endif
namespace MatrixOps{
// Fundamental operations
// Copy(src, dst)
// Fill(dst, value)
// Swap(x, y)
// LargestElementIndex(X)
// Dot(X, Y)
// ConjugateDot(Xc, Y)
// Scale(X, scaleX)
// Add(X, YPlusX, scaleX = 1)
// Rank1Update(A, X, Yt, scaleXY = 1)
// Rank1Update(A, X, scaleXX = 1)
// Rank2Update(A, X, Yt, scaleXY = 1)
// Mult(A, B, CPlusATimesB, scaleATimesB = 1, scale_C = 0)
// Mult(D, A); - D is diagonal
// Mult(A, D); - D is diagonal
// FrobeniusNorm(A)
//
// Sophisticated operations
// LUDecomposition(A, P) - A -> P*unit_lower(A)*upper(A)
// SolveDestructive(A, X) - X holds B, A gets overwritten with LU, X overwritten with solution
// Solve(A, B, X) - A*X == B
// Invert(A)
// Invert(A, Ainv)
// SolveLeastSquares(A, B, X) - A*X == B
// Eigenvalues(A, L)
// Eigensystem(A, L, X) - A*X == X*diag(L)
// SingularValueDecomposition(A, U, S, V) - A == U*S*V
// CholeskyDecomposition(A, L) - A == L*L'
// UnitaryProcrustes(A) - Replaces A with the nearest (Frobenius norm) unitary matrix, A'*A = I
// GeneralizedProcrustes(A, B, C) - Replaces A with nearest (Frobenius norm) matrix such that A'*B*A = C
//// Copy
template <class Tsrc, class Tdst>
typename IsReadableMatrix<typename Tsrc::readable_matrix,
typename IsWritableMatrixView<typename Tdst::writable_matrix,
MatrixOpStatus
>::type>::type
Copy(const Tsrc &src, const Tdst &dst){
assert(src.Rows() == dst.Rows());
assert(src.Cols() == dst.Cols());
typedef typename Tdst::value_type dest_type;
#ifdef USE_MATRIX_OPS_CHECKS
if(src.Rows() != dst.Rows() && src.Cols() != dst.Cols()){ return DIMENSION_MISMATCH; }
#endif
for(size_t j = 0; j < dst.Cols(); ++j){
for(size_t i = 0; i < dst.Rows(); ++i){
dst.Set(i,j, dest_type(src.Get(i,j)));
}
}
return OK;
}
template <class Tsrc, class Tdst>
typename IsReadableMatrix<typename Tsrc::readable_matrix,
typename IsWritableMatrix<typename Tdst::writable_matrix,
MatrixOpStatus
>::type>::type
Copy(const Tsrc &src, Tdst &dst){
return Copy(src, TrivialWritableMatrixView<Tdst>(dst));
}
template <class Tsrc, class Tdst>
typename IsReadableVector<typename Tsrc::readable_vector,
typename IsWritableVectorView<typename Tdst::writable_vector,
MatrixOpStatus
>::type>::type
Copy(const Tsrc &src, const Tdst &dst){
assert(src.size() == dst.size());
typedef typename Tdst::value_type dest_type;
#ifdef USE_MATRIX_OPS_CHECKS
if(src.size() != dst.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < dst.size(); ++i){
dst.Set(i, dest_type(src.Get(i)));
}
return OK;
}
template <class Tsrc, class Tdst>
typename IsReadableVector<typename Tsrc::readable_vector,
typename IsWritableVector<typename Tdst::writable_vector,
MatrixOpStatus
>::type>::type
Copy(const Tsrc &src, Tdst &dst){
return Copy(src, TrivialWritableVectorView<Tdst>(dst));
}
//// Fill
template <class Tdst>
typename IsWritableMatrixView<typename Tdst::writable_matrix,
MatrixOpStatus
>::type
Fill(const Tdst &dst, const typename Tdst::value_type &value){
for(size_t j = 0; j < dst.Cols(); ++j){
for(size_t i = 0; i < dst.Rows(); ++i){
dst.Set(i,j, value);
}
}
return OK;
}
template <class Tdst>
typename IsWritableMatrix<typename Tdst::writable_matrix,
MatrixOpStatus
>::type
Fill(Tdst &dst, const typename Tdst::value_type &value){
return Fill(TrivialWritableMatrixView<Tdst>(dst), value);
}
template <class Tdst>
typename IsWritableVectorView<typename Tdst::writable_vector,
MatrixOpStatus
>::type
Fill(const Tdst &dst, const typename Tdst::value_type &value){
for(size_t i = 0; i < dst.size(); ++i){
dst.Set(i, value);
}
return OK;
}
template <class Tdst>
typename IsWritableVector<typename Tdst::writable_vector,
MatrixOpStatus
>::type
Fill(Tdst &dst, const typename Tdst::value_type &value){
return Fill(TrivialWritableVectorView<Tdst>(dst), value);
}
//// Swap
template <class TX, class TY>
typename IsWritableVectorView<typename TX::writable_vector,
typename IsWritableVectorView<typename TY::writable_vector,
MatrixOpStatus
>::type>::type
Swap(const TX &x, const TY &y){
assert(x.size() == y.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(x.size() != y.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < x.size(); ++i){
std::swap(x.GetMutable(i), y.GetMutable(i));
}
return OK;
}
template <class TX, class TY>
typename IsWritableVector<typename TX::writable_vector,
typename IsWritableVectorView<typename TY::writable_vector,
MatrixOpStatus
>::type>::type
Swap(TX &x, const TY &y){
return Swap(TrivialWritableVectorView<TX>(x), y);
}
template <class TX, class TY>
typename IsWritableVectorView<typename TX::writable_vector,
typename IsWritableVector<typename TY::writable_vector,
MatrixOpStatus
>::type>::type
Swap(const TX &x, TY &y){
return Swap(x, TrivialWritableVectorView<TY>(y));
}
template <class TX, class TY>
typename IsWritableVector<typename TX::writable_vector,
typename IsWritableVector<typename TY::writable_vector,
MatrixOpStatus
>::type>::type
Swap(const TX &x, TY &y){
return Swap(TrivialWritableVectorView<TX>(x), TrivialWritableVectorView<TY>(y));
}
template <class TA>
typename IsWritableVectorView<typename TA::writable_vector,
MatrixOpStatus
>::type
TransposeInPlace(const TA &A){
assert(A.Rows() == A.Cols());
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = j+1; i < A.Rows(); ++i){
std::swap(A.GetMutable(i,j), A.GetMutable(j,i));
}
}
return OK;
}
//// LargestElementIndex
template <class T>
typename IsReadableVector<typename T::readable_vector,
size_t
>::type
LargestElementIndex(const T &x){
typedef typename T::value_type value_Type;
size_t ret = 0;
for(size_t i = 1; i < x.size(); ++i){
if(std::abs(x.Get(i)) > std::abs(x.Get(ret))){
ret = i;
}
}
return ret;
}
//// Dot
template <class TX, class TY>
typename IsReadableVector<typename TX::readable_vector,
typename IsReadableVector<typename TY::readable_vector,
typename TX::value_type
>::type>::type
Dot(const TX &x, const TY &y){
assert(x.size() == y.size());
typename TX::value_type sum(0);
for(size_t i = 0; i < x.size(); ++i){
sum += x.Get(i)*y.Get(i);
}
return sum;
}
//// ConjugateDot
#ifdef USE_COMPLEX_MATRICES
template <class TXC, class TY>
typename IsReadableVector<typename TXC::readable_vector,
typename IsReadableVector<typename TY::readable_vector,
typename TXC::value_type
>::type>::type
ConjugateDot(const TXC &xc, const TY &y){
assert(xc.size() == y.size());
typename TXC::value_type sum(0);
for(size_t i = 0; i < xc.size(); ++i){
sum += std::conj(xc[i])*y[i];
}
return sum;
}
#endif // USE_COMPLEX_MATRICES
//// Scale
template <class TA>
typename IsWritableMatrixView<typename TA::writable_matrix,
MatrixOpStatus
>::type
Scale(const TA &A, const typename TA::value_type &scale){
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = 0; i < A.Rows(); ++i){
A.Set(i,j, scale * A.Get(i,j));
}
}
return OK;
}
template <class TA>
typename IsWritableMatrix<typename TA::writable_matrix,
MatrixOpStatus
>::type
Scale(TA &A, const typename TA::value_type &scale){
return Scale(TrivialWritableMatrixView<TA>(A), scale);
}
template <class TX>
typename IsWritableVectorView<typename TX::writable_vector,
MatrixOpStatus
>::type
Scale(const TX &x, const typename TX::value_type &scale){
for(size_t i = 0; i < x.size(); ++i){
x.Set(i, scale * x.Get(i));
}
return OK;
}
template <class TX>
typename IsWritableVector<typename TX::writable_vector,
MatrixOpStatus
>::type
Scale(TX &x, const typename TX::value_type &scale){
return Scale(TrivialWritableVectorView<TX>(x), scale);
}
//// Add
template <class Tsrc, class Tdst>
typename IsReadableMatrix<typename Tsrc::readable_matrix,
typename IsWritableMatrixView<typename Tdst::writable_matrix,
MatrixOpStatus
>::type>::type
Add(const Tsrc &src, const Tdst &dst, const typename Tdst::value_type &scale_src = typename Tdst::value_type(1)){
assert(src.Rows() == dst.Rows());
assert(src.Cols() == dst.Cols());
#ifdef USE_MATRIX_OPS_CHECKS
if(src.Rows() != dst.Rows() && src.Cols() != dst.Cols()){ return DIMENSION_MISMATCH; }
#endif
for(size_t j = 0; j < dst.Cols(); ++j){
for(size_t i = 0; i < dst.Rows(); ++i){
dst.Set(i,j, dst.Get(i,j) + scale_src * src.Get(i,j));
}
}
return OK;
}
template <class Tsrc, class Tdst>
typename IsReadableMatrix<typename Tsrc::readable_matrix,
typename IsWritableMatrix<typename Tdst::writable_matrix,
MatrixOpStatus
>::type>::type
Add(const Tsrc &src, Tdst &dst, const typename Tdst::value_type &scale_src = typename Tdst::value_type(1)){
return Add(src, TrivialWritableMatrixView<Tdst>(dst), scale_src);
}
template <class Tsrc, class Tdst>
typename IsReadableVector<typename Tsrc::readable_vector,
typename IsWritableVectorView<typename Tdst::writable_vector,
MatrixOpStatus
>::type>::type
Add(const Tsrc &src, const Tdst &dst, const typename Tdst::value_type &scale_src = typename Tdst::value_type(1)){
assert(src.size() == dst.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(src.size() != dst.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < dst.size(); ++i){
dst.Set(i, dst.Get(i) + scale_src * src.Get(i));
}
return OK;
}
template <class Tsrc, class Tdst>
typename IsReadableVector<typename Tsrc::readable_vector,
typename IsWritableVector<typename Tdst::writable_vector,
MatrixOpStatus
>::type>::type
Add(const Tsrc &src, Tdst &dst, const typename Tdst::value_type &scale_src = typename Tdst::value_type(1)){
return Add(src, TrivialWritableVectorView<Tdst>(dst), scale_src);
}
//// Rank1Update
template <class TA, class TX, class TYt>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsReadableVector<typename TX::readable_vector,
typename IsReadableVector<typename TYt::readable_vector,
MatrixOpStatus
>::type>::type>::type
Rank1Update(const TA &A, const TX &X, const TYt &Yt, const typename TA::value_type &scale_XY = typename TA::value_type(1)){
assert(A.Rows() == X.size());
assert(A.Cols() == Yt.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Rows() != X.size() || A.Cols() != Yt.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = 0; i < A.Rows(); ++i){
A.Set(i,j, A.Get(i,j) + scale_XY * X.Get(i)*Yt.Get(j));
}
}
return OK;
}
template <class TA, class TX, class TYt>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsReadableVector<typename TX::readable_vector,
typename IsReadableVector<typename TYt::readable_vector,
MatrixOpStatus
>::type>::type>::type
Rank1Update(TA &A, const TX &X, const TYt &Yt, const typename TA::value_type &scale_XY = typename TA::value_type(1)){
return Rank1Update(TrivialWritableMatrixView<TA>(A), X, Yt, scale_XY);
}
/*
#ifdef USE_COMPLEX_MATRICES
template <class TA, class TX>
MatrixOpStatus Rank1Update(const WritableMatrixView<TA> &A, const ReadableVector<TX> &X, const TA& scaleXX = TA(1)){
assert(A.Rows() == X.size());
assert(A.Cols() == X.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Rows() != X.size() || A.Cols() != X.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = 0; i < A.Rows(); ++i){
A(i,j) += scaleXX * X[i]*std::conj(X[j]);
}
}
return OK;
}
#endif // USE_COMPLEX_MATRICES
//// Rank2Update
#ifdef USE_COMPLEX_MATRICES
template <class TA, class TX, class TY>
MatrixOpStatus Rank2Update(const WritableMatrixView<TA> &A, const ReadableVector<TX> &X, const ReadableVector<TY> &Y, const TA &scaleXY = TA(1)){
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Rows() != A.Cols() || A.Rows() != X.size() || A.Cols() != Y.size()){ return DIMENSION_MISMATCH; }
#endif
#ifdef USE_MATRIX_OPS_ASSERTS
assert(A.Rows() == A.Cols());
assert(A.Rows() == X.size());
assert(A.Cols() == Y.size());
#endif
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = 0; i < A.Rows(); ++i){
A(i,j) += scaleXY * (X[i]*std::conj(Y[j]) + Y[i]*std::conj(X[i]));
}
}
return OK;
}
#endif // USE_COMPLEX_MATRICES
*/
//// Mult matrix vector
template <class TA, class TX, class TY>
typename IsReadableMatrix<typename TA::readable_matrix,
typename IsReadableVector<typename TX::readable_vector,
typename IsWritableVectorView<typename TY::writable_vector,
MatrixOpStatus
>::type>::type>::type
Mult(const TA &A, const TX &X, const TY &Y, const typename TY::value_type &scale_AX = typename TY::value_type(1), const typename TY::value_type &scale_Y = typename TY::value_type(0)){
assert(A.Cols() == X.size());
assert(A.Rows() == Y.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Cols() != X.size() || A.Rows() == Y.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < A.Rows(); ++i){
typename TY::value_type sum(0);
for(size_t j = 0; j < A.Cols(); ++j){
sum += A.Get(i,j)*X.Get(j);
}
Y.Set(i, scale_AX * sum + scale_Y * Y.Get(i));
}
return OK;
}
template <class TA, class TX, class TY>
typename IsReadableMatrix<typename TA::readable_matrix,
typename IsReadableVector<typename TX::readable_vector,
typename IsWritableVector<typename TY::writable_vector,
MatrixOpStatus
>::type>::type>::type
Mult(const TA &A, const TX &X, TY &Y, const typename TY::value_type &scale_AX = typename TY::value_type(1), const typename TY::value_type &scale_Y = typename TY::value_type(0)){
return Mult(A, X, TrivialWritableVectorView<TY>(Y), scale_AX, scale_Y);
}
//// Mult matrix matrix
template <class TA, class TB, class TC>
typename IsReadableMatrix<typename TA::readable_matrix,
typename IsReadableMatrix<typename TB::readable_matrix,
typename IsWritableMatrixView<typename TC::writable_matrix,
MatrixOpStatus
>::type>::type>::type
Mult(const TA &A, const TB &B, const TC &C, const typename TC::value_type &scale_AB = typename TC::value_type(1), const typename TC::value_type &scale_C = typename TC::value_type(0)){
assert(A.Cols() == B.Rows());
assert(A.Rows() == C.Rows());
assert(B.Cols() == C.Cols());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Cols() != B.Rows() || A.Rows() == C.Rows() || B.Cols() == C.Cols()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < A.Rows(); ++i){
for(size_t j = 0; j < B.Cols(); ++j){
typename TC::value_type sum(0);
for(size_t k = 0; k < A.Cols(); ++k){
sum += A.Get(i,k)*B.Get(k,j);
}
C.Set(i,j, scale_AB * sum + scale_C * C.Get(i,j));
}
}
return OK;
}
template <class TA, class TB, class TC>
typename IsReadableMatrix<typename TA::readable_matrix,
typename IsReadableMatrix<typename TB::readable_matrix,
typename IsWritableMatrix<typename TC::writable_matrix,
MatrixOpStatus
>::type>::type>::type
Mult(const TA &A, const TB &B, TC &C, const typename TC::value_type &scale_AB = typename TC::value_type(1), const typename TC::value_type &scale_C = typename TC::value_type(0)){
return Mult(A, B, TrivialWritableMatrixView<TC>(C), scale_AB, scale_C);
}
//// Mult diagonal
template <class TD, class TA>
typename IsWritableMatrixView<typename TA::writable_matrix,
MatrixOpStatus
>::type
Mult(const TDiagonalMatrix<TD> &D, const TA &A){
assert(D.size() == A.Rows());
#ifdef USE_MATRIX_OPS_CHECKS
if(D.size() != A.Rows()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < A.Rows(); ++i){
Scale(GetRow(A,i), D[i]);
}
return OK;
}
template <class TD, class TA>
typename IsWritableMatrix<typename TA::writable_matrix,
MatrixOpStatus
>::type
Mult(const TDiagonalMatrix<TD> &D, TA &A){
return Mult(D, TrivialWritableMatrixView<TA>(A));
}
template <class TA, class TD>
typename IsWritableMatrixView<typename TA::writable_matrix,
MatrixOpStatus
>::type
Mult(const TA &A, const TDiagonalMatrix<TD> &D){
assert(D.size() == A.Cols());
#ifdef USE_MATRIX_OPS_CHECKS
if(D.size() != A.Cols()){ return DIMENSION_MISMATCH; }
#endif
for(size_t j = 0; j < A.Cols(); ++j){
Scale(GetColumn(A,j), D[j]);
}
return OK;
}
template <class TA, class TD>
typename IsWritableMatrix<typename TA::writable_matrix,
MatrixOpStatus
>::type
Mult(TA &A, const TDiagonalMatrix<TD> &D){
return Mult(TrivialWritableMatrixView<TA>(A), D);
}
template <class TD, class TX>
typename IsWritableVectorView<typename TX::writable_vector,
MatrixOpStatus
>::type
Mult(const TDiagonalMatrix<TD> &D, const TX &X){
assert(D.size() == X.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(D.size() != X.size()){ return DIMENSION_MISMATCH; }
#endif
for(size_t i = 0; i < X.size(); ++i){
X.Set(i, D[i] * X.Get(i));
}
return OK;
}
template <class TD, class TX>
typename IsWritableVector<typename TX::writable_vector,
MatrixOpStatus
>::type
Mult(const TDiagonalMatrix<TD> &D, TX &X){
return Mult(D, TrivialWritableMatrixView<TX>(X));
}
#ifdef USE_COMPLEX_MATRICES
template <class TX>
typename IsReadableVector<typename TX::readable_vector,
typename TX::value_type
>::type
Norm(const TX &X){
typename TX::value_type sum(0);
for(size_t i = 0; i < X.Rows(); ++i){
sum += std::pow(std::abs(X.Get(i)), 2);
}
return std::sqrt(sum);
}
template <class TA>
typename IsReadableMatrix<typename TA::readable_matrix,
typename TA::value_type
>::type
FrobeniusNorm(const TA &A){
typename TA::value_type sum(0);
for(size_t j = 0; j < A.Cols(); ++j){
for(size_t i = 0; i < A.Rows(); ++i){
sum += std::pow(std::abs(A.Get(i,j)), 2);
}
}
return std::sqrt(sum);
}
#endif // USE_COMPLEX_MATRICES
#ifdef USING_TCCS_MATRIX
#include "TCCSMatrix.h"
template <class TA, class TX, class TY, class TAlloc>
typename IsWritableVector<typename TY::writable_vector,
MatrixOpStatus
>::type
Mult(
const TCCSMatrix<TA,TAlloc> &A, const TX &X, TY &Y,
const typename TY::value_type &scale_AX = typename TY::value_type(1),
const typename TY::value_type &scale_Y = typename TY::value_type(0)
){
assert(A.Cols() == X.size());
assert(A.Rows() == Y.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Cols() != X.size() || A.Rows() == Y.size()){ return DIMENSION_MISMATCH; }
#endif
Scale(Y, scale_Y);
if(A.flags & TCCSMatrix<TA,TAlloc>::SYMMETRIC){
for(int j = 0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[i] += scale_AX*X[j]*A.values[ip];
if(i != j){ Y[j] += scale_AX*X[i]*A.values[ip]; }
}
}
}
#ifdef USE_COMPLEX_MATRICES
else if(A.flags & TCCSMatrix<TA,TAlloc>::HERMITIAN){
for(int j=0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[i] += scale_AX*X[j]*A.values[ip];
if(i != j){ Y[j] += scale_AX*X[i]*std::conj(A.values[ip]); }
}
}
}
#endif
else{
for(int j = 0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[i] += scale_AX*X[j]*A.values[ip];
}
}
}
return OK;
}
template <class TA, class TX, class TY, class TAlloc>
typename IsWritableVector<typename TY::writable_vector,
MatrixOpStatus
>::type
Mult(
const ConjugateTransposeView<TrivialReadableMatrixView<TCCSMatrix<TA,TAlloc> > > &A, const TX &X, TY &Y,
const typename TY::value_type &scale_AX = typename TY::value_type(1),
const typename TY::value_type &scale_Y = typename TY::value_type(0)
){
assert(A.Rows() == X.size());
assert(A.Cols() == Y.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Rows() != X.size() || A.Cols() == Y.size()){ return DIMENSION_MISMATCH; }
#endif
Scale(Y, scale_Y);
if(A.flags & TCCSMatrix<TA,TAlloc>::SYMMETRIC){
for(int j = 0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[j] += scale_AX*X[i]*std::conj(A.values[ip]);
if(i != j){ Y[i] += scale_AX*X[j]*std::conj(A.values[ip]); }
}
}
}
#ifdef USE_COMPLEX_MATRICES
else if(A.flags & TCCSMatrix<TA,TAlloc>::HERMITIAN){
for(int j=0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[j] += scale_AX*X[i]*A.values[ip];
if(i != j){ Y[i] += scale_AX*X[j]*std::conj(A.values[ip]); }
}
}
}
#endif
else{
for(int j = 0; j < (int)A.Cols(); j++){
for(int ip = A.colptr[j]; ip < A.colptr[j+1]; ip++){
int i = A.rowind[ip];
Y[j] += scale_AX*X[j]*std::conj(A.values[ip]);
}
}
}
return OK;
}
#endif // USING_TCCS_MATRIX
#ifdef USE_ADVANCED_MATRIX_OPS
//// LUDecomposition(A, P, L, U) - A == P*L*U
template <class TA>
typename IsWritableMatrixView<typename TA::writable_matrix,
MatrixOpStatus
>::type
LUDecomposition(const TA &A, WritableVector<size_t> &Pivots){
typedef typename TA::value_type value_type;
const size_t min_dim = ((A.Rows() < A.Cols()) ? A.Rows() : A.Cols());
assert(min_dim == Pivots.size());
#ifdef USE_MATRIX_OPS_CHECKS
if(min_dim != Pivots.size()){ return DIMENSION_MISMATCH; }
#endif
size_t info = 0;
for(size_t j = 0; j < min_dim; ++j){
size_t jp = j + LargestElementIndex(SubVector(GetColumn(A, j), j, A.Rows()-j));
Pivots[j] = jp;
if(value_type(0) != A(jp,j)){
if(jp != j){
Swap(GetRow(A, j), GetRow(A, jp));
}
if(j < A.Rows()){
Scale(SubVector(GetColumn(A,j),j+1,A.Rows()-j-1), value_type(1)/A(j,j)); // possible overflow when inverting A(j,j)
}
}else{
info = j;
}
if(j < min_dim){
Rank1Update(SubMatrix(A, j+1,j+1, A.Rows()-j-1, A.Cols()-j-1), SubVector(GetColumn(A,j), j+1, A.Rows()-j-1), SubVector(GetRow(A,j),j+1, A.Cols()-j-1), value_type(-1));
}
}
if(0 != info){ return SINGULAR_MATRIX; }
else{ return OK; }
}
template <class TA>
typename IsWritableMatrix<typename TA::writable_matrix,
MatrixOpStatus
>::type
LUDecomposition(TA &A, WritableVector<size_t> &Pivots){
return LUDecomposition(TrivialWritableMatrixView<TA>(A), Pivots);
}
//// SolveDestructive(A, X) - X holds B, A gets overwritten with LU, X overwritten with solution
template <class TA, class TX>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableMatrixView<typename TX::writable_matrix,
MatrixOpStatus
>::type>::type
SolveDestructive(const TA &A, const TX &X){
typedef typename TX::value_type value_type;
TVector<size_t> Pivots(A.Rows());
MatrixOpStatus ret;
ret = LUDecomposition(A, Pivots);
// Apply pivots
for(size_t i = 0; i < Pivots.size(); ++i){
if(Pivots[i] != i){
Swap(GetRow(X,i), GetRow(X,Pivots[i]));
}
}
// Solve lower unit
for(size_t j = 0; j < X.Cols(); ++j){
for(size_t k = 0; k < X.Rows(); ++k){
if(value_type(0) != X(k,j)){
for(size_t i = k+1; i < X.Rows(); ++i){
X.Set(i,j, X.Get(i,j) - X.Get(k,j)*A.Get(i,k));
}
}
}
}
// Solver upper non unit
for(size_t j = 0; j < X.Cols(); ++j){
for(size_t k = X.Rows()-1; (signed)k >= 0; --k){
if(value_type(0) != X(k,j)){
X(k,j) /= A(k,k);
for(size_t i = 0; i < k; ++i){
X.Set(i,j, X.Get(i,j) - X.Get(k,j)*A.Get(i,k));
}
}
}
}
return ret;
}
template <class TA, class TX>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableMatrixView<typename TX::writable_matrix,
MatrixOpStatus
>::type>::type
SolveDestructive(TA &A, const TX &X){
return SolveDestructive(TrivialWritableMatrixView<TA>(A), X);
}
template <class TA, class TX>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableMatrix<typename TX::writable_matrix,
MatrixOpStatus
>::type>::type
SolveDestructive(const TA &A, TX &X){
return SolveDestructive(A, TrivialWritableMatrixView<WritableMatrix<TX> >(X));
}
template <class TA, class TX>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableMatrix<typename TX::writable_matrix,
MatrixOpStatus
>::type>::type
SolveDestructive(TA &A, TX &X){
return SolveDestructive(TrivialWritableMatrixView<TA>(A), TrivialWritableMatrixView<TX>(X));
}
template <class TA, class TX>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableVectorView<typename TX::writable_vector,
MatrixOpStatus
>::type>::type
SolveDestructive(const TA &A, const TX &X){
typedef typename TX::value_type value_type;
TVector<size_t> Pivots(A.Rows());
MatrixOpStatus ret;
ret = LUDecomposition(A, Pivots);
// Apply pivots
for(size_t i = 0; i < Pivots.size(); ++i){
if(Pivots[i] != i){
std::swap(X[i], X[Pivots[i]]);
}
}
// Solve lower unit
for(size_t k = 0; k < X.size(); ++k){
if(value_type(0) != X[k]){
for(size_t i = k+1; i < X.size(); ++i){
X.Set(i, X.Get(i) - X.Get(k)*A.Get(i,k));
}
}
}
// Solve upper non unit
for(size_t k = X.size()-1; (signed)k >= 0; --k){
if(value_type(0) != X[k]){
X[k] /= A(k,k);
for(size_t i = 0; i < k; ++i){
X.Set(i, X.Get(i) - X.Get(k)*A.Get(i,k));
}
}
}
return ret;
}
template <class TA, class TX>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableVectorView<typename TX::writable_vector,
MatrixOpStatus
>::type>::type
SolveDestructive(TA &A, const TX &X){
return SolveDestructive(TrivialWritableMatrixView<TA>(A), X);
}
template <class TA, class TX>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableVector<typename TX::writable_vector,
MatrixOpStatus
>::type>::type
SolveDestructive(const TA &A, TX &X){
return SolveDestructive(A, TrivialWritableVectorView<TX>(X));
}
template <class TA, class TX>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableVector<typename TX::writable_vector,
MatrixOpStatus
>::type>::type
SolveDestructive(TA &A, TX &X){
return SolveDestructive(TrivialWritableMatrixView<TA>(A), TrivialWritableVectorView<TX>(X));
}
//// Solve(A, B, X) - A*X == B
//// Invert(A)
template <class TA, class TAinv>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableMatrixView<typename TAinv::writable_matrix,
MatrixOpStatus
>::type>::type
InvertDestructive(const TA &A, const TAinv &Ainv){
Fill(Ainv, typename TAinv::value_type(0));
Fill(Diagonal(Ainv), typename TAinv::value_type(1));
return SolveDestructive(A, Ainv);
}
template <class TA, class TAinv>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableMatrixView<typename TAinv::writable_matrix,
MatrixOpStatus
>::type>::type
InvertDestructive(TA &A, const TAinv &Ainv){
return InvertDestructive(TrivialWritableMatrixView<TA>(A), Ainv);
}
template <class TA, class TAinv>
typename IsWritableMatrixView<typename TA::writable_matrix,
typename IsWritableMatrix<typename TAinv::writable_matrix,
MatrixOpStatus
>::type>::type
InvertDestructive(const TA &A, TAinv &Ainv){
return InvertDestructive(A, TrivialWritableMatrixView<TAinv>(Ainv));
}
template <class TA, class TAinv>
typename IsWritableMatrix<typename TA::writable_matrix,
typename IsWritableMatrix<typename TAinv::writable_matrix,
MatrixOpStatus
>::type>::type
InvertDestructive(TA &A, TAinv &Ainv){
return InvertDestructive(TrivialWritableMatrixView<TA>(A), TrivialWritableMatrixView<TAinv>(Ainv));
}
//// Eigensystem(A, L, X) - A*X == X*diag(L)
template <class TA, class TAlloc>
MatrixOpStatus Eigensystem(const TMatrix<TA,TAlloc> &A, TVector<TA,TAlloc> &Eval, TMatrix<TA,TAlloc> &Evec){
#ifdef USE_MATRIX_OPS_CHECKS
if(A.Rows() != A.Cols() || A.Rows() != Eval.size() || Evec.Rows() != A.Rows() || Evec.Cols() != A.Cols()){ return DIMENSION_MISMATCH; }
#endif
#ifdef USE_MATRIX_OPS_ASSERTS
assert(A.Rows() == A.Cols());
assert(A.Rows() == Evec.Rows());
assert(A.Cols() == Evec.Cols());
assert(A.Rows() == Eval.size());
#endif
return OK;
}
#endif // USE_ADVANCED_MATRIX_OPS
}; // namespace MatrixOps
#endif // _MATRIX_OPS_H_
|
[
"[email protected]"
] |
[
[
[
1,
977
]
]
] |
afd589712b753576248029776262123869c7c14f
|
0f40e36dc65b58cc3c04022cf215c77ae31965a8
|
/src/apps/vis/properties/vis_comradius_property_set.cpp
|
dd12a2cfe3cfccae85fc3fcc58f819214bf44422
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
venkatarajasekhar/shawn-1
|
08e6cd4cf9f39a8962c1514aa17b294565e849f8
|
d36c90dd88f8460e89731c873bb71fb97da85e82
|
refs/heads/master
| 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,821 |
cpp
|
/************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/properties/vis_comradius_property_set.h"
#include "apps/vis/properties/vis_property_names.h"
#include "apps/vis/properties/vec/vis_property_constant_vec.h"
#include "apps/vis/properties/double/vis_property_constant_double.h"
#include "apps/vis/elements/vis_drawable_comradius.h"
namespace vis
{
ComradiusPropertySet::
ComradiusPropertySet()
{}
// ----------------------------------------------------------------------
ComradiusPropertySet::
~ComradiusPropertySet()
{}
// ----------------------------------------------------------------------
void
ComradiusPropertySet::
init( const Element& e )
throw( std::runtime_error )
{
DrawablePropertySet::init(e);
IMPL_PROPERTY( position, shawn::Vec );
IMPL_PROPERTY( blend, double );
stack_blend_->add_t( auto_init_property(
new PropertyConstantDoubleTask::PropertyConstantDouble(0)));
// stack_position_->add_t( auto_init_property( new PropertyConstantVecTask::PropertyConstantVec(shawn::Vec(0,0,0))));
stack_priority_->add_t(auto_init_property(
new PropertyConstantDoubleTask::PropertyConstantDouble(0.1)));
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
48
]
]
] |
9b1077c0a1232dd204edc8c3a4dde994034bbec5
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Samples/AIAD/Character.h
|
74810900be093d7eb6416832c8cfd2ca2f4b1cfd
|
[] |
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 | 15,658 |
h
|
/*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: Character.h
Version: 0.01
---------------------------------------------------------------------------
*/
#pragma once
#include "Prerequisities.h"
#include "AIManager.h"
#include "Vector3.h"
#include "NodeLightning.h"
using namespace nGENE;
using namespace nGENE::AI;
using nGENE::Nature::NodeLightning;
enum ENTITY_TYPE
{
GROUND_PLANE = 11,
DEBRIS = 12,
ENEMY = 13,
ENEMY_PROJECTILE = 14,
PROJECTILE = 15,
ITEM = 16
};
class App;
class CPUCharacter;
class Item
{
public:
virtual void use() {};
};
class Projectile
{
protected:
static uint s_nProjectilesCount;
uint m_nDamage;
NodeVisible* m_pVisual;
PhysicsActor* m_pPhysics;
bool m_bToBeDisposed;
bool m_bEnemy;
Vector3 m_vecVelocity;
wstring m_stName;
public:
Projectile():
m_bToBeDisposed(false)
{
}
virtual ~Projectile();
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material, Vector3& _position, bool _enemyShot,
bool _movable, Vector3 _direction=Vector3::UNIT_Z);
void dispose()
{
m_bToBeDisposed = true;
}
bool isDisposed() const
{
return m_bToBeDisposed;
}
wstring& getName();
Vector3& getPosition();
virtual void update(Real _delta);
};
class BombProjectile: public Projectile
{
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material, Vector3& _position, bool _enemyShot,
bool _movable, Vector3 _direction=Vector3::UNIT_Z);
};
class MissileProjectile: public Projectile
{
protected:
Vector3 m_vecPrevPos;
Vector3 m_vecPrevDir;
CPUCharacter* m_pEnemy;
wstring m_stEnemyName;
NodeParticleSystem* m_pPS;
NodeLight* m_pLight;
public:
virtual ~MissileProjectile();
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material, Vector3& _position, bool _enemyShot,
bool _movable, Vector3 _direction=Vector3::UNIT_Z);
virtual void update(Real _delta);
};
inline wstring& Projectile::getName()
{
return m_stName;
}
class Character;
class DebrisPart
{
protected:
static uint s_nDebrisCount;
NodeVisible* m_pVisual;
PhysicsActor* m_pActor;
public:
virtual ~DebrisPart();
void init(SceneManager* _manager, Vector3& _position);
};
class Explosion
{
protected:
static uint s_nExplosionsCount;
NodeParticleSystem* m_pPS;
NodeVisible* m_pDebris;
NodeLight* m_pLight;
PhysicsActor* m_pActor;
DebrisPart m_Part1;
DebrisPart m_Part2;
DebrisPart m_Part3;
/*DebrisPart m_Part4;
DebrisPart m_Part5;
DebrisPart m_Part6;*/
bool m_bMovable;
uint m_nPassed;
uint m_nPrev;
wstring m_stName;
public:
Explosion():
m_pPS(NULL),
m_pDebris(NULL),
m_pActor(NULL)
{
}
virtual ~Explosion();
virtual void init(SceneManager* _manager, Vector3& _position,
Character* _character);
void update();
bool isDisposed() const;
wstring& getName()
{
return m_stName;
}
};
class Decorator
{
public:
static uint s_nDecoratorsCount;
protected:
NodeVisible* m_pVisual;
//PhysicsActor* m_pActor;
wstring m_stName;
bool m_bToBeDisposed;
public:
Decorator():
m_bToBeDisposed(false)
{
}
virtual ~Decorator();
virtual void init(SceneManager* _manager, Vector3& _position);
wstring& getName()
{
return m_stName;
}
void dispose()
{
m_bToBeDisposed = true;
}
bool isDisposed() const
{
return m_bToBeDisposed;
}
Vector3& getPosition();
};
class Weapon: public Item
{
protected:
uint m_nClipSize;
uint m_nShootSpeed;
uint m_nAmmoLeft;
bool m_bInfiniteAmmo;
uint m_nMaxUses;
uint m_nCurrentUses;
wstring m_stType;
public:
Weapon():
m_nMaxUses(0),
m_nCurrentUses(0),
m_bInfiniteAmmo(true),
m_nAmmoLeft(10),
m_nClipSize(10)
{
}
void reset()
{
m_nAmmoLeft = m_nClipSize;
}
uint getAmmoLeft() const
{
return m_nAmmoLeft;
}
bool isInfiniteAmmo() const
{
return m_bInfiniteAmmo;
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true) {
};
void setMaxUses(uint _value)
{
m_nMaxUses = _value;
m_nCurrentUses = _value;
}
uint getClipSize() const
{
return m_nClipSize;
}
virtual void update() {}
virtual wstring& getTypeName()
{
return m_stType;
}
virtual void addAmmo(uint _count)
{
if(!m_bInfiniteAmmo)
m_nAmmoLeft += _count;
}
};
class BasicWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material)
{
m_pSM = _manager;
m_pWorld = _world;
m_pMaterial = _material;
m_stType = L"one_shot";
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
};
class TwoShotsWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material)
{
m_pSM = _manager;
m_pWorld = _world;
m_pMaterial = _material;
m_stType = L"two_shot";
m_bInfiniteAmmo = false;
m_nAmmoLeft = 50;
m_nClipSize = 50;
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
};
class ThreeShotsWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material)
{
m_pSM = _manager;
m_pWorld = _world;
m_pMaterial = _material;
m_stType = L"three_shot";
m_bInfiniteAmmo = false;
m_nAmmoLeft = 30;
m_nClipSize = 30;
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
};
class LightningWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
NodeLightning m_Bolt;
wstring m_stEnemyName;
CPUCharacter* m_pEnemy;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material);
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
virtual void update();
};
class TwoLightningWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
NodeLightning m_Bolt1;
NodeLightning m_Bolt2;
wstring m_stEnemyName1;
wstring m_stEnemyName2;
CPUCharacter* m_pEnemy1;
CPUCharacter* m_pEnemy2;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material);
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
virtual void update();
};
class BombWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material)
{
m_pSM = _manager;
m_pWorld = _world;
m_pMaterial = _material;
m_stType = L"bomb";
m_bInfiniteAmmo = false;
m_nAmmoLeft = 5;
m_nClipSize = 5;
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
};
class MissileWeapon: public Weapon
{
protected:
SceneManager* m_pSM;
PhysicsWorld* m_pWorld;
PhysicsMaterial* m_pMaterial;
public:
virtual void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material)
{
m_pSM = _manager;
m_pWorld = _world;
m_pMaterial = _material;
m_stType = L"missile";
m_bInfiniteAmmo = false;
m_nAmmoLeft = 10;
m_nClipSize = 10;
}
virtual void use(Vector3& _position, bool _enemyShot, bool _movable=true);
//virtual void update();
};
class UsableItem;
/** Representation of the item on the map.
*/
class PickupItem
{
private:
union
{
UsableItem* m_pItem;
Weapon* m_pWeapon;
};
NodeVisible* m_pVisual;
NodeLight* m_pLight;
PhysicsActor* m_pActor;
bool m_bWeapon;
static uint s_nItemsCount;
wstring m_stName;
wstring m_stType;
bool m_bToBeDisposed;
public:
PickupItem():
m_bToBeDisposed(false),
m_pItem(NULL),
m_bWeapon(false)
{
}
virtual ~PickupItem();
void setItem(UsableItem* _item);
UsableItem* getItem() const;
void setWeapon(Weapon* _weapon)
{
m_pWeapon = _weapon;
m_bWeapon = true;
}
Weapon* getWeapon() const
{
if(m_bWeapon)
return m_pWeapon;
else
return NULL;
}
void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material, Vector3& _position, wstring& _type);
wstring& getName();
wstring& getType()
{
return m_stType;
}
void dispose()
{
m_bToBeDisposed = true;
}
bool isDisposed() const
{
return m_bToBeDisposed;
}
Vector3& getPosition();
virtual void pick();
};
class HealItem: public PickupItem
{
public:
void pick();
};
class MoreHealthItem: public PickupItem
{
public:
void pick();
};
class UsableItem: public Item
{
protected:
uint m_nDuration;
uint m_nPassed;
uint m_nPrev;
bool m_bFinished;
public:
UsableItem()
{
m_nDuration = 0;
m_nPassed = 0;
m_bFinished = false;
}
virtual void onUse()
{
m_nPrev = Engine::getSingleton().getTimer().getMilliseconds();
if(m_nPassed >= m_nDuration)
m_nPassed = 0;
m_bFinished = false;
update();
}
virtual void onEnd()
{
m_bFinished = true;
}
virtual bool update()
{
if(m_nDuration)
{
uint now = Engine::getSingleton().getTimer().getMilliseconds();
uint diff = now - m_nPrev;
m_nPassed += diff;
if(m_nPassed >= m_nDuration)
{
onEnd();
return true;
}
m_nPrev = now;
}
return false;
}
bool isFinished() const
{
return m_bFinished;
}
void setDuration(uint _value)
{
m_nDuration = _value;
}
};
class ShieldUsableItem: public UsableItem
{
public:
ShieldUsableItem()
{
m_nDuration = 10000;
}
virtual bool update();
virtual void onUse();
virtual void onEnd();
};
class AgilityUsableItem: public UsableItem
{
public:
AgilityUsableItem()
{
m_nDuration = 10000;
}
virtual bool update();
virtual void onUse();
virtual void onEnd();
};
class SlowMotionUsableItem: public UsableItem
{
public:
SlowMotionUsableItem()
{
m_nDuration = 10000;
}
virtual bool update();
virtual void onUse();
virtual void onEnd();
};
class PointsItem: public PickupItem
{
public:
void pick();
};
class Character
{
protected:
uint m_nMaxHP;
uint m_nCurrentHP;
NodeVisible* m_pVisual;
Weapon* m_pActiveWeapon;
vector <Item> m_Equipment;
bool m_bMovable;
bool m_bShielded;
public:
Character();
virtual ~Character();
virtual void move(const Vector2& _dir);
void setCurrentHP(uint _value)
{
m_nCurrentHP = _value;
}
virtual uint getCurrentHP() const;
virtual uint getMaxHP() const
{
return m_nMaxHP;
}
void setMaxHP(uint _value)
{
m_nMaxHP = _value;
}
void setShielded(bool _value)
{
m_bShielded = _value;
}
bool isShielded() const
{
return m_bShielded;
}
void addItem(const Item& _item);
virtual void setActiveWeapon(Weapon* _weapon);
Weapon* getActiveWeapon() const;
Vector3& getPosition();
bool isMovable() const
{
return m_bMovable;
}
};
class CPUCharacter;
enum EVENT_TYPE
{
ET_HIT,
ET_NOHITPOINTS
};
class MyState: public AIActorFSMState
{
protected:
CPUCharacter* m_pCharacter;
public:
void setCharacter(CPUCharacter* _character);
};
inline void MyState::setCharacter(CPUCharacter* _character)
{
m_pCharacter = _character;
}
//----------------------------------------------------------------------
class StateMoving: public MyState
{
public:
void update();
};
class StateDead: public MyState
{
public:
void onEnter();
void update();
};
enum MOVEMENT_TYPE
{
MT_BASIC,
MT_PATH_SIN,
MT_PATH_COS,
MT_PATH_CHAIN
};
struct SHiScoreEntry
{
wstring player;
uint points;
};
class CPUCharacter: public Character, public AIActor
{
EXPOSE_TYPE
public:
static uint s_nEnemiesCount;
private:
PhysicsActor* m_pActor;
Material* m_pBase;
Vector3 m_vecStartPos;
wstring m_stName;
StateMoving m_StateMoving;
StateDead m_StateDead;
FSMBrain m_Brain;
FiniteStateMachine m_FSM;
bool m_bToBeDisposed;
bool m_bHit;
float m_fVelocity;
dword m_nPrevTime;
dword m_nHitPassed;
float m_fAmplitude;
float m_fShootDelta;
float m_fShootFrequency;
float m_fMovementPassed;
float m_fFreq;
MOVEMENT_TYPE m_MovementType;
virtual void makeShot(float _delta);
virtual void makeMovement(float _delta);
public:
CPUCharacter():
m_bToBeDisposed(false),
m_fVelocity(1.8f),
m_fShootDelta(0.0f),
m_fShootFrequency(1000.0f),
m_bHit(false),
m_fMovementPassed(0.0f)
{
}
CPUCharacter(IBrain* _brain):
AIActor(_brain),
m_bToBeDisposed(false),
m_fVelocity(1.8f),
m_fShootDelta(0.0f),
m_fShootFrequency(1000.0f),
m_bHit(false),
m_fMovementPassed(0.0f)
{
}
virtual ~CPUCharacter();
void init(SceneManager* _manager, PhysicsWorld* _world,
PhysicsMaterial* _material, bool _movable, Vector3& _position, Vector3& _size,
NodeVisible* _enemy, Vector3& _offset, MOVEMENT_TYPE _movement,
float _amplitude, float _frequency, float _speedMult);
void cleanup();
void update();
wstring& getName();
virtual void onHit(uint _damagePoints);
void dispose()
{
m_bToBeDisposed = true;
}
bool isDisposed() const
{
return m_bToBeDisposed;
}
void setPosition(Vector3& _pos);
};
inline void Character::setActiveWeapon(Weapon* _weapon)
{
m_pActiveWeapon = _weapon;
}
//----------------------------------------------------------------------
inline Weapon* Character::getActiveWeapon() const
{
return m_pActiveWeapon;
}
//----------------------------------------------------------------------
inline void PickupItem::setItem(UsableItem* _item)
{
m_pItem = _item;
}
//----------------------------------------------------------------------
inline UsableItem* PickupItem::getItem() const
{
return m_pItem;
}
//----------------------------------------------------------------------
inline wstring& PickupItem::getName()
{
return m_stName;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//----------------------------------------------------------------------
inline wstring& CPUCharacter::getName()
{
return m_stName;
}
//----------------------------------------------------------------------
inline uint Character::getCurrentHP() const
{
return m_nCurrentHP;
}
//----------------------------------------------------------------------
/// CPUActor class factory.
class CPUActorFactory: public IAIActorFactory
{
public:
virtual AIActor* createAIActor()
{
return new CPUCharacter();
}
virtual AIActor* createAIActor(IBrain* _brain);
void removeAIActor(AIActor* _actor)
{
//NGENE_DELETE(_actor);
}
};
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
929
]
]
] |
4230a71d55f6c373421ca1f0fad3c94722247d4c
|
5ed707de9f3de6044543886ea91bde39879bfae6
|
/ASFantasy/ASFIsOrb/Source/ASFantasyNewParticSignupRqst.cpp
|
7207ea76b82de139e38d2dc95ffae61d0d8dd846
|
[] |
no_license
|
grtvd/asifantasysports
|
9e472632bedeec0f2d734aa798b7ff00148e7f19
|
76df32c77c76a76078152c77e582faa097f127a8
|
refs/heads/master
| 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,468 |
cpp
|
/* ASFantasyNewParticSignupRqst.cpp */
/******************************************************************************/
/******************************************************************************/
#include "CBldVCL.h"
#pragma hdrstop
#include "CommDB.h"
#include "ASFantasyNewParticSignupRqst.h"
using namespace asfantasy;
/******************************************************************************/
/******************************************************************************/
void ASFantasyNewParticSignupRqst::readFromFiler(TDataFiler& /*filer*/)
{
throw ASIException("ASFantasyNewParticSignupRqst::readFromFiler: not supported");
}
/******************************************************************************/
void ASFantasyNewParticSignupRqst::writeToFiler(TDataFiler& /*filer*/)
{
throw ASIException("ASFantasyNewParticSignupRqst::writeToFiler: not supported");
}
/******************************************************************************/
ASFantasyNewSignupResp* ASFantasyNewParticSignupRqst::fulfillRequest()
{
TDatabase* memdb = NULL;
TDatabase* miscdb = NULL;
TDatabase* db = NULL;
TMemberPtr memberPtr;
TParticPtr particPtr;
TTeamPtr teamPtr;
bool success = false;
asmember::TMemberID memberID;
TEncodedParticID encodedParticID;
TRegionName regionName;
TTeamName teamName;
TManagerName managerName;
CStrVar reasonFailed;
try
{
validateRequest();
memdb = GetOpenDatabase(MemberDatabaseName());
miscdb = GetOpenDatabase(MemberMiscDatabaseName());
db = GetOpenDatabase(PrimaryDatabaseName());
memdb->StartTransaction();
db->StartTransaction();
miscdb->StartTransaction();
try
{
fMemberID.ToUpper();
memberPtr = TMember::createGet(fMemberID,cam_MustExist);
updateMember(memberPtr);
createNewPartic(memberPtr,particPtr,teamPtr,fCCardViaFaxPhone);
sendWelcomeEmail(memberPtr,teamPtr,false);
memberID = memberPtr->getMemberID();
encodedParticID = particPtr->encodeParticID();
regionName = teamPtr->getRegionName();
teamName = teamPtr->getTeamName();
managerName = teamPtr->getManagerName();
db->Commit();
memdb->Commit();
miscdb->Commit();
success = true;
}
catch(const Exception& e)
{
memdb->Rollback();
db->Rollback();
miscdb->Rollback();
throw ASIException(e.Message.c_str());
}
catch(...)
{
memdb->Rollback();
db->Rollback();
miscdb->Rollback();
throw;
}
}
catch(const TRequesterError& e)
{
reasonFailed.copy(e.getMessage());
}
catch(const Exception& e)
{
reasonFailed.copyVarg("Internal Error: %s",e.Message.c_str());
}
catch(const ASIException& e)
{
reasonFailed.copyVarg("Internal Error: %s",e.getMsg());
}
catch(const exception& e)
{
reasonFailed.copyVarg("Internal Error: %s",e.what());
}
catch(...)
{
reasonFailed.copy("Internal Error: Unknown");
}
if(!success)
CommErrMsg(cel_Info,"ASFantasyNewMemberSignupRqst::"
"ASFantasyNewParticSignupRqst: signup failed, reason: %s",
reasonFailed.c_str());
return(new ASFantasyNewSignupResp(success, memberID, encodedParticID,
regionName.c_str(), teamName.c_str(), managerName.c_str(),
reasonFailed.c_str()));
}
/******************************************************************************/
/******************************************************************************/
|
[
"[email protected]"
] |
[
[
[
1,
129
]
]
] |
2c77f35fb353e364f3c8a92ac2ae004bef92f505
|
864b3c4db459e0b497eab4ec85cce01122c48fad
|
/kg_maya_manipulator/src/kgLocManipNode.h
|
b2531c34fd60595de08488255f46d282c62e8eff
|
[] |
no_license
|
kgeorge/kgeorge-lib
|
e1b6334f7e02822886641c5a92956045bfd88349
|
c81040deeebb9324845928a65d1d9146fac3d2dd
|
refs/heads/master
| 2021-01-10T08:19:23.124790 | 2009-07-12T23:04:54 | 2009-07-12T23:04:54 | 36,910,482 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,570 |
h
|
#ifndef _kgLocatorNode
#define _kgLocatorNode
//
// Copyright (C) 2003 kgLocator
//
// File: kgLocatorNode.h
//
// Dependency Graph Node: kgLocator
//
// Author: Maya SDK Wizard
//
#include <maya/MPxNode.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MTypeId.h>
#include <maya/MPxLocatorNode.h>
#include <maya/MFloatPointArray.h>
class kgLocator : public MPxLocatorNode
{
public:
kgLocator();
virtual ~kgLocator();
virtual MStatus compute( const MPlug& plug, MDataBlock& data );
static void* creator();
static MStatus initialize();
virtual void draw( M3dView & view, const MDagPath & path,
M3dView::DisplayStyle style, M3dView::DisplayStatus status );
virtual bool isBounded() const;
virtual MBoundingBox boundingBox() const;
public:
#if defined(NEVER)
// There needs to be a MObject handle declared for each attribute that
// the node will have. These handles are needed for getting and setting
// the values later.
//
static MObject input; // Example input attribute
static MObject output; // Example output attribute
#endif
// The typeid is a unique 32bit indentifier that describes this node.
// It is used to save and retrieve nodes of this type from the binary
// file format. If it is not unique, it will cause file IO problems.
//
static MTypeId id;
static MString typeName;
//attributes
static MObject height;
static MFloatPointArray pts;
private:
static bool getPoints( MFloatPointArray &pts );
};
#endif
|
[
"kgeorge2@553ec044-b8b1-11dd-a067-9b1d96bc3259"
] |
[
[
[
1,
64
]
]
] |
9f8b033b2f74b490d27659f794dd857b09dfe435
|
5dfa2f8acf81eb653df4a35a76d6be973b10a62c
|
/trunk/Community_Core_Vision/addons/ofxFFMV/src/ofxffmv.h
|
4dfc8cfd378b7836942c7165dd24c63ac1e264ad
|
[] |
no_license
|
guozanhua/ccv-multicam
|
d69534ff8592f7984a5eadc83ed8b20b9d3df949
|
31206f0de7f73b3d43f2a910fdcdffb7ed1bf2c2
|
refs/heads/master
| 2021-01-22T14:24:52.321877 | 2011-08-31T14:18:44 | 2011-08-31T14:18:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,072 |
h
|
/*
* ofxffmv.h
*
*
* Created on 12/03/11.
* Copyright 2011 NUI Group. All rights reserved.
* Author: Anatoly Churikov
*
*/
#ifndef OFXFFMV_H_INCLUDED
#define OFXFFMV_H_INCLUDED
#include "ofxCameraBase.h"
#include "pgrflycapture.h"
class ofxffmv : ofxCameraBase
{
public:
ofxffmv();
~ofxffmv();
int getCameraBaseCount();
void setCameraFeature(CAMERA_BASE_FEATURE featureCode,int firstValue,int secondValue,bool isAuto,bool isEnabled);
void initializeWithGUID(GUID cameraGuid,int cameraWidth,int cameraHeight,int cameraLeft,int cameraTop,bool useROI,unsigned char cameraDepth,int cameraFramerate,bool isPlaying = false);
void deinitializeCamera();
void updateCurrentFrame();
void getCameraFeature(CAMERA_BASE_FEATURE featureCode,int* firstValue,int* secondValue, bool* isAuto, bool* isEnabled);
void callCameraSettingsDialog();
unsigned char* getCameraFrame();
private:
FlyCaptureImage fcImage;
FlyCaptureContext context;
FlyCaptureInfoEx arInfo;
};
#endif // OFXFFMV_H_INCLUDED
|
[
"[email protected]@da66ed7f-4d6a-8cb4-a557-1474cfe16edc"
] |
[
[
[
1,
34
]
]
] |
15bb1063f0d0db1a9f8c635b91ea3911b63f7e7e
|
3c0d7fc6c0187a8a0eae01b15a77e8e302e524e8
|
/server/src/sprite/effectManager.cpp
|
fbb7f79655d50946a6d30a56e2de2e5449694d2f
|
[
"Artistic-2.0"
] |
permissive
|
klusark/mdpr
|
0342bea08e9585a46d8d1c5ada29a662875d9d6f
|
da2b2287e4ed7eab302255221381a9bcbc5e5dcd
|
refs/heads/master
| 2021-01-01T15:30:10.633491 | 2009-08-23T05:14:36 | 2009-08-23T05:14:36 | 32,649,940 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,206 |
cpp
|
#include <Poco/SharedPtr.h>
#include "spriteManager.hpp"
#include "effectManager.hpp"
#include "helpers.hpp"
EffectManager::EffectManager(SpriteManager *SM)
: active(false),
currentNumberEffects(0),
mySpriteManager(SM)
{
for (;currentNumberEffects < initialNumberOfEffects; ++currentNumberEffects){
std::string name = "effect";
char buff[4];
sprintf(buff, "%d", currentNumberEffects);
name += buff;
Poco::SharedPtr<GenericSprite> newEffect(new Effect(name));
Effects.push_back(dynamic_cast<Effect *>(newEffect.get()));
mySpriteManager->registerSprite(newEffect);
}
}
EffectManager::~EffectManager()
{
}
void EffectManager::addEffect(unsigned short effectID, float x, float y)
{
for (unsigned short i = 0; i < Effects.size(); ++i){
if (!Effects[i]->inUse){
Effects[i]->inUse = true;
Effects[i]->SetX(x);
Effects[i]->SetY(y);
Effects[i]->changeAnimation(effectID);
break;
}
}
}
void EffectManager::addEffect(std::string effectID, float x, float y)
{
addEffect(stringToCRC(effectID), x, y);
}
bool EffectManager::isActive()
{
return active;
}
void EffectManager::setActive(bool toggle)
{
active = toggle;
}
|
[
"joelteichroeb@localhost"
] |
[
[
[
1,
54
]
]
] |
5d8f0cd0d2781267ef80d8cf281580f52ab66e65
|
4d01363b089917facfef766868fb2b1a853605c7
|
/src/SceneObjects/Meshes/MeshOFF.h
|
a65f504ea040560c8046a7f73b48cb2756afdecd
|
[] |
no_license
|
FardMan69420/aimbot-57
|
2bc7075e2f24dc35b224fcfb5623083edcd0c52b
|
3f2b86a1f86e5a6da0605461e7ad81be2a91c49c
|
refs/heads/master
| 2022-03-20T07:18:53.690175 | 2009-07-21T22:45:12 | 2009-07-21T22:45:12 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,098 |
h
|
/**
* Simple vertex / face format, no texture coordinates
*/
#ifndef meshoff_h
#define meshoff_h
#include "Mesh.h"
class MeshOFF : public Mesh
{
public:
MeshOFF(const string& filename)
{
read(filename);
}
void read(const string& filename)
{
fstream in;
int numVertices, numFaces, numEdges;
string format;
try
{
float x, y, z;
int order, a, b, c, d;
in.open(filename.c_str(), std::ios::in);
if (in.fail() || in.eof()) {
cout << "Opening " << filename << " failed." << endl;
return;
}
in >> format;
in >> numVertices >> numFaces >> numEdges;
for (int i = 0; i < numVertices; i++) {
in >> x >> y >> z;
vertices.push_back(Position3(x, y, z));
}
for (int i = 0; i < numFaces; i++) {
in >> order;
if (order == 4) {
in >> a >> b >> c >> d;
faces.push_back(Face(a, b, c, d));
}
else if (order == 3) {
in >> a >> b >> c;
faces.push_back(Face(a, b, c));
}
}
} catch (exception& e) {
cout << e.what() << endl;
}
}
};
#endif
|
[
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
] |
[
[
[
1,
60
]
]
] |
f7bf5470ae9f6f903136136288589973842368d1
|
1eb441701fc977785b13ea70bc590234f4a45705
|
/nukak3d/include/nkKernel.h
|
387622fa3eec59ac7faec6d17413447641f481f9
|
[] |
no_license
|
svn2github/Nukak3D
|
942947dc37c56fc54245bbc489e61923c7623933
|
ec461c40431c6f2a04d112b265e184d260f929b8
|
refs/heads/master
| 2021-01-10T03:13:54.715360 | 2011-01-18T22:16:52 | 2011-01-18T22:16:52 | 47,416,318 | 1 | 2 | null | null | null | null |
ISO-8859-2
|
C++
| false | false | 2,559 |
h
|
/**
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group.
* Bogota - Colombia
* All rights reserved.
*
* Author(s): Alexander Pinzón Fernández.
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef __NKKERNEL__H__
#define __NKKERNEL__H__
#include "nkEngine.h"
#include "nkITKFilterServer.h"
#include "nkPlugin.h"
#include <string>
#include <map>
namespace nukak3d {
/// The engine's system core
class nkKernel {
public:
/*NKENGINE_EXPORTS nkVTKInteractorServer &getnkVTKInteractorServer()
{
return m_RenWinInteractorServer;
}
NKENGINE_EXPORTS nkVTKRenderWindowServer &getnkVTKRenderWindowServer()
{
return m_RenderWindowServer;
}*/
NKENGINE_API nkITKFilterServer &getnkITKFilterServer()
{
return m_itkFilterServer;
}
/*NKENGINE_EXPORTS nkVTKFilterServer &getnkVTKFilterServer()
{
return m_vtkFilterServer;
}*/
/// Loads a plugin
NKENGINE_API bool loadPlugin(const std::string &sFilename) {
if(m_LoadedPlugins.find(sFilename) == m_LoadedPlugins.end())
{
nkPlugin aPlugin(sFilename);
if(aPlugin.isLoaded())
{
m_LoadedPlugins.insert(PluginMap::value_type(
sFilename,
aPlugin
)).first->second.registerPlugin(*this);
return true;
}
}
return false;
}
private:
/// Map of plugins by their associated file names
typedef std::map<std::string, nkPlugin> PluginMap;
PluginMap m_LoadedPlugins; ///< All plugins currently loaded
nkITKFilterServer m_itkFilterServer;
//nkVTKFilterServer m_vtkFilterServer;
//nkVTKRenderWindowServer m_RenderWindowServer;
//nkVTKInteractorServer m_RenWinInteractorServer;
};
} // namespace nukak3d
#endif // NKKERNEL
|
[
"apinzonf@4b68e429-1748-0410-913f-c2fc311d3372"
] |
[
[
[
1,
90
]
]
] |
a362920cd412cce1ee831885c47b7800a164e7f2
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Common/Base/Memory/Memory/FreeList/hkFreeList.inl
|
c2e5bb178407355ac09c18fc5f04ae776512ace7
|
[] |
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 | 3,742 |
inl
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
HK_FORCE_INLINE void hkFreeList::allocBatch(void** out,int sizeIn)
{
void** end = out + sizeIn;
void** cur = out;
Element* head = m_free;
while (cur < end && head)
{
*cur++ = reinterpret_cast<void*>(head);
head = head->m_next;
}
m_free = head;
// Account for number of blocks allocated
m_numFreeElements -= (cur - out);
out = cur;
// If still remaining we need more space
while (cur < end)
{
if (m_top < m_blockEnd)
{
while (m_top < m_blockEnd && cur < end)
{
*cur++ = m_top;
m_top += m_elementSize;
}
// Fix the number of elements
m_numFreeElements -= (cur - out);
// We need to update based on current pos
out = cur;
}
else
{
// This will do an alloc + update m_numFreeElements
*cur++ = addSpace();
// Its accounted for so update out
out = cur;
}
}
}
HK_FORCE_INLINE void hkFreeList::freeBatch(void** in,int sizeIn)
{
m_numFreeElements += sizeIn;
Element* head = m_free;
while (--sizeIn >= 0)
{
Element* ele = reinterpret_cast<Element *>(*in++);
if (ele)
{
ele->m_next = head;
head = ele;
}
else
{
m_numFreeElements--;
}
}
m_free = head;
}
HK_FORCE_INLINE void* hkFreeList::alloc()
{
// if there is a block on the freelist, then just return that
if (m_free)
{
m_numFreeElements --;
// Grab the block
void* data = reinterpret_cast<void*>(m_free);
// Make m_free point to the next free block
m_free = m_free->m_next;
// Return the block
return data;
}
// If there is no space after top, add some space
if (m_top >= m_blockEnd)
{
return addSpace();
}
m_numFreeElements--;
// Else take the memory from the top of the current block
void* data = reinterpret_cast<void*>(m_top);
m_top += m_elementSize;
return data;
}
HK_FORCE_INLINE void hkFreeList::free(void* data)
{
// We've got a free element
m_numFreeElements++;
// Its an element now - add it to the list
Element* ele = reinterpret_cast<Element *>(data);
ele->m_next = m_free;
m_free = ele;
}
inline void hkFreeList::garbageCollect()
{
findGarbage();
freeAllFreeBlocks();
}
/*
* 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,
130
]
]
] |
6d6ca2853cca4a41dac1c3e6cfa9805d335d42a6
|
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
|
/tags/0.11.1-alpha/avcut/tvideoschnitt.cpp
|
9cf8fe4df8bdb94ae5db044d4ca51184370c7e61
|
[] |
no_license
|
BackupTheBerlios/ttcut-svn
|
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
|
958032e74e8bb144a96b6eb7e1d63bc8ae762096
|
refs/heads/master
| 2020-04-22T12:08:57.640316 | 2009-02-08T16:14:00 | 2009-02-08T16:14:00 | 40,747,642 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 27,307 |
cpp
|
/*----------------------------------------------------------------------------*/
/* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */
/*----------------------------------------------------------------------------*/
/* PROJEKT : TTCUT 2005 */
/* FILE : tvideoschnitt.cpp */
/*----------------------------------------------------------------------------*/
/* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/23/2005 */
/* MODIFIED: b. altendorf DATE: 03/01/2005 */
/* MODIFIED: b. altendorf DATE: 03/21/2005 */
/* MODIFIED: b. altendorf DATE: 03/31/2005 */
/* MODIFIED: DATE: */
/*----------------------------------------------------------------------------*/
// ----------------------------------------------------------------------------
// TVIDEOSCHNITT
// ----------------------------------------------------------------------------
/*----------------------------------------------------------------------------*/
/* Die Klasse TVideoSchnitt entstammt dem Projekt "MPEG2Schnitt" von Martin */
/* Dienert und wurde von mir nach C++ portiert und an mein Projekt angepasst. */
/* Copyright (C) 2003 Martin Dienert */
/* Homepage: http:www.mdienert.de/mpeg2schnitt/ */
/* E-Mail: [email protected] */
/* Martin Dienert ist nicht verantwortlich fuer diese Quellen und leistet */
/* diesbezueglich auch keinen Support. */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* This program is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU General Public License as published by the Free */
/* Software Foundation; */
/* either version 2 of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT*/
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. */
/* See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License along */
/* with this program; if not, write to the Free Software Foundation, */
/* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */
/*----------------------------------------------------------------------------*/
// C++ stream I/O header files
// -----------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
#include "tvideoschnitt.h"
#define TWOGIG 2294967296
// construct object
// -----------------------------------------------------------------------------
TVideoSchnitt::TVideoSchnitt( TTProgressBar* pBar )
{
progressBar = pBar;
DateiName = " ";
ZielDateiName = " ";
DateiStream = NULL;
SpeicherStream = NULL;
VideoListe = new TListe(1000);
VideoIndexListe = new TListe(1000);
NeueListe = new TListe(1000);
Anhalten = false;
Timecode_korrigieren = TTCut::correctCutTimeCode;
Bitrate_korrigieren = TTCut::correctCutBitRate;;
IndexDatei_erstellen = TTCut::createCutIDD;
SequenzHeader = new TSequenzHeader();
BildHeader = new TBildHeader();
}
// destruct object
// -----------------------------------------------------------------------------
TVideoSchnitt::~TVideoSchnitt()
{
// Wenn ein DateiStream geoeffnet ist freigeben
if ( ttAssigned(DateiStream) )
{
delete DateiStream;
DateiStream = NULL;
}
// Wenn ein SpeicherStream geoeffnet ist freigeben
if ( ttAssigned(SpeicherStream) )
{
delete SpeicherStream;
SpeicherStream = NULL;
}
// Videoliste freigeben
if ( ttAssigned(VideoListe) )
{
VideoListe->Loeschen();
delete VideoListe;
}
// Video Indexliste freigeben
if ( ttAssigned(VideoIndexListe) )
{
VideoIndexListe->Loeschen();
delete VideoIndexListe;
}
if ( ttAssigned(NeueListe) )
{
if ( IndexDatei_erstellen )
IndexDateiSpeichern(ZielDateiName, NeueListe);
NeueListe->Loeschen();
delete NeueListe;
}
// SequenzHeader freigeben
if ( ttAssigned(SequenzHeader) )
delete SequenzHeader;
// BildHeader freigeben
if ( ttAssigned(BildHeader) )
delete BildHeader;
}
// set pointer to progress dialog
// -----------------------------------------------------------------------------
void TVideoSchnitt::setProgressBar( TTProgressBar* pBar )
{
progressBar = pBar;
}
// save index-file
// -----------------------------------------------------------------------------
void TVideoSchnitt::IndexDateiSpeichern(QString Name, TListe* Liste)
{
long i;
TDateiPuffer* ListenStream;
THeaderKlein* Header;
uint8_t Puffer[4];
if ( Liste->count() > 0 && !Name.isEmpty() )
{
ListenStream = new TDateiPuffer(ttChangeFileExt(Name, "idd"), fmCreate);
Puffer[0] = int('i'); // Puffer mit 'idd' fuellen
Puffer[1] = int('d');
Puffer[2] = int('d');
Puffer[3] = 2; // Version der Indexdatei
// Puffer an den Anfang der Datei schreiben
ListenStream->SchreibenDirekt(Puffer, 4);
for ( i = 0; i < Liste->count(); i++ )
{
Header = (THeaderKlein*)Liste->at(i);
// 1 Byte
ListenStream->SchreibenDirekt((uint8_t*)&Header->HeaderTyp, sizeof(Header->HeaderTyp));
// 8 Byte`
ListenStream->SchreibenDirekt((uint8_t*)&Header->Adresse, sizeof(Header->Adresse));
if ( Header->HeaderTyp == 0x00 )
{
// 2 Byte
ListenStream->SchreibenDirekt((uint8_t*)&Header->TempRefer, sizeof(Header->TempRefer));
// 1 Byte
ListenStream->SchreibenDirekt((uint8_t*)&Header->BildTyp, sizeof(Header->BildTyp));
}
}
delete ListenStream;
}
}
// open cut-target-file
// -----------------------------------------------------------------------------
void TVideoSchnitt::ZielDateiOeffnen(QString ZielDatei)
{
if ( (ZielDateiName != ZielDatei) )
{
if ( ttAssigned(SpeicherStream) )
delete SpeicherStream;
SpeicherStream = new TDateiPuffer(ZielDatei, fmCreate);
if ( IndexDatei_erstellen )
IndexDateiSpeichern(ZielDateiName, NeueListe);
NeueListe->Loeschen();
ZielDateiName = ZielDatei;
}
}
// close cut-target-file
// -----------------------------------------------------------------------------
void TVideoSchnitt::ZielDateiSchliessen()
{
if ( ttAssigned(SpeicherStream) )
{
delete SpeicherStream;
SpeicherStream = NULL;
}
if ( IndexDatei_erstellen )
IndexDateiSpeichern(ZielDateiName, NeueListe);
NeueListe->Loeschen();
ZielDateiName = " ";
}
// open video-source-file
// -----------------------------------------------------------------------------
void TVideoSchnitt::QuellDateiOeffnen(TSchnittPunkt* SchnittPunkt)
{
TMpeg2Header* MpegHeader;
if ( DateiName != SchnittPunkt->VideoName )
{
if ( ttAssigned(DateiStream) )
{
delete DateiStream;
DateiStream = NULL;
}
MpegHeader = new TMpeg2Header();
MpegHeader->DateiOeffnen(SchnittPunkt->VideoName);
MpegHeader->DateiInformationLesen(SequenzHeader, BildHeader);
// neue Liste einlesen
if ( !ttAssigned(SchnittPunkt->VideoListe) )
{
VideoListe->Loeschen();
VideoIndexListe->Loeschen();
MpegHeader->ListeErzeugen(VideoListe, VideoIndexListe);
Liste = VideoListe;
IndexListe = VideoIndexListe;
}
else
{
Liste = SchnittPunkt->VideoListe;
IndexListe = SchnittPunkt->VideoIndexListe;
}
delete MpegHeader;
DateiStream = new TDateiPuffer(SchnittPunkt->VideoName, fmOpenRead);
DateiStream->PufferFreigeben();
DateiName = SchnittPunkt->VideoName;
}
}
// close source-video-file
// -----------------------------------------------------------------------------
void TVideoSchnitt::QuellDateiSchliessen()
{
if ( ttAssigned(DateiStream) )
{
delete DateiStream;
DateiStream = NULL;
}
DateiName = " ";
VideoListe->Loeschen();
VideoIndexListe->Loeschen();
Liste = NULL;
IndexListe = NULL;
}
// video cut process
// -----------------------------------------------------------------------------
int TVideoSchnitt::Schneiden( TTVideoCutList* SchnittListe )
{
int Result;
int I, J;
TSchnittPunkt* SchnittPunkt;
TBildIndex* BildIndex;
THeaderKlein* ListenPunkt;
int BildNr, BildNr2;
int AnfangsIndex;
QString DateiName;
QString actionText;
Result = 0;
AdressDiff = 0;
BildDiff = 0;
BildZaehler = 0;
VideoSchnittAnhalten = false;
Anhalten = false;
ersterSequenzHeader = true;
erstesBild = true;
//qDebug("cut count: %d",SchnittListe->count());
if ( ttAssigned(progressBar) )
{
progressBar->setActionText( "Cut video" );
}
I = 0; // Schnittzaehler
while (I < SchnittListe->count() && !Anhalten )
{
if ( ttAssigned(progressBar) )
{
actionText.sprintf( "cut %d", I+1 );
progressBar->setActionText( actionText );
}
// X. Schnitt
SchnittPunkt = (TSchnittPunkt*)SchnittListe->at(I);
QuellDateiOeffnen( SchnittPunkt );
// Anwender hat beim erstellen der Liste auf Abbrechen gedrueckt
if ( Liste->count() == 0 )
{
Anhalten = true;
}
else
{
// naechstgelegenes I-Frame suchen
SchnittPunkt->Anfang = BildSuchen(1, SchnittPunkt->Anfang, IndexListe);
//index in der header-liste
BildIndex = (TBildIndex*)IndexListe->at(SchnittPunkt->Anfang);
// der Schnitt muss an einem I-Frame beginnen
if ( BildIndex->BildTyp == 1 )
{
ListenPunkt = (THeaderKlein*)Liste->at((BildIndex->BildIndex - 2));
if ( ListenPunkt->HeaderTyp == SequenceStartCode )
{
AnfangsIndex = BildIndex->BildIndex - 2;
ListenPunkt = (THeaderKlein*)Liste->at(BildIndex->BildIndex);
if ( ListenPunkt->HeaderTyp == BildStartCode )
{
// TempReferenz > 0 --> offene Gruppe
BildNr = ListenPunkt->TempRefer;
// Die naechsten Bilder (B-Frames)
// muessen entfernt werden.
if ( BildNr > 0 )
{
// Die Tempreferenze muessen in dieser Gruppe
// neu geschrieben werden.
ListenPunkt = (THeaderKlein*)Liste->at((BildIndex->BildIndex + 1));
if ( ListenPunkt->HeaderTyp == BildStartCode )
{
if ( !Anhalten )
// von Sequenzheader bis Ende I-Frame kopieren und korrigieren
//(Tempreferenz und Timecode)
KopiereSegment(true, AnfangsIndex,
BildIndex->BildIndex, SchnittPunkt->FrameRate, false);
}
else
{
// Ist die TempReferenz > 0 muss nach einem I-Frame noch
// ein B-Frame kommen
qDebug("Ist die TempReferenz > 0 muss nach einem I-Frame noch ein B-Frame kommen");
Result = -4;
return Result;
}
// B-Frames ueberspringen
ListenPunkt = (THeaderKlein*)Liste->at((BildIndex->BildIndex + BildNr + 1));
if ( ListenPunkt->HeaderTyp == BildStartCode )
{
AnfangsIndex = BildIndex->BildIndex + BildNr + 1;
}
else
{
// nach den "herrenlosen" B-Frames sollte eigentlich
// ein P-Frame stehen
qDebug("nach den >herrenlosen< B-Frames sollte eigentlich ein P-Frame stehen");
Result = -4;
return Result;
}
}
// naechstgelegenes I-, oder P-Frame suchen
SchnittPunkt->Ende = BildSuchen(2, SchnittPunkt->Ende, IndexListe);
BildIndex = (TBildIndex*)IndexListe->at(SchnittPunkt->Ende);
ListenPunkt = (THeaderKlein*)Liste->at(BildIndex->BildIndex);
if ( ListenPunkt->HeaderTyp == BildStartCode &&
BildIndex->BildTyp < 3 )
{
// TempReferenz des letzten I- oder P-Frames
BildNr = ListenPunkt->TempRefer;
J = 1;
do
{
// da die Bilder nicht in der angezeigten Reihenfolge
// gespeichert sind muss des letzte B-Frame mit kleinerer
// TempReferenz gesucht werden
ListenPunkt = (THeaderKlein*)Liste->at(BildIndex->BildIndex + J);
if ( ListenPunkt->HeaderTyp == BildStartCode )
BildNr2 = ListenPunkt->TempRefer;
else
// Sicherer Schleifenabbruch am GOPEnde
BildNr2 = BildNr + 1;
J++;
} while( (BildNr > BildNr2) &&
(BildIndex->BildIndex + J < (long)Liste->count()));
// die TempReferenz ist grosser als die TempReferenz des
// letztes P- oder I-Frames
// oder das Ende der GOP ist erreicht
if ( !Anhalten )
// Dateiteil kopieren und korrigieren (Tempreferenz und Timecode)
KopiereSegment(false, AnfangsIndex, BildIndex->BildIndex + J - 2,
SchnittPunkt->FrameRate, false);
}
else
Result = -4; // am Ende des Schnittes muss ein Bildheader stehen
}
else
Result = -3; // der Schnitt muss mit einem Bildheader mit I-Frame beginnen
}
else
Result = -2; // 2 Header vorm 1. I-Frame muss ein Sequenzheader stehen
}
else
Result = -1; // Der Schnitt muss an einem I-Frame beginnen
}
I++; // naechster Schnitt
}
SequenzEndeAnhaengen();
if ( Anhalten || Result < 0 ) // Abbruch durch Anwender
{
DateiName = ZielDateiName; // DateiName merken
NeueListe->Loeschen(); // neue Liste loeschen, dadurch
// wird keine *.idd Datei gespeichert
ZielDateiSchliessen(); // erzeugte Datei schliessen
//if ( ttFileExists(DateiName) ) // und loeschen
// ttDeleteFile(DateiName);
VideoSchnittAnhalten = true; // globale Variable, sagt weiteren
// Proceduren das Schluss ist
}
//qDebug("Meldung 440: Video-Schneiden: Result: %d",Result);
return Result;
}
void TVideoSchnitt::KopiereSegment(bool geaendert, long AnfangsIndex, long EndIndex, float Framerate, bool anzeigen)
{
off64_t Menge;
off64_t Groesse;
off64_t aktAdresse;
off64_t PufferAdr;
off64_t AnfAdrDatei;
off64_t AnfAdrSpeicher;
long iProgress;
uint8_t* Puffer;
long I, J;
THeaderKlein* ListenPunkt;
THeaderKlein* HeaderKlein;
int Tempreferenz;
TTimeCode Zeit;
long BitRate;
float fps = TTCut::frameRate;
int hour, minute, second, msecond;
QString actionText;
uint64_t vfatLimit = 2294967296UL;
//test
int festeBitRate = 0;
bool D2VDatei_erstellen = TTCut::createD2V;
Groesse = 0;
if ( EndIndex > (long)Liste->count() - 2 ) // EndIndex pruefen und eventuell
EndIndex = (long)Liste->count() - 2; // auf maximalen Wert setzen
if ( AnfangsIndex < (long)Liste->count() - 1 ) // AnfangsIndex pruefen, ist er groesser
{ // als die Liste -1 nicht kopieren
AnfAdrSpeicher = SpeicherStream->AktuelleAdr(); // Startadresse der Zieldatei merken
Puffer = new uint8_t [1048576]; // 1 MByte
I = AnfangsIndex; // Zaehler setzen zum Header suchen
J = AnfangsIndex; // Zaehler setzen zum Header korrigieren
ListenPunkt = (THeaderKlein*)Liste->at(I);
aktAdresse = ListenPunkt->Adresse; // Startadresse zum kopieren
AnfAdrDatei = aktAdresse; // Startadresse der Quelldatei merken
//qDebug("KopiereSegment: Anfang: %ld | Ende: %ld | DateiStream-Pos: %lld",AnfangsIndex,
// EndIndex,aktAdresse);
DateiStream->NeuePosition(aktAdresse);
// progress bar
if ( ttAssigned(progressBar) )
{
actionText.sprintf("copy segment: %ld - %ld | stream-Pos: %lld",AnfangsIndex,
EndIndex,aktAdresse);
progressBar->resetProgress();
progressBar->setActionText( actionText );
iProgress = EndIndex-AnfangsIndex;
progressBar->setTotalSteps( iProgress );
}
do
{
// Header suchen der gerade nooch in den Block passt
do
{
I++;
// am Ende der Liste kann man nicht auf den naechsten Header zugreifen
if ( I + 1 < (long)Liste->count() )
// die Endadresse eines Headers/Bildes ist die Anfangsadresse des naechsten Headers
ListenPunkt = (THeaderKlein*)Liste->at(I + 1);
}
while( (ListenPunkt->Adresse - aktAdresse) < 1048576 && // der naechste Header passt nicht mehr in den Puffer
(I <= EndIndex) ); // Ende des Abschnitts
ListenPunkt = (THeaderKlein*)Liste->at(I);
if ( ListenPunkt->Adresse - aktAdresse > 1048576 ) // Fehler in alten Indexdateien
{
qDebug("Meldung84: Der zu kopierende Teil der Datei passt nicht in den Kopierpuffer.");
Anhalten = true;
}
if ( !Anhalten )
{
Groesse = ListenPunkt->Adresse - aktAdresse;
Menge = DateiStream->LesenDirekt(Puffer, Groesse);
if ( Menge < Groesse )
{
if ( Menge < 0 )
qDebug("Meldung114: Dateiname, 'Die Datei 0xText1# laesst sich nicht oeffnen.");
else
qDebug("Meldung122: Die Datei ist scheinbar zu kurz.");
Anhalten = true;
}
}
// Abschnitt korrigieren, Indexdatei erstellen ---------------------------------------------
if ( !Anhalten )
{
do
{
ListenPunkt = (THeaderKlein*)Liste->at(J);
if ( IndexDatei_erstellen || D2VDatei_erstellen ) // Wenn eine neue Indexdatei erstellt werden soll,
{
HeaderKlein = new THeaderKlein(); // neuen ListenPunkt erzeugen,
HeaderKlein->HeaderTyp = ListenPunkt->HeaderTyp; // Headertyp eintragen,
HeaderKlein->Adresse = ListenPunkt->Adresse - AnfAdrDatei + AnfAdrSpeicher; // neue Adresse berechnen,
NeueListe->Add(HeaderKlein); // und zur Liste hinzufuegen.
}
else
HeaderKlein = NULL;
if ( ListenPunkt->HeaderTyp == BildStartCode )
{
BildZaehler++; // Bildzaehler erhoehen
if ( erstesBild ) // Ist das Bild das erste Bild im Abschnitt
{ // muss eventuell die Tempreferenz neu geschrieben werden
erstesBild = false;
BildDiff = ListenPunkt->TempRefer; // Bilddifferenz zum ersten kopierten Bild
}
if ( BildDiff > 0 ) // TempReferenz neu schreiben
{
Tempreferenz = ListenPunkt->TempRefer - BildDiff;
Puffer[ListenPunkt->Adresse - aktAdresse + 4] = Tempreferenz >> 2;
// Bit 10 - 2 von 10 Bit Tempref
Puffer[ListenPunkt->Adresse - aktAdresse + 5] = ((Tempreferenz & 0x0003) << 6) |
// Bit 1 und 0 von 10 Bit Tempref
((Puffer[ListenPunkt->Adresse - aktAdresse + 5]) & 0x3F);
// Bildtype (Bit 5, 4 und 3) und 3 Bit von VBVDelay
}
if ( (IndexDatei_erstellen || D2VDatei_erstellen) && HeaderKlein != NULL )
{
HeaderKlein->TempRefer = ListenPunkt->TempRefer - BildDiff; // Tempreferenz eintragen
HeaderKlein->BildTyp = ListenPunkt->BildTyp; // Bildtyp eintragen
if ( D2VDatei_erstellen )
{
PufferAdr = ListenPunkt->Adresse - aktAdresse + 8;
while( !((Puffer[PufferAdr]) == 0) && ((Puffer[PufferAdr + 1]) == 0) && ((Puffer[PufferAdr + 2]) == 1) )
{
PufferAdr++; // naechsten Startcode suchen
}
if ( Puffer[PufferAdr + 3] == 0xB5 && (Puffer[PufferAdr + 4] & 0xF0) == 0x80 )
{ // erweiterter Startcode mit "Picture coding extension"
PufferAdr += 7;
if ( ((Puffer[PufferAdr]) & 0x80) == 0x80 ) // oberstes Bild zuerst
HeaderKlein->BildTyp = HeaderKlein->BildTyp | 0x80;
if ( ((Puffer[PufferAdr]) & 0x02) == 0x02 ) // repeat_first_field
HeaderKlein->BildTyp = HeaderKlein->BildTyp | 0x40;
}
}
}
}
if ( ListenPunkt->HeaderTyp == GruppenStartCode )
{
BildDiff = 0; // Bilddifferenz zuruecksetzen
if ( Timecode_korrigieren )
{
//Timecode aus Bildzaehler berechnen
hour = (int)trunc( BildZaehler / (3600 * fps));
minute = (int)trunc((BildZaehler - hour * 3600 * fps) / (60 * fps));
second = (int)trunc((BildZaehler - hour * 3600 * fps - minute * 60 * fps) / fps);
msecond = (int)trunc((BildZaehler - hour * 3600 * fps - minute * 60 * fps - second * fps) * 1000.0/fps);
Puffer[ListenPunkt->Adresse - aktAdresse + 4] = ((Puffer[ListenPunkt->Adresse - aktAdresse + 4]) & 0x80) |
// 1 Bit Dropframe
((hour & 0x3F) << 2) | // 5 Bit Stunde
((minute & 0x30) >> 4); // 2 Bit von Minute
Puffer[ListenPunkt->Adresse - aktAdresse + 5] = ((Puffer[ListenPunkt->Adresse - aktAdresse + 5]) & 0x08) |
// 1 Bit Marker
((minute & 0x0F) << 4) | // 4 Bit von Minute
((second & 0x38) >> 3); // 3 Bit von Sekunde
Puffer[ListenPunkt->Adresse - aktAdresse + 6] = ((second & 0x07) << 5) |
// 3 Bit von Sekunde
((msecond & 0x3E) >> 1); // 5 Bit von Bild
Puffer[ListenPunkt->Adresse - aktAdresse + 7] = ((msecond & 0x01) << 7) |
// 1 Bit von Bild
((uint8_t)geaendert << 6) | // wenn geaendert dann Closed Group
((Puffer[ListenPunkt->Adresse - aktAdresse + 7]) & 0x40) ||
// oder Orginalbit Closed Group
((Puffer[ListenPunkt->Adresse - aktAdresse + 7]) & 0x20);
// Bit fuer broken Link
}
}
if ( ListenPunkt->HeaderTyp == SequenceStartCode &&
Bitrate_korrigieren &&
ersterSequenzHeader )
{
ersterSequenzHeader = false;
if ( festeBitRate != 0 )
BitRate = (long)round(festeBitRate / 400);
else
BitRate = (long)round(SequenzHeader->Bitrate / 400);
PufferAdr = ListenPunkt->Adresse - aktAdresse + 8;
Puffer[PufferAdr] = (BitRate & 0x3FC00) >> 10;
PufferAdr++;
Puffer[PufferAdr] = (BitRate & 0x3FC) >> 2;
PufferAdr++;
Puffer[PufferAdr] = (Puffer[PufferAdr] & 0x3F) | (BitRate & 0x03) << 6;
PufferAdr++;
if ( (Puffer[PufferAdr] & 0x02) == 2 )
PufferAdr += 64;
if ( (Puffer[PufferAdr] & 0x01) == 1 )
PufferAdr += 65;
else
PufferAdr++;
if ( Puffer[PufferAdr] == 0 &&
Puffer[PufferAdr + 1] == 0 &&
Puffer[PufferAdr + 2] == 1 &&
Puffer[PufferAdr + 3] == 0xB5 &&
(Puffer[PufferAdr + 4] & 0xF0) == 0x10 )
{
PufferAdr += 6;
Puffer[PufferAdr] = (Puffer[PufferAdr] & 0xE0) | ((BitRate & 0x3E000000) >> 25);
PufferAdr++;
Puffer[PufferAdr] = (Puffer[PufferAdr] & 0x01) | ((BitRate && 0x01FC0000) >> 18);
}
}
J++;
}
while (J <= I);
}
//---------------------------------------------------- Korrigieren, Indexdatei erstellen Ende
if ( !Anhalten )
{
Menge = SpeicherStream->SchreibenDirekt(Puffer, Groesse);
if ( ttAssigned(progressBar) )
{
iProgress = I-AnfangsIndex+1;
Anhalten = progressBar->setProgress( iProgress );
}
if ( Menge < Groesse )
{
if ( SpeicherStream->AktuelleAdr() > vfatLimit - (uint64_t)10 )
qDebug("Meldung82: Dateischreibfehler. Datei groesser 2 GByte; LARGE_FILE_SUPPORT vorhanden?");
else
qDebug("Meldung83: Dateischreibfehler. Festplatte voll?, Menge: %lld",Menge);
Anhalten = true;
}
}
ListenPunkt = (THeaderKlein*)Liste->at(I);
aktAdresse = ListenPunkt->Adresse;
}
while( (I <= EndIndex) && !Anhalten);
delete [] Puffer;
}
}
void TVideoSchnitt::SequenzEndeAnhaengen()
{
long Daten;
THeaderKlein* HeaderKlein;
// Wenn eine neue Indexdatei erstellt wurde,
if ( IndexDatei_erstellen )
{
HeaderKlein = new THeaderKlein(); // neuen ListenPunkt erzeugen,
HeaderKlein->HeaderTyp = 0xB7; // Sequenzendecode eintragen,
HeaderKlein->Adresse = SpeicherStream->AktuelleAdr(); // Adresse eintragen,
NeueListe->Add(HeaderKlein); // und zur Liste hinzufuegen.
}
Daten = 0xB7010000;
SpeicherStream->SchreibenDirekt((uint8_t*)&Daten, 4);
}
long TVideoSchnitt::BildSuchen( int frameTyp, long fromIndex, TListe* index )
{
TBildIndex* frameIndex;
long iPos;
long iFound;
long framePosition;
long numFrames;
numFrames = index->count();
framePosition = fromIndex;
iPos = fromIndex;
iFound = -1;
frameIndex = (TBildIndex*)index->at(iPos);
//if ( frameIndex->BildTyp == frameTyp ) iPos++;
while( iPos < numFrames-1 && iFound < 0 )
{
frameIndex = (TBildIndex*)index->at(iPos);
if ( frameIndex->BildTyp == frameTyp )
iFound = iPos;
iPos++;
}
if ( iPos != iFound && iFound >= 0 )
framePosition = iFound;
return framePosition;
}
|
[
"tritime@7763a927-590e-0410-8f7f-dbc853b76eaa"
] |
[
[
[
1,
776
]
]
] |
3597c0583e77f450c5d9c11a8e75c41be87b5032
|
45fce7543d16bc451271e3e70dc6278d90e8e23b
|
/code/engine/source/FleetReactor.cpp
|
de36bd19e5d0af2d507f029a541f8b9176e3e138
|
[] |
no_license
|
karlssonper/cs249a
|
4bd40b20e903648a9eb2999f25a837e80e8edb34
|
63afe678ef5e1a76e05b474759a9d5ae68093625
|
refs/heads/master
| 2020-04-24T23:09:14.991112 | 2011-12-09T08:48:45 | 2011-12-09T08:48:45 | 2,816,441 | 0 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,194 |
cpp
|
#include "FleetReactor.h"
#include "VirtualTimeActivityManager.h"
#include "Activity.h"
#include "FleetChangeActivityReactor.h"
#include "Exception.h"
using namespace Shipping;
FleetReactor::FleetReactor(const string &_name,
Fleet *_notifier,
VirtualTimeActivityManager::Ptr _vtam) :
Fleet::Notifiee(_name, _notifier),
activityManager_(_vtam),
status_(notActive()),
activity1_(NULL),
activity2_(NULL) {
reactor1_ = new FleetChangeActivityReactor(
"FleetChangeActReactor1",
activityManager_,
NULL,
notifier(),
notifier()->bufferStart());
reactor2_ = new FleetChangeActivityReactor(
"FleetChangeReactor2",
activityManager_,
NULL,
notifier(),
notifier()->bufferStart());
}
FleetReactor::Ptr FleetReactor::FleetReactorNew(const string &_name,
Fleet *_notifier,
Fwk::Ptr<VirtualTimeActivityManager> _vtam) {
FleetReactor::Ptr p = new FleetReactor(_name, _notifier, _vtam);
if (!p) {
std::cerr << "FleetReactorNew new () failed" << std::endl;
throw(Fwk::MemoryException("FleetReactorNew"));
}
return p;
}
void FleetReactor::onTimeChange() {
try {
if (status_ == notActive()) {
if (notifier()->bufferStart() != notifier()->bufferEnd()) {
status_ = active();
string tempName = name();
tempName.append("Swapper1");
if (!activity1_) {
activity1_ = activityManager_->activityNew(tempName);
}
tempName = name();
tempName.append("Swapper2");
if (!activity2_) {
activity2_ = activityManager_->activityNew(tempName);
}
tempName = name();
tempName.append("Swapper1Reactor");
reactor1_->activityIs(activity1_);
activity1_->nextTimeIs(Fwk::Time(
notifier()->bufferStart().value()));
activity1_->notifieeIs(tempName, reactor1_);
activity1_->statusIs(Fwk::Activity::nextTimeScheduled);
tempName = name();
tempName.append("Swapper2Reactor");
reactor2_->activityIs(activity2_);
activity2_->nextTimeIs(Fwk::Time
(notifier()->bufferEnd().value()));
activity2_->notifieeIs(tempName, reactor2_);
activity2_->statusIs(Fwk::Activity::nextTimeScheduled);
}
} else /*active*/ {
if (notifier()->bufferStart() != notifier()->bufferEnd()) {
activity1_->nextTimeIs(notifier()->bufferStart().value());
reactor1_->timeToSwapIs(notifier()->bufferStart());
reactor2_->timeToSwapIs(notifier()->bufferEnd());
activity2_->nextTimeIs(notifier()->bufferEnd().value());
} else {
// deactivate
status_ = notActive();
activity1_->notifieeIs("",0);
activityManager_->activityDel(activity1_->name());
activity1_ = NULL;
reactor1_ = NULL;
activity2_->notifieeIs("",0);
activityManager_->activityDel(activity2_->name());
activity2_ = NULL;
reactor2_ = NULL;
}
}
} // try
catch(Fwk::Exception e) {
std::cerr << "Exception in FleetReactor::onTimeChange: " <<
e.what() << std::endl;
onNotificationException();
}
}
|
[
"[email protected]"
] |
[
[
[
1,
105
]
]
] |
f2c4b548728be3004c3d48c7b6cbc81feb5c4c1b
|
463c3b62132d215e245a097a921859ecb498f723
|
/lib/dlib/entropy_encoder_model/entropy_encoder_model_kernel_6.h
|
675015224b45c741eafb6f1bd9aecb34506edc75
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
athulan/cppagent
|
58f078cee55b68c08297acdf04a5424c2308cfdc
|
9027ec4e32647e10c38276e12bcfed526a7e27dd
|
refs/heads/master
| 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,784 |
h
|
// Copyright (C) 2005 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_ENTROPY_ENCODER_MODEL_KERNEl_6_
#define DLIB_ENTROPY_ENCODER_MODEL_KERNEl_6_
#include "../algs.h"
#include "entropy_encoder_model_kernel_abstract.h"
#include "../assert.h"
namespace dlib
{
template <
unsigned long alphabet_size,
typename entropy_encoder
>
class entropy_encoder_model_kernel_6
{
/*!
INITIAL VALUE
Initially this object's finite context model is empty
CONVENTION
&get_entropy_encoder() == coder
This is an order-(-1) model. So it doesn't really do anything.
Every symbol has the same probability.
!*/
public:
typedef entropy_encoder entropy_encoder_type;
entropy_encoder_model_kernel_6 (
entropy_encoder& coder
);
virtual ~entropy_encoder_model_kernel_6 (
);
inline void clear(
);
inline void encode (
unsigned long symbol
);
entropy_encoder& get_entropy_encoder (
) { return coder; }
static unsigned long get_alphabet_size (
) { return alphabet_size; }
private:
entropy_encoder& coder;
// restricted functions
entropy_encoder_model_kernel_6(entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>&); // copy constructor
entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>& operator=(entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <
unsigned long alphabet_size,
typename entropy_encoder
>
entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>::
entropy_encoder_model_kernel_6 (
entropy_encoder& coder_
) :
coder(coder_)
{
COMPILE_TIME_ASSERT( 1 < alphabet_size && alphabet_size < 65535 );
}
// ----------------------------------------------------------------------------------------
template <
unsigned long alphabet_size,
typename entropy_encoder
>
entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>::
~entropy_encoder_model_kernel_6 (
)
{
}
// ----------------------------------------------------------------------------------------
template <
unsigned long alphabet_size,
typename entropy_encoder
>
void entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>::
clear(
)
{
}
// ----------------------------------------------------------------------------------------
template <
unsigned long alphabet_size,
typename entropy_encoder
>
void entropy_encoder_model_kernel_6<alphabet_size,entropy_encoder>::
encode (
unsigned long symbol
)
{
// use order minus one context
coder.encode(symbol,symbol+1,alphabet_size);
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_ENTROPY_ENCODER_MODEL_KERNEl_6_
|
[
"jimmy@DGJ3X3B1.(none)"
] |
[
[
[
1,
127
]
]
] |
a5799a3d50b91e1e654cba9208c89ffab60cb1e2
|
30b5a9343526e4205f78eef3cf1c3900c9339509
|
/4445_A_Careful_Approach/main.cpp
|
2bcc88a72104a3f0ccf2e483a8c8502b9c9bb7b5
|
[] |
no_license
|
mustaaa/bedri
|
9d3f8ebd823676404279ce50af6e3047ff791a7f
|
465429b4e7600f7e575d881292db062a521fc5c3
|
refs/heads/master
| 2016-09-06T08:32:30.309362 | 2010-03-04T20:20:53 | 2010-03-04T20:20:53 | 33,200,889 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,465 |
cpp
|
#include <string>
#include <iostream>
#include <fstream>
using std::string;
using namespace std;
#include "careful.h"
int main (int argc, char* argv[])
{
int n , begin , end;
LandingScheduler ls;
ifstream input , output;
input.open(argv[1]);
//input.open("approach.in");
if (!input) {
cerr << "error: unable to open file " << argv[1] << endl;
return -1;
}
// output.open("approach.out",ios_base::out);
// if (!output) {
//cerr << "error: unable to open file " << "approach.out" << endl;
// return -1;
// }
input >> n;
if ((n<2||n>8)&&(n!=0))
{
cerr << "Error in input file!";
return -1;
}
while (n!=0)
{
ls.resetLandingScheduler(n);
for (int i = 0; i<n ; i++)
{
input >> begin;
input >> end;
if (end<begin||begin<0||end<0)
{
cerr << "Error in input file!";
return -1;
}
ls.insertLandingInterval(begin,end);
}
ls.findSolution();
input >> n;
if ((n<2||n>8)&&(n!=0))
{
cerr << "Error in input file!";
return -1;
}
}
return 0;
}
//ignore
//List <int> integerlist;
//int a ;
//integerlist.insertAtFrontAndSetCurPtr(1);
//integerlist.print();
//integerlist.insertAfterCurPtr(2);
//integerlist.print();
//integerlist.insertAfterCurPtrAndIncrement(3);
//integerlist.print();
//integerlist.setCurPtrToNextNode();
//integerlist.deleteCurPtr();
//integerlist.getCurPtrData(a);
//cout << "\n" << a << "\n" ;
//integerlist.print();
//integerlist.removeFromBack();
//integerlist.print();
//integerlist.setCurPtrToFirstNode();
//integerlist.getCurPtrData(a);
//cout << "\n" << a << "\n" ;
//integerlist.insertBeforeCurPtr(4);
//integerlist.print();
//integerlist.insertBeforeCurPtrAndDecrement(5);
//integerlist.getCurPtrData(a);
//cout << "\n" << a << "\n" ;
//integerlist.print();
//integerlist.insertAtBack(6);
//integerlist.print();
//integerlist.setCurPtrToLastNode();
//integerlist.setCurPtrToPrevNode();
//integerlist.setCurPtrToPrevNode();
//integerlist.getCurPtrData(a);
//cout << "\n" << a << "\n" ;
//integerlist.print();
|
[
"mustafabedrisen@64716e36-e533-11de-92aa-3ddf338522b3"
] |
[
[
[
1,
94
]
]
] |
8978b3c188aab00c1a96fea05da60309f5046c47
|
3aa746598879eaefa782bf732b444f51c22e5351
|
/NMozLib/Include/BrowserWindow.h
|
8adbb758cc6b9bb690bd76efe1e775399f395c59
|
[] |
no_license
|
tonytonyfly/nmozlib
|
0cdf5087815790d4cd98819de5e021e94eee8566
|
e71c7887816eb92713c049b749733c1ece550759
|
refs/heads/master
| 2021-01-01T04:57:33.819398 | 2008-02-11T02:26:02 | 2008-02-11T02:26:02 | 58,304,343 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,620 |
h
|
/*
This file is part of NMozLib, "Navi Mozilla Library", a wrapper for Mozilla Gecko
Copyright (C) 2008 Adam J. Simmons
http://code.google.com/p/nmozlib/
Portions Copyright (C) 2006 Callum Prentice and Linden Lab Inc.
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __BrowserWindow_H__
#define __BrowserWindow_H__
#include <string>
namespace NMozLib {
class BrowserWindowListener;
class RenderSurface;
struct CaretInfo;
class BrowserWindow
{
public:
virtual ~BrowserWindow() {}
virtual void navigateTo(const std::string& url) = 0;
virtual void navigateStop() = 0;
virtual void navigateRefresh() = 0;
virtual void navigateForward() = 0;
virtual void navigateBack() = 0;
virtual bool canNavigateForward() const = 0;
virtual bool canNavigateBack() const = 0;
virtual std::string evaluateJS(const std::string& script) = 0;
virtual void focus() = 0;
virtual void defocus() = 0;
virtual void injectMouseMove(short x, short y) = 0;
virtual void injectMouseDown(short x, short y) = 0;
virtual void injectMouseUp(short x, short y) = 0;
virtual void injectKeyPress(short keyCode) = 0;
virtual void injectScroll(short numLines) = 0;
virtual void addListener(BrowserWindowListener* listener) = 0;
virtual void removeListener(BrowserWindowListener* listener) = 0;
virtual bool render() = 0;
virtual const RenderSurface& getRenderSurface() const = 0;
virtual CaretInfo getCaretInfo() const = 0;
virtual std::string getCurrentURL() const = 0;
virtual void resize(short width, short height) = 0;
virtual void setBackgroundColor(unsigned char red, unsigned char green, unsigned char blue) = 0;
};
class BrowserWindowListener
{
public:
virtual void onPageChanged(BrowserWindow* caller, int x, int y, int width, int height) = 0;
virtual void onNavigateBegin(BrowserWindow* caller, const std::string& url, bool &shouldContinue) = 0;
virtual void onNavigateComplete(BrowserWindow* caller, const std::string& url, int responseCode) = 0;
virtual void onUpdateProgress(BrowserWindow* caller, short percentComplete) = 0;
virtual void onStatusTextChange(BrowserWindow* caller, const std::string& statusText) = 0;
virtual void onLocationChange(BrowserWindow* caller, const std::string& url) = 0;
virtual void onClickLinkHref(BrowserWindow* caller, const std::string& linkHref) = 0;
};
class RenderSurface
{
public:
RenderSurface();
RenderSurface(short width, short height, short depth = 4);
~RenderSurface();
void resize(short width, short height, short depth, int rowPitch);
unsigned char* buffer;
short width;
short height;
short depth;
int rowPitch;
};
struct CaretInfo
{
bool visible;
int x, y, height;
CaretInfo();
CaretInfo(bool visible, int x, int y, int height);
bool operator==(const CaretInfo& rhs) const;
bool operator!=(const CaretInfo& rhs) const;
};
}
#endif
|
[
"ajs15822@be7176e2-5d45-0410-b9dd-a1b14b2f9e02"
] |
[
[
[
1,
118
]
]
] |
3f8267728fab41e8708a572dabf5868093816e4d
|
74c8da5b29163992a08a376c7819785998afb588
|
/NetAnimal/Game/Hunter/NewGame/Tasks/src/ITask.cpp
|
2ef2ba4ada0c6051dd01af1c0595dbd698f8f04c
|
[] |
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 |
GB18030
|
C++
| false | false | 2,206 |
cpp
|
#include "TasksStableHeaders.h"
#include "ITask.h"
using namespace Orz;
ITask::~ITask(void){}
ITask::ITask(void):_isEnable(false),_isUpdate(false)
{
}
bool ITask::enable(void)
{
if(!_isEnable)
{
_isEnable = true;
_isUpdate = true;
TaskSet::iterator it;
bool ret = doEnable();
for(it = _tasks.begin(); it != _tasks.end(); ++it)
{
ret = ret && (*it)->enable();//当一个为false的返回值之后,其他的都不会被执行
}
return ret;
}
return false;
}
void ITask::disable(void)
{
_isEnable = false;
TaskSet::reverse_iterator it;
for(it = _tasks.rbegin(); it != _tasks.rend(); ++it)
{
(*it)->disable();
}
doDisable();
}
bool ITask::update(TimeType interval)
{
if(_isEnable)
{
if(_isUpdate)
{
TaskSet::iterator it;
bool ret = doUpdate(interval);
for(it = _tasks.begin(); it != _tasks.end(); ++it)
{
ret = (*it)->update(interval) || ret;
}
if(ret)
{
return true;
}
_isUpdate = false;
}
if(_nextTask)
{
if(!_nextTask->isEnable())
_nextTask->enable();
return _nextTask->update(interval);
}
}
return false;
}
void ITask::compose(TaskPtr task)
{
if(_isEnable)
{
task->enable();
}
_tasks.push_back(task);
}
void ITask::push_back(TaskPtr task)
{
if(_nextTask)
{
_nextTask->compose(task);
}
else
{
_nextTask = task;//.push_back(task);
}
}
void ITask::clear(void)
{
_tasks.clear();
_nextTask.reset();
}
void ITask::remove(TaskPtr task)
{
_tasks.erase(std::remove(_tasks.begin(),_tasks.end(), task),_tasks.end());
if(_nextTask == task)
{
_nextTask.reset();
}else
{
_nextTask->remove(task);
}
TaskSet::iterator it;
for(it = _tasks.begin(); it != _tasks.end(); ++it)
{
(*it)->remove(task);//当一个为false的返回值之后,其他的都不会被执行
}
}
bool ITask::isEnable(void)
{
return _isEnable;
}
//private:
// virtual bool doEnable(void) = 0;
// virtual void doDisable(void) = 0;
// virtual bool doUpdate(TimeType interval) = 0;
//
// std::vector<TaskPtr> _tasks;
// TaskPtr _nextTask;
// bool _isEnable;
|
[
"[email protected]"
] |
[
[
[
1,
132
]
]
] |
dc9b380ff3073c7fb8d8b46c103ed9fa8c421bb2
|
1eb441701fc977785b13ea70bc590234f4a45705
|
/nukak3d/src/nkObj3DViewer.cpp
|
3acc24a48b72061cfecefd1683dddba925a6d55a
|
[] |
no_license
|
svn2github/Nukak3D
|
942947dc37c56fc54245bbc489e61923c7623933
|
ec461c40431c6f2a04d112b265e184d260f929b8
|
refs/heads/master
| 2021-01-10T03:13:54.715360 | 2011-01-18T22:16:52 | 2011-01-18T22:16:52 | 47,416,318 | 1 | 2 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 20,472 |
cpp
|
/**
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group.
* Bogota - Colombia
* All rights reserved.
*
* Author(s): Alexander Pinzón Fernández.
*
* ***** END GPL LICENSE BLOCK *****
*/
#include "nkObj3DViewer.h"
#include "itkImageToVTKImageFilter.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include <itkAnalyzeImageIOFactory.h>
#include <vtkImageMarchingCubes.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkDecimatePro.h>
#include "vtkLookupTableManager.h"
#include <vtkActor.h>
#include <vtkProperty.h>
#include <wx/colordlg.h>
#include <vtkrenderer.h>
//*****************************************************************************************
// CONSTRUCTOR
//*****************************************************************************************
nkObj3DViewer::nkObj3DViewer(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name):
wxPanel(parent, id, pos, size, style, name)
{
prv_auiManager.SetManagedWindow(this);
prv_auiManager.SetFlags(prv_auiManager.GetFlags()|
wxAUI_MGR_ALLOW_ACTIVE_PANE|
wxAUI_MGR_HINT_FADE|
wxAUI_MGR_TRANSPARENT_HINT);
long viewStyle = wxWANTS_CHARS | wxNO_FULL_REPAINT_ON_RESIZE;
prv_wxVtkVista3D = new wxVTKRenderWindowInteractor (this, wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
viewStyle,
wxT ("wxVtk 3D view"));
prv_wxVtkVista3D->GetRenderWindow()->SetStereoCapableWindow(1); //! Init stereo window
prv_vista3D = vtkViewImage3D::New();
prv_camera = vtkCamera::New();
prv_render3D = vtkRenderer::New();
prv_render3D->SetActiveCamera(prv_camera);
prv_wxVtkVista3D->GetRenderWindow()->AddRenderer(prv_render3D);
prv_vista3D->SetRenderWindow(prv_wxVtkVista3D->GetRenderWindow());
prv_vista3D->SetRenderer(prv_render3D);
prv_auiManager.AddPane(prv_wxVtkVista3D, wxAuiPaneInfo().
Name(wxT("VIEW_3D")).Caption(_("View 3D")).
Center().Layer(1).PinButton(true).
MinSize(wxSize(200,200)).PaneBorder(true).
CloseButton(false).MaximizeButton(true));
prv_auiManager.Update();
prv_mapper = 0;
prv_actor = 0;
prv_data = 0;
prv_fpsflag = 0;
}
//*****************************************************************************************
// DESTRUCTOR
//*****************************************************************************************
nkObj3DViewer::~nkObj3DViewer(){
prv_vista3D->Detach();
prv_vista3D->Delete();
if(prv_wxVtkVista3D) prv_wxVtkVista3D->Delete();
prv_auiManager.UnInit();
if (prv_render3D != 0) prv_render3D->Delete();
if(prv_mapper != 0 )prv_mapper->Delete();
if(prv_actor != 0 )prv_actor->Delete();
}
//*****************************************************************************************
// CONFIG VIEW
//*****************************************************************************************
void nkObj3DViewer::Configure(void){
prv_vista3D->SetBackgroundColor (0.0,0.0,0.0);
prv_vista3D->SetRenderingModeToPlanar();
this->prBoundingBox();
}
//*****************************************************************************************
// OPEN FILE
//*****************************************************************************************
void nkObj3DViewer::prOpenFile(wxString a_fileName){
vtkPolyDataReader* mi_vtkReader = vtkPolyDataReader::New();
mi_vtkReader->SetFileName(a_fileName.c_str());
mi_vtkReader->Update();
prv_actor = vtkActor::New();
prv_mapper = vtkPolyDataMapper::New();
prv_data = mi_vtkReader->GetOutput();
prv_mapper->SetInput(prv_data);
prv_actor->SetMapper(prv_mapper);
prv_mapper->ScalarVisibilityOff();
prv_render3D->AddActor(prv_actor);
this->prBoundingBox();
prv_render3D->ResetCamera();
prv_render3D->Render();
mi_vtkReader->Delete();
}
//*****************************************************************************************
// MESH CONFIG
//*****************************************************************************************
void nkObj3DViewer::prConfigureMesh3D(vtkPolyData* input){
prv_actor = vtkActor::New();
prv_mapper = vtkPolyDataMapper::New();
prv_data = input;
prv_mapper->SetInput(prv_data);
prv_mapper->Update();
prv_actor->SetMapper(prv_mapper);
prv_mapper->ScalarVisibilityOff();
prv_render3D->AddActor(prv_actor);
this->prBoundingBox();
prv_render3D->ResetCamera();
prv_render3D->Render();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// Boundig box de la imagen 3D
//*****************************************************************************************
void nkObj3DViewer::prBoundingBox()
{
vtkOutlineFilter *prBoundingBox = vtkOutlineFilter::New(); //! Bounding Box creation
prBoundingBox->SetInput(prv_data);
vtkPolyDataMapper *prv_bboxMapper = vtkPolyDataMapper::New(); //! Bounding Box mapper
prv_bboxMapper->SetInput(prBoundingBox->GetOutput());
prv_bboxActor = vtkActor::New(); //! Bounding Box actor
prv_bboxActor->SetMapper(prv_bboxMapper);
prv_bboxActor->GetProperty()->SetColor(1,0.1,0.1); //! Bounding Box color
prv_render3D->AddActor(prv_bboxActor);
prv_bboxActor->VisibilityOff();
prv_render3D->Render();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// Boundig box de la imagen 3D
//*****************************************************************************************
void nkObj3DViewer::prBoundingBoxOnOff()
{
if(prv_bboxActor->GetVisibility()==false )
prv_bboxActor->VisibilityOn();
else
prv_bboxActor->VisibilityOff();
prv_render3D->Render();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// GET POLYDATA
//*****************************************************************************************
vtkPolyData* nkObj3DViewer::GetPolyData()
{
return prv_data;
}
//*****************************************************************************************
// MARCHING CUBES
//*****************************************************************************************
void nkObj3DViewer::prImageToIsoSurface(itk::Image<unsigned short,3>::Pointer an_image,
int a_numContours,
int a_thresholdLower,
int a_thresholdUpper,
double a_red,
double a_green,
double an_blue,
double a_opacity
){
const int Dimension = 3;
typedef unsigned short PixelType;
typedef itk::Image<PixelType, Dimension> ImageType;
typedef itk::ImageToVTKImageFilter<ImageType> Itk2VtkType;
Itk2VtkType::Pointer m_Itk2Vtk = Itk2VtkType::New();
m_Itk2Vtk->SetInput(an_image);
m_Itk2Vtk->Update();
vtkImageMarchingCubes *marcher = vtkImageMarchingCubes::New();
marcher->SetInput(m_Itk2Vtk->GetOutput());
marcher->SetNumberOfContours(a_numContours);
marcher->SetValue(a_thresholdLower, a_thresholdUpper);
marcher->Update();
this->prConfigureMesh3D(marcher->GetOutput());
vtkLookupTable* lut = vtkLookupTableManager::GetLookupTable(1);
prv_mapper->SetLookupTable(lut);
prv_actor->GetProperty()->SetDiffuseColor(a_red,a_green,an_blue);
prv_actor->GetProperty()->SetOpacity(a_opacity);
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// SAVE MESH
//*****************************************************************************************
void nkObj3DViewer::prSaveFile(wxString a_fileName){
vtkPolyDataWriter *l_Writer = vtkPolyDataWriter::New();
l_Writer->SetFileName( a_fileName );
l_Writer->SetInput( (vtkPolyData*)prv_actor->GetMapper()->GetInput() );
l_Writer->Write();
l_Writer->Delete();
}
//*****************************************************************************************
// ACTIVE STEREO
//*****************************************************************************************
void nkObj3DViewer::prActiveStereo(void){
if(!prv_wxVtkVista3D->GetRenderWindow()->GetStereoRender()) {
prv_wxVtkVista3D->GetRenderWindow()->SetStereoTypeToCrystalEyes();
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOn();
}else
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOff();
prv_wxVtkVista3D->GetRenderWindow()->StereoUpdate();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// PASIVE STEREO
//*****************************************************************************************
void nkObj3DViewer::prStereoPassive(void){
if(!prv_wxVtkVista3D->GetRenderWindow()->GetStereoRender()) {
prv_wxVtkVista3D->GetRenderWindow()->SetStereoTypeToAnaglyph();
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOn();
}else
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOff();
prv_wxVtkVista3D->GetRenderWindow()->StereoUpdate();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// STEREO INCREASE - Increase stereo separation
//*****************************************************************************************
void nkObj3DViewer::prStereoMoreSeparation( void )
{
double sep,
inc=0.1;
sep = prv_camera->GetEyeAngle(); //! Get actual separation
prv_camera->SetEyeAngle(sep+inc); //! Increase separation
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// STEREO DECREASE - Decrease stereo separation
//*****************************************************************************************
void nkObj3DViewer::prStereoLessSeparation( void )
{
double sep,
inc=0.1;
sep = prv_camera->GetEyeAngle(); //! Get actual separation
prv_camera->SetEyeAngle(sep-inc); //! Decrease separation
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// MENU -> RESET CAMERA
//*****************************************************************************************
void nkObj3DViewer::prNavResetCamara( void )
{
prv_render3D->ResetCamera();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> TRACKBALL
//*****************************************************************************************
void nkObj3DViewer::prNavTrackball( )
{
vtkInteractorStyleTrackballCamera *l_style = vtkInteractorStyleTrackballCamera::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> JOYSTICK
//*****************************************************************************************
void nkObj3DViewer::prNavJoystick( )
{
vtkInteractorStyleJoystickCamera *l_style = vtkInteractorStyleJoystickCamera::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> FLIGHT
//*****************************************************************************************
void nkObj3DViewer::prNavFlight( )
{
vtkInteractorStyleFlight *l_style = vtkInteractorStyleFlight ::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> UNICAM
//*****************************************************************************************
void nkObj3DViewer::prNavUnicam( )
{
vtkInteractorStyleUnicam *l_style = vtkInteractorStyleUnicam::New();
l_style->SetWorldUpVector(0.0, 1.0, 0.0);
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// FILTRADO DE POLIGONOS -> TRIANGULACION
//*****************************************************************************************
void nkObj3DViewer::prPolyTriangle( )
{
// Surface triangulation
vtkTriangleFilter *l_Triangle = vtkTriangleFilter::New();
l_Triangle->SetInput(prv_data);
l_Triangle->UpdateWholeExtent(); //! Update algorithm
//! Copy filter output in a_Input
vtkPolyData *l_temp = vtkPolyData::New();
l_temp->DeepCopy( l_Triangle->GetOutput() );
prv_data->DeepCopy( l_temp );
//! Delete filters
l_temp->Delete();
l_Triangle->Delete();
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// FILTER -> DECIMATE
//*****************************************************************************************
void nkObj3DViewer::prPolyDecimate( )
{
wxString etiquetas[100];
const int num_datos=1;
etiquetas[0] = _("Decimate ratio");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Decimate mesh"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->cambiarValor(wxT("0.7"),0);
miDlg->ShowModal();
double datos[num_datos];
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
for(int i=0;i<num_datos;i++)
(miDlg->obtenerValor(i)).ToDouble(&datos[i]);
// Triangulate fisrt
this->prPolyTriangle();
// a_Decimate approximation
vtkDecimatePro *l_Decimate = vtkDecimatePro::New();
l_Decimate->SetInput( prv_data );
l_Decimate->PreserveTopologyOn(); //! Turn on/off whether to preserve the topology of the original mesh
l_Decimate->BoundaryVertexDeletionOff(); //! Turn on/off the deletion of vertices on the boundary of a mesh
l_Decimate->SplittingOn(); //! Split triangles
l_Decimate->SetMaximumError(VTK_LARGE_FLOAT); //! Maximun error
l_Decimate->SetTargetReduction (datos[0]); //! Percent of resulting polygons
l_Decimate->UpdateWholeExtent(); //! Update algorithm
//! Copy filter output in a_Input
vtkPolyData *l_temp = vtkPolyData::New();
l_temp->DeepCopy( l_Decimate->GetOutput() );
prv_data->DeepCopy( l_temp );
//! Delete filters
l_temp->Delete();
l_Decimate->Delete();
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
wxEndBusyCursor();
}
delete miDlg;
}
//*****************************************************************************************
// FILTER -> SMOOTH
//*****************************************************************************************
void nkObj3DViewer::prPolySmooth( )
{
wxString etiquetas[100];
const int num_datos=1;
etiquetas[0] = _("Filter iterations");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Smooth mesh"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->cambiarValor(wxT("100"),0);
miDlg->ShowModal();
double datos[1];
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
for(int i=0;i<num_datos;i++)
(miDlg->obtenerValor(i)).ToDouble(&datos[i]);
// Polygon a_Smooth
vtkSmoothPolyDataFilter *l_Smooth = vtkSmoothPolyDataFilter::New();
l_Smooth->SetInput( prv_data );
l_Smooth->SetNumberOfIterations((int)datos[0]);
l_Smooth->SetConvergence(0);
l_Smooth->UpdateWholeExtent();
//! Copy filter output in a_Input
vtkPolyData *l_temp = vtkPolyData::New();
l_temp->DeepCopy( l_Smooth->GetOutput() );
prv_data->DeepCopy( l_temp );
//! Delete filters
l_temp->Delete();
l_Smooth->Delete();
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
wxEndBusyCursor();
}
delete miDlg;
}
//*****************************************************************************************
// FILTERS -> NORMALS
//*****************************************************************************************
void nkObj3DViewer::prPolyNormals( )
{
wxString etiquetas[100];
const int num_datos=1;
etiquetas[0] = _("Angle value for define normal");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Recalc normals"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->cambiarValor(wxT("60"),0);
miDlg->ShowModal();
double datos[1];
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
for(int i=0;i<num_datos;i++)
(miDlg->obtenerValor(i)).ToDouble(&datos[i]);
// Polygon a_Smooth
vtkPolyDataNormals *l_Normals = vtkPolyDataNormals::New();
l_Normals->SetInput( prv_data );
l_Normals->SetFeatureAngle(datos[0]);
l_Normals->UpdateWholeExtent();
//! Copy filter output in a_Input
vtkPolyData *l_temp = vtkPolyData::New();
l_temp->DeepCopy( l_Normals->GetOutput() );
prv_data->DeepCopy( l_temp );
//! Delete filters
l_temp->Delete();
l_Normals->Delete();
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
wxEndBusyCursor();
}
delete miDlg;
}
//*****************************************************************************************
// FILTER -> DEFORM
//*****************************************************************************************
void nkObj3DViewer::prPolyDeform( )
{
wxBeginBusyCursor();
//Deform a mesh
vtkPoints *l_points = vtkPoints::New();
int numPts = prv_data->GetNumberOfPoints();
double p[3];
for(int i=0;i<numPts;i++)
{
prv_data->GetPoint(i,p);
p[0]=p[0]+5.0;
p[1]=p[1]+8.0;
p[2]=p[2]-2.0;
l_points->InsertPoint(i,p[0],p[1],p[2]);
}
//! Copy filter output in a_Input
vtkPolyData *l_temp = vtkPolyData::New();
l_temp->CopyStructure(prv_data);
l_temp->SetPoints(l_points);
l_temp->Update();
prv_data->DeepCopy( l_temp );
l_temp->Delete();
l_points->Delete();
//! Refresh GUI
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
wxEndBusyCursor();
}
//*****************************************************************************************
// RASTERIZER WINDOW
//*****************************************************************************************
vtkWindowToImageFilter* nkObj3DViewer::Snapshot( )
{
//! Save an window snapshot
vtkWindowToImageFilter* l_w2i = vtkWindowToImageFilter::New();
l_w2i->SetInput(prv_wxVtkVista3D->GetRenderWindow());
l_w2i->Update();
return l_w2i;
}
//*****************************************************************************************
// VIDEO CARD INFORMATION
//*****************************************************************************************
wxString nkObj3DViewer::VideoCard( )
{
const char* l_ren = l_ren = prv_wxVtkVista3D->GetRenderWindow()->ReportCapabilities(); //! Capturing Render capabilities from RenderWindow
wxString l_text(l_ren,wxConvUTF8);
return l_text;
}
//*****************************************************************************************
// Actualización de los planos de image
//*****************************************************************************************
void nkObj3DViewer::FPS()
{
if(!prv_fpsflag)
{
prv_fpsEvent=FpsChange::New();
prv_fpsEvent->SetRenderer(prv_render3D);
prv_render3D->AddObserver(vtkCommand::EndEvent,prv_fpsEvent);
prv_fpsEvent->Delete();
prv_fpsflag=1;
}
else
{
prv_render3D->RemoveObserver(vtkCommand::AnyEvent);
prv_fpsflag=0;
}
}
|
[
"apinzonf@4b68e429-1748-0410-913f-c2fc311d3372",
"baperezg@4b68e429-1748-0410-913f-c2fc311d3372"
] |
[
[
[
1,
88
],
[
90,
179
],
[
184,
619
]
],
[
[
89,
89
],
[
180,
183
],
[
620,
638
]
]
] |
4ef0d46c7874b35e9bdec28482880f98f79c7840
|
12732dc8a5dd518f35c8af3f2a805806f5e91e28
|
/trunk/LiteEditor/tags_options_dlg.h
|
78b397f6394acb5eea6731e57988c93c82e4243a
|
[] |
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 | 2,144 |
h
|
///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Jun 6 2007)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#ifndef __tags_options_dlg__
#define __tags_options_dlg__
#include <wx/wx.h>
#include <wx/panel.h>
#include <wx/wxFlatNotebook/wxFlatNotebook.h>
#include <wx/statline.h>
#include <wx/button.h>
#include "serialized_object.h"
#include "wx/filename.h"
#include "filepicker.h"
#include "tags_options_data.h"
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// Class TagsOptionsDlg
///////////////////////////////////////////////////////////////////////////////
class TagsOptionsDlg : public wxDialog
{
private:
protected:
wxFlatNotebook* m_mainBook;
wxPanel* m_generalPage;
wxCheckBox* m_checkParseComments;
wxCheckBox* m_checkDisplayComments;
wxCheckBox* m_checkDisplayTypeInfo;
wxCheckBox* m_checkDisplayFunctionTip;
wxCheckBox* m_checkLoadToMemory;
wxStaticText* m_staticTextHelp;
wxPanel* m_ctagsPage;
wxStaticText* m_staticText1;
FilePicker* m_filePicker;
wxStaticText* m_staticText3;
wxTextCtrl* m_textFileSpec;
wxStaticText* m_staticText5;
wxComboBox* m_comboBoxLang;
wxStaticLine* m_staticline1;
wxButton* m_buttonOK;
wxButton* m_buttonCancel;
wxCheckBox* m_checkLoadLastDB;
TagsOptionsData m_data;
wxCheckBox* m_checkFilesWithoutExt;
protected:
void SetFlag(CodeCompletionOpts flag, bool set);
void InitValues();
void CopyData();
void OnButtonOK(wxCommandEvent &event);
public:
TagsOptionsDlg( wxWindow* parent,
const TagsOptionsData& data,
int id = wxID_ANY,
wxString title = wxT("Tags Options"),
wxPoint pos = wxDefaultPosition,
wxSize size = wxSize(469, 362),
int style = wxDEFAULT_DIALOG_STYLE);
TagsOptionsData &GetData() {return m_data;}
};
#endif //__tags_options_dlg__
|
[
"eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b"
] |
[
[
[
1,
73
]
]
] |
0ea24e4c88f1d9553d15f799d86a9afd4ca43a02
|
b8fbe9079ce8996e739b476d226e73d4ec8e255c
|
/src/engine/rb_ui/jgrid.h
|
63cd53d3c4c2a215a54f1cd550c52f1235417bdc
|
[] |
no_license
|
dtbinh/rush
|
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
|
ad75072777438c564ccaa29af43e2a9fd2c51266
|
refs/heads/master
| 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null |
UTF-8
|
C++
| false | false | 1,922 |
h
|
//****************************************************************************/
// File: JGrid.h
// Date: 16.08.2005
// Author: Ruslan Shestopalyuk
//****************************************************************************/
#ifndef __JGRID_H__
#define __JGRID_H__
#include "jwidget.h"
//****************************************************************************/
// Class: JGrid
// Desc: Arranges children widgets in grid
//****************************************************************************/
class JGrid : public JWidget
{
public:
JGrid ();
virtual void Render ();
virtual void OnSize ();
void SetRowsCols ( int nRows, int nCols );
void SetSpacing ( int width, int height );
void SetMargins ( int left, int right, int top, int bottom );
void Layout ();
expose( JGrid )
{
parent(JWidget);
field( "NRows", m_NRows );
field( "NCols", m_NCols );
field( "HSpacing", m_HSpacing );
field( "VSpacing", m_VSpacing );
field( "MarginL", m_MarginL );
field( "MarginR", m_MarginR );
field( "MarginT", m_MarginT );
field( "MarginB", m_MarginB );
field( "Stretch", m_bStretch );
field( "Uniform", m_bUniform );
}
private:
int m_NRows;
int m_NCols;
int m_HSpacing;
int m_VSpacing;
int m_MarginL;
int m_MarginR;
int m_MarginT;
int m_MarginB;
bool m_bStretch; // stretches children to fit the cells
bool m_bUniform; // cells have equal sizes
}; // class JGrid
#endif // __JGRID_H__
|
[
"[email protected]"
] |
[
[
[
1,
61
]
]
] |
9282ed43780764514cef1d85c6394d49de5d6ace
|
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
|
/Projects/elastix/elastix_sources_v4/src/Components/FixedImagePyramids/FixedRecursivePyramid/elxFixedRecursivePyramid.hxx
|
931db168315541e268e28365c873e5d7757ffee5
|
[] |
no_license
|
mijc/Diploma
|
95fa1b04801ba9afb6493b24b53383d0fbd00b33
|
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
|
refs/heads/master
| 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 763 |
hxx
|
/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxFixedRecursivePyramid_hxx
#define __elxFixedRecursivePyramid_hxx
#include "elxFixedRecursivePyramid.h"
//nothing
#endif //#ifndef __elxFixedRecursivePyramid_hxx
|
[
"[email protected]"
] |
[
[
[
1,
23
]
]
] |
6d9c4def43dcb79195ae7234e407facd70bfe24c
|
021e8c48a44a56571c07dd9830d8bf86d68507cb
|
/build/vtk/QVTKPaintEngine.h
|
5420e3a24fb6a938fa802b84ded4a186f3ec91cb
|
[
"BSD-3-Clause"
] |
permissive
|
Electrofire/QdevelopVset
|
c67ae1b30b0115d5c2045e3ca82199394081b733
|
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
|
refs/heads/master
| 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,406 |
h
|
/*=========================================================================
Copyright 2004 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
license for use of this work by or on behalf of the
U.S. Government. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that this Notice and any
statement of authorship are reproduced on all copies.
=========================================================================*/
/*========================================================================
For general information about using VTK and Qt, see:
http://www.trolltech.com/products/3rdparty/vtksupport.html
=========================================================================*/
/*========================================================================
!!! WARNING for those who want to contribute code to this file.
!!! If you use a commercial edition of Qt, you can modify this code.
!!! If you use an open source version of Qt, you are free to modify
!!! and use this code within the guidelines of the GPL license.
!!! Unfortunately, you cannot contribute the changes back into this
!!! file. Doing so creates a conflict between the GPL and BSD-like VTK
!!! license.
=========================================================================*/
// .NAME QVTKPaintEngine - directs QPainter calls to a VTK window
#ifndef QVTK_PAINT_ENGINE_HPP
#define QVTK_PAINT_ENGINE_HPP
#include <QPaintEngine>
class QVTKWidget;
class QVTKPaintEngineInternal;
//! A paint engine class to direct QPainter calls into a VTK window
class QVTKPaintEngine : public QPaintEngine
{
public:
QVTKPaintEngine();
~QVTKPaintEngine();
// Description:
// begin painting on device (QVTKWidget)
bool begin(QPaintDevice* dev);
// Description:
// end painting on device
bool end();
// Description:
// returns type User
QPaintEngine::Type type() const;
// Description:
// updateState
void updateState(const QPaintEngineState&);
// Description:
// draw a pixmap
void drawPixmap(const QRectF& r, const QPixmap& pm, const QRectF& sr);
// Description:
// draw a path
void drawPath(const QPainterPath& path);
protected:
QVTKWidget* Widget;
QVTKPaintEngineInternal* Internal;
};
#endif
|
[
"ganondorf@ganondorf-VirtualBox.(none)"
] |
[
[
[
1,
74
]
]
] |
63b057ffe5f1ed6aabbe4b706d224e0ff5ef10ba
|
2ca3ad74c1b5416b2748353d23710eed63539bb0
|
/Src/Lokapala/Operator/StatusReportsDTO.cpp
|
d32f3a579dae721e742d5bda14982d3361a777f6
|
[] |
no_license
|
sjp38/lokapala
|
5ced19e534bd7067aeace0b38ee80b87dfc7faed
|
dfa51d28845815cfccd39941c802faaec9233a6e
|
refs/heads/master
| 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,480 |
cpp
|
/**@file StatusReportsDTO.cpp
* @brief CStatusReportsDTO 클래스의 멤버함수를 구현한다.
* @author siva
*/
#include "stdafx.h"
#include "StatusReportsDTO.h"
/**@brief 상황 보고 내용을 추가한다.\n
* 최종적으로 VERIFIED 된 이전의 상태 보고라면 무시한다.\n
* 만약 추가되는 상황의 상태가 VERIFIED, 즉 고장 상태 수리 완료라면 해당 주소에 대한 기존의 상황 보고는 삭제한다.\n
* 만약 기존에 있던 상황 보고라면 무시한다.\n
* 항상 배열 내의 항목들은 시간 순으로 정렬된다.
*/
void CStatusReportsDTO::AddReport(CStatusReportDTO *a_report)
{
int i;
for(int i=m_reports.GetCount()-1; i>=0; i--)
{
if(m_reports[i].m_state == VERIFIED)
{
if( a_report->m_date <= m_reports[i].m_date )
{
return;
}
break;
}
}
if(a_report->m_state == VERIFIED)
{
DeleteVerifiedReports(a_report);
}
for(i=0; i<m_reports.GetCount(); i++)
{
if(m_reports[i].m_comment == a_report->m_comment &&
m_reports[i].m_state == a_report->m_state &&
m_reports[i].m_hostAddress == a_report->m_hostAddress &&
m_reports[i].m_date == a_report->m_date )
{
return;
}
if(a_report->m_date < m_reports[i].m_date)
{
break;
}
}
m_reports.InsertAt(i, *a_report);
}
/**@brief VERIFIED 상태 보고가 들어 왔을 때. 이전 시각의, 동일 주소로부터의 상태 보고를 모두 지운다.
*/
void CStatusReportsDTO::DeleteVerifiedReports(CStatusReportDTO *a_report)
{
for(int i=m_reports.GetCount()-1; i>=0; i--)
{
if(m_reports[i].m_hostAddress == a_report->m_hostAddress && m_reports[i].m_date < a_report->m_date)
{
m_reports.RemoveAt(i);
}
}
}
/**@brief 특정 주소로부터의 상황 보고를 삭제한다.
*/
void CStatusReportsDTO::DeleteReportAt(CString a_hostAddress)
{
for(int i=m_reports.GetCount()-1; i>=0; i--)
{
if(m_reports[i].m_hostAddress == a_hostAddress)
{
m_reports.RemoveAt(i);
}
}
}
/**@brief 특정 주소로부터의 상황 보고를 가져온다.
* @brief a_dest 해당 상황 보고들을 넣어줄 상황 보고 정보체 배열의 주소.
*/
void CStatusReportsDTO::GetReportFrom(CString a_hostAddress, CStatusReportDTOArray *a_dest)
{
for(int i=m_reports.GetCount()-1; i>=0; i--)
{
if(m_reports[i].m_hostAddress == a_hostAddress)
{
a_dest->Add(m_reports[i]);
}
}
}
|
[
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] |
[
[
[
1,
89
]
]
] |
d5fb9abf92701d6a6a9a151d91a0a402856eb97e
|
c1bcff0f1321de8a6425723cdfa0b5aa65b5c81f
|
/TransX/trunk/transx.cpp
|
c5265c2b9cd0ead70df77384bff3936fd8786fe0
|
[
"MIT"
] |
permissive
|
net-lisias-orbiter/transx
|
560266e7a4ef73ed29d9004e406fd8db28da9a43
|
b9297027718a7499934a9614430aebb47422ce7f
|
refs/heads/master
| 2023-06-27T14:16:10.697238 | 2010-09-05T01:18:54 | 2010-09-05T01:18:54 | 390,398,358 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,537 |
cpp
|
/* Copyright (c) 2007 Duncan Sharpe, Steve Arch
**
** 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.*/
#define STRICT
#define ORBITER_MODULE
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include "orbitersdk.h"
#include "mfd.h"
#include "graph.h"
#include "intercept.h"
#include "mfdvarhandler.h"
#include "basefunction.h"
#include "viewstate.h"
#include "shiplist.h"
#include "transx.h"
int TransxMFD::MfdCount=0;
double debug;
TransxMFD::TransxMFD (DWORD w, DWORD h, VESSEL *vessel, UINT mfd)
: MFD2 (w, h, vessel)
// Initialise TransXMFD
{
//Check to see if new Transxstate is required
valid=false;
viewstate=NULL;
if (mfd>20) mfd=1;//Set to safe value in this instance
class shipptrs *shptr=shipptrs::getshipptrs();//Knows ship must be current focus
viewstate=shptr->getviewstate(mfd,this);
viewstate->setmfdactive(true);
++MfdCount;
}
TransxMFD::~TransxMFD()
{
viewstate->setmfdactive(false);
if (!viewstate->getrenderviewport())//If we're closing, take the state with you, otherwise leave it.
{
shipptrs::destroyshipptrs();//destroy all pointer structures
}
--MfdCount;
}
// Called by Orbiter when a screen update is needed
bool TransxMFD::Update (Sketchpad *sketchpad)
{
Title (sketchpad, "TransX MFD");
Pen *pen = GetDefaultPen (TransXFunction::Green); // Retrieves a default MFD pen
valid=viewstate->doupdate(sketchpad,W,H,this);
shipptrs::refreshsave();//allow save again, as new values are now available
sketchpad->SetPen(pen);
if (!valid)
return false;
int linespacing=H/24;
if (debug!=0)
{
char buffer[20];
int length=sprintf(buffer,"Debug:%g",debug);
sketchpad->Text(0, linespacing*22, buffer, length);
}
MFDvariable *varpointer=viewstate->GetCurrVariable();
if (varpointer==NULL)
return false;
varpointer->show(sketchpad,W,linespacing);
return true;
// From Martins (http://www.orbiter-forum.com/project.php?issueid=210#note1142):
// The return value is currently ignored.
// It may be used in the future to indicate if the surface was redrawn, for optimisation purposes (removal of unneccesary surface copies).
}
int TransxMFD::getwidth()
{
return W;
}
int TransxMFD::getheight()
{
return H;
}
int TransxMFD::MsgProc (UINT msg, UINT mfd, WPARAM wparam, LPARAM lparam)
// Standard message parser for messages passed from Orbiter
{
switch (msg) {
case OAPI_MSG_MFD_OPENED:
return (int) new TransxMFD (LOWORD(wparam), HIWORD(wparam), (VESSEL*)lparam, mfd);
}
return 0;
}
char *TransxMFD::ButtonLabel (int bt)
// Routine to pass button label back to Orbiter. Called by Orbiter
{
char *label[] = {"HLP","FWD","BCK", "VW","VAR","-VR", "ADJ", "-AJ","++", "--","EXE"};
return (bt < sizeof(label) / sizeof(char*) ? label[bt] : 0);
}
int TransxMFD::ButtonMenu (const MFDBUTTONMENU **menu) const
// Routine to pass menu description for buttons back to Orbiter. Called by Orbiter
{
static const MFDBUTTONMENU mnu[] = {
{"Toggle Help","On/Off",'H'},
{"Step Forward","/ Add Step",'F'},
{"Step Back",0,'R'},
{"Select View",0,'W'},
{"Next Variable", 0, '.'},
{"Prev. Variable", 0, ','},
{"Set adjustment", "method (+)", '{'},
{"Set adjustment", "method (-)", '}'},
{"Increment", "variable", '='},
{"Decrement", "variable", '-'},
{"Execute","Command",'X'}
};
if (menu) *menu = mnu;
return sizeof(mnu) / sizeof(MFDBUTTONMENU);
}
bool TransxMFD::ConsumeKeyImmediate(char *kstate)
// Routine which processes the keyboard state. Allows continuous change of variable.
{
if (!valid) return false;
MFDvariable *varpointer=viewstate->GetCurrVariable();
if (varpointer==NULL) return false;
if(!varpointer->IsContinuous())
return false; // do not process this continuous change if the variable is not continuous.
if (*(kstate+OAPI_KEY_MINUS)==-128)
{
varpointer->dec_variable();
return true;
}
if (*(kstate+OAPI_KEY_EQUALS)==-128)
{
varpointer->inc_variable();
return true;
}
return false;
}
bool TransxMFD::ConsumeButton(int bt, int event)
// Deal with mouse pressing of keys
{
static const DWORD btkey[11]={OAPI_KEY_H, OAPI_KEY_F, OAPI_KEY_R, OAPI_KEY_W, OAPI_KEY_PERIOD,
OAPI_KEY_COMMA, OAPI_KEY_LBRACKET, OAPI_KEY_RBRACKET, OAPI_KEY_EQUALS, OAPI_KEY_MINUS, OAPI_KEY_X};
if (!valid) return false;
MFDvariable *varpointer=viewstate->GetCurrVariable();
if ((event & PANEL_MOUSE_LBDOWN) && (bt<8 || bt==10)) return ConsumeKeyBuffered (btkey[bt]);
if (bt>9) return false; //No buttons above 10
if (varpointer==NULL) return false;
if (event & PANEL_MOUSE_LBDOWN)
{
// Button 8 or 9 is pressed and the mode is discrete
return ConsumeKeyBuffered (btkey[bt]);
}
// At this point, only the possibility of immediate consumption...
if (!(event & PANEL_MOUSE_LBPRESSED) || !varpointer->IsContinuous()) return false; //Mouse button is down on 9 or 10
if (bt==9)
varpointer->dec_variable();
if (bt==8)
varpointer->inc_variable();
return true;
}
bool TransxMFD::ConsumeKeyBuffered (DWORD key)
{
if (!valid) return false;
MFDvariable *currvar=viewstate->GetCurrVariable();
bool access=(currvar!=NULL);
switch (key) {
case OAPI_KEY_H:
viewstate->fliphelpsystem();
return true;
case OAPI_KEY_F:
viewstate->movetonextfunction();
return true;
case OAPI_KEY_R:
viewstate->movetopreviousfunction();
return true;
case OAPI_KEY_W:
viewstate->inc_viewmode();
return true;
case OAPI_KEY_X:
if (access) currvar->execute();
return true;
case OAPI_KEY_PERIOD: //Switch variable
{
int viewmode=viewstate->getvariableviewmode();
viewstate->GetVarhandler()->setnextcurrent(viewmode);
}
return true;
case OAPI_KEY_COMMA:
{
int viewmode=viewstate->getvariableviewmode();
viewstate->GetVarhandler()->setprevcurrent(viewmode);
}
return true;
case OAPI_KEY_LBRACKET:
if (access) currvar->ch_adjmode();
return true;
case OAPI_KEY_RBRACKET:
if (access) currvar->chm_adjmode();
return true;
case OAPI_KEY_MINUS:
if (access) currvar->dec_variable();
return true;
case OAPI_KEY_EQUALS:
if (access) currvar->inc_variable();
return true;
}
return false; //Key not one of cases above
}
void TransxMFD::WriteStatus(FILEHANDLE scn) const
{
if (!valid)
return;
shipptrs::saveallships(scn);
}
void TransxMFD::ReadStatus(FILEHANDLE scn)
{
shipptrs::restoreallships(scn);
}
|
[
"steve@5a6c10e1-6920-0410-8c7b-9669c677a970",
"agentgonzo@5a6c10e1-6920-0410-8c7b-9669c677a970",
"apogee@5a6c10e1-6920-0410-8c7b-9669c677a970"
] |
[
[
[
1,
41
],
[
43,
66
],
[
68,
68
],
[
72,
72
],
[
76,
82
],
[
84,
86
],
[
95,
119
],
[
121,
137
],
[
139,
168
],
[
170,
208
],
[
212,
250
]
],
[
[
42,
42
],
[
67,
67
],
[
69,
69
],
[
71,
71
],
[
73,
75
],
[
83,
83
],
[
87,
94
],
[
120,
120
],
[
138,
138
],
[
169,
169
],
[
209,
211
]
],
[
[
70,
70
]
]
] |
39e9ab8ab9325e404cb6759ef0b3797e4de52e77
|
d04549b1ba243371de53d6ff113b0716f7fc7c65
|
/KaiAtl/stdafx.h
|
bf1be5dae0b2f829e18bd3eafff03ce5b7178f09
|
[] |
no_license
|
kbogatyrev/Kai2
|
0541e2e48c8c5070eb0a6709b933677b93c55075
|
2eee38d4836b7e138cf38b4c05ebf0e32cb3a34d
|
refs/heads/master
| 2016-09-05T12:52:34.016879 | 2011-04-25T01:17:24 | 2011-04-25T01:17:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 983 |
h
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#pragma once
#ifndef STRICT
#define STRICT
#endif
#include "targetver.h"
#define _ATL_APARTMENT_THREADED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include "resource.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
using namespace ATL;
#include "Error.h"
/*
#define ERROR_LOG (sMsg) wstringstream io__; \
io__ << __LINE__; \
CError::HandleError (sMsg, \
std::wstring (_T(__FILE__)) + \
std::wstring (_T("\t")) + \
io__.str() + \
std::wstring (_T("\t")) + \
std::wstring (_T(__FUNCTION__)));
*/
|
[
"kostya@917a17ce-c119-4def-a483-dcb93d956afe"
] |
[
[
[
1,
36
]
]
] |
1afd8d79034358221d7dda2286011afd4582341a
|
a9afa168fac234c3b838dd29af4a5966a6acb328
|
/CppUTest/src/CppUTest/TestOutput.cpp
|
5d57afa750ab891a3ad0e7785f79aa763c6e2527
|
[] |
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,518 |
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.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TestOutput::TestOutput() :
dotCount_(0), verbose_(false), progressIndication(".")
{
}
TestOutput::~TestOutput()
{
}
void TestOutput::verbose()
{
verbose_ = true;
}
void TestOutput::print(long n)
{
print(StringFrom(n).asCharString());
}
void TestOutput::printDouble(double d)
{
print(StringFrom(d, 3).asCharString());
}
void TestOutput::printHex(long n)
{
print(HexStringFrom(n).asCharString());
}
TestOutput& operator<<(TestOutput& p, const char* s)
{
p.print(s);
return p;
}
TestOutput& operator<<(TestOutput& p, long int i)
{
p.print(i);
return p;
}
void TestOutput::printCurrentTestStarted(const Utest& test)
{
if (verbose_) print(test.getFormattedName().asCharString());
}
void TestOutput::printCurrentTestEnded(const TestResult& res)
{
if (verbose_) {
print(" - ");
print(res.getCurrentTestTotalExecutionTime());
print(" ms\n");
}
else {
printProgressIndicator();
}
}
void TestOutput::printProgressIndicator()
{
print(progressIndication);
if (++dotCount_ % 50 == 0) print("\n");
}
void TestOutput::setProgressIndicator(const char* indicator)
{
progressIndication = indicator;
}
void TestOutput::printTestsStarted()
{
}
void TestOutput::printCurrentGroupStarted(const Utest& test)
{
}
void TestOutput::printCurrentGroupEnded(const TestResult& res)
{
}
void TestOutput::flush()
{
}
void TestOutput::printTestsEnded(const TestResult& result)
{
if (result.getFailureCount() > 0) {
print("\nErrors (");
print(result.getFailureCount());
print(" failures, ");
}
else {
print("\nOK (");
}
print(result.getTestCount());
print(" tests, ");
print(result.getRunCount());
print(" ran, ");
print(result.getCheckCount());
print(" checks, ");
print(result.getIgnoredCount());
print(" ignored, ");
print(result.getFilteredOutCount());
print(" filtered out, ");
print(result.getTotalExecutionTime());
print(" ms)\n\n");
}
void TestOutput::printTestRun(int number, int total)
{
if (total > 1) {
print("Test run ");
print(number);
print(" of ");
print(total);
print("\n");
}
}
void TestOutput::print(const Failure& failure)
{
print("\n");
print(failure.getFileName().asCharString());
print(":");
print(failure.getLineNumber());
print(":");
print(" error: ");
print("Failure in ");
print(failure.getTestName().asCharString());
print("\n");
print("\t");
print(failure.getMessage().asCharString());
print("\n\n");
}
void ConsoleTestOutput::print(const char* s)
{
while (*s) {
if ('\n' == *s) PlatformSpecificPutchar('\r');
PlatformSpecificPutchar(*s);
s++;
}
flush();
}
void ConsoleTestOutput::flush()
{
PlatformSpecificFlush();;
}
|
[
"[email protected]"
] |
[
[
[
1,
181
]
]
] |
0f4c4bbaebcf9159e3e33eb4328117045ba48d63
|
4b116281b895732989336f45dc65e95deb69917b
|
/Documentation/Design Patterns/SingletonPattern/SingletonPattern/main.cpp
|
d013d694ccecb7d6a9441139135763eda5b0d4c8
|
[] |
no_license
|
Pavani565/gsp410-spaceshooter
|
1f192ca16b41e8afdcc25645f950508a6f9a92c6
|
c299b03d285e676874f72aa062d76b186918b146
|
refs/heads/master
| 2021-01-10T00:59:18.499288 | 2011-12-12T16:59:51 | 2011-12-12T16:59:51 | 33,170,205 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,763 |
cpp
|
// Singleton Pattern //
#include <iostream>
#include <time.h>
using namespace std;
class Singleton
{
private:
// A Pointer To The Singleton Class //
static Singleton* m_Single;
// A Flag That We Can Check If The Class Has Been Instantiated Previously //
// This Is Optional, As The Class Can Be Checked To Be Equal To NULL //
static bool m_InstanceFlag;
// A RandomNumber That Will Be Displayed To Prove This Class Has Become A Singleton //
int m_RandomNumber;
// A Private Constructor //
// This Should Make One Wonder "How Do We Make This Class?" //
// Since A Private Constructor Means Only A Member Of This //
// Class Can Instantiate This Class! //
Singleton()
{
// Set The Random Number To 0 //
m_RandomNumber = 0;
// We Initialize The Static Variables Differently From Normal Variables //
}
public:
// A Public Function That Will Create The Class Once, Then Always //
// Return A Pointer Instead Of Creating The Object Again //
// "static" Means This Method Is Unique To This Class And Must Be Called Using //
// This Class's Name, Not An Instance Name. Example: Singleton.getInstance() //
// Would Not Work. This Must Be Called Using Singleton::getInstance() //
static Singleton* getInstance();
// A Prototype Of A Function To Call To Set The RandomNumber //
void setRandomNumber(int Number);
// A Prototype Of A Function To Return The Random Number //
int getRandomNumber(void);
// A Destructor //
~Singleton()
{
// Set The Flag To False As Now This Object Has Been Destructed //
m_InstanceFlag = false;
}
};
//---Initialize The Static Variables---//
// Set The m_InstanceFlag To False //
// We Have To Put The Data Type Here (Like We're Declaring The Variable Again) //
// Because This Variable Exists At The Compiler's Level Or Something Like That //
bool Singleton::m_InstanceFlag = false;
// Set The m_Sinlge To NULL //
Singleton* Singleton::m_Single = NULL;
//-------------------------------------//
// Definition Of The getInstance Function In The Singleton Class //
Singleton* Singleton::getInstance()
{
// Check If The Class Has Been Instantiated //
// It Is Possible To Check Here If m_Single == NULL Instead Of Using A Flag //
if(m_InstanceFlag == false)
{
//If Not, Set The Singleton Pointer To A New Instantiation Of The Class //
m_Single = new Singleton();
// Set The Instance Flag To True //
m_InstanceFlag = true;
// Return The Pointer //
return m_Single;
}
else
{
// If InstanceFlag Has Been Set To True, Then We Simply Return The Pointer //
// Because It Has Already Been Created //
return m_Single;
}
}
// Definition Of The setRandomNumber Function In The Singleton Class //
void Singleton::setRandomNumber(int Number)
{
// Set The Passed In Number To The RandomNumber Variable In The Singleton Class //
m_RandomNumber = Number;
}
// Definition Of The getRandomNumber Function In The Singleton Class //
int Singleton::getRandomNumber(void)
{
// Return The RandomNumber From The Singleton Class //
return m_RandomNumber;
}
int main()
{
// Seed The Random Number Generator //
srand(unsigned(time(NULL)));
// Create A Pointer That Will Point To The Singleton Class //
Singleton* ObjectPointer;
// Set The ObjectPointer To The Same Location As The Internal Pointer //
// Of The Singleton Class By Using The Class Name To Call getInstance //
ObjectPointer = Singleton::getInstance();
// The Singleton Is Now Complete! //
// There Will Never Be Another Instantiation of The Singleton Class //
// Now Time To Prove It Is A Singleton //
//Set The RandomNumber In The Singleton //
ObjectPointer->setRandomNumber(::rand());
// Create Another ObjectPointer //
Singleton *SecondPointer;
// Try To Set This Pointer To Another Instaniation Of The Singleton Class //
SecondPointer = Singleton::getInstance();
// Print The RandomNumber Of The ObjectPointer (Should Be A Random Number) //
printf("ObjectPointer's RandomNumber: %i\n", ObjectPointer->getRandomNumber());
// Print The RandomNumber Of The SecondPointer (Should Be 0 If It Made A Second Object) //
printf("SecondPointer's RandomNumber: %i\n\n", SecondPointer->getRandomNumber());
printf("Both Of These Numbers Are The Same Because The SecondPointer Did Not Create\nAnother Instance, But Instead Was Set To The Same Object As The First Pointer\n\n");
printf("ObjectPointer's Memory Address: %i\n", ObjectPointer);
printf("SecondPointer's Memory Address: %i\n\n", SecondPointer);
printf("As You Can See, They Both Point To The Same Location In Memory!\n");
// Put A Break Point Here! //
// End The Program //
return 0;
}
|
[
"[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7"
] |
[
[
[
1,
132
]
]
] |
b2a793a2a64d3c77ce00e1f68f5a0a82a2994edb
|
a5fde255bbd9ff363761f81ffae078619a0a0471
|
/gaussian/CubicSpline.h
|
57971feea5b43411dcebc4cd07517189bba502a0
|
[] |
no_license
|
FinancialEngineerLab/gaussian
|
4bfdf35208c0cdea15611271908c4058d39dd11b
|
19e1b73b3328bb0d07212b8e77c840fb35744e17
|
refs/heads/master
| 2023-03-17T18:24:38.852378 | 2007-10-07T22:10:48 | 2007-10-07T22:10:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,844 |
h
|
/***************************************************************************
* Copyright (C) 2007 by mjhmeyer *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#pragma once
#include "Typedefs.h"
namespace spline {
/**!
*/
class CubicSpline {
public:
/** Cubic spline passing through the points (x[i],y[i]), 0<=i<nData.
* @param nData = length(x) = length(y) nuber of data points.
* @param ypLeft left endpoint derivative.
* @param ypRight right endpoint derivative.
*/
CubicSpline(int nData, Vector x, Vector y, double ypLeft, double ypRight);
~CubicSpline(void);
/** Number of knots. */
int nData(){ return nData_; }
/** Value at x*/
double operator()(double x){ return value(x);}
/** Value at x*/
double value(double x);
/** Derivative at x. */
double diff(double x);
/** Second derivative at x. */
double diff2(double x);
double x(int i) const { return x_[i]; }
double y(int i) const { return y_[i]; }
double h(int i) const { return h_[i]; }
/** Left endpoint derivative, read-write access. */
double& ypLeft(){ return ypLeft_; }
/** Right endpoint derivative, read-write access. */
double& ypRight(){ return ypRight_; }
private:
// i such that t\in(x_i,x_{i+1}]
int find(double t);
// read-write access
double& h(int i){ return h_[i]; }
double& g(int i){ return g_[i]; }
double& sp(int i){ return sp_[i]; }
int nData_;
Vector x_;
Vector h_;
Vector y_;
double ypLeft_; // y'(x_0)
double ypRight_; // y'(x_l), l=nData-1
Vector g_; // gammas
Vector sp_; // s'(x_{i+1})
};
} // end namespace spline
|
[
"michaeljmeyer"
] |
[
[
[
1,
80
]
]
] |
2dbe49f011829a573f11892bbd49c7f0bcf26320
|
c3179c7c5b2f2fa84498f6b645563e5a7a04f17b
|
/shared/db/key.h
|
f842f4b8f06f570b8a340fecda61325ea6011b38
|
[] |
no_license
|
joshmg/key
|
843214a5f8b5f60124cf94b7fe1fe82e46b575a8
|
02b634d26e7b4ec8346de318cec0641bc6bb52cd
|
refs/heads/master
| 2021-01-01T17:05:36.078466 | 2010-09-30T06:03:55 | 2010-09-30T06:03:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,785 |
h
|
// File: key.h
// Written by Joshua Green
#ifndef KEY_H
#define KEY_H
#include "column.h"
#include "../str/str.h"
#include <string>
struct column;
struct condition;
// --------------------------------------------------------------- KEY ENTRY ---------------------------------------------------------------- //
// + NOTES: //
// - used to contain the individual row's key column entries with their respective file positions inside *.dat //
// - contains: //
// - a single row's value for the table's key column //
// - the row's associated file position within the table's *.dat file //
// - a pointer to the table's key column //
// ------------------------------------------------------------------------------------------------------------------------------------------ //
struct key_entry {
column *col; // pointer to the table's key column
std::string data; // the row's value for the table's key column
long long int fpos; // file position inside *.dat where row starts
long int row_id;
key_entry();
key_entry(column *_key, std::string _data, long long int _fpos, long int _id=0);
~key_entry();
bool operator==(const key_entry &comp);
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
36
]
]
] |
50b6ce94bb4f6bbff55b9d05a4d795505e5e4a24
|
de75637338706776f8770c9cd169761cec128579
|
/VHFOS/Simple Game Framework/GameMonkey/gmThread.cpp
|
34e63381dfc3c38b968ac11e0d2e7f8179939791
|
[] |
no_license
|
huytd/fosengine
|
e018957abb7b2ea2c4908167ec83cb459c3de716
|
1cebb1bec49720a8e9ecae1c3d0c92e8d16c27c5
|
refs/heads/master
| 2021-01-18T23:47:32.402023 | 2008-07-12T07:20:10 | 2008-07-12T07:20:10 | 38,933,821 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 32,962 |
cpp
|
/*
_____ __ ___ __ ____ _ __
/ ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_
/ (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/
\___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/
/___/ /_/
See Copyright Notice in gmMachine.h
*/
#include "gmConfig.h"
#include "gmThread.h"
#include "gmByteCode.h"
#include "gmMachine.h"
#include "gmFunctionObject.h"
#include "gmOperators.h"
#include "gmMachineLib.h"
// helper macros
#define OPCODE_PTR(I) *((gmptr *) (I)); (I) += sizeof(gmptr);
#define OPCODE_PTR_NI(I) *((gmptr *) I);
#define OPCODE_FLOAT(I) *((gmfloat *) I); I += sizeof(gmfloat);
#define OPERATOR(TYPE, OPERATOR) (m_machine->GetTypeNativeOperator((TYPE), (OPERATOR)))
#define CALLOPERATOR(TYPE, OPERATOR) (m_machine->GetTypeOperator((TYPE), (OPERATOR)))
#define GMTHREAD_LOG m_machine->GetLog().LogEntry
#define PUSHNULL top->m_type = GM_NULL; top->m_value.m_int = 0; ++top;
// helper functions
void gmGetLineFromString(const char * a_string, int a_line, char * a_buffer, int a_len)
{
const char * cp = a_string, * eol;
int line = 1;
while(a_line > line)
{
while(*cp && *cp != '\n' && *cp != '\r') ++cp;
if(*cp == '\n') { ++cp; while(*cp == '\r') ++cp; ++line; }
else if(*cp == '\r') { ++cp; if(*cp == '\n') ++cp; ++line; }
if(*cp == '\0') { a_buffer[0] = '\0'; return; }
}
eol = cp;
while(*eol && *eol != '\n' && *eol != '\r') ++eol;
int len = eol - cp;
len = ((a_len - 1) < len) ? (a_len - 1) : len;
memcpy(a_buffer, cp, len);
a_buffer[len] = '\0';
}
//
//
// Implementation of gmThread
//
//
gmThread::gmThread(gmMachine * a_machine, int a_initialByteSize)
{
m_frame = NULL;
m_machine = a_machine;
m_size = a_initialByteSize / sizeof(gmVariable);
m_stack = GM_NEW( gmVariable[m_size] );
m_top = 0;
m_base = 0;
m_numParameters = 0;
#if GMDEBUG_SUPPORT
m_debugUser = 0;
m_debugFlags = 0;
#endif // GMDEBUG_SUPPORT
m_timeStamp = 0;
m_startTime = 0;
m_instruction = NULL;
m_state = KILLED;
m_id = GM_INVALID_THREAD;
m_blocks = NULL;
m_signals = NULL;
m_user = 0;
}
gmThread::~gmThread()
{
Sys_Reset(0);
if(m_stack)
{
delete [] m_stack;
}
}
#if GM_USE_INCGC
void gmThread::GCScanRoots(gmMachine* a_machine, gmGarbageCollector* a_gc)
{
// mark stack
int i;
for(i = 0; i < m_top; ++i)
{
if(m_stack[i].IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, m_stack[i].m_value.m_ref);
a_gc->GetNextObject(object);
}
}
// mark signals
gmSignal * signal = m_signals;
while(signal)
{
if(signal->m_signal.IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, signal->m_signal.m_value.m_ref);
a_gc->GetNextObject(object);
}
signal = signal->m_nextSignal;
}
// mark blocks
gmBlock * block = m_blocks;
while(block)
{
if(block->m_block.IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, block->m_block.m_value.m_ref);
a_gc->GetNextObject(object);
}
block = block->m_nextBlock;
}
}
#else //GM_USE_INCGC
void gmThread::Mark(gmuint32 a_mark)
{
// mark stack
int i;
for(i = 0; i < m_top; ++i)
{
if(m_stack[i].IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, m_stack[i].m_value.m_ref);
if(object->NeedsMark(a_mark)) object->Mark(m_machine, a_mark);
}
}
// mark signals
gmSignal * signal = m_signals;
while(signal)
{
if(signal->m_signal.IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, signal->m_signal.m_value.m_ref);
if(object->NeedsMark(a_mark)) object->Mark(m_machine, a_mark);
}
signal = signal->m_nextSignal;
}
// mark blocks
gmBlock * block = m_blocks;
while(block)
{
if(block->m_block.IsReference())
{
gmObject * object = GM_MOBJECT(m_machine, block->m_block.m_value.m_ref);
if(object->NeedsMark(a_mark)) object->Mark(m_machine, a_mark);
}
block = block->m_nextBlock;
}
}
#endif //GM_USE_INCGC
// RAGE AGAINST THE VIRTUAL MACHINE =)
gmThread::State gmThread::Sys_Execute(gmVariable * a_return)
{
register union
{
const gmuint8 * instruction;
const gmuint32 * instruction32;
};
register gmVariable * top;
gmVariable * base;
gmVariable * operand;
const gmuint8 * code;
if(m_state != RUNNING) return m_state;
#if GMDEBUG_SUPPORT
if(m_debugFlags && m_machine->GetDebugMode() && m_machine->m_isBroken)
{
if(m_machine->m_isBroken(this))
return RUNNING;
}
#endif // GMDEBUG_SUPPORT
// make sure we have a stack frame
GM_ASSERT(m_frame);
GM_ASSERT(GetFunction()->m_type == GM_FUNCTION);
// cache our "registers"
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(m_machine, GetFunction()->m_value.m_ref);
code = (const gmuint8 *) fn->GetByteCode();
if(m_instruction == NULL) instruction = code;
else instruction = m_instruction;
top = GetTop();
base = GetBase();
//
// start byte code execution
//
for(;;)
{
#ifdef GM_CHECK_USER_BREAK_CALLBACK // This may be defined in gmConfig_p.h
// Check external source to break execution with exception eg. Check for CTRL-BREAK
// Endless loop protection could be implemented with this, or in a similar manner.
if( gmMachine::s_userBreakCallback && gmMachine::s_userBreakCallback(this) )
{
GMTHREAD_LOG("User break. Execution halted.");
goto LabelException;
}
#endif //GM_CHECK_USER_BREAK_CALLBACK
switch(*(instruction32++))
{
//
// unary operator
//
case BC_BIT_INV :
case BC_OP_NEG :
case BC_OP_POS :
case BC_OP_NOT :
{
operand = top - 1;
gmOperatorFunction op = OPERATOR(operand->m_type, (gmOperator) instruction32[-1]);
if(op)
{
op(this, operand);
}
else if((fn = CALLOPERATOR(operand->m_type, (gmOperator) instruction32[-1])))
{
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 3);
State res = PushStackFrame(1, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
else
{
GMTHREAD_LOG("unary operator %s undefined for type %s", gmGetOperatorName((gmOperator) instruction32[-1]), m_machine->GetTypeName(operand->m_type));
goto LabelException;
}
break;
}
//
// operator
//
case BC_OP_ADD :
case BC_OP_SUB :
case BC_OP_MUL :
case BC_OP_DIV :
case BC_OP_REM :
case BC_BIT_OR :
case BC_BIT_XOR :
case BC_BIT_AND :
case BC_BIT_SHL :
case BC_BIT_SHR :
case BC_OP_LT :
case BC_OP_GT :
case BC_OP_LTE :
case BC_OP_GTE :
case BC_OP_EQ :
case BC_OP_NEQ :
case BC_GETIND :
{
operand = top - 2;
--top;
register gmType t1, t2;
if( operand->m_type > operand[1].m_type )
{
t1 = operand->m_type;
t2 = operand[1].m_type;
}
else
{
t1 = operand[1].m_type;
t2 = operand->m_type;
}
gmOperator Op = (gmOperator) instruction32[-1];
gmOperatorFunction OpFunc = OPERATOR(t1, Op);
if( !OpFunc )
{
fn = CALLOPERATOR(t1, Op);
if( !fn )
{
OpFunc = OPERATOR(t2, Op);
if( !OpFunc )
fn = CALLOPERATOR(t2, Op);
}
}
if(OpFunc)
{
OpFunc(this, operand);
}
else if(fn)
{
operand[2] = operand[0];
operand[3] = operand[1];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 4);
State res = PushStackFrame(2, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
else
{
GMTHREAD_LOG("operator %s undefined for type %s and %s", gmGetOperatorName(Op), m_machine->GetTypeName(operand->m_type), m_machine->GetTypeName((operand + 1)->m_type));
goto LabelException;
}
break;
}
case BC_SETIND :
{
operand = top - 3;
top -= 3;
gmOperatorFunction op = OPERATOR(operand->m_type, O_SETIND);
if(op)
{
op(this, operand);
}
else if((fn = CALLOPERATOR(operand->m_type, O_SETIND)))
{
operand[4] = operand[2];
operand[3] = operand[1];
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 5);
State res = PushStackFrame(3, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
else
{
GMTHREAD_LOG("setind failed.");
goto LabelException;
}
break;
}
case BC_NOP :
{
break;
}
case BC_LINE :
{
#if GMDEBUG_SUPPORT
if(m_machine->GetDebugMode() && m_machine->m_line)
{
SetTop(top);
m_instruction = instruction;
if(m_machine->m_line(this)) return RUNNING;
}
#endif // GMDEBUG_SUPPORT
break;
}
case BC_GETDOT :
{
operand = top - 1;
gmptr member = OPCODE_PTR(instruction);
top->m_type = GM_STRING;
top->m_value.m_ref = member;
if( operand->m_type != GM_TABLE && *(instruction32-3) == BC_DUP )
{
*operand = m_machine->GetTypeVariable(operand->m_type, *top);
break;
}
gmOperatorFunction op = OPERATOR(operand->m_type, O_GETDOT);
if(op)
{
op(this, operand);
}
else
{
GMTHREAD_LOG("getdot failed.");
goto LabelException;
}
break;
}
case BC_SETDOT :
{
operand = top - 2;
gmptr member = OPCODE_PTR(instruction);
top->m_type = GM_STRING;
top->m_value.m_ref = member;
top -= 2;
gmOperatorFunction op = OPERATOR(operand->m_type, O_SETDOT);
if(op)
{
op(this, operand);
}
else
{
GMTHREAD_LOG("setdot failed.");
goto LabelException;
}
break;
}
case BC_BRA :
{
instruction = code + OPCODE_PTR_NI(instruction);
break;
}
case BC_BRZ :
{
#if GM_BOOL_OP
operand = top - 1;
--top;
if (operand->m_type > GM_USER)
{
// Look for overridden operator.
gmOperatorFunction op = OPERATOR(operand->m_type, O_BOOL);
if (op)
{
op(this, operand);
}
else if ((fn = CALLOPERATOR(operand->m_type, O_BOOL)))
{
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 3);
// Return to the same instruction after making the call but it will be testing the results of the call.
--instruction32;
State res = PushStackFrame(1, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
}
if(operand->m_value.m_int == 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#else // !GM_BOOL_OP
--top;
if(top->m_value.m_int == 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#endif // !GM_BOOL_OP
break;
}
case BC_BRNZ :
{
#if GM_BOOL_OP
operand = top - 1;
--top;
if (operand->m_type > GM_USER)
{
// Look for overridden operator.
gmOperatorFunction op = OPERATOR(operand->m_type, O_BOOL);
if (op)
{
op(this, operand);
}
else if ((fn = CALLOPERATOR(operand->m_type, O_BOOL)))
{
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 3);
// Return to the same instruction after making the call but it will be testing the results of the call.
--instruction32;
State res = PushStackFrame(1, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
}
if(operand->m_value.m_int != 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#else // !GM_BOOL_OP
--top;
if(top->m_value.m_int != 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#endif // !GM_BOOL_OP
break;
}
case BC_BRZK :
{
#if GM_BOOL_OP
operand = top - 1;
if (operand->m_type > GM_USER)
{
// Look for overridden operator.
gmOperatorFunction op = OPERATOR(operand->m_type, O_BOOL);
if (op)
{
op(this, operand);
}
else if ((fn = CALLOPERATOR(operand->m_type, O_BOOL)))
{
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 3);
// Return to the same instruction after making the call but it will be testing the results of the call.
--instruction32;
State res = PushStackFrame(1, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
}
if(operand->m_value.m_int == 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#else // !GM_BOOL_OP
if(top[-1].m_value.m_int == 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#endif // !GM_BOOL_OP
break;
}
case BC_BRNZK :
{
#if GM_BOOL_OP
operand = top - 1;
if (operand->m_type > GM_USER)
{
// Look for overridden operator.
gmOperatorFunction op = OPERATOR(operand->m_type, O_BOOL);
if (op)
{
op(this, operand);
}
else if ((fn = CALLOPERATOR(operand->m_type, O_BOOL)))
{
operand[2] = operand[0];
operand[0] = gmVariable(GM_NULL, 0);
operand[1] = gmVariable(GM_FUNCTION, fn->GetRef());
SetTop(operand + 3);
// Return to the same instruction after making the call but it will be testing the results of the call.
--instruction32;
State res = PushStackFrame(1, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING) break;
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED) { m_machine->Sys_SwitchState(this, KILLED); GM_ASSERT(0); } // operator should not kill a thread
return res;
}
}
if(operand->m_value.m_int != 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#else // !GM_BOOL_OP
if(top[-1].m_value.m_int != 0)
{
instruction = code + OPCODE_PTR_NI(instruction);
}
else instruction += sizeof(gmptr);
#endif // !GM_BOOL_OP
break;
}
case BC_CALL :
{
SetTop(top);
int numParams = (int) OPCODE_PTR(instruction);
State res = PushStackFrame(numParams, &instruction, &code);
top = GetTop();
base = GetBase();
if(res == RUNNING)
{
#if GMDEBUG_SUPPORT
if(m_debugFlags && m_machine->GetDebugMode() && m_machine->m_call)
{
m_instruction = instruction;
if(m_machine->m_call(this)) return RUNNING;
}
#endif // GMDEBUG_SUPPORT
break;
}
if(res == SYS_YIELD) return RUNNING;
if(res == SYS_EXCEPTION) goto LabelException;
if(res == KILLED)
{
if(a_return) *a_return = m_stack[m_top - 1];
m_machine->Sys_SwitchState(this, KILLED);
}
return res;
}
case BC_RET :
{
PUSHNULL;
}
case BC_RETV :
{
SetTop(top);
int res = Sys_PopStackFrame(instruction, code);
top = GetTop();
base = GetBase();
if(res == RUNNING)
{
#if GMDEBUG_SUPPORT
if(m_debugFlags && m_machine->GetDebugMode() && m_machine->m_return)
{
m_instruction = instruction;
if(m_machine->m_return(this)) return RUNNING;
}
#endif // GMDEBUG_SUPPORT
break;
}
if(res == KILLED)
{
if(a_return) *a_return = *(top - 1);
m_machine->Sys_SwitchState(this, KILLED);
return KILLED;
}
if(res == SYS_EXCEPTION) goto LabelException;
break;
}
case BC_FOREACH :
{
gmuint32 localvalue = OPCODE_PTR(instruction);
gmuint32 localkey = localvalue >> 16;
localvalue &= 0xffff;
// iterator is at tos-1, table is at tos -2, push int 1 if continuing loop. write key and value into localkey and localvalue
if(top[-2].m_type != GM_TABLE)
{
GMTHREAD_LOG("foreach expression is not table type");
goto LabelException;
}
GM_ASSERT(top[-1].m_type == GM_INT);
gmTableIterator it = (gmTableIterator) top[-1].m_value.m_int;
gmTableObject * table = (gmTableObject *) GM_MOBJECT(m_machine, top[-2].m_value.m_ref);
gmTableNode * node = table->GetNext(it);
top[-1].m_value.m_int = it;
if(node)
{
base[localkey] = node->m_key;
base[localvalue] = node->m_value;
top->m_type = GM_INT; top->m_value.m_int = 1;
}
else
{
top->m_type = GM_INT; top->m_value.m_int = 0;
}
++top;
break;
}
case BC_POP :
{
--top;
break;
}
case BC_POP2 :
{
top -= 2;
break;
}
case BC_DUP :
{
top[0] = top[-1];
++top;
break;
}
case BC_DUP2 :
{
top[0] = top[-2];
top[1] = top[-1];
top += 2;
break;
}
case BC_SWAP :
{
top[0] = top[-1];
top[-1] = top[-2];
top[-2] = top[0];
break;
}
case BC_PUSHNULL :
{
PUSHNULL;
break;
}
case BC_PUSHINT :
{
top->m_type = GM_INT;
top->m_value.m_int = OPCODE_PTR(instruction);
++top;
break;
}
case BC_PUSHINT0 :
{
top->m_type = GM_INT;
top->m_value.m_int = 0;
++top;
break;
}
case BC_PUSHINT1 :
{
top->m_type = GM_INT;
top->m_value.m_int = 1;
++top;
break;
}
case BC_PUSHFP :
{
top->m_type = GM_FLOAT;
top->m_value.m_float = OPCODE_FLOAT(instruction);
++top;
break;
}
case BC_PUSHSTR :
{
top->m_type = GM_STRING;
top->m_value.m_ref = OPCODE_PTR(instruction);
++top;
break;
}
case BC_PUSHTBL :
{
SetTop(top);
top->m_type = GM_TABLE;
top->m_value.m_ref = m_machine->AllocTableObject()->GetRef();
++top;
break;
}
case BC_PUSHFN :
{
top->m_type = GM_FUNCTION;
top->m_value.m_ref = OPCODE_PTR(instruction);
++top;
break;
}
case BC_PUSHTHIS :
{
*top = *GetThis();
++top;
break;
}
case BC_GETLOCAL :
{
gmuint32 offset = OPCODE_PTR(instruction);
*(top++) = base[offset];
break;
}
case BC_SETLOCAL :
{
gmuint32 offset = OPCODE_PTR(instruction);
base[offset] = *(--top);
break;
}
case BC_GETGLOBAL :
{
top->m_type = GM_STRING;
top->m_value.m_ref = OPCODE_PTR(instruction);
*top = m_machine->GetGlobals()->Get(*top); ++top;
break;
}
case BC_SETGLOBAL :
{
top->m_type = GM_STRING;
top->m_value.m_ref = OPCODE_PTR(instruction);
m_machine->GetGlobals()->Set(m_machine, *top, *(top-1)); --top;
break;
}
case BC_GETTHIS :
{
gmptr member = OPCODE_PTR(instruction);
const gmVariable * thisVar = GetThis();
*top = *thisVar;
top[1].m_type = GM_STRING;
top[1].m_value.m_ref = member;
gmOperatorFunction op = OPERATOR(thisVar->m_type, O_GETDOT);
if(op)
{
op(this, top);
if(top->m_type) { ++top; break; }
}
if(thisVar->m_type == GM_NULL)
{
GMTHREAD_LOG("getthis failed. this is null");
goto LabelException;
}
*top = m_machine->GetTypeVariable(thisVar->m_type, top[1]);
++top;
break;
}
case BC_SETTHIS :
{
gmptr member = OPCODE_PTR(instruction);
const gmVariable * thisVar = GetThis();
operand = top - 1;
*top = *operand;
*operand = *thisVar;
top[1].m_type = GM_STRING;
top[1].m_value.m_ref = member;
--top;
gmOperatorFunction op = OPERATOR(thisVar->m_type, O_SETDOT);
if(op)
{
op(this, operand);
}
else
{
GMTHREAD_LOG("setthis failed.");
goto LabelException;
}
break;
}
default :
{
break;
}
}
}
LabelException:
//
// exception handler
//
m_instruction = instruction;
// spit out error info
LogLineFile();
LogCallStack();
// call machine exception handler
if(gmMachine::s_machineCallback)
{
if(gmMachine::s_machineCallback(m_machine, MC_THREAD_EXCEPTION, this))
{
#if GMDEBUG_SUPPORT
// if we are being debugged, put this thread into a limbo state, waiting for delete.
if(m_machine->GetDebugMode() && m_machine->m_debugUser)
{
m_machine->Sys_SwitchState(this, EXCEPTION);
return EXCEPTION;
}
#endif
}
}
// kill the thread
m_machine->Sys_SwitchState(this, KILLED);
return KILLED;
}
void gmThread::Sys_Reset(int a_id)
{
m_machine->Sys_RemoveBlocks(this);
m_machine->Sys_RemoveSignals(this);
gmStackFrame * frame;
while(m_frame)
{
frame = m_frame->m_prev;
m_machine->Sys_FreeStackFrame(m_frame);
m_frame = frame;
}
m_top = 0;
m_base = 0;
m_instruction = NULL;
m_timeStamp = 0;
m_startTime = 0;
m_id = a_id;
m_numParameters = 0;
m_user = 0;
}
gmThread::State gmThread::PushStackFrame(int a_numParameters, const gmuint8 ** a_ip, const gmuint8 ** a_cp)
{
// calculate new stack base
int base = m_top - a_numParameters;
if( base == 2 ) // When initial thread function is ready, signal thread creation
{
// This may not be the best place to signal, but we at least want a valid 'this'
m_base = base; // Init so some thread queries work
m_machine->Sys_SignalCreateThread(this);
}
gmVariable * fnVar = &m_stack[base - 1];
if(fnVar->m_type != GM_FUNCTION)
{
m_machine->GetLog().LogEntry("attempt to call non function type");
return SYS_EXCEPTION;
}
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(m_machine, fnVar->m_value.m_ref);
if(fn->m_cFunction)
{
//
// Its a native function call, call it now as we cannot stack wind natives. this avoids
// pushing a gmStackFrame.
//
m_numParameters = (short) a_numParameters;
int lastBase = m_base;
int lastTop = m_top;
m_base = base;
int result = fn->m_cFunction(this);
// handle state
if(result == GM_SYS_STATE)
{
// this is special case, a bit messy.
return PushStackFrame(a_numParameters - GM_STATE_NUM_PARAMS, a_ip, a_cp);
}
// NOTE: It is not currently safe for a C binding to kill this thread.
// Since we cant unwind mixed script and native functions anyway,
// perhaps the safest thing would be for ALWAYS delay killed threads
// from deletion.
// push a null if the function did not return anything
if(lastTop == m_top)
{
m_stack[m_base - 2] = gmVariable(GM_NULL, 0);
}
else
{
m_stack[m_base - 2] = m_stack[m_top - 1];
}
// Restore the stack
m_top = m_base - 1;
m_base = lastBase;
// check the call result
if(result != GM_OK)
{
const gmuint8 * returnAddress = (a_ip) ? *a_ip : NULL;
if(result == GM_SYS_YIELD)
{
m_machine->Sys_RemoveSignals(this);
m_instruction = returnAddress;
return SYS_YIELD;
}
else if(result == GM_SYS_BLOCK)
{
m_instruction = returnAddress;
m_machine->Sys_SwitchState(this, BLOCKED);
return BLOCKED;
}
else if(result == GM_SYS_SLEEP)
{
m_instruction = returnAddress;
m_machine->Sys_SwitchState(this, SLEEPING);
return SLEEPING;
}
else if(result == GM_SYS_KILL)
{
return KILLED;
}
return SYS_EXCEPTION;
}
if(!m_frame) // C called C function, no stack frame, so signal killed.
{
return KILLED;
}
// return result
return RUNNING;
}
//
// Its a script function call, push a stack frame
//
int clearSize = fn->GetNumParamsLocals() - a_numParameters;
if(!Touch(clearSize + fn->GetMaxStackSize()))
{
m_machine->GetLog().LogEntry("stack overflow");
return SYS_EXCEPTION;
}
// zero missing params and locals.
if(a_numParameters <= fn->GetNumParams())
{
memset(GetTop(), 0, sizeof(gmVariable) * clearSize);
}
else
{
memset(&m_stack[base + fn->GetNumParams()], 0, sizeof(gmVariable) * fn->GetNumLocals());
}
// push a new stack frame
gmStackFrame * frame = m_machine->Sys_AllocStackFrame();
frame->m_prev = m_frame;
m_frame = frame;
// cache new frame variables
m_frame->m_returnBase = m_base;
if(a_ip)
{
m_frame->m_returnAddress = *a_ip;
*a_ip = (const gmuint8 *) fn->GetByteCode();
*a_cp = *a_ip;
}
else
{
m_frame->m_returnAddress = NULL;
}
m_base = base;
m_top = base + fn->GetNumParamsLocals();
return RUNNING;
}
gmThread::State gmThread::Sys_PopStackFrame(const gmuint8 * &a_ip, const gmuint8 * &a_cp)
{
if(m_frame == NULL)
{
m_machine->GetLog().LogEntry("stack underflow");
return SYS_EXCEPTION;
}
gmStackFrame * frame = m_frame->m_prev;
if( frame == NULL ) // Final frame, we will exit now
{
return KILLED; // Don't clean up stack, let the machine reset it as state changes to killed (so Exit callback can examine valid thread contents)
}
a_ip = m_frame->m_returnAddress;
// Copy old tos to new tos
m_stack[m_base - 2] = m_stack[m_top - 1];
m_top = m_base - 1;
m_base = m_frame->m_returnBase;
m_machine->Sys_FreeStackFrame(m_frame);
m_frame = frame;
// Update instruction and code pointers
GM_ASSERT(GetFunction()->m_type == GM_FUNCTION);
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(m_machine, GetFunction()->m_value.m_ref);
a_cp = (const gmuint8 *) fn->GetByteCode();
return RUNNING;
}
void gmThread::LogLineFile()
{
// spit out the source and line info for the exception.
if(m_base >= 2 && GetFunction()->m_type == GM_FUNCTION)
{
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(m_machine, GetFunction()->m_value.m_ref);
if(fn)
{
int line = fn->GetLine(m_instruction);
gmuint32 id = fn->GetSourceId();
const char * source, * filename;
if(m_machine->GetSourceCode(id, source, filename))
{
char buffer[80];
gmGetLineFromString(source, line, buffer, 80);
m_machine->GetLog().LogEntry(GM_NL"%s(%d) : %s", filename, line, buffer);
}
else
{
m_machine->GetLog().LogEntry(GM_NL"unknown(%d) : ", line);
}
}
}
}
bool gmThread::Touch(int a_extra)
{
// Grow stack if necessary. NOTE: Use better growth metric if needed.
bool reAlloc = false;
while((m_top + a_extra + GMTHREAD_SLACKSPACE) >= m_size)
{
if(sizeof(gmVariable) * m_size > GMTHREAD_MAXBYTESIZE) return false;
m_size *= 2;
reAlloc = true;
}
if(reAlloc)
{
gmVariable * stack = new gmVariable[m_size];
//memset(stack, 0, sizeof(gmVariable) * m_size);
memcpy(stack, m_stack, m_top * sizeof(gmVariable));
if(m_stack)
delete[] m_stack;
m_stack = stack;
}
return true;
}
void gmThread::LogCallStack()
{
m_machine->GetLog().LogEntry(GM_NL"callstack..");
gmStackFrame * frame = m_frame;
int base = m_base;
const gmuint8 * ip = m_instruction;
while(frame)
{
// get the function object
gmVariable * fnVar = &m_stack[base - 1];
if(fnVar->m_type == GM_FUNCTION)
{
gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(m_machine, fnVar->m_value.m_ref);
m_machine->GetLog().LogEntry("%3d: %s", fn->GetLine(ip), fn->GetDebugName());
}
base = frame->m_returnBase;
ip = frame->m_returnAddress;
frame = frame->m_prev;
}
m_machine->GetLog().LogEntry("");
}
|
[
"doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06"
] |
[
[
[
1,
1211
]
]
] |
782ee11133ccf5696b6140d4540fd68d70d1d66d
|
5506729a4934330023f745c3c5497619bddbae1d
|
/vst2.x/tuio/syn.cpp
|
cffe91b2e519a0a464331ffa64bbab7f9a362d00
|
[] |
no_license
|
berak/vst2.0
|
9e6d1d7246567f367d8ba36cf6f76422f010739e
|
9d8f51ad3233b9375f7768be528525c15a2ba7a1
|
refs/heads/master
| 2020-03-27T05:42:19.762167 | 2011-02-18T13:35:09 | 2011-02-18T13:35:09 | 1,918,997 | 4 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 14,742 |
cpp
|
#include <map>
#include <vector>
#include <stdio.h>
#include <math.h>
#include <windows.h> // FOR MIDI ??? !!!*****
#include <time.h> // for random
#include "syn.h"
#include "source/xmlParser.h" // xml
#include "Profile.h"
#define SYNRELEASE(x) if(x)x->release(); x=0;
float random( float lo, float hi )
{
static time_t t_init=0;
if ( ! t_init ) srand( (unsigned int)time(&t_init) );
float fval = (float)(rand() & RAND_MAX) / (float)RAND_MAX;
return (lo + (fval * (hi - lo)));
}
char __b[256];
char*str( int i ) { sprintf(__b,"%i",i);return __b; }
char*str( float f ) { sprintf(__b,"%.3f",f);return __b; }
void num( const char*s, int &i ) { if(s) sscanf(s,"%i",&i); }
void num( const char*s, float &f ) { if(s) sscanf(s,"%f",&f); }
int error(const char*a,const char*b="",int e=0 )
{
printf( "Error:%s%s\n", a,b );
return e;
}
std::vector < Item * > all;
#define $$$ printf("%4d %-8x %s\n", __LINE__, this,__FUNCTION__ );
#define $$(x) printf("%4d %-8x %s %s\n", __LINE__, this,__FUNCTION__, x );
static int _nItems = 0;
int _nIt()
{
return _nItems;
}
inline float clamp(float v, float lo, float hi )
{
if ( v<lo ) return lo;
if ( v>hi ) return hi;
return v;
}
float Item::distance( const Item * it )
{
float dx = x - it->x;
float dy = y - it->y;
float ds = dx*dx + dy*dy;
return sqrt(ds);
}
bool Item::autoDisconnect( float radius )
{
bool dirty = false;
for ( int i=0; i<ncon; i++ )
{
if ( ! con[i] )
continue;
if ( radius )
{
float d = distance(con[i]);
if ( d < radius )
continue;
}
con[i]->onDisconnect( this );
SYNRELEASE(con[i]);
dirty=true;
}
return dirty;
}
bool Item::onDisconnect( Item * downstream )
{
return true;
}
bool Item::onConnect( Item * downstream )
{
return true;
}
bool Item::connect( Item * upstream )
{
if ( ! upstream )
{
return 0;
}
for ( int i=0; i<ncon; i++ )
{
if ( hasType( i , upstream->type ) )
{
if ( con[i] )
continue;
if ( upstream->onConnect( this ) )
{
con[i] = upstream;
con[i]->addref();
return 1;
}
}
}
return 0;
}
bool Item::disconnect( Item * upstream )
{
if ( ! upstream )
{
return 0;
}
for ( int i=0; i<ncon; i++ )
{
if ( con[i] == upstream )
{
con[i]->onDisconnect( this );
SYNRELEASE(con[i]);
return 1;
}
}
return 0;
}
const char * Item::typeName()
{
return "Item";
}
//
bool Item::process( Item::Processor pro, Item *parent, const void * data, bool pre )
{
//printf(__FUNCTION__ " id(%d)\ttype(%d)\n",id,type );
bool r = 1;
if ( pre )
r = pro(this, parent, data);
if ( ! r )
return 0;
for ( int i=0; i<ncon; i++ )
{
if ( ! con[i] )
continue;
r = con[i]->process(pro,this,data,pre);
if ( ! r )
break;
}
if ( ! pre )
r = pro(this, parent, data);
return r;
}
Item::Item( int bufSize, int type, int nc, int i )
: v( new float[bufSize] )
, type(type)
, bSize(bufSize)
, x(random(0.0,1.0))
, y(random(0.0,1.0))
, a(0)
, A(1.0)
, ncon(nc)
, lostCycles(0)
, tex(0)
, _refs(1)
{
static int iiiihhh = 0;
if ( i==-1 )
id = iiiihhh ++;
else id = i;
memset(con,0,MaxConnections*sizeof(Item*));
memset(conTypes,0,MaxConnections*sizeof(unsigned int));
//memset(conMult,1.0f,MaxConnections*sizeof(float));
for ( int i=0; i<MaxConnections; i++ )
conMult[i] = 1.0f;
for ( int i=0; i<bSize; i++ )
v[i] = 0.0f;
all.push_back( this );
_nItems ++;
}
Item::~Item()
{
delete [] v ;
// unsubscribe the list:
std::vector<Item*>::iterator it=all.begin();
for ( ; it!=all.end(); it++ )
{
Item * c = *it;
if ( c == this )
{
all.erase(it);
break;
}
}
// clear pins:
autoDisconnect(0);
// search for downstream con
for ( it=all.begin(); it!=all.end(); it++ )
{
Item * c = *it;
if ( c->disconnect(this) )
break;
}
_nItems --;
}
int Item::release()
{
_refs--;
if ( _refs == 0 )
{
printf( "-@@ %s(%i)\n", typeName(), id );
delete this;
return 0;
}
return _refs;
}
int Item::addref()
{
return ++_refs;
}
struct Controller
: Item
{
Controller( int t=Item::IT_VOLUME )
: Item(0,t,0)
{
}
virtual const char * typeName()
{
return "Controller";
}
};
struct Sin
: Item
{
float _val;
Sin()
: Item(0,IT_SIN,0)
, _val(0)
{
}
virtual const char * typeName()
{
return "Sinus";
}
virtual bool updateFrame( float t, int f)
{
_val = 0.5f + 0.5f * sin( t * (a) );
return 1;
}
virtual float value()
{
return _val;
}
};
//struct Sound
// : Item
//{
// float frq,vol;
// Sound()
// : Item(SizeAudioBuffer,Item::IT_SOUND,2)
// , frq(100)
// , vol(0.5)
// {
// setType( 0, IT_VOLUME );
// setType( 1, IT_FREQUENCY );
// setType( 1, IT_SIN );
// }
//
// virtual const char * typeName()
// {
// return "Sound";
// }
//
// virtual bool updateFrame( float t, int f)
// {
// frq = ( 1.0f + a * 100.0f );
//
// if ( con[0] ) vol = con[0]->value();
// float fmul = 1.0f;
// if ( con[1] ) fmul = con[1]->value();
//
// for ( int i=0; i<bSize; i++ )
// {
// v[i] = clamp( vol * sin((i % int(frq) ) / (frq*fmul)), -1, 1 );
// }
// return 1;
// }
//};
//
struct Amplifier
: Item
{
float vol;
bool needsClear;
Amplifier()
: Item(SizeAudioBuffer,Item::IT_AMP,2)
, vol(0.5)
, needsClear(0)
{
//setType( 0, IT_SOUND );
//setType( 0, IT_FILTER );
setType( 1, IT_VOLUME );
}
virtual const char * typeName()
{
return "Amplifier";
}
bool processAudio( float ** buffer, int nBuffer, int nElems )
{
if ( con[0] )
{
con[0]->processAudio( buffer, nBuffer, nElems );
for ( int b=0; b<nBuffer; b++ )
{
float *chan = buffer[b];
for ( int i=0; i<nElems; i++ )
{
*chan++ *= vol;
}
}
}
return 1;
}
virtual bool updateFrame( float t, int f)
{
PROFILE;
vol = a;
if ( con[1] )
{
vol = clamp( vol * con[1]->value(), 0, 1 );
}
return 1;
}
};
//struct Filter
// : Item
//{
//
// Filter()
// : Item(SizeAudioBuffer,Item::IT_FILTER,3)
// {
// setType( 0, IT_SOUND );
// setType( 0, IT_FILTER );
// setType( 1, IT_FREQUENCY );
// setType( 2, IT_QUALITY );
// }
//
// virtual const char * typeName()
// {
// return "Filter";
// }
//
// virtual bool updateFrame( float t, int f)
// {
// if ( ! con[0] ) return 0;
// //if ( ! con[0]->bSize==bSize ) return 0;
// //for ( int i=0; i<bSize; i++ )
// //{
// // v[i] = con[0]->v[i];
// //}
// return 1;
// }
//};
struct Cursor
: Item
{
Cursor()
: Item(1,Item::IT_CURSOR,0)
{
A = a = 1.0f;
}
virtual const char * typeName()
{
return "Cursor";
}
virtual bool onDisconnect( Item * downstream )
{
A = a = 0;
return true;
}
virtual bool onConnect( Item * downstream )
{
A = a = 1;
return true;
}
};
namespace Midi
{
unsigned int _pitch[16];
unsigned char _ctl[16][128];
unsigned char _note[16][128];
// Callback * _call = 0;
unsigned int _e_cmd = 0; //! cached event for running status
unsigned int _e_chn = 0; //! cached event for running status
unsigned int _e_b0 = 0; //! cached event for running status
unsigned int _e_b1 = 0; //! cached event for running status
// event callback:
void CALLBACK _midiInProc(
HMIDIIN hMidiIn,
unsigned int wMsg,
DWORD dwInstance,
DWORD dwParam1,
DWORD dwParam2
)
{
// get the bytes from lparam into array ;-)
BYTE in_buf[4];
memcpy( in_buf, &dwParam1, 4 );
if ( in_buf[0] < 128 )
{
// data<127, runningstatus
// 2-byte message ( running status on):
_e_b0 = in_buf[0]; // 1st & 2nd byte
_e_b1 = in_buf[1];
}
else
{
// 3-byte message ( running status off ):
_e_chn = (in_buf[0] & 0x0f); //channels[0-15] !!!
_e_cmd = (in_buf[0] & 0xf0);
_e_b0 = in_buf[1]; // 2nd & 3rd byte
_e_b1 = in_buf[2];
}
switch( _e_cmd )
{
case 0x90://note_on
_note[_e_chn][_e_b0] = _e_b1;
break;
case 0xb0://ctl
_ctl[_e_chn][_e_b0] = _e_b1;
break;
case 0xe0://pitch ///PPP fixme!
_pitch[_e_chn] = (_e_b0<<7) | _e_b1; //float!!!!vl;
break;
}
//if ( _call )
//{
// _call->onMidiEvent( _e_cmd, _e_chn, _e_b0, _e_b1 );
//}
}
struct CDevice
{
HMIDIIN _midiIn;
char _err[1024];
CDevice()
{
// _call = 0;
_clear();
}
virtual ~CDevice()
{
_close();
}
bool _error( MMRESULT res )
{
if ( ! res )
return 1;
midiInGetErrorText( res, _err, 1024 );
printf( "Midi Error: %s\n", _err );
return 0; //MessageBox( NULL, _err, "midi in", MB_OK );
}
bool _clear()
{
_midiIn = 0;
_e_chn = 0;
_e_cmd = 0;
_e_b0 = 0;
_e_b1 = 0;
_err[0] = 0;
memset( _ctl, 0, 128*16 );
memset( _note, 0, 128*16 );
memset( _pitch, 0, 16*sizeof(unsigned int) );
return 1;
}
bool _open( unsigned int _deviceID )
{
if ( _midiIn )
{
return true; // shared
}
MMRESULT res = 0;
DWORD_PTR hinst = (DWORD_PTR)::GetModuleHandle(NULL);
res = midiInOpen( &_midiIn, _deviceID, (DWORD_PTR)_midiInProc, hinst, CALLBACK_FUNCTION );
if ( res ) return _error( res );
res = midiInStart( _midiIn );
return _error( res ) ;
}
bool _close()
{
MMRESULT res;
if ( ! _midiIn ) return 0;
res = midiInStop( _midiIn );
if ( res ) return _error( res );
res = midiInClose( _midiIn );
if ( res ) return _error( res );
_midiIn = 0;
// _call = 0;
return 1;
}
bool _reset(unsigned int _deviceID)
{
MMRESULT res;
if ( ! _midiIn ) return 0;
res = midiInStop( _midiIn );
if ( res ) return _error( res );
res = midiInReset( _midiIn );
if ( res ) return _error( res );
res = midiInStart( _midiIn );
return _error( res );
}
bool _getLastError(char * buf)
{
if ( _err[0] == 0 ) return false;
strcpy( buf, _err );
_err[0] = 0;
return 1;
}
virtual unsigned int init( unsigned int n )
{
_clear();
unsigned int r = _open(n);
if ( ! r )
{
printf(__FUNCTION__ " : no device for id %i.\n",n);
for ( unsigned int i=0; i<8; i++ )
{
if ( i==n ) continue;
r = _open( i );
if ( r )
{
printf(__FUNCTION__ " : created device %i instead.\n",i);
return r;
}
}
return 0;
}
printf(__FUNCTION__ " : created device %i .\n",r);
return r;
}
//virtual unsigned int setCallback(Callback * cb)
//{
// _call = cb;
// return 1;
//}
virtual unsigned int getState( unsigned int cmd, unsigned int channel, unsigned int b0 )
{
switch( cmd )
{
case 0x90:
return _note[channel][b0];
case 0xb0:
return _ctl[channel][b0];
case 0xe0:
return _pitch[channel];
}
return 0;
}
}; // CDevice
} // Midi
struct MidiKeyboard
: Item
, Midi::CDevice
{
MidiKeyboard()
: Item(3,1,0)
{
Midi::CDevice::init(1);
}
virtual const char * typeName()
{
return "MidiKeyboard";
}
virtual bool updateFrame(float t, int f)
{
v[0] = float(Midi::_e_cmd | Midi::_e_chn) / 255.0f;
v[1] = float(Midi::_e_b0) / 127.0f;
v[2] = float(Midi::_e_b1) / 127.0f;
A = a = 1.0f;
return 1;
}
virtual float value()
{
int i = 1;
if ( Midi::_e_cmd == 0xb0 )
i = 2;
A *= 0.9f;
return float( v[i] );
}
};
struct MidiSequencer
: Item
{
float s[256][3];
int pos;
int len;
int speed;
MidiSequencer()
: Item(3,Item::IT_MIDI_SEQ,2)
, pos(0)
, len(8)
, speed(600)
{
for ( int i=0; i<len; i++ )
{
s[i][0] = (float(0x90) / 255.0f);
s[i][1] = random(0.1f,0.9f);
s[i][2] = random(0.3f,0.7f);
}
}
virtual const char * typeName()
{
return "Sequencer";
}
virtual bool updateFrame(float t, int f)
{
int MaxSpeed = 1000;
speed = int(MaxSpeed*a);
if ( speed > MaxSpeed )
speed = MaxSpeed;
pos = int(f/(MaxSpeed/speed)) % len;
if ( con[0] )
{
// len
len = int(127.0f*con[0]->value());
}
//if ( con[1] )
//{
// // pos
// speed = int(127.0f*con[1]->value());
//}
if ( con[1] )
{
// note
//s[pos][0] = (float(0x90) / 255.0f);
s[pos][1] = int(127.0f*con[1]->value());
}
v[0] = s[pos][0];
v[1] = s[pos][1];
v[2] = s[pos][2];
A = 1.0f;
return 1;
}
virtual float value()
{
A *= 0.9f;
return float( v[1] );
}
};
//
// this is more like a midi 'state' ..
//
struct MidiEvent
: Item
{
int mapId;
float vel;
MidiEvent( int fid, int b0, int b2=0, int m=1 )
: Item(3,fid,0)
, mapId(m)
{
v[0] = b0 / 255.0f;
v[2] = b2 / 127.0f;
vel = v[2];
}
virtual const char * typeName()
{
if ( type == Item::IT_MIDI_NOTE ) return "Note";
if ( type == Item::IT_MIDI_PROG ) return "Prog";
return "Mi??";
}
virtual bool updateFrame(float t, int f)
{
//v[2] = A;//( A != 0.0f ? vel : 0 );
v[mapId] = a;
return 1;
}
virtual float value()
{
return float( v[mapId] );
}
};
// 'global' interface:
int clearItems()
{
size_t i=0;
while ( ! all.empty() )
{
Item * last = all.back();
if( last ) last->release();
else break;
i ++;
}
return i;
}
int numItems()
{
return all.size();
}
Item * getItem( int index )
{
return all.at(index);
}
Item * createSynItem( int type )
{
switch( type )
{
case Item::IT_MIDI:
{
return new MidiKeyboard;
}
//case Item::IT_SYN:
//{
// return new Syn;
//}
case -1:
case Item::IT_CURSOR:
{
return new Cursor;
}
case Item::IT_AMP:
{
return new Amplifier;
}
case Item::IT_MIDI_SEQ :
{
return new MidiSequencer();
}
case Item::IT_MIDI_NOTE :
{
return new MidiEvent( type, 0x90, 0x7f );
}
case Item::IT_MIDI_PROG:
{
return new MidiEvent( type, 0xc0, 0 );
}
case Item::IT_SIN:
{
return new Sin;
}
default:
//case Item::IT_FREQUENCY:
//case Item::IT_QUALITY:
//case Item::IT_VOLUME:
{
if ( type > 6 && type < 32 )
return new Controller(type);
}
}
//printf("Error: " __FUNCTION__ "stumbled over type %d\n", type);
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
856
]
]
] |
c0a596854ee9f8fd8d87bb4e113ed8fe4568d5d8
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.1/bctestocr/src/bctestocrdocument.cpp
|
10b19740c7e93a83b114c41d32cd62ae0c98efe5
|
[] |
no_license
|
SymbianSource/oss.FCL.sftools.ana.compatanamdw
|
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
|
1169475bbf82ebb763de36686d144336fcf9d93b
|
refs/heads/master
| 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,108 |
cpp
|
/*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Implements test bc for ocr document.
*
*/
// INCLUDE FILES
#include "bctestocrdocument.h"
#include "bctestocrappui.h"
// ================= MEMBER FUNCTIONS ========================================
// ---------------------------------------------------------------------------
// CBCTestOCRDocument* CBCTestOCRDocument::NewL( CEikApplication& )
// Symbian OS two-phased constructor.
// ---------------------------------------------------------------------------
//
CBCTestOCRDocument* CBCTestOCRDocument::NewL( CEikApplication& aApp )
{
CBCTestOCRDocument* self = new( ELeave ) CBCTestOCRDocument( aApp );
return self;
}
// ---------------------------------------------------------------------------
// CBCTestOCRDocument::~CBCTestOCRDocument()
// Destructor.
// ---------------------------------------------------------------------------
//
CBCTestOCRDocument::~CBCTestOCRDocument()
{
}
// ---------------------------------------------------------------------------
// CBCTestOCRDocument::CBCTestOCRDocument( CEikApplication& )
// Overload constructor.
// ---------------------------------------------------------------------------
//
CBCTestOCRDocument::CBCTestOCRDocument( CEikApplication& aApp )
: CEikDocument( aApp )
{
}
// ---------------------------------------------------------------------------
// CEikAppUi* CBCTestOCRDocument::CreateAppUiL()
// Constructs CBCTestVolumeAppUi.
// ---------------------------------------------------------------------------
//
CEikAppUi* CBCTestOCRDocument::CreateAppUiL()
{
return new( ELeave ) CBCTestOCRAppUi;
}
|
[
"none@none"
] |
[
[
[
1,
63
]
]
] |
12ab0cafad773b946b68c597fa5f9eb7a496214e
|
96e96a73920734376fd5c90eb8979509a2da25c0
|
/C3DE/Application.h
|
eb895cdf78f985f48acd9806b6e7638c1f1ca381
|
[] |
no_license
|
lianlab/c3de
|
9be416cfbf44f106e2393f60a32c1bcd22aa852d
|
a2a6625549552806562901a9fdc083c2cacc19de
|
refs/heads/master
| 2020-04-29T18:07:16.973449 | 2009-11-15T10:49:36 | 2009-11-15T10:49:36 | 32,124,547 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 772 |
h
|
#ifndef APPLICATION_H
#define APPLICATION_H
#include "Renderer.h"
#include "RendererListener.h"
#include "PerformanceCounter.h"
#include "Input.h"
#include "ResourceManager.h"
class Application : public RendererListener
{
public:
Application();
virtual ~Application();
bool Init();
bool Update(int deltaTime);
bool Render();
bool Cleanup();
virtual bool Quit() = 0;
virtual void OnLostDevice() = 0;
virtual void OnResetDevice() = 0;
virtual Renderer *GetRenderer() = 0;
protected:
Renderer *m_renderer;
bool m_windowed;
int m_width;
int m_height;
PerformanceCounter *m_performanceCounter;
Input *m_input;
private:
virtual void SetupRenderer() = 0;
virtual void SetupWindow() = 0;
};
#endif
|
[
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
] |
[
[
[
1,
45
]
]
] |
1e042cca02e4d22a9f20d538d4220e520833a337
|
50f94444677eb6363f2965bc2a29c09f8da7e20d
|
/Src/EmptyProject/StateManager.cpp
|
a058291942036dcf500dd8817ed9a939a16aa5f0
|
[] |
no_license
|
gasbank/poolg
|
efd426db847150536eaa176d17dcddcf35e74e5d
|
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
|
refs/heads/master
| 2020-04-10T11:56:52.033568 | 2010-11-04T19:31:00 | 2010-11-04T19:31:00 | 1,051,621 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,855 |
cpp
|
#include "EmptyProjectPCH.h"
#include "StateManager.h"
#include "State.h"
StateManager::StateManager(void)
{
}
StateManager::~StateManager( void )
{
}
void StateManager::setNextStateAsPrevState()
{
m_nextState = m_prevStates;
}
State* StateManager::getCurState() const
{
return m_curStates;
}
void StateManager::transit( double dCurrentTime )
{
if (m_nextState != 0)
{
if (m_curStates != 0)
m_curStates->leave();
m_prevStates = m_curStates;
m_curStates = m_nextState;
m_nextState = 0;
m_curStates->enter( dCurrentTime );
}
}
State* StateManager::getState( GameState gs ) const
{
StateMap::const_iterator cit = m_states.find( gs );
if ( cit == m_states.end() )
return 0;
else
return cit->second;
}
void StateManager::release()
{
StateMap::iterator it = m_states.begin();
for ( ; it != m_states.end(); ++it )
{
EP_SAFE_release( it->second );
}
}
void StateManager::setNextState(GameState state)
{
if ( m_states.find( state ) != m_states.end() )
{
if ( m_curStates != m_states[state] )
m_nextState = m_states[state];
}
else
{
throw std::runtime_error( "Invalid GameState enum" );
}
}
void StateManager::setNextStateForced( GameState state )
{
if ( m_states.find( state ) != m_states.end() )
m_nextState = m_states[state];
else
throw std::runtime_error( "Invalid GameState enum" );
}
GameState StateManager::curStateEnum()
{
StateMap::iterator it = m_states.begin();
for ( ; it != m_states.end(); ++it )
{
if ( it->second == m_curStates )
return it->first;
}
return NULL_STATE;
}
GameState StateManager::prevStateEnum()
{
StateMap::iterator it = m_states.begin();
for ( ; it != m_states.end(); ++it )
{
if ( it->second == m_prevStates )
return it->first;
}
return NULL_STATE;
}
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
8
],
[
10,
21
],
[
23,
24
],
[
29,
29
],
[
97,
97
]
],
[
[
9,
9
],
[
22,
22
],
[
25,
28
],
[
30,
96
]
]
] |
f108ff6445d6ead317f98a562847a1f76fdc5566
|
5da9d428805218901d7c039049d7e13a1a2b1c4c
|
/Vivian/libFade/GDIDraw.h
|
788be1b217db9dbe976cfe70946799333ef918e7
|
[] |
no_license
|
SakuraSinojun/vivianmage
|
840be972f14e17bb76241ba833318c13cf2b00a4
|
7a82ee5c5f37d98b86e8d917d9bb20c96a2d6c7f
|
refs/heads/master
| 2021-01-22T20:44:33.191391 | 2010-12-11T15:26:15 | 2010-12-11T15:26:15 | 32,322,907 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 913 |
h
|
//////////////////////////////////////////////////////////////////
//
// FileName : GDIDraw.h
// Author : SakuraSinojun
// Description : this is the class to use GDISurface.
//
// Version : 1.0.0.1
// Date : 2009.9.6
//
// Copyright(c): 2009-2010 Sakura
//
//////////////////////////////////////////////////////////////////
#pragma once
#include "GDISurface.h"
#include "..\stdafx.h"
#include "Layer.h"
class CGDIDraw
{
public:
CGDIDraw(void);
~CGDIDraw(void);
bool Create(HWND hWnd,int width,int height);
CLayer * Add(CGDISurface *s);
void Remove(CGDISurface *s);
bool Draw(); //绘图。
HRESULT Flip(); //翻页。
private:
HWND m_hWnd;
HDC m_hdc; //最终绘图目标
HDC back; //背景绘图页
CSize size; //绘图页大小
CLayer * first; //绘图页链表头指针
HBITMAP m_bitmap; //背景绘图画布
};
|
[
"SakuraSinojun@c9cc3ed0-94a9-11de-b6d4-8762f465f3f9"
] |
[
[
[
1,
48
]
]
] |
9f98cdc633fdb1cd1a02f97f05227d78de282a3f
|
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
|
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Exception.h
|
4ad0877e012ef9a9c86908c6b1350771fd140c62
|
[
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
gezidan/NETMF-LPC
|
5093ab223eb9d7f42396344ea316cbe50a2f784b
|
db1880a03108db6c7f611e6de6dbc45ce9b9adce
|
refs/heads/master
| 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,728 |
h
|
//-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _CORLIB_NATIVE_SYSTEM_EXCEPTION_H_
#define _CORLIB_NATIVE_SYSTEM_EXCEPTION_H_
namespace System
{
struct Exception
{
// Helper Functions to access fields of managed object
static LPCSTR& Get__message( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_LPCSTR( pMngObj, Library_corlib_native_System_Exception::FIELD___message ); }
static UNSUPPORTED_TYPE& Get_m_innerException( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_corlib_native_System_Exception::FIELD__m_innerException ); }
static UNSUPPORTED_TYPE& Get_m_stackTrace( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_corlib_native_System_Exception::FIELD__m_stackTrace ); }
static INT32& Get_m_HResult( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_INT32( pMngObj, Library_corlib_native_System_Exception::FIELD__m_HResult ); }
// Declaration of stubs. These functions are implemented by Interop code developers
static LPCSTR get_StackTrace( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
};
}
#endif //_CORLIB_NATIVE_SYSTEM_EXCEPTION_H_
|
[
"[email protected]"
] |
[
[
[
1,
34
]
]
] |
b69431b452970487190fc9dace2b52d2ccd569a6
|
3fb88529ec63d45506d159bee677695698e690ee
|
/rrdinfo.h
|
7619263e49b4e58333d983da02fd3e050037e3be
|
[] |
no_license
|
cristifalcas/qt-rrd
|
588f1d51555b146590dd84d969052123700a5217
|
249c1cb702020bcfe79465381053430e9e6f4e80
|
refs/heads/master
| 2021-01-14T13:20:53.669503 | 2009-11-12T22:16:08 | 2009-11-12T22:16:08 | 34,001,301 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,924 |
h
|
#ifndef RRDINFO_H
#define RRDINFO_H
#include "commons.h"
#include <QStringList>
#include <QMutex>
/*
Format:
filename:
DS1:
DS2:
RRA1
RRA2
...
Each "DS" declares a dataset, or a group of values.
Each "RRA" declares an archive of the datasets we'd like to keep for later analyzation.
DS has : ds-name:GAUGE | COUNTER | DERIVE | ABSOLUTE:heartbeat:min:max
RRA has : AVERAGE | MIN | MAX | LAST:xff:steps:rows
*/
class RRDInfo
{
public:
static RRDInfo *instance()
{
if( m_instance == 0 ) m_instance = new RRDInfo();
return m_instance;
}
void setRRAXFileFactor(const double);
void setRRASteps(const quint64);
void setRRAConsolidationFunction(const QString);
void setDSValues(const QString dsname, const quint64 time, const double value);
void setDataFromStatsConfig(const QMap<QString,QMap<QString,QString> >);
void setDatabasePath(const QString);
void setDatabaseOverwrite(bool);
quint64 getDBStep();
const QString getDatabasePath();
quint64 getMinTime();
quint64 getDatasourcesNumber();
quint64 getRRAsNumber();
const typeDS getDatasource(unsigned int);
const typeRRA getRRA(unsigned int);
bool isOverwrite();
void clear(int i=-1);
bool isEmptyValues();
void printInfo(QString dsname = "");
private:
RRDInfo();
static RRDInfo *m_instance;
void createRRA();
typeRRA *rra;
typeDS *datasource;
QString stringDatabasePath;
QMutex mutex;
quint64 datasourcesize;
bool overwritedb;
int timeinseconds(int nr, QString time);
enum StringPeriod { spMinute,
spHour,
spDay,
spWeek,
spMonth,
spYear };
QMap <QString, StringPeriod> period;
};
#endif // RRDINFO_H
|
[
"[email protected]"
] |
[
[
[
1,
78
]
]
] |
beb491529e6f39b8e03e195a6f7e0955f4fe8ee8
|
de75637338706776f8770c9cd169761cec128579
|
/VHFOS/Simple Game Editor/SGEProjectSetting.h
|
213054359687f84170379f4f3f4851ddaf1f92c1
|
[] |
no_license
|
huytd/fosengine
|
e018957abb7b2ea2c4908167ec83cb459c3de716
|
1cebb1bec49720a8e9ecae1c3d0c92e8d16c27c5
|
refs/heads/master
| 2021-01-18T23:47:32.402023 | 2008-07-12T07:20:10 | 2008-07-12T07:20:10 | 38,933,821 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 505 |
h
|
#ifndef _SGE_PROJECT_SETTING_H_
#define _SGE_PROJECT_SETTING_H_
#include <irrlicht.h>
class SGEProjectSetting
{
public:
SGEProjectSetting(irr::io::IFileSystem* fs);
~SGEProjectSetting();
void read(const char* fileName);
void write(const char* fileName=0);
irr::core::stringc fileName;
irr::core::stringc workingDir;
irr::core::stringc meshPath;
irr::core::stringc texturePath;
irr::core::list<irr::core::stringc> zipArchive;
private:
irr::io::IFileSystem* fs;
};
#endif
|
[
"doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06"
] |
[
[
[
1,
23
]
]
] |
06e8aeb3004d0f35001421d517bde2805fb8a4a7
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Common/Visualize/hkVersionReporter.h
|
5d9ccfc27282d2652d120821d52c053420f5106d
|
[] |
no_license
|
blockspacer/transporter-game
|
23496e1651b3c19f6727712a5652f8e49c45c076
|
083ae2ee48fcab2c7d8a68670a71be4d09954428
|
refs/heads/master
| 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,112 |
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_VISUALIZE_VERSION_REPORTER
#define HK_VISUALIZE_VERSION_REPORTER
class hkStreamWriter;
/// This class manages version information between the server and client.
/// Currently the proto call version is the same as the build number and
/// for a client to work with a server they must have the same version
/// number. Please always use the visual debugger client that shipped
/// with the packages you received.
class hkVersionReporter
{
public:
enum Command // for serialization
{
HK_VERSION_INFORMATION = 0x90
};
/// Sends a data 'chunk' which contains the version information
/// of the Havok libs that the senders process/executable is
/// linked with.
static hkResult HK_CALL sendVersionInformation( hkStreamWriter* connection );
public:
static int m_protocalVersion;
static int m_protocalMinimumCompatible;
};
#endif // HK_VISUALIZE_VERSION_REPORTER
/*
* 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,
58
]
]
] |
41b5774316344c71b092d941d973609f8265fd0d
|
191d4160cba9d00fce9041a1cc09f17b4b027df5
|
/ZeroLag2/KUILib/kscbase/src/kscconv.cpp
|
868b155ab9452b32c14566a5725a18ba57e77465
|
[] |
no_license
|
zapline/zero-lag
|
f71d35efd7b2f884566a45b5c1dc6c7eec6577dd
|
1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4
|
refs/heads/master
| 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,020 |
cpp
|
// Copyright (c) 2010 Kingsoft Corporation. All rights reserved.
// Copyright (c) 2010 The KSafe Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "../../Include/kscbase/kscconv.h"
//////////////////////////////////////////////////////////////////////////
std::wstring AnsiToUnicode(const std::string& strAnsi)
{
std::wstring retval;
if (strAnsi.size())
retval = KANSI_TO_UTF16(strAnsi.c_str());
return retval;
}
std::string UnicodeToAnsi(const std::wstring& strUnicode)
{
std::string retval;
if (strUnicode.size())
retval = KUTF16_To_ANSI(strUnicode.c_str());
return retval;
}
std::string UnicodeToUtf8(const std::wstring& strUnicode)
{
std::string retval;
if (strUnicode.size())
retval = KUTF16_To_UTF8(strUnicode.c_str());
return retval;
}
std::wstring Utf8ToUnicode(const std::string& strUtf8)
{
std::wstring retval;
if (strUtf8.size())
retval = KUTF8_To_UTF16(strUtf8.c_str());
return retval;
}
std::string Utf8ToAnsi(const std::string& strUtf8)
{
std::string retval;
std::wstring strTemp;
strTemp = Utf8ToUnicode(strUtf8);
retval = UnicodeToAnsi(strTemp);
return retval;
}
std::string AnsiToUtf8(const std::string& strAnsi)
{
std::string retval;
std::wstring strTemp;
strTemp = AnsiToUnicode(strAnsi);
retval = UnicodeToUtf8(strTemp);
return retval;
}
//////////////////////////////////////////////////////////////////////////
|
[
"Administrator@PC-200201010241"
] |
[
[
[
1,
82
]
]
] |
e8ebc314aaf125e6c2ac3be742cc3c874b4d9b0c
|
e9794179d5506c4cee3ab264b5eaa4aeaca32ffb
|
/snalp/SnalpAddCategoryDialog.cpp
|
57a9e493f23ca9c3be535d74be9e2b34c3e67041
|
[] |
no_license
|
BackupTheBerlios/snalp-svn
|
ac04f142f21761131322c09ea3f7fecfb4295711
|
3c1f0717f372db6941bdbe11200eaddddc4f76ef
|
refs/heads/master
| 2020-06-03T12:42:26.848983 | 2005-11-12T14:01:58 | 2005-11-12T14:01:58 | 40,772,880 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,761 |
cpp
|
#include "SnalpAddCategoryDialog.h"
#include <libglademm.h>
#include <gtkmm/dialog.h>
#include <gtkmm/entry.h>
#include "SnalpException.h"
#include "SnalpSignals.h"
SnalpAddCategoryDialog::SnalpAddCategoryDialog( GladeRef gladeref , boost::shared_ptr<SnalpSignals> _signals )
: dialog(0),entry(0),signals(_signals)
{
try
{
Gtk::Button * button = 0;
gladeref->get_widget<Gtk::Dialog>("AddCategoryDialog",dialog);
gladeref->get_widget<Gtk::Entry>("AddCategoryDialogEntry",entry);
gladeref->get_widget<Gtk::Button>("AddCategoryDialogOkButton",button);
button->signal_clicked().connect(sigc::mem_fun(*this,&SnalpAddCategoryDialog::OnAccept));
gladeref->get_widget<Gtk::Button>("AddCategoryDialogCancelButton",button);
button->signal_clicked().connect(sigc::mem_fun(*dialog,&Gtk::Dialog::hide));
}
catch( Gnome::Glade::XmlError const & xml_error )
{
THROW_SNALP_EXCEPTION(SnalpFatalException,xml_error.what());
}
catch( std::exception const & e )
{
THROW_SNALP_EXCEPTION(SnalpFatalException,e.what());
}
catch( Glib::Exception const & e )
{
THROW_SNALP_EXCEPTION(SnalpFatalException,e.what());
}
catch( ... )
{
THROW_SNALP_EXCEPTION(SnalpFatalException, "Unknown exception caught" );
}
}
SnalpAddCategoryDialog::~SnalpAddCategoryDialog()
{
}
void SnalpAddCategoryDialog::Run()
{
Clear();
dialog->show_all();
}
void SnalpAddCategoryDialog::Clear()
{
entry->set_text("");
}
void SnalpAddCategoryDialog::OnAccept()
{
signals->AddCategorySlot(Glib::locale_from_utf8(entry->get_text()));
Clear();
dialog->hide();
}
|
[
"evilissimo@06cfc98a-34eb-0310-b305-c204f3371456"
] |
[
[
[
1,
62
]
]
] |
bd9ed557ab31afb6b43b6b41f595f8b910e0bfaf
|
9566086d262936000a914c5dc31cb4e8aa8c461c
|
/EnigmaProtocol/Messages/CreatePlayerOrganizationResponseMessage.cpp
|
824d9b62a646518d45fff9a73e46e41a2ba625d8
|
[] |
no_license
|
pazuzu156/Enigma
|
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
|
b8a4dfbd0df206e48072259dbbfcc85845caad76
|
refs/heads/master
| 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 2,499 |
cpp
|
/*
Copyright © 2009 Christopher Joseph Dean Schaefer (disks86)
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "CreatePlayerOrganizationResponseMessage.hpp"
namespace Enigma
{
CreatePlayerOrganizationResponseMessage::CreatePlayerOrganizationResponseMessage()
{
this->SetName("");
this->SetType(CreatePlayerOrganizationResponseMessage::GetMessageType());
//this->SetChannel(CHANNEL_AUTHENTICATION);
//this->SetChannel(CHANNEL_MOVEMENT);
//this->SetChannel(CHANNEL_COMBAT);
this->SetChannel(CHANNEL_CHAT);
//this->SetChannel(CHANNEL_VOICE_CHAT);
}
CreatePlayerOrganizationResponseMessage::~CreatePlayerOrganizationResponseMessage()
{
}
Enigma::s32 CreatePlayerOrganizationResponseMessage::GetOrganizationType()
{
return this->GetInt(0);
}
void CreatePlayerOrganizationResponseMessage::SetOrganizationType(Enigma::s32 value)
{
this->SetInt(0,value);
}
const std::string& CreatePlayerOrganizationResponseMessage::GetName()
{
this->mName = this->GetString(1);
return this->mName;
}
void CreatePlayerOrganizationResponseMessage::SetName(const std::string& value)
{
this->mName=value;
this->ResizeMessage(this->mName.length()+CreatePlayerOrganizationResponseMessage::GetMessageLength(),0);
this->SetString(1,this->mName);
}
void CreatePlayerOrganizationResponseMessage::SetName(std::string& value)
{
this->mName=value;
this->ResizeMessage(this->mName.length()+CreatePlayerOrganizationResponseMessage::GetMessageLength(),0);
this->SetString(1,this->mName);
}
};
|
[
"[email protected]"
] |
[
[
[
1,
64
]
]
] |
77eacbe2db50e78c86d59fbc95eea9afdcd924fb
|
0429e2b2a1a09254b5182e15835da188f7d44a3d
|
/tags/v01/reservationManagement.cpp
|
1ab72c0a38403a3cbe29d0ea2385a9c7bc5afe1e
|
[] |
no_license
|
TheolZacharopoulos/tl2hotel
|
0b5af731aa022b04fc7b894b4fad6ce0b1121744
|
87ff9c75250d702c49d62f43e494cf549ea700b7
|
refs/heads/master
| 2020-03-30T05:41:55.498410 | 2011-04-25T22:24:44 | 2011-04-25T22:24:44 | 42,362,513 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,591 |
cpp
|
#include "reservationManagement.h"
/** Default Constructors
*/
ReservationManagement::ReservationManagement()
{
reservationId=0;
dateFrom = "";
dateTo = "";
}
/** Copy,set,get Constructors
*/
ReservationManagement::ReservationManagement(int reservationId1,QString dateFrom1,QString dateTo1)
{
reservationId=reservationId1;
dateFrom = dateFrom1;
dateTo = dateTo1;
}
int ReservationManagement::getReservationId()
{
return reservationId;
}
QString ReservationManagement::getDateFrom()
{
return dateFrom;
}
QString ReservationManagement::getDateTo()
{
return dateTo;
}
void ReservationManagement::setReservationId(int reservationId1 )
{
reservationId=reservationId1;
}
void ReservationManagement::setDateFrom(QString dateFrom1 )
{
dateFrom = dateFrom1;
}
void ReservationManagement::setDateTo(QString dateTo1 )
{
dateTo = dateTo1;
}
/** Room Reservation Function
*makes the reservation of the selected room
*
*/
void ReservationManagement::roomReservation(QString DateFrom,QString DateTo,int roomId,int CustomerId)
{
if( room.getFree() )
{
sqlMechanism.execQuery("insert into RoomsReservation (DateFrom,DateTo,fkCustomerId,fkRoomId) values('"+DateFrom+"','"+DateTo+"','"+QString("%1").arg(roomId)+"','"+QString("%1").arg(CustomerId)+"') ");
}
else
{
QMessageBox msgBox;
msgBox.setText("Reservation not made.Room is not free at the moment.");
msgBox.exec();
}
}
|
[
"delis89@fb7cbe1a-da42-76e9-2caa-fedf319af631"
] |
[
[
[
1,
80
]
]
] |
db94191ad0b90b22efa6a97e84c1cf93ea3563be
|
a96b15c6a02225d27ac68a7ed5f8a46bddb67544
|
/SetGame/GazaScottHandler.hpp
|
4648102c6b354aa8a7b1966f156624d0344268e5
|
[] |
no_license
|
joelverhagen/Gaza-2D-Game-Engine
|
0dca1549664ff644f61fe0ca45ea6efcbad54591
|
a3fe5a93e5d21a93adcbd57c67c888388b402938
|
refs/heads/master
| 2020-05-15T05:08:38.412819 | 2011-04-03T22:22:01 | 2011-04-03T22:22:01 | 1,519,417 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 759 |
hpp
|
#ifndef GAZASCOTTPACKER_HPP
#define GAZASCOTTPACKER_HPP
#include "Gaza.hpp"
#include "GazaBaseHandler.hpp"
namespace Gaza
{
namespace RectanglePacking
{
class ScottHandler : public BaseHandler
{
public:
ScottHandler();
~ScottHandler();
void initialize(unsigned int width, unsigned int height);
bool addRectangle(sf::IntRect * inputRectangle);
private:
class ScottPackerNode
{
public:
ScottPackerNode(const sf::IntRect &rectangle);
~ScottPackerNode();
bool addRectangle(sf::IntRect * inputRectangle);
sf::IntRect rectangle;
ScottPackerNode * leftChild;
ScottPackerNode * rightChild;
bool filled;
};
ScottPackerNode * rootNode;
};
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
41
]
]
] |
449f16ea2b7984f5270cb015e5d63760a4a134ee
|
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
|
/Base/BufsAndStrings/Desc/Buffer/buf_format.cpp
|
85465d9cb0cce3a8a1f42449007a5d2052e2674b
|
[] |
no_license
|
huellif/symbian-example
|
72097c9aec6d45d555a79a30d576dddc04a65a16
|
56f6c5e67a3d37961408fc51188d46d49bddcfdc
|
refs/heads/master
| 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 310 |
cpp
|
/*
* buf_format.cpp
*
* Created on: 2010-9-28
* Author: thomas
*/
#include <e32cons.h>
#include "buf_format.h"
GLREF_C CConsoleBase* console;
void prompt_case(TDesC& aDesC)
{
console->Printf(_L("\n------------------\ncase : %S\n"), &aDesC);
console->Getch();
}
|
[
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] |
[
[
[
1,
18
]
]
] |
3d8fa02aa0c02b4648f98506ca2ba81e61b10b86
|
4aadb120c23f44519fbd5254e56fc91c0eb3772c
|
/Source/EduNetGames/obsolete/Tutorial_03/NetBoidFactory.h
|
ea0d67e81ef887325fa201f06aa299956e7183e4
|
[] |
no_license
|
janfietz/edunetgames
|
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
|
04d787b0afca7c99b0f4c0692002b4abb8eea410
|
refs/heads/master
| 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,229 |
h
|
#ifndef __NETBOIDFACTORY_H__
#define __NETBOIDFACTORY_H__
//-----------------------------------------------------------------------------
// Copyright (c) 2009, Jan Fietz, Cyrus Preuss
// 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 EduNetGames nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "NetBoid.h"
#include "OpenSteerUT/AbstractEntityFactory.h"
//-----------------------------------------------------------------------------
class NetBoidFactory : public OpenSteer::TEntityFactory<OpenSteer::TNetBoid>
{
ET_DECLARE_BASE( OpenSteer::TEntityFactory<OpenSteer::TNetBoid> );
public:
NetBoidFactory();
virtual ~NetBoidFactory();
};
#endif // __NETBOIDFACTORY_H__
|
[
"janfietz@localhost"
] |
[
[
[
1,
46
]
]
] |
c0e54d78e6263721d5cba1c90e78c8f933e7eab8
|
c7120eeec717341240624c7b8a731553494ef439
|
/src/cplusplus/freezone-samp/src/core/samp/samp_events.cpp
|
a72106c271993c605e5f1d6e1b7314c93e6af5e4
|
[] |
no_license
|
neverm1ndo/gta-paradise-sa
|
d564c1ed661090336621af1dfd04879a9c7db62d
|
730a89eaa6e8e4afc3395744227527748048c46d
|
refs/heads/master
| 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null |
WINDOWS-1251
|
C++
| false | false | 15,626 |
cpp
|
#include "config.hpp"
#include "samp_events.hpp"
#include "samp_events_i.hpp"
#include "pawn/pawn_events.hpp"
#include "core/application.hpp"
#include "core/container/container_handlers.hpp"
namespace samp {
REGISTER_IN_APPLICATION(events);
events::ptr events::instance() {
return application::instance()->get_item<events>();
}
namespace {
events* curr_events = 0;
inline server_ver get_server_ver(int ver) {
switch (ver) {
case 1: return server_ver_022;
case 2: return server_ver_02X;
case 3: return server_ver_03a;
case 4: return server_ver_03b;
default: assert(false);
}
return server_ver_unknown;
}
inline player_disconnect_reason get_reason(int reason_int) {
switch (reason_int) {
case 0: return player_disconnect_reason_time_out;
case 1: return player_disconnect_reason_quit;
case 2: return player_disconnect_reason_kick_ban;
default: assert(false);
}
return player_disconnect_reason_quit;
}
inline player_state get_player_state(int state_int) {
switch (state_int) {
case 0: return player_state_empty;
case 1: return player_state_on_foot;
case 2: return player_state_driver;
case 3: return player_state_passenger;
case 7: return player_state_wasted;
case 8: return player_state_spawned;
case 9: return player_state_spectating;
default: assert(false);
}
return player_state_empty;
}
inline click_source get_click_source(int source) {
return click_source_scoreboard;
}
void OnGameModeInit(AMX* amx, int ver_int) {
server_ver ver = get_server_ver(ver_int);
container_execute_handlers(application::instance(), &on_pre_pre_gamemode_init_i::on_pre_pre_gamemode_init, amx, ver);
container_execute_handlers(application::instance(), &on_pre_gamemode_init_i::on_pre_gamemode_init, amx, ver);
container_execute_handlers(application::instance(), &on_gamemode_init_i::on_gamemode_init, amx, ver);
}
void OnGameModeExit(AMX* amx) {
container_execute_handlers(application::instance(), &on_gamemode_exit_i::on_gamemode_exit, amx);
container_execute_handlers(application::instance(), &on_post_gamemode_exit_i::on_post_gamemode_exit, amx);
container_execute_handlers(application::instance(), &on_post_post_gamemode_exit_i::on_post_post_gamemode_exit, amx);
}
void OnPlayerConnect(int player_id) {
container_execute_handlers(application::instance(), &on_player_connect_i::on_player_connect, player_id);
}
void OnPlayerDisconnect(int player_id, int reason_int) {
player_disconnect_reason reason = get_reason(reason_int);
container_execute_handlers(application::instance(), &on_player_disconnect_i::on_player_disconnect, player_id, reason);
}
void OnPlayerSpawn(int player_id) {
container_execute_handlers(application::instance(), &on_player_spawn_i::on_player_spawn, player_id);
}
void OnPlayerDeath(int player_id, int killer_id, int reason) {
container_execute_handlers(application::instance(), &on_player_death_i::on_player_death, player_id, killer_id, reason);
}
void OnVehicleSpawn(int vehicle_id) {
container_execute_handlers(application::instance(), &on_vehicle_spawn_i::on_vehicle_spawn, vehicle_id);
}
void OnVehicleDeath(int vehicle_id, int killer_id) {
container_execute_handlers(application::instance(), &on_vehicle_death_i::on_vehicle_death, vehicle_id, killer_id);
}
bool OnPlayerText(int player_id, std::string const& text) {
container_execute_handlers(application::instance(), &on_player_text_i::on_player_text, player_id, text);
return false; // Всегда подавляем стандартный вывод текста
}
void OnPlayerCommandText(int player_id, std::string const& cmd) {
container_execute_handlers(application::instance(), &on_player_commandtext_i::on_player_commandtext, player_id, cmd);
}
void OnPlayerRequestClass(int player_id, int class_id) {
container_execute_handlers(application::instance(), &on_player_request_class_i::on_player_request_class, player_id, class_id);
}
void OnPlayerEnterVehicle(int player_id, int vehicle_id, bool is_passenger) {
container_execute_handlers(application::instance(), &on_player_enter_vehicle_i::on_player_enter_vehicle, player_id, vehicle_id, is_passenger);
}
void OnPlayerExitVehicle(int player_id, int vehicle_id) {
container_execute_handlers(application::instance(), &on_player_exit_vehicle_i::on_player_exit_vehicle, player_id, vehicle_id);
}
void OnPlayerStateChange(int player_id, int newstate_int, int oldstate_int) {
player_state state_new = get_player_state(newstate_int);
player_state state_old = get_player_state(oldstate_int);
container_execute_handlers(application::instance(), &on_player_state_change_i::on_player_state_change, player_id, state_new, state_old);
}
void OnPlayerEnterCheckpoint(int player_id) {
container_execute_handlers(application::instance(), &on_player_enter_checkpoint_i::on_player_enter_checkpoint, player_id);
}
void OnPlayerLeaveCheckpoint(int player_id) {
container_execute_handlers(application::instance(), &on_player_leave_checkpoint_i::on_player_leave_checkpoint, player_id);
}
void OnPlayerEnterRaceCheckpoint(int player_id) {
container_execute_handlers(application::instance(), &on_player_enter_racecheckpoint_i::on_player_enter_racecheckpoint, player_id);
}
void OnPlayerLeaveRaceCheckpoint(int player_id) {
container_execute_handlers(application::instance(), &on_player_leave_racecheckpoint_i::on_player_leave_racecheckpoint, player_id);
}
bool OnRconCommand(std::string const& cmd) {
return container_execute_handlers(application::instance(), &on_rconcommand_i::on_rconcommand, cmd, container_execute_rezult_true_if_have_one_true);
}
bool OnPlayerRequestSpawn(int player_id) {
return container_execute_handlers(application::instance(), &on_player_request_spawn_i::on_player_request_spawn, player_id);
}
void OnObjectMoved(int object_id) {
container_execute_handlers(application::instance(), &on_object_moved_i::on_object_moved, object_id);
}
void OnPlayerObjectMoved(int player_id, int object_id) {
container_execute_handlers(application::instance(), &on_playerobject_moved_i::on_playerobject_moved, player_id, object_id);
}
void OnPlayerPickUpPickup(int player_id, int pickup_id) {
container_execute_handlers(application::instance(), &on_player_pickuppickup_i::on_player_pickuppickup, player_id, pickup_id);
}
bool OnVehicleMod(int player_id, int vehicle_id, int component_id) {
return container_execute_handlers(application::instance(), &on_vehicle_mod_i::on_vehicle_mod, player_id, vehicle_id, component_id);
}
void OnEnterExitModShop(int player_id, int enter_exit, int interior_id) {
container_execute_handlers(application::instance(), &on_enter_exit_mod_shop_i::on_enter_exit_mod_shop, player_id, enter_exit, interior_id);
}
bool OnVehiclePaintjob(int player_id, int vehicle_id, int paintjob_id) {
return container_execute_handlers(application::instance(), &on_vehicle_paintjob_i::on_vehicle_paintjob, player_id, vehicle_id, paintjob_id);
}
bool OnVehicleRespray(int player_id, int vehicle_id, int color1, int color2) {
return container_execute_handlers(application::instance(), &on_vehicle_respray_i::on_vehicle_respray, player_id, vehicle_id, color1, color2);
}
void OnVehicleDamageStatusUpdate(int vehicle_id, int player_id) {
container_execute_handlers(application::instance(), &on_vehicle_damage_status_update_i::on_vehicle_damage_status_update, vehicle_id, player_id);
}
void OnPlayerSelectedMenuRow(int player_id, int row) {
container_execute_handlers(application::instance(), &on_player_selected_menurow_i::on_player_selected_menurow, player_id, row);
}
void OnPlayerExitedMenu(int player_id) {
container_execute_handlers(application::instance(), &on_player_exited_menu_i::on_player_exited_menu, player_id);
}
void OnPlayerInteriorChange(int player_id, int interior_id_new, int interior_id_old) {
container_execute_handlers(application::instance(), &on_player_interior_change_i::on_player_interior_change, player_id, interior_id_new, interior_id_old);
}
void OnPlayerKeyStateChange(int player_id, int keys_new, int keys_old) {
container_execute_handlers(application::instance(), &on_player_keystate_change_i::on_player_keystate_change, player_id, keys_new, keys_old);
}
void OnRconLoginAttempt(std::string const& ip, std::string const& password, bool is_success) {
container_execute_handlers(application::instance(), &on_rcon_login_attempt_i::on_rcon_login_attempt, ip, password, is_success);
}
bool OnPlayerUpdate(int player_id) {
return container_execute_handlers(application::instance(), &on_player_update_i::on_player_update, player_id);
}
void OnPlayerStreamIn(int player_id, int for_player_id) {
container_execute_handlers(application::instance(), &on_player_stream_in_i::on_player_stream_in, player_id, for_player_id);
}
void OnPlayerStreamOut(int player_id, int for_player_id) {
container_execute_handlers(application::instance(), &on_player_stream_out_i::on_player_stream_out, player_id, for_player_id);
}
void OnVehicleStreamIn(int vehicle_id, int for_player_id) {
container_execute_handlers(application::instance(), &on_vehicle_stream_in_i::on_vehicle_stream_in, vehicle_id, for_player_id);
}
void OnVehicleStreamOut(int vehicle_id, int for_player_id) {
container_execute_handlers(application::instance(), &on_vehicle_stream_out_i::on_vehicle_stream_out, vehicle_id, for_player_id);
}
void OnDialogResponse(int player_id, int dialog_id, int response, int list_item, std::string const& input_text) {
container_execute_handlers(application::instance(), &on_dialog_response_i::on_dialog_response, player_id, dialog_id, response, list_item, input_text);
}
void OnPlayerClickPlayer(int player_id, int clicked_player_id, int source_int) {
click_source source = get_click_source(source_int);
container_execute_handlers(application::instance(), &on_player_click_player_i::on_player_click_player, player_id, clicked_player_id, source);
}
}
events::events() {
}
events::~events() {
}
void events::configure_pre() {
}
void events::configure(buffer::ptr const& buff, def_t const& def) {
}
void events::configure_post() {
}
void events::plugin_on_load() {
// Получить список:
// cat list | grep " On" | perl -pe 's/\(/ /g' | awk '{print $2}' | perl -pe 's/On(.+)/FZ${1} On${1}/' | awk '{printf(" pawn_events_ptr->add_callback(\"%s\", &%s);\n", $1, $2)}'
pawn::events::ptr pawn_events_ptr = pawn::events::instance();
pawn_events_ptr->add_callback("FZGameModeInit", &OnGameModeInit);
pawn_events_ptr->add_callback("FZGameModeExit", &OnGameModeExit);
pawn_events_ptr->add_callback("FZPlayerConnect", &OnPlayerConnect);
pawn_events_ptr->add_callback("FZPlayerDisconnect", &OnPlayerDisconnect);
pawn_events_ptr->add_callback("FZPlayerSpawn", &OnPlayerSpawn);
pawn_events_ptr->add_callback("FZPlayerDeath", &OnPlayerDeath);
pawn_events_ptr->add_callback("FZVehicleSpawn", &OnVehicleSpawn);
pawn_events_ptr->add_callback("FZVehicleDeath", &OnVehicleDeath);
pawn_events_ptr->add_callback("FZPlayerText", &OnPlayerText);
pawn_events_ptr->add_callback("FZPlayerCommandText", &OnPlayerCommandText);
pawn_events_ptr->add_callback("FZPlayerRequestClass", &OnPlayerRequestClass);
pawn_events_ptr->add_callback("FZPlayerEnterVehicle", &OnPlayerEnterVehicle);
pawn_events_ptr->add_callback("FZPlayerExitVehicle", &OnPlayerExitVehicle);
pawn_events_ptr->add_callback("FZPlayerStateChange", &OnPlayerStateChange);
pawn_events_ptr->add_callback("FZPlayerEnterCheckpoint", &OnPlayerEnterCheckpoint);
pawn_events_ptr->add_callback("FZPlayerLeaveCheckpoint", &OnPlayerLeaveCheckpoint);
pawn_events_ptr->add_callback("FZPlayerEnterRaceCheckpoint", &OnPlayerEnterRaceCheckpoint);
pawn_events_ptr->add_callback("FZPlayerLeaveRaceCheckpoint", &OnPlayerLeaveRaceCheckpoint);
pawn_events_ptr->add_callback("FZRconCommand", &OnRconCommand);
pawn_events_ptr->add_callback("FZPlayerRequestSpawn", &OnPlayerRequestSpawn);
pawn_events_ptr->add_callback("FZObjectMoved", &OnObjectMoved);
pawn_events_ptr->add_callback("FZPlayerObjectMoved", &OnPlayerObjectMoved);
pawn_events_ptr->add_callback("FZPlayerPickUpPickup", &OnPlayerPickUpPickup);
pawn_events_ptr->add_callback("FZVehicleMod", &OnVehicleMod);
pawn_events_ptr->add_callback("FZEnterExitModShop", &OnEnterExitModShop);
pawn_events_ptr->add_callback("FZVehiclePaintjob", &OnVehiclePaintjob);
pawn_events_ptr->add_callback("FZVehicleRespray", &OnVehicleRespray);
pawn_events_ptr->add_callback("FZVehicleDamageStatusUpdate", &OnVehicleDamageStatusUpdate);
pawn_events_ptr->add_callback("FZPlayerSelectedMenuRow", &OnPlayerSelectedMenuRow);
pawn_events_ptr->add_callback("FZPlayerExitedMenu", &OnPlayerExitedMenu);
pawn_events_ptr->add_callback("FZPlayerInteriorChange", &OnPlayerInteriorChange);
pawn_events_ptr->add_callback("FZPlayerKeyStateChange", &OnPlayerKeyStateChange);
pawn_events_ptr->add_callback("FZRconLoginAttempt", &OnRconLoginAttempt);
pawn_events_ptr->add_callback("FZPlayerUpdate", &OnPlayerUpdate);
pawn_events_ptr->add_callback("FZPlayerStreamIn", &OnPlayerStreamIn);
pawn_events_ptr->add_callback("FZPlayerStreamOut", &OnPlayerStreamOut);
pawn_events_ptr->add_callback("FZVehicleStreamIn", &OnVehicleStreamIn);
pawn_events_ptr->add_callback("FZVehicleStreamOut", &OnVehicleStreamOut);
pawn_events_ptr->add_callback("FZDialogResponse", &OnDialogResponse);
pawn_events_ptr->add_callback("FZPlayerClickPlayer", &OnPlayerClickPlayer);
}
} // namespace samp {
|
[
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] |
[
[
[
1,
288
]
]
] |
5ed3a1bbfaea21fb1cb27eefcc724fc65ec5b848
|
0ada9a773daf394d56b8d71458d1a361986d3f2e
|
/cob3_driver/cob3_camera_sensors/common/include/cob3_camera_sensors/ThreeDUtils.h
|
ed82b22137b89d8b5e2eebc60529fa1729f68c98
|
[] |
no_license
|
zhenli/care-o-bot
|
10a66c1fb4fd16312f4b9c420167cb0b96284fa8
|
dd80cf63f26e2b9ab4734921785e5f5bf24bfd80
|
refs/heads/master
| 2021-01-17T23:14:59.329208 | 2010-03-11T08:59:20 | 2010-03-11T08:59:20 | null | 0 | 0 | null | null | null | null |
ISO-8859-2
|
C++
| false | false | 24,176 |
h
|
/****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_driver
* ROS package name: cob3_camera_sensors
* Description: A minimal but "complete" 3D library. This library provides
* classes for 3D points, 3D point clouds, 3D colored point clouds and
* a 6D (translation and orientation) frame class. Also a few algorithms
* for frame reconstruction from point correspondences are provided.
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Jan Fischer, email:[email protected]
* Supervised by: Jan Fischer, email:[email protected]
*
* Date of creation: Nov 2008
* ToDo:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#ifndef __THREEDUTILS_H__
#define __THREEDUTILS_H__
#include "cob3_camera_sensors/MathUtils.h"
#include "cob3_camera_sensors/GlobalDefines.h"
#include <list>
#include <map>
#include <set>
namespace ipa_Utils {
static const double ROT_FACTOR = 0.032; // PI * ROT_FACTOR = 0.1 m
/// Basic point struct/class to represent 3 double components.
class Point3Dbl
{
public:
/// Constructor.
Point3Dbl(){};
/// Copy constructor
Point3Dbl(const Point3Dbl& p3dbl) {m_x=p3dbl.m_x; m_y=p3dbl.m_y; m_z=p3dbl.m_z;}
/// Constructor with initialization.
Point3Dbl(double x, double y, double z) {m_x=x; m_y=y; m_z=z;};
/// Constructor with one value initialization
Point3Dbl(double x) {m_x=x; m_y=x; m_z=x;};
/// Destructor.
~Point3Dbl(){};
/// Set function to assign values.
/// Computes m_x=x, m_y=y, and m_z=z.
/// @param x x value
/// @param y y value
/// @param z z value
void Set(double x, double y, double z){m_x=x; m_y=y; m_z=z;}
/// Set function to assign values.
/// Computes m_x=v, m_y=v, and m_z=v.
/// @param v the value
void Set(double v){m_x=v; m_y=v; m_z=v;}
/// Set function to assign values.
/// Computes m_x=p.m_x, m_y=p.m_y, and m_z=p.m_z.
/// @param p a 3D point
void Set(const Point3Dbl& p) {m_x=p.m_x; m_y=p.m_y; m_z=p.m_z;}
/// String conversion.
std::string Str() const {std::stringstream s; s << m_x << " " << m_y << " " << m_z; return s.str();}
/// x component.
double m_x;
/// y component.
double m_y;
/// z component.
double m_z;
/// Get square of absolute value.
/// @return m_x*m_x+m_y*m_y+m_z*m_z.
double AbsValSqr() const {return m_x*m_x+m_y*m_y+m_z*m_z;}
/// Get the absolute value (magnitude).
/// @see AbsValSqr()
/// @return sqrt(AbsValSqr())
double AbsVal() const {return sqrt(AbsValSqr());}
/// Scalar multiplication.
/// Computes m_x=s*A.m_x, m_y=s*A.m_y, and m_z=s*A.m_z.
/// @param s the scalar
/// @param A the argument vector
void ScalarMul(const double& s, const Point3Dbl& A) {m_x=s*A.m_x; m_y=s*A.m_y; m_z=s*A.m_z;}
/// Scalar multiplication (in-place).
/// Computes m_x*=s, m_y*=s, and m_z*=s.
/// @param s the scalar
void ScalarMul(const double& s) {m_x*=s; m_y*=s; m_z*=s;}
/// Componentwise multiplication.
/// @param A the first argument vector
/// @param B the second argument vector
void CompMul(const Point3Dbl& A, const Point3Dbl& B) {m_x = A.m_x*B.m_x; m_y = A.m_y*B.m_y; m_z = A.m_z*B.m_z;}
/// Componentwise in-place multiplication.
/// Computes m_x *= A.m_x, m_y *= A.m_y, and m_z *= A.m_z.
/// @param A the argument vector
void CompMul(const Point3Dbl& A) {m_x *= A.m_x; m_y *= A.m_y; m_z *= A.m_z;}
/// Normalization.
/// Computes a=A.AbsVal() and ScalarMul(1.0/a, A).
/// @param A the argument vector
void Normalize(const Point3Dbl& A) {double a=A.AbsVal(); if(a<THE_EPS_DEF) Set(0,0,1); else ScalarMul(1.0/a, A);}
/// Normalization (in-place).
void Normalize() {double a=AbsVal(); if(a<THE_EPS_DEF) Set(0,0,1); else {m_x/=a; m_y/=a; m_z/=a;}}
/// Negative vector.
/// Computes m_x=-A.m_x, m_y=-A.m_y, and m_z=-A.m_z.
/// @param A the argument vector
void Negative(const Point3Dbl& A) {m_x=-A.m_x; m_y=-A.m_y; m_z=-A.m_z;}
/// Negative vector (in-place).
/// Computes m_x*=-1.0, m_y*=-1.0, and m_z*=-1.0.
void Negative() {m_x*=-1.0; m_y*=-1.0; m_z*=-1.0;}
/// Scale inversion.
/// Reciprocal component values.
/// @param A the argument vector
void Inverse(const Point3Dbl& A) {m_x=1.0/A.m_x; m_y=1.0/A.m_y; m_z=1.0/A.m_z;}
/// Scale inversion (in-place).
/// Reciprocal component values.
/// Computes m_x=1.0/m_x, m_y=1.0/m_y, and m_z=1.0/m_z.
void Inverse() {m_x=1.0/m_x; m_y=1.0/m_y; m_z=1.0/m_z;}
/// Get the squared euclidian distance between two vectors.
/// Computes dblsqr(A.m_x-m_x)+dblsqr(A.m_y-m_y)+dblsqr(A.m_z-m_z).
/// @param A the argument vector
double GetSqrDistance(const Point3Dbl& A) const {return dblsqr(A.m_x-m_x)+dblsqr(A.m_y-m_y)+dblsqr(A.m_z-m_z);}
/// Get the euclidian distance between two vectors.
/// Computes sqrt(GetSqrDistance(A)).
/// @param Arg the argument vector
double GetDistance(const Point3Dbl& A) const {return sqrt(GetSqrDistance(A));}
/// Vector addition.
/// Computes m_x=A.m_x+B.m_x, m_y=A.m_y+B.m_y, and m_z=A.m_z+B.m_z.
/// @param A the first argument vector
/// @param B the second argument vector
void AddVec(const Point3Dbl& A, const Point3Dbl& B) {m_x=A.m_x+B.m_x; m_y=A.m_y+B.m_y; m_z=A.m_z+B.m_z;}
/// Vector addition (in-place).
/// Computes m_x+=A.m_x, m_y+=A.m_y, m_z+=A.m_z.
/// @param A the argument vector
void AddVec(const Point3Dbl& A) {m_x+=A.m_x; m_y+=A.m_y; m_z+=A.m_z;}
/// Vector substraction. Computes A - B.
/// @param A the first argument vector
/// @param B the second argument vector
void SubVec(const Point3Dbl& A, const Point3Dbl& B) {m_x=A.m_x-B.m_x; m_y=A.m_y-B.m_y; m_z=A.m_z-B.m_z;}
/// Vector substraction (in-place).
/// Computes m_x-=A.m_x, m_y-=A.m_y, m_z-=A.m_z.
/// @param Arg the argument vector
void SubVec(const Point3Dbl& A) {m_x-=A.m_x; m_y-=A.m_y; m_z-=A.m_z;}
/// Scalar product (dot product).
/// Computes m_x*A.m_x+m_y*A.m_y+m_z*A.m_z.
/// @param Arg the argument vector
/// @return the scalar prduct
double ScalarProd(const Point3Dbl& A) const {return m_x*A.m_x+m_y*A.m_y+m_z*A.m_z;}
/// Vector product (cross product).
/// Computes m_x=A.m_y*B.m_z-A.m_z*B.m_y, m_y=A.m_z*B.m_x-A.m_x*B.m_z, and m_z=A.m_x*B.m_y-A.m_y*B.m_x.
/// @param A the first argument vector
/// @param B the second argument vector
void VectorProd(const Point3Dbl& A, const Point3Dbl& B) {m_x=A.m_y*B.m_z-A.m_z*B.m_y; m_y=A.m_z*B.m_x-A.m_x*B.m_z; m_z=A.m_x*B.m_y-A.m_y*B.m_x;}
/// Get the cosine between two vectors.
/// Computes ScalarProd(A)/(AbsVal()*A.AbsVal()).
/// @param A the argument vector
/// @return the cosine
double GetCosine(const Point3Dbl& A) const {if(AbsVal()==0.0 || A.AbsVal()==0.0) return 1.0; else return ScalarProd(A)/(AbsVal()*A.AbsVal());}
/// Get the sine between two vectors.
/// @param A the argument vector
/// @return the sine
double GetSine(const Point3Dbl& A) const {Point3Dbl Tmp; Tmp.VectorProd(*this, A); return Tmp.AbsVal()/(AbsVal()*A.AbsVal());}
/// Get the peak angle between two vectors.
/// Uses atan2().
/// @param A the argument vector
/// @return the angle
double GetAngle(const Point3Dbl& A) const {Point3Dbl Tmp; Tmp.VectorProd(*this, A); return atan2(Tmp.AbsVal(), ScalarProd(A));}
/// Get theta.
/// Get the theta angle of the sphere coordinates.
//double GetThetaSphere(const Point3Dbl& Point) {return atan2(sqrt(dblsqr(Point.m_x)+dblsqr(Point.m_y)),Point.m_z);}
/// Get phi.
/// Get the theta angle of the sphere coordinates.
//double GetPhiSphere(const Point3Dbl& Point) {return atan2(Point.m_y, Point.m_x);}
/// Conversion to sphere coordinates.
/// Assumption xy-plane is the spherical reference plane
void ToSphere();
void ToSphereNormalized();
/// Conversion from sphere to cartesian coordinates.
void ToCart();
/// Conversion from sphere to cartesian coordinates only phi and theta (assuming r=1).
/// @param Phi computed phi
/// @param Theta computed theta
void ToCartNormalized(double Theta, double Phi);
/// Projection of a vector B on this vector.
void Projection(const Point3Dbl& B);
/// Orthogonal projection length.
double GetLengthOrthProjection(const Point3Dbl& B);
/// Orthogonal component.
void OrthProjection(const Point3Dbl& B);
void OrthProjectionDiffVector(const Point3Dbl& B);
};
/// Rotate vector. Rotation of a vector around the axis RotaNormal. The amount of rotation is given by Phi.
/// This function is implemented using Rodrigues' rotation formula (see e.g. http://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula)
/// @param RotaNormal the rotation normal (axis around which will be rotated).
/// @param Phi The angle (amount) of rotation.
/// @param A The vector that is rotated around RotaNormal with angle Phi.
/// @param Res The rotated result vector.
void RotateVector(const Point3Dbl& RotaNormal, double Phi, const Point3Dbl& A, Point3Dbl& Res);
/// Estimate the orientation of two points around the origin
/// This function is implemented using Rodrigues' rotation formula
/// (see e.g. http://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula).
/// @param RotaNormal the rotation normal (axis around which will be rotated).
/// @param Phi the angle (amount) of rotation.
/// @param A the argument vector.
/// @param Res the rotated result vector.
int GetRotation(const Point3Dbl& A1, const Point3Dbl& B1,
const Point3Dbl& A2, const Point3Dbl& B2,
Point3Dbl& RotaNormal, double& Phi);
double GetRotationDistance(Point3Dbl& RotaNormal0, double Alpha0, Point3Dbl& RotaNormal1, double Alpha1);
void GetRotationMean(Point3Dbl& RotaNormal0, double Alpha0, Point3Dbl& RotaNormal1, double Alpha1, Point3Dbl& RotaNormal2, double& Alpha2, double w0=1.0, double w1=1.0);
/// Line function: get the base point of a point Q.
/// This function compute the orthogonal projection of Q on the line given by S0 and S1.
void GetBasePoint(const Point3Dbl& S0, const Point3Dbl& S1, const Point3Dbl& Q, Point3Dbl& X);
/// Line function: get the distance to Q.
/// This function compute the distance between Q and the line given by S0 and S1.
double GetLineDistance(const Point3Dbl& S0, const Point3Dbl& S1, const Point3Dbl& Q);
/// Class to describe a 3D integer point.
/// This class can be used to describe a 3D integer point (integer triple).
class Point3Int
{
public:
Point3Int(){};
Point3Int(int x, int y, int z) {m_x=x; m_y=y; m_z=z;};
~Point3Int(){};
std::string Str() const {std::stringstream s; s << m_x << " " << m_y << " " << m_z << "\n"; return s.str();}
int m_x;
int m_y;
int m_z;
Point3Int operator+(const Point3Int& B) const {Point3Int P; P.m_x=m_x+B.m_x; P.m_y=m_y+B.m_y; P.m_z=m_z+B.m_z; return P;}
};
/// Function to compare two Point3Int to use Point3Int as map key.
struct CmpPoint3Int
{
bool operator()( const Point3Int& p1, const Point3Int& p2 ) const
{
if(p1.m_x < p2.m_x) return true;
if(p1.m_x > p2.m_x) return false;
if(p1.m_y < p2.m_y) return true;
if(p1.m_y > p2.m_y) return false;
if(p1.m_z < p2.m_z) return true;
if(p1.m_z > p2.m_z) return false;
return false;
}
};
/// Class to describe a 5D integer point.
/// This class can be used to describe a 5D integer point.
class Point5Int
{
public:
Point5Int();
Point5Int(int a, int b, int c, int d, int e) {m_a=a; m_b=b; m_c=c; m_d=d; m_e=e;};
~Point5Int(){};
std::string Str() {std::stringstream s; s << m_a << " " << m_b << " " << m_c << " " << m_d << " " << m_e << "\n"; return s.str();}
int m_a;
int m_b;
int m_c;
int m_d;
int m_e;
};
struct CmpPoint5IntKeys
{
bool operator()( const Point5Int& p1, const Point5Int& p2 ) const
{
if(p1.m_a < p2.m_a) return true;
if(p1.m_a > p2.m_a) return false;
if(p1.m_b < p2.m_b) return true;
if(p1.m_b > p2.m_b) return false;
if(p1.m_c < p2.m_c) return true;
if(p1.m_c > p2.m_c) return false;
if(p1.m_d < p2.m_d) return true;
if(p1.m_d > p2.m_d) return false;
if(p1.m_e < p2.m_e) return true;
if(p1.m_e > p2.m_e) return false;
return false;
}
};
class CountsStruct
{
public:
CountsStruct(int p=0, double c=0.0) {Position=p; Counts=c;}
~CountsStruct(){};
int Position;
double Counts;
};
bool thisGreaterOD2(const CountsStruct& e1, const CountsStruct& e2);
typedef std::map<Point5Int, double, CmpPoint5IntKeys> DistanceMap;
/// Class to represent point clouds.
/// This class can be used to handle (create, load, save, maipulate, etc) point clouds.
class PointCloud : public std::vector<Point3Dbl>
{
public:
PointCloud(){};
~PointCloud(){};
/// Make a base point cloud (origin, ex and ey)
/// This function creates the point cloud (0,0,0), (1,0,0), and (0,1,0).
void MakeBase(double Unit=1.0);
/// Assign a set of points to the cloud.
/// @param P the default value for all points
/// @param No the number of points
void AssignPoints(const Point3Dbl& P, int No);
/// Assign a set of random points.
/// Assign a set of random points to the cloud
/// @param Min the minimal possible value of a point component
/// @param Max the maximal possible value of a point component
/// @param No the number of points to be added
/// @param Mask a point that can prevent a certain dimension to be set by setting this dimension to zero
/// @param Append set to true to append PC to the object
void AssignRand(double Min, double Max, int No, bool Append=false, const Point3Dbl& Mask=Point3Dbl(1,1,1));
/// Add random noise to each point component.
/// @param Min the minimal possible value of noise addition
/// @param Max the maximal possible value of noise addition
/// @param Mask a point that can prevent a certain dimension to be set by setting this dimension to zero
void AddRand(double Min, double Max, const Point3Dbl& Mask=Point3Dbl(1,1,1));
/// Imports (and possibly appends) another point cloud.
/// @param PC the point cloud to be imported
/// @param Append set to true to append PC to the object
void ImportCloud(const PointCloud& PC, bool Append=false);
/// Convert to string.
/// Convert to string for input/output purposes
std::string Str() const;
/// Load.
int Load(std::string Name);
/// Save.
int Save(std::string Name) const;
/// A vector sum function.
void VectorSum(Point3Dbl& Sum) const;
/// A vector mean function.
void GetCenter(Point3Dbl& Center) const;
/// Get orientations
void GetOrientations(Point3Dbl& OriX, Point3Dbl& OriY) const;
};
/// Gets the squared euclidian distance between two point clouds.
double PClDistSqr(const PointCloud& A, const PointCloud& B);
/// Gets the euclidian distance of two point clouds.
double PClDist(const PointCloud& A, const PointCloud& B);
/// Frame class for coordinate systems.
/// The first three components are the translation offsets.
/// The fourth component is a rotation angle, valid in the interval [0.0,..,PI).
/// Components five and six are the spherical angles describing the rotation axis, Theta and Phi.
/// Theta is valid in the interval [0.0,..,PI] and Phi is valid in the interval (-PI,..,PI].
class Frame : public DblVector
{
public:
Frame(double tx=0.0, double ty=0.0, double tz=0.0, double rx=0.0, double ry=0.0, double rz=0.0); ///< Constructor.
~Frame(){}; ///< Destructor.
std::string Str() const;
void SetZero(){SetTranslation(0,0,0); SetRotation(0,0,0);} ///< Sets to zero (neutral) value.
void SetTranslation(const Point3Dbl& Trans); ///< Sets translation components.
void SetTranslation(double tx, double ty, double tz); ///< Sets translation components.
void SetRotation(const Point3Dbl& Rot); ///< Sets rotation components.
void SetRotation(double rx, double ry, double rz); ///< Sets rotation components.
int MakeFrameOriginDirectionsXY(const Point3Dbl& O, const Point3Dbl& EX, const Point3Dbl& EY);
int MakeFrameOriginDirectionsXZ(const Point3Dbl& O, const Point3Dbl& EX, const Point3Dbl& EZ);
int MakeFrameThreePoints(const Point3Dbl& p0, const Point3Dbl& p1, const Point3Dbl& p2);
void SetRandomTranslation(double Bound=0.1);
void SetRandomRotation(double Factor=0.1);
void SetRandomFrame(double Bound=0.1, double Factor=0.1); ///< Sets a random frame.
void GetT(Point3Dbl& T) const; ///< Get translation vector.
void GetR(Point3Dbl& R) const; ///< Get rotation vector.
double GetAlpha() {return (*this)[3];} ///< Get the rotation angle.
/// ToWorld performs first a right handed rotation around the rotation axis and
/// then applies the translation.
/// To Frame performs the inverse operation to ToWorld. This means first the data points
/// are translated in opposite direction (-t) and then rotated in opposite direction (-alpha)
/// around the rotation axis.
/// Translation is given by x = this[0], y = this[1], z = this[2]
/// Rotation angle alpha is given by alpha = this[3]
/// Spherical coordinates of rotation axis centered at the origin is given by theta = this[4], phi = this[5].
/// For an explanation of the spherical coordinate system see http://en.wikipedia.org/wiki/Spherical_coordinate_system
/// section 'Coordinate system conversion'
void ToWorld(const Point3Dbl& In, Point3Dbl& Out) const; ///< Convert to world coordinate system.
void ToWorld(Point3Dbl& P) const; ///< Convert to world coordinate system.
void ToWorld(double& x, double& y, double& z) const; ///< Convert to world coordinate system.
void ToFrame(const Point3Dbl& In, Point3Dbl& Out) const; ///< Convert from world to frame.
void ToFrame(Point3Dbl& P) const; ///< Convert from world to frame.
void ToFrame(double& x, double& y, double& z) const; ///< Convert from world to frame.
void Cloud2World(PointCloud& P) const; ///< Convert a point cloud to world coordinate system.
void Cloud2Frame(PointCloud& P) const; ///< Convert a point cloud from world to frame coordinate system.
void eX(Point3Dbl& EX) const;
void eY(Point3Dbl& EY) const;
void eZ(Point3Dbl& EZ) const;
/// Get a conversion frame from three matches.
/// This function gives a coordinate transformation between two frames.
/// The first match has to contain the origins of the two systems.
/// The triple has to be linearly independent.
/// @param OA the origin of cloud A
/// @param the second point of A
/// @param the third point of A
/// @param OB the origin of cloud B
/// @param the second point of B
/// @param the third point of B
/// todo: generalize such that the first point can be arbitrary
int GetFrameThreeMatches(const Point3Dbl& OA, const Point3Dbl& A1, const Point3Dbl& A2,
const Point3Dbl& OB, const Point3Dbl& B1, const Point3Dbl& B2);
/// Get a conversion frame from three matches. Gets the coordinate transformation without knowing the origín points.
/// Not implemented.
//int GetFrameFromTriple(const Point3Dbl& A0, const Point3Dbl& A1, const Point3Dbl& A2);
int GetFrameThreeMatchesNoOrigin(const Point3Dbl& a0, const Point3Dbl& a1, const Point3Dbl& a2,
const Point3Dbl& b0, const Point3Dbl& b1, const Point3Dbl& b2);
/// Get a frame conversion from A to B.
/// This function uses a "greedy" search over the six frame components to estimate a conversion frame between point cloud A and point cloud B.
/// Here the assumptions about the two point clouds are not strong.
/// However, two very "dissimilar" clouds can not be matched as good as clouds that are only translated and rotated relative to each other.
/// @param A the first point cloud A
/// @param B the second point cloud B
/// @param It number of iterations
/// @param Delta step width (at start)
/// @param Shrink shrinkage factor to reduce the step width Delta (Delta[n]=Delta[n-1]*Shrink)
double GetFrameNMatchesIt(const PointCloud& A, const PointCloud& B, int It=6, double Delta=0.1, double Shrink=0.1);
/// Get a frame from correspondence points including outliers.
int GetFrameRANSAC(const PointCloud& A, const PointCloud& B, int IterationsK, double ThreshT, int MinFitPointsD, int MinPointsN=3);
/// Get a mean frame by summing all origins, exs, and eys and applying Gram-Schmidt
int GetMeanFrame(Frame& A, Frame& B);
/// This function estimates a frame difference
double FrameDifferenceSimple(const Frame& A, double RotInfluence=ROT_FACTOR);
double FrameDifference(const Frame& A, double RotInfluence=ROT_FACTOR);
double Norm(double RotInfluence=ROT_FACTOR);
void LimitRotation();
int GetCentralFrame(const PointCloud& PCl);
int ToWorld(const Frame& A, Frame& B);
inline int ToWorld(Frame& A) {return ToWorld(A, A);};
int ToFrame(const Frame& A, Frame& B);
inline int ToFrame(Frame& A) {return ToFrame(A, A);};
void Invert();
};
/// Class to represent a frame list.
class FrameList : public std::list<Frame>
{
public:
std::string Str();
void QTClustering(double Eps, unsigned int MinN=1, bool UseMean=false);
};
/// A list of frames (x, y, z, alpha, beta, gamma) with additional information
class FrameStruct
{
public:
FrameStruct(){};
FrameStruct(Frame F, double S){m_F=F; m_S=S;};// m_u=u; m_v=v;}
~FrameStruct(){};
Frame m_F; ///< The coordinate frame.
double m_S; ///< Scalar that can be used to include a count or probability or error for the frame.
//double m_u;
//double m_v;
std::string Str();
};
bool FrameStructGreater(const FrameStruct& fs1, const FrameStruct& fs2);
/// A list of frame structs, each frame represents a vote
class VotingList : public std::vector<FrameStruct>
{
public:
VotingList(){m_SumS=0;};
VotingList(const FrameStruct& FS) {push_back(FS); m_SumS=FS.m_S;};
~VotingList(){};
/// Returns the center of gravity of all frames.
/// @param center The center of gravity
/// @return Return code
unsigned long GetCenterOfGravity(FrameStruct *center);
inline double AppendVote(const FrameStruct& FS){push_back(FS); m_SumS+=FS.m_S; return m_SumS;};
void GetCentralFrameStruct(FrameStruct& FS);
void GetCentralFrameStructDensity(FrameStruct& FS, double Eps, bool Mean=false);
std::string Str();
double m_SumS;
};
void GeometryTestFrames();
void GeometryTestMeanNorm();
} // end namespace ipa_Utils
#endif // __THREEDUTILS_H__
|
[
"[email protected]"
] |
[
[
[
1,
596
]
]
] |
3d7e4fc02b2c80e3e068f85b4dfcb57ca0a7f02b
|
0f40e36dc65b58cc3c04022cf215c77ae31965a8
|
/src/apps/vis/base/visualization.h
|
737eeb7b8d41ea7b20a889a4b9355410a51ddc0f
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
venkatarajasekhar/shawn-1
|
08e6cd4cf9f39a8962c1514aa17b294565e849f8
|
d36c90dd88f8460e89731c873bb71fb97da85e82
|
refs/heads/master
| 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,078 |
h
|
/************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#ifndef __SHAWN_TUBSAPPS_VIS_VISUALIZATION_H
#define __SHAWN_TUBSAPPS_VIS_VISUALIZATION_H
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/elements/vis_element.h"
#include "sys/util/handle_keeper.h"
#include "apps/vis/elements/vis_element.h"
#include "apps/vis/elements/vis_drawable.h"
#include "apps/vis/elements/vis_drawable_node.h"
#include "apps/vis/elements/vis_camera.h"
#include "apps/vis/elements/vis_group_element.h"
#include "apps/vis/base/vis_needs_cairo.h"
#include "apps/vis/base/vis_context.h"
#include <map>
#include <iostream>
#include <vector>
namespace shawn
{ class SimulationController; class World; }
namespace vis
{
DECLARE_HANDLES( Visualization );
/** \brief Visualization main class.
*
* This class represents the visualization inside Shawn. It's the base class,
* which manages all visualization issues.
*/
class Visualization
: public shawn::KeeperManaged, public shawn::NodeChangeListener
{
public:
typedef std::map<std::string,ElementHandle> ElementMap;
typedef std::vector<DrawableHandle> DrawableList;
///@name Constructor/Destructor
///@{
Visualization( const std::string& );
virtual ~Visualization();
///@}
///@name Getter/Setter
///@{
/**
* Returns the name of the visualization.
*/
virtual std::string name( void ) const throw();
/**
* Shot description of the KeeperManaged subclass.
*/
virtual std::string description( void ) const throw();
/**
* Returns the camera of the visualization.
*/
inline Camera& camera_w( void ) throw()
{ assert( elem_camera_ != NULL ); return *elem_camera_; }
/**
* Returns the camera of the visualization (constant).
*/
inline const Camera& camera( void ) const throw()
{ assert( elem_camera_ != NULL ); return *elem_camera_; }
/**
* Sets the network world to draw.
*/
virtual void set_world( const shawn::World& ) throw();
/**
* Returns the element with the given name.
*
* \param n Element name.
*/
inline ElementHandle element_w( const std::string& n ) throw()
{
ElementMap::const_iterator it = elements_.find(n);
return it==elements_.end()
? NULL
: it->second;
}
/**
* Returns the constant element with the given name.
*
* \param n Element name.
*/
inline ConstElementHandle element( const std::string& n ) const throw()
{
ElementMap::const_iterator it = elements_.find(n);
return it==elements_.end()
? NULL
: it->second;
}
/**
* Returns the world, that is currently associated with the visualization
* (constant).
*/
inline const shawn::World& world( void ) const throw()
{ assert( world_ != NULL ); return *world_; }
/**
* Returns a map of all Vis elements, that are derived from the
* vis::Element class.
*/
inline ElementMap& elements( void ) throw()
{ return elements_; }
///@}
/**
* Base initialization.
*/
virtual void init( void ) throw();
/**
* Adds a new element to the visualization.
*/
virtual void add_element( const ElementHandle& )
throw( std::runtime_error );
/**
* Starts the drawing process. Draws all drawable elements iteratively.
*/
virtual void draw( cairo_t*, double, const Context& )
const throw( std::runtime_error );
/// NodeChangeListener implementations
virtual void node_added(shawn::Node &) throw();
virtual void node_removed(shawn::Node &) throw();
virtual void id_changed(int,int) throw();
virtual bool invalidate(void) throw();
protected:
/**
* Creates a camera instance.
*/
virtual Camera* init_camera( void ) throw();
private:
/// Visualization name.
std::string name_;
/// Network world.
const shawn::World* world_;
/// Camera instance.
Camera* elem_camera_;
/// Map of all vis::Element objects.
ElementMap elements_;
/// List of all vis::Drawable objects.
mutable DrawableList drawables_;
};
}
#endif
#endif
|
[
"[email protected]"
] |
[
[
[
1,
164
]
]
] |
38473ee00b6eb7b06d96179a245907afd4b155f9
|
b14d5833a79518a40d302e5eb40ed5da193cf1b2
|
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Transcoders/Win32/Win32TransService.hpp
|
0c8ce1ec40cffd518ae74dbac4dcd4085b9c98ab
|
[
"Apache-2.0"
] |
permissive
|
andyburke/bitflood
|
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
|
fca6c0b635d07da4e6c7fbfa032921c827a981d6
|
refs/heads/master
| 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,112 |
hpp
|
/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: Win32TransService.hpp,v $
* Revision 1.8 2004/09/08 13:56:47 peiyongz
* Apache License Version 2.0
*
* Revision 1.7 2003/12/24 15:24:15 cargilld
* More updates to memory management so that the static memory manager.
*
* Revision 1.6 2003/05/17 16:32:18 knoaman
* Memory manager implementation : transcoder update.
*
* Revision 1.5 2003/05/15 18:47:07 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.4 2003/03/07 18:15:58 tng
* Return a reference instead of void for operator=
*
* Revision 1.3 2002/11/04 15:14:34 tng
* C++ Namespace Support.
*
* Revision 1.2 2002/04/09 15:44:00 knoaman
* Add lower case string support.
*
* Revision 1.1.1.1 2002/02/01 22:22:37 peiyongz
* sane_include
*
* Revision 1.10 2000/05/09 00:22:45 andyh
* Memory Cleanup. XMLPlatformUtils::Terminate() deletes all lazily
* allocated memory; memory leak checking tools will no longer report
* that leaks exist. (DOM GetElementsByTagID temporarily removed
* as part of this.)
*
* Revision 1.9 2000/03/18 00:00:04 roddey
* Initial updates for two way transcoding support
*
* Revision 1.8 2000/03/07 23:45:36 roddey
* First cut for additions to Win32 xcode. Based very loosely on a
* prototype from Eric Ulevik.
*
* Revision 1.7 2000/03/02 19:55:36 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.6 2000/02/06 07:48:34 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/25 22:49:58 roddey
* Moved the supportsSrcOfs() method from the individual transcoder to the
* transcoding service, where it should have been to begin with.
*
* Revision 1.4 2000/01/25 19:19:09 roddey
* Simple addition of a getId() method to the xcode and netacess abstractions to
* allow each impl to give back an id string.
*
* Revision 1.3 1999/12/18 00:22:33 roddey
* Changes to support the new, completely orthagonal, transcoder architecture.
*
* Revision 1.2 1999/12/15 19:44:02 roddey
* Now implements the new transcoding abstractions, with separate interface
* classes for XML transcoders and local code page transcoders.
*
* Revision 1.1.1.1 1999/11/09 01:06:06 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:35 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef WIN32TRANSSERVICE_HPP
#define WIN32TRANSSERVICE_HPP
#include <xercesc/util/TransService.hpp>
#include <xercesc/util/RefHashTableOf.hpp>
#include <windows.h>
XERCES_CPP_NAMESPACE_BEGIN
class CPMapEntry;
//---------------------------------------------------------------------------
//
// class Win32TransService
//
//---------------------------------------------------------------------------
class XMLUTIL_EXPORT Win32TransService : public XMLTransService
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
Win32TransService();
virtual ~Win32TransService();
// -----------------------------------------------------------------------
// Implementation of the virtual transcoding service API
// -----------------------------------------------------------------------
virtual int compareIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
);
virtual int compareNIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars
);
virtual const XMLCh* getId() const;
virtual bool isSpace(const XMLCh toCheck) const;
virtual XMLLCPTranscoder* makeNewLCPTranscoder();
virtual bool supportsSrcOfs() const;
virtual void upperCase(XMLCh* const toUpperCase) const;
virtual void lowerCase(XMLCh* const toLowerCase) const;
protected :
// -----------------------------------------------------------------------
// Protected virtual methods, implemented in Win32TransService2.cpp
// -----------------------------------------------------------------------
virtual XMLTranscoder* makeNewXMLTranscoder
(
const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
, MemoryManager* const manager
);
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
Win32TransService(const Win32TransService&);
Win32TransService& operator=(const Win32TransService&);
// This is a hash table of entries which map encoding names to their
// Windows specific code pages. The code page allows us to create
// transcoders for those encodings. The encoding names come from XML
// files.
//
// This map is shared unsynchronized among all threads of the process,
// which is cool since it will be read only once its initialized.
static bool isAlias(const HKEY encodingKey
, char* const aliasBuf = 0
, const unsigned int nameBufSz = 0);
RefHashTableOf<CPMapEntry> *fCPMap;
};
//---------------------------------------------------------------------------
//
// class Win32Transcoder
//
//---------------------------------------------------------------------------
class XMLUTIL_EXPORT Win32Transcoder : public XMLTranscoder
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
Win32Transcoder
(
const XMLCh* const encodingName
, const unsigned int winCP
, const unsigned int ieCP
, const unsigned int blockSize
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
~Win32Transcoder();
// -----------------------------------------------------------------------
// Implementation of the virtual transcoder interface
// -----------------------------------------------------------------------
virtual unsigned int transcodeFrom
(
const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes
);
virtual unsigned int transcodeTo
(
const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options
);
virtual bool canTranscodeTo
(
const unsigned int toCheck
) const;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
Win32Transcoder(const Win32Transcoder&);
Win32Transcoder& operator=(const Win32Transcoder&);
// -----------------------------------------------------------------------
// Private data members
//
// fIECP
// This is the internet explorer code page for this encoding.
//
// fWinCP
// This is the windows code page for this encoding.
// -----------------------------------------------------------------------
unsigned int fIECP;
unsigned int fWinCP;
};
//---------------------------------------------------------------------------
//
// class Win32LCPTranscoder
//
//---------------------------------------------------------------------------
class XMLUTIL_EXPORT Win32LCPTranscoder : public XMLLCPTranscoder
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
Win32LCPTranscoder();
~Win32LCPTranscoder();
// -----------------------------------------------------------------------
// Implementation of the virtual transcoder interface
// -----------------------------------------------------------------------
virtual unsigned int calcRequiredSize(const char* const srcText
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
virtual unsigned int calcRequiredSize(const XMLCh* const srcText
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
virtual char* transcode(const XMLCh* const toTranscode);
virtual char* transcode(const XMLCh* const toTranscode,
MemoryManager* const manager);
virtual XMLCh* transcode(const char* const toTranscode);
virtual XMLCh* transcode(const char* const toTranscode,
MemoryManager* const manager);
virtual bool transcode
(
const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
virtual bool transcode
(
const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxChars
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
Win32LCPTranscoder(const Win32LCPTranscoder&);
Win32LCPTranscoder& operator=(const Win32LCPTranscoder&);
};
XERCES_CPP_NAMESPACE_END
#endif
|
[
"[email protected]"
] |
[
[
[
1,
322
]
]
] |
fd285ec3dc4948b3e5cf504a6e77441e7f3cabb7
|
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
|
/src/qwt/src/moc/moc_qwt_slider.cpp
|
5a4f898bb674913198d7df91608ec0adf160a78d
|
[] |
no_license
|
ipodyaco/prorata
|
bd52105499c3fad25781d91952def89a9079b864
|
1f17015d304f204bd5f72b92d711a02490527fe6
|
refs/heads/master
| 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,174 |
cpp
|
/****************************************************************************
** Meta object code from reading C++ file 'qwt_slider.h'
**
** Created: ??? ?? 25 15:38:55 2006
** by: The Qt Meta Object Compiler version 59 (Qt 4.1.4)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../include/qwt_slider.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qwt_slider.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 59
#error "This file was generated using the moc from 4.1.4. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
static const uint qt_meta_data_QwtSlider[] = {
// content:
1, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
5, 10, // properties
2, 25, // enums/sets
// properties: name, type, flags
19, 10, 0x0009510b,
41, 33, 0x0009510b,
53, 49, 0x02095103,
65, 49, 0x02095103,
76, 49, 0x02095103,
// enums: name, flags, count, data
10, 0x0, 5, 33,
33, 0x0, 3, 43,
// enum data: key, value
88, uint(QwtSlider::None),
93, uint(QwtSlider::Left),
98, uint(QwtSlider::Right),
104, uint(QwtSlider::Top),
108, uint(QwtSlider::Bottom),
115, uint(QwtSlider::BgTrough),
124, uint(QwtSlider::BgSlot),
131, uint(QwtSlider::BgBoth),
0 // eod
};
static const char qt_meta_stringdata_QwtSlider[] = {
"QwtSlider\0ScalePos\0scalePosition\0BGSTYLE\0bgStyle\0int\0thumbLength\0"
"thumbWidth\0borderWidth\0None\0Left\0Right\0Top\0Bottom\0BgTrough\0"
"BgSlot\0BgBoth\0"
};
const QMetaObject QwtSlider::staticMetaObject = {
{ &QwtAbstractSlider::staticMetaObject, qt_meta_stringdata_QwtSlider,
qt_meta_data_QwtSlider, 0 }
};
const QMetaObject *QwtSlider::metaObject() const
{
return &staticMetaObject;
}
void *QwtSlider::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QwtSlider))
return static_cast<void*>(const_cast<QwtSlider*>(this));
if (!strcmp(_clname, "QwtAbstractScale"))
return static_cast<QwtAbstractScale*>(const_cast<QwtSlider*>(this));
return QwtAbstractSlider::qt_metacast(_clname);
}
int QwtSlider::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QwtAbstractSlider::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
#ifndef QT_NO_PROPERTIES
if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< ScalePos*>(_v) = scalePosition(); break;
case 1: *reinterpret_cast< BGSTYLE*>(_v) = bgStyle(); break;
case 2: *reinterpret_cast< int*>(_v) = thumbLength(); break;
case 3: *reinterpret_cast< int*>(_v) = thumbWidth(); break;
case 4: *reinterpret_cast< int*>(_v) = borderWidth(); break;
}
_id -= 5;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 0: setScalePosition(*reinterpret_cast< ScalePos*>(_v)); break;
case 1: setBgStyle(*reinterpret_cast< BGSTYLE*>(_v)); break;
case 2: setThumbLength(*reinterpret_cast< int*>(_v)); break;
case 3: setThumbWidth(*reinterpret_cast< int*>(_v)); break;
case 4: setBorderWidth(*reinterpret_cast< int*>(_v)); break;
}
_id -= 5;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 5;
}
#endif // QT_NO_PROPERTIES
return _id;
}
|
[
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
] |
[
[
[
1,
121
]
]
] |
737e0cd034ec210c9186a19f6aabaef95ddfbdbc
|
7abf4cf96f83aff6545d94b6454b32edc01aaab6
|
/WebKit/win/COMVariantSetter.h
|
76ca927110c9c1785ce50d453354d6e52545aebc
|
[
"BSD-3-Clause"
] |
permissive
|
marshall/webkit_titanium
|
07a3a3e9ae35330c4b3195c0c456b73f61c0d258
|
bb47d13ca8cb90d482cedcf359c8a0114578e151
|
refs/heads/master
| 2021-01-22T05:10:11.267990 | 2009-03-05T17:19:29 | 2009-03-05T17:19:29 | 118,904 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,898 |
h
|
/*
* Copyright (C) 2007, 2008 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. ``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
* 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 COMVariantSetter_h
#define COMVariantSetter_h
#include <WebCore/BString.h>
#include <WebCore/COMPtr.h>
#include <wtf/Assertions.h>
namespace WebCore {
class String;
}
template<typename T> struct COMVariantSetter {};
template<typename T> struct COMVariantSetterBase
{
static inline VARENUM variantType(const T&)
{
return COMVariantSetter<T>::VariantType;
}
};
template<> struct COMVariantSetter<WebCore::String> : COMVariantSetterBase<WebCore::String>
{
static const VARENUM VariantType = VT_BSTR;
static void setVariant(VARIANT* variant, const WebCore::String& value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
V_VT(variant) = VariantType;
V_BSTR(variant) = WebCore::BString(value).release();
}
};
template<> struct COMVariantSetter<unsigned long long> : COMVariantSetterBase<unsigned long long>
{
static const VARENUM VariantType = VT_UI8;
static void setVariant(VARIANT* variant, unsigned long long value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
V_VT(variant) = VariantType;
V_UI8(variant) = value;
}
};
template<> struct COMVariantSetter<int> : COMVariantSetterBase<int>
{
static const VARENUM VariantType = VT_I4;
static void setVariant(VARIANT* variant, int value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
V_VT(variant) = VariantType;
V_I4(variant) = value;
}
};
template<typename T> struct COMVariantSetter<COMPtr<T> > : COMVariantSetterBase<COMPtr<T> >
{
static const VARENUM VariantType = VT_UNKNOWN;
static void setVariant(VARIANT* variant, const COMPtr<T>& value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
V_VT(variant) = VariantType;
V_UNKNOWN(variant) = value.get();
value->AddRef();
}
};
template<typename COMType, typename UnderlyingType>
struct COMIUnknownVariantSetter : COMVariantSetterBase<UnderlyingType>
{
static const VARENUM VariantType = VT_UNKNOWN;
static void setVariant(VARIANT* variant, const UnderlyingType& value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
V_VT(variant) = VariantType;
V_UNKNOWN(variant) = COMType::createInstance(value);
}
};
class COMVariant {
public:
COMVariant()
{
::VariantInit(&m_variant);
}
template<typename UnderlyingType>
COMVariant(UnderlyingType value)
{
::VariantInit(&m_variant);
COMVariantSetter<UnderlyingType>::setVariant(&m_variant, value);
}
~COMVariant()
{
::VariantClear(&m_variant);
}
COMVariant(const COMVariant& other)
{
::VariantInit(&m_variant);
other.copyTo(&m_variant);
}
COMVariant& operator=(const COMVariant& other)
{
other.copyTo(&m_variant);
return *this;
}
void copyTo(VARIANT* dest) const
{
::VariantCopy(dest, const_cast<VARIANT*>(&m_variant));
}
VARENUM variantType() const { return static_cast<VARENUM>(V_VT(&m_variant)); }
private:
VARIANT m_variant;
};
template<> struct COMVariantSetter<COMVariant>
{
static inline VARENUM variantType(const COMVariant& value)
{
return value.variantType();
}
static void setVariant(VARIANT* variant, const COMVariant& value)
{
ASSERT(V_VT(variant) == VT_EMPTY);
value.copyTo(variant);
}
};
#endif // COMVariantSetter
|
[
"[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc",
"[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc"
] |
[
[
[
1,
73
],
[
86,
171
]
],
[
[
74,
85
]
]
] |
a8e1576c082ff2959735c8de51ed171395c9df6e
|
d1dc408f6b65c4e5209041b62cd32fb5083fe140
|
/src/ini.cpp
|
be1f5bec2bc7c378eb20d876e173d546b597333a
|
[] |
no_license
|
dmitrygerasimuk/dune2themaker-fossfriendly
|
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
|
89a6920b216f3964241eeab7cf1a631e1e63f110
|
refs/heads/master
| 2020-03-12T03:23:40.821001 | 2011-02-19T12:01:30 | 2011-02-19T12:01:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 74,663 |
cpp
|
/*
Dune II - The Maker
Author : Stefan Hendriks
Contact: [email protected]
Website: http://dune2themaker.fundynamic.com
2001 - 2009 (c) code by Stefan Hendriks
*/
#include "include/d2tmh.h"
using namespace std;
/*
Read a line in the INI file and put it into currentLine
*/
inline bool caseInsCharCompareN(char a, char b) {
return(toupper(a) == toupper(b));
}
bool caseInsCompare(const string& s1, const string& s2) {
return((s1.size( ) == s2.size( )) &&
equal(s1.begin( ), s1.end( ), s2.begin( ), caseInsCharCompareN));
}
// Reads out an entire sentence and returns it
void INI_Sentence(FILE *f, char result[MAX_LINE_LENGTH])
{
char ch;
int pos=0;
// clear out entire string
for (int i=0; i < MAX_LINE_LENGTH;i++)
result[i] = '\0';
while ((feof(f) == 0) && ((ch=fgetc(f)) != '\n'))
{
result[pos]=ch;
pos++;
// do not allow strings greater then 80 characters. This check prevents a crash for
// users who do exceed the limit.
if (pos> (MAX_LINE_LENGTH-1))
break;
putchar(ch);
}
}
/*********************************************************************************/
// Reads out INPUT , will check for a [ at [0] and then checks till ], it will fill section[]
// with the chars in between. So : [MAP] -> section = 'MAP'. Use function INI_SectionType(..)
// to get the correct ID for that.
void INI_Section(char input[MAX_LINE_LENGTH], char section[30]) {
int pos=0;
int end_pos=-1;
memset(section, '\0', sizeof(section));
// check if the first character is a '['
if (input[0] == '[') {
pos=1; // Begin at character 1
// find the ending ]
while (pos < (MAX_LINE_LENGTH-1)) {
if (input[pos] == ']') {
end_pos=pos-1;
break;
}
pos++;
}
if (end_pos > 1 && end_pos < 29) {
for (int wc=0; wc < end_pos; wc++) {
section[wc]=input[wc+1];
}
section[end_pos]='\0'; // terminate string
}
}
}
// Reads out INPUT and will check for an '=' Everything at the left of the
// '=' IS a word and will be put in 'word[]'. Use function INI_WordType(char word[25]) to get
// the correct ID tag.
void INI_Word(char input[MAX_LINE_LENGTH], char word[25]) {
int word_pos = INI_GetPositionOfCharacter(input, '=');
memset(word, '\0', sizeof(word));
if (word_pos > -1 && word_pos < 23) {
for (int wc=0; wc < word_pos; wc++) {
word[wc]=input[wc];
}
word[word_pos]='\0'; // terminate string
}
}
/**
* Return true when string "toFind" is in source string. Else return false.
*
* @param source
* @param toFind
* @return
*/
bool isInString(string source, string toFind) {
string::size_type loc = source.find( toFind , 0 );
if( loc == 0 ) {
return true;
}
return false; // not found in string
}
string INI_SceneFileToScene(string scenefile) {
// wsa / data
if (isInString(scenefile, "HARVEST.WSA")) return "harvest";
if (isInString(scenefile, "IX.WSA")) return "ix";
if (isInString(scenefile, "SARDUKAR.WSA")) return "sardukar";
if (isInString(scenefile, "PALACE.WSA")) return "palace";
if (isInString(scenefile, "REPAIR.WSA")) return "repair";
if (isInString(scenefile, "HVYFTRY.WSA")) return "hvyftry";
if (isInString(scenefile, "HEADQRTS.WSA")) return "headqrts";
if (isInString(scenefile, "QUAD.WSA")) return "quad";
if (isInString(scenefile, "LTANK.WSA")) return "ltank";
char msg[255];
sprintf(msg, "Failed to map dune 2 scenefile [%s] to a d2tm scene file", scenefile.c_str());
logbook(msg);
return "unknown";
}
int INI_StructureType(string structureName) {
if (isInString(structureName, "WINDTRAP")) return WINDTRAP;
if (isInString(structureName, "PALACE")) return PALACE;
if (isInString(structureName, "HEAVYFACTORY")) return HEAVYFACTORY;
if (isInString(structureName, "LIGHTFACTORY")) return LIGHTFACTORY;
if (isInString(structureName, "CONSTYARD")) return CONSTYARD;
if (isInString(structureName, "SILO")) return SILO;
if (isInString(structureName, "HIGHTECH")) return HIGHTECH;
if (isInString(structureName, "IX")) return IX;
if (isInString(structureName, "REPAIR")) return REPAIR;
if (isInString(structureName, "RADAR")) return RADAR;
if (isInString(structureName, "REFINERY")) return REFINERY;
if (isInString(structureName, "WOR")) return WOR;
if (isInString(structureName, "BARRACKS")) return BARRACKS;
if (isInString(structureName, "STARPORT")) return STARPORT;
if (isInString(structureName, "TURRET")) return TURRET;
if (isInString(structureName, "ROCKETTURRET")) return RTURRET;
if (isInString(structureName, "STARPORT")) return STARPORT;
if (isInString(structureName, "SLAB")) return SLAB1;
if (isInString(structureName, "4SLAB")) return SLAB4;
if (isInString(structureName, "WALL")) return WALL;
assert(false); // no recognition is fail.
return 0; // just in case some miracle happened, we need to go on and not crash everything.
}
// Reads out word[], checks structure type, and returns actual source-id
int INI_StructureType(char word[256]) {
string wordAsString(word);
return INI_StructureType(wordAsString);
}
// Reads out word[], does a string compare and returns type id
int INI_WordType(char word[25], int section)
{
// char msg[255];
// memset(msg, 0, sizeof(msg));
// sprintf(msg, "Going to find word-type for [%s]", word);
// logbook(msg);
if (section == SEC_REGION)
{
if (strcmp(word, "Region") == 0)
return WORD_REGION;
if (strcmp(word, "RegionConquer") == 0)
return WORD_REGIONCONQUER;
if (strcmp(word, "House") == 0)
return WORD_REGIONHOUSE;
if (strcmp(word, "Text") == 0)
return WORD_REGIONTEXT;
if (strcmp(word, "Select") == 0)
return WORD_REGIONSELECT;
return WORD_NONE;
}
if (section == INI_SCEN ||
section == INI_DESCRIPTION ||
section == INI_BRIEFING ||
section == INI_ADVICE ||
section == INI_LOSE ||
section == INI_WIN )
{
if (strcmp(word, "Number") == 0)
return WORD_NUMBER;
if (strcmp(word, "Text") == 0)
return WORD_REGIONTEXT;
return WORD_NONE;
}
if (section == INI_SKIRMISH)
{
if (strcmp(word, "Title") == 0)
return WORD_MAPNAME;
if (strcmp(word, "StartCell") == 0)
return WORD_STARTCELL;
}
if (section == INI_GAME)
{
if (strcmp(word, "ModId") == 0)
return WORD_MODID;
}
else if (section == INI_BASIC)
{
if (strcmp(word, "CursorPos") == 0)
return WORD_FOCUS;
if (strcmp(word, "BriefPicture") == 0)
return WORD_BRIEFPICTURE;
}
else if (section >= INI_HOUSEATREIDES && section <= INI_HOUSEMERCENARY)
{
if (strcmp(word, "Team") == 0)
return WORD_TEAM;
if (strcmp(word, "Credits") == 0)
return WORD_CREDITS;
if (strcmp(word, "Quota") == 0)
return WORD_QUOTA;
if (strcmp(word, "Brain") == 0)
return WORD_BRAIN;
//if (strcmp(word, "Skill") == 0)
//return WORD_SKILL;
if (strcmp(word, "House") == 0)
return WORD_HOUSE;
if (strcmp(word, "Focus") == 0)
return WORD_FOCUS;
}
/*
else if (section == INI_MENU)
{
if (strcmp(word, "TitleBitmap") == 0)
return WORD_TITLEBITMAP;
if (strcmp(word, "ClickSound") == 0)
return WORD_MENUCLICKSOUND;
}
else if (section == INI_MOD)
{
// Title of mod
if (strcmp(word, "Title") == 0)
return WORD_TITLE;
// Version of mod
if (strcmp(word, "Version") == 0)
return WORD_VERSION;
// Dir of mod
if (strcmp(word, "Dir") == 0)
return WORD_DIR;
}
else if (section == INI_SIDEBAR)
{
if (strcmp(word, "ColorRed") == 0)
return WORD_RED;
if (strcmp(word, "ColorBlue") == 0)
return WORD_BLUE;
if (strcmp(word, "ColorGreen") == 0)
return WORD_GREEN;
}
else if (section == INI_MOUSE)
{
// normal mouse
if (strcmp(word, "Normal") == 0)
return WORD_MOUSENORMAL;
// cannot move
if (strcmp(word, "CannotMove") == 0)
return WORD_MOUSENOMOVE;
// Move
if (strcmp(word, "Move") == 0)
return WORD_MOUSEMOVE;
// Attack
if (strcmp(word, "Attack") == 0)
return WORD_MOUSEATTACK;
// Deploy
if (strcmp(word, "Deploy") == 0)
return WORD_MOUSEDEPLOY;
}*/
else if (section == INI_MAP)
{
// When reading [MAP], interpet the 'width' and 'height' for default width and height
// for the Map Editor
// Map width
if (strcmp(word, "Width") == 0)
return WORD_MAPWIDTH;
// Map heigth
if (strcmp(word, "Height") == 0)
return WORD_MAPHEIGHT;
// Dune II scens have a seed
if (strcmp(word, "Seed") == 0)
return WORD_MAPSEED;
// Dune II scens have spice blooms
if (strcmp(word, "Bloom") == 0)
return WORD_MAPBLOOM;
// Dune II scens have spice blooms
if (strcmp(word, "Field") == 0)
return WORD_MAPFIELD;
}
else if (section == INI_BULLETS)
{
// Bitmap
if (strcmp(word, "Bitmap") == 0)
return WORD_BITMAP;
// Dead Animation Bitmap
if (strcmp(word, "BitmapExplosion") == 0)
return WORD_BITMAP_DEAD;
// Bitmap width
if (strcmp(word, "BitmapWidth") == 0)
return WORD_BITMAP_WIDTH;
// Frames
if (strcmp(word, "BitmapFrames") == 0)
return WORD_BITMAP_FRAMES;
// Dead frames
if (strcmp(word, "BitmapExplFrames") == 0)
return WORD_BITMAP_DEADFRAMES;
// Damage
if (strcmp(word, "Damage") == 0)
return WORD_DAMAGE;
// Definition
if (strcmp(word, "Definition") == 0)
return WORD_DEFINITION;
if (strcmp(word, "Sound") == 0)
return WORD_SOUND;
}
else if (section == INI_STRUCTURES)
{
// HitPoints
if (strcmp(word, "HitPoints") == 0)
return WORD_HITPOINTS;
// 'getting fixed 'HitPoints
if (strcmp(word, "FixPoints") == 0)
return WORD_FIXHP;
// Power drain
if (strcmp(word, "PowerDrain") == 0)
return WORD_POWERDRAIN;
// Power give
if (strcmp(word, "PowerGive") == 0)
return WORD_POWERGIVE;
// Cost
if (strcmp(word, "Cost") == 0)
return WORD_COST;
// Build time
if (strcmp(word, "BuildTime") == 0)
return WORD_BUILDTIME;
}
else if (section == INI_UNITS)
{
// Bitmap
if (strcmp(word, "Bitmap") == 0)
return WORD_BITMAP;
// TOP Bitmap
if (strcmp(word, "BitmapTop") == 0)
return WORD_BITMAP_TOP;
// ICON Bitmap
if (strcmp(word, "Icon") == 0)
return WORD_ICON;
// WIDTH and HEIGHT of a bitmap
if (strcmp(word, "BitmapWidth") == 0)
return WORD_BITMAP_WIDTH;
// Bitmap Height
if (strcmp(word, "BitmapHeight") == 0)
return WORD_BITMAP_HEIGHT;
// HitPoints
if (strcmp(word, "HitPoints") == 0)
return WORD_HITPOINTS;
// Cost
if (strcmp(word, "Cost") == 0)
return WORD_COST;
// Bullet Type
if (strcmp(word, "BulletType") == 0)
return WORD_BULLETTYPE;
// Move speed
if (strcmp(word, "MoveSpeed") == 0)
return WORD_MOVESPEED;
// Turn speed
if (strcmp(word, "TurnSpeed") == 0)
return WORD_TURNSPEED;
// Attack frequency
if (strcmp(word, "AttackFrequency") == 0)
return WORD_ATTACKFREQ;
// Sight
if (strcmp(word, "Sight") == 0)
return WORD_SIGHT;
// Range
if (strcmp(word, "Range") == 0)
return WORD_RANGE;
// Build time
if (strcmp(word, "BuildTime") == 0)
return WORD_BUILDTIME;
// Description
if (strcmp(word, "Description") == 0)
return WORD_DESCRIPTION;
// BOOLEANS
if (strcmp(word, "IsHarvester") == 0)
return WORD_ISHARVESTER;
if (strcmp(word, "SecondShot") == 0)
return WORD_SECONDSHOT;
if (strcmp(word, "IsInfantry") == 0)
return WORD_ISINFANTRY;
if (strcmp(word, "IsAirborn") == 0)
return WORD_ISAIRBORN;
if (strcmp(word, "AbleToCarry") == 0)
return WORD_ABLETOCARRY;
if (strcmp(word, "FreeRoam") == 0)
return WORD_FREEROAM;
// what structure type produces this kind of unit?
if (strcmp(word, "Producer") == 0) return WORD_PRODUCER;
// HARVESTER
if (strcmp(word, "MaxCredits") == 0) return WORD_HARVESTLIMIT;
if (strcmp(word, "HarvestSpeed") == 0) return WORD_HARVESTSPEED;
if (strcmp(word, "HarvestAmount") == 0) return WORD_HARVESTAMOUNT;
}
else if (section == INI_TEAMS)
{
// SwapColor
if (strcmp(word, "SwapColor") == 0)
return WORD_SWAPCOLOR;
// Red MiniMap value
if (strcmp(word, "MapColorRed") == 0)
return WORD_HOUSE_RED;
// Green MiniMap value
if (strcmp(word, "MapColorGreen") == 0)
return WORD_HOUSE_GREEN;
// Blue MiniMap value
if (strcmp(word, "MapColorBlue") == 0)
return WORD_HOUSE_BLUE;
}
/*
else if (section == INI_ICONS)
{
// Process all Icons here
if (strlen(word) > 1)
return WORD_ICONID;
else
return WORD_NONE;
}
else if (section == INI_BITMAPS)
{
// Process all Bitmaps here
if (strlen(word) > 1)
return WORD_BITMAPID;
else
return WORD_NONE;
}*/
else if (section == INI_STRUCTURES)
{
if (strlen(word) > 1)
{
// Structure properties
if (strcmp(word, "PreBuild") == 0)
return WORD_PREBUILD;
if (strcmp(word, "Description") == 0)
return WORD_DESCRIPTION;
if (strcmp(word, "Power") == 0)
return WORD_POWER; // What power it takes
}
else
return WORD_NONE;
}
else if (section == INI_HOUSES)
{
// each house has properties..
if (strcmp(word, "ColorR") == 0)
return WORD_RED;
if (strcmp(word, "ColorG") == 0)
return WORD_GREEN;
if (strcmp(word, "ColorB") == 0)
return WORD_BLUE;
// and specific stuff:
if (strcmp(word, "FirePower") == 0)
return WORD_FIREPOWER;
if (strcmp(word, "FireRate") == 0)
return WORD_FIRERATE;
if (strcmp(word, "StructPrice") == 0)
return WORD_STRUCTPRICE;
if (strcmp(word, "UnitPrice") == 0)
return WORD_UNITPRICE;
if (strcmp(word, "Speed") == 0)
return WORD_SPEED;
if (strcmp(word, "BuildSpeed") == 0)
return WORD_BUILDSPEED;
if (strcmp(word, "HarvestSpeed") == 0)
return WORD_HARVESTSPEED;
if (strcmp(word, "DumpSpeed") == 0)
return WORD_DUMPSPEED;
}
else if (section == INI_SETTINGS)
{
if (strcmp(word, "FullScreen") == 0) return WORD_FULLSCREEN;
if (strcmp(word, "ScreenWidth") == 0) return WORD_SCREENWIDTH;
if (strcmp(word, "ScreenHeight") == 0) return WORD_SCREENHEIGHT;
if (strcmp(word, "MP3Music") == 0) return WORD_MP3MUSIC;
}
return WORD_NONE;
}
// Scenario section types
int SCEN_INI_SectionType(char section[30], int last)
{
// if (strcmp(section, "PLAYERS") == 0)
// return INI_PLAYER;
//if (strcmp(section, "MAP") == 0)
//return INI_TERRAIN;
if (strcmp(section, "UNITS") == 0)
return INI_UNITS;
if (strcmp(section, "SKIRMISH") == 0)
return INI_SKIRMISH;
if (strcmp(section, "STRUCTURES") == 0)
return INI_STRUCTURES;
if (strcmp(section, "REINFORCEMENTS") == 0)
return INI_REINFORCEMENTS;
if (strcmp(section, "MAP") == 0)
return INI_MAP;
if (strcmp(section, "BASIC") == 0)
return INI_BASIC;
if (strcmp(section, "Atreides") == 0)
return INI_HOUSEATREIDES;
if (strcmp(section, "Ordos") == 0)
return INI_HOUSEORDOS;
if (strcmp(section, "Harkonnen") == 0)
return INI_HOUSEHARKONNEN;
if (strcmp(section, "Sardaukar") == 0)
return INI_HOUSESARDAUKAR;
if (strcmp(section, "Fremen") == 0)
return INI_HOUSEFREMEN;
if (strcmp(section, "Mercenary") == 0)
return INI_HOUSEMERCENARY;
// When nothing found; we assume its just a new ID tag for some unit or structure
// Therefor we return the last known SECTION ID so we can assign the proper WORD ID's
return last;
}
// GAME Section Types
int GAME_INI_SectionType(char section[30], int last)
{
// if (strcmp(section, "BULLETS") == 0)
// return INI_BULLETS;
if (strcmp(section, "SETTINGS") == 0)
return INI_SETTINGS;
if (strcmp(section, "UNITS") == 0)
return INI_UNITS;
if (strcmp(section, "STRUCTURES") == 0)
return INI_STRUCTURES;
// When nothing found; we assume its just a new ID tag for some unit or structure
// Therefor we return the last known SECTION ID so we can assign the proper WORD ID's
return last;
}
// Reads out section[], does a string compare and returns type id
int INI_SectionType(char section[30], int last)
{
if (strcmp(section, "MAP") == 0)
return INI_MAP;
if (strcmp(section, "SKIRMISH") == 0)
return INI_SKIRMISH;
if (strcmp(section, "DESCRIPTION") == 0)
return INI_DESCRIPTION;
if (strcmp(section, "SCEN") == 0)
return INI_SCEN;
if (strcmp(section, "BRIEFING") == 0)
return INI_BRIEFING;
if (strcmp(section, "WIN") == 0)
return INI_WIN;
if (strcmp(section, "LOSE") == 0)
return INI_LOSE;
if (strcmp(section, "ADVICE") == 0)
return INI_ADVICE;
if (strcmp(section, "HOUSES") == 0)
return INI_HOUSES;
if (strcmp(section, "UNITS") == 0)
return INI_UNITS;
if (strcmp(section, "STRUCTURES") == 0)
{
alert("Structure Section found", section, "", "OK", NULL, 13, 0);
return INI_STRUCTURES;
}
alert("No SECTION id found, assuming its an ID nested in section", section, "", "OK", NULL, 13, 0);
// When nothing found; we assume its just a new ID tag for some unit or structure
// Therefor we return the last known SECTION ID so we can assign the proper WORD ID's
return last;
}
// Reads out 'result' and will return the value after the '='. Returns integer.
// For CHAR returns see "INI_WordValueCHAR(char result[80]);
int INI_WordValueINT(char result[MAX_LINE_LENGTH])
{
int pos=0;
int is_pos=-1;
while (pos < (MAX_LINE_LENGTH-1))
{
if (result[pos] == '=')
{
is_pos=pos;
break;
}
pos++;
}
if (is_pos > -1)
{
// Whenever the IS (=) position is known, we make a number out of 'IS_POS' till the next empty
// space.
int end_pos=-1;
while (pos < (MAX_LINE_LENGTH-1))
{
if (result[pos] == '\0')
{
end_pos=pos;
break;
}
pos++;
}
// End position found!
if (end_pos > -1)
{
// We know the END position. We will use that piece of string to read out a number.
char number[10];
// clear out entire string
for (int i=0; i < 10;i++)
number[i] = '\0';
// Copy the part to 'number', Make sure we won't get outside the array of the character.
int cp=is_pos+1;
int c=0;
while (cp < end_pos)
{
number[c] = result[cp];
c++;
cp++;
if (c > 9)
break;
}
return atoi(number);
}
// nothing here, so we return NULL at the end
}
return NULL; // No value, return NULL
}
void INI_WordValueSENTENCE(char result[MAX_LINE_LENGTH], char value[256])
{
int pos=0;
int is_pos=-1;
// clear out entire string
memset(value, 0, sizeof(value));
for (int i=0; i < MAX_LINE_LENGTH;i++)
value[i] = '\0';
while (pos < (MAX_LINE_LENGTH-1))
{
if (result[pos] == '"')
{
is_pos=pos;
break;
}
pos++;
}
if (is_pos > -1)
{
// Whenever the IS (=) position is known, we make a number out of 'IS_POS' till the next empty
// space.
int end_pos=-1;
pos++;
while (pos < (MAX_LINE_LENGTH-1))
{
if (result[pos] == '"')
{
end_pos=pos;
break;
}
pos++;
}
// End position found!
if (end_pos > -1)
{
// We know the END position. We will use that piece of string to read out a number.
// Copy the part to 'value', Make sure we won't get outside the array of the character.
int cp=is_pos+1;
int c=0;
while (cp < end_pos)
{
value[c] = result[cp];
c++;
cp++;
if (c > 254)
break;
}
}
}
}
int INI_GetPositionOfCharacter(char result[MAX_LINE_LENGTH], char c) {
string resultString(result);
return resultString.find_first_of(c, 0);
}
/**
* Return the part after the = sign as string.
*
* @param result
* @return
*/
string INI_WordValueString(char result[MAX_LINE_LENGTH]) {
string resultAsString(result);
int isPos = INI_GetPositionOfCharacter(result, '=');
int length = resultAsString.size();
return resultAsString.substr(isPos+1);
}
// Reads out 'result' and will return the value after the '='. Returns nothing but will put
// the result in 'value[25]'. Max argument may be 256 characters!
void INI_WordValueCHAR(char result[MAX_LINE_LENGTH], char value[256]) {
int pos=0;
int is_pos=-1;
// clear out entire string
memset(value, 0, sizeof(value));
for (int i = 0; i < 256; i++) {
value[i] = '\0';
}
while (pos < (MAX_LINE_LENGTH-1)) {
if (result[pos] == '=') {
is_pos=pos;
break;
}
pos++;
}
if (is_pos > -1) {
// Whenever the IS (=) position is known, we make a number out of 'IS_POS' till the next empty
// space.
int end_pos=-1;
while (pos < (MAX_LINE_LENGTH-1)) {
if (result[pos] == '\0' || result[pos] == '\n') {
end_pos=(pos-1);
break;
}
pos++;
}
// End position found!
if (end_pos > -1) {
// We know the END position. We will use that piece of string to read out a number.
// Copy the part to 'value', Make sure we won't get outside the array of the character.
int cp=is_pos+1;
int c=0;
while (cp <= end_pos) {
value[c] = result[cp];
c++;
cp++;
if (c > 80) {
break;
}
}
}
}
}
// Reads out 'result' and will return TRUE when its 'TRUE' or FALSE when its 'FALSE' , else
// returns NULL
bool INI_WordValueBOOL(char result[MAX_LINE_LENGTH])
{
// use INI_WordValueCHAR to know if its 'true'
char val[256];
INI_WordValueCHAR(result, val);
// When its TRUE , return true
return caseInsCompare(val, "true");
}
// return ID of structure
int getStructureTypeFromChar(char *structure)
{
if (strcmp(structure, "Const Yard") == 0)
return CONSTYARD;
if (strcmp(structure, "Palace") == 0)
return PALACE;
if (strcmp(structure, "Heavy Fctry") == 0)
return HEAVYFACTORY;
if (strcmp(structure, "Light Fctry") == 0)
return LIGHTFACTORY;
if (strcmp(structure, "Windtrap") == 0)
return WINDTRAP;
if (strcmp(structure, "Spice Silo") == 0)
return SILO;
if (strcmp(structure, "Hi-Tech") == 0)
return HIGHTECH;
if (strcmp(structure, "IX") == 0)
return IX;
if (strcmp(structure, "Repair") == 0)
return REPAIR;
if (strcmp(structure, "Outpost") == 0)
return RADAR;
if (strcmp(structure, "Refinery") == 0)
return REFINERY;
if (strcmp(structure, "WOR") == 0)
return WOR;
if (strcmp(structure, "Barracks") == 0)
return BARRACKS;
if (strcmp(structure, "Starport") == 0)
return STARPORT;
if (strcmp(structure, "Turret") == 0)
return TURRET;
if (strcmp(structure, "R-Turret") == 0)
return RTURRET;
logbook("Could not find structure:");
logbook(structure);
return CONSTYARD;
}
/**
* Create seed map.
*
* @param seed
*/
void INI_Load_seed(int seed) {
char msg[256];
sprintf(msg, "Generating seed map with seed %d.", seed);
logbook(msg);
cSeedMapGenerator *seedGenerator = new cSeedMapGenerator(seed);
cSeedMap *seedMap = seedGenerator->generateSeedMap();
logbook("Seedmap generated");
for (int mapY = 0; mapY < 64; mapY++) {
for (int mapX = 0; mapX < 64; mapX++) {
char c = seedMap->getCellTypeCharacter(mapX, mapY);
int type = seedMap->getCellType(mapX, mapY);
int iCell = iCellMake(mapX, mapY);
mapEditor.createCell(iCell, type, 0);
}
}
logbook("Seedmap converted into D2TM map.");
}
// Load
/**
* Return true when line starts with:
* ; # // \n \0
*
* @param linefeed
* @return
*/
bool isCommentLine(char linefeed[MAX_LINE_LENGTH]) {
return linefeed[0] == ';' || linefeed[0] == '#' || (linefeed[0] == '/' && linefeed[1] == '/') || linefeed[0] == '\n' || linefeed[0] == '\0';
}
/**
* Return the name of the directory to look for by house id.
* (ie iHouse == ATREIDES) returns "atreides"
* @param iHouse
* @return
*/
string INI_GetHouseDirectoryName(int iHouse) {
if (iHouse == ATREIDES) return "atreides";
if (iHouse == HARKONNEN) return "harkonnen";
if (iHouse == SARDAUKAR) return "sardaukar";
if (iHouse == ORDOS) return "ordos";
if (iHouse == FREMEN) return "fremen";
if (iHouse == MERCENARY) return "mercenary";
return "unknown";
}
void INI_Load_Regionfile(int iHouse, int iMission) {
char filename[256];
memset(filename, 0, sizeof(filename));
sprintf(filename, "campaign/%s/mission%d.ini", INI_GetHouseDirectoryName(iHouse).c_str(), iMission);
cLogger::getInstance()->log(LOG_INFO, COMP_REGIONINI, "Opening mission file", filename);
////////////////////////////
// START OPENING FILE
////////////////////////////
FILE *stream; // file stream
int wordtype=WORD_NONE; // word
int iRegionIndex=-1;
int iRegionNumber=-1;
int iRegionConquer=-1;
// open file
if( (stream = fopen( filename, "r+t" )) != NULL ) {
char linefeed[MAX_LINE_LENGTH];
char lineword[25];
char linesection[30];
memset(lineword, '\0', sizeof(lineword));
memset(linesection, '\0', sizeof(linesection));
while( !feof( stream ) ) {
INI_Sentence(stream, linefeed);
// Linefeed contains a string of 1 sentence. Whenever the first character is a commentary
// character (which is "//", ";" or "#"), or an empty line, then skip it
if (isCommentLine(linefeed)) {
continue; // Skip
}
wordtype = WORD_NONE;
// Every line is checked for a new section.
INI_Word(linefeed, lineword);
wordtype = INI_WordType(lineword, SEC_REGION);
if (wordtype == WORD_REGION) {
iRegionNumber=-1;
iRegionConquer=-1;
iRegionNumber = INI_WordValueINT(linefeed)-1;
} else if (wordtype == WORD_REGIONCONQUER) {
iRegionNumber=-1;
iRegionConquer=-1;
iRegionIndex++;
iRegionConquer = INI_WordValueINT(linefeed)-1;
game.iRegionConquer[iRegionIndex] = iRegionConquer;
}
if (iRegionIndex > -1 || iRegionNumber > -1) {
if (wordtype == WORD_REGIONHOUSE) {
char cHouseRegion[256];
memset(cHouseRegion, 0, sizeof(cHouseRegion));
INI_WordValueCHAR(linefeed, cHouseRegion);
logbook("Region house");
int iH= getHouseFromChar(cHouseRegion);
if (iRegionNumber > -1) {
world[iRegionNumber].iHouse = iH;
world[iRegionNumber].iAlpha = 255;
}
if (iRegionConquer > -1) {
game.iRegionHouse[iRegionIndex] = iH;
}
}
if (wordtype == WORD_REGIONTEXT && iRegionConquer > -1 && iRegionIndex > -1) {
char cHouseText[256];
INI_WordValueSENTENCE(linefeed, cHouseText);
sprintf(game.cRegionText[iRegionIndex], "%s", cHouseText);
}
if (wordtype == WORD_REGIONSELECT) {
if (iRegionNumber > -1) {
world[iRegionNumber].bSelectable = INI_WordValueBOOL(linefeed);
}
}
}
} // while
fclose(stream);
logbook("[CAMPAIGN] Done");
return;
}
logbook("[CAMPAIGN] Error, could not open file"); // make note on logbook
}
// SCENxxxx.ini loader (for both DUNE II as for DUNE II - The Maker)
int getUnitTypeFromChar(char chunk[35]) {
string unitString(chunk);
if (caseInsCompare(unitString, "Harvester")) return HARVESTER;
if (caseInsCompare(unitString, "Tank")) return TANK;
if (caseInsCompare(unitString, "COMBATTANK")) return TANK;
if (caseInsCompare(unitString, "Siege Tank")) return SIEGETANK;
if (caseInsCompare(unitString, "SIEGETANK")) return SIEGETANK;
if (caseInsCompare(unitString, "Launcher")) return LAUNCHER;
if (caseInsCompare(unitString, "Trooper")) return TROOPER;
if (caseInsCompare(unitString, "Troopers")) return TROOPERS;
if (caseInsCompare(unitString, "Sonic Tank")) return SONICTANK;
if (caseInsCompare(unitString, "SONICTANK")) return SONICTANK;
if (caseInsCompare(unitString, "Quad")) return QUAD;
if (caseInsCompare(unitString, "Trike")) return TRIKE;
if (caseInsCompare(unitString, "Raider Trike")) return RAIDER;
if (caseInsCompare(unitString, "RAIDER")) return RAIDER;
if (caseInsCompare(unitString, "Soldier")) return SOLDIER;
if (caseInsCompare(unitString, "Infantry")) return INFANTRY;
if (caseInsCompare(unitString, "Devastator")) return DEVASTATOR;
if (caseInsCompare(unitString, "Deviator")) return DEVIATOR;
if (caseInsCompare(unitString, "MCV")) return MCV;
if (caseInsCompare(unitString, "Trike")) return TRIKE;
if (caseInsCompare(unitString, "Soldier")) return SOLDIER;
if (caseInsCompare(unitString, "CarryAll")) return CARRYALL;
if (caseInsCompare(unitString, "Ornithopter")) return ORNITHOPTER;
if (caseInsCompare(unitString, "Sandworm")) return SANDWORM;
if (caseInsCompare(unitString, "Saboteur")) return SABOTEUR;
if (caseInsCompare(unitString, "MISSILE")) return MISSILE;
if (caseInsCompare(unitString, "ONEFREMEN")) return UNIT_FREMEN_ONE;
if (caseInsCompare(unitString, "THREEFREMEN")) return UNIT_FREMEN_THREE;
char msg[255];
sprintf(msg, "getUnitTypeFromChar could not determine what unit type '%s' (original is '%s') is. Returning -1; this will probably cause problems.", unitString.c_str(), chunk);
logbook(msg);
return -1;
}
int getHouseFromChar(char chunk[25])
{
if (strcmp(chunk, "Atreides") == 0) return ATREIDES;
if (strcmp(chunk, "Harkonnen") == 0) return HARKONNEN;
if (strcmp(chunk, "Ordos") == 0) return ORDOS;
if (strcmp(chunk, "Sardaukar") == 0) return SARDAUKAR;
if (strcmp(chunk, "Mercenary") == 0) return MERCENARY;
if (strcmp(chunk, "Fremen") == 0) return FREMEN;
if (strcmp(chunk, "Corrino") == 0) return CORRINO;
if (strcmp(chunk, "General") == 0) return GENERALHOUSE;
char msg[255];
sprintf(msg, "getHouseFromChar could not determine what house type '%s' is. Returning -1; this will probably cause problems.", chunk);
logbook(msg);
return -1;
}
/**
* Taken the region conquered by player, in sequential form (meaning, the 1st region the
* player conquers, corresponds with techlevel 1. While the 8th, 9th or 10th region correspond
* with techlevel 4.
*
* This assumes that the player conquers the world in a fixed set of regions.
*
* TODO: Make this moddable.
*
* @param iRegion
* @return
*/
int getTechLevelByRegion(int iRegion) {
if(iRegion == 1) return 1;
if(iRegion == 2 || iRegion == 3 || iRegion == 4) return 2;
if(iRegion == 5 || iRegion == 6 || iRegion == 7) return 3;
if(iRegion == 8 || iRegion == 9 || iRegion == 10) return 4;
if(iRegion == 11 || iRegion == 12 || iRegion == 13) return 5;
if(iRegion == 14 || iRegion == 15 || iRegion == 16) return 6;
if(iRegion == 17 || iRegion == 18 || iRegion == 19) return 7;
if(iRegion == 20 || iRegion == 21) return 8;
return 9;
}
/**
* Returns a string, containing the relative path to the scenario file for
* the given house and region id.
* @param iHouse
* @param iRegion
* @return
*/
string INI_GetScenarioFileName(int iHouse, int iRegion) {
string cHouse;
// each house has a letter for the scenario file
if (iHouse == ATREIDES) cHouse = "a";
if (iHouse == HARKONNEN) cHouse = "h";
if (iHouse == ORDOS) cHouse = "o";
if (iHouse == SARDAUKAR) cHouse = "s";
if (iHouse == MERCENARY) cHouse = "m";
if (iHouse == FREMEN) cHouse = "f";
char filename[256];
memset(filename, '\0', sizeof(filename));
if(iRegion < 10) {
sprintf(filename, "campaign/maps/scen%s00%d.ini", cHouse.c_str(), iRegion);
} else {
sprintf(filename, "campaign/maps/scen%s0%d.ini", cHouse.c_str(), iRegion);
}
return string(filename);
}
void INI_Load_scenario(int iHouse, int iRegion) {
game.bSkirmish = false;
game.mission_init();
string filename = INI_GetScenarioFileName(iHouse, iRegion);
game.iMission = getTechLevelByRegion(iRegion);
char msg[256];
sprintf(msg, "[SCENARIO] '%s' (Mission %d)", filename.c_str(), game.iMission);
logbook(msg);
logbook("[SCENARIO] Opening file");
// declare some temp fields while reading the scenario file.
int blooms[30], fields[30];
char value[256];
memset(blooms, -1, sizeof (blooms));
memset(fields, -1, sizeof (fields));
FILE *stream;
int section=INI_NONE;
int wordtype=WORD_NONE;
int iPlayerID = -1;
int iHumanID = -1;
bool bSetUpPlayers = true;
int iPl_credits[MAX_PLAYERS];
int iPl_house[MAX_PLAYERS];
int iPl_quota[MAX_PLAYERS];
memset(iPl_credits, 0, sizeof (iPl_credits));
memset(iPl_house, -1, sizeof (iPl_house));
memset(iPl_quota, 0, sizeof (iPl_quota));
if( (stream = fopen( filename.c_str(), "r+t" )) != NULL ) {
char linefeed[MAX_LINE_LENGTH];
char lineword[25];
char linesection[30];
memset(lineword, '\0', sizeof(lineword));
memset(linesection, '\0', sizeof(linesection));
memset(linefeed, '\0', sizeof(linefeed));
// infinite loop baby
while( !feof( stream ) ) {
INI_Sentence(stream, linefeed);
// Linefeed contains a string of 1 sentence. Whenever the first character is a commentary
// character (which is "//", ";" or "#"), or an empty line, then skip it
if (isCommentLine(linefeed)) continue; // Skip
// Every line is checked for a new section.
INI_Section(linefeed, linesection);
// line is not starting empty and section is found
if (linesection[0] != '\0' && strlen(linesection) > 1) {
section = SCEN_INI_SectionType(linesection, section);
char msg[255];
sprintf(msg, "[SCENARIO] found section '%s', resulting in section id [%d]", linesection, section);
logbook(msg);
if (section >= INI_HOUSEATREIDES && section <= INI_HOUSEMERCENARY) {
iPlayerID++;
if (iPlayerID > (MAX_PLAYERS-1)) {
iPlayerID = (MAX_PLAYERS-1);
}
if (section == INI_HOUSEATREIDES) iPl_house[iPlayerID] = ATREIDES;
if (section == INI_HOUSEORDOS) iPl_house[iPlayerID] = ORDOS;
if (section == INI_HOUSEHARKONNEN) iPl_house[iPlayerID] = HARKONNEN;
if (section == INI_HOUSEMERCENARY) iPl_house[iPlayerID] = MERCENARY;
if (section == INI_HOUSEFREMEN) iPl_house[iPlayerID] = FREMEN;
if (section == INI_HOUSESARDAUKAR) iPl_house[iPlayerID] = SARDAUKAR;
char msg[255];
sprintf(msg, "[SCENARIO] Setting house to [%d] for playerId [%d]", iPl_house[iPlayerID], iPlayerID);
logbook(msg);
}
continue; // next line
}
// Okay, we found a new section; if its NOT [GAME] then we remember this one!
if (section != INI_NONE)
{
INI_Word(linefeed, lineword);
wordtype = INI_WordType(lineword, section);
}
if (section == INI_BASIC)
{
if (wordtype == WORD_BRIEFPICTURE)
{
// Load name, and load proper briefingpicture
memset(value, 0, sizeof(value));
string scenefile = INI_WordValueString(linefeed);
string scene = INI_SceneFileToScene(scenefile);
scene = INI_SceneFileToScene(scenefile);
if (!isInString(scene, "unknown")) {
LOAD_SCENE(scene);
}
}
if (wordtype == WORD_FOCUS)
{
player[0].focus_cell = INI_WordValueINT(linefeed);
mapCamera->centerAndJumpViewPortToCell(player[0].focus_cell);
}
}
// Dune 2 house found, load player data
if (section >= INI_HOUSEATREIDES && section <= INI_HOUSEMERCENARY)
{
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "Section is between atreides and mercenary, the playerId is [%d]. WordType is [%d]", iPlayerID, wordtype);
logbook(msg);
// link house (found, because > -1)
if (iPlayerID > -1) {
if (wordtype == WORD_BRAIN)
{
char cBrain[256];
memset(cBrain, 0, sizeof(cBrain));
INI_WordValueCHAR(linefeed, cBrain);
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "Brain is [%s]", cBrain);
logbook(msg);
// We know the human brain now, this should be player 0...
if (strcmp(cBrain, "Human") == 0) {
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "Found human player for id [%d]", iPlayerID);
logbook(msg);
iHumanID = iPlayerID;
} else {
logbook("This brain is not human...");
}
} else if (wordtype == WORD_CREDITS) {
int credits = INI_WordValueINT(linefeed)-1;
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "Set credits for player id [%d] to [%d]", iPlayerID, credits);
logbook(msg);
iPl_credits[iPlayerID] = credits;
} else if (wordtype == WORD_QUOTA) {
iPl_quota[iPlayerID] = INI_WordValueINT(linefeed);
}
}
}
if (section == INI_MAP)
{
game.map_height = 64;
game.map_width = 64;
// original dune 2 maps have 64x64 maps
if (wordtype == WORD_MAPSEED)
{
logbook("[SCENARIO] -> [MAP] Seed=");
INI_Load_seed(INI_WordValueINT(linefeed));
}
// Loaded before SEED
if (wordtype == WORD_MAPBLOOM)
{
// This should put spice blooms in our array
// Logic: read till next "," , then use that number to determine
// where the bloom will be (as cell nr)
logbook("[SCENARIO] -> [MAP] Bloom=");
int iBloomID=0;
int iStringID=6; // B L O O M = <6>
int iWordID=0;
char word[10];
memset(word, 0, sizeof(word)); // clear string
for (iStringID; iStringID < MAX_LINE_LENGTH; iStringID++)
{
// until we encounter a "," ...
char letter[1];
letter[0] = '\0';
letter[0] = linefeed[iStringID];
// its a comma!
if (letter[0] == ',' || letter[0] == '\0' || letter[0] == '\n')
{
// from prevID TILL now is a number
iWordID=0;
int original_dune2_cell = atoi(word);
int d2tm_cell = -1;
int iCellX=(original_dune2_cell - ((original_dune2_cell/64) * 64));
int iCellY=(original_dune2_cell / 64);
// Now recalculate it
d2tm_cell = iCellMake(iCellX, iCellY);
blooms[iBloomID] = d2tm_cell;
memset(word, 0, sizeof(word)); // clear string
if (iBloomID < 29)
iBloomID++;
if (letter[0] == '\0' || letter[0] == '\n')
break; // get out
}
else
{
word[iWordID] = letter[0]; // copy
if (iWordID < 9)
iWordID++;
}
}
}
// Loaded before SEED
else if (wordtype == WORD_MAPFIELD)
{
// This should put spice blooms in our array
// Logic: read till next "," , then use that number to determine
// where the bloom will be (as cell nr)
logbook("[SCENARIO] -> [MAP] Field=");
int iFieldID=0;
int iStringID=6; // F I E L D = <6>
int iWordID=0;
char word[10];
memset(word, 0, sizeof(word)); // clear string
for (iStringID; iStringID < MAX_LINE_LENGTH; iStringID++)
{
// until we encounter a "," ...
char letter[1];
letter[0] = '\0';
letter[0] = linefeed[iStringID];
// its a comma!
if (letter[0] == ',' || letter[0] == '\0' || letter[0] == '\n')
{
// from prevID TILL now is a number
iWordID=0;
int original_dune2_cell = atoi(word);
int d2tm_cell = -1;
int iCellX=(original_dune2_cell - ((original_dune2_cell/64) * 64));
int iCellY=(original_dune2_cell / 64);
// Now recalculate it
d2tm_cell = iCellMake(iCellX, iCellY);
fields[iFieldID] = d2tm_cell;
memset(word, 0, sizeof(word)); // clear string
if (iFieldID < 29)
iFieldID++;
if (letter[0] == '\0' || letter[0] == '\n')
break; // get out
}
else
{
word[iWordID] = letter[0]; // copy
if (iWordID < 9)
iWordID++;
}
}
}
}
else if (section == INI_UNITS)
{
// ORIGINAL DUNE 2 MISSION. EVERYBODY IS AGAINST U
if (bSetUpPlayers)
{
logbook("Going to setup players");
int iRealID=1;
for (int iP=0; iP < MAX_PLAYERS; iP++) // till 6 , since player 6 itself is sandworm
{
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "House for id [%d] is [%d] - human id is [%d]", iP, iPl_house[iP], iHumanID);
logbook(msg);
if (iPl_house[iP] > -1) {
if (iP == iHumanID)
{
char msg[255];
memset(msg, 0, sizeof(msg));
sprintf(msg, "Setting up human player, credits to [%d]", iPl_credits[iP]);
logbook(msg);
player[HUMAN].credits = iPl_credits[iP];
player[HUMAN].setHouse(iPl_house[iP]);
player[HUMAN].iTeam = 0;
game.iHouse = iPl_house[iP];
assert(drawManager);
if (drawManager->getCreditsDrawer()) {
drawManager->getCreditsDrawer()->setCredits();
}
if (iPl_quota[iP] > 0) {
game.iWinQuota = iPl_quota[iP];
}
}
else
{
// CPU player
player[iRealID].iTeam = 1; // All AI players are on the same team
// belong to player team
if (iPl_house[iP] == FREMEN) {
if (player[HUMAN].getHouse() == ATREIDES) {
player[iRealID].iTeam = 0;
}
}
player[iRealID].credits = iPl_credits[iP];
player[iRealID].setHouse(iPl_house[iP]);
iRealID++;
}
}
}
bSetUpPlayers=false;
}
int iPart=-1; /*
0 = Controller
1 = Type
2 = HP
3 = Cell
4 = Facing (body)
5 = Facing (head)
*/
// Skip ID= part. It is just for fun there.
int iController, iType, iHP, iCell, iFacingBody, iFacingHead;
iController=iType=iHP=iCell=iFacingBody=iFacingHead=-1;
char chunk[25];
bool bClearChunk=true;
bool bSkipped=false;
int iC=-1;
for (int c=0; c < MAX_LINE_LENGTH; c++)
{
// clear chunk
if (bClearChunk)
{
for (int ic=0; ic < 25; ic++)
chunk[ic] = '\0';
iC=0;
bClearChunk=false;
}
// Fill in chunk
if (iC < 25 && bSkipped && linefeed[c] != ',')
{
chunk[iC] = linefeed[c];
iC++;
}
// , means next part. A ' ' means end
if (linefeed[c] == ',' || linefeed[c] == '\0')
{
iPart++;
if (iPart == 0)
{
int iHouse = getHouseFromChar(chunk);
// Search for a player with this house
for (int i=0; i < MAX_PLAYERS; i++)
if (player[i].getHouse() == iHouse)
{
iController = i; // set controller here.. phew
break;
}
// HACK HACK : Set up fremen house here
if (iHouse == FREMEN)
{
player[5].setHouse(FREMEN); // set up palette
player[5].credits = 9999; // lots of money for the fremen
iController = 5;
}
// Quickfix: fremen house in original dune 2, is house 6 (not detectable)
// in this game.
//if (iHouse == FREMEN)
// iController = 6;
if (iController < 0)
{
char msg[256];
sprintf(msg,"WARNING: Cannot identify house/controller -> STRING '%s'", chunk);
logbook(msg);
}
}
else if (iPart == 1)
{
iType = getUnitTypeFromChar(chunk);
}
// do nothing in part 2
else if (iPart == 3)
{
iCell = atoi(chunk);
}
else if (iPart == 4)
break;
bClearChunk=true;
}
// found the = mark, this means we start chopping now!
if (linefeed[c] == '=')
bSkipped=true;
}
if (iController > -1)
{
//int uID = create_unit(iController, iCell, iType, ACTION_GUARD, -1);
UNIT_CREATE(iCell, iType, iController, true);
// CREATE_UNIT(iCell, iType, iController);
/*
if (bOrDune == false && uID > -1)
{
unit[uID].hp = iHP;
unit[uID].body_face = iFacingBody;
unit[uID].body_head = iFacingHead;
unit[uID].body_should_face = iFacingBody;
unit[uID].head_should_face = iFacingHead;
}*/
}
}
else if (section == INI_STRUCTURES)
{
// In case some funny-face of Westwood did first the structures section, we still set up players then...
// har har har..
// ORIGINAL DUNE 2 MISSION. EVERYBODY IS AGAINST U
if (bSetUpPlayers)
{
int iRealID=1;
for (int iP=0; iP < MAX_PLAYERS; iP++) // till 6 , since player 6 itself is sandworm
{
if (iPl_house[iP] > -1)
if (iP == iHumanID)
{
player[0].credits = iPl_credits[iP];
player[0].setHouse(iPl_house[iP]);
player[0].iTeam=0;
game.iHouse = iPl_house[iP];
if (iPl_quota[iP] > 0) {
game.iWinQuota = iPl_quota[iP];
}
}
else
{
// CPU player
player[iRealID].iTeam = 1; // All AI players are on the same team
// belong to player team
if (iPl_house[iP] == FREMEN) {
if (player[HUMAN].getHouse() == ATREIDES) {
player[iRealID].iTeam = 0;
}
}
player[iRealID].credits = iPl_credits[iP];
player[iRealID].setHouse(iPl_house[iP]);
iRealID++;
}
}
bSetUpPlayers=false;
}
int iPart=-1; /*
0 = Controller
1 = Type
2 = HP
3 = Cell
*/
// Skip ID= part. It is just for fun there.
int iController, iType, iHP, iCell;
iController=iType=iHP=iCell=-1;
char chunk[25];
bool bClearChunk=true;
bool bSkipped=false;
int iC=-1;
bool bGen=false;
int iIS=-1;
// check if this is a 'gen'
if (strstr(linefeed, "GEN") != NULL) bGen=true;
for (int c=0; c < MAX_LINE_LENGTH; c++)
{
// clear chunk
if (bClearChunk)
{
for (int ic=0; ic < 25; ic++) {
chunk[ic] = '\0';
}
iC=0;
bClearChunk=false;
}
// Fill in chunk
if (iC < 25 && bSkipped && linefeed[c] != ',')
{
chunk[iC] = linefeed[c];
iC++;
}
// , means next part. A ' ' means end
if (linefeed[c] == ',' || linefeed[c] == '\0')
{
iPart++;
// this line is not GENXXX
if (bGen == false)
{
if (iPart == 0)
{
int iHouse = getHouseFromChar(chunk);
// Search for a player with this house
for (int i=0; i < MAX_PLAYERS; i++)
{
//char msg[80];
//sprintf(msg, "i=%d, ihouse=%d, house=%d", i, iHouse, player[i].house);
//logbook(msg);
if (player[i].getHouse() == iHouse)
{
iController = i; // set controller here.. phew
break;
}
}
// Quickfix: fremen house in original dune 2, is house 6 (not detectable)
// in this game.
//if (iHouse == FREMEN)
// iController = 6;
if (iController < 0)
{
logbook("WARNING: Identifying house/controller of structure (typo?)");
logbook(chunk);
}
}
else if (iPart == 1)
{
iType = getStructureTypeFromChar(chunk);
}
else if (iPart == 3)
{
iCell = atoi(chunk);
break;
}
}
else
{
if (iPart == 0)
{
int iHouse= getHouseFromChar(chunk);;
// Search for a player with this house
for (int i=0; i < MAX_PLAYERS; i++)
{
if (player[i].getHouse() == iHouse)
{
iController = i; // set controller here.. phew
break;
}
}
}
else if (iPart == 1)
{
// Figure out the cell shit of this GEN
char cCell[5];
for (int cc=0; cc < 5; cc++)
cCell[cc] = '\0';
int iCC=0;
for (int cc=3; cc < iIS; cc++)
{
cCell[iCC] = linefeed[cc];
iCC++;
}
int iGenCell = atoi(cCell);
iCell = iGenCell;
if (strcmp(chunk, "Wall") == 0) iType = WALL;
if (strcmp(chunk, "Concrete") == 0) iType = SLAB1;
break;
}
}
bClearChunk=true;
}
// found the = mark, this means we start chopping now!
if (linefeed[c] == '=')
{
bSkipped=true;
iIS=c;
}
}
if (iController > -1)
{
// anything lower than SLAB1 means a 'normal' structure (TODO: make this less tight coupled)
if (iType < SLAB1) {
if (iType != CONSTYARD) {
cStructureFactory::getInstance()->createSlabForStructureType(iCell, iType);
}
cStructureFactory::getInstance()->createStructure(iCell, iType, iController, 100);
} else {
if (iType == SLAB1)
{
mapEditor.createCell(iCell, TERRAIN_SLAB, 0);
//map.cell[iCell].tile = SLAB;
}
if (iType == WALL)
{
mapEditor.createCell(iCell, TERRAIN_WALL, 0);
}
}
}
else {
logbook("WARNING: Identifying house/controller of structure (typo?)");
}
}
else if (section == INI_REINFORCEMENTS)
{
logbook("[SCENARIO] -> REINFORCEMENTS");
int iPart=-1; /*
0 = Controller
1 = Type
2 = HP
3 = Cell
*/
// Skip ID= part. It is just for fun there.
int iController, iType, iTime, iCell;
iController=iType=iTime=iCell=-1;
char chunk[25];
bool bClearChunk=true;
bool bSkipped=false;
int iC=-1;
int iIS=-1;
for (int c=0; c < MAX_LINE_LENGTH; c++)
{
// clear chunk
if (bClearChunk)
{
memset(chunk, 0, sizeof(chunk));
//for (int ic=0; ic < 25; ic++)
// chunk[ic] = '\0';
iC=0;
bClearChunk=false;
}
// Fill in chunk
if (iC < 25 && bSkipped && linefeed[c] != ',')
{
chunk[iC] = linefeed[c];
iC++;
}
// , means next part. A ' ' means end
if (linefeed[c] == ',' || linefeed[c] == '\0' || linefeed[c] == '+')
{
iPart++;
if (iPart == 0)
{
int iHouse = getHouseFromChar(chunk);
if (iHouse > -1)
{
// Search for a player with this house
for (int i=0; i < MAX_PLAYERS; i++)
{
if (player[i].getHouse() == iHouse)
{
iController = i; // set controller here.. phew
break;
}
}
}
}
else if (iPart == 1)
{
iType = getUnitTypeFromChar(chunk);
}
else if (iPart == 2)
{
// Homebase is home of that house
if (strcmp(chunk, "Homebase") == 0) {
iCell = player[iController].focus_cell;
}
else
{
// enemy base
if (iController == 0)
{
// Find corresponding house and get controller
for (int i=0; i < MAX_PLAYERS; i++)
if (player[i].getHouse() == iHouse && i != iController)
{
iCell = player[i].focus_cell;
break;
}
}
else
{
// computer player must find enemy = human
iCell = player[0].focus_cell;
}
}
}
else if (iPart == 3)
{
int iGenCell = atoi(chunk);
iTime = iGenCell;
SET_REINFORCEMENT(iCell, iController, iTime, iType);
break;
}
bClearChunk=true;
}
// found the = mark, this means we start chopping now!
if (linefeed[c] == '=')
{
bSkipped=true;
iIS=c;
}
}
}
wordtype=WORD_NONE;
}
fclose(stream);
// When loading an original dune 2 scenario, we do a trick now to make the
// players start okay.
// Now apply map settings to all players
for (int iP=0; iP < MAX_PLAYERS; iP++)
{
// minimum of 1000 credits storage per level
if (player[iP].max_credits < 1000) {
player[iP].max_credits = 1000;
}
}
mapEditor.smoothMap();
// now add the spice blooms! :)
for (int iB=0; iB < 30; iB++)
{
// when
if (blooms[iB] > -1)
{
// map.cell[blooms[iB]].tile = BLOOM;
if (DEBUGGING)
{
char msg[256];
sprintf(msg, "[SCENARIO] Placing spice BLOOM at cell : %d", blooms[iB]);
logbook(msg);
}
mapEditor.createCell(blooms[iB], TERRAIN_BLOOM, 0);
}
}
// At this point, show list of unit types
// now add the fields
for (int iB=0; iB < 30; iB++)
{
// when
if (fields[iB] > -1)
{
if (DEBUGGING)
{
char msg[256];
sprintf(msg, "[SCENARIO] Placing spice FIELD at cell : %d", fields[iB]);
logbook(msg);
}
mapEditor.createField(fields[iB], TERRAIN_SPICE, 25+(rnd(50)));
}
}
logbook("[SCENARIO] Done reading");
}
player[AI_WORM].iTeam=-2;
mapEditor.smoothMap();
}
void INI_LOAD_BRIEFING(int iHouse, int iScenarioFind, int iSectionFind)
{
logbook("[BRIEFING] Opening file");
char filename[80];
if (iHouse == ATREIDES) sprintf(filename, "mentata.ini");
if (iHouse == ORDOS) sprintf(filename, "mentato.ini");
if (iHouse == HARKONNEN) sprintf(filename, "mentath.ini");
FILE *stream;
char path[50];
// clear mentat
memset(game.mentat_sentence, 0, sizeof(game.mentat_sentence));
sprintf(path, "campaign/briefings/%s", filename);
logbook(path);
if (DEBUGGING)
{
char msg[255];
sprintf(msg, "Going to find SCEN ID #%d and SectionID %d", iScenarioFind, iSectionFind);
logbook(msg);
}
int iScenario=0;
int iSection=0;
int iLine=0; // max 8 lines
if( (stream = fopen( path, "r+t" )) != NULL )
{
char linefeed[MAX_LINE_LENGTH];
char lineword[25];
char linesection[30];
while( !feof( stream ) )
{
INI_Sentence(stream, linefeed);
// Linefeed contains a string of 1 sentence. Whenever the first character is a commentary
// character (which is "//", ";" or "#"), or an empty line, then skip it
if (isCommentLine(linefeed)) continue; // Skip
INI_Section(linefeed,linesection);
if (linesection[0] != '\0' && strlen(linesection) > 1)
{
// until we found the right sections/parts, keep searching
iSection=INI_SectionType(linesection, iSection);
}
if (iSection == INI_SCEN)
{
INI_Word(linefeed, lineword);
int wordtype = INI_WordType(lineword, iSection);
if (wordtype == WORD_NUMBER)
{
iScenario = INI_WordValueINT(linefeed);
continue;
}
}
if (iScenario == iScenarioFind)
{
if (iSection == iSectionFind)
{
INI_Word(linefeed, lineword);
int wordtype = INI_WordType(lineword, iSection);
if (wordtype == WORD_REGIONTEXT)
{
char cHouseText[256];
INI_WordValueSENTENCE(linefeed, cHouseText);
// this is not a comment, add this....
sprintf(game.mentat_sentence[iLine], "%s",cHouseText);
// logbook(game.mentat_sentence[iLine]);
iLine++;
if (iLine > 9)
break;
}
}
}
/*
*/
}
fclose(stream);
}
logbook("[BRIEFING] File opened");
}
// Game.ini loader
void INI_Install_Game(string filename) {
logbook("[GAME.INI] Opening file");
FILE *stream;
int section=INI_GAME;
int wordtype=WORD_NONE;
int id=-1;
int side_r, side_b, side_g;
int team_r, team_g, team_b; // rgb colors for a team
side_r=side_g=side_b=-1;
team_r=team_g=team_b=-1;
char msg[255];
sprintf(msg, "Opening game settings from : %s", filename.c_str());
logbook(msg);
if( (stream = fopen( filename.c_str(), "r+t" )) != NULL ) {
char linefeed[MAX_LINE_LENGTH];
char lineword[25];
char linesection[30];
// infinite loop baby
while( !feof( stream ) )
{
INI_Sentence(stream, linefeed);
// Linefeed contains a string of 1 sentence. Whenever the first character is a commentary
// character (which is "//", ";" or "#"), or an empty line, then skip it
if (isCommentLine(linefeed))
continue; // Skip
wordtype=WORD_NONE;
// Every line is checked for a new section.
INI_Section(linefeed,linesection);
if (linesection[0] != '\0' && strlen(linesection) > 1)
{
int last=section;
// determine section
section=GAME_INI_SectionType(linesection, section);
// When we changed section and its a section with adding ID's. We should reset
// the ID var
if (last != section)
{
id=-1;
// Show in log file we entered a new section
if (section == INI_UNITS) logbook("[GAME.INI] -> [UNITS]");
if (section == INI_STRUCTURES) logbook("[GAME.INI] -> [STRUCTURES]");
if (section == INI_SETTINGS) logbook("[GAME.INI] -> [SETTINGS]");
}
if (section == INI_TEAMS)
{
// check if we found a new [TEAM part!
if (strstr(linefeed,"[TEAM:") != NULL)
{
id++; // New ID
team_r=team_g=team_b=-1; // new team colors
if (id > MAX_HOUSES) id--;
}
}
// New unit type
if (section == INI_UNITS) {
// check if we found a new [UNIT part!
if (strstr(linefeed,"[UNIT:") != NULL) {
// Get the name of the unit:
// [UNIT: <NAME>]
// 1234567890123...]
char name_unit[35];
for (int nu=0; nu < 35; nu++)
name_unit[nu]='\0';
int c=7, uc=0;
while (c < (MAX_LINE_LENGTH-1)) {
if (linefeed[c] != ' ' &&
linefeed[c] != ']') // skip close bracket
{
name_unit[uc] = linefeed[c];
uc++;
c++;
} else {
break; // get out
}
}
id = getUnitTypeFromChar(name_unit);
if (id >= MAX_UNITTYPES) id--;
} // found a new unit type
}
// New structure type
if (section == INI_STRUCTURES)
{
// check if we found a new [STRUCTURE: part!
if (strstr(linefeed,"[STRUCTURE:") != NULL)
{
// Get the name of the unit:
// [STRUCTURE: <NAME>]
// 123456789012345678]
char name_structure[45];
for (int nu=0; nu < 45; nu++)
name_structure[nu]='\0';
int c=12, uc=0;
while (c < (MAX_LINE_LENGTH-1))
{
if (linefeed[c] != ' ' &&
linefeed[c] != ']') // skip close bracket
{
name_structure[uc] = linefeed[c];
uc++;
c++;
}
else
break; // get out
}
id = INI_StructureType(name_structure);
if (id >= MAX_STRUCTURETYPES) id--;
} // found a new unit type
}
continue; // next line
}
// Check word only when in a section
if (section != INI_GAME) {
INI_Word(linefeed, lineword);
wordtype = INI_WordType(lineword, section);
/**** [UNITS] ****/
// Valid ID
if (section == INI_UNITS && id > -1)
{
// Unit properties
if (wordtype == WORD_HITPOINTS) units[id].hp = INI_WordValueINT(linefeed);
if (wordtype == WORD_COST) units[id].cost = INI_WordValueINT(linefeed);
if (wordtype == WORD_MOVESPEED) units[id].speed = INI_WordValueINT(linefeed);
if (wordtype == WORD_TURNSPEED) units[id].turnspeed = INI_WordValueINT(linefeed);
if (wordtype == WORD_ATTACKFREQ) units[id].attack_frequency = INI_WordValueINT(linefeed);
if (wordtype == WORD_SIGHT) units[id].sight = INI_WordValueINT(linefeed);
if (wordtype == WORD_RANGE) units[id].range = INI_WordValueINT(linefeed);
if (wordtype == WORD_BUILDTIME) units[id].build_time = INI_WordValueINT(linefeed);
// Unit description
if (wordtype == WORD_DESCRIPTION)
{
char n[256];
INI_WordValueCHAR(linefeed, n);
sprintf(units[id].name, "%s", n);
}
// Booleans
if (wordtype == WORD_SECONDSHOT) units[id].second_shot = INI_WordValueBOOL(linefeed);
if (wordtype == WORD_ISINFANTRY) units[id].infantry = INI_WordValueBOOL(linefeed);
if (wordtype == WORD_FREEROAM) units[id].free_roam = INI_WordValueBOOL(linefeed);
if (wordtype == WORD_ISAIRBORN) units[id].airborn = INI_WordValueBOOL(linefeed);
// Harvester specific properties.
if (wordtype == WORD_HARVESTLIMIT) units[id].credit_capacity = INI_WordValueINT(linefeed);
if (wordtype == WORD_HARVESTSPEED) units[id].harvesting_speed = INI_WordValueINT(linefeed);
if (wordtype == WORD_HARVESTAMOUNT) units[id].harvesting_amount = INI_WordValueINT(linefeed);
if (wordtype == WORD_PRODUCER) {
string producerString = INI_WordValueString(linefeed);
// determine structure type from that
int type = INI_StructureType(producerString);
// int type = INI_StructureType(producerString.c_str());
units[id].structureTypeItLeavesFrom = type;
}
}
}
// Structure w0h00
if (section == INI_STRUCTURES && id > -1)
{
if (wordtype == WORD_HITPOINTS) {
structures[id].hp = INI_WordValueINT(linefeed);
}
if (wordtype == WORD_FIXHP) structures[id].fixhp = INI_WordValueINT(linefeed);
if (wordtype == WORD_POWERDRAIN) structures[id].power_drain = INI_WordValueINT(linefeed);
if (wordtype == WORD_POWERGIVE) structures[id].power_give = INI_WordValueINT(linefeed);
if (wordtype == WORD_COST) structures[id].cost = INI_WordValueINT(linefeed);
if (wordtype == WORD_BUILDTIME) structures[id].build_time = INI_WordValueINT(linefeed);
}
if (section == INI_SETTINGS) {
switch (wordtype) {
case WORD_FULLSCREEN:
game.windowed = (INI_WordValueBOOL(linefeed) == false);
break;
case WORD_SCREENWIDTH:
game.ini_screen_width=INI_WordValueINT(linefeed);
break;
case WORD_SCREENHEIGHT:
game.ini_screen_height=INI_WordValueINT(linefeed);
break;
case WORD_MP3MUSIC:
game.bMp3 = INI_WordValueBOOL(linefeed);
break;
}
}
} // while
fclose(stream);
} // if
logbook("[GAME.INI] Done");
}
void INI_LOAD_SKIRMISH(char filename[80], bool bScan)
{
// search for new entry in previewed maps
int iNew=-1;
for (int i=0; i < 100; i++)
{
if (PreviewMap[i].name[0] == '\0')
{
iNew=i;
break;
}
}
if (iNew < 0) {
return;
}
// first clear it all out
for (int x=0; x < game.map_width; x++) {
for (int y = 0; y < game.map_height; y++) {
int cll = iCellMake(x, y);
PreviewMap[iNew].mapdata[cll]=TERRAIN_SAND;
}
}
// Load file
FILE *stream; // file stream
int section=INI_NONE; // section
int wordtype=WORD_NONE; // word
int iYLine=0;
int iStart=0;
if( (stream = fopen( filename, "r+t" )) != NULL )
{
char linefeed[MAX_LINE_LENGTH];
char lineword[25];
char linesection[30];
for (int iCl=0; iCl < MAX_LINE_LENGTH; iCl++)
{
linefeed[iCl] = '\0';
if (iCl < 25) lineword[iCl] = '\0';
if (iCl < 30) linesection[iCl] = '\0';
}
// infinite loop baby
while( !feof( stream ) )
{
INI_Sentence(stream, linefeed);
// Linefeed contains a string of 1 sentence. Whenever the first character is a commentary
// character (which is "//", ";" or "#"), or an empty line, then skip it
if (isCommentLine(linefeed)) {
continue; // Skip
}
// Every line is checked for a new section.
INI_Section(linefeed,linesection);
if (linesection[0] != '\0' && strlen(linesection) > 1) {
int iOld=section;
section= INI_SectionType(linesection, section);
// section found
if (iOld != section) {
if (section == INI_MAP) {
if (PreviewMap[iNew].terrain == NULL) {
PreviewMap[iNew].terrain = create_bitmap(128,128);
clear(PreviewMap[iNew].terrain);
//clear_to_color(PreviewMap[iNew].terrain, makecol(255,255,255));
}
continue; // skip
}
}
}
// Okay, we found a new section; if its NOT [GAME] then we remember this one!
if (section != INI_NONE) {
INI_Word(linefeed, lineword);
wordtype = INI_WordType(lineword, section);
} else {
continue;
}
if (section == INI_SKIRMISH)
{
if (wordtype == WORD_MAPNAME)
{
INI_WordValueSENTENCE(linefeed, PreviewMap[iNew].name);
//logbook(PreviewMap[iNew].name);
}
if (wordtype == WORD_STARTCELL) {
if (iStart == 0)
{
for (int i=0; i < 5; i++)
PreviewMap[iNew].iStartCell[i] = -1;
}
// start locations
if (iStart < 5)
{
PreviewMap[iNew].iStartCell[iStart]= INI_WordValueINT(linefeed);
iStart++;
}
}
}
if (section == INI_MAP)
{
int iLength=strlen(linefeed);
// END!
if (iLength < 2) {
break; // done
}
for (int iX=0; iX < iLength; iX++) {
char letter[1];
letter[0] = '\0';
letter[0] = linefeed[iX];
int iCll=iCellMake((iX+1),(iYLine+1));
int iColor=makecol(194, 125, 60);
// rock
if (letter[0] == '%') iColor = makecol(80,80,60);
if (letter[0] == '^') iColor = makecol(80,80,60);
if (letter[0] == '&') iColor = makecol(80,80,60);
if (letter[0] == '(') iColor = makecol(80,80,60);
// mountain
if (letter[0] == 'R') iColor = makecol(48, 48, 36);
if (letter[0] == 'r') iColor = makecol(48, 48, 36);
// spicehill
if (letter[0] == '+') iColor = makecol(180,90,25); // bit darker
// spice
if (letter[0] == '-') iColor = makecol(186,93,32);
// HILLS (NEW)
if (letter[0] == 'H') iColor = makecol(188, 115, 50);
if (letter[0] == 'h') iColor = makecol(188, 115, 50);
if (iCll > -1) {
if (iColor == makecol(194,125,60)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_SAND;
} else if (iColor == makecol(80,80,60)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_ROCK;
} else if (iColor == makecol(48,48,36)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_MOUNTAIN;
} else if (iColor == makecol(180,90,25)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_SPICEHILL;
} else if (iColor == makecol(186,93,32)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_SPICE;
} else if (iColor == makecol(188,115,50)) {
PreviewMap[iNew].mapdata[iCll]=TERRAIN_HILL;
} else {
char msg[255];
sprintf(msg, "iniLoader::skirmish() - Could not determine terrain type for char \"%c\", falling back to SAND", letter[0]);
logbook(msg);
PreviewMap[iNew].mapdata[iCll]=TERRAIN_SAND;
iColor = makecol(255, 255, 255);
}
}
putpixel(PreviewMap[iNew].terrain, 1+(iX*2), 1+(iYLine*2), iColor);
putpixel(PreviewMap[iNew].terrain, 1+(iX*2)+1, 1+(iYLine*2), iColor);
putpixel(PreviewMap[iNew].terrain, 1+(iX*2)+1, 1+(iYLine*2)+1, iColor);
putpixel(PreviewMap[iNew].terrain, 1+(iX*2), 1+(iYLine*2)+1, iColor);
}
iYLine++;
}
} // end of file
// starting points
for (int i=0; i < 5; i++)
{
if (PreviewMap[iNew].iStartCell[i] > -1)
{
int x=iCellGiveX(PreviewMap[iNew].iStartCell[i]);
int y=iCellGiveY(PreviewMap[iNew].iStartCell[i]);
putpixel(PreviewMap[iNew].terrain, 1+(x*2), 1+(y*2), makecol(255,255,255));
putpixel(PreviewMap[iNew].terrain, 1+(x*2)+1, 1+(y*2), makecol(255,255,255));
putpixel(PreviewMap[iNew].terrain, 1+(x*2)+1, 1+(y*2)+1, makecol(255,255,255));
putpixel(PreviewMap[iNew].terrain, 1+(x*2), 1+(y*2)+1, makecol(255,255,255));
}
}
fclose(stream);
} // file exists
}
/*
Pre-scanning of skirmish maps:
- open file
- read [SKIRMISH] data (name of map, startcells, etc)
- create preview of map in BITMAP (minimap preview)
*/
void INI_PRESCAN_SKIRMISH() {
// scans for all ini files
INIT_PREVIEWS(); // clear all of them
struct al_ffblk file;
if (!al_findfirst("skirmish/*", &file, FA_ARCH)) {
do {
char msg[1024];
char fullname[1024];
sprintf(fullname, "skirmish/%s", file.name);
sprintf(msg, "Loading skirmish map: %s", fullname);
logbook(msg);
INI_LOAD_SKIRMISH(fullname, true);
} while (!al_findnext(&file));
} else {
logbook("No skirmish maps found in skirmish directory.");
}
al_findclose(&file);
}
// this code should make it possible to read any ini file in the skirmish
// directory. However, Allegro 4.2.0 somehow gives weird results.
// when upgrading to Allegro 4.2.2, the method works. But FBLEND crashes, even
// after recompiling it against Allegro 4.2.2...
//
// See: http://www.allegro.cc/forums/thread/600998
|
[
"stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151"
] |
[
[
[
1,
2682
]
]
] |
6f036175c37613d4f9aa8225d2b7adf2579a6a06
|
faacd0003e0c749daea18398b064e16363ea8340
|
/3rdparty/phonon/addoninterface.h
|
bbf7c6d03e75f48356cea77b7a3fae7e623eb254
|
[] |
no_license
|
yjfcool/lyxcar
|
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
|
750be6c984de694d7c60b5a515c4eb02c3e8c723
|
refs/heads/master
| 2016-09-10T10:18:56.638922 | 2009-09-29T06:03:19 | 2009-09-29T06:03:19 | 42,575,701 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,095 |
h
|
/* This file is part of the KDE project
Copyright (C) 2007-2008 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PHONON_ADDONINTERFACE_H
#define PHONON_ADDONINTERFACE_H
#include "phononnamespace.h"
#include <QtCore/QList>
#include <QtCore/QVariant>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
#ifndef QT_NO_PHONON_MEDIACONTROLLER
namespace Phonon
{
/** \class AddonInterface addoninterface.h Phonon/AddonInterface
* \short Interface for Menu, Chapter, Angle and Title/Track control.
*
* \author Matthias Kretz <[email protected]>
*/
class AddonInterface
{
public:
virtual ~AddonInterface() {}
enum Interface {
NavigationInterface = 1,
ChapterInterface = 2,
AngleInterface = 3,
TitleInterface = 4,
SubtitleInterface = 5,
AudioChannelInterface = 6
};
enum NavigationCommand {
Menu1Button
};
enum ChapterCommand {
availableChapters,
chapter,
setChapter
};
enum AngleCommand {
availableAngles,
angle,
setAngle
};
enum TitleCommand {
availableTitles,
title,
setTitle,
autoplayTitles,
setAutoplayTitles
};
enum SubtitleCommand {
availableSubtitles,
currentSubtitle,
setCurrentSubtitle
};
enum AudioChannelCommand {
availableAudioChannels,
currentAudioChannel,
setCurrentAudioChannel
};
virtual bool hasInterface(Interface iface) const = 0;
virtual QVariant interfaceCall(Interface iface, int command,
const QList<QVariant> &arguments = QList<QVariant>()) = 0;
};
} // namespace Phonon
Q_DECLARE_INTERFACE(Phonon::AddonInterface, "AddonInterface0.2.phonon.kde.org")
#endif //QT_NO_PHONON_MEDIACONTROLLER
QT_END_NAMESPACE
QT_END_HEADER
#endif // PHONON_ADDONINTERFACE_H
|
[
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
] |
[
[
[
1,
103
]
]
] |
79996b0a50375a05c4c9f1c9f09080e1e5ab6004
|
b6bad03a59ec436b60c30fc793bdcf687a21cf31
|
/som2416/wince5/s3c2450kbd.cpp
|
681617c42bbe556e6bde0e29bbcf1b83c9db4559
|
[] |
no_license
|
blackfa1con/openembed
|
9697f99b12df16b1c5135e962890e8a3935be877
|
3029d7d8c181449723bb16d0a73ee87f63860864
|
refs/heads/master
| 2021-01-10T14:14:39.694809 | 2010-12-16T03:20:27 | 2010-12-16T03:20:27 | 52,422,065 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 21,266 |
cpp
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
#include <windows.h>
#include <ceddk.h>
#include <nkintr.h>
#undef ZONE_INIT
#include <keybddbg.h>
#include <keybddr.h>
#include <keybdpdd.h>
#include <keybdist.h>
#include "s3c2450kbd.hpp"
#include <s3c2450.h>
//[david.modify] 2008-05-16 11:58
#include <args.h>
#include <bsp_cfg.h>
#include <image_cfg.h>
#include <dbgmsg_david.h>
#include <xllp_gpio_david.h>
// Pointer to device control registers
volatile S3C2450_IOPORT_REG *v_pIOPregs;
volatile S3C2450_SPI_REG *v_pSPIregs;
//[david.modify] 2008-05-16 12:08
volatile BSP_ARGS *g_pBspArgs;
//[david. end] 2008-05-16 12:08
DWORD g_dwSysIntr_Keybd = SYSINTR_UNDEFINED;
// Scan code consts
static const UINT8 scE0Extended = 0xe0;
static const UINT8 scE1Extended = 0xe1;
static const UINT8 scKeyUpMask = 0x80;
UINT32
ScanCodeToVKeyEx(
UINT32 ScanCode,
KEY_STATE_FLAGS KeyStateFlags,
UINT32 VKeyBuf[16],
UINT32 ScanCodeBuf[16],
KEY_STATE_FLAGS KeyStateFlagsBuf[16]
);
// There is really only one physical keyboard supported by the system.
Ps2Keybd *v_pp2k;
extern void ReadRegDWORD( LPCWSTR szKeyName, LPCWSTR szValueName, LPDWORD pdwValue );
//[david.modify] 2008-06-12 16:54
//==========================
#include <hotkey.h>
//static BOOL HotKeyHandler (DWORD dwHotKey, DWORD dwScanCode, BOOL bKeyUp);
//static BOOL HotKeyHandlerApp (DWORD dwHotKey, DWORD dwScanCode, BOOL bKeyUp);
static HANDLE g_hAudioVolChangeEvent = NULL;
//static HANDLE g_hAppEvent = NULL;
//#define dim(arr) (sizeof (arr) / sizeof (arr[0]))
#if 0 //unused code, f.w.lin
typedef struct
{
PFN_HOTKEY_HDLR pfHdlr;
HANDLE hEvent;
LPCTSTR szName;
} HOTKEY;
static HOTKEY g_HotKeys [MAX_HOTKEY_NUM];
void HotKeyInit()
{
memset(g_HotKeys, 0, sizeof(g_HotKeys));
}
HANDLE HotKeyRegister (DWORD dwHotKey, PFN_HOTKEY_HDLR pfHdlr, LPTSTR szName)
{
if (dwHotKey < MAX_HOTKEY_NUM)
{
g_HotKeys[dwHotKey].szName = szName;
if (NULL == g_HotKeys [dwHotKey].hEvent)
{
g_HotKeys [dwHotKey].hEvent = CreateEvent (
NULL, FALSE, FALSE, g_HotKeys[dwHotKey].szName);
if (NULL==g_HotKeys [dwHotKey].hEvent)
{
DEBUGMSG(1, (TEXT("HotKeyRegister: create event fail, error code %d\r\n"), GetLastError()));
}
}
if (NULL != g_HotKeys [dwHotKey].hEvent)
{
g_HotKeys [dwHotKey].pfHdlr = pfHdlr;
}
}
return g_HotKeys [dwHotKey].hEvent;
}
// HotKeyProcess() function to call the hotkey handler registered in the g_HotKeys[] in sequence,
// if One handler returns TURE, means the key event is completely handled and not necessary to deliver to other handlers
// otherwise return FALSE means the handler not treat the key or it still necessary to be treated in other handler.
// Retrun value:
// FALSE: the key have not finished handling, continue to be transfer.
// TURE: the key have been finished handling.
BOOL HotKeyProcess (DWORD dwScanCode, BOOL bKeyUp)
{
BOOL bRet = FALSE;
DWORD i;
for (i = 0; i < MAX_HOTKEY_NUM; i++)
{
if (g_HotKeys [i].pfHdlr != NULL)
{
if ((*g_HotKeys [i].pfHdlr)(i, dwScanCode, bKeyUp))
{
bRet = TRUE;
break;
}
}
}
return bRet;
}
#endif
#if 0
// from bsp_cfg.h
// KEYBD 有三个键,对应如下;
//[david.modify] 2008-05-16 10:19
//GPG2 KEY6(up) 音量加EINT10 - down
//GPG1 KEY4 (OK) 确认键EINT9
//GPG0 KEY3 (down) 音量减EINT8 - up
//代表SCANCODE, 在ScanCodeToVKeyTable中映射成VKEY
#define VK_RETURN_SCANCODE 0x5a
#define VK_DOWN_SCANCODE 0x6a
#define VK_UP_SCANCODE 0x6c
#define EINT8_KEY VK_UP_SCANCODE //8
#define EINT9_KEY VK_RETURN_SCANCODE //9
#define EINT10_KEY VK_DOWN_SCANCODE //10
#endif
//#define SCAN_CODE_VOLUP 0x00
//#define SCAN_CODE_VOLDOWN 0x01
#define SCAN_CODE_VOLUP EINT8_KEY
#define SCAN_CODE_VOLDOWN EINT10_KEY
#define SCAN_CODE_APP2 0x02
#define SCAN_CODE_UP 0x08
#define SCAN_CODE_LEFT 0x09
#define SCAN_CODE_RIGHT 0x05
#define SCAN_CODE_DOWN 0x03
#define SCAN_CODE_APP1 0x04
#define SCAN_CODE_APP3 0x06
#define SCAN_CODE_CANCEL 0x07
#define SCAN_CODE_RETURN 0x0A
#define SCAN_CODE_NONE 0xFF
#define KEYPAD_NUM 3
#if 0 //unused code, f.w.lin
static BOOL HotKeyHandler (DWORD dwHotKey, DWORD dwScanCode, BOOL bKeyUp)
{
BOOL bRet = FALSE;
if (dwHotKey == HOTKEY_VOL_CHANGE)
{
bRet = TRUE;
switch (dwScanCode)
{
case SCAN_CODE_VOLUP:
if (bKeyUp)
{
SetEventData (g_hAudioVolChangeEvent, 1);
SetEvent (g_hAudioVolChangeEvent);
}
break;
case SCAN_CODE_VOLDOWN:
if (bKeyUp)
{
SetEventData (g_hAudioVolChangeEvent, 0);
SetEvent (g_hAudioVolChangeEvent);
}
break;
default:
bRet = FALSE;
break;
}
}
return bRet;
}
static BOOL HotKeyHandlerApp (DWORD dwHotKey, DWORD dwScanCode, BOOL bKeyUp)
{
BOOL bRet = FALSE;
if (dwHotKey == HOTKEY_ATLAS_APP)
{
bRet = TRUE;
switch (dwScanCode)
{
case SCAN_CODE_APP1:
if (bKeyUp)
{
SetEventData (g_hAppEvent, 1);
SetEvent (g_hAppEvent);
}
break;
case SCAN_CODE_APP2:
if (bKeyUp)
{
SetEventData (g_hAppEvent, 2);
SetEvent (g_hAppEvent);
}
break;
case SCAN_CODE_APP3:
if (bKeyUp)
{
SetEventData (g_hAppEvent, 3);
SetEvent (g_hAppEvent);
}
break;
default:
bRet = FALSE;
break;
}
}
return bRet;
}
#endif
//==========================
void WINAPI KeybdPdd_PowerHandler(BOOL bOff)
{
if (!bOff) {
v_pp2k->KeybdPowerOn();
}
else {
v_pp2k->KeybdPowerOff();
}
return;
}
#define ONEBIT 0x1
int putcToKBCTL(UCHAR c)
{
UINT i;
v_pSPIregs->SPPIN &= ~(1<<1);
v_pIOPregs->GPLDAT &= ~(ONEBIT << 14); //Set _SS signal to low (Slave Select)
while((v_pSPIregs->SPSTA & 1)==0); // wait while busy
v_pSPIregs->SPTDAT = c; // write left justified data
while((v_pSPIregs->SPSTA & 1)==0); // wait while busy
v_pIOPregs->GPLDAT |= (ONEBIT << 14); //Set _SS signal to high (Slave Select)
v_pSPIregs->SPPIN |= (1<<1);
i = v_pSPIregs->SPRDATB;
return(i);
}
void getsFromKBCTL(UINT8 *m, int cnt) {
int i, j;
volatile tmp = 1;
for(j = 0; j < 3; j++)
tmp += tmp;
for(j = 0; j < 250 * 30; j++)
tmp += tmp;
for(i = 0; i < cnt; i++) {
m[i] = putcToKBCTL(0xFF);
for(j = 0; j < 400; j++)
tmp+= tmp;
}
}
void putsToKBCTL(UINT8 *m, int cnt)
{
int i, j, x;
volatile tmp = 1;
for(j = 0; j < 3; j++)
x = j;
for(j = 0; j < 3; j++)
tmp += tmp;
for(j = 0; j < 250 * 30; j++)
tmp += tmp;
for(i = 0; i < cnt; i++) {
j = putcToKBCTL(m[i]);
for(j = 0; j < 400; j++)
tmp+= tmp;
for(j = 0; j < 400; j++)
x = j;
}
}
char lrc(UINT8 *buffer, int count)
{
char lrc;
int n;
lrc = buffer[0] ^ buffer[1];
for (n = 2; n < count; n++)
{
lrc ^= buffer[n];
}
if (lrc & 0x80)
lrc ^= 0xC0;
return lrc;
}
int USAR_WriteRegister(int reg, int data)
{
UINT8 cmd_buffer[4];
cmd_buffer[0] = 0x1b; //USAR_PH_WR;
cmd_buffer[1] = (unsigned char)reg;
cmd_buffer[2] = (unsigned char)data;
cmd_buffer[3] = lrc((UINT8 *)cmd_buffer,3);
putsToKBCTL((UINT8 *)cmd_buffer,4);
return TRUE;
}
BOOL
KeybdDriverInitializeAddresses(
void
)
{
bool RetValue = TRUE;
DWORD dwIOBase;
DWORD dwSSPBase;
DEBUGMSG(1,(TEXT("++KeybdDriverInitializeAddresses\r\n")));
ReadRegDWORD(TEXT("HARDWARE\\DEVICEMAP\\KEYBD"), _T("IOBase"), &dwIOBase );
if(dwIOBase == 0) {
DEBUGMSG(1, (TEXT("Can't fount registry entry : HARDWARE\\DEVICEMAP\\KEYBD\\IOBase\r\n")));
goto error_return;
}
DEBUGMSG(1, (TEXT("HARDWARE\\DEVICEMAP\\KEYBD\\IOBase:%x\r\n"), dwIOBase));
ReadRegDWORD(TEXT("HARDWARE\\DEVICEMAP\\KEYBD"), _T("SSPBase"), &dwSSPBase );
if(dwSSPBase == 0) {
DEBUGMSG(1, (TEXT("Can't fount registry entry : HARDWARE\\DEVICEMAP\\KEYBD\\SSPBase\r\n")));
goto error_return;
}
DEBUGMSG(1, (TEXT("HARDWARE\\DEVICEMAP\\KEYBD\\SSPBase:%x\r\n"), dwSSPBase));
v_pIOPregs = (volatile S3C2450_IOPORT_REG *)VirtualAlloc(0, sizeof(S3C2450_IOPORT_REG), MEM_RESERVE, PAGE_NOACCESS);
if(v_pIOPregs == NULL) {
DEBUGMSG(1,(TEXT("[KBD] v_pIOPregs : VirtualAlloc failed!\r\n")));
goto error_return;
}
else {
if(!VirtualCopy((PVOID)v_pIOPregs, (PVOID)(dwIOBase), sizeof(S3C2450_IOPORT_REG), PAGE_READWRITE|PAGE_NOCACHE ))
{
DEBUGMSG(1,(TEXT("[KBD] v_pIOPregs : VirtualCopy failed!\r\n")));
goto error_return;
}
}
DEBUGMSG(1, (TEXT("[KBD] v_pIOPregs mapped at %x\r\n"), v_pIOPregs));
v_pSPIregs = (volatile S3C2450_SPI_REG *)VirtualAlloc(0, sizeof(S3C2450_SPI_REG), MEM_RESERVE, PAGE_NOACCESS);
if (v_pSPIregs == NULL) {
DEBUGMSG(1, (TEXT("[KBD] v_pSPIregs : VirtualAlloc failed!\r\n")));
goto error_return;
}
else {
if (!VirtualCopy((PVOID)v_pSPIregs, (PVOID)(dwSSPBase), sizeof(S3C2450_SPI_REG), PAGE_READWRITE | PAGE_NOCACHE))
{
DEBUGMSG(1, (TEXT("[KBD] v_pSPIregs : VirtualCopy failed!\r\n")));
goto error_return;
}
}
//[david.modify] 2008-05-16 12:07
//==================================
if (g_pBspArgs == NULL)
{
PHYSICAL_ADDRESS BspArgsPA = { IMAGE_SHARE_ARGS_PA_START, 0 };
g_pBspArgs = (BSP_ARGS *) MmMapIoSpace(BspArgsPA, sizeof(BSP_ARGS), FALSE);
}
//[david.modify] 2008-06-12 16:53
//添加音量控制; 按音量键, 产生g_hAudioVolChangeEvent事件;
// AUDIO驱动收到g_hAudioVolChangeEvent事件,产生MSG
//=========================
// g_hAudioVolChangeEvent = HotKeyRegister (HOTKEY_VOL_CHANGE, HotKeyHandler, ATLAS_AUDIO_VOL_EVENT);
g_hAudioVolChangeEvent = CreateEvent(NULL, FALSE, FALSE, ATLAS_AUDIO_VOL_EVENT);
if (g_hAudioVolChangeEvent == NULL)
{
RetValue=FALSE;
}
DPNOK(g_hAudioVolChangeEvent);
//==================================
DEBUGMSG(1, (TEXT("[KBD] v_pSPIregs mapped at %x\r\n"), v_pSPIregs));
DEBUGMSG(1,(TEXT("--KeybdDriverInitializeAddresses\r\n")));
return TRUE;
error_return:
if ( v_pIOPregs )
VirtualFree((PVOID)v_pIOPregs, 0, MEM_RELEASE);
if ( v_pSPIregs )
VirtualFree((PVOID)v_pSPIregs, 0, MEM_RELEASE);
v_pIOPregs = 0;
v_pSPIregs = 0;
DEBUGMSG(1,(TEXT("--KeybdDriverInitializeAddresses[FAILED!!!]\r\n")));
return FALSE;
}
static UINT KeybdPdd_GetEventEx2(UINT uiPddId, UINT32 rguiScanCode[16], BOOL rgfKeyUp[16])
{
SETFNAME(_T("KeybdPdd_GetEventEx2"));
UINT32 scInProgress = 0;
static UINT32 scPrevious;
BOOL fKeyUp;
UINT8 ui8ScanCode;
UINT cEvents = 0;
stGPIOInfo stGPIOInfo; //[david.modify] 2008-05-17 12:03
DEBUGCHK(rguiScanCode != NULL);
DEBUGCHK(rgfKeyUp != NULL);
//[david.modify] 2008-05-16 12:02
//=====================================
//getsFromKBCTL(&ui8ScanCode, 1);
ui8ScanCode = g_pBspArgs->uninit_misc.dwButtonType;
RETAILMSG(1,(TEXT("KEY:0x%X\n"),ui8ScanCode));
DPNOK(ui8ScanCode);
//=====================================
#if 0
DEBUGMSG(ZONE_SCANCODES,
(_T("%s: scan code 0x%08x, code in progress 0x%08x, previous 0x%08x\r\n"),
pszFname, ui8ScanCode, scInProgress, scPrevious));
#endif
//[david.modify] 2008-05-17 10:40
//==========================
//按键有上升沿和下降沿两次中断
#if 0
#define VK_RETURN_SCANCODE 0x5a
#define VK_DOWN_SCANCODE 0x6a
#define VK_UP_SCANCODE 0x6c
#define EINT8_KEY VK_DOWN_SCANCODE //8
#define EINT9_KEY VK_RETURN_SCANCODE //9
#define EINT10_KEY VK_UP_SCANCODE //10
// KEYBD 有三个键,对应如下;
//[david.modify] 2008-05-16 10:19
//GPG2 KEY6(up) 音量加EINT10 - down
//GPG1 KEY4 (OK) 确认键EINT9
//GPG0 KEY3 (down) 音量减EINT8 - up
//代表SCANCODE, 在ScanCodeToVKeyTable中映射成VKEY
#define VK_RETURN_SCANCODE 0x5a
#define VK_DOWN_SCANCODE 0x6a
#define VK_UP_SCANCODE 0x6c
#define EINT8_KEY VK_UP_SCANCODE //8
#define EINT9_KEY VK_RETURN_SCANCODE //9
#define EINT10_KEY VK_DOWN_SCANCODE //10
#endif
#define SCAN_CODE_VOLUP EINT8_KEY
#define SCAN_CODE_VOLDOWN EINT10_KEY
DPNOK(ui8ScanCode);
if(ui8ScanCode==SCAN_CODE_VOLUP) {
stGPIOInfo.u32PinNo = GPG0;
GetGPIOInfo(&stGPIOInfo, (void*)v_pIOPregs);
DPNOK(stGPIOInfo.u32Stat);
if(stGPIOInfo.u32Stat) { //high
ui8ScanCode|=scKeyUpMask;
SetEventData (g_hAudioVolChangeEvent, 1);
SetEvent (g_hAudioVolChangeEvent);
}else{ //low
}
}
else if(ui8ScanCode==EINT9_KEY) {
stGPIOInfo.u32PinNo = GPG1;
GetGPIOInfo(&stGPIOInfo, (void*)v_pIOPregs);
DPNOK(stGPIOInfo.u32Stat);
if(stGPIOInfo.u32Stat) { //high
ui8ScanCode|=scKeyUpMask;
}else{ //low
}
}
else if(ui8ScanCode==SCAN_CODE_VOLDOWN) {
stGPIOInfo.u32PinNo = GPG2;
DPNOK(stGPIOInfo.u32Stat);
GetGPIOInfo(&stGPIOInfo, (void*)v_pIOPregs);
if(stGPIOInfo.u32Stat) { //high
ui8ScanCode|=scKeyUpMask;
SetEventData (g_hAudioVolChangeEvent, 0);
SetEvent (g_hAudioVolChangeEvent);
}else{ //low
}
}
//==========================
scInProgress = ui8ScanCode;
if (scInProgress == scPrevious) {
// mdd handles auto-repeat so ignore auto-repeats from keybd
} else {
// Not a repeated key. This is the real thing.
scPrevious = scInProgress;
if (ui8ScanCode & scKeyUpMask) {
fKeyUp = TRUE;
scInProgress &= ~scKeyUpMask;
} else {
fKeyUp = FALSE;
}
rguiScanCode[cEvents] = scInProgress;
rgfKeyUp[cEvents] = fKeyUp;
++cEvents;
}
return cEvents;
}
void WINAPI KeybdPdd_ToggleKeyNotification(KEY_STATE_FLAGS KeyStateFlags)
{
unsigned int fLights;
DEBUGMSG(1, (TEXT("KeybdPdd_ToggleKeyNotification\r\n")));
fLights = 0;
if (KeyStateFlags & KeyShiftCapitalFlag) {
fLights |= 0x04;
}
if (KeyStateFlags & KeyShiftNumLockFlag) {
fLights |= 0x2;
}
/*
Keyboard lights is disabled once driver is installed because the
PS2 controller sends back a response which goes to the IST and corrupts
the interface. When we figure out how to disable the PS2 response we
can re-enable the lights routine below
*/
return;
}
BOOL Ps2Keybd::IsrThreadProc()
{
DWORD dwPriority;
//DWORD dwIrq_Keybd = 0;
// look for our priority in the registry -- this routine sets it to zero if
// it can't find it.
ReadRegDWORD( TEXT("HARDWARE\\DEVICEMAP\\KEYBD"), _T("Priority256"), &dwPriority );
if(dwPriority == 0) {
dwPriority = 240; // default value is 145
}
DEBUGMSG(1, (TEXT("IsrThreadProc:\r\n")));
m_hevInterrupt = CreateEvent(NULL,FALSE,FALSE,NULL);
if (m_hevInterrupt == NULL) {
DEBUGMSG(1, (TEXT("IsrThreadProc: InterruptInitialize\r\n")));
goto leave;
}
//ReadRegDWORD( TEXT("HARDWARE\\DEVICEMAP\\KEYBD"), _T("Irq"), &dwIrq_Keybd );
//[david.modify] 2008-05-16 09:50
//======================================
/*
[HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\KEYBD]
"DriverName"="kbdmouse.dll"
"Irq"=dword:2
"IOBase"=dword:B2100000
"SSPBase"=dword:B1D00000
*/
//===============================================
//DPNOK(dwIrq_Keybd);
// Call the OAL to translate the IRQ into a SysIntr value.
// EINT1
#if 0
if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &dwIrq_Keybd, sizeof(DWORD), &g_dwSysIntr_Keybd, sizeof(DWORD), NULL))
{
RETAILMSG(1, (TEXT("ERROR: Failed to obtain sysintr value for keyboard interrupt.\r\n")));
g_dwSysIntr_Keybd = SYSINTR_UNDEFINED;
goto leave;
}
#endif
//[david.modify] 2008-05-16 11:58
// 强制指定KEYPAD中断INTR
g_dwSysIntr_Keybd = SYSINTR_KEYPAD;
if (!InterruptInitialize(g_dwSysIntr_Keybd,m_hevInterrupt,NULL,0)) {
DEBUGMSG(1, (TEXT("IsrThreadProc: KeybdInterruptEnable\r\n")));
goto leave;
}
// update the IST priority
CeSetThreadPriority(GetCurrentThread(), (int)dwPriority);
extern UINT v_uiPddId;
extern PFN_KEYBD_EVENT v_pfnKeybdEvent;
KEYBD_IST keybdIst;
keybdIst.hevInterrupt = m_hevInterrupt;
keybdIst.dwSysIntr_Keybd = g_dwSysIntr_Keybd;
keybdIst.uiPddId = v_uiPddId;
keybdIst.pfnGetKeybdEvent = KeybdPdd_GetEventEx2;
keybdIst.pfnKeybdEvent = v_pfnKeybdEvent;
KeybdIstLoop(&keybdIst);
leave:
return 0;
}
DWORD Ps2KeybdIsrThread(Ps2Keybd *pp2k)
{
DEBUGMSG(1,(TEXT("Ps2KeybdIsrThread:\r\n")));
pp2k->IsrThreadProc();
return 0;
}
BOOL Ps2Keybd::IsrThreadStart()
{
HANDLE hthrd;
DEBUGMSG(1,(TEXT("IsrThreadStart:\r\n")));
hthrd = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Ps2KeybdIsrThread,this,0,NULL);
// Since we don't need the handle, close it now.
CloseHandle(hthrd);
return TRUE;
}
BOOL Ps2Keybd::Initialize()
{
DEBUGMSG(1,(TEXT("Ps2Keybd::Initialize\r\n")));
DEBUGMSG(1,(TEXT("Ps2Keybd::Initialize Done\r\n")));
return TRUE;
}
BOOL Ps2Keybd::KeybdPowerOn()
{
// UINT8 msg[5];
// int t;
char dummy = (char)0xff;
DEBUGMSG(1,(TEXT("++Ps2Keybd::KeybdPowerOn\r\n")));
#if 0
// Setup KBDINT as output
v_pIOPregs->GPFCON &= ~(0x3 << 4); // Clear GPF2
v_pIOPregs->GPFCON |= (0x2 << 4); // Set GPF2 to EINT2 for Keyboard interrupt
v_pIOPregs->GPFUDP &= ~(0x3 << 4);
v_pIOPregs->GPFUDP |= (0x1 << 4);
v_pIOPregs->EXTINT0 = READEXTINT0(v_pIOPregs->EXTINT0) & ~(0x7 << 8); // Clear EINT2
v_pIOPregs->EXTINT0 = READEXTINT0(v_pIOPregs->EXTINT0) | (0xA << 8); // fallig edge triggered for EINT2
// setup SPI interface
// GPL12 : SPIMISO (KBDSPIMISO)
// GPL11 : SPIMOSI (KBDSPIMOSI)
// GPL10 : SPICLK (KBDSPICLK)
v_pIOPregs->GPLCON &= ~((0x3 << 24) | (0x3 << 22) | (0x3 << 20)); // Clear GPG12,11,10
v_pIOPregs->GPLCON |= ((0x2 << 24) | (0x2 << 22) | (0x2 << 20));
v_pIOPregs->GPLUDP &= ~((0x3 << 24) | (0x3 << 22) | (0x3 << 20));
v_pIOPregs->GPLUDP |= ((0x1 << 24) | (0x1 << 22) | (0x1 << 20));
// setup _SS signal(nSS_KBD)
v_pIOPregs->GPLCON &= ~(0x3 << 28); // Clear GPL14
v_pIOPregs->GPLCON |= (1 << 28); // Set Port GPL14 to output for nSS signal
v_pIOPregs->GPLUDP &= ~((0x3 << 28));
v_pIOPregs->GPLUDP |= ((0x1 << 28));
// setup _PWR_OK signal (KEYBOARD)
v_pIOPregs->GPFCON &= ~(0x3 << 6); // Clear GPF3
v_pIOPregs->GPFCON |= (1 << 6); // Set Port GPF3 to output for _PWR_OK signal
v_pIOPregs->GPFUDP &= ~((0x3 << 6));
v_pIOPregs->GPFUDP |= ((0x1 << 6));
v_pIOPregs->GPFDAT &=~(1 << 3); // set _PWR_OK to 0
// Setup IO port for SPI interface & Keyboard
// Setup SPI registers
// Interrupt mode, prescaler enable, master mode, active high clock, format B, normal mode
v_pSPIregs->SPCON &=~(0x3f<<0);
v_pSPIregs->SPCON |= (1<<5)|(1<<4)|(1<<3)|(0x0<<2)|(1<<1);
v_pSPIregs->SPPIN |= (1<<0);//Feedback Clock Disable, Master Out Keep
// Developer MUST change the value of prescaler properly whenever value of PCLK is changed.
v_pSPIregs->SPPRE = 255;// 99.121K = 203M/4/2/(255+1) PCLK=50.75Mhz FCLK=203Mhz SPICLK=99.121Khz
for(t=0;t<20000; t++); // delay
msg[0] = (char)0x1b; msg[1] = (char)0xa0; msg[2] = (char)0x7b; msg[3] = (char)0; // Initialize USAR
for(t=0; t < 10; t++) {
dummy = putcToKBCTL(0xff);
}
for(t=0; t<10; t++) { // wait for a while
putsToKBCTL(msg,3);
for(t=0;t<20000; t++);
}
t = 100;
while(t--) {
volatile unsigned int read_atn = 0;
v_pIOPregs->GPFCON &= ~(3<<4);
read_atn = v_pIOPregs->GPFDAT & 0x04;
v_pIOPregs->GPFCON |= (2<< 4);
if(read_atn == 0) { // Read _ATN
break;
}
} //check _ATN
if(t != 0) {
getsFromKBCTL(msg,3);
}
t=100000;
while(t--); // delay
msg[0] = (char)0x1b; msg[1] = (char)0xa1; msg[2] = (char)0x7a; msg[3] = (char)0; //Initialization complete
putsToKBCTL(msg,3);
#endif
DEBUGMSG(1,(TEXT("--Ps2Keybd::KeybdPowerOn\r\n")));
return(TRUE);
}
BOOL Ps2Keybd::KeybdPowerOff()
{
DEBUGMSG(1,(TEXT("++Ps2Keybd::KeybdPowerOff\r\n")));
DEBUGMSG(1,(TEXT("--Ps2Keybd::KeybdPowerOff\r\n")));
return(TRUE);
}
|
[
"[email protected]"
] |
[
[
[
1,
811
]
]
] |
df3f72a726837172d6e76a194b53a8fb9fbe778b
|
f2cf9ead30a7298b3c1ec672ac118429fbac0a40
|
/Poc1/Source/Poc1.Fast.Terrain/Source/SphereCloudsBitmap.cpp
|
7a3a7b5287c5a233199dd6c56f1b1351c1eeaf38
|
[] |
no_license
|
johann-gambolputty/robotbastards
|
3af0b6cf5d948e8bb0450d596ecb5362bfe5a28d
|
1874568ada150e04ba83fff2ea067f5a4b63f893
|
refs/heads/master
| 2021-01-10T09:52:51.773773 | 2009-08-08T00:19:33 | 2009-08-08T00:19:33 | 44,774,636 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,043 |
cpp
|
#include "StdAfx.h"
#include "SphereCloudsBitmap.h"
#include "Sse/SseRidgedFractal.h"
#include "Sse/SseSimpleFractal.h"
#include "Mem.h"
#include "UEnums.h"
#pragma unmanaged
namespace Poc1
{
namespace Fast
{
namespace Terrain
{
class _CRT_ALIGN( 16 ) SphereCloudsBitmapImpl
{
public :
SphereCloudsBitmapImpl( )
{
// m_Gen.Setup( 2.5f, 0.8f, 8 );
m_Gen.Setup( 1.5f, 0.8f, 8 );
}
void Setup( const float xOffset, const float zOffset, const float cloudCutoff, const float cloudBorder )
{
m_XOffset = _mm_set1_ps( xOffset );
m_ZOffset = _mm_set1_ps( zOffset );
m_CloudCutoff = _mm_mul_ps( _mm_set1_ps( cloudCutoff ), _mm_set1_ps( 255.0f ) );
m_CloudBorder = _mm_mul_ps( _mm_set1_ps( cloudBorder ), _mm_set1_ps( 255.0f ) );
m_CloudBorderDiff = _mm_div_ps( _mm_set1_ps( 255.0f ), _mm_sub_ps( m_CloudBorder, m_CloudCutoff ) );
}
void GenerateCloudsFace( const UCubeMapFace face, const UPixelFormat format, const int width, const int height, const int stride, unsigned char* pixels );
private :
__m128 m_XOffset;
__m128 m_ZOffset;
__m128 m_CloudCutoff;
__m128 m_CloudBorder;
__m128 m_CloudBorderDiff;
// SseRidgedFractal m_Gen;
SseSimpleFractal m_Gen;
};
inline __m128 CubeFaceFractal( const SseRidgedFractal& fractal, const UCubeMapFace face, const __m128& uuuu, const __m128& vvvv, const __m128& xOffset, const __m128& zOffset )
{
__m128 xxxx, yyyy, zzzz;
CubeFacePosition( face, uuuu, vvvv, xxxx, yyyy, zzzz );
SetLength( xxxx, yyyy, zzzz, 3.0f );
// return fractal.GetValue( _mm_add_ps( xxxx, xOffset ), yyyy, _mm_add_ps( zzzz, zOffset ) );
__m128 res = fractal.GetValue( _mm_add_ps( xxxx, xOffset ), yyyy, _mm_add_ps( zzzz, zOffset ) );
return res;
}
inline __m128 CubeFaceFractal( const SseSimpleFractal& fractal, const UCubeMapFace face, const __m128& uuuu, const __m128& vvvv, const __m128& xOffset, const __m128& zOffset )
{
__m128 xxxx, yyyy, zzzz;
CubeFacePosition( face, uuuu, vvvv, xxxx, yyyy, zzzz );
SetLength( xxxx, yyyy, zzzz, 6.0f );
// __m128 res = fractal.GetValue( _mm_add_ps( xxxx, xOffset ), yyyy, _mm_add_ps( zzzz, zOffset ) );
// return _mm_mul_ps( _mm_set1_ps( 255 ), res );
xxxx = _mm_add_ps( xxxx, xOffset );
zzzz = _mm_add_ps( zzzz, zOffset );
__m128 res = fractal.GetValue( xxxx, yyyy, zzzz );
xxxx = _mm_add_ps( res, xxxx );
zzzz = _mm_add_ps( res, zzzz );
res = fractal.GetValue( xxxx, yyyy, zzzz );
res = _mm_mul_ps( res, res ); // TODO: AP: ^1.55 is better - need an SSE2 pow function though - see: http://jrfonseca.blogspot.com/2008/09/fast-sse2-pow-tables-or-polynomials.html
__m128 offset = _mm_set1_ps( 0.25f );
__m128 invOffset = _mm_sub_ps( _mm_set1_ps( 1 ), offset );
res = _mm_div_ps( _mm_sub_ps( res, offset ), invOffset );
// Clamp to 0-1 range
res = Clamp( res, _mm_set1_ps( 0 ), _mm_set1_ps( 1 ) );
return res;
}
void SphereCloudsBitmapImpl::GenerateCloudsFace( const UCubeMapFace face, const UPixelFormat format, const int width, const int height, const int stride, unsigned char* pixels )
{
float fRes = 2.0f;
float hfRes = fRes / 2;
float incU = fRes / float( width - 1 );
float incV = fRes / float( height - 1 );
__m128 vvvv = _mm_set1_ps( -hfRes );
__m128 vvvvInc = _mm_set1_ps( incV );
__m128 uuuuStart = _mm_add_ps( _mm_set1_ps( -hfRes ), _mm_set_ps( 0, incU, incU * 2, incU * 3 ) );
__m128 uuuuInc = _mm_set1_ps( incU * 4 );
_CRT_ALIGN( 16 ) float res[ 4 ] = { 0, 0, 0, 0 };
_CRT_ALIGN( 16 ) float alphaValues[ 4 ] = { 0, 0, 0, 0 };
int width4 = width / 4;
unsigned char* rowPixel = pixels;
for ( int row = 0; row < height; ++row )
{
unsigned char* curPixel = rowPixel;
__m128 uuuu = uuuuStart;
for ( int col = 0; col < width4; ++col )
{
/*
private void Cyclone( ref float x, ref float y, float cX, float cY, float
cR )
{
float dX = x - cX;
float dY = y - cY;
float dC2 = ( dX * dX ) + ( dY * dY );
if ( dC2 > cR * cR )
{
return;
}
float dC = ( float )Math.Sqrt( dC2 );
float rS = ( 1 - ( dC / cR ) );
float rot = ( rS * rS ) * 0.6f * ( float )Math.PI;
rot += m_Noise.GetNoise( rot, 1.124570f, 1.124570f ) * 0.2f * rS;
float sRot = ( float )Math.Sin( rot );
float cRot = ( float )Math.Cos( rot );
x = cX + ( float )( dX * cRot - dY * sRot );
y = cY + ( float )( dX * sRot + dY * cRot );
}
private Color GetValue( float x, float y )
{
// Cyclone( ref x, ref y, 0.5f, 0.5f, 0.4f );
// float n0 = m_Noise.GetNoise( 2.0098f + x * 15.917894f, 5.0973502375f +
y * 15.917894f, 0 );
// float res = m_Noise.GetNoise( n0 + x * 10.109175f, n0 + y *
10.109175f, 0 );
float res = fBm( 2.0098f + x * 3.012839f, 3.0973502375f + y * 5.012839f,
2.2f, 12, 0.51f );
res = fBm( res + x * 6.012839f, res + y * 6.012839f, 2.1f, 16, 0.5f );
res = res < 0 ? 0 : res > 1 ? 1 : res;
res = ( float )Math.Pow( res, 1.55f );
float offset = 0.3f;
if ( res < offset )
{
return Color.Black;
}
res = ( res - offset ) / ( 1 - offset );
res *= 255.0f;
int c = ( int )( Math.Max( 0, Math.Min( res, 255 ) ) );
return Color.FromArgb( c, c, c );
}
*/
// TODO: AP: Could move face switch to outer loop
// __m128 value = CubeFaceFractal( m_Gen, face, uuuu, vvvv, m_XOffset, m_ZOffset );
// value = _mm_mul_ps( value, _mm_set1_ps( 255.0f ) );
// __m128 cutMask = _mm_cmpgt_ps( value, m_CloudCutoff );
// value = _mm_and_ps( cutMask, value );
__m128 value = CubeFaceFractal( m_Gen, face, uuuu, vvvv, m_XOffset, m_ZOffset );
__m128 scaledValue = _mm_mul_ps( value, _mm_set1_ps( 255 ) );
_mm_store_ps( res, scaledValue );
unsigned char b0 = 0xff; //( unsigned char )( res[ 3 ] );
unsigned char b1 = 0xff; //( unsigned char )( res[ 2 ] );
unsigned char b2 = 0xff; //( unsigned char )( res[ 1 ] );
unsigned char b3 = 0xff; //( unsigned char )( res[ 0 ] );
switch ( format )
{
case FormatR8G8B8A8 :
{
// const __m128 borderMask = _mm_cmpgt_ps( value, m_CloudBorder );
// const __m128 fadeValue = _mm_mul_ps( _mm_sub_ps( value, m_CloudCutoff ), m_CloudBorderDiff );
// __m128 alpha = _mm_or_ps( _mm_and_ps( borderMask, _mm_set1_ps( 255.0f ) ), _mm_andnot_ps( borderMask, fadeValue ) );
// alpha = _mm_and_ps( cutMask, alpha );
// _mm_store_ps( alphaValues, alpha );
__m128 alpha = _mm_min_ps( _mm_set1_ps( 255 ), _mm_mul_ps( scaledValue, _mm_set1_ps( 8 ) ) );
_mm_store_ps( alphaValues, alpha );
unsigned char a0 = ( unsigned char )( alphaValues[ 3 ] );
unsigned char a1 = ( unsigned char )( alphaValues[ 2 ] );
unsigned char a2 = ( unsigned char )( alphaValues[ 1 ] );
unsigned char a3 = ( unsigned char )( alphaValues[ 0 ] );
curPixel[ 0 ] = curPixel[ 1 ] = curPixel[ 2 ] = b0; curPixel[ 3 ] = a0;
curPixel[ 4 ] = curPixel[ 5 ] = curPixel[ 6 ] = b1; curPixel[ 7 ] = a1;
curPixel[ 8 ] = curPixel[ 9 ] = curPixel[ 10 ] = b2; curPixel[ 11 ] = a2;
curPixel[ 12 ] = curPixel[ 13 ] = curPixel[ 14 ] = b3; curPixel[ 15 ] = a3;
curPixel += 16;
break;
};
case FormatR8G8B8 :
curPixel[ 0 ] = curPixel[ 1 ] = curPixel[ 2 ] = b0;
curPixel[ 3 ] = curPixel[ 4 ] = curPixel[ 5 ] = b1;
curPixel[ 6 ] = curPixel[ 7 ] = curPixel[ 8 ] = b2;
curPixel[ 9 ] = curPixel[ 10 ] = curPixel[ 11 ] = b3;
curPixel += 12;
break;
};
uuuu = _mm_add_ps( uuuu, uuuuInc );
}
vvvv = _mm_add_ps( vvvv, vvvvInc );
rowPixel += stride;
}
}
}; //Terrain
}; //Fast
}; //Poc1
#pragma managed
using namespace Rb::Rendering::Interfaces::Objects;
namespace Poc1
{
namespace Fast
{
namespace Terrain
{
SphereCloudsBitmap::SphereCloudsBitmap( )
{
m_pImpl = new ( Aligned( 16 ) ) SphereCloudsBitmapImpl;
}
SphereCloudsBitmap::~SphereCloudsBitmap( )
{
AlignedDelete( m_pImpl );
}
SphereCloudsBitmap::!SphereCloudsBitmap( )
{
AlignedDelete( m_pImpl );
}
void SphereCloudsBitmap::Setup( float xOffset, float zOffset, float cloudCutoff, float cloudBorder )
{
m_pImpl->Setup( xOffset, zOffset, cloudCutoff, cloudBorder );
}
void SphereCloudsBitmap::GenerateFace( CubeMapFace face, PixelFormat format, const int width, const int height, const int stride, unsigned char* pixels )
{
m_pImpl->GenerateCloudsFace( GetUCubeMapFace( face ), GetUPixelFormat( format ), width, height, stride, pixels );
}
}; //Terrain
}; //Fast
}; //Poc1
|
[
"fishy.coder@1e31eab0-7329-0410-87fb-016d5637cad0"
] |
[
[
[
1,
259
]
]
] |
e5df139c7716aa19a31331fb6f33c3fc032b7caf
|
f96efcf47a7b6a617b5b08f83924c7384dcf98eb
|
/tags/mucc_1_0_5_10/ChatWindow.h
|
9ec7dc10d8c503e2b8b43cb94eb399efcf5b0492
|
[] |
no_license
|
BackupTheBerlios/mtlen-svn
|
0b4e7c53842914416ed3f6b1fa02c3f1623cac44
|
f0ea6f0cec85e9ed537b89f7d28f75b1dc108554
|
refs/heads/master
| 2020-12-03T19:37:37.828462 | 2011-12-07T20:02:16 | 2011-12-07T20:02:16 | 40,800,938 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,181 |
h
|
/*
MUCC Group Chat GUI Plugin for Miranda IM
Copyright (C) 2004 Piotr Piastucki
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
class ChatWindow;
#ifndef CHATWINDOW_INCLUDED
#define CHATWINDOW_INCLUDED
#include "mucc.h"
#include "ChatEvent.h"
#include "ChatUser.h"
#include "AdminWindow.h"
#include "ChatContainer.h"
#define DM_CHAT_EVENT (WM_USER+1)
#define DM_CHAT_QUERY (WM_USER+2)
#define WM_TLEN_SMILEY (WM_USER+200)
class ChatWindow{
private:
static ChatWindow * list;
static CRITICAL_SECTION mutex;
static bool released;
static HFONT hListGroupFont, hListFont;
static COLORREF colorListBg, colorListText, colorListGroupText;
static COLORREF colorInputBg, colorLogBg;
ChatContainer * container;
HANDLE hEvent;
HWND hWnd;
HFONT hEditFont;
HTREEITEM hUserGroups[5];
char * module;
char * roomId;
char * roomName;
char * topic;
int options;
int roomFlags;
int font, fontSize;
int bBold, bItalic, bUnderline;
int wasFirstMessage;
COLORREF fontColor;
int isStarted;
ChatWindow * prev;
ChatWindow * next;
int adminDialogMode;
AdminWindow * adminWindow;
ChatUser * users;
ChatUser * userMe;
void addUser(ChatUser *);
void removeUser(ChatUser *);
ChatUser * findUser(const char *);
int getUserGroup(ChatUser *);
ChatUser * getSelectedUser();
ChatEventList eventList;
int appendMessage(const MUCCEVENT *event);
int appendEvent(const MUCCEVENT *event);
void rebuildLog();
int logMessage(const MUCCEVENT *event);
public:
enum LOGFLAGS {
FLAG_SHOW_NICKNAMES = 0x00000001,
FLAG_MSGINNEWLINE = 0x00000002,
FLAG_SHOW_DATE = 0x00000010,
FLAG_SHOW_TIMESTAMP = 0x00000020,
FLAG_SHOW_SECONDS = 0x00000040,
FLAG_LONG_DATE = 0x00000080,
FLAG_FORMAT_FONT = 0x00000100,
FLAG_FORMAT_SIZE = 0x00000200,
FLAG_FORMAT_COLOR = 0x00000400,
FLAG_FORMAT_STYLE = 0x00000800,
FLAG_FORMAT_ALL = 0x00000F00,
FLAG_LOG_MESSAGES = 0x00001000,
FLAG_LOG_JOINED = 0x00002000,
FLAG_LOG_LEFT = 0x00004000,
FLAG_LOG_TOPIC = 0x00008000,
FLAG_LOG_ALL = 0x0000F000,
FLAG_OPT_SENDONENTER= 0x01000000
};
enum ADMINMODES {
ADMIN_MODE_KICK = 1,
ADMIN_MODE_ROLE = 2,
ADMIN_MODE_BROWSER = 3
};
int hSplitterPos;
int vSplitterPos;
int hSplitterMinBottom;
int hSplitterMinTop;
int vSplitterMinLeft;
int vSplitterMinRight;
ChatWindow (MUCCWINDOW *);
~ChatWindow ();
ChatWindow * getNext();
void setNext(ChatWindow *);
ChatWindow * getPrev();
ChatContainer* getContainer();
void setPrev(ChatWindow *);
void setHWND(HWND);
HWND getHWND();
HANDLE getEvent();
const char * getModule();
void setModule(const char *);
const char * getRoomId();
void setRoomId(const char *);
const char * getRoomName();
void setRoomName(const char *);
void setOptions(int);
int getOptions();
void setRoomFlags(int);
int getRoomFlags();
int getFontSizeNum();
int getFontSize(int);
int getFontNameNum();
const char * getFontName(int);
void setFont(int font, int size, int bBold, int bItalic, int bUnderline, COLORREF color);
int getFont();
int getFontSize();
int getFontStyle();
COLORREF getFontColor();
int start();
int startPriv();
void startAdminDialog(int mode);
int kickAndBan(int time);
int kickAndBan(const char *id, int time, const char *);
int unban(const char *id);
int setRights(int flags);
int setRights(const char *id, int flags);
void queryResultContacts(MUCCQUERYRESULT *queryResult);
void queryResultUsers(MUCCQUERYRESULT *queryResult);
void setTreeItem(int, HTREEITEM);
HTREEITEM getTreeItem(int);
ChatUser * findUserByNick(const char *);
ChatUser * getMe();
void refreshSettings();
void setAdminWindow(AdminWindow *);
AdminWindow * getAdminWindow();
int logEvent(const MUCCEVENT *event);
int changePresence(const MUCCEVENT *event);
int changeTopic(const MUCCEVENT *event);
int changeRoomInfo(const MUCCEVENT *event);
int leave();
static void refreshSettings(int force);
static HFONT getListGroupFont();
static HFONT getListFont();
static COLORREF getListTextColor();
static COLORREF getListGroupTextColor();
static int getDefaultOptions();
static void init();
static void release();
static ChatWindow * getWindow(const char *module, const char *roomId);
};
#endif
|
[
"the_leech@3f195757-89ef-0310-a553-cc0e5972f89c"
] |
[
[
[
1,
179
]
]
] |
acba139ee6da6f7c84b5e8bddae568f1cd70cabf
|
3d9e738c19a8796aad3195fd229cdacf00c80f90
|
/src/gui/gl_widget_2/GL_widget_2.cpp
|
d3297318738dbda7d45ddfccf5eecf7d871ba405
|
[] |
no_license
|
mrG7/mesecina
|
0cd16eb5340c72b3e8db5feda362b6353b5cefda
|
d34135836d686a60b6f59fa0849015fb99164ab4
|
refs/heads/master
| 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 39,023 |
cpp
|
/* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info: http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: GL_widget_2.cpp 586 2009-04-03 20:01:21Z miklosb $
*/
#include <algorithm>
#include <iostream>
#include <math.h>
#include <QtCore/QSettings>
#include <GL/glew.h>
#include <QtOpenGL/QGLPixelBuffer>
#include <constants.h>
#include <gui/app/static/Application_settings.h>
#include <gui/app/static/Color_map_factory.h>
#include <gui/gl_widget_2/GL_widget_2.h>
#include <gui/gl_widget/Visualization_layer.h>
//#include "Computation_thread.h"
double round(double x) {
if(x>=0.5){return ceil(x);}else{return floor(x);}
}
GL_widget_2::GL_widget_2(QWidget * parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), renderer_type(OPEN_GL), use_display_lists(true) {
std::cout << "widget constructor called" << std::endl;
xmin = xmin_old = -300;
xmax = xmax_old = 100;
ymin = ymin_old = -300;
ymax = ymax_old = 300;
layers.clear();
default_cursor = cursor();
default_bounding_box = true;
bounding_ymin = bounding_xmin = -1;
bounding_ymax = bounding_xmax = 1;
painter = 0;
pbuffer = 0;
dynamic_texture = 0;
rendering_effect = RENDERING_NORMAL;
want_repaint = false;
// full_screen = false;
QSettings settings;
if (!settings.contains("npr-render")) {
settings.setValue("npr-render", false);
} Application_settings::add_setting("npr-render", AS_BOOL);
if (!settings.contains("npr-render-paper")) {
settings.setValue("npr-render-paper", true);
} Application_settings::add_setting("npr-render-paper", AS_BOOL);
if (!settings.contains("npr-render-distortion")) {
settings.setValue("npr-render-distortion", (double)0.015);
} Application_settings::add_setting("npr-render-distortion", AS_DOUBLE);
if (!settings.contains("npr-render-edge-detection-width")) {
settings.setValue("npr-render-edge-detection-width", (double)0.001);
} Application_settings::add_setting("npr-render-edge-detection-width", AS_DOUBLE);
if (settings.value("npr-render").toBool()) rendering_effect = RENDERING_PENCIL;
Application_settings::add_int_setting("background-color-red", 255);
Application_settings::add_int_setting("background-color-green", 255);
Application_settings::add_int_setting("background-color-blue", 255);
}
void GL_widget_2::switch_render_effect() {
if (rendering_effect == RENDERING_NORMAL)
rendering_effect = RENDERING_PENCIL;
else rendering_effect = RENDERING_NORMAL;
resizeGL(width(),height());
glBindTexture( GL_TEXTURE_2D, 0);
repaintGL();
}
GL_widget_2::~GL_widget_2() {}
void GL_widget_2::update_bounding_box(const QRectF& r) {
if (default_bounding_box || r.x() < bounding_xmin) bounding_xmin = r.x();
if (default_bounding_box || r.x()+r.width() > bounding_xmax) bounding_xmax = r.x()+r.width();
if (default_bounding_box || r.y() < bounding_ymin) bounding_ymin = r.y();
if (default_bounding_box || r.y()+r.height() > bounding_ymax) bounding_ymax = r.y()+r.height();
default_bounding_box = false;
}
void GL_widget_2::set_window_to_boundingbox() {
if (default_bounding_box) return;
double margin_percent=BOUNDING_BOX_MARGIN_PERCENT;
double x_min = bounding_xmin;
double x_max = bounding_xmax;
double y_min = bounding_ymin;
double y_max = bounding_ymax;
double x_margin = (x_max - x_min) * margin_percent;
double y_margin = (y_max - y_min) * margin_percent;
x_min -= x_margin; x_max += x_margin;
y_min -= y_margin; y_max += y_margin;
set_window(x_min, x_max, y_min, y_max);
}
void GL_widget_2::export_to_image(QString image_filepath) {
bool old_dlists = get_use_display_lists();
set_use_display_lists(false);
repaint();
QImage image = grabFrameBuffer();
set_use_display_lists(old_dlists);
repaint();
image.save(image_filepath,"PNG");
std::cout << "Image written to " << image_filepath.toStdString() << std::endl;
}
void GL_widget_2::export_to_vector(QString file_name) {
QPrinter printer;
printer.setOutputFileName(file_name);
printer.setResolution(72);
printer.setPageSize(QPrinter::A0);
// printer.setOrientation(QPrinter::Landscape); //ps would be not correct
printer.setFullPage(true);
printer.setColorMode(QPrinter::Color);
QPainter painter;
set_renderer_type(GL_widget_2::QT_PAINTER);
set_painter(&painter);
painter.begin(&printer);
paint_to_painter();
painter.end();
set_painter(0);
set_renderer_type(GL_widget_2::OPEN_GL);
if (printer.printerState() < 2) // idle or active
std::cout << "Image written to " << file_name.toStdString() << std::endl;
else
std::cout << "Could not write image to " << file_name.toStdString() << std::endl;
}
void GL_widget_2::print_to_printer() {
QPrinter printer;
QPrintDialog print_dialog(&printer, this);
if (print_dialog.exec() == QDialog::Accepted) {
QPainter painter;
set_renderer_type(GL_widget_2::QT_PAINTER);
set_painter(&painter);
painter.begin(&printer);
paint_to_painter();
painter.end();
set_painter(0);
set_renderer_type(GL_widget_2::OPEN_GL);
}
}
GL_widget_2::Renderer_type GL_widget_2::get_renderer_type() { return renderer_type; }
void GL_widget_2::set_renderer_type(Renderer_type r) { renderer_type = r; }
QPainter* GL_widget_2::get_painter() { return painter; }
void GL_widget_2::set_painter(QPainter* p) { painter = p; }
void GL_widget_2::attach(Visualization_layer *l) {
layers.push_back(l);
l->attach(this);
// l->activate();
}
void GL_widget_2::detach(Visualization_layer *l) {
std::vector<Visualization_layer*>::iterator to_delete = std::find(layers.begin(),layers.end(),l);
if (to_delete!=layers.end())
layers.erase(to_delete);
}
void GL_widget_2::repaintGL() {
set_scales();
updateGL();
emit repaitedGL();
}
void GL_widget_2::paintGL () {
bool is_valid;
std::vector<Visualization_layer *>::iterator it, end;
//int infologLength = 0;
//int charsWritten = 0;
QSettings settings;
switch (rendering_effect) {
case RENDERING_PENCIL:
// render into pbuffer
pbuffer->makeCurrent();
//glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
default_bounding_box = true;
end=layers.end();
for (it=layers.begin(); it!=end; it++) {
Visualization_layer *l = *it;
if (l->is_active()) {
l->draw();
QRectF bbox = l->get_bounding_box(&is_valid);
if (is_valid)
update_bounding_box(bbox);
}
}
glFlush();
//pbuffer->toImage().save("D:/pbuffer.png");
// on the screen now
makeCurrent();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//draw a quad with the texture on it
//glGenTextures(1, &noise_texture);
//GLubyte *noise_data = make_2d_noise_texture(128,4,4);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 128, 128, 0, GL_RGBA, GL_UNSIGNED_BYTE, noise_data);
//glUniform1i(noise_uniform,6);
//
//glActiveTexture(GL_TEXTURE0+6);
//std::cout << "noise texture: " << noise_texture << std::endl;
//glBindTexture(GL_TEXTURE_2D, noise_texture);
//
//glGetProgramiv(npr_shader_program, GL_INFO_LOG_LENGTH,&infologLength);
//if (infologLength > 0)
//{
// infoLog = (char *)malloc(infologLength);
// glGetProgramInfoLog(npr_shader_program, infologLength, &charsWritten, infoLog);
// std::cout << infoLog << std::endl;
// free(infoLog);
//}
if (settings.value("npr-render-paper").toBool()) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,paper_texture);
glBegin(GL_QUADS);
glTexCoord2d(0,0);
glVertex2d(0, 0);
glTexCoord2d(10,0);
glVertex2d(2048, 0);
glTexCoord2d(10,10);
glVertex2d(2048, 2048);
glTexCoord2d(0,10);
glVertex2d(0, 2048);
glEnd();
}
glActiveTexture(GL_TEXTURE0+6);
glBindTexture(GL_TEXTURE_2D, noise_texture);
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, paper_texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, dynamic_texture);
// activate shader program
glUseProgram(npr_shader_program);
glBegin(GL_QUADS);
glTexCoord2d(0,0);
glVertex2d(0, 0);
glTexCoord2d(1,0);
glVertex2d(2048, 0);
glTexCoord2d(1,1);
glVertex2d(2048, 2048);
glTexCoord2d(0,1);
glVertex2d(0, 2048);
glEnd();
glUseProgram(0);
glActiveTexture(GL_TEXTURE0);
glFlush();
break;
default:
// render directly into the widget
makeCurrent();
glBindTexture(GL_TEXTURE_2D, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
default_bounding_box = true;
end=layers.end();
//do computation for layers
//if (! computation_thread->isRunning()) {
// computation_thread->start();
//} else {
// std::cout << LOG_GREEN << "thread is running" << std::endl;
// // std::cout << LOG_RED << "DONE Preparing layers" << std::endl;
// // std::cout << LOG_BLUE << "START Drawing layers" << std::endl;
//}
//render them
makeCurrent();
for (it=layers.begin(); it!=end; it++) {
Visualization_layer *l = *it;
if (l->is_active()) {
l->draw();
QRectF bbox = l->get_bounding_box(&is_valid);
if (is_valid)
update_bounding_box(bbox);
}
}
glFlush();
// std::cout << LOG_BLUE << "DONE Drawing layers" << std::endl;
break;
}
}
void GL_widget_2::paint_to_painter() {
painter->setClipRegion(QRegion(0,0,width(), height()));
std::vector<Visualization_layer *>::iterator it, end=layers.end();
for (it=layers.begin(); it!=end; it++) {
Visualization_layer *l = *it;
if (l->is_active())
l->draw();
}
}
void GL_widget_2::set_point_pen(QPen pen) {
point_pen = pen;
}
void GL_widget_2::set_line_pen(QPen pen) {
line_pen = pen;
}
void GL_widget_2::resizeGL ( int w, int h ) {
xmin = xmin_old;
xmax = xmax_old;
ymin = ymin_old;
ymax = ymax_old;
emit widget_resized_to(QRect(0,0,w,h));
set_scales();
double xratio,yratio,bxmin,bxmax,bymin,bymax, half_width,half_height;
switch (rendering_effect) {
case RENDERING_PENCIL:
// free old pencil buffer if exists
if (pbuffer) {
pbuffer->releaseFromDynamicTexture();
glDeleteTextures(1, &dynamic_texture);
delete pbuffer;
}
// create new pencil buffer and init
pbuffer = new QGLPixelBuffer(QSize(2048, 2048), format(), this);
pbuffer->makeCurrent();
init_common();
// generate texture that has the same size/format as the pbuffer
dynamic_texture = pbuffer->generateDynamicTexture();
// bind the dynamic texture to the pbuffer - this is a no-op under X11
pbuffer->bindToDynamicTexture(dynamic_texture);
// set projection matrix such that the 2048x2048 covers the view screen
xratio = 2048.0/w;
bxmin = ((1-xratio)*xmax + (1+xratio)*xmin)/2;
bxmax = ((1+xratio)*xmax + (1-xratio)*xmin)/2;
yratio = 2048.0/h;
bymin = ((1-yratio)*ymax + (1+yratio)*ymin)/2;
bymax = ((1+yratio)*ymax + (1-yratio)*ymin)/2;
glViewport(0,0,2048,2048);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(bxmin, bxmax, bymin, bymax, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// update the widget projection such that it is a window in the middle of 2048x2048
makeCurrent();
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
half_width=width()/2;
half_height=height()/2;
glOrtho(1024-half_width, 1024+half_width, 1024-half_height, 1024+half_height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
default:
makeCurrent();
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(xmin, xmax, ymin, ymax, -1, 1);
break;
}
}
char *read_text_from_file(const QString &name) {
QFile file(name);
if (!file.open(QIODevice::ReadOnly)) {
std::cout << "File " << name.toStdString() << " could not be open" << std::endl;
return 0;
}
int count = file.bytesAvailable ();
char* data = (char *)malloc(sizeof(char) * (count+1));
file.read(data, count);
data[count] = '\0';
file.close();
return data;
}
void GL_widget_2::initializeGL () {
makeCurrent();
init_common();
set_scales();
//init shaders
glewInit();
if (glewIsSupported("GL_VERSION_2_0")) {
std::cout << "OpenGL 2.0 is supported" << std::endl;
GLint texSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);
std::cout << "Maximum texture size: " << texSize << std::endl;
char *vs,*fs;
GLuint f,v;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
vs = read_text_from_file(":/pencil.vert");
fs = read_text_from_file(":/pencil.frag");
const char * vv = vs;
const char * ff = fs;
glShaderSource(v, 1, &vv,NULL);
glShaderSource(f, 1, &ff,NULL);
free(vs);free(fs);
glCompileShader(v);
int success;
glGetShaderiv(v, GL_COMPILE_STATUS, &success);
if (success!=GL_TRUE) std::cout << LOG_ERROR << "Vertex shader NOT compiled" << std::endl;
glCompileShader(f);
glGetShaderiv(f, GL_COMPILE_STATUS, &success);
if (success!=GL_TRUE) std::cout << LOG_ERROR << "Fragment shader NOT compiled" << std::endl;
npr_shader_program = glCreateProgram();
glAttachShader(npr_shader_program,v);
glAttachShader(npr_shader_program,f);
glLinkProgram(npr_shader_program);
glGetProgramiv(npr_shader_program, GL_LINK_STATUS, &success);
if (success!=GL_TRUE) std::cout << LOG_ERROR << "Shader program NOT compiled" << std::endl;
glUseProgram(npr_shader_program);
GLint noise_uniform = glGetUniformLocation(npr_shader_program, "hatchmap");
// glGenTextures(1, &noise_texture);
glActiveTexture(GL_TEXTURE0+6);
noise_texture = bindTexture(QPixmap(":/perlin.png"), GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, noise_texture);
noise_uniform = glGetUniformLocation(npr_shader_program, "hatchmap");
glUniform1i(noise_uniform,6);
glActiveTexture(GL_TEXTURE0);
paper_texture = bindTexture(QPixmap(":/paper.png"), GL_TEXTURE_2D);
QSettings settings;
GLint hatchscale_location = glGetUniformLocation(npr_shader_program, "hatchScale");
glUniform1f(hatchscale_location, settings.value("npr-render-distortion").toDouble());
GLint edge_location = glGetUniformLocation(npr_shader_program, "edgeSize");
glUniform1f(edge_location, settings.value("npr-render-edge-detection-width").toDouble());
//glBindTexture(GL_TEXTURE_2D, paper_texture);
//glBindTexture( GL_TEXTURE_2D, 0);
glUseProgram(0);
} else {
std::cout << LOG_ERROR << "OpenGL 2.0 is not supported" << std::endl;
}
double xratio,yratio,bxmin,bxmax,bymin,bymax, half_width,half_height;
switch (rendering_effect) {
case RENDERING_PENCIL:
// free old pencil buffer if exists
if (pbuffer) {
pbuffer->releaseFromDynamicTexture();
glDeleteTextures(1, &dynamic_texture);
delete pbuffer;
}
// create new pencil buffer and init
pbuffer = new QGLPixelBuffer(QSize(2048, 2048), format(), this);
pbuffer->makeCurrent();
init_common();
// generate texture that has the same size/format as the pbuffer
dynamic_texture = pbuffer->generateDynamicTexture();
// bind the dynamic texture to the pbuffer - this is a no-op under X11
pbuffer->bindToDynamicTexture(dynamic_texture);
// set projection matrix such that the 2048x2048 covers the view screen
xratio = 2048.0/width();
bxmin = ((1-xratio)*xmax + (1+xratio)*xmin)/2;
bxmax = ((1+xratio)*xmax + (1-xratio)*xmin)/2;
yratio = 2048.0/height();
bymin = ((1-yratio)*ymax + (1+yratio)*ymin)/2;
bymax = ((1+yratio)*ymax + (1-yratio)*ymin)/2;
glViewport(0,0,2048,2048);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(bxmin, bxmax, bymin, bymax, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// update the widget projection such that it is a window in the middle of 2048x2048
makeCurrent();
glViewport(0, 0, width(), height());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
half_width=width()/2;
half_height=height()/2;
glOrtho(1024-half_width, 1024+half_width, 1024-half_height, 1024+half_height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
default:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width(), 0, height(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
}
}
void GL_widget_2::init_common() {
glClearColor(Application_settings::get_int_setting("background-color-red")/255.0,
Application_settings::get_int_setting("background-color-green")/255.0,
Application_settings::get_int_setting("background-color-blue")/255.0,
1.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // Make round points, not square points
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Antialias the lines
glEnable(GL_BLEND); // Enable Blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Type Of Blending To Use
// glEnable(GL_MULTISAMPLE);
}
void GL_widget_2::set_window(double x_min, double x_max,
double y_min, double y_max) {
xmin_old = xmin = x_min;
xmax_old = xmax = x_max;
ymin_old = ymin = y_min;
ymax_old = ymax = y_max;
set_scales();
double xratio,yratio,bxmin,bxmax,bymin,bymax;
switch (rendering_effect) {
case RENDERING_PENCIL:
pbuffer->makeCurrent();
xratio = 2048.0/width();
bxmin = ((1-xratio)*xmax + (1+xratio)*xmin)/2;
bxmax = ((1+xratio)*xmax + (1-xratio)*xmin)/2;
yratio = 2048.0/height();
bymin = ((1-yratio)*ymax + (1+yratio)*ymin)/2;
bymax = ((1+yratio)*ymax + (1-yratio)*ymin)/2;
glViewport(0,0,2048,2048);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(bxmin, bxmax, bymin, bymax, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
default:
makeCurrent();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(xmin, xmax, ymin, ymax, -1, 1);
break;
}
repaintGL();
// updateGL();
}
void GL_widget_2::set_scales() {
xscal = yscal = (width()/(xmax - xmin) < height()/(ymax - ymin) ) ? width() / (xmax - xmin) : height() / (ymax - ymin);
double xcenter = xmin + (xmax - xmin) / 2;
double ycenter = ymin + (ymax - ymin) / 2;
//if(xscal<1) {
// // if xscal < 1, width()/xscal > width(). then we can round it
// // with loosing precision.
// xmin = xcenter - (int)(width()/xscal)/2;
// xmax = xcenter + (int)(width()/xscal)/2;
// ymin = ycenter - (int)(height()/yscal)/2;
// ymax = ycenter + (int)(height()/yscal)/2;
//} else {
xmin = xcenter - (width()/xscal)/2;
xmax = xcenter + (width()/xscal)/2;
ymin = ycenter - (height()/yscal)/2;
ymax = ycenter + (height()/yscal)/2;
//}
}
void GL_widget_2::move_center(const double distx, const double disty) {
xmin += distx; xmin_old += distx;
xmax += distx; xmax_old += distx;
ymin += disty; ymin_old += disty;
ymax += disty; ymax_old += disty;
double xratio,yratio,bxmin,bxmax,bymin,bymax;
switch (rendering_effect) {
case RENDERING_PENCIL:
pbuffer->makeCurrent();
xratio = 2048.0/width();
bxmin = ((1-xratio)*xmax + (1+xratio)*xmin)/2;
bxmax = ((1+xratio)*xmax + (1-xratio)*xmin)/2;
yratio = 2048.0/height();
bymin = ((1-yratio)*ymax + (1+yratio)*ymin)/2;
bymax = ((1+yratio)*ymax + (1-yratio)*ymin)/2;
glViewport(0,0,2048,2048);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(bxmin, bxmax, bymin, bymax, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
default:
makeCurrent();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(xmin, xmax, ymin, ymax, -1, 1);
break;
}
repaintGL();
// updateGL();
}
void GL_widget_2::set_center(const double x, const double y) {
if(xscal<1) {
xmin = x - (int)(width()/xscal)/2;
xmax = x + (int)(width()/xscal)/2;
ymin = y - (int)(height()/yscal)/2;
ymax = y + (int)(height()/yscal)/2;
} else {
xmin = x - (width()/xscal)/2;
xmax = x + (width()/xscal)/2;
ymin = y - (height()/yscal)/2;
ymax = y + (height()/yscal)/2;
}
// this is so that we can not zoom out higher than the maximum rendering area (for infinite lines and rays)
bool need_set_scales = false; double new_min, new_max;
if (xmax > GL_MAX_DRAWING_COORDINATE) {
xmax = GL_MAX_DRAWING_COORDINATE;
new_min=(ymin+ymax)/2-(ymax-ymin)/100;
new_max=(ymin+ymax)/2+(ymax-ymin)/100;
ymin=new_min;
ymax=new_max;
need_set_scales = true;
}
if (xmin < -GL_MAX_DRAWING_COORDINATE) {
xmin = -GL_MAX_DRAWING_COORDINATE;
new_min=(ymin+ymax)/2-(ymax-ymin)/100;
new_max=(ymin+ymax)/2+(ymax-ymin)/100;
ymin=new_min;
ymax=new_max;
need_set_scales = true;
}
if (ymax > GL_MAX_DRAWING_COORDINATE) {
ymax = GL_MAX_DRAWING_COORDINATE;
new_min=(xmin+xmax)/2-(xmax-xmin)/100;
new_max=(xmin+xmax)/2+(xmax-xmin)/100;
xmin=new_min;
xmax=new_max;
need_set_scales = true;
}
if (ymin < -GL_MAX_DRAWING_COORDINATE) {
ymin = -GL_MAX_DRAWING_COORDINATE;
new_min=(xmin+xmax)/2-(xmax-xmin)/100;
new_max=(xmin+xmax)/2+(xmax-xmin)/100;
xmin=new_min;
xmax=new_max;
need_set_scales = true;
}
if (need_set_scales) set_scales();
xmin_old = xmin;
xmax_old = xmax;
ymin_old = ymin;
ymax_old = ymax;
double xratio,yratio,bxmin,bxmax,bymin,bymax;
switch (rendering_effect) {
case RENDERING_PENCIL:
pbuffer->makeCurrent();
xratio = 2048.0/width();
bxmin = ((1-xratio)*xmax + (1+xratio)*xmin)/2;
bxmax = ((1+xratio)*xmax + (1-xratio)*xmin)/2;
yratio = 2048.0/height();
bymin = ((1-yratio)*ymax + (1+yratio)*ymin)/2;
bymax = ((1+yratio)*ymax + (1-yratio)*ymin)/2;
glViewport(0,0,2048,2048);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(bxmin, bxmax, bymin, bymax, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
break;
default:
makeCurrent();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(xmin, xmax, ymin, ymax, -1, 1);
break;
}
repaintGL();
}
void GL_widget_2::zoom(double ratio, double xc, double yc) {
xscal = xscal*ratio; yscal = yscal*ratio;
set_center(xc, yc);
}
void GL_widget_2::zoom(double ratio) {
zoom(ratio,
xmin + (xmax - xmin) / 2 ,
ymin + (ymax - ymin) / 2 );
}
double GL_widget_2::x_real(int x) const {
if(xscal<1)
return(xmin+(int)(x/xscal));
else
return (xmin+x/xscal);
}
double GL_widget_2::y_real(int y) const {
if(yscal<1)
return(ymax-(int)(y/yscal));
else
return (ymax-y/yscal);
}
double GL_widget_2::x_pixel_d(double x) {
return (x-xmin)*xscal;
}
double GL_widget_2::y_pixel_d(double y) {
return -1*(y-ymax)*yscal;
}
double GL_widget_2::x_pixel_dist_d(double d) {
return d*xscal;
}
double GL_widget_2::y_pixel_dist_d(double d) {
return d*yscal;
}
void GL_widget_2::selection_copied_by(double x, double y)
{
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
(*it)->selection_copied_by(x,y);
emit points_modified();
}
void GL_widget_2::selection_moved_by(double x, double y)
{
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
(*it)->selection_moved_by(x,y);
emit points_modified();
}
bool GL_widget_2::selection_deleted()
{
bool something_deleted = false;
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
something_deleted = something_deleted || (*it)->selection_deleted();
if (hasFocus() && something_deleted) {
emit points_modified();
return true;
}
return false;
}
void GL_widget_2::clear_selection()
{
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
(*it)->clear_selection();
}
void GL_widget_2::ray_selection(double x, double y, bool* hit) {
*hit = false;
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active()) {
bool layer_hit = false;
(*it)->ray_selection(x, y, &layer_hit);
*hit = *hit || layer_hit;
}
}
void GL_widget_2::disk_selection(double x, double y, double radius, bool* hit) {
*hit = false;
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active()) {
bool layer_hit = false;
(*it)->disk_selection(x, y, radius, &layer_hit);
*hit = *hit || layer_hit;
}
}
void GL_widget_2::box_selection(double x, double y, double width, double height, bool* hit) {
*hit = false;
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active()) {
bool layer_hit = false;
(*it)->box_selection(x, y, width, height, &layer_hit);
*hit = *hit || layer_hit;
}
}
void GL_widget_2::request_repaint() {
want_repaint = true;
}
void GL_widget_2::application_settings_changed(const QString& settings_name) {
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
(*it)->application_settings_changed(settings_name);
if (want_repaint) {
repaintGL();
want_repaint = false;
}
if (settings_name=="npr-render") {
if (rendering_effect != RENDERING_NORMAL ^ Application_settings::get_bool_setting("npr-render")) {
switch_render_effect(); repaint();
}
}
if (settings_name=="npr-render-paper") repaint();
if (settings_name=="npr-render-distortion") {
QSettings settings;
glUseProgram(npr_shader_program);
GLint hatchscale_location = glGetUniformLocation(npr_shader_program, "hatchScale");
glUniform1f(hatchscale_location, settings.value("npr-render-distortion").toDouble());
glUseProgram(0);
repaint();
}
if (settings_name=="npr-render-edge-detection-width") {
QSettings settings;
glUseProgram(npr_shader_program);
GLint edge_location = glGetUniformLocation(npr_shader_program, "edgeSize");
glUniform1f(edge_location, settings.value("npr-render-edge-detection-width").toDouble());
glUseProgram(0);
repaint();
}
if (settings_name.startsWith("background-color")) {
glClearColor(Application_settings::get_int_setting("background-color-red")/255.0,
Application_settings::get_int_setting("background-color-green")/255.0,
Application_settings::get_int_setting("background-color-blue")/255.0,
1.0f);
repaintGL();
}
if (settings_name == "random-colormap-resolution") {
Color_map_factory::add_color_map(new Random_color_map(Application_settings::get_int_setting("random-colormap-resolution"), "Random"));
repaint();
}
}
void GL_widget_2::add_point_to_selection(double x, double y) {
emit add_point_to_selection(QPointF(x,y));
}
void GL_widget_2::add_line_to_selection(double x1, double y1, double x2, double y2) {
emit add_line_to_selection(QLineF(x1,y1,x2,y2));
}
void GL_widget_2::add_circle_to_selection(double x, double y, double r) {
emit add_circle_to_selection(QPointF(x,y), r);
}
void GL_widget_2::remove_point_from_selection(double x, double y) {
emit remove_point_from_selection(QPointF(x,y));
}
void GL_widget_2::remove_line_from_selection(double x1, double y1, double x2, double y2) {
emit remove_line_from_selection(QLineF(x1,y1,x2,y2));
}
void GL_widget_2::remove_circle_from_selection(double x, double y, double r) {
emit remove_circle_from_selection(QPointF(x,y), r);
}
void GL_widget_2::smooth_zoom(double x_min, double x_max, double y_min, double y_max) {
double o_x_min = xmin;
double o_x_max = xmax;
double o_y_min = ymin;
double o_y_max = ymax;
if (o_x_min == x_min && o_x_max == x_max && o_y_min == y_min && o_y_max == y_max) return;
QSettings settings;
int min_squared_distance = settings.value("navigation-smooth-zoom-steps").toInt();
// std::cout << "navigation-smooth-zoom-steps: " << min_squared_distance << std::endl;
// these parameters should be moved outside, ini file or user interface...
double uniform_ratio = 1.00;
double total_steps = min_squared_distance;//SMOOTH_ZOOM_STEPS;
double uniform_steps = (int) total_steps * uniform_ratio;
double accel_steps = (int) total_steps - uniform_steps;
double c_x_min = o_x_min; double x_min_step = uniform_ratio * (x_min - o_x_min)/uniform_steps;
double c_x_max = o_x_max; double x_max_step = uniform_ratio * (x_max - o_x_max)/uniform_steps;
double c_y_min = o_y_min; double y_min_step = uniform_ratio * (y_min - o_y_min)/uniform_steps;
double c_y_max = o_y_max; double y_max_step = uniform_ratio * (y_max - o_y_max)/uniform_steps;
for (int i=0; i<uniform_steps; i++) {
c_x_min += x_min_step;
c_x_max += x_max_step;
c_y_min += y_min_step;
c_y_max += y_max_step;
set_window(c_x_min, c_x_max, c_y_min, c_y_max);
// msg("ren");
}
if (accel_steps==0) return;
double acc_x_min = ((1-uniform_ratio) * (x_min - o_x_min) - x_min_step * accel_steps) / accel_steps / accel_steps;
double acc_x_max = ((1-uniform_ratio) * (x_max - o_x_max) - x_max_step * accel_steps) / accel_steps / accel_steps;
double acc_y_min = ((1-uniform_ratio) * (y_min - o_y_min) - y_min_step * accel_steps) / accel_steps / accel_steps;
double acc_y_max = ((1-uniform_ratio) * (y_max - o_y_max) - y_max_step * accel_steps) / accel_steps / accel_steps;
double a_x_min = c_x_min;
double a_x_max = c_x_max;
double a_y_min = c_y_min;
double a_y_max = c_y_max;
for (int i=1; i<accel_steps+1; i++) {
a_x_min = c_x_min + x_min_step*i + acc_x_min * i*i;
a_x_max = c_x_max + x_max_step*i + acc_x_max * i*i;
a_y_min = c_y_min + y_min_step*i + acc_y_min * i*i;
a_y_max = c_y_max + y_max_step*i + acc_y_max * i*i;
set_window(a_x_min, a_x_max, a_y_min, a_y_max);
}
}
void GL_widget_2::mousePressEvent(QMouseEvent *e)
{
emit(s_mousePressEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mousePressEvent(e);
}
void GL_widget_2::mouseReleaseEvent(QMouseEvent *e)
{
emit(s_mouseReleaseEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseReleaseEvent(e);
}
void GL_widget_2::mouseMoveEvent(QMouseEvent *e)
{
emit(s_mouseMoveEvent(e));
emit mouse_at(QPointF(x_real(e->x()), y_real(e->y())));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseMoveEvent(e);
}
void GL_widget_2::wheelEvent(QWheelEvent *e)
{
emit(s_wheelEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->wheelEvent(e);
}
void GL_widget_2::mouseDoubleClickEvent(QMouseEvent *e)
{
emit(s_mouseDoubleClickEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->mouseDoubleClickEvent(e);
}
void GL_widget_2::keyPressEvent(QKeyEvent *e)
{
emit(s_keyPressEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->keyPressEvent(e);
}
void GL_widget_2::save_view(bool) {
QString bounding_box = tr("%1 %2 %3 %4").arg(x_min()).arg(x_max()).arg(y_min()).arg(y_max());
QSettings settings;
QString file_name = QFileDialog::getSaveFileName(
this,
"Choose a filename to save view",
settings.value("last-view-directory",QString()).toString(),
"View files (*.2view)");
if (file_name=="") return;
if (!file_name.endsWith(".2view")) file_name += ".2view";
QString save_directory = file_name;
save_directory.truncate(file_name.lastIndexOf('/'));
settings.setValue("last-view-directory",save_directory);
QFile f(file_name);
if ( !f.open( QIODevice::WriteOnly ) ) {
std::cout << LOG_ERROR << tr("File `%1' could not be open for writing!").arg(file_name).toStdString() << std::endl;
return;
}
QTextStream fs( &f );
fs << bounding_box;
f.close();
std::cout << "Camera view stored in " << file_name.toStdString() << std::endl;
}
void GL_widget_2::load_view(bool) {
QSettings settings;
QString file_name = QFileDialog::getOpenFileName(
this,
"Choose a filename to load view",
settings.value("last-view-directory",QString()).toString(),
"View files (*.2view)");
if (file_name!="") {
if (!file_name.endsWith(".2view")) file_name += ".2view";
QString save_directory = file_name;
save_directory.truncate(file_name.lastIndexOf('/'));
settings.setValue("last-view-directory",save_directory);
QFile file(file_name);
if (!file.open(QIODevice::ReadOnly)) {
std::cout << LOG_ERROR << tr("File `%1' could not be open for reading!").arg(file_name).toStdString() << std::endl;
return;
}
QTextStream ts(&file);
double xmin, xmax, ymin, ymax;
ts >> xmin; ts >> xmax; ts >> ymin; ts >> ymax;
file.close();
smooth_zoom(xmin, xmax,ymin,ymax);
std::cout << "Camera view reloaded from " << file_name.toStdString() << std::endl;
}
}
void GL_widget_2::keyReleaseEvent(QKeyEvent *e)
{
emit(s_keyReleaseEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->keyReleaseEvent(e);
if (e->key()==Qt::Key_Space && e->modifiers() == Qt::ControlModifier) {
QSettings settings;
settings.setValue("npr-render",!settings.value("npr-render").toBool());
switch_render_effect();
emit settings_changed();
}
if (e->key()==Qt::Key_F && e->modifiers() == Qt::ControlModifier) { switch_full_screen(); }
//if (e->key() == Qt::Key_V && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier)) {
// QString bounding_box = tr("%1 %2 %3 %4").arg(x_min()).arg(x_max()).arg(y_min()).arg(y_max());
// QSettings settings;
// settings.setValue("viewer-buffer-2d-view-state",bounding_box);
// std::cout << "Current view stored" << std::endl;
//}
//if (e->key() == Qt::Key_V && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier)) {
// QSettings settings;
// QString doc_text = settings.value("viewer-buffer-2d-view-state").toString();
// QTextStream ts(&doc_text);
// double xmin, xmax, ymin, ymax;
// ts >> xmin; ts >> xmax; ts >> ymin; ts >> ymax;
// smooth_zoom(xmin, xmax,ymin,ymax);
// std::cout << "Camera view reloaded with "<< doc_text.toStdString() << std::endl;
//}
//if (e->key() == Qt::Key_P && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier)) {
// QString bounding_box = tr("%1 %2 %3 %4").arg(x_min()).arg(x_max()).arg(y_min()).arg(y_max());
//
// QSettings settings;
// QString file_name = QFileDialog::getSaveFileName(
// this,
// "Choose a filename to save view",
// settings.value("last-data-directory",QString()).toString(),
// "View files (*.2view)");
// if (file_name=="") return;
// if (!file_name.endsWith(".2view")) file_name += ".2view";
// QString save_directory = file_name;
// save_directory.truncate(file_name.lastIndexOf('/'));
// settings.setValue("last-data-directory",save_directory);
// QFile f(file_name);
// if ( !f.open( QIODevice::WriteOnly ) ) {
// std::cout << LOG_ERROR << tr("File `%1' could not be open for writing!").arg(file_name).toStdString() << std::endl;
// return;
// }
// QTextStream fs( &f );
// fs << bounding_box;
// f.close();
// std::cout << "Camera view stored in " << file_name.toStdString() << std::endl;
//}
//if (e->key() == Qt::Key_P && e->modifiers() == (Qt::ControlModifier | Qt::AltModifier)) {
// QSettings settings;
// QString file_name = QFileDialog::getOpenFileName(
// this,
// "Choose a filename to load view",
// settings.value("last-data-directory",QString()).toString(),
// "View files (*.2view)");
// if (file_name!="") {
// if (!file_name.endsWith(".2view")) file_name += ".2view";
// QString save_directory = file_name;
// save_directory.truncate(file_name.lastIndexOf('/'));
// settings.setValue("last-data-directory",save_directory);
// QFile file(file_name);
// if (!file.open(QIODevice::ReadOnly)) {
// std::cout << LOG_ERROR << tr("File `%1' could not be open for reading!").arg(file_name).toStdString() << std::endl;
// return;
// }
// QTextStream ts(&file);
// double xmin, xmax, ymin, ymax;
// ts >> xmin; ts >> xmax; ts >> ymin; ts >> ymax;
// file.close();
// smooth_zoom(xmin, xmax,ymin,ymax);
// std::cout << "Camera view reloaded from " << file_name.toStdString() << std::endl;
// }
//}
}
void GL_widget_2::switch_full_screen() {
std::cout << "should switch to full screen" << std::endl;
// QWidget* tlw = topLevelWidget();
//if (! isFullScreen())
//{
// old_parent = parentWidget();
// setParent(0);
// setWindowFlags(windowFlags() | Qt::Window | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
// std::cout << "Widget is window: " << isWindow() << std::endl;
// showFullScreen();
// move(0,0);
//}
//else
//{
// setParent(old_parent);
// showNormal();
// //tlw->move(prev_pos);
//}
//full_screen = ! full_screen;
//setWindowState(windowState() ^ Qt::WindowFullScreen);
//if (full_scren) {
// w->setWindowState(w->windowState() & ~WindowMinimized | WindowActive);
//} else {
//}
}
void GL_widget_2::enterEvent(QEvent *e)
{
emit(s_enterEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->enterEvent(e);
}
void GL_widget_2::leaveEvent(QEvent *e)
{
emit(s_leaveEvent(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->leaveEvent(e);
}
bool GL_widget_2::event(QEvent *e)
{
emit(s_event(e));
std::vector<Visualization_layer*>::iterator it;
for(it = layers.begin(); it!= layers.end(); it++)
if((*it)->is_active())
(*it)->event(e);
return QWidget::event(e);
}
void GL_widget_2::set_default_cursor(QCursor c) { default_cursor = c; }
QCursor GL_widget_2::get_default_cursor() { return default_cursor; }
|
[
"balint.miklos@localhost"
] |
[
[
[
1,
1257
]
]
] |
b976f500a5476aabefb0020a7464386b78f1ff6f
|
7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d
|
/AppData/Sources/VS 2005 WinCE SDK 8.0 GUI/Source/stdafx.cpp
|
76ae4383dc9ecd101d1f1f2ec71a4d1e2a38edbc
|
[] |
no_license
|
SchweinDeBurg/afx-scratch
|
895585e98910f79127338bdca5b19c5e36921453
|
3181b779b4bb36ef431e5ce39e297cece1ca9cca
|
refs/heads/master
| 2021-01-19T04:50:48.770595 | 2011-06-18T05:14:22 | 2011-06-18T05:14:22 | 32,185,218 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,032 |
cpp
|
// $PROJECT$ application.
// Copyright (c) $YEAR$ by $AUTHOR$,
// All rights reserved.
// stdafx.cpp - source file that includes just the standard includes
// initially generated by $GENERATOR$ on $DATE$ at $TIME$
// visit http://zarezky.spb.ru/projects/afx_scratch.html for more info
//////////////////////////////////////////////////////////////////////////////////////////////
// PCH includes
#include "stdafx.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// linker options
#if defined(_DEBUG) || defined(DEBUG)
#pragma comment(linker, "/nodefaultlib:libcd.lib")
#else
#pragma comment(linker, "/nodefaultlib:libc.lib")
#endif // _DEBUG || DEBUG
//////////////////////////////////////////////////////////////////////////////////////////////
// required libraries
#pragma comment(lib, "aygshell.lib")
#if defined(_CPPRTTI) && (_WIN32_WCE < 0x500)
#pragma comment(lib, "ccrtrtti.lib")
#endif // _CPPRTTI && _WIN32_WCE
// end of file
|
[
"Elijah@9edebcd1-9b41-0410-8d36-53a5787adf6b",
"Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b"
] |
[
[
[
1,
9
],
[
13,
14
],
[
16,
21
],
[
23,
23
],
[
25,
30
],
[
32,
33
]
],
[
[
10,
12
],
[
15,
15
],
[
22,
22
],
[
24,
24
],
[
31,
31
]
]
] |
2160091bd11f534291fa99207c97590e7056e623
|
e2e49023f5a82922cb9b134e93ae926ed69675a1
|
/tools/aoslcpp/include/aosl/layer_ref.hpp
|
2e5d2e582b617c51972828e073d9d96d08049bf2
|
[] |
no_license
|
invy/mjklaim-freewindows
|
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
|
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
|
refs/heads/master
| 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,444 |
hpp
|
// Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
/**
* @file
* @brief Generated from layer_ref.xsd.
*/
#ifndef AOSLCPP_AOSL__LAYER_REF_HPP
#define AOSLCPP_AOSL__LAYER_REF_HPP
// Begin prologue.
//
#include <aoslcpp/common.hpp>
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include "aosl/layer_ref_forward.hpp"
#include <memory> // std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include <xsd/cxx/tree/containers-wildcard.hxx>
#ifndef XSD_DONT_INCLUDE_INLINE
#define XSD_DONT_INCLUDE_INLINE
#undef XSD_DONT_INCLUDE_INLINE
#else
#endif // XSD_DONT_INCLUDE_INLINE
/**
* @brief C++ namespace for the %artofsequence.org/aosl/1.0
* schema namespace.
*/
namespace aosl
{
/**
* @brief Union class corresponding to the %layer_ref
* schema type.
*
* The mapping represents unions as strings.
*
* Reference to a Layer or automatically find layers using a search
logic. */
class Layer_ref: public ::xml_schema::String
{
public:
/**
* @brief Create an instance from a C string.
*
* @param v A string value.
*/
Layer_ref (const char* v);
/**
* @brief Create an instance from a string.
*
* @param v A string value.
*/
Layer_ref (const ::std::string& v);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Layer_ref (const ::xercesc::DOMElement& e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a DOM attribute.
*
* @param a A DOM attribute to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Layer_ref (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a string fragment.
*
* @param s A string fragment to extract the data from.
* @param e A pointer to DOM element containing the string fragment.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Layer_ref (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
Layer_ref (const Layer_ref& x,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual Layer_ref*
_clone (::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0) const;
};
}
#ifndef XSD_DONT_INCLUDE_INLINE
#endif // XSD_DONT_INCLUDE_INLINE
#include <iosfwd>
namespace aosl
{
::std::ostream&
operator<< (::std::ostream&, const Layer_ref&);
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace aosl
{
}
#include <iosfwd>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
namespace aosl
{
void
operator<< (::xercesc::DOMElement&, const Layer_ref&);
void
operator<< (::xercesc::DOMAttr&, const Layer_ref&);
void
operator<< (::xml_schema::ListStream&,
const Layer_ref&);
}
#ifndef XSD_DONT_INCLUDE_INLINE
#include "aosl/layer_ref.inl"
#endif // XSD_DONT_INCLUDE_INLINE
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__LAYER_REF_HPP
|
[
"klaim@localhost"
] |
[
[
[
1,
213
]
]
] |
58297e41d4dbd706401b4512922ce339eee8afff
|
877bad5999a3eeab5d6d20b5b69a273b730c5fd8
|
/TestKhoaLuan/DirectShowTVSample/Chapter-12/ASFCaptureGraphBuilder/StdAfx.cpp
|
ce4d6d7e084db1f845d30471180abc6cfd1b6837
|
[] |
no_license
|
eaglezhao/tracnghiemweb
|
ebdca23cb820769303d27204156a2999b8381e03
|
aaae7bb7b9393a8000d395c1d98dcfc389e3c4ed
|
refs/heads/master
| 2021-01-10T12:26:27.694468 | 2010-10-06T01:15:35 | 2010-10-06T01:15:35 | 45,880,587 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 309 |
cpp
|
// stdafx.cpp : source file that includes just the standard includes
// ASFCaptureGraphBuilder.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
[
"[email protected]"
] |
[
[
[
1,
8
]
]
] |
1189231f676a7b4c70d3ad316c202c4b53d8d23e
|
ac342d97dda23af771da4f257a12a2910aed8987
|
/rtspcore.cpp
|
35688e73da1c16786302cff6180d0cd5303994c2
|
[] |
no_license
|
kitech/mwget
|
41cfb180c67d22fe3abe67a8c1ecfb2d71d762a4
|
c7aafefd4061f70ec565778b313732792a276fc0
|
refs/heads/master
| 2020-05-28T13:23:32.333877 | 2011-11-16T03:32:21 | 2011-11-16T03:32:21 | 2,785,265 | 8 | 5 | null | null | null | null |
IBM852
|
C++
| false | false | 6,564 |
cpp
|
#include "real.h"
#include "rtsp_session.h"
#include "rtspcore.h"
RTSPRetriever::RTSPRetriever ( int ts )
: Retriever( ts )
{
}
RTSPRetriever::~RTSPRetriever ()
{
}
bool RTSPRetriever::TaskValid(long bsize )
{
return false ;
}
void test_rtsp_protocol()
{
bool dret = false ;
char ftpcmd[100] = {0};
char rbuf[1024] = {0};
std::string allhr ;
int rlen = 0 ;
int hlen = 0 ;
int clen = 0 ;
int nleft = 0 ;
char * s = 0 ;
HttpHeader hr ;
KSocket * csock = new KSocket() ;
std::string session ;
std::string challenge1 , challenge2 , checksum ;
dret = csock->Connect( "localhost", 554 ) ;
if( dret ) printf("connect ok\n");
else printf("connect error\n");
hr.AddHeader( "CSeq", "1");
hr.AddHeader( "User-Agent", "RealMedia Player Version 6.0.9.1235 (linux-2.0-libc6-i386-gcc2.95)");
hr.AddHeader( "ClientChallenge", "9e26d33f2984236010ef6253fb1887f7");
hr.AddHeader( "PlayerStarttime", "[28/03/2003:22:50:23 00:00]");
hr.AddHeader( "CompanyID", "KnKV4M4I/B2FjJ1TToLycw==");
hr.AddHeader( "GUID", "00000000-0000-0000-0000-000000000000");
hr.AddHeader( "RegionData", "0");
hr.AddHeader( "ClientID", "Linux_2.4_6.0.9.1235_play32_RN01_EN_586");
hr.AddHeader( "Pragma", "initiate-session");
allhr = "OPTIONS rtsp://localhost:554 RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("send ok\n");
else printf("send error\n");
csock->Reads(rbuf) ;
printf(rbuf ) ;
hr.Parse(rbuf);
//hr.Dump() ;
session = hr.GetHeader( "Session" ) ;
challenge1 = hr.GetHeader ( "RealChallenge1");
printf("Get RealChallenge1: %s\n", challenge1.c_str());
//////////////
hr.ClearHeaders();
hr.AddHeader( "CSeq", "2");
hr.AddHeader( "Accept", "application/sdp");
hr.AddHeader( "Session", session );
hr.AddHeader( "Bandwidth", "10485800");
hr.AddHeader( "SupportsMaximumASMBandwidth", "1");
hr.AddHeader( "GUID", "00000000-0000-0000-0000-000000000000");
hr.AddHeader( "Require", "com.real.retain-entity-for-setup");
allhr = "DESCRIBE rtsp://localhost/10.rm RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("send ok\n");
else printf("send error\n");
do
{
rlen = csock->Peek(rbuf + rlen , sizeof(rbuf) );
if( rlen <= 0 ) break ;
if( ( s = strstr(rbuf ,"\r\n\r\n") ) != 0 )
{
hlen = s - rbuf + 4 ;
break ;
}
}while(true);
hr.ClearHeaders();
hr.Parse(rbuf);
std::string status = hr.GetHeader( "Status" ) ;
//hr.Dump() ;
memset(rbuf , 0 , sizeof(rbuf));
csock->Read(rbuf , hlen ) ;
printf(rbuf );
nleft = clen = atoi(hr.GetHeader( "Content-length" ).c_str() );
nleft = 0 ;
printf("read content\n");
while(nleft < clen )
{
memset(rbuf, 0 , sizeof(rbuf) );
rlen = csock->Read( rbuf , sizeof(rbuf)-1);
if ( rlen >=0 ) nleft += rlen ;
printf(rbuf);
}
///////////////╝Ă╦Ńchallenge2╝░checksum
char challenge1_buff[128] = {0};
char challenge2_buff[128] = {0};
char checksum_buff[128] = {0} ;
strcpy(challenge1_buff,challenge1.c_str());
real_calc_response_and_checksum(challenge2_buff,checksum_buff,challenge1_buff);
printf("\nsend setup \n");
hr.ClearHeaders();
hr.AddHeader( "CSeq", "3");
//hr.AddHeader( "RealChallenge2", "e6de874aa5e64dd35f056f3a7ab857a701d0a8e3, sd=e8a45675");
hr.AddHeader( "RealChallenge2", std::string(challenge2_buff)+", sd="+std::string(checksum_buff) );
hr.AddHeader( "Transport", "x-pn-tng/tcp;mode=play");
hr.AddHeader( "If-Match", session );
allhr = "SETUP rtsp://localhost/10.rm/streamid=0 RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("send ok\n");
else printf("send error\n");
memset(rbuf, 0 , sizeof(rbuf) );
csock->Reads(rbuf) ;
printf(rbuf ) ;
///////////////
printf("\nsend setup2 \n");
hr.ClearHeaders();
hr.AddHeader( "CSeq", "4");
hr.AddHeader( "Transport", "x-pn-tng/tcp;mode=play");
hr.AddHeader( "Session", session );
allhr = "SETUP rtsp://localhost/10.rm/streamid=1 RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("send ok\n");
else printf("send error\n");
memset(rbuf, 0 , sizeof(rbuf) );
csock->Reads(rbuf) ;
printf(rbuf ) ;
///////////////
printf("\nsend SET_PARAMETER \n");
hr.ClearHeaders();
hr.AddHeader( "CSeq", "5");
hr.AddHeader( "Subscribe", "stream=0;rule=0,stream=0;rule=1,stream=1;rule=0,stream=1;rule=1");
hr.AddHeader( "Session", session );
allhr = "SET_PARAMETER rtsp://localhost/10.rm RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("send ok\n");
else printf("send error\n");
memset(rbuf, 0 , sizeof(rbuf) );
csock->Reads(rbuf) ;
printf(rbuf ) ;
///////////////
printf("\nsend PLAY \n");
hr.ClearHeaders();
hr.AddHeader( "CSeq", "6");
hr.AddHeader( "Session", session );
hr.AddHeader( "Range", "npt=80.000-");
allhr = "PLAY rtsp://localhost/10.rm RTSP/1.0\r\n";
allhr += hr.HeaderString() ;
//allhr = "PLAY rtsp://localhost/10.rm RTSP/1.0\r\n"
// "CSeq: 6\r\n"
// "Session: "+session+"\r\n"
// "Range: npt=0.00-\r\n\r\n";
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("\nsend ok\n");
else printf("\nsend error\n");
memset(rbuf, 0 , sizeof(rbuf) );
csock->Reads(rbuf) ;
printf("\n============================\n");
printf(rbuf ) ;
printf("\n============================\n");
////////getparam position now
printf("\nGetParam now\n");
hr.ClearHeaders();
hr.AddHeader( "CSeq", "7");
hr.AddHeader( "Session", session );
hr.AddHeader( "Content-Type", "application/x-rtsp-mh");
hr.AddHeader( "Content-Length","9");
allhr = "GET_PARAMETER rtsp://localhost/10.rm RTSP/1.0\r\n";
allhr += hr.HeaderString();
allhr += "position\n";
printf(allhr.c_str());
dret = csock->Write(allhr.c_str(), allhr.length());
if( dret ) printf("\nsend ok\n");
else printf("\nsend error\n");
memset(rbuf, 0 , sizeof(rbuf) );
csock->Reads(rbuf) ;
printf(rbuf ) ;
printf("\nreturn ing %d \n" , session.length());
delete csock ;
}
|
[
"[email protected]"
] |
[
[
[
1,
252
]
]
] |
d19254c2c2094e6bb974740c989e87c11c17f83f
|
b22c254d7670522ec2caa61c998f8741b1da9388
|
/Tools/MapMerger/MapMerger.cpp
|
638bac0598bec9d4247296cde9726dfa5268ba0b
|
[] |
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 | 4,211 |
cpp
|
#include "MapMerger.h"
#include <fstream>
#include <map>
/***********************************************************
merge maps using information in the given file
***********************************************************/
void MapMerger::Merge(const std::string &InfoFile)
{
std::ifstream file(InfoFile.c_str());
file >> _sizeX;
file >> _sizeY;
file >> _sizeZ;
std::string newmapname;
file >> newmapname;
std::vector<mapInfo> maps;
while(!file.eof())
{
mapInfo mp;
file >> mp.name;
file >> mp.posX;
file >> mp.posY;
file >> mp.posZ;
maps.push_back(mp);
}
_bricks = new int[_sizeX*_sizeY*_sizeZ];
memset(_bricks, 0, _sizeX*_sizeY*_sizeZ*sizeof(int));
_physics = new short[_sizeX*_sizeY*_sizeZ];
memset(_physics, 0, _sizeX*_sizeY*_sizeZ*sizeof(short));
_materials = new short[_sizeX*_sizeY*_sizeZ];
memset(_materials, 0, _sizeX*_sizeY*_sizeZ*sizeof(short));
for(size_t i=0; i<maps.size(); ++i)
{
if(maps[i].name != "")
MergeMap(maps[i]);
}
WriteToFile(newmapname);
}
/***********************************************************
merge a map to the big one
***********************************************************/
void MapMerger::MergeMap(const mapInfo & mi)
{
std::ifstream file(mi.name.c_str());
int sizeX, sizeY, sizeZ;
file >> sizeX;
file >> sizeY;
file >> sizeZ;
int nbbricks;
file >> nbbricks;
std::map<int, int> mapidx;
// calculate new index for bricks
for(int i=0; i<nbbricks; ++i)
{
std::string tmpbr;
file >> tmpbr;
size_t j=0;
for(; j<_bricklist.size(); ++j)
if(_bricklist[j] == tmpbr)
break;
if(j == _bricklist.size())
_bricklist.push_back(tmpbr);
mapidx[i] = j;
}
// merge map bricks
for(int y=0;y<sizeY;y++)
{
// get graphic info
for(int x=0;x<sizeX;x++)
{
for(int z=0;z<sizeZ;z++)
{
int tmp;
file >> tmp;
if(tmp != 0)
GetBrick(x+mi.posX, y+mi.posY, z+mi.posZ) = mapidx[tmp-1]+1;
//else
// GetBrick(x+mi.posX, y+mi.posY, z+mi.posZ) = 0;
}
}
// get physic info
for(int x=0;x<sizeX;x++)
{
for(int z=0;z<sizeZ;z++)
{
short tmp;
file >> tmp;
if(tmp != 0)
GetPhysic(x+mi.posX, y+mi.posY, z+mi.posZ) = tmp;
}
}
// get material info
for(int x=0;x<sizeX;x++)
{
for(int z=0;z<sizeZ;z++)
{
short tmp;
file >> tmp;
if(tmp != 0)
GetMaterial(x+mi.posX, y+mi.posY, z+mi.posZ) = tmp;
}
}
}
}
/***********************************************************
return a brick fo the map
***********************************************************/
int & MapMerger::GetBrick(int X, int Y, int Z)
{
return _bricks[Y*_sizeX*_sizeZ+X*_sizeZ+Z];
}
// return a brick fo the map
short & MapMerger::GetPhysic(int X, int Y, int Z)
{
return _physics[Y*_sizeX*_sizeZ+X*_sizeZ+Z];
}
// return a brick fo the map
short & MapMerger::GetMaterial(int X, int Y, int Z)
{
return _materials[Y*_sizeX*_sizeZ+X*_sizeZ+Z];
}
/***********************************************************
write result to file
***********************************************************/
void MapMerger::WriteToFile(const std::string &FileName)
{
int * ptr = _bricks;
short * ptrP = _physics;
short * ptrM = _materials;
std::ofstream file(FileName.c_str());
file <<_sizeX << " " <<_sizeY << " " <<_sizeZ << std::endl;
file <<_bricklist.size() << std::endl << std::endl;
for(size_t j=0; j<_bricklist.size(); ++j)
file <<_bricklist[j] << std::endl;
file << std::endl<< std::endl;
for(int y=0;y<_sizeY;y++)
{
// write graphic
for(int x=0;x<_sizeX;x++)
{
for(int z=0;z<_sizeZ;z++)
{
file<<*ptr<<" ";
++ptr;
}
file<< std::endl;
}
file<< std::endl;
// write physic
for(int x=0;x<_sizeX;x++)
{
for(int z=0;z<_sizeZ;z++)
{
file<<*ptrP<<" ";
++ptrP;
}
file<< std::endl;
}
file<< std::endl;
// write material
for(int x=0;x<_sizeX;x++)
{
for(int z=0;z<_sizeZ;z++)
{
file<<*ptrM<<" ";
++ptrM;
}
file<< std::endl;
}
file<< std::endl;
}
}
|
[
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] |
[
[
[
1,
205
]
]
] |
d6b7485ab1fe3b5c534b0437d4a31ad31a8cd3aa
|
2e8e317aa42c16a7c30f3efaf401eb96715b0ce0
|
/textEdit.h
|
0f5ea0ffbb8a1afade1d23521a4df0c877ea17ea
|
[] |
no_license
|
barrycburton/aucrEdit
|
dc647b3f460b4bc07f4911435ca05529523b1100
|
f378f7519c35b976ce9b46322d24b71bc49a91b5
|
refs/heads/master
| 2016-09-02T04:45:22.743896 | 2011-04-03T22:37:05 | 2011-04-03T22:37:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,052 |
h
|
//textEdit.h
#ifndef TEXTEDIT_H
#define TEXTEDIT_H
#include <qwidget.h>
#include <qevent.h>
#include <qlayout.h>
#include <qabstractlayout.h>
#include <qlabel.h>
#include <qstring.h>
#include <qmultilineedit.h>
#include <wchar.h>
#include <stdlib.h>
#include "recogArea.h"
class recogArea;
class MyMultiLineEdit : public QMultiLineEdit
{
Q_OBJECT
public:
MyMultiLineEdit( QWidget* parent, const char* name );
bool myHasMarkedText();
public slots:
void myEnd();
void myDel();
void setFound( wchar_t );
};
class textEdit : public QWidget
{
Q_OBJECT
public slots:
void setText( QString );
public:
textEdit( QWidget* parent = 0, const char* name = 0 );
~textEdit();
QMultiLineEdit* getMyMultiLineEdit();
recogArea* getRecogArea();
QSize sizeHint() const;
QSizePolicy sizePolicy() const;
private:
recogArea* entry;
QLabel* textLab;
MyMultiLineEdit* textbox;
QVBoxLayout* mainLay;
QSpacerItem* topShim;
QSpacerItem* bottomShim;
};
#endif //TEXTEDIT_H
|
[
"[email protected]"
] |
[
[
[
1,
60
]
]
] |
f92da036b7120b3eb0a56ec307d5beb99d339bcc
|
7cf0bc0c3120c2040c3ed534421082cd93f0242f
|
/ab_mfc/ab_mfc/Page1.cpp
|
aabbb0f258eb429bf9b615129cd19b876f914ba0
|
[] |
no_license
|
zephyrer/ab-mfc
|
3d7be0283fa3fff3dcb7120fc1544e60a3811d88
|
f228b27a6fdbcb55f481155e9e9d77302335336a
|
refs/heads/master
| 2021-01-13T02:15:55.470629 | 2010-12-10T12:16:23 | 2010-12-10T12:16:23 | 40,066,957 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 13,404 |
cpp
|
// Page1.cpp : 实现文件
//
#include "stdafx.h"
#include "ab_mfc.h"
#include "Page1.h"
// CPage1 对话框
IMPLEMENT_DYNAMIC(CPage1, CDialog)
CPage1::CPage1(CWnd* pParent /*=NULL*/)
: CDialog(CPage1::IDD, pParent)
, m_comb_add(_T(""))
, m_list_add(_T(""))
, m_list_ctrl_add(_T(""))
, m_spinval(_T("spinval"))
{
}
CPage1::~CPage1()
{
}
void CPage1::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_comb_add);
DDX_Text(pDX, IDC_EDIT2, m_list_add);
DDX_Control(pDX, IDC_COMBO1, m_comb);
DDX_Control(pDX, IDC_LIST1, m_list);
DDX_Control(pDX, IDC_LIST2, m_list_ctrl);
DDX_Text(pDX, IDC_EDIT3, m_list_ctrl_add);
DDX_Control(pDX, IDC_PROGRESS1, m_progress);
DDX_Control(pDX, IDC_SLIDER1, m_slider);
DDX_Control(pDX, IDC_DATETIMEPICKER1, m_datetime);
DDX_Control(pDX, IDC_SPIN1, m_spin);
DDX_Control(pDX, IDC_IPADDRESS1, m_ipaddress);
DDX_Text(pDX, IDC_SPINVAL, m_spinval);
}
BEGIN_MESSAGE_MAP(CPage1, CDialog)
ON_BN_CLICKED(IDC_BUTTON_COMB_ADD, &CPage1::OnBnClickedButtonCombAdd)
ON_BN_CLICKED(IDC_BUTTON_COMB_DEL, &CPage1::OnBnClickedButtonCombDel)
ON_BN_CLICKED(IDC_IDC_BUTTON_LIST_ADD, &CPage1::OnBnClickedIdcButtonListAdd)
ON_BN_CLICKED(IDC_IDC_BUTTON_LIST_DEL, &CPage1::OnBnClickedButton4)
ON_BN_CLICKED(IDC_IDC_BUTTON_LIST_CTRL_ADD, &CPage1::OnBnClickedIdcButtonListCtrlAdd)
ON_NOTIFY(NM_RCLICK, IDC_LIST2, &CPage1::OnNMRclickList2)
ON_BN_CLICKED(IDC_IDC_BUTTON_LIST_CTRL_DEL, &CPage1::OnBnClickedIdcButtonListCtrlDel)
ON_COMMAND(ID_ADD, &CPage1::OnAdd)
ON_COMMAND(ID_DEL, &CPage1::OnDel)
ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER1, &CPage1::OnNMCustomdrawSlider1)
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, &CPage1::OnDeltaposSpin1)
ON_BN_CLICKED(IDC_BUTTON_GETTIME, &CPage1::OnBnClickedButtonGettime)
ON_BN_CLICKED(IDC_BUTTON_GETIP, &CPage1::OnBnClickedButtonGetip)
ON_WM_HSCROLL()
// ON_NOTIFY(NM_THEMECHANGED, IDC_SCROLLBAR1, &CPage1::OnThemechangedScrollbar1)
ON_WM_VSCROLL()
END_MESSAGE_MAP()
// CPage2 消息处理程序
BOOL CPage1::OnInitDialog()
{
CDialog::OnInitDialog();
m_comb.AddString("superKiki");
m_comb.SetCurSel(0);
//设置list_ctrl风格
DWORD dwStyle = ::GetWindowLong(m_list_ctrl.m_hWnd, GWL_STYLE);
dwStyle &= ~(LVS_TYPEMASK);
dwStyle &= ~(LVS_EDITLABELS);
//设置新风格
SetWindowLong(m_list_ctrl.m_hWnd, GWL_STYLE,dwStyle|LVS_REPORT|LVS_NOLABELWRAP|LVS_SHOWSELALWAYS);
//设置扩展风格
DWORD styles = LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES|LVS_EX_CHECKBOXES;
ListView_SetExtendedListViewStyleEx(m_list_ctrl.m_hWnd,styles,styles);
ListView_SetBkColor(m_list_ctrl,RGB(254,240,69));
ListView_SetTextBkColor(m_list_ctrl,RGB(254,240,69));
LV_COLUMN lvcol;
lvcol.mask =LVCF_TEXT;
lvcol.pszText = "Name";
ListView_InsertColumn(m_list_ctrl, 0, &lvcol);
ListView_SetColumnWidth(m_list_ctrl, 0, 100);
lvcol.mask =LVCF_TEXT;
lvcol.pszText = "Password";
ListView_InsertColumn(m_list_ctrl, 1, &lvcol);
ListView_SetColumnWidth(m_list_ctrl, 1, 100);
ListView_SetExtendedListViewStyle(m_list_ctrl,LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);//设置显示样式
/* 其中LVS_EX_FULLROWSELECT 就是前面说得整行选中
LVS_EX_GRIDLINES 网格线(只适用与report风格的listctrl)
LVS_EX_CHECKBOXES 前面加个checkbox
pListCtrl->SetExtendedStyle( m_listctrl.GetExtendedStyle()|LVS_EX_SUBITEMIMAGES);
这也是一个很重要的属性,这样的话,可以在列表中加ICON,记得windows的
任务管理器吗,你想做得那样,这个属性也要加哦,这个我以后会讲的~
*/
//这是MFC种添加列的方法
// m_list.InsertColumn( 0, "ID", LVCFMT_LEFT, 40 );//插入列
// m_list.InsertColumn( 1, "NAME", LVCFMT_LEFT, 50 );
//slider + progress
m_slider.SetRange(0,100);
m_progress.SetRange(0,100);
CString strNum;
strNum.Format("%d", m_slider.GetPos());
SetDlgItemText(IDC_NUM, strNum);
//spin
m_spin.SetBuddy(GetDlgItem(IDC_NUM));
m_spin.SetRange(0, 5);
m_spin.SetPos(0);
return TRUE;
}
void CPage1::OnBnClickedButtonCombAdd()
{
UpdateData(TRUE);
if(m_comb_add == "")
{
MessageBox("没有内容!", "oops!", MB_OK);
return;
}
m_comb.AddString(m_comb_add);
m_comb.SetCurSel(m_comb.GetCount()-1);
m_comb_add = "";
UpdateData(FALSE);
}
void CPage1::OnBnClickedButtonCombDel()
{
if(m_comb.GetCount() == 0)
{
MessageBox("没东西了!", "oops!", MB_OK);
}
UpdateData(TRUE);
int curSel = m_comb.GetCurSel();
m_comb.DeleteString(curSel);
if(m_comb.GetCount() == 0)
{
SetDlgItemText(IDC_COMBO1,"");
}
else
m_comb.SetCurSel(m_comb.GetCount()-1);
UpdateData(FALSE);
}
void CPage1::OnBnClickedIdcButtonListAdd()
{
UpdateData(TRUE);
if(m_list_add == "")
{
MessageBox("没有内容!","oops!",MB_OK);
return;
}
m_list.AddString(m_list_add);
m_list_add = "";
UpdateData(FALSE);
}
void CPage1::OnBnClickedButton4()
{
int curSel = m_list.GetCurSel();
if (LB_ERR != curSel)
{
m_list.DeleteString(curSel); //删除 m_mlist 选中的项目。
}
else
{
MessageBox("没有要删除的项目!", "oops!", MB_OK);
}
}
void CPage1::OnBnClickedIdcButtonListCtrlAdd()
{
UpdateData(TRUE);
if (m_list_ctrl_add == "")
{
MessageBox("没有内容!", "oops!", MB_OK);
return;
}
int nRow = m_list_ctrl.GetItemCount();//从后往前插入
nRow = m_list_ctrl.InsertItem(nRow, m_list_ctrl_add);//插入行
m_list_ctrl.SetItemText(nRow,1, m_list_ctrl_add);//设置数据
UpdateData(FALSE);
}
void CPage1::OnNMRclickList2(NMHDR *pNMHDR, LRESULT *pResult)
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
if(pNMListView->iItem != -1)
{
DWORD dwPos = GetMessagePos();
CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
CMenu menu;
VERIFY( menu.LoadMenu( IDR_MENU_LIST) );
CMenu* popup = menu.GetSubMenu(0);
ASSERT( popup != NULL );
popup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this );
}
*pResult = 0;
}
void CPage1::OnBnClickedIdcButtonListCtrlDel()
{
int nChoice = m_list_ctrl.GetNextItem(-1, LVNI_SELECTED);// 获得选择项.
if (nChoice != -1) // 当存在选择项时
{
m_list_ctrl.DeleteItem(nChoice); // 删除项.
}
else
{
AfxMessageBox(_T("没有选择项存在,请先进行选择!"));
}
}
void CPage1::OnAdd()
{
OnBnClickedIdcButtonListCtrlAdd();
}
void CPage1::OnDel()
{
OnBnClickedIdcButtonListCtrlDel();
}
void CPage1::OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
int curPos = m_slider.GetPos();
m_progress.SetPos(curPos);
CString strNum;
strNum.Format("%d", curPos);
SetDlgItemText(IDC_NUM, strNum);
*pResult = 0;
}
void CPage1::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)// 已修改
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
pNMUpDown->iDelta = pNMUpDown->iDelta; // Spin Contrl的用法(很简单吧~)
m_spinval.Format("%d", pNMUpDown->iDelta); // 转换数据格式,int -> CString
SetDlgItemText(IDC_SPINVAL,m_spinval); // 将数据显示在静态控件上
*pResult = 0;
}
void CPage1::OnBnClickedButtonGettime()// 已修改
{
SYSTEMTIME st;
m_datetime.GetTime(&st);
CString strTime;
CString strGmt = CTime::GetCurrentTime().FormatGmt("当前日期:%Y/%m/%d\n 当前时间:%H:%M:%S\n"); // 得到当前时间
strTime.Format("从控件上得到的时间:%d年%d月%d日", st.wYear, st.wMonth, st.wDay);
MessageBox(strGmt + strTime, "日期", MB_OK);
}
void CPage1::OnBnClickedButtonGetip()
{
int b1, b2, b3, b4; // IP的四段,想一想为什么是int型而不是BYTE型呢?
CString strIP;
WSADATA wsd;
PHOSTENT hostinfo;
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
AfxMessageBox( "网络初始化失败 ");
}
else
{
if (gethostname(strIP.GetBuffer(128), 128) == 0)
{
//获取主机相关信息
MessageBox(strIP, "第一步,得到您的机器名:", MB_OK);
if ((hostinfo = gethostbyname(strIP)) != NULL)
{
strIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);// 得到IP字符串
}
MessageBox(strIP, "第二步,得到您的IP:", MB_OK);
}
}
WSACleanup();
MessageBox("确定完成", "第三步,将您的IP字符串转成IP格式:", MB_OK);
sscanf(strIP, "%d.%d.%d.%d", &b1, &b2, &b3, &b4); // 将字符串转成IP
m_ipaddress.SetAddress(b1, b2, b3, b4);
}
void CPage1::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: Add your message handler code here and/or call default
int minpos;
int maxpos;
if (pScrollBar != GetDlgItem(IDC_SCROLLBAR1)) // 判断是不是本控件,如果不是,则直接返回
return ; // $$$$这是必要的, 为防止其它控件产生WM_HSCROLL消息干扰
pScrollBar->SetScrollRange(0, 100); // 设置滚动条范围
pScrollBar->GetScrollRange(&minpos, &maxpos);
maxpos = pScrollBar->GetScrollLimit(); // 得到实际滚动条范围
// 得到滚动条的当前位置
int curpos = pScrollBar->GetScrollPos(); // 得到当前滑块所在位置
CWnd *HwndHstr = GetDlgItem(IDC_Hstr); // 得到显示横坐标标签的句柄
RECT rect;
pScrollBar->GetWindowRect(&rect); // 得到本控件的区域范围
int per = (rect.right - rect.left) / maxpos; // 得到它滚动一格的距离 $$:必要的
HwndHstr->GetWindowRect(&rect); // 得到显示横坐标标签的区域
ScreenToClient(&rect); // 计算相对坐标
// 根据消息对滑块的位置以及标签的位置进行计算
switch (nSBCode)
{
case SB_LEFT:
curpos = minpos; // 到最左处
break;
case SB_RIGHT: // 到最右处
curpos = maxpos;
break;
// 释放滑块
case SB_ENDSCROLL:
break;
case SB_LINELEFT: // 点击左区域或左翻页时滑块及标签移动
case SB_PAGELEFT:
if (curpos > minpos)
{
curpos--;
rect.left -= per;
rect.right -= per;
}
break;
case SB_LINERIGHT: // 点击右区域或右翻页时滑块及标签移动
case SB_PAGERIGHT:
if (curpos < maxpos - 1) // 想一想为什么要减1?
{
curpos++;
rect.left += per;
rect.right += per;
}
break;
case SB_THUMBPOSITION: //点击滑块进行拖曳时滑块及标签同时移动
case SB_THUMBTRACK:
rect.left += (nPos - curpos) * per;
rect.right += (nPos - curpos) * per;
curpos = nPos;
break;
}
// 将滑块及标签移动新的位置
pScrollBar->SetScrollPos(curpos);
HwndHstr->MoveWindow(&rect);
CString strNum;
strNum.Format("%d", curpos);
SetDlgItemText(IDC_Hstr, strNum); // 发给显示标签当前位置数值
CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
}
void CPage1::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: Add your message handler code here and/or call default
int minpos;
int maxpos;
if (pScrollBar != GetDlgItem(IDC_SCROLLBAR2)) // 判断是不是本控件,如果不是,则直接返回
return ;
pScrollBar->SetScrollRange(0, 100); // 设置滚动条范围
pScrollBar->GetScrollRange(&minpos, &maxpos);
maxpos = pScrollBar->GetScrollLimit(); // 得到实际滚动条范围
// Get the current position of scroll box.
int curpos = pScrollBar->GetScrollPos(); // 得到当前滑块所在位置
CWnd *HwndHstr = GetDlgItem(IDC_Vstr); // 得到显示横坐标标签的句柄
RECT rect;
pScrollBar->GetWindowRect(&rect); // 得到滚动条区域
int per = (rect.bottom - rect.top) / maxpos; // 得到它滚动一格的距离
HwndHstr->GetWindowRect(&rect); // 得到显示横坐标标签的区域
ScreenToClient(&rect); // 计算相对坐标
// 根据消息对滑块及标签位置进行定位
switch (nSBCode)
{
case SB_TOP: // 到最顶处
curpos = minpos;
break;
// 到最底处
case SB_BOTTOM:
curpos = maxpos;
break;
// 释放滑块
case SB_ENDSCROLL:
break;
// 点击上区域或者向上翻页按钮滑块及标签坐标变化
case SB_LINEUP:
case SB_PAGEUP:
if (curpos > minpos)
{
curpos--;
rect.top -= per;
rect.bottom -= per;
}
break;
case SB_LINEDOWN: // 点击下区域或者向下翻页按钮滑块及标签坐标变化
case SB_PAGEDOWN:
if (curpos < maxpos - 1)
{
curpos++;
rect.top += per;
rect.bottom += per;
}
break;
case SB_THUMBPOSITION: //点击滑块进行拖曳时滑块及标签同时移动
case SB_THUMBTRACK:
rect.top += (nPos - curpos) * per;
rect.bottom += (nPos - curpos) * per;
curpos = nPos;
break;
}
// 将滑块及标签移动最新位置
pScrollBar->SetScrollPos(curpos);
HwndHstr->MoveWindow(&rect);
CString strNum;
strNum.Format("%d", curpos);
SetDlgItemText(IDC_Vstr, strNum); // 显示当前纵坐标
CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}
void CPage1::OnOK()
{
return;
}
|
[
"[email protected]",
"superkiki1989@ce34bfc1-e555-5f21-4a2b-332ae8037cd2"
] |
[
[
[
1,
1
],
[
9,
9
],
[
18,
18
],
[
41,
41
],
[
59,
61
],
[
111,
115
],
[
118,
118
],
[
128,
128
],
[
141,
141
],
[
143,
143
],
[
178,
178
],
[
187,
187
],
[
191,
192
],
[
216,
217
],
[
219,
219
],
[
242,
245
],
[
249,
249
],
[
251,
255
],
[
259,
259
],
[
261,
267
],
[
272,
452
],
[
454,
458
]
],
[
[
2,
8
],
[
10,
17
],
[
19,
40
],
[
42,
58
],
[
62,
110
],
[
116,
117
],
[
119,
127
],
[
129,
140
],
[
142,
142
],
[
144,
177
],
[
179,
186
],
[
188,
190
],
[
193,
215
],
[
218,
218
],
[
220,
241
],
[
246,
248
],
[
250,
250
],
[
256,
258
],
[
260,
260
],
[
268,
271
],
[
453,
453
]
]
] |
d3c25e7411d34f5e7ca3d7b151b3b6a8b18c0f5d
|
97b7853d2eb3481f9fb091c5e61cb8d9ba052a50
|
/include/djVisual.h
|
2206c8562517d1a5093f54071def26b55d3192f3
|
[] |
no_license
|
mentat/tehDJ
|
dad7826f7bca57603d57120267ef0711d2572859
|
ee1f782374897bf5e00102827194b89614029eed
|
refs/heads/master
| 2021-01-25T03:54:58.836751 | 2011-03-23T22:27:09 | 2011-03-23T22:27:09 | 1,518,542 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,080 |
h
|
// --*-c++-*--
/*
tehDJ - Mp3 DJ System
Copyright (C) 2002 Jesse Lovelace
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef DJ_VISUAL_H
#define DJ_VISUAL_H
#include <vector>
#include <rfftw.h>
#include <fftw.h>
#include "LogScale.h"
#include "CircQueue.h"
using namespace std;
class VisualNode
{
public:
VisualNode(short *l, short *r, unsigned long n, unsigned long o)
: left(l), right(r), length(n), offset(o)
{
// left and right are allocated and then passed to this class
// the code that allocated left and right should give up all ownership
}
~VisualNode()
{
delete [] left;
delete [] right;
}
short *left, *right;
long length, offset;
};
class wxVisual: public wxWindow
{
public:
wxVisual() { Init(); }
virtual ~wxVisual();
wxVisual(wxWindow *parent, const wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0)
{
Init();
Create(parent, id, pos, size, style);
}
virtual void Init();
virtual bool Create(wxWindow *parent, const wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0);
virtual void Process(short * left, short * right, unsigned int length) = 0;
virtual void Run() = 0;
virtual void Stop() = 0;
void SetBufferSize(unsigned long sz);
void Eat( short * buffer, unsigned int length, int bits, int channels);
void OnPaint(wxPaintEvent& event);
virtual void OnSize(wxSizeEvent& event) = 0;
void OnTimer(wxTimerEvent & event);
protected:
virtual void DoPaint(wxDC * dc) = 0;
//wxThread m_vis;
//CircQueue<wxBitmap> m_queue;
wxMutex m_lock;
short * m_left;
short * m_right;
bool m_mono;
unsigned long m_length;
unsigned long m_actual;
};
class wxMonoScope: public wxVisual
{
public:
wxMonoScope(wxWindow *parent, const wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0)
{
Init();
Create(parent, id, pos, size, style);
}
wxMonoScope() { Init(); }
virtual bool Create(wxWindow *parent,
wxWindowID id = -1,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0);
virtual void Init();
virtual ~wxMonoScope();
virtual void Stop();
virtual void Run();
virtual void Process(short * left, short * right, unsigned int length);
//void OnPaint(wxPaintEvent& event);
virtual void OnSize(wxSizeEvent& event);
//void OnTimer(wxTimerEvent & event);
private:
virtual void DoPaint(wxDC * dc);
wxColor m_startColor, m_targetColor;
wxTimer m_timer;
vector<double> m_mags;
vector<wxRect> m_rects;
double m_scaleFactor,
m_falloff;
int m_analyzerBarWidth,
m_fps;
LogScale m_scale;
rfftw_plan plan;
fftw_real lin[512], rin[512], lout[1024], rout[1024];
DECLARE_EVENT_TABLE()
DECLARE_DYNAMIC_CLASS(wxMonoScope)
};
class wxStereoScope : public wxVisual
{
public:
wxStereoScope(wxWindow *parent, const wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0)
{
Init();
Create(parent, id, pos, size, style);
}
wxStereoScope() { Init(); }
virtual bool Create(wxWindow *parent,
wxWindowID id = -1,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0);
virtual void Init();
virtual ~wxStereoScope();
virtual void Stop();
virtual void Run();
virtual void Process(short * left, short * right, unsigned int length);
void OnSize(wxSizeEvent& event);
protected:
void DoPaint(wxDC * dc);
wxColor m_startColor, m_targetColor;
wxTimer m_timer;
vector<double> m_mags;
vector<wxRect> m_rects;
bool m_rubberband;
double m_falloff;
int m_fps;
DECLARE_EVENT_TABLE()
DECLARE_DYNAMIC_CLASS(wxStereoScope)
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
198
]
]
] |
f133afcefec578b04cd9218c90641f4a718046ec
|
b4bff7f61d078e3dddeb760e21174a781ed7f985
|
/Examples/Tutorial/UserInterface/39ColorChooser.cpp
|
25ca4eb265da9042351a56bd53406a142c168dfe
|
[] |
no_license
|
Langkamp/OpenSGToolbox
|
8283edb6074dffba477c2c4d632e954c3c73f4e3
|
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
|
refs/heads/master
| 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,416 |
cpp
|
// OpenSG Tutorial Example: Creating a Button Component
//
// This tutorial explains how to edit the basic features of
// a Button and a ToggleButtoncreated in the OSG User
// Interface library.
//
// Includes: Button PreferredSize, MaximumSize, MinimumSize, Font,
// Text,and adding a Button to a Scene. Also note that clicking
// the Button causes it to appear pressed
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
// The general scene file loading handler
#include "OSGSceneFileHandler.h"
// Input
#include "OSGWindowUtils.h"
// UserInterface Headers
#include "OSGUIForeground.h"
#include "OSGUIDrawingSurface.h"
#include "OSGInternalWindow.h"
#include "OSGGraphics2D.h"
#include "OSGLookAndFeelManager.h"
#include "OSGUIDrawUtils.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerRefPtr TutorialWindow;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
// 01 Button Headers
#include "OSGColorChooser.h"
#include "OSGFlowLayout.h"
#include "OSGLayers.h"
// Create a class to allow for the use of the Escape
// key to exit
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
// Make Torus Node (creates Torus in background of scene)
NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);
// Make Main Scene Node and add the Torus
NodeRefPtr scene = OSG::Node::create();
scene->setCore(OSG::Group::create());
scene->addChild(TorusGeometryNode);
// Create the Graphics
GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();
// Initialize the LookAndFeelManager to enable default settings
LookAndFeelManager::the()->getLookAndFeel()->init();
ColorChooserRefPtr TheColorChooser = ColorChooser::create();
TheColorChooser->setColor(Color4f(0.0f,0.0f,0.0f,1.0f));
// Create Background to be used with the MainInternalWindow
ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
// Create The Internal Window
InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
// Assign the Button to the MainInternalWindow so it will be displayed
// when the view is rendered.
MainInternalWindow->pushToChildren(TheColorChooser);
MainInternalWindow->setLayout(MainInternalWindowLayout);
MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
MainInternalWindow->setPosition(Pnt2f(50,50));
MainInternalWindow->setPreferredSize(Vec2f(400,400));
MainInternalWindow->setTitle(std::string("Internal Window"));
// Create the Drawing Surface
UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
TutorialDrawingSurface->setGraphics(TutorialGraphics);
TutorialDrawingSurface->setEventProducer(TutorialWindow);
TutorialDrawingSurface->openWindow(MainInternalWindow);
// Create the UI Foreground Object
UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();
TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
mgr->setRoot(scene);
// Add the UI Foreground Object to the Scene
ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
TutorialViewport->addForeground(TutorialUIForeground);
// Show the whole Scene
mgr->showAll();
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"39ColorChooser");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
|
[
"[email protected]"
] |
[
[
[
1,
180
]
]
] |
f637d0ade1ce131d4584a450861b9318c99c1baa
|
bb9c5cb1153d2255e362f281c2fbc15135eb41d0
|
/Gosu/Math.hpp
|
6792ad031b16eedc640b40b11ea5978cf6300e8d
|
[] |
no_license
|
tobi994/tangame
|
38710879439fd08a9d482f99f7d29f4b30afe2fa
|
dcc64836b38d9f4ea3ba8eb19c3057cbc5bf4764
|
refs/heads/master
| 2021-01-10T02:42:45.691598 | 2008-08-31T07:53:56 | 2008-08-31T07:53:56 | 48,272,581 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,611 |
hpp
|
//! \file Math.hpp
//! Contains simple math functionality.
#ifndef GOSU_MATH_HPP
#define GOSU_MATH_HPP
namespace Gosu
{
//! Pi.
const double pi = 3.1415926536;
//! Truncates the fractional part of a real value. Equivalent to
//! static_cast<long>.
inline long trunc(double value)
{
return static_cast<long>(value);
}
//! Rounds a real value towards the next integer.
inline long round(double value)
{
if (value >= 0)
return static_cast<long>(value + 0.5);
else
return static_cast<long>(value - 0.5);
}
//! Returns a real value between min and max. Uses std::rand (so you have
//! to call std::srand before using it).
double random(double min, double max);
//! Returns the horizontal distance between the origin and the point to
//! which you would get if you moved radius pixels in the direction
//! specified by angle.
//! \param angle Angle in degrees where 0.0 means upwards.
double offsetX(double angle, double radius);
//! Returns the vertical distance between the origin and the point to
//! which you would get if you moved radius pixels in the direction
//! specified by angle.
//! \param angle Angle in degrees where 0.0 means upwards.
double offsetY(double angle, double radius);
//! Returns the angle between two points in degrees, where 0.0 means
//! upwards. Returns def if both points are equal.
double angle(double fromX, double fromY, double toX, double toY,
double def = 0);
//! Returns the smallest positive angle between two angles.
double angleDiff(double angle1, double angle2);
//! Normalizes an angle to fit into the range [0; 360[.
double normalizeAngle(double angle);
//! Returns value * value.
template<typename T>
T square(T value)
{
return value * value;
}
//! Returns min if value is smaller than min, max if value is larger than
//! max and value otherwise.
template<typename T>
T boundBy(T value, T min, T max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
//! Returns the square of the distance between two points.
inline double distanceSqr(double x1, double y1, double x2, double y2)
{
return square(x1 - x2) + square(y1 - y2);
}
//! Returns the distance between two points.
double distance(double x1, double y1, double x2, double y2);
}
#endif
|
[
"lucaslevin@38d87d5a-f654-0410-a73f-b91a456e9eba"
] |
[
[
[
1,
80
]
]
] |
d617326c97cfbdafc35be905ec2c66884ca8996b
|
463c3b62132d215e245a097a921859ecb498f723
|
/lib/dlib/algs.h
|
d4ecd71ccc0023d5c5dc4964a624f0aa5c89101d
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] |
permissive
|
athulan/cppagent
|
58f078cee55b68c08297acdf04a5424c2308cfdc
|
9027ec4e32647e10c38276e12bcfed526a7e27dd
|
refs/heads/master
| 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 25,462 |
h
|
// Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_ALGs_
#define DLIB_ALGs_
// this file contains miscellaneous stuff
#ifdef _MSC_VER
// Disable the following warnings for Visual Studio
// this is to disable the "'this' : used in base member initializer list"
// warning you get from some of the GUI objects since all the objects
// require that their parent class be passed into their constructor.
// In this case though it is totally safe so it is ok to disable this warning.
#pragma warning(disable : 4355)
// This is a warning you get sometimes when Visual Studio performs a Koenig Lookup.
// This is a bug in visual studio. It is a totally legitimate thing to
// expect from a compiler.
#pragma warning(disable : 4675)
// This is a warning you get from visual studio 2005 about things in the standard C++
// library being "deprecated." I checked the C++ standard and it doesn't say jack
// about any of them (I checked the searchable PDF). So this warning is total Bunk.
#pragma warning(disable : 4996)
// This is a warning you get from visual studio 2003:
// warning C4345: behavior change: an object of POD type constructed with an initializer
// of the form () will be default-initialized.
// I love it when this compiler gives warnings about bugs in previous versions of itself.
#pragma warning(disable : 4345)
// Disable warnings about conversion from size_t to unsigned long and long.
#pragma warning(disable : 4267)
// Disable warnings about conversion from double to float
#pragma warning(disable : 4244)
#pragma warning(disable : 4305)
#endif
#ifdef __BORLANDC__
// Disable the following warnings for the Borland Compilers
//
// These warnings just say that the compiler is refusing to inline functions with
// loops or try blocks in them.
//
#pragma option -w-8027
#pragma option -w-8026
#endif
#include <string> // for the exceptions
#ifdef __CYGWIN__
namespace std
{
typedef std::basic_string<wchar_t> wstring;
}
#endif
#include <algorithm> // for std::swap
#include <new> // for std::bad_alloc
#include <cstdlib>
#include "platform.h"
#include "assert.h"
#include "error.h"
#include "noncopyable.h"
#include "enable_if.h"
#include "uintn.h"
// ----------------------------------------------------------------------------------------
/*!A _dT !*/
template <typename charT>
inline charT _dTcast (const char a, const wchar_t b);
template <>
inline char _dTcast<char> (const char a, const wchar_t ) { return a; }
template <>
inline wchar_t _dTcast<wchar_t> (const char , const wchar_t b) { return b; }
template <typename charT>
inline const charT* _dTcast ( const char* a, const wchar_t* b);
template <>
inline const char* _dTcast<char> ( const char* a, const wchar_t* ) { return a; }
template <>
inline const wchar_t* _dTcast<wchar_t> ( const char* , const wchar_t* b) { return b; }
#define _dT(charT,str) _dTcast<charT>(str,L##str)
/*!
requires
- charT == char or wchar_t
- str == a string or character literal
ensures
- returns the literal in the form of a charT type literal.
!*/
// ----------------------------------------------------------------------------------------
namespace dlib
{
// ----------------------------------------------------------------------------------------
/*!A swap !*/
// make swap available in the dlib namespace
using std::swap;
// ----------------------------------------------------------------------------------------
/*!
Here is where I define my return codes. It is
important that they all be < 0.
!*/
enum general_return_codes
{
TIMEOUT = -1,
WOULDBLOCK = -2,
OTHER_ERROR = -3,
SHUTDOWN = -4,
PORTINUSE = -5
};
// ----------------------------------------------------------------------------------------
inline unsigned long square_root (
unsigned long value
)
/*!
requires
- value <= 2^32 - 1
ensures
- returns the square root of value. if the square root is not an
integer then it will be rounded up to the nearest integer.
!*/
{
unsigned long x;
// set the initial guess for what the root is depending on
// how big value is
if (value < 3)
return value;
else if (value < 4096) // 12
x = 45;
else if (value < 65536) // 16
x = 179;
else if (value < 1048576) // 20
x = 717;
else if (value < 16777216) // 24
x = 2867;
else if (value < 268435456) // 28
x = 11469;
else // 32
x = 45875;
// find the root
x = (x + value/x)>>1;
x = (x + value/x)>>1;
x = (x + value/x)>>1;
x = (x + value/x)>>1;
if (x*x < value)
return x+1;
else
return x;
}
// ----------------------------------------------------------------------------------------
template <
typename T
>
void median (
T& one,
T& two,
T& three
);
/*!
requires
- T implements operator<
- T is swappable by a global swap()
ensures
- #one is the median
- #one, #two, and #three is some permutation of one, two, and three.
!*/
template <
typename T
>
void median (
T& one,
T& two,
T& three
)
{
using std::swap;
using dlib::swap;
if ( one < two )
{
// one < two
if ( two < three )
{
// one < two < three : two
swap(one,two);
}
else
{
// one < two >= three
if ( one < three)
{
// three
swap(three,one);
}
}
}
else
{
// one >= two
if ( three < one )
{
// three <= one >= two
if ( three < two )
{
// two
swap(two,one);
}
else
{
// three
swap(three,one);
}
}
}
}
// ----------------------------------------------------------------------------------------
namespace relational_operators
{
template <
typename A,
typename B
>
bool operator> (
const A& a,
const B& b
) { return b < a; }
// ---------------------------------
template <
typename A,
typename B
>
bool operator!= (
const A& a,
const B& b
) { return !(a == b); }
// ---------------------------------
template <
typename A,
typename B
>
bool operator<= (
const A& a,
const B& b
) { return !(b < a); }
// ---------------------------------
template <
typename A,
typename B
>
bool operator>= (
const A& a,
const B& b
) { return !(a < b); }
}
// ----------------------------------------------------------------------------------------
template <
typename T
>
void exchange (
T& a,
T& b
)
/*!
This function does the exact same thing that global swap does and it does it by
just calling swap. But a lot of compilers have problems doing a Koenig Lookup
and the fact that this has a different name (global swap has the same name as
the member functions called swap) makes them compile right.
So this is a workaround but not too ugly of one. But hopefully I get get
rid of this in a few years. So this function is alredy deprecated.
This also means you should NOT use this function in your own code unless
you have to support an old buggy compiler that benefits from this hack.
!*/
{
using std::swap;
using dlib::swap;
swap(a,b);
}
// ----------------------------------------------------------------------------------------
/*!A is_pointer_type
This is a template where is_pointer_type<T>::value == true when T is a pointer
type ane false otherwise.
!*/
template <
typename T
>
class is_pointer_type
{
public:
enum { value = false };
private:
is_pointer_type();
};
template <
typename T
>
class is_pointer_type<T*>
{
public:
enum { value = true };
private:
is_pointer_type();
};
// ----------------------------------------------------------------------------------------
/*!A is_const_type
This is a template where is_const_type<T>::value == true when T is a const
type ane false otherwise.
!*/
template <typename T>
struct is_const_type
{
static const bool value = false;
};
template <typename T>
struct is_const_type<const T>
{
static const bool value = true;
};
// ----------------------------------------------------------------------------------------
/*!A is_same_type
This is a template where is_same_type<T,U>::value == true when T and U are the
same type and false otherwise.
!*/
template <
typename T,
typename U
>
class is_same_type
{
public:
enum {value = false};
private:
is_same_type();
};
template <typename T>
class is_same_type<T,T>
{
public:
enum {value = true};
private:
is_same_type();
};
// ----------------------------------------------------------------------------------------
/*!A is_convertible
This is a template that can be used to determine if one type is convertible
into another type.
For example:
is_convertible<int,float>::value == true // because ints are convertible to floats
is_convertible<int*,float>::value == false // because int pointers are NOT convertible to floats
!*/
template <typename from, typename to>
struct is_convertible
{
struct yes_type { char a; };
struct no_type { yes_type a[2]; };
static const from& from_helper();
static yes_type test(to);
static no_type test(...);
const static bool value = sizeof(test(from_helper())) == sizeof(yes_type);
};
// ----------------------------------------------------------------------------------------
/*!A is_signed_type
This is a template where is_signed_type<T>::value == true when T is a signed
integral type and false when T is an unsigned integral type.
!*/
template <
typename T
>
struct is_signed_type
{
static const bool value = static_cast<T>((static_cast<T>(0)-static_cast<T>(1))) < 0;
};
// ----------------------------------------------------------------------------------------
/*!A is_unsigned_type
This is a template where is_unsigned_type<T>::value == true when T is an unsigned
integral type and false when T is a signed integral type.
!*/
template <
typename T
>
struct is_unsigned_type
{
static const bool value = static_cast<T>((static_cast<T>(0)-static_cast<T>(1))) > 0;
};
// ----------------------------------------------------------------------------------------
template <
typename T
>
class copy_functor
{
public:
void operator() (
const T& source,
T& destination
) const
{
destination = source;
}
};
// ----------------------------------------------------------------------------------------
/*!A static_switch
To use this template you give it some number of boolean expressions and it
tells you which one of them is true. If more than one of them is true then
it causes a compile time error.
for example:
static_switch<1 + 1 == 2, 4 - 1 == 4>::value == 1 // because the first expression is true
static_switch<1 + 1 == 3, 4 == 4>::value == 2 // because the second expression is true
static_switch<1 + 1 == 3, 4 == 5>::value == 0 // 0 here because none of them are true
static_switch<1 + 1 == 2, 4 == 4>::value == compiler error // because more than one expression is true
!*/
template < bool v1 = 0, bool v2 = 0, bool v3 = 0, bool v4 = 0, bool v5 = 0,
bool v6 = 0, bool v7 = 0, bool v8 = 0, bool v9 = 0, bool v10 = 0,
bool v11 = 0, bool v12 = 0, bool v13 = 0, bool v14 = 0, bool v15 = 0 >
struct static_switch;
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0> { const static int value = 0; };
template <> struct static_switch<1,0,0,0,0,0,0,0,0,0,0,0,0,0,0> { const static int value = 1; };
template <> struct static_switch<0,1,0,0,0,0,0,0,0,0,0,0,0,0,0> { const static int value = 2; };
template <> struct static_switch<0,0,1,0,0,0,0,0,0,0,0,0,0,0,0> { const static int value = 3; };
template <> struct static_switch<0,0,0,1,0,0,0,0,0,0,0,0,0,0,0> { const static int value = 4; };
template <> struct static_switch<0,0,0,0,1,0,0,0,0,0,0,0,0,0,0> { const static int value = 5; };
template <> struct static_switch<0,0,0,0,0,1,0,0,0,0,0,0,0,0,0> { const static int value = 6; };
template <> struct static_switch<0,0,0,0,0,0,1,0,0,0,0,0,0,0,0> { const static int value = 7; };
template <> struct static_switch<0,0,0,0,0,0,0,1,0,0,0,0,0,0,0> { const static int value = 8; };
template <> struct static_switch<0,0,0,0,0,0,0,0,1,0,0,0,0,0,0> { const static int value = 9; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,1,0,0,0,0,0> { const static int value = 10; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,1,0,0,0,0> { const static int value = 11; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,0,1,0,0,0> { const static int value = 12; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,0,0,1,0,0> { const static int value = 13; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,0,0,0,1,0> { const static int value = 14; };
template <> struct static_switch<0,0,0,0,0,0,0,0,0,0,0,0,0,0,1> { const static int value = 15; };
// ----------------------------------------------------------------------------------------
/*!A is_built_in_scalar_type
This is a template that allows you to determine if the given type is a built
in scalar type such as an int, char, float, short, etc...
For example, is_built_in_scalar_type<char>::value == true
For example, is_built_in_scalar_type<std::string>::value == false
!*/
template <typename T> struct is_built_in_scalar_type { const static bool value = false; };
template <> struct is_built_in_scalar_type<float> { const static bool value = true; };
template <> struct is_built_in_scalar_type<double> { const static bool value = true; };
template <> struct is_built_in_scalar_type<long double> { const static bool value = true; };
template <> struct is_built_in_scalar_type<short> { const static bool value = true; };
template <> struct is_built_in_scalar_type<int> { const static bool value = true; };
template <> struct is_built_in_scalar_type<long> { const static bool value = true; };
template <> struct is_built_in_scalar_type<unsigned short> { const static bool value = true; };
template <> struct is_built_in_scalar_type<unsigned int> { const static bool value = true; };
template <> struct is_built_in_scalar_type<unsigned long> { const static bool value = true; };
template <> struct is_built_in_scalar_type<uint64> { const static bool value = true; };
template <> struct is_built_in_scalar_type<char> { const static bool value = true; };
template <> struct is_built_in_scalar_type<signed char> { const static bool value = true; };
template <> struct is_built_in_scalar_type<unsigned char> { const static bool value = true; };
// Don't define one for wchar_t when using a version of visual studio
// older than 8.0 (visual studio 2005) since before then they improperly set
// wchar_t to be a typedef rather than its own type as required by the C++
// standard.
#if !defined(_MSC_VER) || _NATIVE_WCHAR_T_DEFINED
template <> struct is_built_in_scalar_type<wchar_t> { const static bool value = true; };
#endif
// ----------------------------------------------------------------------------------------
/*!A assign_zero_if_built_in_scalar_type
This function assigns its argument the value of 0 if it is a built in scalar
type according to the is_built_in_scalar_type<> template. If it isn't a
built in scalar type then it does nothing.
!*/
template <typename T> inline typename disable_if<is_built_in_scalar_type<T>,void>::type assign_zero_if_built_in_scalar_type (T&){}
template <typename T> inline typename enable_if<is_built_in_scalar_type<T>,void>::type assign_zero_if_built_in_scalar_type (T& a){a=0;}
// ----------------------------------------------------------------------------------------
template <typename T>
T put_in_range (
const T& a,
const T& b,
const T& val
)
/*!
requires
- T is a type that looks like double, float, int, or so forth
ensures
- if (val is within the range [a,b]) then
- returns val
- else
- returns the end of the range [a,b] that is closest to val
!*/
{
if (a < b)
{
if (val < a)
return a;
else if (val > b)
return b;
}
else
{
if (val < b)
return b;
else if (val > a)
return a;
}
return val;
}
// overload for double
inline double put_in_range(const double& a, const double& b, const double& val)
{ return put_in_range<double>(a,b,val); }
// ----------------------------------------------------------------------------------------
/*!A tabs
This is a template to compute the absolute value a number at compile time.
For example,
abs<-4>::value == 4
abs<4>::value == 4
!*/
template <long x, typename enabled=void>
struct tabs { const static long value = x; };
template <long x>
struct tabs<x,typename enable_if_c<(x < 0)>::type> { const static long value = -x; };
// ----------------------------------------------------------------------------------------
/*!A tmax
This is a template to compute the max of two values at compile time
For example,
abs<4,7>::value == 7
!*/
template <long x, long y, typename enabled=void>
struct tmax { const static long value = x; };
template <long x, long y>
struct tmax<x,y,typename enable_if_c<(y > x)>::type> { const static long value = y; };
// ----------------------------------------------------------------------------------------
/*!A tmin
This is a template to compute the min of two values at compile time
For example,
abs<4,7>::value == 4
!*/
template <long x, long y, typename enabled=void>
struct tmin { const static long value = x; };
template <long x, long y>
struct tmin<x,y,typename enable_if_c<(y < x)>::type> { const static long value = y; };
// ----------------------------------------------------------------------------------------
/*!A is_function
This is a template that allows you to determine if the given type is a function.
For example,
void funct();
is_built_in_scalar_type<funct>::value == true
is_built_in_scalar_type<int>::value == false
!*/
template <typename T> struct is_function { static const bool value = false; };
template <typename T>
struct is_function<T (void)> { static const bool value = true; };
template <typename T, typename A0>
struct is_function<T (A0)> { static const bool value = true; };
template <typename T, typename A0, typename A1>
struct is_function<T (A0, A1)> { static const bool value = true; };
template <typename T, typename A0, typename A1, typename A2>
struct is_function<T (A0, A1, A2)> { static const bool value = true; };
template <typename T, typename A0, typename A1, typename A2, typename A3>
struct is_function<T (A0, A1, A2, A3)> { static const bool value = true; };
template <typename T, typename A0, typename A1, typename A2, typename A3, typename A4>
struct is_function<T (A0, A1, A2, A3, A4)> { static const bool value = true; };
template <typename T> class funct_wrap0
{
public:
funct_wrap0(T (&f_)()):f(f_){}
T operator()() const { return f(); }
private:
T (&f)();
};
template <typename T, typename A0> class funct_wrap1
{
public:
funct_wrap1(T (&f_)(A0)):f(f_){}
T operator()(A0 a0) const { return f(a0); }
private:
T (&f)(A0);
};
template <typename T, typename A0, typename A1> class funct_wrap2
{
public:
funct_wrap2(T (&f_)(A0,A1)):f(f_){}
T operator()(A0 a0, A1 a1) const { return f(a0,a1); }
private:
T (&f)(A0,A1);
};
template <typename T, typename A0, typename A1, typename A2> class funct_wrap3
{
public:
funct_wrap3(T (&f_)(A0,A1,A2)):f(f_){}
T operator()(A0 a0, A1 a1, A2 a2) const { return f(a0,a1,a2); }
private:
T (&f)(A0,A1,A2);
};
template <typename T, typename A0, typename A1, typename A2, typename A3> class funct_wrap4
{
public:
funct_wrap4(T (&f_)(A0,A1,A2,A3)):f(f_){}
T operator()(A0 a0, A1 a1, A2 a2, A3 a3) const { return f(a0,a1,a2,a3); }
private:
T (&f)(A0,A1,A2,A3);
};
template <typename T, typename A0, typename A1, typename A2, typename A3, typename A4> class funct_wrap5
{
public:
funct_wrap5(T (&f_)(A0,A1,A2,A3,A4)):f(f_){}
T operator()(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) const { return f(a0,a1,a2,a3,a4); }
private:
T (&f)(A0,A1,A2,A3,A4);
};
/*!A wrap_function
This is a template that allows you to turn a global function into a
function object. The reason for this template's existance is so you can
do stuff like this:
template <typename T>
void call_funct(const T& funct)
{ cout << funct(); }
std::string test() { return "asdfasf"; }
int main()
{
call_funct(wrap_function(test));
}
The above code doesn't work right on some compilers if you don't
use wrap_function.
!*/
template <typename T>
funct_wrap0<T> wrap_function(T (&f)()) { return funct_wrap0<T>(f); }
template <typename T, typename A0>
funct_wrap1<T,A0> wrap_function(T (&f)(A0)) { return funct_wrap1<T,A0>(f); }
template <typename T, typename A0, typename A1>
funct_wrap2<T,A0,A1> wrap_function(T (&f)(A0, A1)) { return funct_wrap2<T,A0,A1>(f); }
template <typename T, typename A0, typename A1, typename A2>
funct_wrap3<T,A0,A1,A2> wrap_function(T (&f)(A0, A1, A2)) { return funct_wrap3<T,A0,A1,A2>(f); }
template <typename T, typename A0, typename A1, typename A2, typename A3>
funct_wrap4<T,A0,A1,A2,A3> wrap_function(T (&f)(A0, A1, A2, A3)) { return funct_wrap4<T,A0,A1,A2,A3>(f); }
template <typename T, typename A0, typename A1, typename A2, typename A3, typename A4>
funct_wrap5<T,A0,A1,A2,A3,A4> wrap_function(T (&f)(A0, A1, A2, A3, A4)) { return funct_wrap5<T,A0,A1,A2,A3,A4>(f); }
}
#endif // DLIB_ALGs_
|
[
"jimmy@DGJ3X3B1.(none)"
] |
[
[
[
1,
758
]
]
] |
1685bfe73242540a3027435452905849bbf479cc
|
45229380094a0c2b603616e7505cbdc4d89dfaee
|
/wavelets/facedetector_src/src/cvLib/annetwork.cpp
|
43432d12f372a1bc25f0a030970446a84d4a19c0
|
[] |
no_license
|
xcud/msrds
|
a71000cc096723272e5ada7229426dee5100406c
|
04764859c88f5c36a757dbffc105309a27cd9c4d
|
refs/heads/master
| 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,999 |
cpp
|
#include "stdafx.h"
#include "annetwork.h"
#include "annlayer.h"
#include "vec2d.h"
//////////////////////////////////////////////////constructor/destructor////////////////////////////////////////////////////////
ANNetwork::ANNetwork(const wchar_t* fname) : m_status(-1),
m_nrule(0.2f), m_alpha(0.7f),
m_input_vec(0), m_add_vec(0), m_mul_vec(0)
{
int res = 0;
unsigned int neurons_num = 0;
float w = 0.0f;
unsigned int layers_num = 0;
FILE* fp = _wfopen(fname, L"rt");
if (fp != 0) {
//get num of layers////////////////////////////////////
if ((res = fwscanf(fp, L"%d", &layers_num)) != 1) {
fclose(fp);
m_status = -1;
return;
}
m_neurons.resize(layers_num);
//get num of Neurons per layer/////////////////////////
for (unsigned int l = 0; l < layers_num; l++) {
if ((res = fwscanf(fp, L"%d", &neurons_num)) != 1) {
fclose(fp);
m_status = -2;
return;
} else
m_neurons[l] = neurons_num;
}
for (unsigned int l = 0; l < layers_num - 1; l++)
m_layers.push_back(new AnnLayer(m_neurons[l] + 1, m_neurons[l+1]));
//activation function for hidden/output layers/////////////////////
if ((res = fwscanf(fp, L"%d %d", &m_actfun[0], &m_actfun[1])) != 2) {
m_actfun[0] = AnnLayer::LINEAR;
m_actfun[1] = AnnLayer::SIGMOID;
}
//normalization params////////////////////////////////////////////
m_add_vec = new vec2D(1, m_neurons[0]);
m_mul_vec = new vec2D(1, m_neurons[0]);
m_input_vec = new vec2D(1, m_neurons[0]);
for (unsigned int n = 0; n < m_neurons[0]; n++) {
float add, mul;
if ((res = fwscanf(fp, L"%f %f", &add, &mul)) != 2) { //blank network file?
for (unsigned int m = 0; m < m_neurons[0]; m++) {
(*m_add_vec)[m] = 0.0f; //default add = 0
(*m_mul_vec)[m] = 1.0f; //default mult = 1
}
break;
}
(*m_add_vec)[n] = add;
(*m_mul_vec)[n] = mul;
}
//load weights/////////////////////////////////////////////////////
for (unsigned int l = 0; l < m_layers.size(); l++) { //load all weights except input layer
vec2D& tW = *m_layers[l]->m_tW;
for (unsigned int n = 0; n < tW.height(); n++) { //num of Neurons in layer
for (unsigned int i = 0; i < tW.width(); i++) { //num of inputs in Neuron
if ((res = fwscanf(fp, L"%f", &w)) != 1) { //blank network file?
fclose(fp);
m_status = 1;
init_weights((unsigned int)time(0)); //init to random values
return;
} else {
tW(n, i) = w;
}
}
}
}
fclose(fp);
m_status = 0;
} else
m_status = -1;
}
ANNetwork::~ANNetwork()
{
if (m_input_vec)
delete m_input_vec;
if (m_add_vec)
delete m_add_vec;
if (m_mul_vec)
delete m_mul_vec;
for (unsigned int l = 0; l < m_layers.size(); l++) //delete layers
delete m_layers[l];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////init neuron weights///////////////////////////////////////////////////////
void ANNetwork::init_weights(unsigned int rseed) const
{
int w;
srand(rseed);
//input layer remains with w=1.0
for (unsigned int l = 0; l < m_layers.size(); l++) {
vec2D& tW = *m_layers[l]->m_tW;
for (unsigned int n = 0; n < tW.height(); n++) {
for (unsigned int i = 0; i < tW.width(); i++) {
w = 0xFFF & rand();
w -= 0x800;
tW(n, i) = (float)w / 2048.0f;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////run network////////////////////////////////////////////////////////////////
void ANNetwork::classify(const float* ivec, float* ovec) const
{
//normalize input Xout = (Xin + add) * mul
*m_input_vec = ivec;
m_input_vec->add(*m_input_vec, *m_add_vec); //input = input .+ add
m_input_vec->mule(*m_input_vec, *m_mul_vec); //input = input .* mul
m_layers[0]->set_input(*m_input_vec, m_actfun[0]); //copy m_input_vec to layer[0]->inputs[1:size-1], 0-bias
//m_layers[0]->get_input().print();
//hidden layers
for (unsigned int l = 0; l < m_layers.size(); l++) {
AnnLayer* pnext = 0;
if (l + 1 < m_layers.size())
pnext = m_layers[l+1];
m_layers[l]->run(m_actfun[1], pnext);
}
//output layer
m_layers[m_layers.size()-1]->get_output(ovec, m_actfun[1]);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ANNetwork::saveWs(bool file) const
{
FILE* fp;
wchar_t fname[256] = L"";
for (unsigned int i = 0; i < m_layers.size(); i++) {
swprintf(fname, L"W%d.txt", i + 1);
if (file && (fp = _wfopen(fname, L"wt"))) {
const vec2D &tW = *m_layers[i]->m_tW;
for (unsigned int x = 0; x < tW.width(); x++) {
for (unsigned int y = 0; y < tW.height(); y++)
fwprintf(fp, L" %f", tW(y, x));
fwprintf(fp, L"\n");
}
fclose(fp);
} else {
const vec2D& tW = *m_layers[i]->m_tW;
wprintf(L"W%d %dx%d\n", i + 1, tW.width(), tW.height());
for (unsigned int x = 0; x < tW.width(); x++) {
for (unsigned int y = 0; y < tW.height(); y++)
wprintf(L" %8.4f", tW(y, x));
wprintf(L"\n");
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
[
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] |
[
[
[
1,
184
]
]
] |
4db122e2ad070824af2c54764ca689c7518216b4
|
ce262ae496ab3eeebfcbb337da86d34eb689c07b
|
/SETools/SEToolsCommon/SECollada/SEColladaScene.cpp
|
54381e96567fb33f972d157fc075b76675a877e8
|
[] |
no_license
|
pizibing/swingengine
|
d8d9208c00ec2944817e1aab51287a3c38103bea
|
e7109d7b3e28c4421c173712eaf872771550669e
|
refs/heads/master
| 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 20,091 |
cpp
|
// Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEToolsCommonPCH.h"
#include "SEColladaScene.h"
using namespace Swing;
SEColladaScene::OrientationMode SEColladaScene::ms_eOrientationMode =
SEColladaScene::OM_UNKNOWN;
//----------------------------------------------------------------------------
SEColladaScene::SEColladaScene(SEImageConverter* pImageConverter)
{
SE_ASSERT( pImageConverter );
m_pDAE = SE_NEW DAE;
m_pImageConverter = pImageConverter;
EnableKeyFrameController = true;
EnableJointMesh = false;
EnableTCoord = true;
EnableControllers = true;
}
//----------------------------------------------------------------------------
SEColladaScene::~SEColladaScene()
{
SE_DELETE m_pDAE;
}
//----------------------------------------------------------------------------
bool SEColladaScene::Load(const char* acFilename)
{
// Clean the scene out of date.
CleanUp();
m_pDAE->clear();
ToolSystem::DebugOutput("COLLADA DOM loading process started" );
// Load a .dae file from disk, and set up DAE runtime automatically.
daeInt iRes = m_pDAE->load(acFilename);
if( iRes != DAE_OK )
{
ToolSystem::DebugOutput("The COLLADA file %s is illegal",
acFilename);
return false;
}
// Get the DOM interface for later use.
domCOLLADA* pDom = m_pDAE->getDom(acFilename);
// Do triangulation work unconditionally at the very beginning.
ToolSystem::DebugOutput("Begin conditioning of triangulation");
Triangulate(m_pDAE);
ToolSystem::DebugOutput("Finish conditioning of triangulation");
// Get current coordinate frame orientation.
// The default is positive Y-axis.
ms_eOrientationMode = OM_Y_UP;
if( pDom->getAsset()->getUp_axis() )
{
domAsset::domUp_axis* pUp = pDom->getAsset()->getUp_axis();
switch( pUp->getValue() )
{
case UPAXISTYPE_X_UP:
ToolSystem::DebugOutput("Right-handed system with X upward");
ms_eOrientationMode = OM_X_UP;
break;
case UPAXISTYPE_Y_UP:
ToolSystem::DebugOutput("Right-handed system with Y upward");
ms_eOrientationMode = OM_Y_UP;
break;
case UPAXISTYPE_Z_UP:
ToolSystem::DebugOutput("Right-handed system with Z upward");
ms_eOrientationMode = OM_Z_UP;
break;
default:
break;
}
}
// Load all the image libraries.
int iImageLibCount = (int)pDom->getLibrary_images_array().getCount();
for( int i = 0; i < iImageLibCount; i++ )
{
LoadImageLibrary(pDom->getLibrary_images_array()[i]);
}
// Load all the effect libraries.
int iEffectLibCount = (int)pDom->getLibrary_effects_array().getCount();
for( int i = 0; i < iEffectLibCount; i++ )
{
LoadEffectLibrary(pDom->getLibrary_effects_array()[i]);
}
// Load all the material libraries.
int iMaterialLibCount =
(int)pDom->getLibrary_materials_array().getCount();
for( int i = 0; i < iMaterialLibCount; i++ )
{
LoadMaterialLibrary(pDom->getLibrary_materials_array()[i]);
}
// Load all the animation libraries.
int iAnimationLibCount =
(int)pDom->getLibrary_animations_array().getCount();
for( int i = 0; i < iAnimationLibCount; i++ )
{
LoadAnimationLibrary(pDom->getLibrary_animations_array()[i] );
}
// Swing Engine scene graph creation pass.
// Find the scene we want and load it.
domCOLLADA::domSceneRef spDomScene = pDom->getScene();
daeElement* pDefaultScene = 0;
if( spDomScene )
{
domInstanceWithExtraRef spInstanceVisualScene =
spDomScene->getInstance_visual_scene();
if( spInstanceVisualScene )
{
pDefaultScene = spInstanceVisualScene->getUrl().getElement();
}
}
if( pDefaultScene )
{
LoadScene((domVisual_scene*)pDefaultScene);
}
else
{
return false;
}
// Deferred processing of lights.
ProcessLights();
// Deferred processing of cameras.
ProcessCameras();
// Deferred processing of controllers.
if( EnableControllers )
{
ProcessControllers();
}
return true;
}
//----------------------------------------------------------------------------
SENode* SEColladaScene::GetScene()
{
return m_spSceneRoot;
}
//----------------------------------------------------------------------------
unsigned int SEColladaScene::GetMaxOffset(
domInputLocalOffset_Array& rInputArray)
{
unsigned int uiMaxOffset = 0;
for( int i = 0; i < (int)rInputArray.getCount(); i++ )
{
if( rInputArray[i]->getOffset() > uiMaxOffset )
{
uiMaxOffset = (unsigned int)rInputArray[i]->getOffset();
}
}
return uiMaxOffset;
}
//----------------------------------------------------------------------------
void SEColladaScene::CreateTrianglesFromPolylist(domMesh* pDomMesh,
domPolylist* pDomPolylist)
{
// Create a new <triangles> inside the mesh that has the same material
// as the <polylist>.
domTriangles* pDomTriangles = (domTriangles*)pDomMesh->createAndPlace(
"triangles");
pDomTriangles->setMaterial(pDomPolylist->getMaterial());
domP* pDomTrianglesP = (domP*)pDomTriangles->createAndPlace("p");
// Give the new <triangles> the same <_dae> and <parameters> as the old
// <polylist>.
for( int i = 0; i < (int)(pDomPolylist->getInput_array().getCount()); i++ )
{
pDomTriangles->placeElement(
pDomPolylist->getInput_array()[i]->clone());
}
// Get the number of inputs and primitives for the polygons array.
int iInputCount = (int)GetMaxOffset(pDomPolylist->getInput_array()) + 1;
int iPrimitiveCount = (int)(pDomPolylist->getVcount()->getValue(
).getCount());
unsigned int uiOffset = 0;
unsigned int uiTrianglesProcessed = 0;
// Triangulate all the primitives, this generates all the triangles in a
// single <p> element.
for( int j = 0; j < iPrimitiveCount; j++ )
{
int iTriangleCount = (int)pDomPolylist->getVcount()->getValue()[j] - 2;
// Write out the primitives as triangles, just fan using the first
// element as the base.
int iIndex = iInputCount;
for( int k = 0; k < iTriangleCount; k++ )
{
// First vertex.
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomPolylist->getP()->getValue()[uiOffset + l]);
}
// Second vertex.
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomPolylist->getP()->getValue()[uiOffset + iIndex + l]);
}
// Third vertex.
iIndex += iInputCount;
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomPolylist->getP()->getValue()[uiOffset + iIndex + l]);
}
uiTrianglesProcessed++;
}
uiOffset += (unsigned int)pDomPolylist->getVcount()->getValue()[j] *
iInputCount;
}
pDomTriangles->setCount(uiTrianglesProcessed);
}
//----------------------------------------------------------------------------
void SEColladaScene::CreateTrianglesFromPolygons(domMesh* pDomMesh,
domPolygons* pDomPolygons)
{
// Create a new <triangles> inside the mesh that has the same material as
// the <polygons>.
domTriangles *pDomTriangles = (domTriangles*)pDomMesh->createAndPlace(
"triangles");
pDomTriangles->setCount(0);
pDomTriangles->setMaterial(pDomPolygons->getMaterial());
domP* pDomTrianglesP = (domP*)pDomTriangles->createAndPlace("p");
// Give the new <triangles> the same <_dae> and <parameters> as the old
// <polygons>.
for( int i = 0; i < (int)(pDomPolygons->getInput_array().getCount()); i++ )
{
pDomTriangles->placeElement(
pDomPolygons->getInput_array()[i]->clone());
}
// Get the number of inputs and primitives for the polygons array.
int iInputCount = (int)GetMaxOffset(pDomPolygons->getInput_array()) + 1;
int iPrimitiveCount = (int)(pDomPolygons->getP_array().getCount());
// Triangulate all the primitives, this generates all the triangles in a
// single <p> element.
for( int j = 0; j < iPrimitiveCount; j++ )
{
// Check the polygons for consistancy (some exported files have had
// the wrong number of indices).
domP* pDomCurrentP = pDomPolygons->getP_array()[j];
int iElementCount = (int)(pDomCurrentP->getValue().getCount());
if( (iElementCount%iInputCount) != 0 )
{
}
else
{
int iTriangleCount = (iElementCount/iInputCount) - 2;
// Write out the primitives as triangles, just fan using the first
// element as the base.
int iIndex = iInputCount;
for( int k = 0; k < iTriangleCount; k++ )
{
// First vertex.
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomCurrentP->getValue()[l]);
}
// Second vertex.
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomCurrentP->getValue()[iIndex + l]);
}
// Third vertex.
iIndex += iInputCount;
for( int l = 0; l < iInputCount; l++ )
{
pDomTrianglesP->getValue().append(
pDomCurrentP->getValue()[iIndex + l]);
}
pDomTriangles->setCount(pDomTriangles->getCount() + 1);
}
}
}
}
//----------------------------------------------------------------------------
void SEColladaScene::Triangulate(DAE* pDAE)
{
SE_ASSERT( pDAE );
daeDatabase* pDataBase = pDAE->getDatabase();
SE_ASSERT( pDataBase );
int iGeometryCount = (int)(pDataBase->getElementCount(0, "geometry"));
for( int i = 0; i < iGeometryCount; i++ )
{
// Find the next geometry element.
domGeometry* pDomGeometry;
pDataBase->getElement((daeElement**)&pDomGeometry, i, 0, "geometry");
// Get the mesh out of the geometry.
domMesh* pDomMesh = pDomGeometry->getMesh();
if( !pDomMesh )
continue;
// Loop over all the polygons elements.
int iPolygonsCount = (int)(pDomMesh->getPolygons_array().getCount());
for( int j = 0; j < iPolygonsCount; j++ )
{
// Get the polygons out of the mesh.
domPolygons* pDomPolygons = pDomMesh->getPolygons_array()[j];
CreateTrianglesFromPolygons(pDomMesh, pDomPolygons);
}
while( pDomMesh->getPolygons_array().getCount() > 0 )
{
domPolygons* pDomPolygons = pDomMesh->getPolygons_array().get(0);
// Remove the polygons from the mesh.
pDomMesh->removeChildElement(pDomPolygons);
}
// Loop over all the polylist elements.
int iPolylistCount = (int)(pDomMesh->getPolylist_array().getCount());
for( int j = 0; j < iPolylistCount; j++)
{
// Get the polylist out of the mesh.
domPolylist* pDomPolylist = pDomMesh->getPolylist_array()[j];
CreateTrianglesFromPolylist(pDomMesh, pDomPolylist);
}
while( pDomMesh->getPolylist_array().getCount() > 0 )
{
domPolylist* pDomPolylist = pDomMesh->getPolylist_array().get(0);
// Remove the polylist from the mesh.
pDomMesh->removeChildElement(pDomPolylist);
}
}
}
//----------------------------------------------------------------------------
SEVector3f SEColladaScene::GetTransformedVector(float fX, float fY, float fZ)
{
SEVector3f vec3fRes;
// COLLADA uses right-handed based system, now we only have these three
// situations to deal with. The result vector is a left-handed based
// Swing Engine vector.
switch( ms_eOrientationMode )
{
case OM_Y_UP:
vec3fRes.X = fX;
vec3fRes.Y = fY;
vec3fRes.Z = -fZ;
break;
case OM_Z_UP:
vec3fRes.X = fX;
vec3fRes.Y = fZ;
vec3fRes.Z = fY;
break;
case OM_X_UP:
vec3fRes.X = -fY;
vec3fRes.Y = fX;
vec3fRes.Z = -fZ;
break;
default:
SE_ASSERT( false );
}
return vec3fRes;
}
//----------------------------------------------------------------------------
void SEColladaScene::GetInverseBindingTransformation(SETransformation&
rDstTransformation, domListOfFloats* pSrcMatrix, int iSrcBase)
{
// Given a COLLADA homogeneous inverse binding matrix M:
// m00 m01 m02 t0
// m10 m11 m12 t1
// m20 m21 m22 t2
// 0 0 0 1
// in column major order.
//
// Given a Swing Engine homogeneous vector V:
// x
// y
// z
// w
// in column major order.
//
// We should construct a homogeneous matrix that could finish the
// following operations:
// (1) Transform V back to the original DCC right-handed system,
// say, V0, by using a homogeneous matrix M0:
//
// Y_UP: Z_UP: X_UP:
// 1 0 0 0 1 0 0 0 0 1 0 0
// 0 1 0 0 0 0 1 0 -1 0 0 0
// 0 0 -1 0 0 1 0 0 0 0 -1 0
// 0 0 0 1 0 0 0 1 0 0 0 1
// in column major order.
//
// (2) Transform V0 into the COLLADA binding joint's local right-
// handed system, say, V1, by using M.
//
// (3) Transform V1 back to the Swing Engine binding joint's local
// left-handed system, say, V2, by using a homogeneous matrix M1:
//
// Y_UP: Z_UP: X_UP:
// 1 0 0 0 1 0 0 0 0 -1 0 0
// 0 1 0 0 0 0 1 0 1 0 0 0
// 0 0 -1 0 0 1 0 0 0 0 -1 0
// 0 0 0 1 0 0 0 1 0 0 0 1
// in column major order.
//
// The final combination of these three operations will be:
// V2 = M1*M*M0*V.
// So M1*M*M0 is the matrix we want:
//
// Y_UP: Z_UP: X_UP:
// m00 m01 -m02 t0 m00 m02 m01 t0 m11 -m10 m12 -t1
// m10 m11 -m12 t1 m20 m22 m21 t2 -m01 m00 -m02 t0
// -m20 -m21 m22 -t2 m10 m12 m11 t1 m21 -m20 m22 -t2
// 0 0 0 1 0 0 0 1 0 0 0 1
// in column major order.
float fM00, fM01, fM02, fM10, fM11, fM12, fM20, fM21, fM22;
float fT0, fT1, fT2;
fM00 = (float)(*pSrcMatrix)[iSrcBase ];
fM01 = (float)(*pSrcMatrix)[iSrcBase + 1];
fM02 = (float)(*pSrcMatrix)[iSrcBase + 2];
fM10 = (float)(*pSrcMatrix)[iSrcBase + 4];
fM11 = (float)(*pSrcMatrix)[iSrcBase + 5];
fM12 = (float)(*pSrcMatrix)[iSrcBase + 6];
fM20 = (float)(*pSrcMatrix)[iSrcBase + 8];
fM21 = (float)(*pSrcMatrix)[iSrcBase + 9];
fM22 = (float)(*pSrcMatrix)[iSrcBase + 10];
fT0 = (float)(*pSrcMatrix)[iSrcBase + 3];
fT1 = (float)(*pSrcMatrix)[iSrcBase + 7];
fT2 = (float)(*pSrcMatrix)[iSrcBase + 11];
// MT form is enough for our usage.
switch( ms_eOrientationMode )
{
case OM_Y_UP:
{
SEVector3f vec3fRow0(fM00, fM01, -fM02);
SEVector3f vec3fRow1(fM10, fM11, -fM12);
SEVector3f vec3fRow2(-fM20, -fM21, fM22);
SEMatrix3f mat3fM(vec3fRow0, vec3fRow1, vec3fRow2, false);
SEVector3f vec3fT(fT0, fT1, -fT2);
rDstTransformation.SetMatrix(mat3fM);
rDstTransformation.SetTranslate(vec3fT);
}
break;
case OM_Z_UP:
{
SEVector3f vec3fRow0(fM00, fM02, fM01);
SEVector3f vec3fRow1(fM20, fM22, fM21);
SEVector3f vec3fRow2(fM10, fM12, fM11);
SEMatrix3f mat3fM(vec3fRow0, vec3fRow1, vec3fRow2, false);
SEVector3f vec3fT(fT0, fT2, fT1);
rDstTransformation.SetMatrix(mat3fM);
rDstTransformation.SetTranslate(vec3fT);
}
break;
case OM_X_UP:
{
SEVector3f vec3fRow0(fM11, -fM10, fM12);
SEVector3f vec3fRow1(-fM01, fM00, -fM02);
SEVector3f vec3fRow2(fM21, -fM20, fM22);
SEMatrix3f mat3fM(vec3fRow0, vec3fRow1, vec3fRow2, false);
SEVector3f vec3fT(-fT1, fT0, -fT2);
rDstTransformation.SetMatrix(mat3fM);
rDstTransformation.SetTranslate(vec3fT);
}
break;
default:
SE_ASSERT( false );
break;
}
}
//----------------------------------------------------------------------------
bool SEColladaScene::LoadScene(domVisual_sceneRef spDomVisualScene)
{
// Create Swing Engine scene graph's root.
// Save the scene name instead of scene id.
m_spSceneRoot = SE_NEW SENode;
xsNCName strSceneName = spDomVisualScene->getName();
m_spSceneRoot->SetName(strSceneName);
ToolSystem::DebugOutput("SEColladaScene::Loading Collada Scene %s",
(const char*)strSceneName);
// Recurse through the scene, load and add nodes.
domNode_Array& rDomNodeArray = spDomVisualScene->getNode_array();
int iTopLevelNodeCount = (int)rDomNodeArray.getCount();
for( int i = 0; i < iTopLevelNodeCount; i++ )
{
SENode* pNode = LoadNode(rDomNodeArray[i], m_spSceneRoot);
if( pNode )
{
const char* acNodeName = pNode->GetName().c_str();
m_Nodes[acNodeName] = pNode;
}
}
// Finally add the scene root node.
m_Nodes[strSceneName] = m_spSceneRoot;
// Update Swing Engine scene graph.
m_spSceneRoot->UpdateRS();
m_spSceneRoot->UpdateGS();
return true;
}
//----------------------------------------------------------------------------
void SEColladaScene::CleanUp()
{
m_spSceneRoot = 0;
m_Images.clear();
m_Effects.clear();
m_Materials.clear();
m_InstanceMaterials.clear();
m_InstanceLights.clear();
m_InstanceCameras.clear();
m_Animations.clear();
m_Nodes.clear();
m_Geometries.clear();
m_Lights.clear();
m_Cameras.clear();
m_InstanceControllers.clear();
m_Bones.clear();
}
//----------------------------------------------------------------------------
|
[
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] |
[
[
[
1,
575
]
]
] |
78a9ad2b49765223a4345846c25dcedca6435979
|
20c74d83255427dd548def97f9a42112c1b9249a
|
/src/libsrc/game/control-class.h
|
0b10c93a06310caecb7967e7b8d8ea647155e121
|
[] |
no_license
|
jonyzp/roadfighter
|
70f5c7ff6b633243c4ac73085685595189617650
|
d02cbcdcfda1555df836379487953ae6206c0703
|
refs/heads/master
| 2016-08-10T15:39:09.671015 | 2011-05-05T12:00:34 | 2011-05-05T12:00:34 | 54,320,171 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 601 |
h
|
#ifndef CONTROL_CLASS_H
#define CONTROL_CLASS_H
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code)&0x8000)?1:0)
#define KEY_UP(vk_code) ((GetAsyncKeyState(vk_code)&0x8000)?0:1)
enum keyCodes
{
KEY_A,KEY_B,KEY_C,KEY_D,KEY_E,KEY_F,KEY_G,KEY_H,KEY_I,KEY_J,KEY_K,KEY_L,KEY_M,
KEY_N,KEY_O,KEY_P,KEY_Q,KEY_R,KEY_S,KEY_T,KEY_U,KEY_V,KEY_W,KEY_X,KEY_Y,KEY_Z,
KEY_SPACEBAR,KEY_ESCAPE,KEY_ENTER
);
class EXPORT Control
{
public:
void up() = 0;
void down() = 0;
void left() = 0;
void right() = 0;
void button1() = 0;
void button2() = 0;
void startButton() = 0;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
25
]
]
] |
062281c8e06a3ea255d323028990dd4f7c1c24ec
|
ba200ae9f30b89d1e32aee6a6e5ef2c991cee157
|
/trunk/GosuImpl/Graphics/TextTTFWin.cpp
|
fe26a0963abe61bca1e61d535d317825caa035cb
|
[
"MIT"
] |
permissive
|
clebertavares/gosu
|
1d5fd08d22825d18f2840dfe1c53c96f700b665f
|
e534e0454648a4ef16c7934d3b59b80ac9ec7a44
|
refs/heads/master
| 2020-04-08T15:36:38.697104 | 2010-02-20T16:57:25 | 2010-02-20T16:57:25 | 537,484 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,679 |
cpp
|
#include <windows.h>
#include <Gosu/Utility.hpp>
// Adapted from http://www.codeproject.com/KB/GDI/xfont.aspx.
// Credits go to Philip Patrick and Hans Dietrich!
struct FONT_PROPERTIES_ANSI
{
char csName[1024];
char csCopyright[1024];
char csTrademark[1024];
char csFamily[1024];
};
struct TT_OFFSET_TABLE
{
USHORT uMajorVersion;
USHORT uMinorVersion;
USHORT uNumOfTables;
USHORT uSearchRange;
USHORT uEntrySelector;
USHORT uRangeShift;
};
struct TT_TABLE_DIRECTORY
{
char szTag[4]; //table name
ULONG uCheckSum; //Check sum
ULONG uOffset; //Offset from beginning of file
ULONG uLength; //length of the table in bytes
};
struct TT_NAME_TABLE_HEADER
{
USHORT uFSelector; //format selector. Always 0
USHORT uNRCount; //Name Records count
USHORT uStorageOffset; //Offset for strings storage, from start of the table
};
struct TT_NAME_RECORD
{
USHORT uPlatformID;
USHORT uEncodingID;
USHORT uLanguageID;
USHORT uNameID;
USHORT uStringLength;
USHORT uStringOffset; //from start of storage area
};
#define SWAPWORD(x) MAKEWORD(HIBYTE(x), LOBYTE(x))
#define SWAPLONG(x) MAKELONG(SWAPWORD(HIWORD(x)), SWAPWORD(LOWORD(x)))
#define _T(x) x
#define TRACE printf
namespace Gosu
{
std::wstring getNameFromTTFFile(const std::wstring& filename)
{
FONT_PROPERTIES_ANSI fp;
FONT_PROPERTIES_ANSI * lpFontProps = &fp;
memset(lpFontProps, 0, sizeof(FONT_PROPERTIES_ANSI));
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = ::CreateFile(filename.c_str(),
GENERIC_READ,// | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
TRACE(_T("ERROR: failed to open '%s'\n"), Gosu::narrow(filename).c_str());
TRACE(_T("ERROR: %s failed\n"), _T("CreateFile"));
return filename;
}
// get the file size
DWORD dwFileSize = ::GetFileSize(hFile, NULL);
if (dwFileSize == INVALID_FILE_SIZE)
{
TRACE(_T("ERROR: %s failed\n"), _T("GetFileSize"));
::CloseHandle(hFile);
return filename;
}
//TRACE(_T("dwFileSize = %d\n"), dwFileSize);
// Create a file mapping object that is the current size of the file
HANDLE hMappedFile = NULL;
hMappedFile = ::CreateFileMapping(hFile,
NULL,
PAGE_READONLY, //PAGE_READWRITE,
0,
dwFileSize,
NULL);
if (hMappedFile == NULL)
{
TRACE(_T("ERROR: %s failed\n"), _T("CreateFileMapping"));
::CloseHandle(hFile);
return filename;
}
LPBYTE lpMapAddress = (LPBYTE) ::MapViewOfFile(hMappedFile, // handle to file-mapping object
FILE_MAP_READ,//FILE_MAP_WRITE, // access mode
0, // high-order DWORD of offset
0, // low-order DWORD of offset
0); // number of bytes to map
if (lpMapAddress == NULL)
{
TRACE(_T("ERROR: %s failed\n"), _T("MapViewOfFile"));
::CloseHandle(hMappedFile);
::CloseHandle(hFile);
return filename;
}
BOOL bRetVal = FALSE;
int index = 0;
TT_OFFSET_TABLE ttOffsetTable;
memcpy(&ttOffsetTable, &lpMapAddress[index], sizeof(TT_OFFSET_TABLE));
index += sizeof(TT_OFFSET_TABLE);
ttOffsetTable.uNumOfTables = SWAPWORD(ttOffsetTable.uNumOfTables);
ttOffsetTable.uMajorVersion = SWAPWORD(ttOffsetTable.uMajorVersion);
ttOffsetTable.uMinorVersion = SWAPWORD(ttOffsetTable.uMinorVersion);
//check is this is a true type font and the version is 1.0
if (ttOffsetTable.uMajorVersion != 1 || ttOffsetTable.uMinorVersion != 0)
return L"";
TT_TABLE_DIRECTORY tblDir;
memset(&tblDir, 0, sizeof(TT_TABLE_DIRECTORY));
BOOL bFound = FALSE;
char szTemp[4096];
memset(szTemp, 0, sizeof(szTemp));
for (int i = 0; i< ttOffsetTable.uNumOfTables; i++)
{
//f.Read(&tblDir, sizeof(TT_TABLE_DIRECTORY));
memcpy(&tblDir, &lpMapAddress[index], sizeof(TT_TABLE_DIRECTORY));
index += sizeof(TT_TABLE_DIRECTORY);
strncpy(szTemp, tblDir.szTag, 4);
if (stricmp(szTemp, "name") == 0)
{
bFound = TRUE;
tblDir.uLength = SWAPLONG(tblDir.uLength);
tblDir.uOffset = SWAPLONG(tblDir.uOffset);
break;
}
else if (szTemp[0] == 0)
{
break;
}
}
if (bFound)
{
index = tblDir.uOffset;
TT_NAME_TABLE_HEADER ttNTHeader;
memcpy(&ttNTHeader, &lpMapAddress[index], sizeof(TT_NAME_TABLE_HEADER));
index += sizeof(TT_NAME_TABLE_HEADER);
ttNTHeader.uNRCount = SWAPWORD(ttNTHeader.uNRCount);
ttNTHeader.uStorageOffset = SWAPWORD(ttNTHeader.uStorageOffset);
TT_NAME_RECORD ttRecord;
bFound = FALSE;
for (int i = 0;
i < ttNTHeader.uNRCount &&
(lpFontProps->csCopyright[0] == 0 ||
lpFontProps->csName[0] == 0 ||
lpFontProps->csTrademark[0] == 0 ||
lpFontProps->csFamily[0] == 0);
i++)
{
memcpy(&ttRecord, &lpMapAddress[index], sizeof(TT_NAME_RECORD));
index += sizeof(TT_NAME_RECORD);
ttRecord.uNameID = SWAPWORD(ttRecord.uNameID);
ttRecord.uStringLength = SWAPWORD(ttRecord.uStringLength);
ttRecord.uStringOffset = SWAPWORD(ttRecord.uStringOffset);
if (ttRecord.uNameID == 1 || ttRecord.uNameID == 0 || ttRecord.uNameID == 7)
{
int nPos = index; //f.GetPosition();
index = tblDir.uOffset + ttRecord.uStringOffset + ttNTHeader.uStorageOffset;
memset(szTemp, 0, sizeof(szTemp));
memcpy(szTemp, &lpMapAddress[index], ttRecord.uStringLength);
index += ttRecord.uStringLength;
if (szTemp[0] != 0)
{
_ASSERTE(strlen(szTemp) < sizeof(lpFontProps->csName));
switch (ttRecord.uNameID)
{
case 0:
if (lpFontProps->csCopyright[0] == 0)
strncpy(lpFontProps->csCopyright, szTemp,
sizeof(lpFontProps->csCopyright)-1);
break;
case 1:
if (lpFontProps->csFamily[0] == 0)
strncpy(lpFontProps->csFamily, szTemp,
sizeof(lpFontProps->csFamily)-1);
bRetVal = TRUE;
break;
case 4:
if (lpFontProps->csName[0] == 0)
strncpy(lpFontProps->csName, szTemp,
sizeof(lpFontProps->csName)-1);
break;
case 7:
if (lpFontProps->csTrademark[0] == 0)
strncpy(lpFontProps->csTrademark, szTemp,
sizeof(lpFontProps->csTrademark)-1);
break;
default:
break;
}
}
index = nPos;
}
}
}
::UnmapViewOfFile(lpMapAddress);
::CloseHandle(hMappedFile);
::CloseHandle(hFile);
if (lpFontProps->csName[0] == 0)
strcpy(lpFontProps->csName, lpFontProps->csFamily);
return Gosu::widen(lpFontProps->csName);
}
}
|
[
"[email protected]"
] |
[
[
[
1,
247
]
]
] |
530a85a5365b817186ccd09139d4375328f609b9
|
de2f72b217bc8a9b1f780090bedf425a2ad9587a
|
/Pangea/Graphics/src/MainWindow.cpp
|
4b4055bb8a552b51f5124906c411fed1aa36473c
|
[] |
no_license
|
axelwass/oliveira
|
65b32a7f16cb7e00a95cdf3051a731a2004aaf5f
|
4c34730a720465311e367f8e25cc1cced46801c7
|
refs/heads/master
| 2021-01-18T14:18:42.622080 | 2011-04-18T18:39:08 | 2011-04-18T18:39:08 | 32,120,045 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,032 |
cpp
|
/*
* MainWindow.cpp
*
* Created on: Oct 19, 2009
* Author: Mariano
*/
#include "../include/MainWindow.h"
#include <GL/gl.h>
#include <SDL/SDL_ttf.h>
MainWindow * MainWindow::instance = NULL;
/* Updates screen and also pops events */
int MainWindow::Refresh(int delay) {
real passedTime = SDL_GetTicks() - time;
fps = 1000.0 / passedTime;
time = SDL_GetTicks();
/* Update screen */
glFinish();
SDL_GL_SwapBuffers();
// Set background color
glClearColor(35 / 255.0f, 35 / 255.0f, 50 / 255.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Set 2D view
glViewport(0, 0, width, height);
return running;
}
MainWindow::MainWindow(int width, int height) {
this->width = width;
this->height = height;
this->running = true;
SDL_Init(SDL_INIT_EVERYTHING);
TTF_Init();
SDL_EnableUNICODE(1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
screen = SDL_SetVideoMode(width, height, 32, SDL_OPENGL);
SDL_WM_SetCaption("Engine", NULL);
// Enable blending
glEnable(GL_BLEND | GL_ALPHA_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//Enable textures
glEnable(GL_TEXTURE_2D);
// Enable two sided lighing
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
time = SDL_GetTicks();
}
void MainWindow::End() {
SDL_FreeSurface(screen);
SDL_Quit();
}
int MainWindow::getWidth() {
return width;
}
int MainWindow::getHeight() {
return height;
}
real MainWindow::getFPS() {
return fps;
}
void MainWindow::onKeyUp(int key) {
}
void MainWindow::onKeyDown(int key) {
if (key == 27) {
this->End();
running = false;
}
}
MainWindow::~MainWindow() {
}
|
[
"merchante.mariano@d457d4b0-f835-b411-19da-99c4f284aa10"
] |
[
[
[
1,
104
]
]
] |
aa2e6196e5caec63e87d21aefad4e4864e603215
|
bef7d0477a5cac485b4b3921a718394d5c2cf700
|
/dingus/dingus/math/MathUtils.h
|
3fbbd25a765c0b2f3d00f2220671c266f0e3bb05
|
[
"MIT"
] |
permissive
|
TomLeeLive/aras-p-dingus
|
ed91127790a604e0813cd4704acba742d3485400
|
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
|
refs/heads/master
| 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,292 |
h
|
// --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#ifndef __MATH_UTILS_H
#define __MATH_UTILS_H
#include "FPU.h"
namespace dingus {
/**
* Clamps value to the given range.
*/
inline float clamp( float value, float vmin = 0.0f, float vmax = 1.0f ) {
assert( vmin <= vmax );
if( value < vmin )
value = vmin;
else if( value > vmax )
value = vmax;
return value;
};
/**
* Smoothing function.
*
* Uses critically damped spring for ease-in/ease-out smoothing. Stable
* at any time intervals. Based on GPG4 article.
*
* @param from Current value.
* @param to Target value (may be moving).
* @param vel Velocity (updated by the function, should be maintained between calls).
* @param smoothTime Time in which the target should be reached, if travelling at max. speed.
* @param dt Delta time.
* @return Updated value.
*/
template< typename T >
inline T smoothCD( const T& from, const T& to, T& vel, float smoothTime, float dt )
{
float omega = 2.0f / smoothTime;
float x = omega * dt;
// approximate exp()
float exp = 1.0f / (1.0f + x + 0.48f*x*x + 0.235f*x*x*x );
T change = from - to;
T temp = ( vel + omega * change ) * dt;
vel = ( vel - omega * temp ) * exp;
return to + ( change + temp ) * exp;
}
template< typename T >
class CTabularFunction {
public:
CTabularFunction( int nvals, const T* vals )
: mValueCount(nvals)
, mValueCountMinusOne(nvals-1)
{
assert( vals );
assert( nvals > 0 );
mValues = new T[ nvals ];
memcpy( mValues, vals, nvals*sizeof(T) );
}
~CTabularFunction()
{
delete[] mValues;
}
void eval( float t, T& val ) const {
float alpha = clamp( t, 0.0f, 1.0f ) * mValueCountMinusOne;
int idx0 = round( alpha - 0.5f );
assert( idx0 >= 0 && idx0 < mValueCount );
int idx1 = idx0 + 1;
if( idx1 >= mValueCount )
idx1 = mValueCount-1;
float lerp = alpha - idx0;
val = mValues[idx0] + (mValues[idx1]-mValues[idx0]) * lerp;
}
private:
int mValueCount;
T* mValues;
float mValueCountMinusOne;
};
}; // namespace
#endif
|
[
"[email protected]"
] |
[
[
[
1,
93
]
]
] |
017f7f724ceb85a7a1e67951c5f8d0b827299114
|
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
|
/Game/MenuView.cpp
|
83a2883a8bf75088a79309ef5b22a04d07dc90c6
|
[
"Apache-2.0"
] |
permissive
|
notpushkin/palm-heroes
|
d4523798c813b6d1f872be2c88282161cb9bee0b
|
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
|
refs/heads/master
| 2021-05-31T19:10:39.270939 | 2010-07-25T12:25:00 | 2010-07-25T12:25:00 | 62,046,865 | 2 | 1 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 7,249 |
cpp
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#include "stdafx.h"
#include "Credits.h"
#include "MenuView.h"
#include "Dlg_ScenList.h"
#include "Dlg_Save.h"
#include "Dlg_ScenProps.h"
#include "Dlg_HallOfFame.h"
/*
* Main dialog
*/
const iDib::pixel menuBtnText[15] = {
RGB16(210,190,115), RGB16(214,192,110), RGB16(216,192,102), RGB16(219,193,96), RGB16(221,193,85),
RGB16(224,194,76), RGB16(228,196,67), RGB16(231,195,59), RGB16(233,196,49), RGB16(236,196,40),
RGB16(239,198,31), RGB16(242,198,23), RGB16(224,198,16), RGB16(247,199,0), RGB16(248,200,0)
};
class iMainMenuDlg : public iDialog, public IViewCmdHandler
{
public:
class iMainMenuBtn : public iButton
{
public:
iMainMenuBtn(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect, TextResId textKey, uint32 uid, uint32 state = Visible|Enabled)\
: iButton(pViewMgr, pCmdHandler, rect, uid, state), m_TextKey(textKey)
{}
void OnBtnDown() const
{
//gSfxMgr.PlaySound(CSND_BUTTON);
}
void OnCompose()
{
gApp.Surface().Darken50Rect(GetScrRect());
// Compose outer frame
iRect rect = GetScrRect();
rect.InflateRect(1);
uint16 cColor_Grey = RGB16(32,32,32);
gApp.Surface().HLine(iPoint(rect.x+2, rect.y), rect.x+rect.w-3, cColor_Grey);
gApp.Surface().HLine(iPoint(rect.x+2, rect.y+rect.h-1), rect.x+rect.w-3, cColor_Grey);
gApp.Surface().VLine(iPoint(rect.x,rect.y+2), rect.y+rect.h-2, cColor_Grey);
gApp.Surface().VLine(iPoint(rect.x+rect.w-1,rect.y+2), rect.y+rect.h-2, cColor_Grey);
iDibFont::ComposeProps props = iDibFont::ComposeProps(iGradient(menuBtnText,15), cColor_Black, iDibFont::DecBorder);
uint32 state = GetButtonState();
if ( state & iButton::Disabled ) {
props = iDibFont::ComposeProps(RGB16(128,100,0), cColor_Black, iDibFont::DecBorder);
} else if ( state & iButton::Pressed ) {
props = iDibFont::ComposeProps(RGB16(255,255,255), cColor_Black, iDibFont::DecBorder);
gApp.Surface().Darken50Rect(GetScrRect());
}
iTextComposer::FontConfig fc(iTextComposer::FS_LARGE, props );
gTextComposer.TextOut(fc, gApp.Surface(), iPoint(), gTextMgr[m_TextKey], GetScrRect(), AlignCenter, (state&iButton::Pressed?iPoint(1,1):iPoint(0,0)) );
}
private:
TextResId m_TextKey;
};
public:
iMainMenuDlg(iViewMgr* pViewMgr) : iDialog(pViewMgr) {}
enum {
BTN_DIST = 5
};
private:
void OnCreateDlg()
{
iRect rc = GetDlgMetrics(); rc.h = DEF_BTN_HEIGHT+2;
bool registered = IS_REGISTERED();
AddChild(new iMainMenuBtn(m_pMgr, this, rc, TRID_MENU_NEWGAME, 100, Visible|Enabled)); rc.y+=DEF_BTN_HEIGHT+BTN_DIST;
AddChild(new iMainMenuBtn(m_pMgr, this, rc, TRID_MENU_LOADGAME, 101, (registered)?(Visible|Enabled):Visible)); rc.y+=DEF_BTN_HEIGHT+BTN_DIST;
AddChild(new iMainMenuBtn(m_pMgr, this, rc, TRID_MENU_HIGHSCORE, 102, Visible|Enabled)); rc.y+=DEF_BTN_HEIGHT+BTN_DIST;
AddChild(new iMainMenuBtn(m_pMgr, this, rc, TRID_MENU_CREDITS, 103, Visible|Enabled)); rc.y+=DEF_BTN_HEIGHT+BTN_DIST;
AddChild(new iMainMenuBtn(m_pMgr, this, rc, TRID_MENU_EXITGAME, 104, Visible|Enabled));
}
void OnPlace(iRect& rect)
{
rect.y += 40;
}
void OnCompose()
{
}
iSize GetDlgMetrics() const
{ return iSize(150,5*(DEF_BTN_HEIGHT+2) + 12); }
void iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param) { EndDialog(pView->GetUID()); }
};
/*
*
*/
iMenuView::iMenuView()
: iChildGameView(false, CV_UNDEFINED)
{
m_crComposer.Init();
}
// TODO:: move const somewhere away OR otherwise automate!
//#define BLOOMBITS_HASH 0x7a89324b
// Hash updated to reflect current 'dumpbits.dat' file version!
//#define BLOOMBITS_HASH 0xe31751e0
#define BLOOMBITS_HASH 0x955884d1
void iMenuView::Start()
{
if (gEnterNewKey) {
bool registered = IS_REGISTERED();
if (registered) {
iTextDlg tdlg(&gApp.ViewMgr(), gTextMgr[TRID_REG_SUCCEDED], gTextMgr[TRID_REG_DONE], PID_GREEN);
tdlg.DoModal();
} else {
gSettings.SetActivationKey(iStringT());
iTextDlg tdlg(&gApp.ViewMgr(), gTextMgr[TRID_REG_FAILED], gTextMgr[TRID_REG_INVALIDKEY], PID_RED);
tdlg.DoModal();
}
gEnterNewKey = false;
}
while (1) {
iMainMenuDlg mdlg(&gApp.ViewMgr());
sint32 res = mdlg.DoModal();
if (res == 100) {
// Start new game
iScenListDlg sldlg(&gApp.ViewMgr());
res = sldlg.DoModal();
if (res == DRC_OK) {
iMapInfo scenProps = sldlg.SelScen();
iScenPropsDlg spdlg(&gApp.ViewMgr(), scenProps, false);
if (spdlg.DoModal() == DRC_OK) {
scenProps.ReorderPlayers();
gGame.StartNewGame(scenProps, true);
break;
}
} else {
continue;
}
} else if (res == 101) {
// Load saved game
iSaveDlg saveDlg(&gApp.ViewMgr(), false);
res = saveDlg.DoModal();
if (res == DRC_OK) {
iMapInfo scenProps = saveDlg.SelScenario();
iScenPropsDlg spdlg(&gApp.ViewMgr(), scenProps, true);
if (spdlg.DoModal() == DRC_OK) {
scenProps.ReorderPlayers();
gGame.StartNewGame(scenProps, false);
break;
}
} else {
continue;
}
} else if (res == 102) {
iDlg_HallOfFame dlg(&gApp.ViewMgr(), gRootPath + _T("PalmHeroes.hsc"));
dlg.DoModal();
} else if (res == 103) {
StartCredits();
break;
} else if (res == 104) {
// Quit to WM200x
gGame.Quit();
break;
}
}
}
void iMenuView::StartCredits()
{
m_crComposer.StartCredits();
}
void iMenuView::StopCredits()
{
m_crComposer.StopCredits();
Start();
}
bool iMenuView::Process(fix32 t)
{
if (m_crComposer.IsCreaditsStarted() && m_crComposer.IsCreaditsEnd()) StopCredits();
Invalidate();
return true;
}
void iMenuView::OnCompose()
{
m_crComposer.Compose(gApp.Surface(),iPoint(0,0));
// gGfxMgr.Blit(PDGG_LOGO, gApp.Surface(), iPoint(44,2));
// gGfxMgr.Blit(PDGG_LOGO2, gApp.Surface(), iPoint(174,3));
#if 0
gTextComposer.TextOut(
iTextComposer::FontConfig(iTextComposer::FS_MEDIUM, iDibFont::ComposeProps(cColor_White, cColor_Black, iDibFont::DecBorder ) ),
gApp.Surface(), iPoint(), _T("Эксклюзивная версия для читателей журнала Mobi (www.mobi.ru)"),
iRect(0,m_Rect.y2()-15,m_Rect.w, 15), AlignCenter);
#endif
}
void iMenuView::OnMouseClick(const iPoint& pos)
{
StopCredits();
}
void iMenuView::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param)
{
uint32 uid = pView->GetUID();
}
|
[
"palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276"
] |
[
[
[
1,
239
]
]
] |
48fe2ed6acb55e0103a44de461f6b442c8a20794
|
8fa4334746f35b9103750bb23ec2b8d38e93cbe9
|
/coding/qt/forum/forum/accountWidget.h
|
61d702bd931ee20000a71499aa1863449b6815c0
|
[] |
no_license
|
zhzengj/testrepo
|
620b22b2cf1e8ff10274a9d0c6491816cecaec3b
|
daf8bd55fd347220f07bfd7d15b02b01a516479b
|
refs/heads/master
| 2016-09-11T00:50:57.846600 | 2011-10-16T07:59:48 | 2011-10-16T07:59:48 | 2,365,453 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 701 |
h
|
#ifndef _H_ACCOUNT_WIDGET_H_
#define _H_ACCOUNT_WIDGET_H_
#include "ui_account.h"
class JAccountSvr;
class JUserOpWidget;
class QStandardItemModel;
class JAccountWidget : public QWidget
{
Q_OBJECT
private:
Ui::Account m_ui;
JAccountSvr * m_svr;
JUserOpWidget * m_UserOp;
QStandardItemModel * m_model;
public:
explicit JAccountWidget(JAccountSvr * svr, QWidget * parent = 0);
~JAccountWidget();
protected slots:
void onItemChged(QStandardItem * item);
void onAddAccount();
void onModifyAccount();
void onDeleteAccount();
protected:
void setupTable();
QStandardItem * createItem(const QString & text, bool isEdit = false, bool isChk = false);
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
33
]
]
] |
ae56580460c1ec31da0bee20e40bc70e07529420
|
5bd189ea897b10ece778fbf9c7a0891bf76ef371
|
/BasicEngine/BasicEngine/Game/Object/Behaviour/Behaviour.h
|
17701ddd05699bb5eb688bad9762b489e680d302
|
[] |
no_license
|
boriel/masterullgrupo
|
c323bdf91f5e1e62c4c44a739daaedf095029710
|
81b3d81e831eb4d55ede181f875f57c715aa18e3
|
refs/heads/master
| 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null |
WINDOWS-1250
|
C++
| false | false | 771 |
h
|
#ifndef __BEHAVIOUR_H__
#define __BEHAVIOUR_H__
#include <stdlib.h>
class cObjectAgent; // se pone así para evitar doble inclusion
class cBehaviour {
protected:
cObjectAgent *mpCharacter;
public:
//Inicializa los atributos del comportamiento y es llamada en el
//momento en que se asocia este comportamiento a un personaje
virtual bool Init(cObjectAgent *lpCharacter);
//Deinicializa los atributos del comportamiento y es llamada en el
//momento en que se elimina este comportamiento de un personaje
virtual void Deinit();
//Esta función se llama cada frame para actualizar la lógica asociada
//al comportamiento (Behaviuor)
virtual void Update(float lfTimestep) = 0;
cBehaviour(): mpCharacter(NULL) {}
};
#endif
|
[
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7"
] |
[
[
[
1,
29
]
]
] |
f325f57c36e782889368ed2372a1e66ae0bc9b47
|
b14d5833a79518a40d302e5eb40ed5da193cf1b2
|
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/impl/DOMEntityImpl.hpp
|
42102da1b20acd5e0a44d2d4e55a2194dec9d703
|
[
"Apache-2.0"
] |
permissive
|
andyburke/bitflood
|
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
|
fca6c0b635d07da4e6c7fbfa032921c827a981d6
|
refs/heads/master
| 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,586 |
hpp
|
#ifndef DOMEntityImpl_HEADER_GUARD_
#define DOMEntityImpl_HEADER_GUARD_
/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOMEntityImpl.hpp,v 1.9 2004/09/08 13:55:51 peiyongz Exp $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/DOM.hpp> for the entire
// DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
#include <xercesc/util/XercesDefs.hpp>
#include "DOMNodeImpl.hpp"
#include "DOMParentNode.hpp"
#include <xercesc/dom/DOMEntity.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class DOMEntityReference;
class CDOM_EXPORT DOMEntityImpl: public DOMEntity {
private:
DOMNodeImpl fNode;
DOMParentNode fParent;
const XMLCh * fName;
const XMLCh * fPublicId;
const XMLCh * fSystemId;
const XMLCh * fNotationName;
DOMEntityReference* fRefEntity;
// New data introduced in DOM Level 3
const XMLCh* fActualEncoding;
const XMLCh* fEncoding;
const XMLCh* fVersion;
const XMLCh* fBaseURI;
bool fEntityRefNodeCloned;
// private helper function
void cloneEntityRefTree() const;
friend class XercesDOMParser;
public:
DOMEntityImpl(DOMDocument *doc, const XMLCh *eName);
DOMEntityImpl(const DOMEntityImpl &other, bool deep=false);
virtual ~DOMEntityImpl();
// Declare all of the functions from DOMNode.
DOMNODE_FUNCTIONS;
virtual const XMLCh * getPublicId() const;
virtual const XMLCh * getSystemId() const;
virtual const XMLCh * getNotationName() const;
virtual void setNotationName(const XMLCh *arg);
virtual void setPublicId(const XMLCh *arg);
virtual void setSystemId(const XMLCh *arg);
//DOM Level 2 additions. Non standard functions
virtual void setEntityRef(DOMEntityReference *);
virtual DOMEntityReference* getEntityRef() const;
//Introduced in DOM Level 3
virtual const XMLCh* getActualEncoding() const;
virtual void setActualEncoding(const XMLCh* actualEncoding);
virtual const XMLCh* getEncoding() const;
virtual void setEncoding(const XMLCh* encoding);
virtual const XMLCh* getVersion() const;
virtual void setVersion(const XMLCh* version);
virtual void setBaseURI(const XMLCh *arg);
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
DOMEntityImpl & operator = (const DOMEntityImpl &);
};
XERCES_CPP_NAMESPACE_END
#endif
|
[
"[email protected]"
] |
[
[
[
1,
104
]
]
] |
db5af790d4ea4c2d5da7947461363484d88f4b2e
|
12732dc8a5dd518f35c8af3f2a805806f5e91e28
|
/trunk/LiteEditor/options_base_dlg.cpp
|
798470f17d9c9de4e00be486effe2106cdaf3418
|
[] |
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 | 10,224 |
cpp
|
///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Feb 1 2007)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif //WX_PRECOMP
#include "options_base_dlg.h"
#include "wx/wxFlatNotebook/wxFlatNotebook.h"
#include "lexer_configuration.h"
#include "lexer_page.h"
#include "editor_config.h"
#include "manager.h"
///////////////////////////////////////////////////////////////////////////
BEGIN_EVENT_TABLE( OptionsDlg, wxDialog )
EVT_BUTTON( wxID_OK, OptionsDlg::OnButtonOK )
EVT_BUTTON( wxID_CANCEL, OptionsDlg::OnButtonCancel )
EVT_BUTTON( wxID_APPLY, OptionsDlg::OnButtonApply )
END_EVENT_TABLE()
OptionsDlg::OptionsDlg( wxWindow* parent, int id, wxString title, wxPoint pos, wxSize size, int style ) : wxDialog( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
this->Centre( wxBOTH );
wxBoxSizer* mainSizer;
mainSizer = new wxBoxSizer( wxVERTICAL );
long nbStyle = wxFNB_FF2 | wxFNB_NO_NAV_BUTTONS | wxFNB_NO_X_BUTTON | wxFNB_NODRAG | wxFNB_BACKGROUND_GRADIENT;
m_book = new wxFlatNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, nbStyle );
m_book->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
m_book->AddPage( CreateGeneralPage(), wxT("General"), true );
m_book->AddPage( CreateSyntaxHighlightPage(), wxT("Syntax Highlight"), false );
mainSizer->Add( m_book, 1, wxEXPAND | wxALL, 5 );
m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
mainSizer->Add( m_staticline1, 0, wxALL|wxEXPAND, 5 );
wxBoxSizer* btnSizer;
btnSizer = new wxBoxSizer( wxHORIZONTAL );
m_okButton = new wxButton( this, wxID_OK, wxT("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
btnSizer->Add( m_okButton, 0, wxALIGN_RIGHT|wxALL, 5 );
m_cancelButton = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
btnSizer->Add( m_cancelButton, 0, wxALIGN_RIGHT|wxALL, 5 );
m_applyButton = new wxButton( this, wxID_APPLY, wxT("Apply"), wxDefaultPosition, wxDefaultSize, 0 );
btnSizer->Add( m_applyButton, 0, wxALIGN_RIGHT|wxALL, 5 );
mainSizer->Add( btnSizer, 0, wxALIGN_RIGHT, 5 );
this->SetSizer( mainSizer );
this->Layout();
}
wxPanel *OptionsDlg::CreateSyntaxHighlightPage()
{
wxPanel *page = new wxPanel( m_book, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer *sz = new wxBoxSizer(wxVERTICAL);
page->SetSizer(sz);
long style = wxFNB_FF2 | wxFNB_NO_NAV_BUTTONS | wxFNB_DROPDOWN_TABS_LIST | wxFNB_NO_X_BUTTON;
m_lexersBook = new wxFlatNotebook(page, wxID_ANY, wxDefaultPosition, wxDefaultSize, style);
sz->Add(m_lexersBook, 1, wxEXPAND | wxALL, 5);
m_lexersBook->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
bool selected = true;
EditorConfig::ConstIterator iter = EditorConfigST::Get()->LexerBegin();
for(; iter != EditorConfigST::Get()->LexerEnd(); iter++){
LexerConfPtr lexer = iter->second;
m_lexersBook->AddPage(CreateLexerPage(m_lexersBook, lexer), lexer->GetName(), selected);
selected = false;
}
return page;
}
wxPanel *OptionsDlg::CreateGeneralPage()
{
OptionsConfigPtr options = EditorConfigST::Get()->GetOptions();
m_general = new wxPanel( m_book, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* vSz1;
vSz1 = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* sbSizer1;
sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( m_general, -1, wxT("Folding:") ), wxVERTICAL );
m_checkBoxDisplayFoldMargin = new wxCheckBox( m_general, wxID_ANY, wxT("Display Folding Margin"), wxDefaultPosition, wxDefaultSize, 0 );
m_checkBoxDisplayFoldMargin->SetValue(options->GetDisplayFoldMargin());
sbSizer1->Add( m_checkBoxDisplayFoldMargin, 0, wxALL, 5 );
m_checkBoxMarkFoldedLine = new wxCheckBox( m_general, wxID_ANY, wxT("Underline Folded Line"), wxDefaultPosition, wxDefaultSize, 0 );
m_checkBoxMarkFoldedLine->SetValue(options->GetUnderlineFoldLine());
sbSizer1->Add( m_checkBoxMarkFoldedLine, 0, wxALL, 5 );
m_staticText1 = new wxStaticText( m_general, wxID_ANY, wxT("Fold Style:"), wxDefaultPosition, wxDefaultSize, 0 );
sbSizer1->Add( m_staticText1, 0, wxALL, 5 );
wxString m_foldStyleChoiceChoices[] = { wxT("Simple"), wxT("Arrows"), wxT("Flatten Tree Square Headers"), wxT("Flatten Tree Circular Headers") };
int m_foldStyleChoiceNChoices = sizeof( m_foldStyleChoiceChoices ) / sizeof( wxString );
m_foldStyleChoice = new wxChoice( m_general, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_foldStyleChoiceNChoices, m_foldStyleChoiceChoices, 0 );
sbSizer1->Add( m_foldStyleChoice, 0, wxALL|wxEXPAND, 5 );
m_foldStyleChoice->SetStringSelection( options->GetFoldStyle() );
vSz1->Add( sbSizer1, 0, wxEXPAND, 5 );
wxStaticBoxSizer* sbSizer3;
sbSizer3 = new wxStaticBoxSizer( new wxStaticBox( m_general, -1, wxT("Bookmarks:") ), wxVERTICAL );
m_displayBookmarkMargin = new wxCheckBox( m_general, wxID_ANY, wxT("Display Selection / Bookmark margin"), wxDefaultPosition, wxDefaultSize, 0 );
m_displayBookmarkMargin->SetValue(options->GetDisplayBookmarkMargin());
sbSizer3->Add( m_displayBookmarkMargin, 0, wxALL, 5 );
m_staticText6 = new wxStaticText( m_general, wxID_ANY, wxT("Bookmark Shape:"), wxDefaultPosition, wxDefaultSize, 0 );
sbSizer3->Add( m_staticText6, 0, wxALL, 5 );
wxString m_bookmarkShapeChoices[] = { wxT("Small Rectangle"), wxT("Rounded Rectangle"), wxT("Circle"), wxT("Small Arrow") };
int m_bookmarkShapeNChoices = sizeof( m_bookmarkShapeChoices ) / sizeof( wxString );
m_bookmarkShape = new wxChoice( m_general, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_bookmarkShapeNChoices, m_bookmarkShapeChoices, 0 );
sbSizer3->Add( m_bookmarkShape, 0, wxALL|wxEXPAND, 5 );
m_bookmarkShape->SetStringSelection(options->GetBookmarkShape());
wxGridSizer* gSizer1;
gSizer1 = new wxGridSizer( 2, 2, 0, 0 );
m_staticText4 = new wxStaticText( m_general, wxID_ANY, wxT("Select the bookmark background colour:"), wxDefaultPosition, wxDefaultSize, 0 );
gSizer1->Add( m_staticText4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_bgColourPicker = new wxColourPickerCtrl(m_general, wxID_ANY, options->GetBookmarkBgColour(), wxDefaultPosition, wxDefaultSize, wxCLRP_SHOW_LABEL);
gSizer1->Add( m_bgColourPicker, 0, wxALIGN_RIGHT|wxALL, 5 );
m_staticText5 = new wxStaticText( m_general, wxID_ANY, wxT("Select the bookmark forground colour:"), wxDefaultPosition, wxDefaultSize, 0 );
gSizer1->Add( m_staticText5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_fgColourPicker = new wxColourPickerCtrl( m_general, wxID_ANY, options->GetBookmarkFgColour(), wxDefaultPosition, wxDefaultSize, wxCLRP_SHOW_LABEL);
gSizer1->Add( m_fgColourPicker, 0, wxALIGN_RIGHT|wxALL, 5 );
sbSizer3->Add( gSizer1, 1, wxEXPAND, 5 );
vSz1->Add( sbSizer3, 0, wxEXPAND, 5 );
wxStaticBoxSizer* sbSizer4;
sbSizer4 = new wxStaticBoxSizer( new wxStaticBox( m_general, -1, wxT("General:") ), wxVERTICAL );
wxFlexGridSizer* fgSizer;
fgSizer = new wxFlexGridSizer( 3, 2, 0, 0 );
m_highlighyCaretLine = new wxCheckBox( m_general, wxID_ANY, wxT("Highlight Caret Line"), wxDefaultPosition, wxDefaultSize, 0 );
m_highlighyCaretLine->SetValue(options->GetHighlightCaretLine());
fgSizer->Add( m_highlighyCaretLine, 0, wxALL, 5 );
m_displayLineNumbers = new wxCheckBox( m_general, wxID_ANY, wxT("Dsiplay Line Numbers"), wxDefaultPosition, wxDefaultSize, 0 );
m_displayLineNumbers->SetValue(options->GetDisplayLineNumbers());
fgSizer->Add( m_displayLineNumbers, 0, wxALL, 5 );
m_showIndentationGuideLines = new wxCheckBox( m_general, wxID_ANY, wxT("Show Indentation Guidelines"), wxDefaultPosition, wxDefaultSize, 0 );
m_showIndentationGuideLines->SetValue(options->GetShowIndentationGuidelines());
fgSizer->Add( m_showIndentationGuideLines, 0, wxALL, 5 );
sbSizer4->Add( fgSizer, 1, wxEXPAND, 5 );
vSz1->Add( sbSizer4, 0, wxEXPAND, 5 );
m_general->SetSizer( vSz1 );
m_general->Layout();
vSz1->Fit( m_general );
return m_general;
}
wxPanel *OptionsDlg::CreateLexerPage(wxPanel *parent, LexerConfPtr lexer)
{
return new LexerPage(parent, lexer);
}
void OptionsDlg::OnButtonOK(wxCommandEvent &event)
{
wxUnusedVar(event);
SaveChanges();
ManagerST::Get()->ApplySettingsChanges();
// and close the dialog
EndModal(wxID_OK);
}
void OptionsDlg::OnButtonApply(wxCommandEvent &event)
{
SaveChanges();
ManagerST::Get()->ApplySettingsChanges();
wxUnusedVar(event);
}
void OptionsDlg::OnButtonCancel(wxCommandEvent &event)
{
wxUnusedVar(event);
EndModal(wxID_CANCEL);
}
void OptionsDlg::SaveChanges()
{
int max = m_lexersBook->GetPageCount();
for(int i=0; i<max; i++){
wxWindow *win = m_lexersBook->GetPage((size_t)i);
LexerPage *page = dynamic_cast<LexerPage*>( win );
if( page ){
page->SaveSettings();
}
}
// construct an OptionsConfig object and update the configuration
OptionsConfigPtr options(new OptionsConfig(NULL));
options->SetDisplayFoldMargin( m_checkBoxDisplayFoldMargin->IsChecked() );
options->SetUnderlineFoldLine( m_checkBoxMarkFoldedLine->IsChecked() );
options->SetFoldStyle(m_foldStyleChoice->GetStringSelection());
options->SetDisplayBookmarkMargin(m_displayBookmarkMargin->IsChecked());
options->SetBookmarkShape( m_bookmarkShape->GetStringSelection());
options->SetBookmarkBgColour( m_bgColourPicker->GetColour() );
options->SetBookmarkFgColour( m_fgColourPicker->GetColour() );
options->SetHighlightCaretLine( m_highlighyCaretLine->IsChecked() );
options->SetDisplayLineNumbers( m_displayLineNumbers->IsChecked() );
options->SetShowIndentationGuidelines( m_showIndentationGuideLines->IsChecked() );
EditorConfigST::Get()->SetOptions(options);
ManagerST::Get()->ApplySettingsChanges();
}
|
[
"eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b"
] |
[
[
[
1,
241
]
]
] |
455f08286b2f26cbd113d5c23d9bacad47f9563d
|
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
|
/Code/controllers/Tcleaner/robotapi/real/RealDifferentialWheels.h
|
18f6044ba679b968ca5da923cdff4cae3825e259
|
[] |
no_license
|
dh-04/tpf-robotica
|
5efbac38d59fda0271ac4639ea7b3b4129c28d82
|
10a7f4113d5a38dc0568996edebba91f672786e9
|
refs/heads/master
| 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,685 |
h
|
#ifndef robotapi_real_RealDifferentialWheels_h
#define robotapi_real_RealDifferentialWheels_h
#include <robotapi/IDifferentialWheels.h>
#include <robotapi/DifferentialWheelsWOdometry.h>
#include <protocol/handlers/DCMotorBoardPacketHandler.h>
#include <robotapi/real/RealDevice.h>
#include <WorldInfo.h>
namespace robotapi {
namespace real {
class RealDifferentialWheels : public robotapi::DifferentialWheelsWOdometry , public robotapi::real::RealDevice {
public:
RealDifferentialWheels(WorldInfo * wi, protocol::handlers::DCMotorBoardPacketHandler * dcmbphl,
protocol::handlers::DCMotorBoardPacketHandler * dcmbphr,
std::string name);
~RealDifferentialWheels();
void setSpeed(double left, double right);
double getLeftSpeed();
double getRightSpeed();
void enableEncoders(int ms);
void disableEncoders();
double getLeftEncoder();
double getRightEncoder();
void moveWheels(double left, double right);
void moveLeftWheel(double left);
void moveRightWheel(double right);
void moveLeftWheel(double left, double speed);
void moveRightWheel(double right, double speed);
double getLeftMotorConsumption();
double getRightMotorConsumption();
bool isAlarmPresent();
bool isAlarmPresent(bool left);
bool motorIsOff();
bool motorIsOff(bool left);
private:
protocol::handlers::DCMotorBoardPacketHandler * leftBoard;
protocol::handlers::DCMotorBoardPacketHandler * rightBoard;
};
} /* End of namespace robotapi::real */
} /* End of namespace robotapi */
#endif // robotapi_real_RealDifferentialWheels_h
|
[
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
] |
[
[
[
1,
67
]
]
] |
96d95a01d16b5eb48c9c6dbad84848e452199e39
|
1bc2f450f157ce39cbd92d0549e1459368a76e94
|
/testsrc/ODINTest/ImageTest.cpp
|
36d408f13641691e5ba4f936ae29c8890130b664
|
[] |
no_license
|
mirror/odin
|
168267277386d6c07c006cb196fec3bb208f5e3c
|
63b4633a87b03a924df612271c2d6310c34834a8
|
refs/heads/master
| 2023-09-01T13:28:38.392325 | 2011-10-09T15:38:02 | 2011-10-09T15:38:02 | 9,256,124 | 5 | 4 | null | null | null | null |
UTF-8
|
C++
| false | false | 14,888 |
cpp
|
/******************************************************************************
ODIN - Open Disk Imager in a Nutshell
Copyright (C) 2008
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 3 of the 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
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/>
For more information and the latest version of the source code see
<http://sourceforge.net/projects/odin-win>
******************************************************************************/
#include "stdafx.h"
#include "ImageTest.h"
#include "ImageStreamSimulator.h"
#include "..\..\src\ODIN\ODINThread.h"
#include "..\..\src\ODIN\ReadThread.h"
#include "..\..\src\ODIN\WriteThread.h"
#include "..\..\src\ODIN\CompressionThread.h"
#include "..\..\src\ODIN\DecompressionThread.h"
#include "..\..\src\ODIN\BufferQueue.h"
#include <iostream>
using namespace std;
// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( ImageTest );
static vector<unsigned __int64> sSavePositions, sRestorePositions;
unsigned ImageTest::sSavedCrc32;
void ImageTest::setUp()
{
int cReadChunkSize = 64 * 1024;
int nBufferCount = 8;
fClusterSize = 4096;
fEmptyReaderQueue = new CImageBuffer(cReadChunkSize, nBufferCount, L"fEmptyReaderQueue");
fFilledReaderQueue = new CImageBuffer(L"fFilledReaderQueue");
fEmptyCompDecompQueue = new CImageBuffer(cReadChunkSize, nBufferCount, L"fEmptyCompDecompQueue");
fFilledCompDecompQueue = new CImageBuffer(L"fFilledCompDecompQueue");
}
void ImageTest::tearDown()
{
delete fEmptyReaderQueue;
delete fFilledReaderQueue;
delete fEmptyCompDecompQueue;
delete fFilledCompDecompQueue;
}
void ImageTest::runSimpleSaveRestore(bool verifyOnly)
{
CImageStreamSimulator streamSimSource(4*1024*1024, true); // 4MB
CImageStreamSimulator streamSimTarget(false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
unsigned __int64 size = streamSimSource.GetSize() ;
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, verifyOnly);
COdinThread* writeThread = new CWriteThread(&streamSimTarget, fFilledReaderQueue, fEmptyReaderQueue, verifyOnly);
// Run threads
readThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 2;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
WaitUntilDone(threadHandleArray, 2);
delete readThread;
delete writeThread;
delete [] threadHandleArray;
if (verifyOnly) {
DWORD crcRead = streamSimSource.GetCRC32();
CPPUNIT_ASSERT(sSavedCrc32 == crcRead);
} else {
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
CPPUNIT_ASSERT(crcRead == crcWrite);
sSavedCrc32 = crcWrite;
}
}
void ImageTest::saveRestoreImageTestSimple()
{
cout << "saveRestoreImageTestSimple()" << endl;
runSimpleSaveRestore(false);
cout << " ...done." << endl;
}
void ImageTest::verifyTestSimple()
{
cout << "verifyTestSimple()" << endl;
runSimpleSaveRestore(true);
cout << " ...done." << endl;
}
/*
void ImageTest::saveImageTestSimple()
{
CImageStreamSimulator streamSimSource(4*1024*1024, true); // 4MB
CImageStreamSimulator streamSimTarget(false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
unsigned __int64 size = streamSimSource.GetSize() ;
cout << "saveImageTestSimple()" << endl;
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, false);
COdinThread* writeThread = new CWriteThread(&streamSimTarget, fFilledReaderQueue, fEmptyReaderQueue, false);
// Run threads
readThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 2;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
WaitUntilDone(threadHandleArray, 2);
cout << " ...done." << endl;
delete readThread;
delete writeThread;
delete [] threadHandleArray;
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
CPPUNIT_ASSERT(crcRead == crcWrite);
}
void ImageTest::restoreImageTestSimple()
{
CImageStreamSimulator streamSimTarget(true);
CImageStreamSimulator streamSimSource(4*1024*1024, false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
cout << "restoreImageTestSimple()" << endl;
// create threads and save an image
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, false);
CWriteThread* writeThread = new CWriteThread(&streamSimTarget, fFilledReaderQueue, fEmptyReaderQueue, false);
// Run threads
readThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 2;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
WaitUntilDone(threadHandleArray, 2);
delete readThread;
delete writeThread;
delete [] threadHandleArray;
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
CPPUNIT_ASSERT(crcRead == crcWrite);
}
*/
void ImageTest::saveImageTestRunLengthStandard()
{
int runLengths[] = {563, 318, 745, 157, 486, 41, 290, 64, 51, 100, 51, 159, 125, 762};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "saveImageTestRunLengthStandard()" << endl;
saveImageTestRunLength(runLengths, len);
}
void ImageTest::restoreImageTestRunLengthStandard()
{
int runLengths[] = {563, 318, 745, 157, 486, 41, 290, 64, 51, 100, 51, 159, 125, 762};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "restoreImageTestRunLengthStandard()" << endl;
restoreImageTestRunLength(runLengths, len);
CPPUNIT_ASSERT(sSavePositions == sRestorePositions);
}
void ImageTest::saveImageTestRunLengthLong()
{
int runLengths[] = {5000, 5000, 100, 100};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "saveImageTestRunLengthLong()" << endl;
saveImageTestRunLength(runLengths, len);
}
void ImageTest::restoreImageTestRunLengthLong()
{
int runLengths[] = {5000, 5000, 100, 100};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "restoreImageTestRunLengthLong()" << endl;
restoreImageTestRunLength(runLengths, len);
CPPUNIT_ASSERT(sSavePositions == sRestorePositions);
}
void ImageTest::saveImageTestRunLengthShort()
{
int runLengths[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 1, 1};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "saveImageTestRunLengthShort()" << endl;
saveImageTestRunLength(runLengths, len);
}
void ImageTest::restoreImageTestRunLengthShort()
{
int runLengths[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 1, 1};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "restoreImageTestRunLengthShort()" << endl;
restoreImageTestRunLength(runLengths, len);
// LogSeekPositions();
CPPUNIT_ASSERT(sSavePositions == sRestorePositions);
}
void ImageTest::saveImageTestRunLengthSpecial()
{
// test the special case that the run length is the same as block size of read thread
int runLengths[] = {16, 16};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "saveImageTestRunLengthSpecial()" << endl;
saveImageTestRunLength(runLengths, len);
}
void ImageTest::restoreImageTestRunLengthSpecial()
{
int runLengths[] = {16, 16};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
cout << "restoreImageTestRunLengthSpecial()" << endl;
restoreImageTestRunLength(runLengths, len);
CPPUNIT_ASSERT(sSavePositions == sRestorePositions);
}
void ImageTest::WaitUntilDone(HANDLE* threadHandleArray, int threadCount)
{
while (TRUE) {
DWORD result = MsgWaitForMultipleObjects(threadCount, threadHandleArray, FALSE, INFINITE, QS_ALLEVENTS);
if (result >= WAIT_OBJECT_0 && result < (DWORD)threadCount) {
// ATLTRACE("event arrived: %d, thread id: %x\n", result, threadHandleArray[result]);
if (--threadCount == 0) {
//cout << " All worker threads are terminated now\n" << endl;
break;
}
// setup new array with the remaining threads:
for (int i=result; i<threadCount; i++)
threadHandleArray[i] = threadHandleArray[i+1];
}
}
}
void ImageTest::saveCompressedImageGzipTest()
{
cout << "saveCompressedImageGzipTest()..." << endl;
saveCompressed(compressionGZip);
cout << " ... done" << endl;
}
void ImageTest::saveCompressedImageBzip2Test()
{
cout << "saveCompressedImageBzip2Test()..." << endl;
saveCompressed(compressionBZIP2);
cout << " ... done" << endl;
}
void ImageTest::saveCompressed(TCompressionFormat compressionType)
{
int runLengths[] = {563, 318, 745, 157, 486, 41, 290, 64, 51, 100, 51, 159, 125, 762};
int len = sizeof(runLengths) / sizeof(runLengths[0]);
CImageStreamSimulator streamSimSource(runLengths, len, IImageStream::forReading, true);
CImageStreamSimulator streamSimTarget(false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
unsigned __int64 size = streamSimSource.GetSize() ;
// create threads and save an image
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, false);
COdinThread* compressionThread = new CCompressionThread(compressionType, fFilledReaderQueue, fEmptyReaderQueue, fEmptyCompDecompQueue, fFilledCompDecompQueue);
COdinThread* writeThread = new CWriteThread(&streamSimTarget, fFilledCompDecompQueue, fEmptyCompDecompQueue, false);
readThread->SetAllocationMapReaderInfo(streamSimSource.GetRunLengthStreamReader(), fClusterSize);
// Run threads
readThread->Resume();
compressionThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 3;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
threadHandleArray[2] = compressionThread->GetHandle();
WaitUntilDone(threadHandleArray, 3);
delete readThread;
delete writeThread;
delete compressionThread;
delete [] threadHandleArray;
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
}
void ImageTest::saveImageTestRunLength(int* runLengthArray, int len)
{
CImageStreamSimulator streamSimSource(runLengthArray, len, IImageStream::forReading, true);
CImageStreamSimulator streamSimTarget(false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
unsigned __int64 size = streamSimSource.GetSize() ;
// cout << "size of test stream is: " << size << endl;
// create threads and save an image
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, false);
COdinThread* writeThread = new CWriteThread(&streamSimTarget, fFilledReaderQueue, fEmptyReaderQueue, false);
// streamSimTarget.WriteImageFileHeaderAndAllocationMap(streamSimSource);
readThread->SetAllocationMapReaderInfo(streamSimSource.GetRunLengthStreamReader(), fClusterSize);
// Run threads
readThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 2;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
WaitUntilDone(threadHandleArray, 2);
delete readThread;
delete writeThread;
delete [] threadHandleArray;
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
sSavePositions = streamSimSource.GetSeekPositions();
CPPUNIT_ASSERT(crcRead == crcWrite);
}
void ImageTest::restoreImageTestRunLength(int* runLengthArray, int len)
{
unsigned __int64 simFileSize = 0;
for (int i=0; i<len; i+=2)
simFileSize += runLengthArray[i] * fClusterSize;
CImageStreamSimulator streamSimTarget(runLengthArray, len, IImageStream::forWriting, true);
CImageStreamSimulator streamSimSource(simFileSize, false);
streamSimSource.SetClusterSize(fClusterSize);
streamSimTarget.SetClusterSize(fClusterSize);
unsigned __int64 size = streamSimSource.GetSize() ;
// cout << "size of test stream is: " << size << endl;
// create threads and save an image
CReadThread* readThread = new CReadThread(&streamSimSource, fEmptyReaderQueue, fFilledReaderQueue, false);
CWriteThread* writeThread = new CWriteThread(&streamSimTarget, fFilledReaderQueue, fEmptyReaderQueue, false);
writeThread->SetAllocationMapReaderInfo(streamSimTarget.GetRunLengthStreamReader(), fClusterSize);
readThread->SetVolumeDataOffset(0);
// Run threads
readThread->Resume();
writeThread->Resume();
// wait until done:
int threadCount = 2;
HANDLE* threadHandleArray = new HANDLE[threadCount];
threadHandleArray[0] = readThread->GetHandle();
threadHandleArray[1] = writeThread->GetHandle();
WaitUntilDone(threadHandleArray, 2);
delete readThread;
delete writeThread;
delete [] threadHandleArray;
DWORD crcRead = streamSimSource.GetCRC32();
DWORD crcWrite = streamSimTarget.GetCRC32();
sRestorePositions = streamSimTarget.GetSeekPositions();
CPPUNIT_ASSERT(crcRead == crcWrite);
}
void ImageTest::LogSeekPositions()
{
cout << endl;
cout << "Seek positions comparisons:" << endl;
cout << "size of save is: " << sSavePositions.size() << " / size of restore is. " << sRestorePositions.size() << endl;
vector<unsigned __int64>::iterator it;
cout << "Save positions: " << endl;
for (it = sSavePositions.begin(); it!=sSavePositions.end(); ++it)
cout << *it << ", ";
cout << endl;
cout << "Restore positions: " << endl;
for (it = sRestorePositions.begin(); it!=sRestorePositions.end(); ++it)
cout << *it << ", ";
cout << endl;
}
|
[
"kaltduscher65@b91d169b-bf28-450c-9b59-d70c078a1df8"
] |
[
[
[
1,
417
]
]
] |
c737535a220a1bfd871fb339f652e0ff10e9938d
|
97fd2a81a3baffb26dc5b627c08aa4a69574a761
|
/inc/ListItems/FeedsListItem.h
|
af512919eeef89345baf70f8afe7858c199dba3a
|
[] |
no_license
|
drstrangecode/Bada_RssReader_DrStrangecode
|
c4c61dacabacf9419a0335d70a141dc8374c8b2e
|
b3cf7b1f6afc43af782c0713fa6b54b1e95d0c1a
|
refs/heads/master
| 2016-09-06T05:34:10.075095 | 2011-10-16T16:08:46 | 2011-10-16T16:08:46 | 2,542,044 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,587 |
h
|
/*
* FeedsListItem.h
*
* Created by: Dr. Strangecode
* ---------------------------------------------
* This is free code, it can be used, modified,
* destroyed, raped and whatever without limits.
* I own no copyrights over it.
* This code is 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.
* ---------------------------------------------
* For more free code visit http://drstrangecode.org
*/
#ifndef FEEDSLISTITEM_H_
#define FEEDSLISTITEM_H_
#include <FBase.h>
#include <FGraphics.h>
#include <FUi.h>
#include <FApp.h>
class FeedsListItem : public Osp::Ui::Controls::CustomItem {
public:
static const int ITEM_HEIGHT = 100;
static const int ITEM_LEFT_MARGIN = 10;
static const int ICON_DIMENSION = 0;//ITEM_HEIGHT;
static const int ICO_ELM_ID = 1;
static const int TITLE_ELM_ID = 2;
static const int CATEGORIES_ELM_ID = 3;
static const int ABOUT_ELM_ID = 4;
static const int SEPARATOR_ELM_ID = 5;
FeedsListItem();
virtual ~FeedsListItem();
result Construct(int width,
Osp::Base::String & title,
Osp::Base::String & categories,
Osp::Base::String & about);
private:
Osp::Graphics::Bitmap * pRowIcon;
Osp::Graphics::Bitmap * pRowSeparatorBitmap;
};
#endif /* FEEDSLISTITEM_H_ */
|
[
"[email protected]"
] |
[
[
[
1,
51
]
]
] |
2c52f22337f74d7aafc9e721755791b55efdfcae
|
b5ab57edece8c14a67cc98e745c7d51449defcff
|
/Captain's Log/MainGame/Source/WinMain.cpp
|
def45e1aca6249f082f960721d983ca173f77a5e
|
[] |
no_license
|
tabu34/tht-captainslog
|
c648c6515424a6fcdb628320bc28fc7e5f23baba
|
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
|
refs/heads/master
| 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,906 |
cpp
|
//////////////////////////////////////////////////////////////////////////////////////////////
// File : "WinMain.cpp"
//
// Author : David Brown (DB)
// Based in part on:
// -Window code from the book: "Physics for Game Developers" by David M. Bourg.
// -The previous WinMain.cpp by Jensen Rivera.
//
// Last Modified : 3/31/2009
//
// Purpose : To provide a basic window framework for student games.
//
//////////////////////////////////////////////////////////////////////////////////////////////
#include "precompiled_header.h"
#include <windows.h> // Needed for Windows Applications.
#define VLD_AGGREGATE_DUPLICATES
#define VLD_MAX_DATA_DUMP 0
#include <vld.h>
#include "CGame.h"
#define _CRTDBG_MAP_ALLOC
const char* g_szWINDOW_CLASS_NAME = "SGDWindowClass"; // Window Class Name.
const char* g_szWINDOW_TITLE = "Captain's Log"; // Window Title.
const int g_nWINDOW_WIDTH = 1440; // Window Width.
const int g_nWINDOW_HEIGHT = 900; // Window Height.
//const int g_nWINDOW_WIDTH = 1800; // Window Width.
//const int g_nWINDOW_HEIGHT = 1125; // Window Height.
// Windowed or Full screen depending on project setting
#ifdef _DEBUG
const BOOL g_bIS_WINDOWED = TRUE;
#else
const BOOL g_bIS_WINDOWED = TRUE;
#endif
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// This is the main message handler of the system.
PAINTSTRUCT ps; // Used in WM_PAINT.
HDC hdc; // Handle to a device context.
// What is the message
switch(msg)
{
// To skip ALT pop up menu (system menu)
case WM_SYSKEYUP:
case WM_SYSCHAR:
return(0);
break;
// Handle ALT+F4
case WM_CLOSE:
{
// Sends us a WM_DESTROY
DestroyWindow(hWnd);
}
break;
// and lose/gain focus
case WM_ACTIVATE:
{
// gaining focus
if (LOWORD(wParam) != WA_INACTIVE)
{
// unpause game code here
}
else // losing focus
{
// pause game code here
}
}
break;
case WM_CREATE:
{
// Do initialization here
return(0);
}
break;
case WM_PAINT:
{
// Start painting
hdc = BeginPaint(hWnd,&ps);
// End painting
EndPaint(hWnd,&ps);
return(0);
}
break;
case WM_DESTROY:
{
// Kill the application
PostQuitMessage(0);
return(0);
}
break;
default:
break;
}
// Process any messages that we didn't take care of
return (DefWindowProc(hWnd, msg, wParam, lParam));
}
// Checks to see if the game was already running in another window.
//
// NOTE: Don't call this function if your game needs to have more
// than one instance running on the same computer (i.e. client/server)
BOOL CheckIfAlreadyRunning(void)
{
// Find a window of the same window class name and window title
HWND hWnd = FindWindow(g_szWINDOW_CLASS_NAME, g_szWINDOW_TITLE);
// If one was found
if (hWnd)
{
// If it was minimized
if (IsIconic(hWnd))
// restore it
ShowWindow(hWnd, SW_RESTORE);
// Bring it to the front
SetForegroundWindow(hWnd);
return TRUE;
}
// No other copies found running
return FALSE;
}
BOOL RegisterWindowClass(HINSTANCE hInstance)
{
WNDCLASSEX winClassEx; // This will describe the window class we will create.
// First fill in the window class structure
winClassEx.cbSize = sizeof(winClassEx);
winClassEx.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
winClassEx.lpfnWndProc = WindowProc;
winClassEx.cbClsExtra = 0;
winClassEx.cbWndExtra = 0;
winClassEx.hInstance = hInstance;
winClassEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winClassEx.hIconSm = NULL;
winClassEx.hCursor = LoadCursor(NULL, IDC_ARROW);
winClassEx.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winClassEx.lpszMenuName = NULL;
winClassEx.lpszClassName = g_szWINDOW_CLASS_NAME;
// Register the window class
return RegisterClassEx(&winClassEx);
}
// Creates and sizes the window appropriately depending on if
// the application is windowed or full screen.
HWND MakeWindow(HINSTANCE hInstance)
{
// Setup window style flags
DWORD dwWindowStyleFlags = WS_VISIBLE;
if (g_bIS_WINDOWED)
{
dwWindowStyleFlags |= WS_OVERLAPPEDWINDOW;
}
else
{
dwWindowStyleFlags |= WS_POPUP;
ShowCursor(FALSE); // Stop showing the mouse cursor
}
// Setup the desired client area size
RECT rWindow;
rWindow.left = 0;
rWindow.top = 0;
rWindow.right = g_nWINDOW_WIDTH;
rWindow.bottom = g_nWINDOW_HEIGHT;
// Get the dimensions of a window that will have a client rect that
// will really be the resolution we're looking for.
AdjustWindowRectEx(&rWindow,
dwWindowStyleFlags,
FALSE,
WS_EX_APPWINDOW);
// Calculate the width/height of that window's dimensions
int nWindowWidth = rWindow.right - rWindow.left;
int nWindowHeight = rWindow.bottom - rWindow.top;
// Create the window
return CreateWindowEx(WS_EX_APPWINDOW, // Extended Style flags.
g_szWINDOW_CLASS_NAME, // Window Class Name.
g_szWINDOW_TITLE, // Title of the Window.
dwWindowStyleFlags, // Window Style Flags.
(GetSystemMetrics(SM_CXSCREEN)/2) - (nWindowWidth/2), // Window Start Point (x, y).
(GetSystemMetrics(SM_CYSCREEN)/2) - (nWindowHeight/2), // -Does the math to center the window over the desktop.
nWindowWidth, // Width of Window.
nWindowHeight, // Height of Window.
NULL, // Handle to parent window.
NULL, // Handle to menu.
hInstance, // Application Instance.
NULL); // Creation parameters.
}
//////////////////////////
// WinMain //
//////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg; // Generic message.
HWND hWnd; // Main Window Handle.
// Don't let more than one instance of the application exist
//
// NOTE: Comment out the following section of code if your game needs to have more
// than one instance running on the same computer (i.e. client/server)
////////////////////////////////////////////////////////////////////////
if (!hPrevInstance)
{
if (CheckIfAlreadyRunning())
return FALSE;
}
////////////////////////////////////////////////////////////////////////
// Register the window class
if (!RegisterWindowClass(hInstance))
return 0;
// Create the window
hWnd = MakeWindow(hInstance);
if (!hWnd)
return 0;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
//////////////////////////////////////////
// Initialize Game here
//////////////////////////////////////////
CGame *pGame=CGame::GetInstance();
pGame->Initialize(hWnd, hInstance, g_nWINDOW_WIDTH, g_nWINDOW_HEIGHT, g_bIS_WINDOWED);
//////////////////////////////////////////
// Enter main event loop
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Test if this is a quit
if (msg.message == WM_QUIT)
break;
// Translate any accelerator keys
TranslateMessage(&msg);
// Send the message to the window proc
DispatchMessage(&msg);
}
//////////////////////////////////
// Put Game Logic Here
//////////////////////////////////
if(pGame->Main()==false)
PostQuitMessage(0);
//////////////////////////////////
}
/////////////////////////////////////////
// Shutdown Game Here
/////////////////////////////////////////
pGame->Shutdown();
/////////////////////////////////////////
// Unregister the window class
UnregisterClass(g_szWINDOW_CLASS_NAME, hInstance);
// Return to Windows like this.
return (int)(msg.wParam);
}
|
[
"notserp007@34577012-8437-c882-6fb8-056151eb068d",
"dpmakin@34577012-8437-c882-6fb8-056151eb068d"
] |
[
[
[
1,
16
],
[
20,
28
],
[
31,
35
],
[
37,
296
]
],
[
[
17,
19
],
[
29,
30
],
[
36,
36
]
]
] |
4ca6185942be3e4432a9a409b653e4ac3a791a1d
|
279b68f31b11224c18bfe7a0c8b8086f84c6afba
|
/playground/barfan/findik-mysql-poc-3/mysqldbmanager.hpp
|
8346a8bebc569dd78a5c68d5da7a32a64f0cc0bc
|
[] |
no_license
|
bogus/findik
|
83b7b44b36b42db68c2b536361541ee6175bb791
|
2258b3b3cc58711375fe05221588d5a068da5ea8
|
refs/heads/master
| 2020-12-24T13:36:19.550337 | 2009-08-16T21:46:57 | 2009-08-16T21:46:57 | 32,120,100 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 612 |
hpp
|
#include "dbmanager.hpp"
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
namespace findik {
class mysqldbmanager : public dbmanager {
public:
mysqldbmanager();
void connectDb(std::string host, std::string db,
std::string username, std::string password);
bool hostnameQuery(std::string hostname);
bool contentQuery(std::string content);
bool hostnameRegexQuery(std::string hostname);
bool contentRegexQuery(std::string content);
private:
};
}
|
[
"barfan@d40773b4-ada0-11de-b0a2-13e92fe56a31"
] |
[
[
[
1,
26
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.