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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5cfcd635d6be6b4d4bc3d68e9578369f5701f557
|
5658f11c308ee807e7a7e39b63ae22b28f1b6fc5
|
/ECOMPLUS/test_s60v3fp0/testcomponent/src/DLLMain.cpp
|
9a62612c6d276383b082c4aa540e205c5258b8c6
|
[] |
no_license
|
michaelmaguire/ecomplus
|
83222f2d4b7023ae7df4e183f08db60f2d920faf
|
6b30cd67a9a58f2a87d8137cfaae6ece2b2e6008
|
refs/heads/master
| 2021-01-10T19:50:57.833227 | 2010-01-21T22:27:49 | 2010-01-21T22:27:49 | 32,109,737 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 1,424 |
cpp
|
/**
*
* Copyright © 2004 Michael Maguire.
*
* You are hereby granted free use of the software in this file,
* provided you maintain this entire copyright notice at the top.
*
* This software is provided "as is," and the copyright holder
* makes no representations or warranties, express or implied,
* including but not limited to warranties of merchantability or
* fitness for any particular purpose or that the use of this software
* or documentation will not infringe any third party patents,
* copyrights, trademarks or other rights.
*
* The copyright holder will not be liable for any direct, indirect
* special or consequential damages arising out of any use of this
* software or documentation.
*
*/
#include <e32base.h>
//#include <e32std.h>
#include <ecom/implementationproxy.h>
#include "TestComponent.h"
// Provides a key value pair table, this is used to identify
// the correct construction function for the requested interface.
const TImplementationProxy ImplementationTable[] =
{
{{KCID_MTestInterface}, CTestComponent::NewL}
};
// Function used to return an instance of the proxy table.
EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
{
aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
return ImplementationTable;
}
// DLL Entry point
GLDEF_C TInt E32Dll()
{
return(KErrNone);
}
|
[
"michael.maguire@34284986-6d7c-11de-84e2-6792fbbe797f"
] |
[
[
[
1,
48
]
]
] |
3b72db69a0da6938f6d415ab16188ccc39289ee7
|
cd0987589d3815de1dea8529a7705caac479e7e9
|
/webkit/WebKitTools/DumpRenderTree/chromium/DRTDevToolsClient.h
|
73ae861f667361a12632a6ea695fad1d16e995f5
|
[] |
no_license
|
azrul2202/WebKit-Smartphone
|
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
|
023d6fe819445369134dee793b69de36748e71d7
|
refs/heads/master
| 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,352 |
h
|
/*
* Copyright (C) 2010 Google 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DRTDevToolsClient_h
#define DRTDevToolsClient_h
#include "DRTDevToolsCallArgs.h"
#include "Task.h"
#include "public/WebDevToolsFrontendClient.h"
#include <wtf/Noncopyable.h>
#include <wtf/OwnPtr.h>
namespace WebKit {
class WebDevToolsFrontend;
struct WebDevToolsMessageData;
class WebString;
class WebView;
} // namespace WebKit
class DRTDevToolsAgent;
class DRTDevToolsClient : public WebKit::WebDevToolsFrontendClient
, public Noncopyable {
public:
DRTDevToolsClient(DRTDevToolsAgent*, WebKit::WebView*);
virtual ~DRTDevToolsClient();
void reset();
// WebDevToolsFrontendClient implementation
virtual void sendFrontendLoaded();
virtual void sendMessageToBackend(const WebKit::WebString&);
virtual void sendDebuggerCommandToAgent(const WebKit::WebString& command);
virtual void activateWindow();
virtual void closeWindow();
virtual void dockWindow();
virtual void undockWindow();
void asyncCall(const DRTDevToolsCallArgs&);
void allMessagesProcessed();
TaskList* taskList() { return &m_taskList; }
private:
void call(const DRTDevToolsCallArgs&);
class AsyncCallTask: public MethodTask<DRTDevToolsClient> {
public:
AsyncCallTask(DRTDevToolsClient* object, const DRTDevToolsCallArgs& args)
: MethodTask<DRTDevToolsClient>(object), m_args(args) {}
virtual void runIfValid() { m_object->call(m_args); }
private:
DRTDevToolsCallArgs m_args;
};
TaskList m_taskList;
WebKit::WebView* m_webView;
DRTDevToolsAgent* m_drtDevToolsAgent;
WTF::OwnPtr<WebKit::WebDevToolsFrontend> m_webDevToolsFrontend;
};
#endif // DRTDevToolsClient_h
|
[
"[email protected]"
] |
[
[
[
1,
90
]
]
] |
c356d3d74b1537f222332aa18a518eae6af6d89a
|
c3531ade6396e9ea9c7c9a85f7da538149df2d09
|
/Param/src/OpenGL/GLElement.h
|
47e06dfa627ca8cea37bc85de2e4a8fd32eda662
|
[] |
no_license
|
feengg/MultiChart-Parameterization
|
ddbd680f3e1c2100e04c042f8f842256f82c5088
|
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
|
refs/heads/master
| 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,229 |
h
|
#ifndef GLELEMENT_H_
#define GLELEMENT_H_
class QGLWidget;
#include "../Common/BasicDataType.h"
#include "../Numerical/matrix.h"
#ifdef WIN32
#include <GL/GLAux.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
/* ================== Macros ================== */
// Material macros
#define MATERIAL_AMBIENT 0X00000001
#define MATERIAL_DIFFUSE 0X00000002
#define MATERIAL_SPECULAR 0X00000003
#define MATERIAL_EMISSION 0X00000004
#define MATERIAL_SHININESS 0X00000005
// Light macros
#define LIGHT_TYPE_DIRECTIONAL 0X0000001
#define LIGHT_TYPE_SPOT 0X0000001
#define LIGHT_TYPE_POINT 0X0000002
#define LIGHT_AMBIENT 0X00000001
#define LIGHT_DIFFUSE 0X00000002
#define LIGHT_SPECULAR 0X00000003
#define LIGHT_POSITION 0X00000004
#define LIGHT_SPOT_DIRECTION 0X00000005
#define LIGHT_SPOT_EXPONENT 0X00000006
#define LIGHT_SPOT_CUTOFF 0X00000007
#define LIGHT_CONSTANT_ATTENUATION 0X00000008
#define LIGHT_LINEAR_ATTENUATION 0X00000009
#define LIGHT_QUADRATIC_ATTENUATION 0X0000000A
// Projection macros
#define PROJECTION_TYPE_ORTHOGONAL 0X00000001
#define PROJECTION_TYPE_PERSPECTIVE 0X00000002
#define CHECK_IMAGE_WIDTH 64
#define CHECK_IMAGE_HEIGHT 64
/* ================== Material Information ================== */
class GLMaterial
{
public:
float ambient[4];
float diffuse[4];
float specular[4];
float emission[4];
float shininess;
unsigned int face;
public:
// Constructor
GLMaterial();
GLMaterial(const GLMaterial& material);
// Destructor
~GLMaterial();
// Initializer
void ClearData();
// Set material value
void SetValue(int pname, float* param);
// Set material
void SetMaterial();
};
/* ================== Light Information ================== */
class GLLight
{
public:
float type;
float ambient[4];
float diffuse[4];
float specular[4];
float position[4];
float direction[3];
float exponent;
float cutoff;
float constant_attenuation;
float linear_attenuation;
float quadratic_attenuation;
unsigned int lightID;
public:
// Constructor
GLLight();
// Destructor
~GLLight();
// Initializer
void ClearData();
// Set light value
void SetValue(int pname, float* param);
// Set light
void SetLight();
};
/* ================== Projection Information ================== */
class GLProjection
{
private:
double vv_left; // Viewing volume (vv) left
double vv_right;
double vv_top;
double vv_bottom;
double vv_near;
double vv_far;
int type;
double fov;
double aspect;
int vp_left; // Viewport (vp) left
int vp_right;
int vp_top;
int vp_bottom;
double object_center[3];
double object_radius;
double object_ratio;
public:
// Constructor
GLProjection();
// Destructor
~GLProjection();
// Initializer
void ClearData();
// Set object information
void SetObjectInfo(double cx, double cy, double cz, double r);
// Set projection
void SetProjection(int width, int height);
void SetProjection(int left, int right, int top, int bottom);
// Zoom
void Zoom(double scale);
};
/* ================== OpenGL Element Information ================== */
class COpenGL
{
public:
double m_BkColor[4]; // Background color (rgba)
GLMaterial m_Material; // OpenGL material structure
GLLight m_Light; // OpenGL lighting structure
GLProjection m_Projection; // OpenGL projection structure
CMatrix m_ModelViewMatrix;
QGLWidget* m_GLContext;
private:
GLuint texName;
GLubyte checkImage[CHECK_IMAGE_WIDTH][CHECK_IMAGE_HEIGHT][4];
public:
// Constructor
COpenGL();
// Destructor
~COpenGL();
// Initializer
void ClearData();
// Debug
bool DetectOpenGLError();
// Message handlers
void OnCreate(QGLWidget* glWidget);
void OnResize(int width, int height);
void OnReset(int width, int height);
void OnInit();
void OnBeginPaint();
void OnEndPaint();
void OnDestroy();
// OpenGL basic operations.
void Project(Coord pos, Coord& eye);
void UnProject(Coord eye, Coord& pos);
void GetDepth(int x, int y, float& depth);
void GetWorldCoord(int x, int y, Coord& pos);
void GetViewPort(int viewport[4]);
// Set object information
void SetObjectInfo(double cx, double cy, double cz, double r);
// get/set/apply model view matrix.
CMatrix GetModelViewMatrix();
void SetModelViewMatrix(CMatrix& mvmatrix);
void SetModelView();
// load/save model view matrix and project matrix.
bool LoadGLMatrix(std::string filename);
bool SaveGLMatrix(std::string filename);
void Create2DTexture(int type);
void MakeCheckImage();
void MakeLineImage();
void MakeBoundaryImage();
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
240
]
]
] |
c96496b3215d975125b4c357587ec0f0f8cf3f04
|
faacd0003e0c749daea18398b064e16363ea8340
|
/modules/mp3player/database.cpp
|
21b2b7702b983f3fa78cea336ae9056f19864200
|
[] |
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 | 4,305 |
cpp
|
/*
* Copyright (C) 2008-2009 Pavlov Denis
*
* Comments unavailable.
*
* 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 any later version.
*
*/
#include "database.h"
/*
* Works with database of mp3 files. The db stores tags and file paths to make it faster.
*/
mp3playerDatabase::mp3playerDatabase(QObject *parent) {
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(QDir::toNativeSeparators(QDir::homePath()+"/data.sqlite"));
bool ok = m_db.open();
if(!ok) {
qDebug() << "mp3player: Can't open database of media files!";
m_db_ok = false;
return;
} else {
qDebug() << "mp3player: Using sqlite database. It's ok!";
QSqlQuery query(m_db);
if(!query.exec("select * from tracks limit 1;")) {
qDebug() << "Trying to create table.";
QFile file("./conf/mp3player.sql");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QString q;
while (!file.atEnd()) { q += file.readLine(); }
if(!query.exec(q)) {
qDebug() << "mp3player: Tried to create table in database but failed. Won't use sqlite!";
m_db_ok = false;
} else {
qDebug() << "mp3player: Database successfully created!";
m_db_ok = true;
}
}
}
}
mp3playerDatabase::~mp3playerDatabase() {
m_db.close();
}
/*
* Adds a track to DB
*/
void mp3playerDatabase::addTrack(
QString fileName,
QString artist,
QString album,
QString trackName,
QString duration) {
QSqlQuery query(m_db);
query.prepare("insert into tracks (filename, artist, album, trackname, duration) values (:fileName, :artist, :album, :trackName, :duration);");
query.bindValue(":fileName", fileName);
query.bindValue(":artist", artist);
query.bindValue(":album", album);
query.bindValue(":trackName", trackName);
query.bindValue(":duration", duration);
if(!query.exec()) {
qDebug() << "mp3player: Can't add a track" << fileName << "to database!";
}
}
/*
* When track already exists in DB but some tag fields are have been changed updates them.
*/
void mp3playerDatabase::updateTrack(
QString fileName,
QString artist,
QString album,
QString trackName,
QString duration) {
QSqlQuery query(m_db);
query.prepare("update tracks set artist = :artist, album = :album, trackname = :trackName, duration = :duration where filename = :fileName;");
query.bindValue(":fileName", fileName);
query.bindValue(":artist", artist);
query.bindValue(":album", album);
query.bindValue(":trackName", trackName);
query.bindValue(":duration", duration);
if(!query.exec()) {
qDebug() << "mp3player: Can't update track" << fileName << "to database!";
}
}
/*
* Checks if the track data record exists in db
*/
bool mp3playerDatabase::ifExists(QString fileName) {
QSqlQuery query(m_db);
fileName = fileName.replace("'", "\\'");
QString q = QString("select filename from tracks where filename = '%1' limit 1;").arg(fileName);
qDebug() << "Query is" << q;
if(!query.exec(q)) {
qDebug() << "mp3player: Database track existance check failed!";
return false;
} else {
if(query.first()) {
qDebug() << "File" << fileName << "found in database!";
return true;
} else {
qDebug() << "File" << fileName << "NOT found in database!";
return false;
}
}
}
/*
* Gets track information.
*/
ATrackData mp3playerDatabase::getTrack(QString fileName) {
ATrackData td;
td.artist = "Unknown";
td.album = "Unknown";
td.trackName = fileName;
QSqlQuery query(m_db);
QString q = QString("select filename, artist, album, trackname from tracks where filename = '%1' limit 1;").arg(fileName);
if(!query.exec(q)) {
qDebug() << "mp3player: Database track existance check failed!";
} else {
if(query.first()) {
td.artist = query.value(1).toString();
td.album = query.value(2).toString();
td.trackName = query.value(3).toString();
}
}
return td;
}
|
[
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
] |
[
[
[
1,
138
]
]
] |
b70f4c38023cfe0e7d425c7a407b1fd9cc72a5a2
|
638c9b075ac3bfdf3b2d96f1dd786684d7989dcd
|
/spark/source/SpString.cpp
|
518b01cd977e3420a75a39d30d98b45be83842fd
|
[] |
no_license
|
cycle-zz/archives
|
4682d6143b9057b21af9845ecbd42d7131750b1b
|
f92b677342e75e5cb7743a0d1550105058aff8f5
|
refs/heads/master
| 2021-05-27T21:07:16.240438 | 2010-03-18T08:01:46 | 2010-03-18T08:01:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,947 |
cpp
|
// headers
#include "SpString.h"
// ---------------------------------------------------------------------------
using namespace Spark;
// ---------------------------------------------------------------------------
// Static Declarations:
// ---------------------------------------------------------------------------
const SpString SpString::EMPTY = "";
// ---------------------------------------------------------------------------
// Construction:
// ---------------------------------------------------------------------------
SpString::SpString() : SpStringBase()
{
// EMPTY!
}
// ---------------------------------------------------------------------------
SpString::SpString(const SpString& rkStr) :
SpStringBase( static_cast< const SpStringBase& >(rkStr) )
{
// EMPTY!
}
// ---------------------------------------------------------------------------
SpString::SpString( const SpStringBase& rkStr )
: SpStringBase( rkStr )
{
// EMPTY!
}
// ---------------------------------------------------------------------------
SpString::SpString( const char* pacStr )
: SpStringBase( pacStr )
{
// EMPTY!
}
// ---------------------------------------------------------------------------
SpString::SpString( const char* pacStr, SpString::SizeType kLength )
: SpStringBase( pacStr, kLength )
{
// EMPTY!
}
// ---------------------------------------------------------------------------
SpString::SpString(const SpString& rkStr, SizeType kStart, SizeType kEnd)
: SpStringBase( rkStr, kStart, kEnd )
{
// EMPTY@
}
// ---------------------------------------------------------------------------
SpString::SpString( SpString::SizeType kLength, char c )
: SpStringBase( kLength, c )
{
// EMPTY!
}
// ---------------------------------------------------------------------------
void SpString::clear()
{
resize(0);
}
// ---------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
61
]
]
] |
e39cdd5817bdaf515a75eebf39ded9529ba357f2
|
5095bbe94f3af8dc3b14a331519cfee887f4c07e
|
/Shared/Components/Data/apsdata.cpp
|
cf9732dff328f9c564b901fb70d77b2177fc527d
|
[] |
no_license
|
sativa/apsim_development
|
efc2b584459b43c89e841abf93830db8d523b07a
|
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
|
refs/heads/master
| 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,081 |
cpp
|
//---------------------------------------------------------------------------
#include <general\pch.h>
#include <vcl.h>
#pragma hdrstop
USEFORM("TAPSTable_form.cpp", APSTable_form);
USEFORM("TAnalysis_form.cpp", Analysis_form);
USEFORM("TSummary_form.cpp", Summary_form);
USEFORM("TProbability_analysis_form.cpp", Probability_analysis_form);
USEFORM("TTime_series_form.cpp", Time_series_form);
USEFORM("TDifference_form.cpp", Difference_form);
USEFORM("TFrequency_form.cpp", Frequency_form);
USEFORM("TPie_frequency_form.cpp", Pie_frequency_form);
USEFORM("txy_form.cpp", XY_form);
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
// Package source.
//---------------------------------------------------------------------------
#pragma argsused
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*)
{
return 1;
}
//---------------------------------------------------------------------------
|
[
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] |
[
[
[
1,
26
]
]
] |
77f6f79ee67c14021fdcd517611193566568c11d
|
2f77d5232a073a28266f5a5aa614160acba05ce6
|
/01.DevelopLibrary/04.SmsCode/InfoCenterOfSmartPhone/UiEditControl.h
|
776304a1a8a778f00eff9721f4c70d20cd19f3b6
|
[] |
no_license
|
radtek/mobilelzz
|
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
|
402276f7c225dd0b0fae825013b29d0244114e7d
|
refs/heads/master
| 2020-12-24T21:21:30.860184 | 2011-03-26T02:19:47 | 2011-03-26T02:19:47 | 58,142,323 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 992 |
h
|
#ifndef __UiEditControl_h__
#define __UiEditControl_h__
#define UiEditControl_Click 1001
class UiEditControl: public UiEdit
{
public:
UiEditControl();
virtual ~UiEditControl();
void UpdateData( long lFlag );
//void UpdateTextByRecievers(BOOL bIsAddChar = FALSE, long lWillPos = Invalid_4Byte);
//virtual void OnFocused(UiWin *pWinPrev);
//zds 2010/03/21 19:39
//int OnLButtonUp123 ( UINT fwKeys, int xPos, int yPos );
//zds 2010/03/21 19:39
virtual int OnLButtonUp( UINT fwKeys,
int xPos,
int yPos
);
virtual int OnKeyDown(int nVirtKey, DWORD lKeyData);
//virtual void OnClick( size_t nIndex );
//virtual int OnChar( TCHAR chCharCode, LPARAM lKeyData );
void UpdateRecievers();
void UpdateContactors();
private:
//long GetLinePos();
void ConvertLinePos2RowCol(long lLinePos, long& lRow, long& lCol);
void ConvertRowCol2LinePos(long lRow, long lCol, long& lLinePos);
};
#endif //__UiEditControl_h__
|
[
"lidan8908589@8983de3c-2b35-11df-be6c-f52728ce0ce6",
"[email protected]"
] |
[
[
[
1,
15
],
[
17,
17
],
[
21,
21
],
[
23,
38
]
],
[
[
16,
16
],
[
18,
20
],
[
22,
22
]
]
] |
7b8b3e5473fbec4ac54619da8578599fc16b7b7a
|
a6250264963232300013b985b4cee08d835f8c30
|
/01.HelloWorld/stdafx.cpp
|
f415146d89e10362425cd43e8d688583c7a4bb89
|
[] |
no_license
|
JeffreyZksun/irrlichtbeginner
|
2f0783a324bd11c2b2ec9b8abe5990196ac4bced
|
f1c2dec123ed75a7fcf76d712775bfc69ab51fa7
|
refs/heads/master
| 2021-01-22T11:47:43.204556 | 2011-05-08T04:07:19 | 2011-05-08T04:07:19 | 40,518,879 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 300 |
cpp
|
// stdafx.cpp : source file that includes just the standard includes
// 01.HelloWorld.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
]
]
] |
e81fd93460f61401c2493ba724db732e52a58fae
|
a7513d1fb4865ea56dbc1fcf4584fb552e642241
|
/avl_array/src/detail/aa_size.hpp
|
983db85188ced2e19f45d2d26774c86dc6dec691
|
[
"MIT"
] |
permissive
|
det/avl_array
|
f0cab062fa94dd94cdf12bea4321c5488fb5cdcc
|
d57524a623af9cfeeff060b479cc47285486d741
|
refs/heads/master
| 2021-01-15T19:40:10.287367 | 2010-05-06T13:13:35 | 2010-05-06T13:13:35 | 35,425,204 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,956 |
hpp
|
///////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2006-2009, Universidad de Alcala //
// //
// See accompanying LICENSE.TXT //
// //
///////////////////////////////////////////////////////////////////
/*
detail/aa_size.hpp
------------------
Methods related to the size of the tree (get/change size):
size(): retrieve current size (O(1))
empty(): true if empty; false otherwise (O(1))
max_size(): estimated maximum size in theory (O(1))
resize(n): change size (O(min{N, n log N}))
resize(n,t): idem, but add copies of t "
Private helper methods:
resize(n,DP): change size (rebuild) O(max{old_size,new_size})
*/
#ifndef _AVL_ARRAY_SIZE_HPP_
#define _AVL_ARRAY_SIZE_HPP_
#ifndef _AVL_ARRAY_HPP_
#error "Don't include this file. Include avl_array.hpp instead."
#endif
namespace mkr // Public namespace
{
//////////////////////////////////////////////////////////////////
// ---------------------- PUBLIC INTERFACE -----------------------
// size(): number of elements contained
//
// Complexity: O(1)
template<class T,class A,bool bW,class W,bool bP,class P>
inline
typename avl_array<T,A,bW,W,bP,P>::size_type
avl_array<T,A,bW,W,bP,P>::size () const
{
return node_t::m_count-1;
}
// empty(): inform of whether the container is empty or not
//
// Complexity: O(1)
template<class T,class A,bool bW,class W,bool bP,class P>
inline
bool
avl_array<T,A,bW,W,bP,P>::empty () const
{
return size()==0;
}
// max_size(): estimated maximum size (in theory) supposing
// that a whole address space is available (which is
// obviously impossible) and taking into account that
// end()-begin() should fit in difference_type
//
// Complexity: O(1)
template<class T,class A,bool bW,class W,bool bP,class P>
//not inline
typename avl_array<T,A,bW,W,bP,P>::size_type
avl_array<T,A,bW,W,bP,P>::max_size ()
{
// If pointers are smaller or eq.
// to size_type, the limit is
// imposed by the address space
if (sizeof(void*)<=sizeof(size_type))
return ( ( size_type(1) <<
((sizeof(void*)<<3)-1) ) /
sizeof(payload_node_t) ) << 1;
size_type mxp, mxu, r, mn; // Otherwise, it depends on
// the sizes ratio
mxp = ( ( size_type(1) <<
((sizeof(size_type)<<3)-1) ) /
sizeof(payload_node_t) ) << 1;
mn = sizeof(difference_type) < sizeof(size_type) ?
sizeof(difference_type) : sizeof(size_type);
mxu = size_type(1) << ((mn<<3)-2);
r = ( sizeof(void*) - // Using r we avoid
sizeof(size_type) ) << 3; // overflow on mxp
return (mxu>>r) < mxp ? // If the index type size is more
mxu : // restrictive, choose it. Otherwise
(mxp<<r); // choose the address space limit
}
// resize(): change the size of the avl_array, deleting
// elements from the end, or appending copies of t
// (depending on the specified new size n)
//
// Complexity: (O(min{N, n log N}))
template<class T,class A,bool bW,class W,bool bP,class P>
//not inline
void
avl_array<T,A,bW,W,bP,P>::resize
(typename avl_array<T,A,bW,W,bP,P>::size_type n,
typename avl_array<T,A,bW,W,bP,P>::const_reference t)
{
size_type sz=size(); // If there's a big
// difference with
if (n<=0) // respect to the
clear (); // current size, resize
else if ((n>sz && // building (linking)
worth_rebuild(n-sz,sz)) || // the whole tree again
(n<sz &&
worth_rebuild(sz-n,sz,true)))
{
copy_data_provider<const_pointer> dp(&t);
resize (n, dp);
}
else if (n>sz) // If the difference
insert (end(), n-size(), t); // is small,
else if (n<sz) // append or remove
erase (begin()+n, end()); // elements one by one
}
// resize(): change the size of the avl_array, deleting
// elements from the end, or appending default constructed
// T objects (depending on the specified new size n)
//
// Complexity: (O(min{N, n log N}))
template<class T,class A,bool bW,class W,bool bP,class P>
//not inline
void
avl_array<T,A,bW,W,bP,P>::resize
(typename avl_array<T,A,bW,W,bP,P>::size_type n)
{
null_data_provider<const_pointer> dp;
node_t * first, * last, * p;
size_type sz=size(); // If there's a big
// difference with
if (n<=0) // respect to the
clear (); // current size, resize
else if ((n>sz && // building (linking)
worth_rebuild(n-sz,sz)) || // the whole tree again
(n<sz &&
worth_rebuild(sz-n,sz,true)))
resize (n, dp);
else if (n<sz) // Otherwise append or
erase (begin()+n, end()); // remove elements one
else if (n>sz) // by one
{
construct_nodes_list (first, last, n-sz, dp, false);
while (first)
{
p = first;
first = first->m_next;
insert_before (p, dummy());
}
}
}
// ------------------- PRIVATE HELPER METHODS --------------------
// resize(n,DP): change the size of the avl_array, deleting
// elements from the end, or appending new elements
// (depending on the specified new size n).
// Do it rebuilding the whole tree in all cases
//
// Complexity: O(max{old_size,new_size})
template<class T,class A,bool bW,class W,bool bP,class P>
template<class DP>
void
avl_array<T,A,bW,W,bP,P>::resize
(typename avl_array<T,A,bW,W,bP,P>::size_type n,
DP & dp)
{
node_t * first, * last;
node_t * p, * next;
// Build a new tree adding
if (n>size()) // and/or recycling nodes
{
construct_nodes_list (first, last, n-size(), dp);
node_t::m_prev->m_next = first;
build_known_size_tree (n, node_t::m_next);
}
else
{
node_t::m_prev->m_next = NULL;
next = build_known_size_tree (n, node_t::m_next);
while (next) // Destruct remaining
{ // old elements
p = next;
next = next->m_next;
delete_node (p);
}
}
}
//////////////////////////////////////////////////////////////////
} // namespace mkr
#endif
|
[
"martin@cobete"
] |
[
[
[
1,
218
]
]
] |
3c4022597747a1ea149e205cbc79eaae53077e2b
|
c6f4fe2766815616b37beccf07db82c0da27e6c1
|
/LinearMovement.h
|
3d6a66ef0fe08bd9dcd16b9871b6bf891d4c9aac
|
[] |
no_license
|
fragoulis/gpm-sem1-spacegame
|
c600f300046c054f7ab3cbf7193ccaad1503ca09
|
85bdfb5b62e2964588f41d03a295b2431ff9689f
|
refs/heads/master
| 2023-06-09T03:43:53.175249 | 2007-12-13T03:03:30 | 2007-12-13T03:03:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,240 |
h
|
#pragma once
#include "movement.h"
namespace tlib
{
class OCLinearMovement : public IOCMovement
{
protected:
// The velocity of the object
float m_fVelocity;
public:
/**
* Constructors
*/
OCLinearMovement();
OCLinearMovement( float fVel, const Vector3f& vDir );
/**
* Destructor
*/
virtual ~OCLinearMovement(){}
/**
* Returns the unique component ID
*/
const string componentID() const {
return string("linearmovement");
}
/**
* Returns the velocity of the object associated with this component
*/
float getVelocity() const { return m_fVelocity; }
/**
* Sets the velocity of the object
*/
void setVelocity( float vel ) { m_fVelocity = vel; }
/**
* Alters the velocity of the object
*/
void addVelocity( float scalar ) { m_fVelocity += scalar; }
/**
* Updates the object's position
*/
virtual void update();
}; // end of OCLinearMovement class
} // end of namespace tlib
|
[
"john.fragkoulis@201bd241-053d-0410-948a-418211174e54"
] |
[
[
[
1,
55
]
]
] |
7e2ebe13b10eb8c2b5539380cf16d8b6fb82fcd4
|
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
|
/Demo/Loader.h
|
b849a9bd7cd3ef6d9b6bd21125b517ad208d8078
|
[] |
no_license
|
BackupTheBerlios/ejvm
|
7258cd180256970d57399d0c153d00257dbb127c
|
626602de9ed55a825efeefd70970c36bcef0588d
|
refs/heads/master
| 2020-06-11T19:47:07.882834 | 2006-07-10T16:39:59 | 2006-07-10T16:39:59 | 39,960,044 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,189 |
h
|
#ifndef LOADER_H_
#define LOADER_H_
#include "typeDefs.h"
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
class ClassData;
class Object;
class Loader
{
public:
static Loader * getInstance();//finished
static void deleteLoader();
/**
* psudoCode:
* if(!(classData=lookupdClassData(className)))
* u1[] classFile = classFiel2bytes(className);
* classData = Heap->createClassData(classFile);
* return classData;
*/
ClassData * getClassData(const char * className);
/**
* if success return pointer to the loaded classData
* if failed return NULL
*/
/**
* This function searches for the className, if found return pointer to the ClassData, if not found create the classData
* by the given array instead of opening any files....
*/
ClassData * getClassData(const char * className, const byte classFile[]){
//This function should be implemented, for now it will return NULL;
return NULL;
}
private:
~Loader(){/*cout<<"Loader destructor"<<endl;*/;}
Loader();
byte * makeArrayInCPP(char * fileName);
static Loader * loaderInstance;
};
#endif /*LOADER_H_*/
|
[
"almahallawy"
] |
[
[
[
1,
48
]
]
] |
2530106b9b6d6d1c0d4c69aa95ec422abf09a39a
|
1775576281b8c24b5ce36b8685bc2c6919b35770
|
/trunk/side_edit.cpp
|
1376ed1a36e0b7924a4642b4c6ed1480eb3c0497
|
[] |
no_license
|
BackupTheBerlios/gtkslade-svn
|
933a1268545eaa62087f387c057548e03497b412
|
03890e3ba1735efbcccaf7ea7609d393670699c1
|
refs/heads/master
| 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 15,627 |
cpp
|
#include "main.h"
#include "map.h"
#include "checks.h"
#include "editor_window.h"
#include "tex_box.h"
#include "tex_browser.h"
struct side_data
{
bool xoff_consistent;
bool yoff_consistent;
bool sector_consistent;
int x_offset;
int y_offset;
int sector;
string tex_middle;
string tex_upper;
string tex_lower;
tex_box_t *tbox_upper;
tex_box_t *tbox_middle;
tex_box_t *tbox_lower;
vector<GtkWidget*> widgets;
side_data()
{
x_offset = y_offset = -1;
tex_middle = tex_upper = tex_lower = "";
xoff_consistent = yoff_consistent = true;
}
};
side_data side1;
side_data side2;
//GtkWidget *side1_edit = NULL;
//GtkWidget *side2_edit = NULL;
extern Map map;
extern GtkWidget *editor_window;
extern vector<int> selected_items;
extern int hilight_item;
static gboolean tex_box_clicked(GtkWidget *widget, GdkEventButton *event, gpointer data)
{
GtkEntry *entry = (GtkEntry*)data;
string tex;
if (event->button == 1)
{
tex = open_texture_browser(true, false, false, gtk_entry_get_text(entry));
gtk_entry_set_text(entry, tex.c_str());
}
return true;
}
void tex_upper_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string tex = str_upper(gtk_entry_get_text(entry));
gtk_entry_set_text(entry, tex.c_str());
sdat->tex_upper = tex;
if (tex == "-")
tex = "";
sdat->tbox_upper->change_texture(tex, sdat->tbox_upper->textype, sdat->tbox_upper->scale);
}
void tex_middle_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string tex = str_upper(gtk_entry_get_text(entry));
gtk_entry_set_text(entry, tex.c_str());
sdat->tex_middle = tex;
if (tex == "-")
tex = "";
sdat->tbox_middle->change_texture(tex, sdat->tbox_middle->textype, sdat->tbox_middle->scale);
}
void tex_lower_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string tex = str_upper(gtk_entry_get_text(entry));
gtk_entry_set_text(entry, tex.c_str());
sdat->tex_lower = tex;
if (tex == "-")
tex = "";
sdat->tbox_lower->change_texture(tex, sdat->tbox_lower->textype, sdat->tbox_lower->scale);
}
void xoff_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string val = gtk_entry_get_text(entry);
if (val == "")
sdat->xoff_consistent = false;
else
{
sdat->xoff_consistent = true;
sdat->x_offset = atoi(val.c_str());
}
}
void yoff_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string val = gtk_entry_get_text(entry);
if (val == "")
sdat->yoff_consistent = false;
else
{
sdat->yoff_consistent = true;
sdat->y_offset = atoi(val.c_str());
}
}
void sector_ref_changed(GtkEditable *editable, gpointer data)
{
side_data *sdat = (side_data*)data;
GtkEntry *entry = (GtkEntry*)editable;
string val = gtk_entry_get_text(entry);
if (val == "")
sdat->sector_consistent = false;
else
{
sdat->sector_consistent = true;
sdat->sector = atoi(val.c_str());
}
}
GtkWidget* setup_side_edit(int side)
{
GtkWidget *widget = NULL;
int line = -1;
bool side_exists = false;
side_data* sdat = NULL;
// Setup data
if (side == 1)
sdat = &side1;
else
sdat = &side2;
sdat->widgets.clear();
sdat->xoff_consistent = true;
sdat->yoff_consistent = true;
sdat->sector_consistent = true;
if (selected_items.size() == 0)
{
if (map.l_getside(hilight_item, side))
{
sdat->x_offset = map.l_getside(hilight_item, side)->x_offset;
sdat->y_offset = map.l_getside(hilight_item, side)->y_offset;
sdat->sector = map.l_getside(hilight_item, side)->sector;
sdat->tex_lower = map.l_getside(hilight_item, side)->tex_lower;
sdat->tex_middle = map.l_getside(hilight_item, side)->tex_middle;
sdat->tex_upper = map.l_getside(hilight_item, side)->tex_upper;
line = hilight_item;
side_exists = true;
}
}
else
{
// Find the first selected line with an existing side
for (int a = 0; a < selected_items.size(); a++)
{
if (map.l_getside(selected_items[a], side))
{
sdat->x_offset = map.l_getside(selected_items[a], side)->x_offset;
sdat->y_offset = map.l_getside(selected_items[a], side)->y_offset;
sdat->sector = map.l_getside(selected_items[a], side)->sector;
sdat->tex_lower = map.l_getside(selected_items[a], side)->tex_lower;
sdat->tex_middle = map.l_getside(selected_items[a], side)->tex_middle;
sdat->tex_upper = map.l_getside(selected_items[a], side)->tex_upper;
side_exists = true;
line = selected_items[a];
break;
}
}
// Check consistency
for (int a = 0; a < selected_items.size(); a++)
{
if (map.l_getside(selected_items[a], side))
{
if (sdat->xoff_consistent && sdat->x_offset != map.l_getside(selected_items[a], side)->x_offset)
sdat->xoff_consistent = false;
if (sdat->yoff_consistent && sdat->y_offset != map.l_getside(selected_items[a], side)->y_offset)
sdat->yoff_consistent = false;
if (sdat->sector_consistent && sdat->sector != map.l_getside(selected_items[a], side)->sector)
sdat->sector_consistent = false;
if (sdat->tex_middle != "" && sdat->tex_middle != map.l_getside(selected_items[a], side)->tex_middle)
sdat->tex_middle = "";
if (sdat->tex_upper != "" && sdat->tex_upper != map.l_getside(selected_items[a], side)->tex_upper)
sdat->tex_upper = "";
if (sdat->tex_lower != "" && sdat->tex_lower != map.l_getside(selected_items[a], side)->tex_lower)
sdat->tex_lower = "";
}
}
}
widget = gtk_vbox_new(false, 0);
// Textures frame
GtkWidget *frame = gtk_frame_new("Textures");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
GtkWidget *hbox = gtk_hbox_new(true, 0);
gtk_container_add(GTK_CONTAINER(frame), hbox);
/*
delete sdat->tbox_upper;
delete sdat->tbox_middle;
delete sdat->tbox_lower;
*/
if (!sdat->tbox_upper)
sdat->tbox_upper = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
else
{
sdat->tbox_upper->setup_widget();
sdat->tbox_upper->change_texture("", 1, 2.0f, false);
}
if (!sdat->tbox_lower)
sdat->tbox_lower = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
else
{
sdat->tbox_lower->setup_widget();
sdat->tbox_lower->change_texture("", 1, 2.0f, false);
}
if (!sdat->tbox_middle)
sdat->tbox_middle = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
else
{
sdat->tbox_middle->setup_widget();
sdat->tbox_middle->change_texture("", 1, 2.0f, false);
}
// Upper tex
GtkWidget *vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
//sdat->tbox_upper = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
sdat->tbox_upper->set_size(96, 96);
gtk_box_pack_start(GTK_BOX(vbox), sdat->tbox_upper->widget, true, true, 0);
GtkWidget *entry = gtk_entry_new();
gtk_widget_set_size_request(entry, 96, -1);
sdat->widgets.push_back(entry);
gtk_entry_set_alignment(GTK_ENTRY(entry), 0.5);
gtk_entry_set_text(GTK_ENTRY(entry), sdat->tex_upper.c_str());
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(tex_upper_changed), sdat);
gtk_box_pack_start(GTK_BOX(vbox), entry, false, false, 4);
gtk_box_pack_start(GTK_BOX(hbox), vbox, true, true, 0);
gtk_widget_set_events(sdat->tbox_upper->widget, GDK_BUTTON_PRESS_MASK);
if (side_exists)
g_signal_connect(G_OBJECT(sdat->tbox_upper->widget), "button_press_event", G_CALLBACK(tex_box_clicked), entry);
// Middle tex
vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
//sdat->tbox_middle = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
sdat->tbox_middle->set_size(96, 96);
gtk_box_pack_start(GTK_BOX(vbox), sdat->tbox_middle->widget, true, true, 0);
entry = gtk_entry_new();
gtk_widget_set_size_request(entry, 96, -1);
sdat->widgets.push_back(entry);
gtk_entry_set_alignment(GTK_ENTRY(entry), 0.5);
gtk_entry_set_text(GTK_ENTRY(entry), sdat->tex_middle.c_str());
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(tex_middle_changed), sdat);
gtk_box_pack_start(GTK_BOX(vbox), entry, false, false, 4);
gtk_box_pack_start(GTK_BOX(hbox), vbox, true, true, 4);
gtk_widget_set_events(sdat->tbox_middle->widget, GDK_BUTTON_PRESS_MASK);
if (side_exists)
g_signal_connect(G_OBJECT(sdat->tbox_middle->widget), "button_press_event", G_CALLBACK(tex_box_clicked), entry);
// Lower tex
vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
//sdat->tbox_lower = new tex_box_t("", 1, 2.0f, rgba_t(180, 180, 180, 255, 0));
sdat->tbox_lower->set_size(96, 96);
gtk_box_pack_start(GTK_BOX(vbox), sdat->tbox_lower->widget, true, true, 0);
entry = gtk_entry_new();
gtk_widget_set_size_request(entry, 96, -1);
sdat->widgets.push_back(entry);
gtk_entry_set_alignment(GTK_ENTRY(entry), 0.5);
gtk_entry_set_text(GTK_ENTRY(entry), sdat->tex_lower.c_str());
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(tex_lower_changed), sdat);
gtk_box_pack_start(GTK_BOX(vbox), entry, false, false, 4);
gtk_box_pack_start(GTK_BOX(hbox), vbox, true, true, 4);
gtk_widget_set_events(sdat->tbox_lower->widget, GDK_BUTTON_PRESS_MASK);
if (side_exists)
g_signal_connect(G_OBJECT(sdat->tbox_lower->widget), "button_press_event", G_CALLBACK(tex_box_clicked), entry);
if (line != -1)
{
if (map.l_needsuptex(line, side) || sdat->tex_upper != "-")
sdat->tbox_upper->change_texture(sdat->tex_upper, 1, 2.0f, false);
if (map.l_needsmidtex(line, side) || sdat->tex_middle != "-")
sdat->tbox_middle->change_texture(sdat->tex_middle, 1, 2.0f, false);
if (map.l_needslotex(line, side) || sdat->tex_lower != "-")
sdat->tbox_lower->change_texture(sdat->tex_lower, 1, 2.0f, false);
}
gtk_box_pack_start(GTK_BOX(widget), frame, true, true, 0);
// Offsets
GtkWidget *hbox2 = gtk_hbox_new(true, 0);
frame = gtk_frame_new("Offsets");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
// X
hbox = gtk_hbox_new(false, 0);
gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new("X:"), false, false, 0);
entry = gtk_entry_new();
sdat->widgets.push_back(entry);
gtk_widget_set_size_request(entry, 32, -1);
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(xoff_changed), sdat);
if (sdat->xoff_consistent)
gtk_entry_set_text(GTK_ENTRY(entry), parse_string("%d", sdat->x_offset).c_str());
gtk_box_pack_start(GTK_BOX(hbox), entry, true, true, 4);
gtk_box_pack_start(GTK_BOX(vbox), hbox, false, false, 0);
// Y
hbox = gtk_hbox_new(false, 0);
gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new("Y:"), false, false, 0);
entry = gtk_entry_new();
sdat->widgets.push_back(entry);
gtk_widget_set_size_request(entry, 32, -1);
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(yoff_changed), sdat);
if (sdat->xoff_consistent)
gtk_entry_set_text(GTK_ENTRY(entry), parse_string("%d", sdat->y_offset).c_str());
gtk_box_pack_start(GTK_BOX(hbox), entry, true, true, 4);
gtk_box_pack_start(GTK_BOX(vbox), hbox, false, false, 4);
gtk_container_add(GTK_CONTAINER(frame), vbox);
gtk_box_pack_start(GTK_BOX(hbox2), frame, true, true, 0);
// Side (create/delete)
frame = gtk_frame_new("Side");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
GtkWidget *button_create = gtk_button_new_with_label("Create");
gtk_box_pack_start(GTK_BOX(vbox), button_create, false, false, 0);
GtkWidget *button_delete = gtk_button_new_with_label("Delete");
sdat->widgets.push_back(button_delete);
gtk_box_pack_start(GTK_BOX(vbox), button_delete, false, false, 0);
gtk_container_add(GTK_CONTAINER(frame), vbox);
gtk_box_pack_start(GTK_BOX(hbox2), frame, true, true, 0);
gtk_box_pack_start(GTK_BOX(widget), hbox2, false, false, 0);
// Sector reference
frame = gtk_frame_new("Sector Reference");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
hbox = gtk_hbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(hbox), 4);
entry = gtk_entry_new();
gtk_widget_set_size_request(entry, 32, -1);
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(sector_ref_changed), sdat);
sdat->widgets.push_back(entry);
if (sdat->sector_consistent)
gtk_entry_set_text(GTK_ENTRY(entry), parse_string("%d", sdat->sector).c_str());
gtk_box_pack_start(GTK_BOX(hbox), entry, true, true, 0);
gtk_container_add(GTK_CONTAINER(frame), hbox);
gtk_box_pack_start(GTK_BOX(widget), frame, false, false, 0);
if (!side_exists)
{
for (int a = 0; a < sdat->widgets.size(); a++)
gtk_widget_set_sensitive(sdat->widgets[a], false);
gtk_widget_set_sensitive(button_create, true);
}
else
gtk_widget_set_sensitive(button_create, false);
return widget;
}
void apply_side_edit()
{
vector<sidedef_t*> side1s;
vector<sidedef_t*> side2s;
// Get sidedefs that are to be modified
if (selected_items.size() == 0)
{
if (map.l_getside(hilight_item, 1))
vector_add_nodup(side1s, map.l_getside(hilight_item, 1));
if (map.l_getside(hilight_item, 2))
vector_add_nodup(side2s, map.l_getside(hilight_item, 2));
}
else
{
for (int a = 0; a < selected_items.size(); a++)
{
if (map.l_getside(selected_items[a], 1))
vector_add_nodup(side1s, map.l_getside(selected_items[a], 1));
if (map.l_getside(selected_items[a], 2))
vector_add_nodup(side2s, map.l_getside(selected_items[a], 2));
}
}
// Upper texture
if (side1.tex_upper != "")
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->tex_upper = side1.tex_upper;
}
if (side2.tex_upper != "")
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->tex_upper = side2.tex_upper;
}
// Middle texture
if (side1.tex_middle != "")
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->tex_middle = side1.tex_middle;
}
if (side2.tex_middle != "")
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->tex_middle = side2.tex_middle;
}
// Lower texture
if (side1.tex_lower != "")
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->tex_lower = side1.tex_lower;
}
if (side2.tex_lower != "")
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->tex_lower = side2.tex_lower;
}
// X Offset
if (side1.xoff_consistent)
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->x_offset = side1.x_offset;
}
if (side2.xoff_consistent)
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->x_offset = side2.x_offset;
}
// Y Offset
if (side1.yoff_consistent)
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->y_offset = side1.y_offset;
}
if (side2.yoff_consistent)
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->y_offset = side2.y_offset;
}
// Sector
if (side1.sector_consistent)
{
for (int a = 0; a < side1s.size(); a++)
side1s[a]->sector = side1.sector;
}
if (side2.sector_consistent)
{
for (int a = 0; a < side2s.size(); a++)
side2s[a]->sector = side2.sector;
}
}
|
[
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
] |
[
[
[
1,
515
]
]
] |
fb809b3e5aa603efa065e3eeadce56bff0e46873
|
096a82f2a4c8dfe4444467b3f55efba278e88022
|
/Voltmeter/Voltmeter.cpp
|
8ce715df599c8bcb6fa1373d2a7fb4eae07c2a27
|
[] |
no_license
|
pulse-cc/Metrology
|
88d9b0140f7fa73f113a6cad26ddf63a94a7350c
|
ca242c465b7a2ddf58e9fb607a66196ca1bdedcb
|
refs/heads/master
| 2021-01-17T05:24:58.113444 | 2011-08-17T12:10:49 | 2011-08-17T12:10:49 | 2,143,670 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,434 |
cpp
|
#include "stdafx.h"
#include "math.h"
#include "PCL_Static.h"
// Do not move or remove: this is required for PCL static objects allocating
static const LRoot LAppRoot(0);
#include "Voltmeter.h"
#include "Calibrator.h"
static Voltmeter *pVRef = new Voltmeter(Voltmeter::REFERENCE);
static Voltmeter *pVVer = new Voltmeter(Voltmeter::VERIFIED);
static Calibrator *pC = getCalibrator();
typedef struct {
double A, B, C;
} data_t;
#define _(X) (((data_t*)m_data)->X)
Voltmeter::Voltmeter(Purpose Which)
{
if (Which == REFERENCE) {
printf("Creating REFERENCE VIRTUAL voltmeter\n");
m_data = new(data_t);
_(A) = 0.05;
_(B) = 0.33;
_(C) = 0.7;
}
else if (Which == VERIFIED) {
printf("Creating VERIFIED VIRTUAL voltmeter\n");
m_data = new(data_t);
_(A) = LRandomFromTo(0.001, 0.01);
_(B) = LRandomFromTo(0.01, 1.);
_(C) = LRandomFromTo(0.01, 0.9);
}
else {
fprintf(stderr, "Unknown voltmeter purpose %d\n", Which);
exit(1);
}
}
Voltmeter::~Voltmeter()
{
delete m_data;
}
VOLTMETER_API Voltmeter *getVoltmeter(Voltmeter::Purpose Which)
{
if (Which == Voltmeter::REFERENCE) return pVRef;
if (Which == Voltmeter::VERIFIED) return pVVer;
fprintf(stderr, "Unknown voltmeter purpose %d\n", Which);
exit(1);
return 0;
}
double Voltmeter::getVoltage()
{
return _(A) * pC->getVoltage() + _(B) * abs(sin((double)pC->getFrequency())*0.01) + _(C);
}
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
56
],
[
58,
58
]
],
[
[
57,
57
]
]
] |
c731d32b3c65ea21730553801991232826507c5d
|
50e6ba037f1c60e5342c707a9d4223ac379a8047
|
/BTDeviceManager.h
|
89eaad3f09ca4af945f36dcc5cf45b9a72b12b50
|
[] |
no_license
|
buryhuang/blueplus
|
299bbe23efa93f9d3acceeedccd5e8194cb71891
|
7843ccfa4b8fc773c6de1992acb9c9bb805671ed
|
refs/heads/master
| 2021-05-06T15:59:40.471142 | 2011-05-31T06:50:46 | 2011-05-31T06:50:46 | 113,696,936 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,935 |
h
|
/** \addtogroup application
* @{
*/
#pragma once
#include "ManagedThread.h"
#include "BlueTooth.h"
#include "BlueToothSocket.h"
#include <map>
using namespace std;
#define DEF_BTDEV_MGR CBTDeviceManager::GetInstance(L"BT Device Manager")
#define DEF_BTDEV_HANDLER CBTDeviceMgrBTHandler::GetInstance()
class CBTDeviceMgrBTHandler :
public CBTHandler
{
public:
CBTDeviceMgrBTHandler(void);
virtual ~CBTDeviceMgrBTHandler(void);
virtual void OnDeviceDiscovered(BTH_ADDR deviceAddr, int deviceClass, wstring deviceName, bool paired);
virtual void OnServiceDiscovered(BTH_ADDR deviceAddr, vector<ServiceRecord>);
static CBTDeviceMgrBTHandler* GetInstance(){
if(m_instance==NULL){
m_instance = new CBTDeviceMgrBTHandler();
}
return m_instance;
}
protected:
static CBTDeviceMgrBTHandler* m_instance;
};
class CDevMgrBTHandlerThread:public CSocketHandler, public CManagedThread
{
public:
CDevMgrBTHandlerThread::CDevMgrBTHandlerThread(wstring name,SOCKADDR_BTH sockaddr)
:CManagedThread(name),m_sockaddrBth(sockaddr){}
virtual void OnAccept(SOCKET s){}
virtual void OnReceive(SOCKET s, BYTEBUFFER buff);
virtual void OnConnect();
virtual void OnClose(){};
virtual int Run();
wstring GetStatusString(){return m_pSocket->GetStatusString();}
CBlueToothSocket::CONNECT_STATUS_T GetStatus(){return m_pSocket->GetStatus();};
private:
SOCKADDR_BTH m_sockaddrBth;
CBlueToothSocket * m_pSocket;
};
class CBTDevice
{
public:
CBTDevice(BTH_ADDR deviceAddr, int deviceClass, wstring deviceName, bool paired);
CDevMgrBTHandlerThread* m_pSockHandler;
BTH_ADDR m_addrBth;
bool m_bPaired;
wstring m_deviceName;
int m_iDeviceClass;
vector<ServiceRecord> m_listService;
};
typedef map<BTH_ADDR, CBTDevice*> BT_DEV_MAP;
class CBTDeviceManager: public CManagedThread
{
public:
CBTDeviceManager(void);
CBTDeviceManager(wstring name):CManagedThread(name){};
virtual ~CBTDeviceManager(void);
virtual int Run();
virtual bool RegisterDevice(CBTDevice* pDevice);
virtual bool RegisterDevice(BTH_ADDR deviceAddr, int deviceClass, wstring deviceName, bool paired);
virtual bool UnregisterDevice(CBTDevice* pDevice);
virtual bool UnregisterDevice(BTH_ADDR deviceAddr);
virtual bool UpdateDevice(BTH_ADDR deviceAddr, int deviceClass, wstring deviceName, bool paired);
virtual bool UpdateDevice(CBTDevice* pDevice);
virtual bool UpdateServices(BTH_ADDR deviceAddr, vector<ServiceRecord> serviceList);
virtual CBlueToothSocket::CONNECT_STATUS_T GetDeviceConnStatus(BTH_ADDR deviceAddr);
virtual BT_DEV_MAP GetDeviceMap();
void ListDevices();
static CBTDeviceManager* GetInstance(wstring name){
if(m_instance==NULL){
m_instance = new CBTDeviceManager(name);
}
return m_instance;
}
protected:
BT_DEV_MAP m_mapBTDevice;
static CBTDeviceManager* m_instance;
HANDLE m_hMutex;
};
/** @}*/
|
[
"[email protected]"
] |
[
[
[
1,
105
]
]
] |
027e0bd5b3ddb430aa4f4c5b22344b5046ce51fd
|
f8403b6b1005f80d2db7fad9ee208887cdca6aec
|
/JuceLibraryCode/modules/juce_gui_basics/lookandfeel/juce_LookAndFeel.h
|
7ac645978c33a4f6b0e7657072aa41363d99b01f
|
[] |
no_license
|
sonic59/JuceText
|
25544cb07e5b414f9d7109c0826a16fc1de2e0d4
|
5ac010ffe59c2025d25bc0f9c02fc829ada9a3d2
|
refs/heads/master
| 2021-01-15T13:18:11.670907 | 2011-10-29T19:03:25 | 2011-10-29T19:03:25 | 2,507,112 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 33,829 |
h
|
/*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
#define __JUCE_LOOKANDFEEL_JUCEHEADER__
#include "../widgets/juce_Slider.h"
#include "../layout/juce_TabbedComponent.h"
#include "../windows/juce_AlertWindow.h"
class ToggleButton;
class TextButton;
class AlertWindow;
class TextLayout;
class ScrollBar;
class ComboBox;
class Button;
class FilenameComponent;
class DocumentWindow;
class ResizableWindow;
class GroupComponent;
class MenuBarComponent;
class DropShadower;
class GlyphArrangement;
class PropertyComponent;
class TableHeaderComponent;
class Toolbar;
class ToolbarItemComponent;
class PopupMenu;
class ProgressBar;
class FileBrowserComponent;
class DirectoryContentsDisplayComponent;
class FilePreviewComponent;
class ImageButton;
class CallOutBox;
class Drawable;
class CaretComponent;
class LayoutLabel;
class FrameLabel;
//==============================================================================
/**
LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
can be used to apply different 'skins' to the application.
*/
class JUCE_API LookAndFeel
{
public:
//==============================================================================
/** Creates the default JUCE look and feel. */
LookAndFeel();
/** Destructor. */
virtual ~LookAndFeel();
//==============================================================================
/** Returns the current default look-and-feel for a component to use when it
hasn't got one explicitly set.
@see setDefaultLookAndFeel
*/
static LookAndFeel& getDefaultLookAndFeel() noexcept;
/** Changes the default look-and-feel.
@param newDefaultLookAndFeel the new look-and-feel object to use - if this is
set to null, it will revert to using the default one. The
object passed-in must be deleted by the caller when
it's no longer needed.
@see getDefaultLookAndFeel
*/
static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
//==============================================================================
/** Looks for a colour that has been registered with the given colour ID number.
If a colour has been set for this ID number using setColour(), then it is
returned. If none has been set, it will just return Colours::black.
The colour IDs for various purposes are stored as enums in the components that
they are relevent to - for an example, see Slider::ColourIds,
Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
If you're looking up a colour for use in drawing a component, it's usually
best not to call this directly, but to use the Component::findColour() method
instead. That will first check whether a suitable colour has been registered
directly with the component, and will fall-back on calling the component's
LookAndFeel's findColour() method if none is found.
@see setColour, Component::findColour, Component::setColour
*/
const Colour findColour (int colourId) const noexcept;
/** Registers a colour to be used for a particular purpose.
For more details, see the comments for findColour().
@see findColour, Component::findColour, Component::setColour
*/
void setColour (int colourId, const Colour& colour) noexcept;
/** Returns true if the specified colour ID has been explicitly set using the
setColour() method.
*/
bool isColourSpecified (int colourId) const noexcept;
//==============================================================================
virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
/** Allows you to change the default sans-serif font.
If you need to supply your own Typeface object for any of the default fonts, rather
than just supplying the name (e.g. if you want to use an embedded font), then
you should instead override getTypefaceForFont() to create and return the typeface.
*/
void setDefaultSansSerifTypefaceName (const String& newName);
//==============================================================================
/** Override this to get the chance to swap a component's mouse cursor for a
customised one.
*/
virtual MouseCursor getMouseCursorFor (Component& component);
//==============================================================================
/** Draws the lozenge-shaped background for a standard button. */
virtual void drawButtonBackground (Graphics& g,
Button& button,
const Colour& backgroundColour,
bool isMouseOverButton,
bool isButtonDown);
virtual const Font getFontForTextButton (TextButton& button);
/** Draws the text for a TextButton. */
virtual void drawButtonText (Graphics& g,
TextButton& button,
bool isMouseOverButton,
bool isButtonDown);
/** Draws the contents of a standard ToggleButton. */
virtual void drawToggleButton (Graphics& g,
ToggleButton& button,
bool isMouseOverButton,
bool isButtonDown);
virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
virtual void drawTickBox (Graphics& g,
Component& component,
float x, float y, float w, float h,
bool ticked,
bool isEnabled,
bool isMouseOverButton,
bool isButtonDown);
//==============================================================================
/* AlertWindow handling..
*/
virtual AlertWindow* createAlertWindow (const String& title,
const String& message,
const String& button1,
const String& button2,
const String& button3,
AlertWindow::AlertIconType iconType,
int numButtons,
Component* associatedComponent);
virtual void drawAlertBox (Graphics& g,
AlertWindow& alert,
const Rectangle<int>& textArea,
TextLayout& textLayout);
virtual int getAlertBoxWindowFlags();
virtual int getAlertWindowButtonHeight();
virtual const Font getAlertWindowMessageFont();
virtual const Font getAlertWindowFont();
void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
bool isUsingNativeAlertWindows();
/** Draws a progress bar.
If the progress value is less than 0 or greater than 1.0, this should draw a spinning
bar that fills the whole space (i.e. to say that the app is still busy but the progress
isn't known). It can use the current time as a basis for playing an animation.
(Used by progress bars in AlertWindow).
*/
virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
int width, int height,
double progress, const String& textToShow);
//==============================================================================
// Draws a small image that spins to indicate that something's happening..
// This method should use the current time to animate itself, so just keep
// repainting it every so often.
virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
int x, int y, int w, int h);
//==============================================================================
/** Draws one of the buttons on a scrollbar.
@param g the context to draw into
@param scrollbar the bar itself
@param width the width of the button
@param height the height of the button
@param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
@param isScrollbarVertical true if it's a vertical bar, false if horizontal
@param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
@param isButtonDown whether the mouse button's held down
*/
virtual void drawScrollbarButton (Graphics& g,
ScrollBar& scrollbar,
int width, int height,
int buttonDirection,
bool isScrollbarVertical,
bool isMouseOverButton,
bool isButtonDown);
/** Draws the thumb area of a scrollbar.
@param g the context to draw into
@param scrollbar the bar itself
@param x the x position of the left edge of the thumb area to draw in
@param y the y position of the top edge of the thumb area to draw in
@param width the width of the thumb area to draw in
@param height the height of the thumb area to draw in
@param isScrollbarVertical true if it's a vertical bar, false if horizontal
@param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
thumb, or its x position for horizontal bars
@param thumbSize for vertical bars, the height of the thumb, or its width for
horizontal bars. This may be 0 if the thumb shouldn't be drawn.
@param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
currently dragging the thumb
@param isMouseDown whether the mouse is currently dragging the scrollbar
*/
virtual void drawScrollbar (Graphics& g,
ScrollBar& scrollbar,
int x, int y,
int width, int height,
bool isScrollbarVertical,
int thumbStartPosition,
int thumbSize,
bool isMouseOver,
bool isMouseDown);
/** Returns the component effect to use for a scrollbar */
virtual ImageEffectFilter* getScrollbarEffect();
/** Returns the minimum length in pixels to use for a scrollbar thumb. */
virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
/** Returns the default thickness to use for a scrollbar. */
virtual int getDefaultScrollbarWidth();
/** Returns the length in pixels to use for a scrollbar button. */
virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
//==============================================================================
/** Returns a tick shape for use in yes/no boxes, etc. */
virtual const Path getTickShape (float height);
/** Returns a cross shape for use in yes/no boxes, etc. */
virtual const Path getCrossShape (float height);
//==============================================================================
/** Draws the + or - box in a treeview. */
virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
//==============================================================================
virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
//==============================================================================
// These return a pointer to an internally cached drawable - make sure you don't keep
// a copy of this pointer anywhere, as it may become invalid in the future.
virtual const Drawable* getDefaultFolderImage();
virtual const Drawable* getDefaultDocumentFileImage();
virtual void createFileChooserHeaderText (const String& title,
const String& instructions,
GlyphArrangement& destArrangement,
int width);
virtual void drawFileBrowserRow (Graphics& g, int width, int height,
const String& filename, Image* icon,
const String& fileSizeDescription,
const String& fileTimeDescription,
bool isDirectory,
bool isItemSelected,
int itemIndex,
DirectoryContentsDisplayComponent& component);
virtual Button* createFileBrowserGoUpButton();
virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
DirectoryContentsDisplayComponent* fileListComponent,
FilePreviewComponent* previewComp,
ComboBox* currentPathBox,
TextEditor* filenameBox,
Button* goUpButton);
//==============================================================================
virtual void drawBubble (Graphics& g,
float tipX, float tipY,
float boxX, float boxY, float boxW, float boxH);
//==============================================================================
/** Fills the background of a popup menu component. */
virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
/** Draws one of the items in a popup menu. */
virtual void drawPopupMenuItem (Graphics& g,
int width, int height,
bool isSeparator,
bool isActive,
bool isHighlighted,
bool isTicked,
bool hasSubMenu,
const String& text,
const String& shortcutKeyText,
Image* image,
const Colour* const textColour);
/** Returns the size and style of font to use in popup menus. */
virtual const Font getPopupMenuFont();
virtual void drawPopupMenuUpDownArrow (Graphics& g,
int width, int height,
bool isScrollUpArrow);
/** Finds the best size for an item in a popup menu. */
virtual void getIdealPopupMenuItemSize (const String& text,
bool isSeparator,
int standardMenuItemHeight,
int& idealWidth,
int& idealHeight);
virtual int getMenuWindowFlags();
virtual void drawMenuBarBackground (Graphics& g, int width, int height,
bool isMouseOverBar,
MenuBarComponent& menuBar);
virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
virtual void drawMenuBarItem (Graphics& g,
int width, int height,
int itemIndex,
const String& itemText,
bool isMouseOverItem,
bool isMenuOpen,
bool isMouseOverBar,
MenuBarComponent& menuBar);
//==============================================================================
virtual void drawComboBox (Graphics& g, int width, int height,
bool isButtonDown,
int buttonX, int buttonY,
int buttonW, int buttonH,
ComboBox& box);
virtual const Font getComboBoxFont (ComboBox& box);
virtual Label* createComboBoxTextBox (ComboBox& box);
virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
//==============================================================================
virtual void drawLabel (Graphics& g, Label& label);
virtual void drawLayoutLabel (Graphics& g, LayoutLabel& layoutLabel);
virtual void drawFrameLabel (Graphics& g, FrameLabel& frameLabel);
//==============================================================================
virtual void drawLinearSlider (Graphics& g,
int x, int y,
int width, int height,
float sliderPos,
float minSliderPos,
float maxSliderPos,
const Slider::SliderStyle style,
Slider& slider);
virtual void drawLinearSliderBackground (Graphics& g,
int x, int y,
int width, int height,
float sliderPos,
float minSliderPos,
float maxSliderPos,
const Slider::SliderStyle style,
Slider& slider);
virtual void drawLinearSliderThumb (Graphics& g,
int x, int y,
int width, int height,
float sliderPos,
float minSliderPos,
float maxSliderPos,
const Slider::SliderStyle style,
Slider& slider);
virtual int getSliderThumbRadius (Slider& slider);
virtual void drawRotarySlider (Graphics& g,
int x, int y,
int width, int height,
float sliderPosProportional,
float rotaryStartAngle,
float rotaryEndAngle,
Slider& slider);
virtual Button* createSliderButton (bool isIncrement);
virtual Label* createSliderTextBox (Slider& slider);
virtual ImageEffectFilter* getSliderEffect();
//==============================================================================
virtual void getTooltipSize (const String& tipText, int& width, int& height);
virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
//==============================================================================
virtual Button* createFilenameComponentBrowseButton (const String& text);
virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
ComboBox* filenameBox, Button* browseButton);
//==============================================================================
virtual void drawCornerResizer (Graphics& g,
int w, int h,
bool isMouseOver,
bool isMouseDragging);
virtual void drawResizableFrame (Graphics& g,
int w, int h,
const BorderSize<int>& borders);
//==============================================================================
virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
const BorderSize<int>& border,
ResizableWindow& window);
virtual void drawResizableWindowBorder (Graphics& g,
int w, int h,
const BorderSize<int>& border,
ResizableWindow& window);
//==============================================================================
virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
Graphics& g, int w, int h,
int titleSpaceX, int titleSpaceW,
const Image* icon,
bool drawTitleTextOnLeft);
virtual Button* createDocumentWindowButton (int buttonType);
virtual void positionDocumentWindowButtons (DocumentWindow& window,
int titleBarX, int titleBarY,
int titleBarW, int titleBarH,
Button* minimiseButton,
Button* maximiseButton,
Button* closeButton,
bool positionTitleBarButtonsOnLeft);
virtual int getDefaultMenuBarHeight();
//==============================================================================
virtual DropShadower* createDropShadowerForComponent (Component* component);
//==============================================================================
virtual void drawStretchableLayoutResizerBar (Graphics& g,
int w, int h,
bool isVerticalBar,
bool isMouseOver,
bool isMouseDragging);
//==============================================================================
virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
const String& text,
const Justification& position,
GroupComponent& group);
//==============================================================================
virtual void createTabButtonShape (Path& p,
int width, int height,
int tabIndex,
const String& text,
Button& button,
TabbedButtonBar::Orientation orientation,
bool isMouseOver,
bool isMouseDown,
bool isFrontTab);
virtual void fillTabButtonShape (Graphics& g,
const Path& path,
const Colour& preferredBackgroundColour,
int tabIndex,
const String& text,
Button& button,
TabbedButtonBar::Orientation orientation,
bool isMouseOver,
bool isMouseDown,
bool isFrontTab);
virtual void drawTabButtonText (Graphics& g,
int x, int y, int w, int h,
const Colour& preferredBackgroundColour,
int tabIndex,
const String& text,
Button& button,
TabbedButtonBar::Orientation orientation,
bool isMouseOver,
bool isMouseDown,
bool isFrontTab);
virtual int getTabButtonOverlap (int tabDepth);
virtual int getTabButtonSpaceAroundImage();
virtual int getTabButtonBestWidth (int tabIndex,
const String& text,
int tabDepth,
Button& button);
virtual void drawTabButton (Graphics& g,
int w, int h,
const Colour& preferredColour,
int tabIndex,
const String& text,
Button& button,
TabbedButtonBar::Orientation orientation,
bool isMouseOver,
bool isMouseDown,
bool isFrontTab);
virtual void drawTabAreaBehindFrontButton (Graphics& g,
int w, int h,
TabbedButtonBar& tabBar,
TabbedButtonBar::Orientation orientation);
virtual Button* createTabBarExtrasButton();
//==============================================================================
virtual void drawImageButton (Graphics& g, Image* image,
int imageX, int imageY, int imageW, int imageH,
const Colour& overlayColour,
float imageOpacity,
ImageButton& button);
//==============================================================================
virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
int width, int height,
bool isMouseOver, bool isMouseDown,
int columnFlags);
//==============================================================================
virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
bool isMouseOver, bool isMouseDown,
ToolbarItemComponent& component);
virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
const String& text, ToolbarItemComponent& component);
//==============================================================================
virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
bool isOpen, int width, int height);
virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
PropertyComponent& component);
virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
PropertyComponent& component);
virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
//==============================================================================
virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
//==============================================================================
virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
//==============================================================================
/** Plays the system's default 'beep' noise, to alert the user about something very important.
*/
virtual void playAlertSound();
//==============================================================================
/** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
static void drawGlassSphere (Graphics& g,
float x, float y,
float diameter,
const Colour& colour,
float outlineThickness) noexcept;
static void drawGlassPointer (Graphics& g,
float x, float y,
float diameter,
const Colour& colour, float outlineThickness,
int direction) noexcept;
/** Utility function to draw a shiny, glassy oblong (for text buttons). */
static void drawGlassLozenge (Graphics& g,
float x, float y,
float width, float height,
const Colour& colour,
float outlineThickness,
float cornerSize,
bool flatOnLeft, bool flatOnRight,
bool flatOnTop, bool flatOnBottom) noexcept;
static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
private:
//==============================================================================
friend class WeakReference<LookAndFeel>;
WeakReference<LookAndFeel>::Master masterReference;
Array <int> colourIds;
Array <Colour> colours;
// default typeface names
String defaultSans, defaultSerif, defaultFixed;
ScopedPointer<Drawable> folderImage, documentImage;
bool useNativeAlertWindows;
void drawShinyButtonShape (Graphics& g,
float x, float y, float w, float h, float maxCornerSize,
const Colour& baseColour,
float strokeWidth,
bool flatOnLeft,
bool flatOnRight,
bool flatOnTop,
bool flatOnBottom) noexcept;
// This has been deprecated - see the new parameter list..
virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
};
#endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
|
[
"[email protected]"
] |
[
[
[
1,
684
]
]
] |
cba804d46d570b4d4970e89ad23ae96ff71341c8
|
bf4f0fc16bd1218720c3f25143e6e34d6aed1d4e
|
/Action.h
|
ab532783553cc815cbb654ec058af66bf87ef8f9
|
[] |
no_license
|
shergin/downright
|
4b0f161700673d7eb49459e4fde2b7d095eb91bb
|
6cc40cd35878e58f4ae8bae8d5e58256e6df4ce8
|
refs/heads/master
| 2020-07-03T13:34:20.697914 | 2009-09-29T19:15:07 | 2009-09-29T19:15:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 718 |
h
|
#pragma once
#include "StringTool.h"
class CAction
{
public:
int m_Type;
CString m_Param[3];
void operator = (CString s);
operator CString();
CString GetDescription(void);
void SetActionType(int type);
static void GetKeyElement(CString &s,int &type,int &key);
};
const CString StandartAction[]=
{
_T("Close"),
_T("Maximize"),
_T("Minimize"),
_T("MinimizeAll"),
_T("Copy"),
_T("Paste"),
_T("Cut"),
_T("Open"),
_T("Save"),
_T("Print"),
_T("Next"),
_T("Back")
_T("NextWindow"),
_T("PrevWindow"),
_T("Undo"),
_T("Redo"),
_T("SelectAll"),
_T("CloseDocument"),
_T("Shutdown")
};
#define StandartActionCount (sizeof(StandartAction)/sizeof(StandartAction[0]))
|
[
"[email protected]"
] |
[
[
[
1,
37
]
]
] |
cd096cdff7bdcdb756317c9e1b4ea51202bf217b
|
0f8559dad8e89d112362f9770a4551149d4e738f
|
/Wall_Destruction/Havok/Source/Physics/Utilities/Actions/AngularDashpot/hkpAngularDashpotAction.inl
|
369451fc4a02323c6c6db60c441b438d6302091a
|
[] |
no_license
|
TheProjecter/olafurabertaymsc
|
9360ad4c988d921e55b8cef9b8dcf1959e92d814
|
456d4d87699342c5459534a7992f04669e75d2e1
|
refs/heads/master
| 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,739 |
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-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
inline const hkQuaternion& hkpAngularDashpotAction::getRotation() const
{
return m_rotation;
}
inline void hkpAngularDashpotAction::setRotation(const hkQuaternion& q)
{
m_rotation = q;
}
inline hkReal hkpAngularDashpotAction::getStrength() const
{
return m_strength;
}
inline void hkpAngularDashpotAction::setStrength(hkReal s)
{
m_strength = s;
}
inline hkReal hkpAngularDashpotAction::getDamping() const
{
return m_damping;
}
inline void hkpAngularDashpotAction::setDamping(hkReal s)
{
m_damping = s;
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
|
[
"[email protected]"
] |
[
[
[
1,
53
]
]
] |
e6fbc7bb2333f715fc698b9d1a855a7b9028a340
|
cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca
|
/Nestopia/core/board/NstBoardBtlSmb2b.hpp
|
f256a32a94b814ca07c333c1855d50496b583a8d
|
[] |
no_license
|
nicoya/OpenEmu
|
e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e
|
dd5091414baaaddbb10b9d50000b43ee336ab52b
|
refs/heads/master
| 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,768 |
hpp
|
////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia 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.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_BOARD_BTL_SMB2B_H
#define NST_BOARD_BTL_SMB2B_H
#ifdef NST_PRAGMA_ONCE
#pragma once
#endif
namespace Nes
{
namespace Core
{
namespace Boards
{
namespace Btl
{
class Smb2b : public Board
{
public:
explicit Smb2b(const Context&);
private:
void SubReset(bool);
void SubSave(State::Saver&) const;
void SubLoad(State::Loader&,dword);
void Sync(Event,Input::Controllers*);
NES_DECL_PEEK( 6000 );
NES_DECL_POKE( 4020 );
NES_DECL_POKE( 4120 );
struct Irq
{
void Reset(bool);
bool Clock();
uint count;
};
ClockUnits::M2<Irq> irq;
};
}
}
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
72
]
]
] |
e9a9fb74f5e7fcd384024f11bd61bd7fc74641b9
|
619941b532c6d2987c0f4e92b73549c6c945c7e5
|
/Source/Nuclex/Audio/AudioDevice.cpp
|
947eeaa14472b68f0f0d6c6e7920b1098819c465
|
[] |
no_license
|
dzw/stellarengine
|
2b70ddefc2827be4f44ec6082201c955788a8a16
|
2a0a7db2e43c7c3519e79afa56db247f9708bc26
|
refs/heads/master
| 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 906 |
cpp
|
// //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## AudioDevice.cpp - Audio renderer //
// ### # # ### //
// # ### # ### Instance of an audio device which can be used for actual //
// # ## # # ## ## sound output and sound file format decoding //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#include "Nuclex/Audio/AudioDevice.h"
using namespace Nuclex;
using namespace Nuclex::Audio;
|
[
"[email protected]"
] |
[
[
[
1,
12
]
]
] |
0d13580a232fd6362ab4a2e992249245a2daabb9
|
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
|
/Common/ModelsC/QALMdls/QHEATRCT.H
|
f1e1502a4ca79dafb1dca97dc18d2a9d7ee3b52c
|
[] |
no_license
|
abcweizhuo/Test3
|
0f3379e528a543c0d43aad09489b2444a2e0f86d
|
128a4edcf9a93d36a45e5585b70dee75e4502db4
|
refs/heads/master
| 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,573 |
h
|
//================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#ifndef __QHEATRCT_H
#define __QHEATRCT_H
#include "models.h"
#define DllImportExport
//===========================================================================
//
//
//
//===========================================================================
class DllImportExport QGibbsiteHOR : public CR_EqnHeat
{
public:
QGibbsiteHOR(CR_EqnHeatFactory * Factory, pCR_Eqn pEqn) : CR_EqnHeat(Factory, pEqn) { };
virtual ~QGibbsiteHOR() { };
virtual double totDHf(SpModel *Mdl, double T, double P);
};
DEFINE_CLASSBUILDER1(QGibbsiteHOR, CR_EqnHeat, pCR_Eqn)
//===========================================================================
//
//
//
//===========================================================================
class DllImportExport QBoehmiteHOR : public CR_EqnHeat
{
public:
QBoehmiteHOR(CR_EqnHeatFactory * Factory, pCR_Eqn pEqn) : CR_EqnHeat(Factory, pEqn) { };
virtual ~QBoehmiteHOR() { };
virtual double totDHf(SpModel *Mdl, double T, double P);
};
DEFINE_CLASSBUILDER1(QBoehmiteHOR, CR_EqnHeat, pCR_Eqn)
//===========================================================================
//
//
//
//===========================================================================
/*
class DllImportExport CEC_GibbACEq : public CR_EqnControl
{
protected:
double dRqdExtent;
double dACEq;
public:
CEC_GibbACEq(pCR_Eqn pEqn) : CR_EqnControl(pEqn) { Clear(); };
virtual ~CEC_GibbACEq() { };
virtual eScdReactionBasis Basis() { return RctEquilibrium;};
virtual void Clear();
virtual void Parse(CRCTTokenFile &TF);
virtual void SetUp();
virtual void BuildDataDefn(DataDefnBlk & DDB);
virtual flag DataXchg(DataChangeBlk & DCB);
virtual flag VerifyData();
virtual void CalcKs(double ProdMoles, double &EqK, double &K);
};
DEFINE_CLASSBUILDER1(CEC_GibbACEq, CR_EqnControl, pCR_Eqn)
//===========================================================================
//
//
//
//===========================================================================
class DllImportExport CEC_BoehmACEq: public CR_EqnControl
{
protected:
double dRqdExtent;
double dACEq;
double dK0;
double dPercM45;
double dVLiq; // kL/h
double dSSA; // m^2/g
double dTSA; // m^2/L
double dMSolids; // m^2/L
double dResTime; // Secs
double dACOut;
double dTRct;
public:
CEC_BoehmACEq(pCR_Eqn pEqn) : CR_EqnControl(pEqn) { Clear(); };
virtual ~CEC_BoehmACEq() { };
virtual eScdReactionBasis Basis() { return RctEquilibrium;};
virtual void Clear();
virtual void Parse(CRCTTokenFile &TF);
virtual void SetUp();
virtual void BuildDataDefn(DataDefnBlk & DDB);
virtual flag DataXchg(DataChangeBlk & DCB);
virtual flag VerifyData();
virtual void CalcKs(double ProdMoles, double &EqK, double &K);
};
DEFINE_CLASSBUILDER1(CEC_BoehmACEq, CR_EqnControl, pCR_Eqn)
*/
//===========================================================================
//
//
//
//===========================================================================
#undef DllImportExport
#endif
|
[
"[email protected]"
] |
[
[
[
1,
129
]
]
] |
31583c7b45bfea423e457325bbbc821842bd35b8
|
c95a83e1a741b8c0eb810dd018d91060e5872dd8
|
/Game/ObjectDLL/ObjectShared/AIHumanStrategy.h
|
54e8c0e9dd56dcb6f85523c2bb156e0d1927681c
|
[] |
no_license
|
rickyharis39/nolf2
|
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
|
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
|
refs/heads/master
| 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 21,801 |
h
|
// (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved
#ifndef __AI_HUMAN_STRATEGY_H__
#define __AI_HUMAN_STRATEGY_H__
#include "AIBrain.h"
#include "AIStrategy.h"
#include "AnimationMgr.h"
#include "AIVolume.h"
class CCharacter;
class CAIHuman;
class CWeapon;
class AIVolume;
class CAIPath;
class CAIPathWaypoint;
class CAnimationContext;
class CAIHumanStrategyShoot;
class AINode;
class AINodeCover;
class AINodeSearch;
class AINodePickup;
class AINodePanic;
// Classes
class CAIHumanStrategy : public CAIClassAbstract
{
public : // Public member variables
DECLARE_AI_FACTORY_CLASS_ABSTRACT_SPECIFIC(Strategy);
CAIHumanStrategy( );
// Ctors/Dtors/etc
virtual LTBOOL Init(CAIHuman* pAIHuman);
virtual void Load(ILTMessage_Read *pMsg) {}
virtual void Save(ILTMessage_Write *pMsg) {}
// Updates
virtual void Update() {}
virtual LTBOOL UpdateAnimation();
// Misc
virtual LTBOOL DelayChangeState() { return LTFALSE; }
// Simple accessors
protected :
// Simple accessors
CAIHuman* GetAI() { return m_pAIHuman; }
CAnimationContext* GetAnimationContext();
protected :
CAIHuman* m_pAIHuman;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyOneShotAni
//
// PURPOSE : AI CheckingPulse - ability to ... to play a one shot ani
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyOneShotAni : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyOneShotAni, kStrat_HumanOneShotAni);
CAIHumanStrategyOneShotAni( );
// Ctors/Dtors/etc
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Set(EnumAnimPropGroup eGroup, EnumAnimProp eProp);
void Reset() { m_eState = eUnset; m_Prop.Clear(); }
void Update();
LTBOOL UpdateAnimation();
// State
LTBOOL IsUnset() { return m_eState == eUnset; }
LTBOOL IsSet() { return m_eState == eSet; }
LTBOOL IsAnimating() { return m_eState == eAnimating; }
LTBOOL IsDone() { return m_eState == eDone; }
// Simple accessors
protected :
enum State
{
eUnset,
eSet,
eAnimating,
eDone,
};
protected :
State m_eState;
CAnimationProp m_Prop;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyFollowPath
//
// PURPOSE : AI Follow path ability - to walk a path of AINodes
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyFollowPath : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyFollowPath, kStrat_HumanFollowPath);
CAIHumanStrategyFollowPath( );
~CAIHumanStrategyFollowPath( );
enum Medium
{
eMediumGround,
eMediumUnderwater,
};
public :
// Ctors/Dtors/etc
LTBOOL Init(CAIHuman* pAIHuman, CAIHumanStrategyShoot* pStrategyShoot);
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Reset();
LTBOOL Set(const LTVector& vDestination, LTBOOL bDivergePaths);
LTBOOL Set(const LTVector& vDestination, const LTVector& vDir, LTBOOL bDivergePaths);
LTBOOL Set(AINode* pNodeDestination, LTBOOL bDivergePaths);
LTBOOL Set(AIVolume* pVolumeDestination, LTBOOL bDivergePaths);
LTBOOL SetRandom(AIVolume* pVolumeSrcPrev, AIVolume* pVolumeSrc, AIVolume* pVolumeSrcNext);
void Update();
LTBOOL UpdateAnimation();
// Path reservation.
void ReservePath();
void ClearReservedPath();
// Handlers
void HandleModelString(ArgList* pArgList);
// Misc
LTBOOL DelayChangeState();
// Movement types
void SetMovement(EnumAnimProp eMovement);
EnumAnimProp GetMovement();
void SetMovementModifier(EnumAnimPropGroup eGroup, EnumAnimProp eProp) { m_bModifiedMovement = LTTRUE; m_aniModifiedMovement.Set(eGroup, eProp); }
void ClearMovementModifier() { m_bModifiedMovement = LTFALSE; }
// Medium types
void SetMedium(Medium eMedium);
// Simple accessors
LTBOOL IsUnset() { return m_eState == eStateUnset; }
LTBOOL IsSet() { return m_eState == eStateSet; }
LTBOOL IsDone() { return m_eState == eStateDone; }
const LTVector& GetDest() const { return m_vDest; }
void GetInitialDir(LTVector* pvDir);
void GetFinalDir(LTVector* pvDir);
AIVolume* GetNextVolume(AIVolume* pVolume, AIVolume::EnumVolumeType eVolumeType);
// Debug rendering.
void DebugDrawPath();
void DebugRemainingDrawPath();
protected :
LTBOOL UpdateMoveTo(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateClimbTo(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateJumpTo(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateFaceJumpLand(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateFaceLadder(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateFaceDoor(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateOpenDoors(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateWaitForDoors(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateReleaseGate(CAIPathWaypoint* pWaypoint);
LTBOOL UpdateMoveTeleport(CAIPathWaypoint* pWaypoint);
LTBOOL DoorsBlocked( HOBJECT hDoor );
protected : // Protected enumerations
enum State
{
eStateUnset,
eStateSet,
eStateDone,
};
enum DoorState
{
eDoorStateNone,
eDoorStateWaitingForAnimationToStart,
eDoorStateWaitingForAnimationToFinish,
eDoorStateWaitingForDoorToOpen,
eDoorStateWalkingThroughDoor,
};
protected :
CAIPath* m_pPath;
State m_eState;
Medium m_eMedium;
DoorState m_eDoorState;
EnumAnimProp m_eDoorAction;
LTFLOAT m_fLastDoor1Yaw;
LTFLOAT m_fLastDoor2Yaw;
CAnimationProp m_aniModifiedMovement;
LTBOOL m_bModifiedMovement;
uint32 m_cStuckOnDoorUpdates;
LTBOOL m_bDoorShootThroughable;
LTVector m_vDest;
LTBOOL m_bCheckAnimStatus;
// Debug
LTBOOL m_bDrawingPath;
class CAIHumanStrategyShoot* m_pStrategyShoot;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyDodge
//
// PURPOSE : AI ability to dodge
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyDodge : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
enum State
{
eStateChecking,
eStateDodging,
eStateFleeing,
eStateCovering,
};
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyDodge, kStrat_HumanDodge);
CAIHumanStrategyDodge( );
// Ctors/Dtors/etc
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Dodge
void Dodge();
LTBOOL IsDodging() const { return m_eState == eStateDodging; }
State GetDodgeState() const { return m_eState; }
// Outcome
DodgeStatus GetStatus() const { return m_eDodgeStatus; }
DodgeAction GetAction() const { return m_eDodgeAction; }
// Simple accessors
const LTVector& GetScatterPosition() const { return m_vScatterPosition; }
void ForceDodge() { m_bForceDodge = LTTRUE; }
protected :
// Update Check
void UpdateCheck();
// Update Dodge
void UpdateDodge();
void UpdateDodgeDive();
void UpdateDodgeFlee();
void UpdateDodgeCover();
// Check
void Check();
protected :
AINode* m_pNode;
State m_eState;
DodgeStatus m_eDodgeStatus;
DodgeAction m_eDodgeAction;
LTVector m_vScatterPosition;
Direction m_eDirection;
LTVector m_vDir;
LTBOOL m_bForceDodge;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyTaunt
//
// PURPOSE : AI ability to taunt
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyTaunt : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
enum State
{
eStateChecking,
eStateTaunting,
};
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyTaunt, kStrat_HumanTaunt);
CAIHumanStrategyTaunt( );
// Ctors/Dtors/etc
LTBOOL Init(CAIHuman* pAIHuman);
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Taunting.
LTBOOL IsTaunting() const { return m_eState == eStateTaunting; }
void ResetTaunting() { Check(); }
protected:
void Check();
protected :
LTFLOAT m_fCheckTime;
State m_eState;
// The following do not need to be saved.
LTFLOAT m_fMinTauntDistSqr;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyCover
//
// PURPOSE : AI ability to use cover
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyCover : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_ABSTRACT_SPECIFIC(Strategy);
CAIHumanStrategyCover( );
// Ctors/Dtors/etc
virtual LTBOOL Init(CAIHuman* pAIHuman);
virtual void Clear();
virtual void Load(ILTMessage_Read *pMsg);
virtual void Save(ILTMessage_Write *pMsg);
// Updates
virtual void Update();
virtual LTBOOL UpdateAnimation();
// Cover
virtual void Cover(LTFLOAT fDelay = 0.0f);
virtual void Uncover(LTFLOAT fDelay= 0.0f);
// Simple accessors
void SetCoverNode(AINode *pCoverNode) { m_pCoverNode = pCoverNode; }
void SetCoverTime(LTFLOAT fCoverTime, LTFLOAT fCoverTimeRandom = 0.0f) { m_fCoverTime = fCoverTime + GetRandom(0.0f, fCoverTimeRandom); }
void SetUncoverTime(LTFLOAT fUncoverTime, LTFLOAT fUncoverTimeRandom = 0.0f) { m_fUncoverTime = fUncoverTime + GetRandom(0.0f, fUncoverTimeRandom); }
LTBOOL IsCovered() { return m_eState == eCovered; }
LTBOOL IsUncovered() { return m_eState == eUncovered; }
LTBOOL IsCovering() { return m_eState == eCovering; }
LTBOOL IsUncovering() { return m_eState == eUncovering; }
virtual LTBOOL CanBlindFire();
virtual LTBOOL OneAnimCover() { return m_bOneAnimCover; }
protected :
void SwitchToCover();
void SwitchToUncover();
enum State
{
eCovered,
eWillUncover,
eUncovering,
eUncovered,
eWillCover,
eCovering,
};
protected :
State m_eState; // Our state
LTBOOL m_bOneAnimCover; // Attack from cover is all one animation.
LTBOOL m_bOneAnimFiring; // Playing the one animation firing animation.
LTBOOL m_bWantCover; // Has Cover been requested
LTFLOAT m_fCoverTimer; // How long have we been Covered
LTFLOAT m_fCoverTime; // How long should we stay Covered for
LTFLOAT m_fCoverDelay; // When should we execute a Cover request
LTBOOL m_bWantUncover; // Has Uncover been requested
LTFLOAT m_fUncoverTimer; // How long have we been Uncovered
LTFLOAT m_fUncoverTime; // How long should we stay Uncovered for
LTFLOAT m_fUncoverDelay; // When should we execute a Uncover request
// These don't need saving
AINode* m_pCoverNode; // Our cover node
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyCoverDuck
//
// PURPOSE : AI cover ability that uses ducking
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyCoverDuck : public CAIHumanStrategyCover
{
typedef CAIHumanStrategyCover super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyCoverDuck, kStrat_HumanCoverDuck);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Simple accessors
virtual LTBOOL OneAnimCover() { return LTFALSE; }
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyCoverBlind
//
// PURPOSE : AI cover ability that simply stays behind cover and blind fires
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyCoverBlind : public CAIHumanStrategyCover
{
typedef CAIHumanStrategyCover super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyCoverBlind, kStrat_HumanCoverBlind);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Simple accessors
virtual LTBOOL CanBlindFire() { return LTTRUE; }
virtual LTBOOL OneAnimCover() { return LTFALSE; }
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyCover1WayCorner
//
// PURPOSE : AI cover ability that uses Cornerping in one direction
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyCover1WayCorner : public CAIHumanStrategyCover
{
typedef CAIHumanStrategyCover super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyCover1WayCorner, kStrat_HumanCover1WayCorner);
CAIHumanStrategyCover1WayCorner( );
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Simple accessors
protected:
LTFLOAT GetMovementData();
protected :
Direction m_eDirection;
LTVector m_vDir;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyCover2WayCorner
//
// PURPOSE : AI cover ability that uses Cornerping in one direction
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyCover2WayCorner : public CAIHumanStrategyCover
{
typedef CAIHumanStrategyCover super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyCover2WayCorner, kStrat_HumanCover2WayCorner);
CAIHumanStrategyCover2WayCorner( );
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Simple accessors
protected:
LTFLOAT GetMovementData();
protected :
Direction m_eDirection;
LTVector m_vDir;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyGrenade
//
// PURPOSE : AI ability to use Grenade
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyGrenade : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_ABSTRACT_SPECIFIC(Strategy);
// Throw
virtual void Throw(LTFLOAT fTime = 0.5f) { }
virtual LTBOOL ShouldThrow() { return LTFALSE; }
virtual LTBOOL IsThrowing() { return LTFALSE; }
// Handlers
virtual void HandleModelString(ArgList* pArgList) {}
// Simple accessors
protected :
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyGrenadeThrow
//
// PURPOSE : AI Grenade ability that throws the grenade
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyGrenadeThrow : public CAIHumanStrategyGrenade
{
typedef CAIHumanStrategyGrenade super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyGrenadeThrow, kStrat_HumanGrenadeThrow);
CAIHumanStrategyGrenadeThrow( );
// Ctors/Dtors/etc
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Updates
void Update();
LTBOOL UpdateAnimation();
// Handlers
void HandleModelString(ArgList* pArgList);
// Throw
void Throw(LTFLOAT fTime = 0.5f);
LTBOOL ShouldThrow();
LTBOOL IsThrowing();
// Simple accessors
protected :
enum State
{
eStateNone,
eStateThrowing,
eStateThrow,
eStateThrown,
eStateDone,
};
protected :
State m_eState;
LTFLOAT m_fHangtime;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyShoot
//
// PURPOSE : AI shoot ability - to fire at something
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyShoot : public CAIHumanStrategy
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_ABSTRACT_SPECIFIC(Strategy);
CAIHumanStrategyShoot( );
~CAIHumanStrategyShoot( );
// Ctors/Dtors/etc
LTBOOL Init(CAIHuman* pAIHuman);
virtual void Load(ILTMessage_Read *pMsg);
virtual void Save(ILTMessage_Write *pMsg);
// Updates
void Update(HOBJECT hTarget = LTNULL);
LTBOOL UpdateAnimation();
// Handlers
void HandleModelString(ArgList* pArgList);
// Clearing
void Clear();
// Reloading
LTBOOL IsReloading() const { return m_eState == eStateReloading; }
void Reload(LTBOOL bInstant = LTFALSE);
LTBOOL ShouldReload();
// FOV
void SetIgnoreFOV(LTBOOL bIgnoreFOV) { m_bIgnoreFOV = bIgnoreFOV; }
// Blind fire
LTBOOL IsBlind() const { return m_bShootBlind; }
void SetShootBlind(LTBOOL bBlind) { m_bShootBlind = bBlind; }
// Hack...
virtual LTBOOL IsFiring() { return m_bFired; }
void ClearFired() { m_bFired = LTFALSE; }
void ForceFire(HOBJECT hTargetObject);
// Simple accessors
protected :
// Updates
virtual void UpdateFiring(HOBJECT hTarget, const LTVector& vTargetPos, CWeapon* pWeapon) = 0;
virtual void UpdateAiming(HOBJECT hTarget) = 0;
void UpdateNeedsReload(CWeapon* pWeapon);
void UpdateReloading(CWeapon* pWeapon);
// Handlers
virtual void HandleFired(const char* const pszSocketName);
// Aim/Fire
virtual void Aim();
virtual void Fire();
LTVector GetFirePosition(CWeapon*);
// Reload
LTBOOL NeedsReload() { return m_bNeedsReload; }// Clip Empty?
LTBOOL CanReload(); // Do we have a Reserve, or can we generate?
LTBOOL IsOutOfAmmo() { return m_bOutOfAmmo; } // Ammo in Reserves?
LTBOOL CanGenerateAmmo( int iWeaponIndex ); // Are we able to generate ammo?
protected :
enum State
{
eStateNone,
eStateAiming,
eStateFiring,
eStateReloading,
};
protected :
State m_eState; // Our state
LTBOOL m_bFired; // Did we fire?
LTBOOL m_bNeedsReload; // Do we need to reload?
LTBOOL m_bOutOfAmmo; // Are we out of ammo?
LTBOOL m_bFirstUpdate; // Our first update?
LTBOOL m_bIgnoreFOV; // Fire regardless of FOV
LTBOOL m_bShootBlind; // Shoot blind?
HMODELSOCKET m_hFiringSocket; // Socket the shot should come from
// (if not INVALID_MODEL_SOCKET)
uint32 m_iAnimRandomSeed; // Randomizing aim/fire animation pairs.
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyShootBurst
//
// PURPOSE : AI shoot ability - to burst fire at something
//
// ----------------------------------------------------------------------- //
class CAIHumanStrategyShootBurst : public CAIHumanStrategyShoot
{
typedef CAIHumanStrategyShoot super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyShootBurst, kStrat_HumanShootBurst);
CAIHumanStrategyShootBurst( );
// Ctors/Dtors/etc
LTBOOL Init(CAIHuman* pAIHuman);
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Simple accessors
protected :
// Updates
virtual void UpdateFiring(HOBJECT hTarget, const LTVector& vTargetPos, CWeapon* pWeapon);
virtual void UpdateAiming(HOBJECT hTarget);
// Aim/Fire
virtual void Aim();
virtual void Fire();
// Handlers
virtual void HandleFired(const char* const pszSocketName);
// Burst methods
void CalculateBurst();
protected :
LTFLOAT m_fBurstInterval; // How long between bursts (this is the timer)
int m_nBurstShots; // How many shots in each burst (this is the counter)
LTBOOL m_bUseIntervals; // Do we pause between bursts?
LTBOOL m_bPreFire;
};
// ----------------------------------------------------------------------- //
//
// CLASS : CAIHumanStrategyFlashlight
//
// PURPOSE : AI strategy for using a flashlight
//
// ----------------------------------------------------------------------- //
// For constructor. warning C4355: 'this' : used in base member initializer list
#pragma warning( push )
#pragma warning( disable : 4355 )
class CAIHumanStrategyFlashlight : public CAIHumanStrategy, public ILTObjRefReceiver
{
typedef CAIHumanStrategy super;
public :
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyFlashlight, kStrat_HumanFlashlight);
CAIHumanStrategyFlashlight( );
~CAIHumanStrategyFlashlight( );
// Ctors/Dtors/etc
void Load(ILTMessage_Read *pMsg);
void Save(ILTMessage_Write *pMsg);
// Handlers
void HandleModelString(ArgList* pArgList);
// ILTObjRefReceiver function.
virtual void OnLinkBroken( LTObjRefNotifier *pRef, HOBJECT hObj );
// Simple accessors
protected :
void FlashlightShow();
void FlashlightHide();
void FlashlightOn();
void FlashlightOff();
void FlashlightCreate();
void FlashlightDestroy();
protected :
LTObjRefNotifier m_hFlashlightModel;
};
#pragma warning( pop )
#endif
|
[
"[email protected]"
] |
[
[
[
1,
930
]
]
] |
c093d81686643a92cce7cb27097545738b0bf4c2
|
814e67bf5d1c2f2e233b3ec1ee07faaaa65a9951
|
/compiladormarvel/VerificadorVariaveis.h
|
6e46c124af27519e010778e89d248b5f59cd4171
|
[] |
no_license
|
lsalamon/compiladormarvel
|
686a5814e363fee41163d8a447d6753ebe84d220
|
55ea7a3f3cb76ec738e792e608ab01a9f48e5f8b
|
refs/heads/master
| 2021-01-10T08:17:50.321427 | 2009-03-20T14:06:43 | 2009-03-20T14:06:43 | 50,113,476 | 0 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 2,168 |
h
|
/*
Arquivo header que define a classe VerificacaoVariaveis, que herda de
Visitor (é a implementação de Visitor para o caso em que a declaração
das variáveis é verificada).
*/
#ifndef VERIFICADORVARIAVEIS_H
#define VERIFICADORVARIAVEIS_H
#include "Visitor.h"
// Define os atributos e os métodos visitantes
class VerificadorVariaveis : public Visitor {
public:
int parametros; // define a quantidade de parametros
int offset; // offset
// void* ponteiro_estrutura_tipo;
public:
// Declaração do construtor
VerificadorVariaveis();
// Métodos visitantes
void visit(ProgramNode* programNode);
void visit(StatementListNode* stmtNode);
void visit(NameDeclNode* nameDeclNode);
void visit(FragmentNode* fragmentNode);
void visit(IfNode* ifNode);
void visit(WhileNode* whileNode);
void visit(AssignNode* assignNode);
void visit(FragCallNode* fragCallNode);
void visit(ReadNode* readNode);
void visit(WriteNode* writeNode);
void visit(ConstantNode* constantNode);
void visit(ExpressionListNode* expressionListNode);
void visit(CallNode* callNode);
void visit(ArrayNode* arrayNode);
void visit(RelOpNode* relationalOpNode);
void visit(AddOpNode* additionalOpNode);
void visit(MultOpNode* multOpNode);
void visit(BoolOpNode* boolOpNode);
void visit(BitwiseOpNode* bitwiseOpNode);
void visit(NotNode* notNode);
void visit(NegativeNode* negativeNode);
void visit(ModifierListNode* modifierListNode);
void visit(ModifierNode* modifierNode);
void visit(IdNode* idNode);
void visit(IdListNode* idListNode);
void visit(NumberNode* numberNode);
void visit(LiteralNode* literalNode);
};
#endif
|
[
"sergiorossini@df256a42-0e3e-0410-b2fe-0dffcef58804",
"cslopes@df256a42-0e3e-0410-b2fe-0dffcef58804"
] |
[
[
[
1,
8
],
[
11,
55
]
],
[
[
9,
10
]
]
] |
d519faf1f01a58573d91473cc8c9ca86a7ee54df
|
5fa57a0bf6492f713b33847752d8be7059d7cd5f
|
/test_run.cpp
|
42ff29c682c1ec07e9deb02e9740248969367a55
|
[] |
no_license
|
smitec/workers
|
75bad36602ee3d341a7261612cd6e3e6d1a8d3e0
|
875dec02c7f604361838949972443c30243db3ea
|
refs/heads/master
| 2021-01-18T13:49:45.115527 | 2011-09-24T07:57:10 | 2011-09-24T07:57:10 | 2,261,180 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,207 |
cpp
|
/*#include <iostream>
#include <vector>
#include "worker.h"
#include "master.h"
#include <time.h>
#include <fstream>
#include <math.h>
using namespace std;
double threadCompare(int numThreads);
class testWorker: public Worker
{
public:
void work();
};
class anotherWorker: public Worker
{
public:
void work();
};
void testWorker::work()
{
//Simple making of a string
string* res = new string("This Wroked Yay!");
this->result = (void*)res;
this->finished = true;
}
void anotherWorker::work()
{
//Run a loop so it takes up some time
int res = 0;
for(int i = 0; i < 100000; i++)
{
for (int j = 0; j < 10000; j++)
{
res = sqrt(i*j);
}
}
this->result = (void*)clock();
this->finished = true;
}
double threadCompare(int numThreads) {
vector<anotherWorker> withThreads;
vector<anotherWorker> withoutThreads;
if (numThreads > 20) {
numThreads = 20;
}
for (int i = 0; i < numThreads; i++) {
withThreads.push_back(anotherWorker());
withoutThreads.push_back(anotherWorker());
}
double res1 = 0;
clock_t start, finish, tstart;
tstart = clock();
for (int i = 0; i < numThreads; i++) {
withThreads[i].start_worker(0);
}
start = clock();
for (int i = 0; i < numThreads; i++) {
withoutThreads[i].work();
}
finish = clock();
double res2 = (finish - start)/(1.0*CLOCKS_PER_SEC);
void* res[20];
for (int i = 0; i < numThreads; i++) {
res[i] = withThreads[i].get_result();
}
//find max finish time
finish = 0;
for (int i = 0; i < numThreads; i++) {
finish = ((clock_t)res[i] > finish) ? (clock_t)res[i] : finish;
}
res1 = (finish - tstart)/(1.0*CLOCKS_PER_SEC);
std::cout << "Results for "<< numThreads << " Threads :\n\tWithout Threads- " << res2 << "s\n\tWith Threads- " << res1 <<"s\n";
std::cout << "\tRatio (without/with): " << res2/res1 << "\n";
return res2/res1;
}
int main()
{
threadCompare(5);
return 0;
}
*/
|
[
"[email protected]"
] |
[
[
[
1,
101
]
]
] |
a2fd318f5cde7b5ab695327ec5dda22233fb6806
|
997e067ab6b591e93e3968ae1852003089dca848
|
/src/game/server/entities/light.cpp
|
e117d6aa371893f44139eddd7fd63e88f3e066f3
|
[
"LicenseRef-scancode-other-permissive",
"Zlib"
] |
permissive
|
floff/ddracemax_old
|
06cbe9f60e7cef66e58b40c5f586921a1c881ff3
|
f1356177c49a3bc20632df9a84a51bc491c37f7d
|
refs/heads/master
| 2016-09-05T11:59:55.623581 | 2011-01-14T04:58:25 | 2011-01-14T04:58:25 | 777,555 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,278 |
cpp
|
/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */
#include <engine/e_config.h>
#include <engine/e_server_interface.h>
#include <game/generated/g_protocol.hpp>
#include <game/server/gamecontext.hpp>
#include "light.hpp"
//////////////////////////////////////////////////
// LIGHT
//////////////////////////////////////////////////
const int TICK=(server_tickspeed()*0.15f);
LIGHT::LIGHT(vec2 pos, float rotation, int length)
: ENTITY(NETOBJTYPE_LASER)
{
this->pos = pos;
this->rotation = rotation;
this->length = length;
this->eval_tick=server_tick();
game.world.insert_entity(this);
step();
}
bool LIGHT::hit_character()
{
vec2 nothing;
CHARACTER *hit = game.world.intersect_character(pos, to, 0.0f, nothing, 0);
if(!hit)
return false;
hit->freeze(server_tickspeed()*3);
return true;
}
void LIGHT::move()
{
if (speed != 0)
{
if ((cur_length>=length && speed>0) || (cur_length<=0 && speed<0))
speed=-speed;
cur_length+=speed*TICK + length_l;
length_l=0;
if (cur_length>length)
{
length_l=cur_length-length;
cur_length=length;
}
else if(cur_length<0)
{
length_l=0+cur_length;
cur_length=0;
}
}
rotation+=ang_speed*TICK;
if (rotation>pi*2)
rotation-=pi*2;
else if(rotation<0)
rotation+=pi*2;
}
void LIGHT::step()
{
move();
vec2 dir;
dir.x=sin(rotation);
dir.y=cos(rotation);
vec2 to2 = pos + normalize(dir)*cur_length;
col_intersect_nolaser(pos, to2, &to,0 );
}
void LIGHT::reset()
{
//game.world.destroy_entity(this);
}
void LIGHT::tick()
{
if (server_tick() > eval_tick+TICK)
{
eval_tick=server_tick();
step();
}
hit_character();
return;
}
void LIGHT::snap(int snapping_client)
{
if(networkclipped(snapping_client,pos) && networkclipped(snapping_client,to))
return;
NETOBJ_LASER *obj = (NETOBJ_LASER *)snap_new_item(NETOBJTYPE_LASER, id, sizeof(NETOBJ_LASER));
obj->x = (int)pos.x;
obj->y = (int)pos.y;
obj->from_x = (int)to.x;
obj->from_y = (int)to.y;
int start_tick = eval_tick;
if (start_tick<server_tick()-4)
start_tick=server_tick()-4;
else if (start_tick>server_tick())
start_tick=server_tick();
obj->start_tick = start_tick;
}
|
[
"[email protected]"
] |
[
[
[
1,
112
]
]
] |
f9c6cf948b66ee0ef8fdef0c32cd93b371c282e8
|
10c14a95421b63a71c7c99adf73e305608c391bf
|
/gui/image/qnativeimage.cpp
|
fcd0f5937980338d9ea1f379cb71e9119f00e7e7
|
[] |
no_license
|
eaglezzb/wtlcontrols
|
73fccea541c6ef1f6db5600f5f7349f5c5236daa
|
61b7fce28df1efe4a1d90c0678ec863b1fd7c81c
|
refs/heads/master
| 2021-01-22T13:47:19.456110 | 2009-05-19T10:58:42 | 2009-05-19T10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,457 |
cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
// #include <qdebug.h>
#include "qnativeimage_p.h"
#include "qcolormap.h"
#include "private/qpaintengine_raster_p.h"
#if defined(Q_WS_X11) && !defined(QT_NO_MITSHM)
#include <qx11info_x11.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <qwidget.h>
#endif
QT_BEGIN_NAMESPACE
#ifdef Q_WS_WIN
typedef struct {
BITMAPINFOHEADER bmiHeader;
DWORD redMask;
DWORD greenMask;
DWORD blueMask;
} BITMAPINFO_MASK;
QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool isTextBuffer, HDC drawDC)
{
#ifndef Q_OS_WINCE
Q_UNUSED(isTextBuffer);
#endif
BITMAPINFO_MASK bmi;
memset(&bmi, 0, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biSizeImage = 0;
if (format == QImage::Format_RGB16) {
bmi.bmiHeader.biBitCount = 16;
#ifdef Q_OS_WINCE
if (isTextBuffer) {
bmi.bmiHeader.biCompression = BI_RGB;
bmi.redMask = 0;
bmi.greenMask = 0;
bmi.blueMask = 0;
} else
#endif
{
bmi.bmiHeader.biCompression = BI_BITFIELDS;
bmi.redMask = 0xF800;
bmi.greenMask = 0x07E0;
bmi.blueMask = 0x001F;
}
} else {
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.redMask = 0;
bmi.greenMask = 0;
bmi.blueMask = 0;
}
//modify HDC display_dc = GetDC(0);
HDC display_dc = drawDC;
hdc = CreateCompatibleDC(display_dc);
// ReleaseDC(0, display_dc);
Q_ASSERT(hdc);
uchar *bits = 0;
bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi), DIB_RGB_COLORS, (void**) &bits, 0, 0);
Q_ASSERT(bitmap);
Q_ASSERT(bits);
null_bitmap = (HBITMAP)SelectObject(hdc, bitmap);
image = QImage(bits, width, height, format);
Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster);
static_cast<QRasterPaintEngine *>(image.paintEngine())->setDC(hdc);
#ifndef Q_OS_WINCE
GdiFlush();
#endif
}
QNativeImage::~QNativeImage()
{
if (bitmap || hdc) {
Q_ASSERT(hdc);
Q_ASSERT(bitmap);
if (null_bitmap)
SelectObject(hdc, null_bitmap);
DeleteDC(hdc);
DeleteObject(bitmap);
}
}
QImage::Format QNativeImage::systemFormat()
{
//modify
// if (QColormap::instance().depth() == 16)
// return QImage::Format_RGB16;
return QImage::Format_RGB32;
}
#elif defined(Q_WS_X11) && !defined(QT_NO_MITSHM)
QNativeImage::QNativeImage(int width, int height, QImage::Format format,bool /* isTextBuffer */, QWidget *widget)
{
if (!X11->use_mitshm) {
xshmimg = 0;
xshmpm = 0;
image = QImage(width, height, format);
return;
}
QX11Info info = widget->x11Info();
int dd = info.depth();
Visual *vis = (Visual*) info.visual();
xshmimg = XShmCreateImage(X11->display, vis, dd, ZPixmap, 0, &xshminfo, width, height);
if (!xshmimg) {
qWarning("QNativeImage: Unable to create shared XImage.");
return;
}
bool ok;
xshminfo.shmid = shmget(IPC_PRIVATE, xshmimg->bytes_per_line * xshmimg->height,
IPC_CREAT | 0777);
ok = xshminfo.shmid != -1;
if (ok) {
xshmimg->data = (char*)shmat(xshminfo.shmid, 0, 0);
xshminfo.shmaddr = xshmimg->data;
ok = (xshminfo.shmaddr != (char*)-1);
if (ok)
image = QImage((uchar *)xshmimg->data, width, height, systemFormat());
}
xshminfo.readOnly = false;
if (ok)
ok = XShmAttach(X11->display, &xshminfo);
if (!ok) {
qWarning() << "QNativeImage: Unable to attach to shared memory segment.";
if (xshmimg->data) {
free(xshmimg->data);
xshmimg->data = 0;
}
XDestroyImage(xshmimg);
xshmimg = 0;
if (xshminfo.shmaddr)
shmdt(xshminfo.shmaddr);
if (xshminfo.shmid != -1)
shmctl(xshminfo.shmid, IPC_RMID, 0);
return;
}
xshmpm = XShmCreatePixmap(X11->display, DefaultRootWindow(X11->display), xshmimg->data,
&xshminfo, width, height, dd);
if (!xshmpm) {
qWarning() << "QNativeImage: Unable to create shared Pixmap.";
}
}
QNativeImage::~QNativeImage()
{
if (!xshmimg)
return;
if (xshmpm) {
XFreePixmap(X11->display, xshmpm);
xshmpm = 0;
}
XShmDetach(X11->display, &xshminfo);
xshmimg->data = 0;
XDestroyImage(xshmimg);
xshmimg = 0;
shmdt(xshminfo.shmaddr);
shmctl(xshminfo.shmid, IPC_RMID, 0);
}
QImage::Format QNativeImage::systemFormat()
{
if (QX11Info::appDepth() == 16)
return QImage::Format_RGB16;
return QImage::Format_RGB32;
}
#elif defined(Q_WS_MAC)
QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *)
: image(width, height, format)
{
cgColorSpace = CGColorSpaceCreateDeviceRGB();
uint cgflags = kCGImageAlphaNoneSkipFirst;
#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
if(QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
cgflags |= kCGBitmapByteOrder32Host;
#endif
cg = CGBitmapContextCreate(image.bits(), width, height, 8, image.bytesPerLine(), cgColorSpace, cgflags);
CGContextTranslateCTM(cg, 0, height);
CGContextScaleCTM(cg, 1, -1);
Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster);
static_cast<QRasterPaintEngine *>(image.paintEngine())->setCGContext(cg);
}
QNativeImage::~QNativeImage()
{
CGContextRelease(cg);
CGColorSpaceRelease(cgColorSpace);
}
QImage::Format QNativeImage::systemFormat()
{
return QImage::Format_RGB32;
}
#else // other platforms...
QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *)
: image(width, height, format)
{
}
QNativeImage::~QNativeImage()
{
}
QImage::Format QNativeImage::systemFormat()
{
return QImage::Format_RGB32;
}
#endif // platforms
QT_END_NAMESPACE
|
[
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
] |
[
[
[
1,
283
]
]
] |
0586fd137c219c7ef2736d40b7f377164dc1ff7a
|
da48afcbd478f79d70767170da625b5f206baf9a
|
/tbmessage/src/EditMsgDlg.cpp
|
8cda0bf96509dd580dd686237b3c8f7d45df5fb9
|
[] |
no_license
|
haokeyy/fahister
|
5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04
|
c71dc56a30b862cc4199126d78f928fce11b12e5
|
refs/heads/master
| 2021-01-10T19:09:22.227340 | 2010-05-06T13:17:35 | 2010-05-06T13:17:35 | null | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 3,114 |
cpp
|
// EditMsgDlg.cpp : implementation file
//
#include "stdafx.h"
#include "tbmessage.h"
#include "EditMsgDlg.h"
// CEditMsgDlg dialog
IMPLEMENT_DYNAMIC(CEditMsgDlg, CDialog)
CEditMsgDlg::CEditMsgDlg(CWnd* pParent /*=NULL*/)
: CDialog(CEditMsgDlg::IDD, pParent)
{
}
CEditMsgDlg::~CEditMsgDlg()
{
}
void CEditMsgDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//DDX_Control(pDX, IDC_DHTML_EDIT_MSG, m_MsgEdit);
}
BEGIN_MESSAGE_MAP(CEditMsgDlg, CDialog)
ON_BN_CLICKED(IDOK, &CEditMsgDlg::OnBnClickedOk)
END_MESSAGE_MAP()
BOOL CEditMsgDlg::OnInitDialog()
{
CDialog::OnInitDialog();
this->SetDlgItemText(IDC_EDIT1, bodyInnerHtml);
this->GetDlgItem(IDC_EDIT1)->SetFocus();
return TRUE;
}
CString CEditMsgDlg::GetMsgHtml()
{
return bodyInnerHtml;
}
CString CEditMsgDlg::GetMsgText()
{
return bodyInnerHtml;
}
void CEditMsgDlg::SetMsgHtml(CString szMsgHtml)
{
bodyInnerHtml = szMsgHtml;
}
//CString CEditMsgDlg::InternalGetMsgHtml()
//{
// IDispatch *pDisp = m_MsgEdit.get_DOM();
// if (pDisp)
// {
// IHTMLElement *pBody;
// BSTR bstrBody;
// IHTMLDocument2 *pDoc = (IHTMLDocument2 *)pDisp;
// pDoc->get_body(&pBody);
// pBody->get_innerHTML(&bstrBody);
// CString szBody(bstrBody);
// ::SysFreeString(bstrBody);
//
// return szBody;
// }
// return CString();
//}
//
//CString CEditMsgDlg::InternalGetMsgText()
//{
// IDispatch *pDisp = m_MsgEdit.get_DOM();
// if (pDisp)
// {
// IHTMLElement *pBody;
// BSTR bstrBody;
// IHTMLDocument2 *pDoc = (IHTMLDocument2 *)pDisp;
// pDoc->get_body(&pBody);
// pBody->get_innerText(&bstrBody);
// CString szBody(bstrBody);
// ::SysFreeString(bstrBody);
//
// return szBody;
// }
// return CString();
//}
//
//void CEditMsgDlg::InternalSetMsgHtml(CString szMsgHtml)
//{
// BSTR bstrBody = szMsgHtml.AllocSysString();
// IDispatch *pDisp = m_MsgEdit.get_DOM();
// if (pDisp)
// {
// IHTMLDocument2 *pDoc = (IHTMLDocument2 *)pDisp;
// IHTMLElement *pBody;
// pDoc->get_body(&pBody);
// pBody->put_innerHTML(bstrBody);
//
// ::SysFreeString(bstrBody);
// }
//}
void CEditMsgDlg::OnBnClickedOk()
{
//bodyInnerHtml = InternalGetMsgHtml();
//bodyInnerText = InternalGetMsgText();
this->GetDlgItemText(IDC_EDIT1, bodyInnerHtml);
this->GetDlgItemText(IDC_EDIT1, bodyInnerText);
if (bodyInnerText.IsEmpty())
{
MessageBox("没有输入任何消息内容。", "错误", MB_ICONERROR);
return;
}
OnOK();
}
//BEGIN_EVENTSINK_MAP(CEditMsgDlg, CDialog)
////ON_EVENT(CEditMsgDlg, IDC_DHTML_EDIT_MSG, 1, CEditMsgDlg::DocumentCompleteDhtmlEditMsg, VTS_NONE)
//END_EVENTSINK_MAP()
//
//void CEditMsgDlg::DocumentCompleteDhtmlEditMsg()
//{
// if (!bodyInnerHtml.IsEmpty())
// {
// InternalSetMsgHtml(bodyInnerHtml);
// }
//}
|
[
"[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395"
] |
[
[
[
1,
137
]
]
] |
6f9561fbd9f89faea61ef2f3617618cedadf3bde
|
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
|
/ xcommon/CImage/CIMAGE/SRC/imajpeg.h
|
0bf8098a402a621c729c8b57005753d1b98b886f
|
[] |
no_license
|
wermanhme1990/xcommon
|
49d7185a28316d46992ad9311ae9cdfe220cb586
|
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
|
refs/heads/master
| 2016-09-06T12:43:43.593776 | 2008-12-05T04:24:11 | 2008-12-05T04:24:11 | 39,864,906 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,744 |
h
|
// imajpeg.h : interface of the CImageJPEG class
/*
* Purpose: JPG Image Class Loader and Writer
*/
/* === C R E D I T S & D I S C L A I M E R S ==============
* CImageJPEG (c) 07/Aug/2001 <[email protected]>
* Permission is given by the author to freely redistribute and include
* this code in any program as long as this credit is given where due.
*
* original CImageJPEG and CImageIterator implementation are:
* Copyright: (c) 1995, Alejandro Aguilar Sierra <[email protected]>
*
* This software is based in part on the work of the Independent JPEG Group.
* Copyright (C) 1991-1998, Thomas G. Lane.
*
* COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
* OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
* THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
* OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
* CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
* THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
* SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
* PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER.
*
* Use at your own risk!
* ==========================================================
*/
#ifndef __JPEG_H__
#define __JPEG_H__
#include "..\include\cimage.h"
class CImageJPEG: public CImage
{
public:
CImageJPEG(): CImage() {}
// Implementation
public:
virtual BOOL Read(FILE*);
virtual BOOL Write(FILE*);
};
#endif // __JPEG_H__
|
[
"[email protected]"
] |
[
[
[
1,
47
]
]
] |
8ecc09ac0908ff3f9098a9d0736b55b118488b54
|
2982a765bb21c5396587c86ecef8ca5eb100811f
|
/util/wm5/LibMathematics/Rational/Wm5Integer.inl
|
cc67d0c92437b436346d27c3f030ab15f815659d
|
[] |
no_license
|
evanw/cs224final
|
1a68c6be4cf66a82c991c145bcf140d96af847aa
|
af2af32732535f2f58bf49ecb4615c80f141ea5b
|
refs/heads/master
| 2023-05-30T19:48:26.968407 | 2011-05-10T16:21:37 | 2011-05-10T16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null |
UTF-8
|
C++
| false | false | 32,740 |
inl
|
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
template <int N>
Integer<N>::Integer (int i)
{
if (i >= 0)
{
memset(mBuffer, 0, INT_BYTES);
}
else
{
memset(mBuffer, 0xFF, INT_BYTES);
}
memcpy(mBuffer, &i, sizeof(int));
#ifdef WM5_BIG_ENDIAN
short save = mBuffer[0];
mBuffer[0] = mBuffer[1];
mBuffer[1] = save;
#endif
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>::Integer (const Integer& value)
{
memcpy(mBuffer, value.mBuffer, INT_BYTES);
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>::~Integer ()
{
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator= (const Integer& value)
{
memcpy(mBuffer, value.mBuffer, INT_BYTES);
return *this;
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetSign () const
{
return (mBuffer[INT_LAST] & 0x8000) ? -1 : +1;
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator== (const Integer& value) const
{
return Compare(*this, value) == 0;
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator!= (const Integer& value) const
{
return Compare(*this, value) != 0;
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator< (const Integer& value) const
{
int s0 = GetSign();
int s1 = value.GetSign();
if (s0 > 0)
{
if (s1 > 0)
{
return Compare(*this, value) < 0;
}
else
{
return false;
}
}
else
{
if (s1 > 0)
{
return true;
}
else
{
return Compare(*this, value) < 0;
}
}
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator<= (const Integer& value) const
{
int s0 = GetSign();
int s1 = value.GetSign();
if (s0 > 0)
{
if (s1 > 0)
{
return Compare(*this, value) <= 0;
}
else
{
return false;
}
}
else
{
if (s1 > 0)
{
return true;
}
else
{
return Compare(*this, value) <= 0;
}
}
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator> (const Integer& value) const
{
int s0 = GetSign();
int s1 = value.GetSign();
if (s0 > 0)
{
if (s1 > 0)
{
return Compare(*this, value) > 0;
}
else
{
return true;
}
}
else
{
if (s1 > 0)
{
return false;
}
else
{
return Compare(*this, value) > 0;
}
}
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::operator>= (const Integer& value) const
{
int s0 = GetSign();
int s1 = value.GetSign();
if (s0 > 0)
{
if (s1 > 0)
{
return Compare(*this, value) >= 0;
}
else
{
return true;
}
}
else
{
if (s1 > 0)
{
return false;
}
else
{
return Compare(*this, value) >= 0;
}
}
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::Compare (const Integer<N>& value0, const Integer<N>& value1)
{
for (int i = INT_LAST; i >= 0; --i)
{
unsigned int uiValue0 = (unsigned int)value0.mBuffer[i];
unsigned int uiValue1 = (unsigned int)value1.mBuffer[i];
if (uiValue0 < uiValue1)
{
return -1;
}
else if (uiValue0 > uiValue1)
{
return +1;
}
}
return 0;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator- () const
{
Integer result = *this;
// Negate the bits.
int i;
for (i = 0; i < INT_SIZE; ++i)
{
result.mBuffer[i] = ~result.mBuffer[i];
}
// Add 1 (place in carry bit and add zero to 'result').
unsigned int carry = 1;
for (i = 0; i < INT_SIZE; ++i)
{
unsigned int b1 = result.ToUnsignedInt(i);
unsigned int sum = b1 + carry;
result.FromUnsignedInt(i, sum);
carry = (sum & 0x00010000) ? 1 : 0;
}
// Test for overflow.
if (result.GetSign() == GetSign())
{
assertion(result == 0, "Integer overflow\n");
}
return result;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator+ (const Integer& value) const
{
Integer result;
unsigned int carry = 0;
for (int i = 0; i < INT_SIZE; ++i)
{
unsigned int b0 = ToUnsignedInt(i);
unsigned int b1 = value.ToUnsignedInt(i);
unsigned int sum = b0 + b1 + carry;
result.FromUnsignedInt(i, sum);
carry = (sum & 0x00010000) ? 1 : 0;
}
// Test for overflow.
if (GetSign() == value.GetSign())
{
assertion(result.GetSign() == GetSign(), "Integer overflow\n");
}
return result;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator- (const Integer& value) const
{
return *this + (-value);
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator* (const Integer& value) const
{
int s0 = GetSign();
int s1 = value.GetSign();
int sProduct = s0*s1;
Integer op0 = (s0 > 0 ? *this : -*this);
Integer op1 = (s1 > 0 ? value : -value);
// Product of single-digit number with multiple-digit number.
unsigned short product[2*INT_SIZE];
unsigned short* pCurrent = product;
// Product of the two multiple-digit operands.
unsigned short result[2*INT_SIZE];
unsigned short* rCurrent = result;
memset(result,0,2*INT_BYTES);
for (int i0 = 0, size = 2*INT_SIZE; i0 < INT_SIZE; ++i0, --size)
{
unsigned int b0 = op0.ToUnsignedInt(i0);
if (b0 > 0)
{
unsigned short* pBuffer = pCurrent;
unsigned int carry = 0;
int i1;
for (i1 = 0; i1 < INT_SIZE; ++i1)
{
unsigned int b1 = op1.ToUnsignedInt(i1);
unsigned int prod = b0*b1 + carry;
*pBuffer++ = (unsigned short)(prod & 0x0000FFFF);
carry = (prod & 0xFFFF0000) >> 16;
}
*pBuffer = (unsigned short)carry;
unsigned short* rBuffer = rCurrent;
pBuffer = pCurrent;
carry = 0;
unsigned int sum, term0, term1;
for (i1 = 0; i1 <= INT_SIZE; ++i1)
{
term0 = (unsigned int)(*pBuffer++);
term1 = (unsigned int)(*rBuffer);
sum = term0 + term1 + carry;
*rBuffer++ = (unsigned short)(sum & 0x0000FFFF);
carry = (sum & 0x00010000) ? 1 : 0;
}
for (/**/; carry > 0 && i1 < size; i1++)
{
term0 = (unsigned int)(*rBuffer);
sum = term0 + carry;
*rBuffer++ = (unsigned short)(sum & 0x0000FFFF);
carry = (sum & 0x00010000) ? 1 : 0;
}
}
pCurrent++;
rCurrent++;
}
// Test for overflow. You can test earlier inside the previous loop, but
// testing here allows you to get an idea of how much overflow there is.
// This information might be useful for an application to decide how large
// to choose the integer size.
for (int i = 2*INT_SIZE-1; i >= INT_SIZE; --i)
{
assertion(result[i] == 0, "Integer overflow\n");
}
assertion((result[INT_LAST] & 0x8000) == 0, "Integer overflow\n");
Integer intResult;
memcpy(intResult.mBuffer, result, INT_BYTES);
if (sProduct < 0)
{
intResult = -intResult;
}
return intResult;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> operator* (int i, const Integer<N>& value)
{
return value*i;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator/ (const Integer& value) const
{
// TO DO. On division by zero, return INVALID or signed INFINITY?
Integer quotient, remainder;
return GetDivMod(*this, value, quotient, remainder) ? quotient : 0;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator% (const Integer& value) const
{
// TO DO. On division by zero, return INVALID or signed INFINITY?
Integer quotient, remainder;
return GetDivMod(*this, value, quotient, remainder) ? remainder : 0;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator+= (const Integer& value)
{
*this = *this + value;
return *this;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator-= (const Integer& value)
{
*this = *this - value;
return *this;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator*= (const Integer& value)
{
*this = *this * value;
return *this;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator/= (const Integer& value)
{
*this = *this / value;
return *this;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator<< (int shift) const
{
if (shift < 0)
{
return 0;
}
if (shift == 0)
{
return *this;
}
// Number of 16-bit blocks to shift.
Integer result;
int blocks = shift/16;
if (blocks > INT_LAST)
{
return 0;
}
int i;
if (blocks > 0)
{
int j = INT_LAST - blocks;
for (i = INT_LAST; j >= 0; --i, --j)
{
result.mBuffer[i] = mBuffer[j];
}
for (/**/; i >= 0; --i)
{
result.mBuffer[i] = 0;
}
}
// Number of left-over bits to shift.
int bits = shift % 16;
if (bits > 0)
{
unsigned int lo, hi, value;
int iM1;
for (i = INT_LAST, iM1 = i - 1; iM1 >= 0; --i, --iM1)
{
lo = ToUnsignedInt(iM1);
hi = ToUnsignedInt(i);
value = (lo | (hi << 16));
value <<= bits;
result.FromUnsignedInt(i, ((0xFFFF0000 & value) >> 16));
}
value = ToUnsignedInt(0);
value <<= bits;
result.FromUnsignedInt(0, (0x0000FFFF & value));
}
return result;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N> Integer<N>::operator>> (int shift) const
{
if (shift < 0)
{
return 0;
}
if (shift == 0)
{
return *this;
}
// Number of 16-bit blocks to shift.
Integer result;
int blocks = shift/16;
if (blocks > INT_LAST)
{
return 0;
}
int i;
if (blocks > 0)
{
int j = blocks;
for (i = 0; j <= INT_LAST; ++i, ++j)
{
result.mBuffer[i] = mBuffer[j];
}
if (GetSign() > 0)
{
for (/**/; i <= INT_LAST; ++i)
{
result.mBuffer[i] = 0;
}
}
else
{
for (/**/; i <= INT_LAST; ++i)
{
result.mBuffer[i] = (short)(0x0000FFFFu);
}
}
}
// Number of left-over bits to shift.
int bits = shift % 16;
if (bits > 0)
{
unsigned int value;
int p1;
for (i = 0, p1 = 1; p1 <= INT_LAST; ++i, ++p1)
{
value = ToUnsignedInt(i, p1);
value >>= bits;
result.FromUnsignedInt(i, value);
}
value = ToUnsignedInt(INT_LAST);
if (GetSign() < 0)
{
value |= 0xFFFF0000; // sign extension
}
value >>= bits;
result.FromUnsignedInt(INT_LAST, value);
}
return result;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator<<= (int shift)
{
if (shift <= 0)
{
return *this;
}
// Number of 16-bit blocks to shift.
int blocks = shift/16;
if (blocks > INT_LAST)
{
return *this;
}
int i;
if (blocks > 0)
{
int j = INT_LAST - blocks;
for (i = INT_LAST; j >= 0; --i, --j)
{
mBuffer[i] = mBuffer[j];
}
for (/**/; i >= 0; --i)
{
mBuffer[i] = 0;
}
}
// Number of left-over bits to shift.
int bits = shift % 16;
if (bits > 0)
{
unsigned int value;
int m1;
for (i = INT_LAST, m1 = i-1; m1 >= 0; i--, m1--)
{
value = ToUnsignedInt(m1, i);
value <<= bits;
FromUnsignedInt(i, ((0xFFFF0000 & value) >> 16));
}
value = ToUnsignedInt(0);
value <<= bits;
FromUnsignedInt(0, (0x0000FFFF & value));
}
return *this;
}
//----------------------------------------------------------------------------
template <int N>
Integer<N>& Integer<N>::operator>>= (int shift)
{
if (shift <= 0)
{
return *this;
}
// Number of 16-bit blocks to shift.
int blocks = shift/16;
if (blocks > INT_LAST)
{
return *this;
}
int i;
if (blocks > 0)
{
int j = blocks;
for (i = 0, j = blocks; j <= INT_LAST; ++i, ++j)
{
mBuffer[i] = mBuffer[j];
}
if (GetSign() > 0)
{
for (/**/; i <= INT_LAST; ++i)
{
mBuffer[i] = 0;
}
}
else
{
for (/**/; i <= INT_LAST; ++i)
{
mBuffer[i] = -1;
}
}
}
// Number of left-over bits to shift.
int bits = shift % 16;
if (bits > 0)
{
unsigned int value;
int p1;
for (i = 0, p1 = 1; p1 <= INT_LAST; ++i, ++p1)
{
value = ToUnsignedInt(i, p1);
value >>= bits;
FromUnsignedInt(i, value);
}
value = ToUnsignedInt(INT_LAST);
if (GetSign() < 0)
{
value |= 0xFFFF0000; // sign extension
}
value >>= bits;
FromUnsignedInt(INT_LAST, value);
}
return *this;
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::GetDivMod (const Integer& numer, const Integer& denom,
Integer& quotient, Integer& remainder)
{
if (denom == 0)
{
assertion(false, "Division by zero\n");
quotient = 0;
remainder = 0;
return false;
}
if (numer == 0)
{
quotient = 0;
remainder = 0;
return true;
}
// Work with the absolute values of the numerator and denominator.
int s0 = numer.GetSign();
int s1 = denom.GetSign();
Integer absNumer = s0*numer;
Integer absDenom = s1*denom;
int compare = Compare(absNumer, absDenom);
if (compare < 0)
{
// numerator < denominator: numerator = 0*denominator + numerator
quotient = 0;
remainder = numer;
return true;
}
if (compare == 0)
{
// numerator == denominator: numerator = 1*denominator + 0
quotient = 1;
remainder = 0;
return true;
}
// numerator > denominator, do the division to find quotient and remainder
if (absDenom > 0x0000FFFF)
{
DivMultiple(absNumer, absDenom, quotient, remainder);
}
else
{
DivSingle(absNumer, absDenom.mBuffer[0], quotient, remainder);
}
// Apply the original signs of numerator and denominator.
quotient *= s0*s1;
remainder *= s0;
#ifdef _DEBUG
Integer test = numer - denom*quotient - remainder;
assertion(test == 0, "Invalid result\n");
#endif
return true;
}
//----------------------------------------------------------------------------
template <int N>
void Integer<N>::DivSingle (const Integer& numer, short denom,
Integer& quotient, Integer& remainder)
{
// The denominator is a single "digit".
unsigned int uiDenom = 0x0000FFFF & (unsigned int)denom;
// Get the numerator.
int nStart = numer.GetLeadingBlock();
const short* numBuffer = &numer.mBuffer[nStart];
unsigned int digit1 = 0;
// Get the quotient.
short* quoBuffer = "ient.mBuffer[nStart];
quotient = 0;
int lastNonZero = -1;
for (int i = nStart; i >= 0; --i, --numBuffer, --quoBuffer)
{
unsigned int digitB = digit1;
digit1 = 0x0000FFFF & (unsigned int)(*numBuffer);
unsigned int uiNumer = (digitB << 16) | digit1;
unsigned int uiQuotient = uiNumer/uiDenom;
digit1 = uiNumer - uiQuotient*uiDenom;
*quoBuffer = (short)(uiQuotient & 0x0000FFFF);
if (lastNonZero == -1 && uiQuotient > 0)
{
lastNonZero = i;
}
}
assertion(lastNonZero >= 0, "Unexpected result\n");
// Get the remainder.
remainder = 0;
if (digit1 & 0xFFFF0000)
{
memcpy(remainder.mBuffer, &digit1, 2*sizeof(short));
#ifdef WM5_BIG_ENDIAN
short save = remainder.mBuffer[0];
remainder.mBuffer[0] = remainder.mBuffer[1];
remainder.mBuffer[1] = save;
#endif
}
else
{
unsigned short tmp = (unsigned short)digit1;
memcpy(remainder.mBuffer, &tmp, sizeof(short));
}
}
//----------------------------------------------------------------------------
template <int N>
void Integer<N>::DivMultiple (const Integer& numer,
const Integer& denom, Integer& quotient, Integer& remainder)
{
quotient = 0;
remainder = 0;
// Normalization to allow good estimate of quotient. TO DO: It is
// possible that the numerator is large enough that normalization causes
// overflow when computing the product adjust*numer; an assertion will
// fire in this case. Ideally, the overflow would be allowed and the
// digit in the overflow position becomes the first digit of the numerator
// in the division algorithm. This will require a mixture of Integer<N>
// and Integer<N+1>, though.
int dInit = denom.GetLeadingBlock();
int leadingDigit = denom.ToInt(dInit);
int adjust = 0x10000/(leadingDigit + 1);
Integer adjNum = adjust*numer;
Integer adjDen = adjust*denom;
assertion(adjDen.GetLeadingBlock() == dInit, "Unexpected result\n");
// Get first two "digits" of denominator.
unsigned int d1 = adjDen.ToUnsignedInt(dInit);
unsigned int d2 = adjDen.ToUnsignedInt(dInit - 1);
// Determine the maximum necessary division steps.
int nInit = adjNum.GetLeadingBlock();
assertion(nInit >= dInit, "Unexpected result\n");
int qInit;
unsigned int rHat;
if (nInit != dInit)
{
qInit = nInit - dInit - 1;
rHat = 1;
}
else
{
qInit = 0;
rHat = 0;
}
for (/**/; qInit >= 0; --qInit)
{
// Get first three indices of remainder.
unsigned int n0, n1, n2;
if (rHat > 0)
{
n0 = adjNum.ToUnsignedInt(nInit--);
n1 = adjNum.ToUnsignedInt(nInit--);
n2 = adjNum.ToUnsignedInt(nInit);
}
else
{
n0 = 0;
n1 = adjNum.ToUnsignedInt(nInit--);
n2 = adjNum.ToUnsignedInt(nInit);
}
// Estimate the quotient.
unsigned int tmp = (n0 << 16) | n1;
unsigned int qHat = (n0 != d1 ? tmp/d1 : 0x0000FFFF);
unsigned int prod = qHat*d1;
assertion(tmp >= prod, "Unexpected result\n");
rHat = tmp - prod;
if (d2*qHat > 0x10000*rHat + n2)
{
qHat--;
rHat += d1;
if (d2*qHat > 0x10000*rHat + n2)
{
// If this block is entered, we have exactly the quotient for
// the division. The adjustment block of code later cannot
// happen.
qHat--;
rHat += d1;
}
}
// Compute the quotient for this step of the division.
Integer localQuo;
localQuo.FromUnsignedInt(qInit, qHat);
// Compute the remainder.
Integer product = localQuo*adjDen;
adjNum -= product;
if (adjNum < 0)
{
qHat--;
adjNum += adjDen;
assertion(adjNum >= 0, "Unexpected result\n");
}
// Set quotient digit.
quotient.FromUnsignedInt(qInit, qHat);
if (adjNum >= adjDen)
{
// Prepare to do another division step.
nInit = adjNum.GetLeadingBlock();
}
else
{
// Remainder is smaller than divisor, finished dividing.
break;
}
}
// Unnormalize the remainder.
if (adjNum > 0)
{
short divisor = (short)(adjust & 0x0000FFFF);
Integer shouldBeZero;
DivSingle(adjNum, divisor, remainder, shouldBeZero);
}
else
{
remainder = 0;
}
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetLeadingBlock () const
{
for (int i = INT_LAST; i >= 0; --i)
{
if (mBuffer[i] != 0)
{
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetTrailingBlock () const
{
for (int i = 0; i <= INT_LAST; ++i)
{
if (mBuffer[i] != 0)
{
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetLeadingBit (int i) const
{
assertion(0 <= i && i <= INT_LAST, "Input out of range\n");
if (i < 0 || i > INT_LAST)
{
return -1;
}
// This is a binary search for the high-order bit of mBuffer[i]. The
// return value is the index into the bits (0 <= index < 16).
int value = (int)mBuffer[i];
if ((value & 0xFF00) != 0)
{
if ((value & 0xF000) != 0)
{
if ((value & 0xC000) != 0)
{
if ((value & 0x8000) != 0)
{
return 15;
}
else // (value & 0x4000) != 0
{
return 14;
}
}
else // (value & 0x3000) != 0
{
if ((value & 0x2000) != 0)
{
return 13;
}
else // (value & 0x1000) != 0
{
return 12;
}
}
}
else // (value & 0x0F00) != 0
{
if ((value & 0x0C00) != 0)
{
if ((value & 0x0800) != 0)
{
return 11;
}
else // (value & 0x0400) != 0
{
return 10;
}
}
else // (value & 0x0300) != 0
{
if ((value & 0x0200) != 0)
{
return 9;
}
else // (value & 0x0100) != 0
{
return 8;
}
}
}
}
else // (value & 0x00FF)
{
if ((value & 0x00F0) != 0)
{
if ((value & 0x00C0) != 0)
{
if ((value & 0x0080) != 0)
{
return 7;
}
else // (value & 0x0040) != 0
{
return 6;
}
}
else // (value & 0x0030) != 0
{
if ((value & 0x0020) != 0)
{
return 5;
}
else // (value & 0x0010) != 0
{
return 4;
}
}
}
else // (value & 0x000F) != 0
{
if ((value & 0x000C) != 0)
{
if ((value & 0x0008) != 0)
{
return 3;
}
else // (value & 0x0004) != 0
{
return 2;
}
}
else // (value & 0x0003) != 0
{
if ((value & 0x0002) != 0)
{
return 1;
}
else // (value & 0x0001) != 0
{
return 0;
}
}
}
}
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetTrailingBit (int i) const
{
assertion(0 <= i && i <= INT_LAST, "Input out of range\n");
if (i < 0 || i > INT_LAST)
{
return -1;
}
// This is a binary search for the low-order bit of mBuffer[i]. The
// return value is the index into the bits (0 <= index < 16).
int value = (int)mBuffer[i];
if ((value & 0x00FF) != 0)
{
if ((value & 0x000F) != 0)
{
if ((value & 0x0003) != 0)
{
if ((value & 0x0001) != 0)
{
return 0;
}
else // (value & 0x0002) != 0
{
return 1;
}
}
else // (value & 0x000C) != 0
{
if ((value & 0x0004) != 0)
{
return 2;
}
else // (value & 0x0080) != 0
{
return 3;
}
}
}
else // (value & 0x00F0) != 0
{
if ((value & 0x0030) != 0)
{
if ((value & 0x0010) != 0)
{
return 4;
}
else // (value & 0x0020) != 0
{
return 5;
}
}
else // (value & 0x00C0) != 0
{
if ((value & 0x0040) != 0)
{
return 6;
}
else // (value & 0x0080) != 0
{
return 7;
}
}
}
}
else // (value & 0xFF00)
{
if ((value & 0x0F00) != 0)
{
if ((value & 0x0300) != 0)
{
if ((value & 0x0100) != 0)
{
return 8;
}
else // (value & 0x0200) != 0
{
return 9;
}
}
else // (value & 0x0C00) != 0
{
if ((value & 0x0400) != 0)
{
return 10;
}
else // (value & 0x0800) != 0
{
return 11;
}
}
}
else // (value & 0xF000) != 0
{
if ((value & 0x3000) != 0)
{
if ((value & 0x1000) != 0)
{
return 12;
}
else // (value & 0x2000) != 0
{
return 13;
}
}
else // (value & 0xC000) != 0
{
if ((value & 0x4000) != 0)
{
return 14;
}
else // (value & 0x8000) != 0
{
return 15;
}
}
}
}
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetLeadingBit () const
{
int block = GetLeadingBlock();
if (block >= 0)
{
int bit = GetLeadingBit(block);
if (bit >= 0)
{
return bit + 16*block;
}
}
return -1;
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::GetTrailingBit () const
{
int block = GetTrailingBlock();
if (block >= 0)
{
int bit = GetTrailingBit(block);
if (bit >= 0)
{
return bit + 16*block;
}
}
return -1;
}
//----------------------------------------------------------------------------
template <int N>
void Integer<N>::SetBit (int i, bool on)
{
// assert(0 <= i && i <= INT_LAST);
int block = i/16;
int bit = i % 16;
if (on)
{
mBuffer[block] |= (1 << bit);
}
else
{
mBuffer[block] &= ~(1 << bit);
}
}
//----------------------------------------------------------------------------
template <int N>
bool Integer<N>::GetBit (int i) const
{
// assert(0 <= i && i <= INT_LAST);
int block = i/16;
int bit = i % 16;
return (mBuffer[block] & (1 << bit)) != 0;
}
//----------------------------------------------------------------------------
template <int N>
unsigned int Integer<N>::ToUnsignedInt (int i) const
{
// assert(0 <= i && i <= INT_LAST);
return 0x0000FFFF & (unsigned int)mBuffer[i];
}
//----------------------------------------------------------------------------
template <int N>
void Integer<N>::FromUnsignedInt (int i, unsigned int value)
{
// assert(0 <= i && i <= INT_LAST);
mBuffer[i] = (short)(value & 0x0000FFFF);
}
//----------------------------------------------------------------------------
template <int N>
unsigned int Integer<N>::ToUnsignedInt (int lo, int hi) const
{
unsigned int uiLo = ToUnsignedInt(lo);
unsigned int uiHi = ToUnsignedInt(hi);
return (uiLo | (uiHi << 16));
}
//----------------------------------------------------------------------------
template <int N>
int Integer<N>::ToInt (int i) const
{
// assert(0 <= i && i <= INT_LAST);
return (int)(0x0000FFFF & (unsigned int)mBuffer[i]);
}
//----------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
1220
]
]
] |
009fac127c47efd0aa7cae8f89db4997a3c81202
|
9df4b47eb2d37fd7f08b8e723e17f733fd21c92b
|
/plugintemplate/libs/lib_ini.cpp
|
2a0855a16894bc47b819deeddcdcbb6b67178465
|
[] |
no_license
|
sn4k3/sourcesdk-plugintemplate
|
d5a806f8793ad328b21cf8e7af81903c98b07143
|
d89166b79a92b710d275c817be2fb723f6be64b5
|
refs/heads/master
| 2020-04-09T07:11:55.754168 | 2011-01-23T22:58:09 | 2011-01-23T22:58:09 | 32,112,282 | 1 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 21,447 |
cpp
|
//========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============
// Plugin Template
//
// Please Read (LICENSE.txt) and (README.txt)
// Dont Forget Visit:
// (http://www.sourceplugins.com) -> VPS Plugins
// (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins
//
//===================================================================================
#define NO_INCLUDE_LIBRARIES
#include "includes/default.h"
#include "libs/lib_ini.h"
#include "tier0/memdbgon.h"
LIB_INI_CLASS::LIB_INI_CLASS()
{
Reset();
}
LIB_INI_CLASS::LIB_INI_CLASS(const char *file, bool autoload /*= false*/)
{
Reset();
pathFile = file;
if(autoload)
Load();
}
LIB_INI_CLASS::~LIB_INI_CLASS()
{
Reset();
fileHearder.~BasicStr();
}
void LIB_INI_CLASS::Reset(bool unsetFile /*= true*/)
{
if(unsetFile) pathFile = NULL;
fileHearder.Clean();
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
map_itn->second->RemoveAll();
map_file.clear();
}
bool LIB_INI_CLASS::Load()
{
return Load(pathFile);
}
bool LIB_INI_CLASS::Load(const char *file)
{
if(!file) return false;
if(!VAR_IFACE_FILESYSTEM->FileExists(file)) return false;
FileHandle_t pFile = VAR_IFACE_FILESYSTEM->Open(file, "rb");
if(!pFile) return false;
Reset();
pathFile = LIB_STRING_CLASS::StrNew(file);
char line[MAX_STR_LENGTH], section[MAX_STR_LENGTH], entry[MAX_STR_LENGTH], value[MAX_STR_LENGTH];
char *lastsection = NULL, *szComment = NULL;
//IniKeyValue iniKeyValue_temp;
//IniKey iniKey_temp;
unsigned int i = 0; /*loc = 0, loc2 = 0, loc3 = 0,*/
int comment = 0, includeOther = 0;
while (!VAR_IFACE_FILESYSTEM->EndOfFile(pFile))
{
if(!VAR_IFACE_FILESYSTEM->ReadLine(line, sizeof(line), pFile))
continue;
if (!line || line[0] == '\n' || line[0] == '\r' || (lastsection && (line[0] == '#' || line[0] == ';' || (line[0] == '/' && line[0+1] == '/'))))
continue;
comment = -1;
includeOther = -1;
for(i = 0; i < strlen(line); i++)
{
if(line[i] == '\r' || line[i] == '\n')
line[i] = '\0';
/*else if(line[i] == '[')
loc = i+1;
else if(line[i] == ']')
loc2 = i-1;
else if(line[i] == '=')
loc3 = i;*/
else if(line[i] == ';' || line[i] == '#' || (line[i] == '/' && line[i-1] == '/'))
comment = i+1;
else if(line[i] == '>' && line[i-1] == '-')
includeOther = i+1;
}
if(includeOther != -1)
{
char *fileToinclude = LIB_STRING_CLASS::SubStr(line, includeOther, strlen(line));
fileToinclude = LIB_STRING_CLASS::StrTrim(fileToinclude);
Join(fileToinclude);
}
szComment = NULL;
if(comment != -1)
{
szComment = LIB_STRING_CLASS::SubStr(line, comment, strlen(line));
szComment = LIB_STRING_CLASS::StrTrim(szComment);
if(!lastsection && szComment)
{
if(fileHearder.IsNULL()) fileHearder = BasicStr("// ");
else fileHearder.Cat("// ");
fileHearder.Cat(szComment);
fileHearder.Cat("\n");
}
}
if (sscanf(line, "[%[^]]", section) == 1)
{
//IniKey iniKey_temp;
//iniKey_temp.szKey = LIB_STRING_CLASS::StrNew(section);
//iniKey_temp.szComment = szComment ? LIB_STRING_CLASS::StrNew(szComment) : NULL;
lastsection = section;
if(!Exists(section))
map_file[BasicStr(section)] = new CUtlVector<IniKeyValue>();
continue;
}
// else
if ((sscanf (line, "%[^=] = \"%[^\"]\"", entry, value) == 2)
|| (sscanf (line, "%[^=] = '%[^\']'", entry, value) == 2)
|| (sscanf (line, "%[^=] = %[^;#]", entry, value) == 2)
|| (sscanf (line, "%[^=]=\"%[^\"]\"", entry, value) == 2)
|| (sscanf (line, "%[^=]='%[^\']'", entry, value) == 2)
|| (sscanf (line, "%[^=]=%[^;#]", entry, value) == 2))
{
if(!lastsection) continue;
if ((strcmp (value, "\"\"") == 0) || (strcmp (value, "''") == 0)) continue;
const char *newentry = LIB_STRING_CLASS::StrTrim(entry, true, true);
IniKeyValue iniKeyValue_temp;
iniKeyValue_temp.szKeyName = BasicStr(newentry);
iniKeyValue_temp.szKeyValue = BasicStr(value);
iniKeyValue_temp.szComment = BasicStr(szComment);
map_file[lastsection]->AddToTail(iniKeyValue_temp);
continue;
}
}
VAR_IFACE_FILESYSTEM->Close(pFile);
return true;
}
CUtlVector<const char *>* LIB_INI_CLASS::GetSections()
{
CUtlVector<const char *>* vec = new CUtlVector<const char *>();
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
vec->AddToTail(map_itn->first.ToString());
return vec;
}
CUtlVector<LIB_INI_CLASS::IniKeyValue>* LIB_INI_CLASS::GetSectionKeyValues(const char *section)
{
CUtlVector<IniKeyValue>* vec = new CUtlVector<IniKeyValue>();
map_itn = map_file.find(section);
if(map_itn == map_file.end())
return vec;
for(int i = 0; map_itn->second->Count(); i++)
vec->AddToTail(map_itn->second->Element(i));
return vec;
}
bool LIB_INI_CLASS::Exists(const char *Key)
{
return map_file.find(Key) != map_file.end();
}
bool LIB_INI_CLASS::Exists(const char *Key, const char *KeyName)
{
return GetIndex(Key, KeyName) != -1;
}
bool LIB_INI_CLASS::Remove(const char *Key, bool movedata /*= false*/, const char *forKey /*= NULL*/, bool createIt /*= true*/)
{
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return false;
if(forKey) // Try to move data
{
if(LIB_STRING_CLASS::FStrEq(Key, forKey))
return false;
if(!createIt && !Exists(forKey))
{
return false;
}
for(int i = 0; i < map_itn->second->Count(); i++) // Copy data for the new key
{
IniKeyValue keyvalue = map_itn->second->Element(i);
New(forKey, keyvalue.szKeyName.str, keyvalue.szKeyValue.str, keyvalue.szComment.str, true);
}
}
// Remove data
map_itn->second->RemoveAll();
map_file.erase(map_itn);
return true;
}
unsigned int LIB_INI_CLASS::Remove(const char *Key, const char *KeyName, bool isPartial /*= false*/)
{
unsigned int Rcount = 0;
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return Rcount;
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
if(isPartial)
{
if(!strstr(keyvalue.szKeyName.str, KeyName))
{
Rcount++;
map_itn->second->Remove(i);
}
}
else
{
if(LIB_STRING_CLASS::FStrEq(keyvalue.szKeyName.str, KeyName))
{
Rcount++;
map_itn->second->Remove(i);
}
}
}
return Rcount;
}
unsigned int LIB_INI_CLASS::RemoveAllComments(bool fromKeys, bool fromKeynames)
{
unsigned int rcount = 0;
/*for(int i = 0; i < vec_keys.Count(); i++)
{
if(vec_keys[i].szComment)
{
rcount++;
vec_keys[i].szComment = NULL;
}
}*/
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
for(int i = 0; i < map_itn->second->Count(); i++)
{
map_itn->second->Element(i).szComment.Clean();
rcount++;
}
}
return rcount;
}
unsigned int LIB_INI_CLASS::RemoveComment(const char *Key, bool isPartial /*= false*/)
{
unsigned int Rcount = 0;
/*for(int i = 0; i < vec_keys.Count(); i++)
{
if(isPartial)
{
if(!strstr(vec_keys[i].szKey, Key))
{
Rcount++;
vec_keys[i].szComment = NULL;
}
}
else
{
if(LIB_STRING_CLASS::FStrEq(vec_keys[i].szKey, Key))
{
Rcount++;
vec_keys[i].szComment = NULL;
}
}
}*/
return Rcount;
}
unsigned int LIB_INI_CLASS::RemoveComment(const char *Key, const char *KeyName, bool isPartial /*= false*/)
{
int Rcount = 0;
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return Rcount;
for(int i = 0; i < map_itn->second->Count(); i++)
{
if(isPartial)
{
if(!strstr(map_itn->second->Element(i).szKeyName.str, KeyName))
{
Rcount++;
map_itn->second->Element(i).szComment.Clean();
}
}
else
{
if(LIB_STRING_CLASS::FStrEq(map_itn->second->Element(i).szKeyName.str, KeyName))
{
Rcount++;
map_itn->second->Element(i).szComment.Clean();
}
}
}
return Rcount;
}
bool LIB_INI_CLASS::New(const char *Key, const char *comment /*= NULL*/)
{
if(!Key) return false;
if(Exists(Key)) return false;
map_file[Key] = new CUtlVector<IniKeyValue>();
return true;
}
bool LIB_INI_CLASS::New(const char *Key, const char *keyName, const char *KeyValue, const char *comment /*= NULL*/, bool createIt /*= true*/)
{
if(!Key) return false;
if(!keyName) return false;
if(createIt)
New(Key);
else if(!Exists(Key)) return false;
IniKeyValue inikeyvalue;
inikeyvalue.szKeyName = BasicStr(keyName);
inikeyvalue.szKeyValue = BasicStr(KeyValue);
inikeyvalue.szComment = BasicStr(comment);
map_file[Key]->AddToTail(inikeyvalue);
return true;
}
unsigned int LIB_INI_CLASS::GetCount() const
{
return map_file.size();
}
unsigned int LIB_INI_CLASS::GetCount(const char *Key)
{
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return 0;
return map_itn->second->Count();
}
int LIB_INI_CLASS::GetLine(const char *Key)
{
int Lcount = -1;
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return Lcount;
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
Lcount++;
if(LIB_STRING_CLASS::FStrEq(map_itn->first.str, Key)) break;
}
return Lcount;
}
int LIB_INI_CLASS::GetLine(const char *Key, const char *KeyName)
{
int Lcount = -1;
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return Lcount;
for(int i = 0; i < map_itn->second->Count(); i++)
{
Lcount++;
if(LIB_STRING_CLASS::FStrEq(map_itn->second->Element(i).szKeyName.str, KeyName)) break;
}
return Lcount;
}
int LIB_INI_CLASS::GetIndex(const char *Key, const char *KeyName)
{
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
return -1;
for(int i = 0; i < map_itn->second->Count(); i++)
if(LIB_STRING_CLASS::FStrEq(map_itn->second->Element(i).szKeyName.str, KeyName))
return i;
return -1;
}
/*spt_inikeys_struct SIniLib::GetElement(int keyIndex)
{
spt_inikeys_struct tempStruct;
tempStruct.szKey = NULL;
tempStruct.szComment = NULL;
if(keyIndex > SPT_Ini_Data.Count()-1) return tempStruct;
return SPT_IniKeys_Data[keyIndex];
}
spt_ini_struct SIniLib::GetElement(int keyIndex, int keyNameLine)
{
spt_ini_struct tempStruct;
tempStruct.szKey = NULL;
tempStruct.szKeyName = NULL;
tempStruct.szKeyValue = NULL;
tempStruct.szComment = NULL;
if(keyIndex > SPT_Ini_Data.Count()-1) return tempStruct;
int count = -1;
for(int i = 0; i < SPT_Ini_Data.Count(); i++)
{
if(FStrEq(SPT_Ini_Data[i].szKey, SPT_IniKeys_Data[keyIndex].szKey))
{
count++;
if(count == keyNameLine)
return SPT_Ini_Data[i];
}
}
return tempStruct;
}
SIniLib *SIniLib::GetFirst()
{
if(SPT_Ini_Data.Count() == 0 || SPT_IniKeys_Data.Count() == 0) return NULL;
SIniLib *newIni = new SIniLib(this);
return newIni;
}
SIniLib *SIniLib::GetNextKey()
{
if(iGetNextKey == 0)
{
iGetNextKey++;
return new SIniLib(this);
}
iGetNextKey++;
iGetNextValue = 0;
SIniLib* newIni = new SIniLib(this);
newIni->Delete(0);
if(newIni->SPT_IniKeys_Data.Count() == 0) return NULL;
return newIni;
}
SIniLib *SIniLib::GetNextKeyName()
{
if(SPT_Ini_Data.Count() == 0 || SPT_IniKeys_Data.Count() == 0) return NULL;
if(GetCount(SPT_IniKeys_Data[0].szKey) <= 1) return NULL;
if(iGetNextValue == 0)
{
iGetNextValue++;
return new SIniLib(this);
}
iGetNextValue++;
SIniLib* newIni = new SIniLib(this);
for(int i = 0; i < newIni->SPT_Ini_Data.Count(); i++)
{
if(FStrEq(newIni->SPT_Ini_Data[i].szKey, newIni->SPT_IniKeys_Data[0].szKey))
{
if(newIni->SPT_Ini_Data.Count()-1 == 0) return NULL;
newIni->SPT_Ini_Data.Remove(i);
return newIni;
}
}
return NULL;
}
*/
const char *LIB_INI_CLASS::GetValueStr(const char *Key, const char *KeyName)
{
int index = GetIndex(Key, KeyName);
if(index == -1) return NULL;
return map_file[Key]->Element(index).szKeyValue.ToString();
}
int LIB_INI_CLASS::GetValueInt(const char *Key, const char *KeyName)
{
const char *value = GetValueStr(Key, KeyName);
if(value == NULL) return -1;
return atoi(value);
}
float LIB_INI_CLASS::GetValueFloat(const char *Key, const char *KeyName)
{
const char *value = GetValueStr(Key, KeyName);
if(value == NULL) return -1;
return atof(value);
}
const char *LIB_INI_CLASS::GetComment(const char *Key, const char *KeyName)
{
int index = GetIndex(Key, KeyName);
if(index == -1) return NULL;
return map_file[Key]->Element(index).szComment.ToString();
}
bool LIB_INI_CLASS::SetValue(const char *Key, const char *KeyName, const char *KeyValue, const char *comment /*= NULL*/, bool createIt /*= true*/)
{
if(!Key) return false;
if(!KeyName) return false;
int index = GetIndex(Key, KeyName);
if(index == -1)
{
return createIt ? New(Key, KeyName, KeyValue, comment, true) : false;
}
map_file[Key]->Element(index).szKeyValue = BasicStr(KeyValue);
map_file[Key]->Element(index).szComment = BasicStr(comment);
return true;
}
bool LIB_INI_CLASS::SetComment(const char *Key, const char *KeyName, const char *comment)
{
int index = GetIndex(Key, KeyName);
if(index == -1) return false;
map_file[Key]->Element(index).szComment = BasicStr(comment);
return true;
}
void LIB_INI_CLASS::SetHearder(const char *text, bool appendLine /*= true*/)
{
if(!text) return;
if(!appendLine)
{
fileHearder = BasicStr(text);
}
else
{
if(fileHearder.IsNULL())
fileHearder = BasicStr(text);
else
fileHearder.Cat(text);
}
fileHearder.Cat("\n");
}
bool LIB_INI_CLASS::Rename(const char *Key, const char *NewKey)
{
return Remove(Key, true, NewKey, true);
}
bool LIB_INI_CLASS::Rename(const char *Key, const char *KeyName, const char *NewKeyName)
{
int index = GetIndex(Key, KeyName);
if(index == -1) return false;
map_file[Key]->Element(index).szKeyName = BasicStr(NewKeyName);
return true;
}
/*bool LIB_INI_CLASS::Move(const char *Key, const char matchOperator, int lines)
{
int index = GetIndex(Key);
if(index == -1) return false;
int moveTo = index;
IniKey inikey = vec_keys[index];
switch(matchOperator)
{
case '<':
vec_keys.Remove(index);
vec_keys.AddToHead(inikey);
return true;
case '>':
vec_keys.Remove(index);
vec_keys.AddToTail(inikey);
return true;
case '-':
if(lines <= 0) return false;
moveTo -= lines;
break;
case '+':
if(lines <= 0) return false;
moveTo += lines;
break;
default:
return false;
}
if(moveTo < 0)
moveTo = 0;
else if(moveTo >= vec_keys.Count())
moveTo = vec_keys.Count()-1;
if(moveTo == index) return true;
int elmC = 0;
if(matchOperator == '-')
elmC = vec_keys.InsertBefore(moveTo, inikey);
else
elmC = vec_keys.InsertAfter(moveTo, inikey);
if(elmC < index) index++;
//else if (elmC > index) index--;
vec_keys.Remove(index);
return true;
}*/
bool LIB_INI_CLASS::Move(const char *Key, const char *KeyName, const char matchOperator, int lines)
{
int index = GetIndex(Key, KeyName);
if(index == -1) return false;
int moveTo = index;
IniKeyValue tempme = map_file[Key]->Element(index);
if(matchOperator == '<')
{
map_file[Key]->Remove(index);
map_file[Key]->AddToHead(tempme);
return true;
}
if(matchOperator == '>')
{
map_file[Key]->Remove(index);
map_file[Key]->AddToTail(tempme);
return true;
}
if(lines <= 0) return false;
if(matchOperator == '-')
{ moveTo -= lines;}
else if(matchOperator == '+')
{ moveTo += lines;}
else
return false;
int count = map_file[Key]->Count();
if(moveTo < 0)
moveTo = 0;
else if(moveTo > count-1)
moveTo = count-1;
if(moveTo == index) return true;
int elmC = 0;
if(matchOperator == '-')
elmC = map_file[Key]->InsertBefore(moveTo, tempme);
else
elmC = map_file[Key]->InsertAfter(moveTo, tempme);
if(elmC < index) index++;
//else if (elmC > index) index--;
map_file[Key]->Remove(index/*-1*/);
return true;
}
void LIB_INI_CLASS::Join(LIB_INI_CLASS *toJoin, bool replaceValues /*= false*/)
{
if(!toJoin) return;
for(map_itn = map_file.begin(); map_itn!=toJoin->map_file.end(); ++map_itn)
{
if(!Exists(map_itn->first.str))
New(map_itn->first.str);
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
int index = GetIndex(map_itn->first.str, keyvalue.szKeyName.str);
if(index == -1)
{
New(map_itn->first.str, keyvalue.szKeyName.str, keyvalue.szKeyValue.str, keyvalue.szComment.str);
continue;
}
if(replaceValues)
{
map_itn->second->Element(i).szKeyValue = BasicStr(keyvalue.szKeyValue.str);
map_itn->second->Element(i).szComment = BasicStr(keyvalue.szComment.str);
continue;
}
}
}
}
bool LIB_INI_CLASS::Join(const char *file, bool replaceValues /*= false*/)
{
LIB_INI_CLASS *ini = new LIB_INI_CLASS(file);
if(!ini->Load()) return false;
Join(ini, replaceValues);
ini->~LIB_INI_CLASS();
return true;
}
bool LIB_INI_CLASS::Write(const char *file /*= NULL*/, const char *extraText /*= NULL*/, bool forceCreate /*= true*/)
{
if(!file)
file = pathFile;
if(!file) return false;
if(!forceCreate)
if(!VAR_IFACE_FILESYSTEM->FileExists(file)) return false;
FileHandle_t pFile = VAR_IFACE_FILESYSTEM->Open(file, "w");
if(!fileHearder.IsNULL()) VAR_IFACE_FILESYSTEM->FPrintf(pFile, "%s\n",fileHearder);
if(extraText) VAR_IFACE_FILESYSTEM->FPrintf(pFile, "%s\n",extraText);
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
VAR_IFACE_FILESYSTEM->FPrintf(pFile, "\n[%s]\n",map_itn->first.str);
//if(vec_keys[i].szComment)
// VAR_IFACE_FILESYSTEM->FPrintf(pFile, "\t#%s",vec_keys[i].szComment);
//VAR_IFACE_FILESYSTEM->FPrintf(pFile, "\n");
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
VAR_IFACE_FILESYSTEM->FPrintf(pFile, "%s=%s",keyvalue.szKeyName.str, keyvalue.szKeyValue.str);
if(!keyvalue.szComment.IsNULL())
VAR_IFACE_FILESYSTEM->FPrintf(pFile, "\t#%s", keyvalue.szComment.str);
VAR_IFACE_FILESYSTEM->FPrintf(pFile, "\n");
}
}
VAR_IFACE_FILESYSTEM->Close(pFile);
return true;
}
bool LIB_INI_CLASS::Save(const char *file /*= NULL*/, const char *extraText /*= NULL*/, bool forceCreate /*= true*/)
{
return Write(file, extraText, forceCreate);
}
KeyValues *LIB_INI_CLASS::Convert(const char *nameSpace /*= "Ini2KV"*/)
{
KeyValues *iniToKv = new KeyValues(nameSpace);
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
KeyValues *tempKv = new KeyValues(map_itn->first.str);
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
tempKv->SetString(keyvalue.szKeyName.str, keyvalue.szKeyValue.str);
}
iniToKv->AddSubKey(tempKv);
}
return iniToKv;
}
void LIB_INI_CLASS::Convert(KeyValues *kv)
{
if(!kv) return;
Reset();
KeyValues *tempForeachKv, *tempValueForeachKv;
for(tempForeachKv = kv->GetFirstSubKey(); tempForeachKv; tempForeachKv = tempForeachKv->GetNextKey())
{
const char *Key = tempForeachKv->GetName();
if(!Key) continue;
New(Key);
for(tempValueForeachKv = tempForeachKv->GetFirstValue(); tempValueForeachKv; tempValueForeachKv = tempValueForeachKv->GetNextValue())
{
New(Key, tempValueForeachKv->GetName(), tempValueForeachKv->GetString(), NULL, false);
}
}
}
void LIB_INI_CLASS::SetFilePath(const char *newFile)
{
LIB_STRING_CLASS::StrNew(newFile);
}
void LIB_INI_CLASS::PrintHearder()
{
Msg("\n--------------------------------------\nFile: %s\n\n%s\n",pathFile, fileHearder.str);
Msg("\n--------------------------------------\n\n");
}
void LIB_INI_CLASS::Print(const char *Key /*= NULL*/)
{
Msg("\n--------------------------------------\nFile: %s\n\n",pathFile);
if(Key)
{
map_itn = map_file.find(Key);
if(map_itn == map_file.end())
{
Msg("The section [%s] doesn't exists!\n", Key);
}
else
{
Msg("[%s]\n", Key);
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
Msg("%s=%s", keyvalue.szKeyName.str, keyvalue.szKeyValue.str);
if(!keyvalue.szComment.IsNULL())
Msg("\t#%s", keyvalue.szComment.str);
Msg("\n");
}
}
}
else
{
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
Msg("[%s]\n", map_itn->first.str);
for(int i = 0; i < map_itn->second->Count(); i++)
{
IniKeyValue keyvalue = map_itn->second->Element(i);
Msg("%s=%s", keyvalue.szKeyName.str, keyvalue.szKeyValue.str);
if(!keyvalue.szComment.IsNULL())
Msg("\t#%s", keyvalue.szComment.str);
Msg("\n");
}
Msg("\n");
}
}
Msg("--------------------------------------\n\n");
}
void LIB_INI_CLASS::PrintKeys()
{
Msg("\n--------------------------------------\nFile: %s\n\n",pathFile);
for(map_itn = map_file.begin(); map_itn!=map_file.end(); ++map_itn)
{
Msg("[%s]\n",map_itn->first.str);
}
Msg("\n--------------------------------------\n\n");
}
|
[
"[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b"
] |
[
[
[
1,
814
]
]
] |
afeba6f22cfe3dfc859c61bce81c0c130cb038b2
|
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
|
/ouan-tests/NxOgreSimpleDemo/Application.cpp
|
4a0d9371e01ec18e09edb089be8af1f58600fe1a
|
[] |
no_license
|
juanjmostazo/ouan-tests
|
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
|
eaa73fb482b264d555071f3726510ed73bef22ea
|
refs/heads/master
| 2021-01-10T20:18:35.918470 | 2010-06-20T15:45:00 | 2010-06-20T15:45:00 | 38,101,212 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,591 |
cpp
|
#include "Application.h"
Application::Application()
{
m_root = NULL;
m_window = NULL;
m_sceneMgr = NULL;
m_viewport = NULL;
m_camera = NULL;
m_NXOgreWorld = NULL;
m_NXOgreScene = NULL;
m_NXOgreRenderSystem = NULL;
m_NXOgreTimeController = NULL;
m_exitRequested = false;
m_showInfo = false;
}
Application::~Application()
{
SimpleInputManager::finalise();
delete m_root;
}
bool Application::initialise()
{
//m_root = new Ogre::Root("ogre_plugins.txt", "ogre_config.txt", "ogre_log.txt");
m_root = new Ogre::Root();
bool configDialogUserContinue = m_root->showConfigDialog();
if ( ! configDialogUserContinue )
{
throw std::exception( "User closed/canceled config dialog" );
}
m_window = m_root->initialise(true, "NxOgre Basic Demo");
m_sceneMgr = m_root->createSceneManager(Ogre::ST_GENERIC);
loadResources();
m_camera = m_sceneMgr->createCamera("FixedCamera");
m_camera->setNearClipDistance(0.1f);
m_camera->setPosition(Ogre::Vector3(0, 5, 20));
m_viewport = m_window->addViewport(m_camera);
SimpleInputManager::initialise(m_window);
m_NXOgreWorld = NxOgre::World::createWorld();
NxOgre::SceneDescription sceneDesc;
sceneDesc.mGravity = NxOgre::Vec3(0, -9.8f, 0);
sceneDesc.mName = "NxOgreScene";
m_NXOgreScene = m_NXOgreWorld->createScene(sceneDesc);
m_NXOgreRenderSystem = new OGRE3DRenderSystem(m_NXOgreScene);
m_NXOgreTimeController = NxOgre::TimeController::getSingleton();
return true;
}
void Application::loadResources()
{
// You can specify as many locations as you want, or have several resource groups that you
// load/unload when you need.
// You may also wish to read the resource locations from a configuration file instead of
// having them hard-coded.
Ogre::ResourceGroupManager& resourceManager = Ogre::ResourceGroupManager::getSingleton();
Ogre::String secName, typeName, archName;
Ogre::ConfigFile cf;
cf.load("resources.cfg");
Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
}
}
resourceManager.initialiseAllResourceGroups();
}
bool Application::setup()
{
Ogre::OverlayManager::getSingleton().getByName("InfoPanel")->show();
m_NXOgreScene->getMaterial(0)->setStaticFriction(0.5);
m_NXOgreScene->getMaterial(0)->setDynamicFriction(0.5);
m_NXOgreScene->getMaterial(0)->setRestitution(0.1);
m_NXOgreRenderSystem->createBody(new NxOgre::Box(1, 1, 1),NxOgre::Vec3(0, 20, 0),"cube.1m.mesh");
m_NXOgreRenderSystem->createBody(new NxOgre::Box(1, 1, 1),NxOgre::Vec3(-1, 30, 0),"cube.1m.mesh");
m_NXOgreRenderSystem->createBody(new NxOgre::Box(1, 1, 1),NxOgre::Vec3(0, 25, 0),"cube.1m.mesh");
m_NXOgreRenderSystem->createBody(new NxOgre::Box(1, 1, 1),NxOgre::Vec3(5, 20, 0),"cube.1m.mesh");
m_NXOgreRenderSystem->createBody(new NxOgre::Box(1, 1, 1),NxOgre::Vec3(-5, 20, 0),"cube.1m.mesh");
m_NXOgreScene->createSceneGeometry(new NxOgre::PlaneGeometry(0, NxOgre::Vec3(0, 1, 0)), Matrix44_Identity);
Ogre::Plane *plane = new Ogre::Plane;
plane->normal = Ogre::Vector3::UNIT_Y;
plane->d = 0;
Ogre::MeshManager::getSingleton().createPlane("ground",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, *plane,
150, 150, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);
Ogre::Entity* pPlaneEnt = m_sceneMgr->createEntity("groundInstance", "ground");
pPlaneEnt->setCastShadows(false);
pPlaneEnt->setMaterialName("Examples/GrassFloor");
m_sceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);
return true;
}
void Application::update()
{
Ogre::Timer loopTimer;
bool continueRunning = true;
while (continueRunning)
{
Ogre::WindowEventUtilities::messagePump();
SimpleInputManager::capture();
float elapsedSeconds = loopTimer.getMicroseconds() * 1.0 / 1000000;
m_NXOgreTimeController->advance(elapsedSeconds);
loopTimer.reset();
updateOverlayInfo();
bool renderFrameSuccess = m_root->renderOneFrame();
if (!renderFrameSuccess || m_exitRequested)
{
continueRunning = false;
}
}
}
void Application::updateOverlayInfo()
{
if (m_showInfo)
{
Ogre::OverlayElement* overlay = Ogre::OverlayManager::getSingleton().getOverlayElement("InfoPanelFps");
overlay->setCaption("Current FPS: "+Ogre::StringConverter::toString(m_window->getLastFPS()));
overlay = Ogre::OverlayManager::getSingleton().getOverlayElement("InfoPanelNTriangles");
overlay->setCaption("Triangle count: "+Ogre::StringConverter::toString(m_window->getTriangleCount()));
}
else
{
Ogre::OverlayElement* overlay = Ogre::OverlayManager::getSingleton().getOverlayElement("InfoPanelFps");
overlay->setCaption("Press I to view Statistics");
overlay = Ogre::OverlayManager::getSingleton().getOverlayElement("InfoPanelNTriangles");
overlay->setCaption("");
}
}
bool Application::keyPressed( const OIS::KeyEvent& e )
{
if ( e.key == OIS::KC_ESCAPE )
{
m_exitRequested = true;
}
if ( e.key == OIS::KC_I )
{
m_showInfo = !m_showInfo;
}
return true;
}
bool Application::mouseMoved( const OIS::MouseEvent& e )
{
return true;
}
|
[
"ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde"
] |
[
[
[
1,
191
]
]
] |
a28e6902b2cd3e8252e73e60e5e796e172032b38
|
c63685bfe2d1ecfdfebcda0eab70642f6fcf4634
|
/Dog_GLSL_ABR/GLSLFilter.h
|
b1933ad61225d55500a3ae7b2f5e439b4d710b69
|
[] |
no_license
|
Shell64/cgdemos
|
8afa9272cef51e6d0544d672caa0142154e231fc
|
d34094d372fea0536a5b3a17a861bb1a1bfac8c4
|
refs/heads/master
| 2021-01-22T23:26:19.112999 | 2011-10-13T12:38:10 | 2011-10-13T12:38:10 | 35,008,078 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 712 |
h
|
#ifndef __GLSL_FILTER_H__
#define __GLSL_FILTER_H__
class ProgramGLSL;
class ShaderObject;
class GLTexImage;
class GLSLFilter
{
public:
GLSLFilter(void);
~GLSLFilter(void);
void Run( GLTexImage* src, GLTexImage* dst );
void CreateGuassianKernel( float sigma );
protected:
class Pass
{
public:
Pass( const char* shader_file );
void Apply( float* kernel, float* offset, int kernelSize );
protected:
ProgramGLSL m_program;
GLint m_kernelParam;
GLint m_offsetParam;
GLint m_kernelSizeParam;
GLint m_texParam;
};
protected:
Pass m_hPass;
Pass m_vPass;
float* m_kernel;
float* m_offset;
int m_kernelSize;
};
#endif//__GLSL_FILTER_H__
|
[
"hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0"
] |
[
[
[
1,
44
]
]
] |
30cc4cc96be468914c09fea00573fa9f7479f810
|
5506729a4934330023f745c3c5497619bddbae1d
|
/vst2.x/tuio/tuio.h
|
466ad939746f924c76405ab9c1ec175139fe0946
|
[] |
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 | 587 |
h
|
#ifndef __tuio_onboard__
#define __tuio_onboard__
namespace Tuio
{
//
//! /tuio/2Dobj set id fi x y a X Y A m r
//! /tuio/2Dcur set id x y X Y m
//
struct Object
{
int id, fi;
float x, y, a, X, Y, A, m, r;
int type, state;
};
struct Listener
{
virtual void startBundle() = 0;
virtual void call( Object & o ) = 0;
virtual void call( int aliveId ) = 0;
};
struct Parser;
struct MessageQueue
{
MessageQueue(Listener & l);
~MessageQueue();
private:
Parser *parser;
};
};
#endif // __tuio_onboard__
|
[
"[email protected]"
] |
[
[
[
1,
40
]
]
] |
8f23cbd0521e27ecb7e4d4d40f6bf70dc87e85fd
|
5e0422794380a8f3bf06d0c37ac2354f4b91fefb
|
/fastnetwork/acceptor_factory.h
|
06398ae8265db1b10b15fc84594c7dc26ee18c81
|
[] |
no_license
|
OrAlien/fastnetwork
|
1d8fb757b855b1f23cc844cda4d8dc7a568bc38e
|
792d28d8b5829c227aebe8378f60db17de4d6f14
|
refs/heads/master
| 2021-05-28T20:30:24.031458 | 2010-06-02T14:30:04 | 2010-06-02T14:30:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 539 |
h
|
#pragma once
#include "transport_type.h"
#include "io_acceptor.h"
#include "udp_acceptor.h"
namespace fastnetwork {
class acceptor_factory
{
public:
acceptor_factory(void){}
~acceptor_factory(void){}
public:
static boost::shared_ptr<io_acceptor> new_acceptor( transport_type type, io_service & ios ) {
boost::shared_ptr<io_acceptor> acceptor;
switch( type ) {
case UDP:
acceptor.reset( new fastnetwork::udp::udp_acceptor(ios) );
break;
default:
break;
}
return acceptor;
}
};
}
|
[
"everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408"
] |
[
[
[
1,
26
]
]
] |
63243fb9f1237658c7ad8cab0b998965fd10a4fd
|
9ad9345e116ead00be7b3bd147a0f43144a2e402
|
/SeedMinerIntegratedSolution/Include/Query/InfixToPostfix.h
|
71004e245727c39546ae0dd0b768805588df5d5b
|
[] |
no_license
|
asankaf/scalable-data-mining-framework
|
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
|
811fddd97f52a203fdacd14c5753c3923d3a6498
|
refs/heads/master
| 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 386 |
h
|
#ifndef INFIXTOPOSTFIX
#define INFIXTOPOSTFIX
#include <iostream>
#include <stack>
#include "Expression.h"
#include "Symbol.h"
#include "And.h"
using namespace std;
class InfixToPostfix
{
private:
Expression* postfixExpression;
bool precedance(Symbol* stackTop,Symbol* inputSymbol);
public:
Expression* makePostfixExpression(Expression* tokens);
};
#endif
|
[
"buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] |
[
[
[
1,
23
]
]
] |
4c9b703229fef4c8554a59949da9fa86f8972dd8
|
baefe42cfbc7b054b87847b28aadafa790a72562
|
/txc2.cc
|
8a8f01feb676a7340d86935304b0aed9ee8c95df
|
[] |
no_license
|
kwygbo/TicToc_pts
|
09238708edf3b5781c2fbc64e9abe62ec9baf145
|
a77c603111ed65982de07bea9c3c402d77bd45fa
|
refs/heads/master
| 2020-05-31T01:19:46.877535 | 2011-09-27T01:58:00 | 2011-09-27T01:58:00 | 2,447,919 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 990 |
cc
|
//
// This file is part of an OMNeT++/OMNEST simulation example.
//
// Copyright (C) 2003 Ahmet Sekercioglu
// Copyright (C) 2003-2008 Andras Varga
//
// This file is distributed WITHOUT ANY WARRANTY. See the file
// `license' for details on this and other legal matters.
//
#include <string.h>
#include <omnetpp.h>
class Txc2 : public cSimpleModule
{
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
};
Define_Module(Txc2);
void Txc2::initialize()
{
if (strcmp("tic", getName()) == 0)
{
// The `ev' object works like `cout' in C++.
EV << "Sending initial message\n";
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}
void Txc2::handleMessage(cMessage *msg)
{
// msg->getName() is name of the msg object, here it will be "tictocMsg".
EV << "Received message `" << msg->getName() << "', sending it out again\n";
send(msg, "out");
}
|
[
"[email protected]"
] |
[
[
[
1,
40
]
]
] |
cf7ef52c2e5287b45a18b9aa34e59361858d4a12
|
a0d4f557ddaf4351957e310478e183dac45d77a1
|
/src/Door/LoadProjectDoor.cpp
|
be7cccd375f2193ce6710874a94e1c504c239a04
|
[] |
no_license
|
houpcz/Houp-s-level-editor
|
1f6216e8ad8da393e1ee151e36fc37246279bfed
|
c762c9f5ed064ba893bf34887293a73dd35a06f8
|
refs/heads/master
| 2016-09-11T11:03:34.560524 | 2011-08-09T11:37:49 | 2011-08-09T11:37:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,225 |
cpp
|
#include <string>
#include "door.h"
#include "DoorSystem.h"
#include "LoadProjectDoor.h"
#include "..\Script\ScriptSystem.h"
#include "..\LevelEditor.h"
#include "..\Utils\FileMan.h"
C_LoadProjectDoor::C_LoadProjectDoor(FILE * fr)
{
Load(fr);
}
C_LoadProjectDoor::C_LoadProjectDoor(int n_x, int n_y, int n_width, int n_height, string n_title)
{
doorKind = D_LOAD_PROJECT;
title = n_title;
x = n_x;
y = n_y;
width = n_width;
height = n_height;
}
C_LoadProjectDoor::~C_LoadProjectDoor()
{
}
void C_LoadProjectDoor::FirstTime()
{
char c_str[256];
sprintf(c_str, "*");
string allFileNames = "";
string temp;
fileName = FileMan::Inst()->GetDirectoryList(c_str);
int clearID = -1;
for(int loop1 = 0; loop1 < fileName.size(); loop1++)
{
temp = fileName[loop1];
if(temp.compare("data") == 0)
{
clearID = loop1;
} else {
allFileNames += temp + ";";
}
}
if(clearID >= 0)
{
fileName.erase(fileName.begin() + clearID, fileName.begin() + clearID + 1);
}
if(fileName.size() > 0)
{
fileNameIndex = 0;
temp = fileName[fileNameIndex];
}
else
{
fileNameIndex = -1;
temp = "None";
allFileNames = "Use new project button";
}
fProjectName = new C_Input(80, 10, 10, 1, temp, allFileNames);
label[0] = new C_Label(5, 10, 4, 1, "Name", "nohelp");
bOk = new C_Button(110, 35, 40, 20, "OK");
bNext = new C_Button(240, 10, 20, 20, ">", FontMan::ALIGN_HCENTER | FontMan::ALIGN_VCENTER, "Shows next file in levels directory");
bBack = new C_Button(215, 10, 20, 20, "<", FontMan::ALIGN_HCENTER | FontMan::ALIGN_VCENTER, "Shows previous file in levels directory");
AddFormElement(fProjectName);
AddFormElement(label[0]);
AddFormElement(bOk);
AddFormElement(bNext);
AddFormElement(bBack);
closeable = true;
resizeableVertical = false;
resizeableHorizontal = false;
minimalizeable = false;
isTitle = true;
SetDontSave(true);
}
void C_LoadProjectDoor::DoorActionDown(int button)
{
C_Door::DoorActionDown(button);
if(button == LEFTBUTTON)
{
if(bOk->GetIsPushedAndUnpush())
{
C_LevelEditor::Inst()->LoadProject(fProjectName->GetString());
// TODO no spaces in project name control
close = true;
}
if(bNext->GetIsPushedAndUnpush())
{
fProjectName->SetActive(false);
if(fileNameIndex >= 0)
{
fileNameIndex = (++fileNameIndex) % fileName.size();
fProjectName->SetTitle(fileName[fileNameIndex]);
}
} else
if(bBack->GetIsPushedAndUnpush())
{
fProjectName->SetActive(false);
if(fileNameIndex >= 0)
{
fileNameIndex = --fileNameIndex;
if(fileNameIndex < 0) fileNameIndex = fileName.size() - 1;
fProjectName->SetTitle(fileName[fileNameIndex]);
}
}
}
}
|
[
"[email protected]"
] |
[
[
[
1,
121
]
]
] |
c0f2637e54e8b168be868d3c13383f1a96a5683a
|
8f816734df7cb71af9c009fa53eeb80a24687e63
|
/EngineCore/include/Camera.h
|
479e1ce0068fb361c58a1af2027f790214b6e6a8
|
[] |
no_license
|
terepe/rpgskyengine
|
46a3a09a1f4d07acf1a04a1bcefff2a9aabebf56
|
fbe0ddc86440025d9670fc39fb7ca72afa223953
|
refs/heads/master
| 2021-01-23T13:18:32.028357 | 2011-06-01T13:35:16 | 2011-06-01T13:35:16 | 35,915,383 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 1,407 |
h
|
#pragma once
#include "BaseCamera.h"
#include "Frustum.h"
#include "Pos2D.h"
#include <windows.h>
class CCamera : public CBaseCamera
{
public:
CCamera();
virtual const Vec3D& getTargetPos(){return m_vTargetPos;}
virtual void setTargetPos(const Vec3D& vPos);
virtual void FrameMove(float fElapsedTime);
virtual void MoveTarget();
virtual void MoveTargetWithPlane();
virtual void MoveAroundTarget();
virtual Vec3D GetViewDir() const { return m_vLookAt - m_vEyePt; }
virtual Vec3D GetCrossDir() const { return (m_vLookAt - m_vEyePt).cross(Vec3D(0,1,0));}
virtual Matrix GetProjXView() const { return m_mProjMatrix*m_mViewMatrix; }
virtual float GetRadius() const { return m_fRadius; }
virtual int BoxCrossF(BBox & bbox) { return m_Frustum.CheckAABBVisible(bbox); }
virtual CFrustum& GetFrustum() { return m_Frustum; }
public:
virtual void GetPickRay(Vec3D& pRayPos, Vec3D& pRayDir,int x, int y,const RECT& rc); // 拾取
virtual void World2Screen(const Vec3D& vWorldPos, Pos2D& posScreen);
protected:
CFrustum m_Frustum; // 视锥
// 对象坐标
Vec3D m_vTargetPos;
// 距离:摄像机到对象的距离
float m_fRadius;
float m_fDefaultRadius;
// 摄像机与目标点之间最小最大半径
float m_fMinRadius,m_fMaxRadius;
// 摄像机最小最大(上下)倾斜角度
float m_fMinPitchAngle,m_fMaxPitchAngle;
};
|
[
"rpgsky.com@97dd8ffa-095c-11df-8772-5d79768f539e"
] |
[
[
[
1,
41
]
]
] |
4b08dc9d4c3ccff16668a40eae2168d3fb703f9b
|
5df145c06c45a6181d7402279aabf7ce9376e75e
|
/src/johnapplication.h
|
36832a253f04bfdceecd9679291889d4b7d834f1
|
[] |
no_license
|
plus7/openjohn
|
89318163f42347bbac24e8272081d794449ab861
|
1ffdcc1ea3f0af43b9033b68e8eca048a229305f
|
refs/heads/master
| 2021-03-12T22:55:57.315977 | 2009-05-15T11:30:00 | 2009-05-15T11:30:00 | 152,690 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 646 |
h
|
#ifndef JOHNAPPLICATION_H
#define JOHNAPPLICATION_H
#include <QtGui/QApplication>
class BookmarksManager;
class BBSMenuManager;
class QSettings;
class JohnApplication : public QApplication
{
public:
JohnApplication( int & argc, char ** argv );
virtual ~JohnApplication();
void setupDB();
static QString profileDir();
static QSettings *settings();
static BookmarksManager *bookmarksManager();
static BBSMenuManager *bbsMenuManager();
private:
static QSettings *m_settings;
static BookmarksManager *m_bookmarkMgr;
static BBSMenuManager *m_bbsMenuMgr;
};
#endif // JOHNAPPLICATION_H
|
[
"[email protected]"
] |
[
[
[
1,
24
]
]
] |
a676fbc42ffe462ebb674683809e87194d4c37ce
|
daf73e5c289ba4726ab62a9593ca2960aab644ce
|
/mmfunctions.h
|
9630052bc2531b613ac67b566bbddb8cc45ea100
|
[] |
no_license
|
rwarrin/MusicMover
|
021fcabe4e6935540e8583f170cd1770be7df78a
|
3aec4f0f37bf54074736bb1658df82f00ecb2d7a
|
refs/heads/master
| 2016-09-06T09:00:58.762532 | 2011-07-01T18:32:06 | 2011-07-01T18:32:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 624 |
h
|
#ifndef MMFUNCTIONs_H
#define MMFUNCTIONS_H
#include <iostream>
#include <stdio.h>
#include <Windows.h>
#include <string>
using namespace std;
string CreateDirectoryNameFromFile(char * filename);
string SetWorkingDirectory(char *path);
string GetFilename(char *path);
void DisplayProgress(int current, int max);
void ParseFilename(string filename);
void ParseFilename(string filename, string &artist, string &album, string &song);
int ProcessFile(string filename, string previousfilename);
string CreateCleanDirectoryName(string filename);
void CleanString(string &thestring);
#endif // MMFUNCTION_H
|
[
"[email protected]"
] |
[
[
[
1,
21
]
]
] |
b82fe6391e9145b4cf9078a88cd77226e4b0fbb6
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_004.cpp
|
672f9e7d9f6f6a5ebb2292f3971265646cf54911
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,040 |
cpp
|
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
//O --variadics
// Tests macro expansion order in conjunction with the need to skip expansion
// of the same macro as it is currently expanded.
#define CONCAT(a, b) a ## b
#define CONCAT_INDIRECT() CONCAT
//R #line 20 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT)(1, 2)
//R #line 23 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT(1, 2))
//R #line 26 "t_1_004.cpp"
//R 12
CONCAT(CONCAT_, INDIRECT)()(1, 2)
//R #line 29 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CONCAT_, INDIRECT())(1, 2)
//R #line 32 "t_1_004.cpp"
//R 1 CONCAT(2, 3)
CONCAT(1, CONCAT(2, 3))
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
32
]
]
] |
1d4007309eb6cbe095653b54faac657edbb1eea0
|
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
|
/src/orders/PauseOrder.h
|
aafe6349b4ed997d04a6a7a5b8ddd93cf995bfe4
|
[] |
no_license
|
commel/opencombat2005
|
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
|
d72fc2b0be12367af34d13c47064f31d55b7a8e0
|
refs/heads/master
| 2023-05-19T05:18:54.728752 | 2005-12-01T05:11:44 | 2005-12-01T05:11:44 | 375,630,282 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 536 |
h
|
#pragma once
#include "order.h"
class PauseOrder :
public Order
{
public:
PauseOrder(long pauseTime, int oldState, int pauseState);
virtual ~PauseOrder(void);
inline long GetPauseTime() { return _pauseTime; }
inline long GetTotalTime() { return _totalTime; }
inline void IncrementTotalTime(long dt) { _totalTime += dt; }
inline int GetOldState() { return _oldState; }
inline int GetPauseState() { return _pauseState; }
protected:
long _pauseTime;
long _totalTime;
int _oldState;
int _pauseState;
};
|
[
"opencombat"
] |
[
[
[
1,
22
]
]
] |
4c3795efb484904bd847e785c4e398bcbceea0c2
|
0b66a94448cb545504692eafa3a32f435cdf92fa
|
/tags/0.5/cbear.berlios.de/windows/com/traits.hpp
|
8933b6a03d8ea2d57095086011abca95ffae1750
|
[
"MIT"
] |
permissive
|
BackupTheBerlios/cbear-svn
|
e6629dfa5175776fbc41510e2f46ff4ff4280f08
|
0109296039b505d71dc215a0b256f73b1a60b3af
|
refs/heads/master
| 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,614 |
hpp
|
/*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_WINDOWS_COM_TRAITS_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_COM_TRAITS_HPP_INCLUDED
#include <cbear.berlios.de/base/undefined.hpp>
#include <cbear.berlios.de/base/swap.hpp>
#include <cbear.berlios.de/windows/message_box.hpp>
#include <cbear.berlios.de/policy/main.hpp>
// BOOST_STATIC_ASSERT
#include <boost/static_assert.hpp>
// boost::mpl::if_
#include <boost/mpl/if.hpp>
// boost::is_class
#include <boost/type_traits/is_class.hpp>
// boost::is_enum
#include <boost/type_traits/is_enum.hpp>
namespace cbear_berlios_de
{
namespace windows
{
namespace com
{
using namespace windows;
template<class Type>
struct traits;
enum io_type
{
in = 1,
out = 2,
in_out = in|out,
};
typedef ::VARTYPE vartype_t;
template<class Type>
struct class_traits
{
typedef Type type;
typedef typename type::internal_policy internal_policy;
typedef typename internal_policy::type internal_type;
typedef typename type::move_type move_type;
static const vartype_t vt = type::vt;
static typename type::extra_result extra() { return type::extra(); }
template<io_type Io>
struct io_traits;
template<>
struct io_traits<in>
{
typedef internal_type internal_result;
typedef const type &wrap_result;
static internal_result internal(wrap_result X)
{
return X.internal();
}
static wrap_result wrap(internal_result &X)
{
return type::wrap_ref(X);
}
};
template<>
struct io_traits<in_out>
{
typedef internal_type *internal_result;
typedef type &wrap_result;
static internal_result internal(wrap_result X)
{
return &X.internal();
}
static wrap_result wrap(internal_result &X)
{
return type::wrap_ref(*X);
}
};
template<>
struct io_traits<out>
{
typedef internal_type *internal_result;
typedef type &wrap_result;
static internal_result internal(wrap_result X)
{
type Temp;
Temp.swap(X);
return &X.internal();
}
static wrap_result wrap(internal_result &X)
{
internal_policy::construct(*X);
return type::wrap_ref(*X);
}
};
};
template<class Type, vartype_t Vt>
struct default_traits
{
typedef Type type;
typedef policy::standard_policy<type> internal_policy;
typedef type internal_type;
typedef type move_type;
static const vartype_t vt = Vt;
static void *extra() { return 0; }
template<io_type Io>
struct io_traits;
template<>
struct io_traits<in>
{
typedef internal_type internal_result;
typedef type wrap_result;
static internal_result internal(wrap_result X) { return X; }
static wrap_result wrap(internal_result &X) { return X; }
};
template<>
struct io_traits<in_out>
{
typedef internal_type *internal_result;
typedef type &wrap_result;
static internal_result internal(wrap_result X) { return &X; }
static wrap_result wrap(internal_result &X) { return *X; }
};
template<>
struct io_traits<out>
{
typedef internal_type *internal_result;
typedef type &wrap_result;
static internal_result internal(wrap_result X)
{
X = type();
return &X;
}
static wrap_result wrap(internal_result &X)
{
internal_policy::construct(*X);
return *X;
}
};
};
struct undefined_traits
{
template<io_type> struct io_traits
{
typedef base::undefined internal_result;
};
};
template<class Type>
struct enum_traits: default_traits<Type, ::VT_INT> {};
template<class Type>
struct traits:
boost::mpl::if_<
boost::is_class<Type>,
class_traits<Type>,
typename boost::mpl::if_<
boost::is_enum<Type>, enum_traits<Type>, undefined_traits>::type>::type
{
};
template<io_type Io, class Type>
struct io_traits: traits<Type>::template io_traits<Io> {};
template<io_type Io, class Type>
struct internal_result
{
typedef typename io_traits<Io, Type>::internal_result type;
};
template<io_type Io, class Type>
typename internal_result<Io, Type>::type internal(const Type &X)
{
return io_traits<Io, Type>::internal(X);
}
template<io_type Io, class Type>
typename internal_result<Io, Type>::type internal(Type &X)
{
return io_traits<Io, Type>::internal(X);
}
template<io_type Io, class Type>
struct internal_result<Io, base::move_t<Type> >: internal_result<Io, Type>
{
};
template<io_type Io, class Type>
typename internal_result<Io, Type>::type internal(const base::move_t<Type> &X)
{
return io_traits<Io, Type>::internal(X.get());
}
template<io_type Io, class Type>
typename internal_result<Io, Type>::type internal(base::move_t<Type> &X)
{
return io_traits<Io, Type>::internal(X.get());
}
template<class Type>
struct internal_in_result: internal_result<in, Type> {};
template<class Type>
typename internal_in_result<Type>::type internal_in(const Type &X)
{
return internal<in>(X);
}
template<class Type>
struct internal_in_out_result: internal_result<in_out, Type> {};
template<class Type>
typename internal_in_out_result<Type>::type internal_in_out(Type &X)
{
return internal<in_out>(X);
}
template<class Type>
struct internal_out_result: internal_result<out, Type> {};
template<class Type>
typename internal_out_result<Type>::type internal_out(Type &X)
{
return internal<out>(X);
}
template<io_type Io, class Type>
struct wrap_result
{
typedef typename io_traits<Io, Type>::wrap_result type;
};
template<io_type Io, class Type>
typename wrap_result<Io, Type>::type wrap(
typename internal_result<Io, Type>::type &X)
{
return io_traits<Io, Type>::wrap(X);
}
template<class Type>
struct wrap_in_result: wrap_result<in, Type> {};
template<class Type>
typename wrap_in_result<Type>::type wrap_in(
typename internal_in_result<Type>::type &X)
{
return wrap<in, Type>(X);
}
template<class Type>
struct wrap_in_out_result: wrap_result<in_out, Type> {};
template<class Type>
typename wrap_in_out_result<Type>::type wrap_in_out(
typename internal_in_out_result<Type>::type &X)
{
return wrap<in_out, Type>(X);
}
template<class Type>
struct wrap_out_result: wrap_result<out, Type> {};
template<class Type>
typename wrap_out_result<Type>::type wrap_out(
typename internal_out_result<Type>::type &X)
{
return wrap<out, Type>(X);
}
#define CBEAR_BERLIOS_DE_WINDOWS_COM_DECLARE_DEFAULT_TRAITS(T, VT) \
template<> struct traits<T>: default_traits<T, VT> {}
}
}
}
#endif
|
[
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] |
[
[
[
1,
321
]
]
] |
32606a5a2b2c840de3fe70713fa0ce37f99a7168
|
804e416433c8025d08829a08b5e79fe9443b9889
|
/src/graphics/tilemap_xp.cpp
|
d5bfc7a7f0ef23d82702887f71702f5ca0234638
|
[
"BSD-2-Clause"
] |
permissive
|
cstrahan/argss
|
e77de08db335d809a482463c761fb8d614e11ba4
|
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
|
refs/heads/master
| 2020-05-20T05:30:48.876372 | 2010-10-03T23:21:59 | 2010-10-03T23:21:59 | 1,682,890 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 14,184 |
cpp
|
/////////////////////////////////////////////////////////////////////////////
// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Headers
///////////////////////////////////////////////////////////
#include <string>
#include <map>
#include <math.h>
#include "tilemap_xp.h"
#include "aruby.h"
#include "argss/classes/atilemap.h"
#include "graphics/graphics.h"
#include "graphics/viewport.h"
#include "player.h"
///////////////////////////////////////////////////////////
/// Static Variables
///////////////////////////////////////////////////////////
int Tilemap::autotiles_id[6][8][4];
///////////////////////////////////////////////////////////
/// Class Init
///////////////////////////////////////////////////////////
void Tilemap::Init() {
int temp[192] = {
26, 27, 32, 33, 04, 27, 32, 33, 26, 05, 32, 33, 04, 05, 32, 33,
26, 27, 32, 11, 04, 27, 32, 11, 26, 05, 32, 11, 04, 05, 32, 11,
26, 27, 10, 33, 04, 27, 10, 33, 26, 05, 10, 33, 04, 05, 10, 33,
26, 27, 10, 11, 04, 27, 10, 11, 26, 05, 10, 11, 04, 05, 10, 11,
24, 25, 30, 31, 24, 05, 30, 31, 24, 25, 30, 11, 24, 05, 30, 11,
14, 15, 20, 21, 14, 15, 20, 11, 14, 15, 10, 21, 14, 15, 10, 11,
28, 29, 34, 35, 28, 29, 10, 35, 04, 29, 34, 35, 04, 29, 10, 35,
38, 39, 44, 45, 04, 39, 44, 45, 38, 05, 44, 45, 04, 05, 44, 45,
24, 29, 30, 35, 14, 15, 44, 45, 12, 13, 18, 19, 12, 13, 18, 11,
16, 17, 22, 23, 16, 17, 10, 23, 40, 41, 46, 47, 04, 41, 46, 47,
36, 37, 42, 43, 36, 05, 42, 43, 12, 17, 18, 23, 12, 13, 42, 43,
36, 41, 42, 47, 16, 17, 46, 47, 12, 17, 42, 47, 00, 01, 06, 07
};
memcpy(autotiles_id, temp, 192 * sizeof(int));
}
///////////////////////////////////////////////////////////
/// Constructor
///////////////////////////////////////////////////////////
Tilemap::Tilemap(VALUE iid) {
id = iid;
viewport = rb_iv_get(id, "@viewport");
tileset = Qnil;
autotiles = rb_iv_get(id, "@autotiles");
map_data = Qnil;
flash_data = Qnil;
priorities = Qnil;
visible = true;
ox = 0;
oy = 0;
autotile_time = 0;
autotile_frame = 0;
}
///////////////////////////////////////////////////////////
/// Destructor
///////////////////////////////////////////////////////////
Tilemap::~Tilemap() {
std::map<unsigned long, std::map<int, std::map<int, Bitmap*> > >::iterator it1_autotiles_cache;
std::map<int, std::map<int, Bitmap*> >::iterator it2_autotiles_cache;
std::map<int, Bitmap*>::iterator it3_autotiles_cache;
for (it1_autotiles_cache = autotiles_cache.begin(); it1_autotiles_cache != autotiles_cache.end(); it1_autotiles_cache++) {
for (it2_autotiles_cache = it1_autotiles_cache->second.begin(); it2_autotiles_cache != it1_autotiles_cache->second.end(); it2_autotiles_cache++) {
for (it3_autotiles_cache = it2_autotiles_cache->second.begin(); it3_autotiles_cache != it2_autotiles_cache->second.end(); it3_autotiles_cache++) {
delete it3_autotiles_cache->second;
}
}
}
}
///////////////////////////////////////////////////////////
/// Class Is Tilemap Disposed?
///////////////////////////////////////////////////////////
bool Tilemap::IsDisposed(VALUE id) {
return Graphics::drawable_map.count(id) == 0;
}
///////////////////////////////////////////////////////////
/// Class New Tilemap
///////////////////////////////////////////////////////////
void Tilemap::New(VALUE id) {
Graphics::drawable_map[id] = new Tilemap(id);
}
///////////////////////////////////////////////////////////
/// Class Get Tilemap
///////////////////////////////////////////////////////////
Tilemap* Tilemap::Get(VALUE id) {
return (Tilemap*)Graphics::drawable_map[id];
}
///////////////////////////////////////////////////////////
/// Class Dispose Tilemap
///////////////////////////////////////////////////////////
void Tilemap::Dispose(unsigned long id) {
if (Tilemap::Get(id)->viewport != Qnil) {
Viewport::Get(Tilemap::Get(id)->viewport)->RemoveZObj(id);
} else {
Graphics::RemoveZObj(id);
}
delete Graphics::drawable_map[id];
std::map<unsigned long, Drawable*>::iterator it = Graphics::drawable_map.find(id);
Graphics::drawable_map.erase(it);
}
///////////////////////////////////////////////////////////
/// Update
///////////////////////////////////////////////////////////
void Tilemap::Update() {
autotile_time += 1;
if (autotile_time == 8) {
autotile_time = 0;
autotile_frame += 1;
}
}
///////////////////////////////////////////////////////////
/// Refresh Bitmaps
///////////////////////////////////////////////////////////
void Tilemap::RefreshBitmaps() {
std::map<unsigned long, std::map<int, std::map<int, Bitmap*> > >::iterator it1_autotiles_cache;
std::map<int, std::map<int, Bitmap*> >::iterator it2_autotiles_cache;
std::map<int, Bitmap*>::iterator it3_autotiles_cache;
for (it1_autotiles_cache = autotiles_cache.begin(); it1_autotiles_cache != autotiles_cache.end(); it1_autotiles_cache++) {
for (it2_autotiles_cache = it1_autotiles_cache->second.begin(); it2_autotiles_cache != it1_autotiles_cache->second.end(); it2_autotiles_cache++) {
for (it3_autotiles_cache = it2_autotiles_cache->second.begin(); it3_autotiles_cache != it2_autotiles_cache->second.end(); it3_autotiles_cache++) {
it3_autotiles_cache->second->Changed();
}
}
}
}
///////////////////////////////////////////////////////////
/// Draw
///////////////////////////////////////////////////////////
void Tilemap::Draw(long z_level) {
if (!visible) return;
if (tileset == Qnil || map_data == Qnil || priorities == Qnil) return;
if (z_level == 0) {
RefreshData();
Bitmap::Get(tileset)->Refresh();
}
int width = NUM2INT(rb_iv_get(map_data, "@xsize"));
int height = NUM2INT(rb_iv_get(map_data, "@ysize"));
int layers = NUM2INT(rb_iv_get(map_data, "@zsize"));
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (viewport != Qnil) {
Rect rect = Viewport::Get(viewport)->GetViewportRect();
glEnable(GL_SCISSOR_TEST);
glScissor(rect.x, Player::GetHeight() - (rect.y + rect.height), rect.width, rect.height);
glTranslatef((float)rect.x, (float)rect.y, 0.0f);
}
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
int tiles_x = (int)ceil(Player::GetWidth() / 32.0);
int tiles_y = (int)ceil(Player::GetHeight() / 32.0);
for (int z = 0; z < layers; z++) {
for (int y = 0; y <= tiles_y; y++) {
for (int x = 0; x <= tiles_x; x++) {
int map_x = ox / 32 + x;
int map_y = oy / 32 + y;
if (map_x >= width || map_y >= height) continue;
TileData tile = data_cache[map_x][map_y][z];
int tile_z;
if (tile.priority == 0) {
tile_z = 0;
} else {
tile_z = tile.priority * 32 + y * 32 + z * 32;
if (map_y == 0 && tile.priority == 1) tile_z += 32;
}
if (tile_z == z_level) {
float dst_x = (float)(x * 32 - ox % 32);
float dst_y = (float)(y * 32 - oy % 32);
if (tile.id < 384 && tile.id != 0) {
VALUE bitmap_id = rb_ary_entry(rb_iv_get(autotiles, "@autotiles"), tile.id / 48 - 1);
if (Bitmap::IsDisposed(bitmap_id)) continue;
Bitmap* autotile_bitmap = Bitmap::Get(bitmap_id);
int tile_id = tile.id % 48;
int frame = autotile_frame % (autotile_bitmap->GetWidth() / 96);
if (autotiles_cache.count(bitmap_id) == 0 ||
autotiles_cache[bitmap_id].count(tile_id) == 0 ||
autotiles_cache[bitmap_id][tile_id].count(frame) == 0) {
autotiles_cache[bitmap_id][tile_id][frame] = new Bitmap(32, 32);
int* tiles = autotiles_id[tile_id >> 3][tile_id & 7];
for (int i = 0; i < 4; i++) {
Rect rect(((tiles[i] % 6) << 4) + frame * 96, (tiles[i] / 6) << 4, 16, 16);
autotiles_cache[bitmap_id][tile_id][frame]->Blit((i % 2) << 4, (i / 2) << 4, autotile_bitmap, rect, 255);
}
glPushMatrix();
autotiles_cache[bitmap_id][tile_id][frame]->Refresh();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
autotiles_cache[bitmap_id][tile_id][frame]->BindBitmap();
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(dst_x, dst_y);
glTexCoord2f(1.0f, 0.0f); glVertex2f(dst_x + 32.0f, dst_y);
glTexCoord2f(1.0f, 1.0f); glVertex2f(dst_x + 32.0f, dst_y + 32.0f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(dst_x, dst_y + 32.0f);
glEnd();
} else if (tile.id != 0){
float src_x = (float)((tile.id - 384) % 8 * 32);
float src_y = (float)((tile.id - 384) / 8 * 32);
Bitmap::Get(tileset)->BindBitmap();
float bmpw = (float)Bitmap::Get(tileset)->GetWidth();
float bmph = (float)Bitmap::Get(tileset)->GetHeight();
glBegin(GL_QUADS);
glTexCoord2f(src_x / bmpw, src_y / bmph); glVertex2f(dst_x, dst_y);
glTexCoord2f((src_x + 32.0f) / bmpw, src_y / bmph); glVertex2f(dst_x + 32.0f, dst_y);
glTexCoord2f((src_x + 32.0f) / bmpw, (src_y + 32.0f) / bmph); glVertex2f(dst_x + 32.0f, dst_y + 32.0f);
glTexCoord2f(src_x / bmpw, (src_y + 32.0f) / bmph); glVertex2f(dst_x, dst_y + 32.0f);
glEnd();
}
}
}
}
}
glDisable(GL_SCISSOR_TEST);
}
void Tilemap::Draw(long z, Bitmap* dst_bitmap) {
}
///////////////////////////////////////////////////////////
/// Refresh Data
///////////////////////////////////////////////////////////
void Tilemap::RefreshData() {
bool update = false;
if (rb_iv_get(map_data, "@modified") == Qtrue) {
rb_iv_set(map_data, "@modified", Qfalse);
update = true;
}
if (rb_iv_get(priorities, "@modified") == Qtrue) {
rb_iv_set(priorities, "@modified", Qfalse);
update = true;
}
if (!update) return;
int width = NUM2INT(rb_iv_get(map_data, "@xsize"));
int height = NUM2INT(rb_iv_get(map_data, "@ysize"));
int layers = NUM2INT(rb_iv_get(map_data, "@zsize"));
VALUE map_data_array = rb_iv_get(map_data, "@data");
VALUE priorities_array = rb_iv_get(priorities, "@data");
data_cache.resize(width);
for (int x = 0; x < width; x++) {
data_cache[x].resize(height);
for (int y = 0; y < height; y++) {
data_cache[x][y].resize(layers);
for (int z = 0; z < layers; z++) {
TileData tile;
tile.id = NUM2INT(rb_ary_entry(map_data_array, x + y * width + z * width * height));
tile.priority = NUM2INT(rb_ary_entry(priorities_array, tile.id));
data_cache[x][y][z] = tile;
}
}
}
}
///////////////////////////////////////////////////////////
/// Properties
///////////////////////////////////////////////////////////
VALUE Tilemap::GetViewport() {
return viewport;
}
void Tilemap::SetViewport(VALUE nviewport) {
if (viewport != nviewport) {
if (viewport != Qnil) {
Viewport::Get(viewport)->RemoveZObj(id);
} else {
Graphics::RemoveZObj(id);
}
int height = NUM2INT(rb_iv_get(map_data, "@ysize"));
if (nviewport != Qnil) {
for (int i = 0; i < height + 5; i++) {
Viewport::Get(nviewport)->RegisterZObj(i * 32, id, true);
}
} else {
for (int i = 0; i < height + 5; i++) {
Graphics::RegisterZObj(i * 32, id, true);
}
}
}
viewport = nviewport;
}
VALUE Tilemap::GetTileset() {
return tileset;
}
void Tilemap::SetTileset(VALUE ntileset) {
tileset = ntileset;
}
VALUE Tilemap::GetMapData() {
return map_data;
}
void Tilemap::SetMapData(VALUE nmap_data) {
if (map_data != nmap_data) {
if (viewport != Qnil) {
Viewport::Get(viewport)->RemoveZObj(id);
} else {
Graphics::RemoveZObj(id);
}
if (nmap_data != Qnil) {
rb_iv_set(nmap_data, "@modified", Qtrue);
int height = NUM2INT(rb_iv_get(nmap_data, "@ysize"));
if (viewport != Qnil) {
for (int i = 0; i < height + 8; i++) {
Viewport::Get(viewport)->RegisterZObj(i * 32, id, true);
}
} else {
for (int i = 0; i < height + 8; i++) {
Graphics::RegisterZObj(i * 32, id, true);
}
}
}
}
map_data = nmap_data;
}
VALUE Tilemap::GetFlashData() {
return flash_data;
}
void Tilemap::SetFlashData(VALUE nflash_data) {
flash_data = nflash_data;
}
VALUE Tilemap::GetPriorities() {
return priorities;
}
void Tilemap::SetPriorities(VALUE npriorities) {
if (priorities != npriorities) rb_iv_set(npriorities, "@modified", Qtrue);
priorities = npriorities;
}
bool Tilemap::GetVisible() {
return visible;
}
void Tilemap::SetVisible(bool nvisible) {
visible = nvisible;
}
int Tilemap::GetOx() {
return ox;
}
void Tilemap::SetOx(int nox) {
ox = nox;
}
int Tilemap::GetOy() {
return oy;
}
void Tilemap::SetOy(int noy) {
oy = noy;
}
|
[
"vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda",
"npepinpe@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda"
] |
[
[
[
1,
31
],
[
33,
405
]
],
[
[
32,
32
]
]
] |
ca7fbe9f131004ac5a345edc681facd3c9429bbb
|
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
|
/Code/controllers/OdometryCalibration/robotapi/real/RealRobot.h
|
6839a750f09a426e06e6d009b44db45fb81b00f8
|
[] |
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 | 2,219 |
h
|
#ifndef robotapi_real_RealRobot_h
#define robotapi_real_RealRobot_h
#include <robotapi/IRobot.h>
#include <protocol/handlers/BatteryBoardPacketHandler.h>
#include <protocol/handlers/DCMotorBoardPacketHandler.h>
#include <protocol/handlers/DistanceSensorBoardPacketHandler.h>
#include <protocol/handlers/ServoBoardPacketHandler.h>
#include <protocol/handlers/TrashBinBoardPacketHandler.h>
#include <protocol/PacketServer.h>
#include <WorldInfo.h>
#include <string>
#include <map>
namespace robotapi {
namespace real {
class RealRobot : virtual public robotapi::IRobot {
public:
RealRobot(WorldInfo * wi);
std::string getName();
double getTime();
int getMode();
bool getSynchronization();
double getBasicTimeStep();
ICamera & getCamera(std::string name);
IDistanceSensor & getDistanceSensor(std::string name);
IServo & getServo(std::string name);
IDevice & getDevice(std::string name);
IDifferentialWheels & getDifferentialWheels(std::string name);
IBattery & getBattery(std::string name);
ITrashBin & getTrashBin(std::string name);
void step(int ms);
private:
void initServos(protocol::PacketServer * ps);
void initServo(protocol::PacketServer * ps, protocol::handlers::ServoBoardPacketHandler * sbph, std::string name, int id);
void initWheels(protocol::PacketServer * ps);
void initBatteries(protocol::PacketServer * ps);
void initDistanceSensors(protocol::PacketServer * ps);
void initDistanceSensor(protocol::PacketServer * ps, protocol::handlers::DistanceSensorBoardPacketHandler * dsbph, std::string name, int id);
void initCameras();
void initTrashBins(protocol::PacketServer * ps);
std::map<std::string, IServo *> servos;
std::map<std::string, IDifferentialWheels *> wheels;
std::map<std::string, IBattery *> batteries;
std::map<std::string, IDistanceSensor *> distanceSensors;
std::map<std::string, ICamera *> cameras;
std::map<std::string, ITrashBin *> trashBins;
WorldInfo * wi;
};
} /* End of namespace robotapi::real */
} /* End of namespace robotapi */
#endif // robotapi_real_RealRobot_h
|
[
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
] |
[
[
[
1,
74
]
]
] |
bf36159beadce2f3fde09ee8df723778c8448524
|
4d838ba98a21fc4593652e66eb7df0fac6282ef6
|
/CaveProj/ChestCounter.h
|
0a8e872c88c4573f912d4bc9f15e1686a42f671a
|
[] |
no_license
|
davidhart/ProceduralCaveEditor
|
39ed0cf4ab4acb420fa2ad4af10f9546c138a83a
|
31264591f2dcd250299049c826aeca18fc52880e
|
refs/heads/master
| 2021-01-17T15:10:09.100572 | 2011-05-03T19:24:06 | 2011-05-03T19:24:06 | 69,302,913 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 593 |
h
|
#pragma once
#ifndef _CHESTCOUNTER_H_
#define _CHESTCOUNTER_H_
#include <d3d10.h>
#include <D3DX10.h>
class RenderWindow;
class ChestCounter
{
public:
ChestCounter();
void Load(RenderWindow& renderWindow);
void Unload();
void Draw(RenderWindow& renderWindow);
inline void Reset() { _collected = 0; }
inline void SetTotal(int total) { _total = total; }
inline void OnCollected() { ++_collected; }
private:
unsigned int _total;
unsigned int _collected;
ID3DX10Sprite* _sprite;
ID3DX10Font* _font;
ID3D10ShaderResourceView* _iconTexture;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
31
]
]
] |
83913206cd27aba0a62dbf32e79753453555bf4c
|
cfa667b1f83649600e78ea53363ee71dfb684d81
|
/code/editor/ui/mainframe.cc
|
56d7b9c1673488fd6bc08d039982ab2eb5dd2d7d
|
[] |
no_license
|
zhouxh1023/nebuladevice3
|
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
|
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
|
refs/heads/master
| 2021-01-23T08:56:15.823698 | 2011-08-26T02:22:25 | 2011-08-26T02:22:25 | 32,018,644 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,633 |
cc
|
//------------------------------------------------------------------------------
// mainframe.cc
// (C) 2011 xiongyouyi
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "mainframe.h"
#include "wx/wx.h"
#include "wx/aui/aui.h"
#include "createpanel.h"
#include "terrainpanel.h"
#include "displaypanel.h"
#include "CanvasPanel.h"
#include "../app/editorapplication.h"
namespace Editor
{
////@begin control identifiers
#define ID_FILE_NEW 10004
#define ID_FILE_OPEN 10006
#define ID_FILE_SAVE 10007
#define ID_FILE_SAVEAS 10008
#define ID_FILE_EXIT 10009
#define ID_EDIT_UNDO 10005
#define ID_EDIT_REDO 10010
#define ID_EDIT_DELETE 10011
////@end control identifiers
/*!
* MainFrame type definition
*/
IMPLEMENT_CLASS( MainFrame, wxFrame )
/*!
* MainFrame event table definition
*/
BEGIN_EVENT_TABLE( MainFrame, wxFrame )
END_EVENT_TABLE()
/*!
* MainFrame constructors
*/
MainFrame::MainFrame( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
wxFrame::Create( parent, id, caption, pos, size, style );
CreateControls();
SetIcon(wxIcon(_T("NebulaIcon")));
Centre();
}
/*!
* MainFrame destructor
*/
MainFrame::~MainFrame()
{
GetAuiManager().UnInit();
}
/*!
* Member initialisation
*/
void MainFrame::Init()
{
}
/*!
* Control creation for MainFrame
*/
void MainFrame::CreateControls()
{
GetAuiManager().SetManagedWindow(this);
// Create menubar
wxMenuBar* menuBar = new wxMenuBar;
// file menu
wxMenu* fileMenu = new wxMenu;
fileMenu->Append(ID_FILE_NEW, _("New"), _T(""), wxITEM_NORMAL);
fileMenu->Append(ID_FILE_OPEN, _("Open"), _T(""), wxITEM_NORMAL);
fileMenu->Append(ID_FILE_SAVE, _("Save"), _T(""), wxITEM_NORMAL);
fileMenu->Append(ID_FILE_SAVEAS, _("SaveAs"), _T(""), wxITEM_NORMAL);
fileMenu->AppendSeparator();
fileMenu->Append(ID_FILE_EXIT, _("Exit"), _T(""), wxITEM_NORMAL);
menuBar->Append(fileMenu, _("File"));
// edit menu
wxMenu* editMenu = new wxMenu;
editMenu->Append(ID_EDIT_UNDO, _("Undo"), _T(""), wxITEM_NORMAL);
editMenu->Append(ID_EDIT_REDO, _("Redo"), _T(""), wxITEM_NORMAL);
editMenu->AppendSeparator();
editMenu->Append(ID_EDIT_DELETE, _("Delete"), _T(""), wxITEM_NORMAL);
menuBar->Append(editMenu, _("Edit"));
this->SetMenuBar(menuBar);
// Create main toolbar
wxToolBar* mainToolbar = CreateToolBar( wxTB_FLAT|wxTB_HORIZONTAL|wxTB_NODIVIDER, wxID_ANY );
mainToolbar->AddTool(ID_FILE_NEW, _T("New"),
wxBitmap( wxT("./res/page_world.png"), wxBITMAP_TYPE_PNG),
wxEmptyString);
mainToolbar->AddTool(ID_FILE_OPEN, _T("Open"),
wxBitmap( wxT("./res/folder_page.png"), wxBITMAP_TYPE_PNG),
wxEmptyString);
mainToolbar->AddTool(ID_FILE_SAVE, _T("Save"),
wxBitmap( wxT("./res/arrow_join.png"), wxBITMAP_TYPE_PNG),
wxEmptyString);
mainToolbar->AddTool(ID_EDIT_UNDO, _T("Undo"),
wxBitmap( wxT("./res/arrow_turn_left.png"), wxBITMAP_TYPE_PNG),
wxEmptyString);
mainToolbar->AddTool(ID_EDIT_REDO, _T("Redo"),
wxBitmap( wxT("./res/arrow_turn_right.png"), wxBITMAP_TYPE_PNG),
wxEmptyString);
mainToolbar->Realize();
this->SetToolBar(mainToolbar);
// Create statusbar
int fieldsWidth[3]={140, 200, -1};
wxStatusBar* statusBar = new wxStatusBar( this, wxID_ANY, wxST_SIZEGRIP|wxNO_BORDER );
statusBar->SetFieldsCount(3, fieldsWidth);
this->SetStatusBar(statusBar);
// Create main canvas panel
this->canvasPanel = new CanvasPanel( this );
GetAuiManager().AddPane(this->canvasPanel, wxAuiPaneInfo().Centre().CaptionVisible(false).
CloseButton(false).DestroyOnClose(false).Resizable(true).Floatable(false));
// Create command panel
wxFlatNotebook* notebook = new wxFlatNotebook( this, wxID_ANY, wxDefaultPosition, wxSize(240, -1),
wxFNB_NO_X_BUTTON | wxFNB_NO_NAV_BUTTONS | wxFNB_NODRAG | wxFNB_FF2 | wxFNB_CUSTOM_DLG );
notebook->SetCustomizeOptions( wxFNB_CUSTOM_TAB_LOOK | wxFNB_CUSTOM_ORIENTATION | wxFNB_CUSTOM_LOCAL_DRAG );
notebook->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
this->bookImageList.Add( wxBitmap(wxT("./res/chart_organisation.png"), wxBITMAP_TYPE_PNG) );
this->bookImageList.Add( wxBitmap(wxT("./res/shape_square_edit.png"), wxBITMAP_TYPE_PNG) );
this->bookImageList.Add( wxBitmap(wxT("./res/page_lightning.png"), wxBITMAP_TYPE_PNG) );
notebook->SetImageList(&this->bookImageList);
notebook->AddPage(new CreatePanel(notebook, wxID_ANY), "Create", true, 0);
notebook->AddPage(new TerrainPanel(notebook, wxID_ANY), "Terrain", false, 1);
notebook->AddPage(new DisplayPanel(notebook, wxID_ANY), "Display", false, 2);
notebook->Layout();
GetAuiManager().AddPane(notebook, wxAuiPaneInfo().Right());
// Set auimanager options
GetAuiManager().SetFlags(wxAUI_MGR_DEFAULT | wxAUI_MGR_TRANSPARENT_DRAG);
GetAuiManager().Update();
}
//------------------------------------------------------------------------------
/**
*/
void MainFrame::InitNebula()
{
Util::String cmdline;
cmdline.Format("-externalwindow %d", ((HWND)this->canvasPanel->GetHWND()));
Util::CommandLineArgs args(cmdline);
GetEditor()->SetCmdLineArgs(args);
GetEditor()->Open();
GetEditor()->BeginUpdate();
}
//------------------------------------------------------------------------------
/**
*/
CanvasPanel* MainFrame::GetCanvas()
{
return this->canvasPanel;
}
}
|
[
"[email protected]"
] |
[
[
[
1,
188
]
]
] |
3a38c083b41b14aa8b17ec39cb2aeb7a220a2cb1
|
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
|
/SMDK/TransCritical/TTechQAL/QALDynPrecip.cpp
|
266361b1581d05852531a95a862c67badb6d61a4
|
[] |
no_license
|
abcweizhuo/Test3
|
0f3379e528a543c0d43aad09489b2444a2e0f86d
|
128a4edcf9a93d36a45e5585b70dee75e4502db4
|
refs/heads/master
| 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 33,454 |
cpp
|
//================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// QAL Classifier Model 2004 - Transcritical Technologies/ QAL
// Time-stamp: <2007-05-23 03:58:13 Rod Stephenson Transcritical Pty Ltd>
// Copyright (C) 2005 by Transcritical Technologies Pty Ltd and KWA
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __QALPRECIP_CPP
#include "qaldynprecip.h"
static MInitialiseTest InitTest("DynPrecip");
static MSpeciePtr spAlumina (InitTest, "NaAl[OH]4(l)", false);
static MSpeciePtr spWater (InitTest, "H2O(l)", false);
static MSpeciePtr spWaterVapor (InitTest, "H2O(g)", false);
static MSpeciePtr spTHA (InitTest, "Al[OH]3(s)", false);
static MSpeciePtr spCausticSoda (InitTest, "NaOH(l)", false);
static MSpeciePtr spOccSoda (InitTest, "Na2O(s)", false);
static MSpeciePtr spCarbonate (InitTest, "Na2CO3(l)", false);
static MSpeciePtr spBoundSoda (InitTest, "NaOH*(s)", false);
static MSpeciePtr spOrganics (InitTest, "Na2C5.2O7.2(l)", false);
static MSpeciePtr spBoundOrganics (InitTest, "Na2C5.2O7.2*(s)", false);
static MSpeciePtr spOxalate (InitTest, "Na2C2O4(s)", false);
enum PrecipMethod {GRM_Fixed, GRM_White, GRM_CAR_QAL, GRM_TTTest};
enum CoolType{COOL_dQ, COOL_dT, COOL_Hx};
enum EvapType{EVAP_NONE, EVAP_FIXED, EVAP_dT};
enum ICool{COOL_NONE, COOL_INTERNAL, COOL_EXTERNAL};
enum PrecipComponents {iALUMINA, iOCC_SODA, iBOUND_ORGANICS, iWATER, nPRECIPCOMPS};
enum {GRM_AAEq, GRM_sigma};
enum {PB_None, PB_SSA, PB_PSD}; // Particle balance model
enum {idFeed, idUflow, idOflow};
enum ThermalHeatLossMethods {THL_None, THL_TempDrop, THL_FixedHeatFlow, THL_Ambient, THL_FixedTemp};
/// Utility Class for heat exchanger
static MInOutDefStruct s_IODefs[]=
{
{ "Feed", "Feed", idFeed, 1, 10, 0, 1.0f, MIO_In |MIO_Material },
{ "Underflow", "UFlow", idUflow, 1, 1, 0, 1.0f, MIO_Out|MIO_Material },
{ "Overflow", "OFlow", idOflow, 0, 1, 1, 1.0f, MIO_Out|MIO_Material },
{ NULL },
};
double Drw_CDynPrecipitator[] =
{
MDrw_Poly, -5,10, -5,-10, 5,-10, 5,10,
MDrw_End
};
//---------------------------------------------------------------------------
DEFINE_TRANSFER_UNIT(CDynPrecipitator, "DynPrecipitator", DLL_GroupName)
void CDynPrecipitator_UnitDef::GetOptions()
{
SetDefaultTag("PC");
SetDrawing("Tank", Drw_CDynPrecipitator);
SetTreeDescription("QAL:DynamicPrecipitator");
SetDescription("TODO: QAL PB Model");
SetModelSolveMode(MSolveMode_All);
SetModelGroup(MGroup_Alumina);
SetModelLicense(MLicense_HeatExchange|MLicense_Alumina);
};
//---------------------------------------------------------------------------
CDynPrecipitator::CDynPrecipitator(MUnitDefBase *pUnitDef, TaggedObject * pNd) :
MBaseMethod(pUnitDef, pNd)
{ //default values...
m_bEvapConnected = 0;
bKernelOK = false;
bOnLine = 1;
dTempDropRqd = 0.5;
dFixedTempRqd = C2K(70);
dThermalLossRqd = 1500.0;
iThermalLossMethod = THL_TempDrop;
iCoolMethod=0;
dTankVol = 3000;
dAggMinLim = .5;
iPSD=0;
dSolPrecip = 0.0;
dGrowthRate = 0.0;
dGrowthRateFactor = 0.0;
dYield = 0.0;
dTin = C2K(25.0);
dTout = C2K(25.0);
dDiamin = 0.0;
dSALin = 0.0;
dQvin = 0.0;
dQvout = 0.0;
dACin = 0.0;
dACout = 0.0;
dResidenceTime = 0.0;
dThermalLoss = 0.0;
dReactionHeat = 0.0;
m_dCoolOutTotHz = 0.0;
dtact = 0.5;
m_ddeltaT = 1.;
ER_White = 7200.0;
K_White = 1.96e9;
gF_White = 1.0;
m_dSurfaceAct = 1.0;
m_dSodaConst = 9e-3;
dGrowthRateFactor = 1.0;
dAgglRateFactor = 1.0;
dNuclRateFactor = 1.0;
m_dConvergenceLimit = 1.0e-6;
alreadySolved = false;
m_lItermax = 1000;
}
//---------------------------------------------------------------------------
CDynPrecipitator::~CDynPrecipitator()
{
// delete[] x;
// delete[] xo;
}
bool CDynPrecipitator::ValidateDataFields()
{//ensure parameters are within expected ranges
return true;
}
//---------------------------------------------------------------------------
void CDynPrecipitator::Init()
{
SetIODefinition(s_IODefs);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Modified for NaAl[OH]4 as primary species.
void CDynPrecipitator::AdjustMasses(MStream & Prod)
{
double &InAluminaMass = Feed.MassVector[spAlumina]; // NaAl[OH]4(l)
double &InWaterMass = Feed.MassVector[spWater]; // H2O
double &InTHAMass = Feed.MassVector[spTHA]; // NaAl[OH]3(s)
double &InCausticMass = Feed.MassVector[spCausticSoda]; // NaOH
double &InBoundSodaMass = Feed.MassVector[spBoundSoda];
double &InOrganicMass = Feed.MassVector[spOrganics];
double &InBoundOrganicMass = Feed.MassVector[spBoundOrganics];
double &AluminaMass = Prod.MassVector[spAlumina]; // NaAl[OH]4(l)
double &WaterMass = Prod.MassVector[spWater]; // H2O
double &THAMass = Prod.MassVector[spTHA]; // NaAl[OH]3(s)
double &CausticMass = Prod.MassVector[spCausticSoda]; // NaOH
double &BoundSodaMass = Prod.MassVector[spBoundSoda];
double &OrganicMass = Prod.MassVector[spOrganics];
double &BoundOrganicMass = Prod.MassVector[spBoundOrganics];
if (m_dMassDamping>0.0) {
// Mass damping terms... may only be needed at very high rates
for (int i=0; i<nPRECIPCOMPS; i++)
x[i] = xo[i]*m_dMassDamping+x[i]*(1-m_dMassDamping);
}
///
// adjust masses... x is mass of precipitated Gibbsite
AluminaMass = InAluminaMass - Alpha*x[iALUMINA];
THAMass = InTHAMass + x[iALUMINA];
CausticMass = InCausticMass + x[iALUMINA]*(Alpha-1) - x[iOCC_SODA];
OrganicMass = InOrganicMass - x[iBOUND_ORGANICS];
BoundOrganicMass = InBoundOrganicMass + x[iBOUND_ORGANICS];
BoundSodaMass = InBoundSodaMass + x[iOCC_SODA];
WaterMass = InWaterMass - x[3]; // Water is only lost through evaporation
// if (m_bUpdateT) Prod.MarkStateChanged(); // Manual fixup of heat loads eventually...
}
void CDynPrecipitator::AdjustT(MStream &Prod)
{
double dHeatIn = Feed.totHz();
dReactionHeat = x[iALUMINA]*GibbsiteHOR(K2C(Prod.T));
double newTotDH = m_dOldTotDH*m_dDamping+(m_dTotThermalLoss-dReactionHeat)*(1-m_dDamping);
if (iThermalLossMethod == THL_TempDrop)
Tank.T = Feed.T - dTempDropRqd;
else if (iThermalLossMethod == THL_FixedTemp)
Tank.T = dFixedTempRqd;
else
Tank.Set_totHz(dHeatIn - newTotDH);
m_dOldTotDH = newTotDH;
}
void CDynPrecipitator::AdjustSSA(MStream &Prod)
{
}
//---------------------------------------------------------------------------
// All the precipitation rate calcs are done in this routine
// Takes the product composition and calculates rates from this
// Rates (in kg/s) are put into global x
//---------------------------------------------------------------------------
void CDynPrecipitator::EvalPrecipRates(MStream & Prod, double T)
{
PBRates();
double deltaT = m_ddeltaT;
for (int i=0; i<nClasses; i++) {
if (Ndot[i] < 0) {
double dtm = -n[i]*(1.0 - 0.7)/Ndot[i];
if (dtm < deltaT) deltaT = dtm;
}
}
double sumar = 0.0, sumv = 0.0, sumn = 0.0;
for (int i=0; i<nClasses; i++) {
NewN[i] = n[i] + Ndot[i]*deltaT;
double dd = D[i];
double dd2 = dd*dd;
double dd3=dd2*dd;
sumar+= dd2*NewN[i];
sumv += dd3*NewN[i];
sumn += NewN[i];
}
double newVol = PI/6*sumv*DIST_CORR*1.0e-18;
xo[0] = x[0]; xo[1]=x[1]; xo[2]=x[2]; xo[3]=x[3];
m_dSolidsOut = newVol*Tank.Mass()*2420; //Tank.Density(MP_Sol);
x[iALUMINA] = (m_dSolidsOut-m_dSolidsIn); // Precipitation is as trihydrate
x[iBOUND_ORGANICS]=0.;
//x[iOCC_SODA]=x[iALUMINA]*dSoda/100.;
//x[iOCC_SODA] = 0;
//x[iALUMINA] -= x[iOCC_SODA];
x[iWATER]= 0.0;
}
//---------------------------------------------------------------------------
// All the thermal loss calcs are done in this routine
// Also calculate the water loss through evaporation
// m_dTotThermalLoss is the total thermal loss,
//---------------------------------------------------------------------------
void CDynPrecipitator::EvalLosses(MStream & Prod)
{
}
void CDynPrecipitator::AdjustPSD(MStream & Prod)
{
}
//------------------------------------------------------------------------
// Check for convergence of the iteration
//
//
//------------------------------------------------------------------------
void CDynPrecipitator::DoResults(MStream & Prod)
{
//m_dNuclN = m_PSDin.getN()-m_PSD.getN();
MIBayer & FeedB=Feed.IF<MIBayer>(false);
MIBayer & ProdB=Prod.IF<MIBayer>(false);
dACin = FeedB.AtoC();
dACout = ProdB.AtoC();
dQvin = Feed.Volume();
dQvout = Prod.Volume();
dQmin = Feed.Mass();
dQmout = Prod.Mass();
double dQvout25 = Prod.Volume(MP_All, C2K(25));
double Cout = ProdB.CausticConc(Prod.T);
m_dACeq = ProdB.AluminaConcSat(Prod.T)/Cout;
m_dSSat = ProdB.AtoC()/m_dACeq;
dYield = Cout*(dACin-dACout);
double SolIn = Feed.MassVector[spTHA];
double SolOut = Prod.MassVector[spTHA];
dTHAPrecip = SolOut - SolIn;
dAlPrecip = dTHAPrecip*102/156;
SolIn = Feed.Mass(MP_Sol);
SolOut = Prod.Mass(MP_Sol);
dSolPrecip = SolOut - SolIn;
dSolConc = Prod.Mass(MP_Sol)/dQvout25;
m_dLiquorTin = Prod.T;
dTin = Feed.T;
dTout = Prod.T;
m_dNucleation = m_dNuclN * PI/6*1.4618*Sqr(L1)*L1*1e-18*Prod.Density(MP_Sol);
dResidenceTime = dTankVol/GTZ(Prod.Volume(MP_SL));
dFeedNTot = Feed.Volume(MP_All, C2K(25))*fpsd.getNTot();
dProdNTot = Prod.Volume(MP_All, C2K(25))*m_dNumber;
}
void CDynPrecipitator::EvalProducts()
{
try {
x[0] = x[1] = x[2] = x[3] = 0.0;
FlwIOs.AddMixtureIn_Id(Feed, idFeed);
MStream & UFlow = FlwIOs[FlwIOs.First[idUflow]].Stream; //Reference to the output stream
MStream & OFlow = FlwIOs[FlwIOs.First[idOflow]].Stream; //Reference to the output stream
// if (!alreadySolved || UFlow.MassFlow() < 1.0e-3)
Tank = Feed;
//else
//Tank = UFlow;
UFlow = Tank;
OFlow = Tank;
OFlow.SetF(Tank, MP_All, 0.0);
UFlow.SetF(Tank, MP_All, 1.0);
bool streamOK=true;
if (!bOnLine) return;
// Check for existence of Bayer Property...
MIBayer & FeedB=Feed.IF<MIBayer>(false); // Do the checks up front
Log.SetCondition(IsNothing(FeedB), 1, MMsg_Warning, "Bad Feed Stream - Not BATC Bayer Model");
// Try PSD
MIPSD & FeedPSD = Feed.IF<MIPSD>(false);
if (!IsNothing(FeedPSD))
lPBType = PB_PSD;
else { // Try SSA...
MISSA & FeedSSA = Feed.IF<MISSA>(false);
if (!IsNothing(FeedSSA))
lPBType = PB_SSA;
else
lPBType = PB_None;
}
Log.SetCondition(lPBType==PB_None, 1, MMsg_Warning, "Bad Feed Stream - No PSD or SSA Property");
if (IsNothing(FeedB) || IsNothing(FeedPSD)) streamOK = false;
if (!IsNothing(FeedPSD)) {
displayPSD(Feed, 2);
}
if (bOnLine && streamOK) { // Online and have Bayer and SSA properties...
fpsd =QALPSD(Feed);
m_dSolidsIn = fpsd.getVol()*Feed.Mass()*2420; // Feed.Density(MP_Sol);
if (!bKernelOK) {
AgglomKernel();
BinFactors();
bKernelOK = true;
}
DoPrecip(Tank);
displayPSD(Feed, 4);
displayPSD(Tank, 5);
DoResults(Tank);
UFlow = Tank;
alreadySolved = true;
} else { // Just tidy up and put some sensible stuff in the results...
Log.Message(MMsg_Warning, "Stream Problem...");
}
}
catch (MMdlException &e)
{
Log.Message(MMsg_Error, e.Description);
}
catch (MFPPException &e)
{
e.ClearFPP();
Log.Message(MMsg_Error, e.Description);
}
catch (MSysException &e)
{
Log.Message(MMsg_Error, e.Description);
}
catch (...)
{
Log.Message(MMsg_Error, "Some Unknown Exception occured");
}
}
//--------------------------------------------------------------------------
void CDynPrecipitator::ClosureInfo(MClosureInfo & CI)
{//ensure heat balance
if (CI.DoFlows())
{
CI.AddPowerIn(0, -dThermalLoss);
}
}
void CDynPrecipitator::DoPrecip(MStream & Prod)
{
bool converged = false;
int Iter=0; // Number of iterations in main loop
m_dOldTotDH = 0.0;
getN(Prod);
m_dSSA = m_dArea;
while (!converged && Iter < m_lItermax) { // Main iterative loop on final temperature and concentration
EvalPrecipRates(Prod); /// Determine the precipitation rates
EvalLosses(Prod); /// Evaluate the thermal losses
AdjustMasses(Prod); /// Adjust the mass flows
AdjustT(Prod); /// Adjust temperature for thermal losses, reaction heats etc
// AdjustSSA(Prod); /// Adjust SSA
//AdjustPSD(Prod); /// Adjust PSD
converged = true; //// Final convergence test
Iter++;
}
if (Iter==m_lItermax) {/// Convergence Failure, automatically increase damping and iterations???
}
putN(Prod);
m_lIterations = Iter;
Log.SetCondition(Iter==m_lItermax, 4, MMsg_Warning, "Precip loop failed to converge....");
}
// Precalculate Agglomeration Kernel and bin split factors
void CDynPrecipitator::AgglomKernel() {
for (int i=0; i<nClasses; i++) {
for (int j=0; j<=i; j++) {
beta[i][j] = beta[j][i] = exp(-(D[i]*D[i]+D[j]*D[j])/1600.);
// dbg.log("i, j = %3d %3d %12.5g", i, j, beta[i][j]);
}
}
}
void CDynPrecipitator::BinFactors() {
int k;
double alpha = 2;
double a1 = alpha-1;
for (int i=0; i<nClasses; i++) {
for (int j=0; j<i; j++) {
k = klf(i,j);
bsplit[i][j] = (alpha - pow(alpha, i-k) - pow(alpha, j-k))/a1;
// dbg.log("i, j = %3d %3d %12.5g", i, j, bsplit[i][j]);
}
bsplit[i][i] = .5;
}
}
void CDynPrecipitator::displayPSD(MStream &ms, int scrn)
{
MIPSD & mpsd = ms.IF<MIPSD>(false); /// Does the mud stream have PSD...
int ic = mpsd.getSizeCount();
if (ic>40) ic=40;
double x=0.0;
QALPSD ps(ms);
for (int i=0; i<ic; i++) {
switch (iPSD) {
case 0:
x = ps.getFrac(i);
break;
case 1:
x = ps.getN(i);
break;
case 2:
x = mpsd.getSize(i);
break;
}
dd[scrn][i]=x;
}
}
// Ilievski Correlation (1991)
// Note this uses Caustic as Na2O
double CDynPrecipitator::AgglomRate() {
double ssat = m_dSSat/(MW_Na2O/(2*MW_NaOH)); // Caustic as Na2O
dAgglomRate = 5.0e-10*pow(ssat, 4)/3600;
return dAgglomRate;
}
// Just the White method ala CAR for the moment...
double CDynPrecipitator::GrowthRate() {
const double T = Tank.T;
switch (iGrowthRateMethod) {
case GRM_Fixed: // dGrowthRate given directly in access window
return dGrowthRate;
case GRM_White:
{
double ssat=m_dSSat;
if (ssat < 0) ssat=0.0;
dGrowthRate = gF_White*K_White*Exps(-ER_White/Tank.T)*Sqr(ssat)/1000000./3600.; // m/s
}
case GRM_CAR_QAL:
{
MIBayer & TankB = Tank.IF<MIBayer>(false);
double C = TankB.CausticConc(T);
double C25 = TankB.CausticConc(C2K(25));
double CtoS = TankB.CtoS();
double S_out = C25/CtoS;
// double FC = TankB.FreeCaustic(T);
double FC = TankB.FreeCaustic(C2K(25));
double ACeq = TankB.AluminaConcSat(T)/C;
double TOOC=TankB.TOC(C2K(25))*MW_Na2CO3/MW_C;
double a=Exps(-m_dActivationEnergy/T);
double b=Exps(-TOOC*m_dk_TOC);
double c=Pow(GTZ(S_out), m_dn_s);
double d=Pow(GTZ(FC), m_dn_fc);
double e=Pow(GTZ(ACeq), m_dn_eq);
double K = m_dK0*a*b*c*d*e;
double ACout = TankB.AtoC();
double VLiq = Tank.Volume()*3600.;
double MSolids = Tank.MassVector[spTHA]*3600.0/1000.0;
double Sol = MSolids*1000.0/GTZ(VLiq);
double deltaAC = K * dResidenceTime/3600 *
Pow(GTZ(ACout-ACeq),m_dn_) * Pow(GTZ(Sol),m_dn_sol) * Pow(GTZ(m_dSSA),m_dn_ssa);
const double denS = Tank.Density(MP_Sol);
const double XG = Tank.MassVector[spAlumina]/Tank.MassVector[spTHA];
const double alpha = 117.963/77.963;
dGrowthRate = 2./denS*XG/alpha/ACout/m_dArea*deltaAC;
}
}
dGrowthYield = m_dArea*dGrowthRate/2*2420; // kg hydrate /s /kg slurry
return dGrowthRate;
}
// Misra 1970
double CDynPrecipitator::NucleationRate() {
if (iGrowthRateMethod==GRM_CAR_QAL) {
MIBayer & TankB=Tank.IF<MIBayer>(false);
const double T = Tank.T;
const double SPO = Tank.MassVector[spOxalate]/Tank.MassVector[spAlumina];
const double A = TankB.AluminaConc(T);
const double ASAT = TankB.AluminaConcSat(T);
const double ssat = A/ASAT;
/// Insert Code here....
dNuclRate = (1+1500*SPO)*exp(2100*(1./343. - 1/T))*pow(ssat-1, 6)*TankB.SodaConc(T);
return dNuclRate*m_dArea/3600*1000000;
} else {
double ssat=m_dSSat;
if (ssat < 0) ssat=0.0;
dNuclRate = 5.0e8*pow(ssat,4)*m_dSSA/3600;
return dNuclRate;
}
}
// Calculate numbers for agglomeration...
// Loop over all pairs of bins < NClasses
// Calculate agglomeration rate for these bins
// and destination bin(s)
void CDynPrecipitator::Agglomeration() {
for (int i=0; i<nClasses-1; i++) {
// Special case when j=i
// ie agglomeration of particles of equal sizes.
int k = i+1;
double NN = beta[i][i]*Sqr(n[i])*dAgglRateFactor*dAgglomRate;
Ndot[i] -= NN;
Ndot[k] += bsplit[i][i]*NN;
// And the rest
for (int j=0; j<i; j++) {
k = i; // Destination bin
if (k+1 < nClasses) {
NN = beta[i][j]*n[i]*n[j]*dAgglRateFactor*dAgglomRate;
Ndot[i] -= NN;
Ndot[j] -= NN;
Ndot[k] += bsplit[i][j]*NN;
Ndot[k+1] += (1-bsplit[i][j])*NN;
//dbg.log("i,j %3d, %3d, NN = %12.5g", i, j, NN);
}
}
}
}
// Numbers for Growth
void CDynPrecipitator::Growth()
{
for (int i = 1; i<nClasses-1; i++) {
double g = n[i]*AREA_CORR/DIST_CORR*dGrowthRate/D[i]*1.0e6*dGrowthRateFactor;
Ndot[i] -= g;
Ndot[i+1] += g;
}
}
void CDynPrecipitator::Nucleation()
{
Ndot[1] += dNuclRate*dNuclRateFactor;
dNuclYield = PI/6.*pow(D[1],3)*2420*dNuclRate*dNuclRateFactor*1.0e-18/3600;
}
void CDynPrecipitator::Attrition() {}
void CDynPrecipitator::AttritionRate() {}
/// Calculate all the particle balance rates...
/// Ndot[i] ... rate of change of n[i], #/s/kg
void CDynPrecipitator::PBRates()
{
for (int i=0; i<nClasses; i++) Ndot[i] = (Feed.Mass()*fpsd.getN(i) - Tank.Mass()*n[i])/(Tank.Density()*dTankVol);
if (bAgglomOn) {
AgglomRate();
Agglomeration();
}
if (bNuclOn) {
NucleationRate();
Nucleation();
}
if (bGrowthOn) {
GrowthRate();
Growth();
}
if(bAttritionOn) {
AttritionRate();
Attrition();
}
// Save the values for display
for (int i=0; i<nClasses; i++) {
switch (iDType) {
case 0:
dd[6][i]=0;
break;
case 1:
dd[6][i]=0;
break;
case 2:
dd[6][i]=Ndot[i];
break;
case 3:
dd[6][i]=n[i];
break;
case 4:
dd[6][i]=NewN[i];
break;
}
}
}
void CDynPrecipitator::getN(MStream &s)
{
QALPSD p(s);
for (int i=0; i<nClasses; i++) n[i] = p.getN(i);
m_dArea = p.getArea();
m_dVol = p.getVol();
m_dNumber = p.getNTot();
} // Fetch all the numbers to local N, return total
void CDynPrecipitator::putN(MStream &s)
{
MIPSD & sP = s.IF<MIPSD>(false);
double solidsContent = s.MassVector[spTHA]/GTZ(s.Mass());
if (fabs(solidsContent) < 1.0e-10) return;
double avvol = PI/6.*D[0]*D[0]*D[0]*.125*1.0e-18;
double z = n[0]*avvol*2420/solidsContent;
sP.putFrac(0, z);
for (int i=1; i<nClasses; i++) {
avvol = PI/6.*pow(D[i],3)*DIST_CORR*1.0e-18;
double z = n[i]*avvol*2420/solidsContent;
sP.putFrac(i, z);
}
} // Put local N to stream
void CDynPrecipitator::BuildDataFields()
{
static MDDValueLst DDB1[]={
{GRM_Fixed, "Fixed" },
{GRM_White, "White"},
{GRM_CAR_QAL, "CAR-QAL"},
{0}};
static MDDValueLst DDB2[]={
{0, "Fraction" },
{1, "Number"},
{2, "F*"},
{0}};
static MDDValueLst DDB3[]={
{THL_None, "None" },
{THL_TempDrop, "TempDrop"},
{THL_FixedHeatFlow, "FixedLoss"},
{THL_Ambient, "Ambient"},
{0}};
static MDDValueLst DDB5[]={
{ COOL_dQ, "Fixed.dQ"},
{ COOL_dT, "Fixed.dT" },
{ COOL_Hx, "HeatExchange"},
{0}};
static MDDValueLst DDB6[]={
{ EVAP_NONE, "None"},
{ EVAP_FIXED, "Fixed"},
{ EVAP_dT, "Ambient" },
{0}};
static MDDValueLst DDB7[]={
{ COOL_NONE, "None"},
{ COOL_INTERNAL, "Internal"},
{ COOL_EXTERNAL, "External" },
{0}};
static MDDValueLst DDB14[]={
{0, "Growth" },
{1, "Aggl (N/s/m^3)"},
{2, "deltaN"},
{3, "oldN"},
{4, "newN"},
{0}};
DD.Text ("");
#ifdef TTDEBUG
DD.CheckBox("TTDBG", "", &bTTDebug, MF_PARAMETER);
#endif
DD.CheckBox("On", "", &bOnLine, MF_PARAMETER|MF_SET_ON_CHANGE);
// DD.CheckBox("Int.Cooling", "", &m_bInternalCool, MF_PARAMETER|MF_SET_ON_CHANGE);
//DD.CheckBox("Ext.Cooling", "", &m_bExternalCool, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.Text("");
DD.CheckBox("Growth.On", "", &bGrowthOn, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.CheckBox("Agglom.On", "", &bAgglomOn, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.CheckBox("Nucleation.On", "", &bNuclOn, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.CheckBox("Attrition.On", "", &bAttritionOn, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.Long ("Cooling", "", &iCoolType, MF_PARAMETER|MF_SET_ON_CHANGE, DDB7);
//m_RB.OnOffCheckBox();
DD.Long ("Evaporation", "", &iEvapMethod , MF_PARAMETER|MF_SET_ON_CHANGE, DDB6);
DD.Show(iEvapMethod!=EVAP_NONE);
DD.Double("Evap.Rate", "", &m_dEvapRate ,iEvapMethod==EVAP_FIXED?MF_PARAMETER:MF_RESULT, MC_Qm("kg/s"));
DD.Show(iEvapMethod==EVAP_dT);
DD.Double("Evap.Per.degK", "", &m_dEvapRateK ,MF_PARAMETER, MC_Qm("kg/s"));
DD.Show();
DD.Long ("ThermalLossMethod", "",&iThermalLossMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB3);
DD.Show(iThermalLossMethod==THL_TempDrop);
DD.Double("Temp_Drop", "", &dTempDropRqd ,MF_PARAMETER, MC_dT("C"));
DD.Show(iThermalLossMethod==THL_FixedHeatFlow);
DD.Double("ThermalLossRqd", "", &dThermalLossRqd ,MF_PARAMETER, MC_Pwr("kW"));
DD.Show(iThermalLossMethod==THL_Ambient);
DD.Double("ThermalLossAmbient", "", &dThermalLossAmbient ,MF_PARAMETER, MC_UA);
DD.Show();
DD.Text("");
DD.Text ("Requirements");
DD.Double("TankVol", "", &dTankVol ,MF_PARAMETER, MC_Vol("m^3"));
DD.Text ("");
DD.Text ("Results Tank");
DD.Double("ResidenceTime", "", &dResidenceTime ,MF_RESULT, MC_Time("h"));
DD.Double("SuperSat", "", &m_dSSat, MF_RESULT, MC_);
DD.Double("Yield", "", &dYield ,MF_RESULT, MC_Conc("kg/m^3"));
DD.Double("SolidsIn", "", &m_dSolidsIn, MF_RESULT, MC_Qm("kg/s"));
DD.Double("SolidsOut", "", &m_dSolidsOut, MF_RESULT, MC_Qm("kg/s"));
DD.Double("NucleationYield", "", &dNuclYield, MF_RESULT, MC_Qm("kg/s"));
DD.Double("GrowthYield", "", &dGrowthYield, MF_RESULT, MC_Qm("kg/s"));
DD.Double("THA.Precip", "", &dTHAPrecip ,MF_RESULT, MC_Qm("kg/s"));
DD.Double("Solids.Precip", "", &dSolPrecip ,MF_RESULT, MC_Qm("kg/s"));
DD.Double("Solids.Conc", "", &dSolConc ,MF_RESULT, MC_Conc("kg/m^3"));
DD.Text ("Results");
DD.Show();
DD.Double("Vol_FlowIn", "", &dQvin ,MF_RESULT, MC_Qv("L/s"));
DD.Double("Vol_FlowOut", "", &dQvout ,MF_RESULT, MC_Qv("L/s"));
DD.Double("MassFlowIn", "", &dQmin ,MF_RESULT, MC_Qm("t/d"));
DD.Double("MassFlowOut", "", &dQmout ,MF_RESULT, MC_Qm("t/d"));
DD.Double("ACin", "", &dACin ,MF_RESULT, MC_);
DD.Double("ACout", "", &dACout ,MF_RESULT, MC_);
DD.Double("ACequil", "", &m_dACeq ,MF_RESULT, MC_);
DD.Double("TempIn", "", &dTin ,MF_RESULT, MC_T("C"));
DD.Double("TempOut", "", &dTout ,MF_RESULT, MC_T("C"));
DD.Text("");
DD.Page("Precip");
DD.Long ("GrowthMethod", "", (long*)&iGrowthRateMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB1);
DD.Double("Convergence.Limit", "", &m_dConvergenceLimit, MF_PARAMETER|MF_INIT_HIDDEN, MC_);
DD.Double("Acceleration", "", &m_ddeltaT, MF_PARAMETER|MF_INIT_HIDDEN, MC_);
DD.Double("Thermal.Damping", "", &m_dDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%"));
DD.Double("Mass.Damping", "", &m_dMassDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%"));
DD.Long("Iterations", "", &m_lIterations, MF_RESULT|MF_NO_FILING);
DD.Long("IterMax", "", &m_lItermax, MF_PARAMETER);
// DD.Double("Vol.Damping", "", &m_dVolDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%"));
DD.Show (iGrowthRateMethod==GRM_Fixed);
DD.Double("Precip.Rate", "", &dGrowthRate ,MF_PARAMETER, MC_Ldt("um/h"));
DD.Show (iGrowthRateMethod==GRM_White);
DD.Double("ER_White", "", &ER_White ,MF_PARAMETER, MC_T("K"));
DD.Double("K_White", "", &K_White ,MF_PARAMETER, MC_);
DD.Double("gF_White", "", &gF_White ,MF_PARAMETER, MC_);
DD.Show (iGrowthRateMethod==GRM_CAR_QAL);
DD.Double("ActivationEnergy", "", &m_dActivationEnergy ,MF_PARAMETER, MC_T("K"));
DD.Double("K0", "", &m_dK0 ,MF_PARAMETER, MC_);
//DD.Double("K1", "", &m_dK1 ,MF_PARAMETER, MC_);
DD.Double("k_TOC", "", &m_dk_TOC ,MF_PARAMETER, MC_);
DD.Double("n_s", "", &m_dn_s ,MF_PARAMETER, MC_);
DD.Double("n_fc", "", &m_dn_fc ,MF_PARAMETER, MC_);
DD.Double("n_eq", "", &m_dn_eq ,MF_PARAMETER, MC_);
DD.Double("n_", "", &m_dn_ ,MF_PARAMETER, MC_);
DD.Double("n_sol", "", &m_dn_sol ,MF_PARAMETER, MC_);
DD.Double("n_ssa", "", &m_dn_ssa ,MF_PARAMETER, MC_);
DD.Show();
DD.Text("Fudge Factors");
DD.Double("Growth.Rate.Factor", "", &dGrowthRateFactor, MF_PARAMETER, MC_);
DD.Double("Agglom.Rate.Factor", "", &dAgglRateFactor, MF_PARAMETER, MC_);
DD.Double("Nucl.Rate.Factor", "", &dNuclRateFactor, MF_PARAMETER, MC_);
DD.Show();
DD.Text("Results");
DD.Double("Growth.Rate", "", &dGrowthRate ,MF_RESULT|MF_NO_FILING, MC_Ldt("um/h"));
DD.Double("Agglom.Rate", "", &dAgglomRate ,MF_RESULT|MF_NO_FILING, MC_);
DD.Double("Nucl.Rate", "", &dNuclRate ,MF_RESULT|MF_NO_FILING, MC_);
DD.Double("SSAin", "", &m_dSSAin ,MF_RESULT, MC_);//SurfAreaM);
DD.Double("SSA", "", &m_dSSA ,MF_RESULT, MC_);//SurfAreaM);
DD.Text("Thermal and Mass Balance");
DD.Double("Mass.Flow.In", "", &dQmin ,MF_RESULT|MF_NO_FILING, MC_Qm("t/d"));
DD.Double("Mass.Flow.Out", "", &dQmout ,MF_RESULT|MF_NO_FILING, MC_Qm("t/d"));
DD.Show(iEvapMethod);
DD.Double("Evap.Mass.Loss", "", &m_dEvapRate, MF_RESULT, MC_Qm("kg/s"));
DD.Double("Evap.Thermal.Loss", "", &m_dEvapThermalLoss ,MF_RESULT, MC_Pwr("kW"));
DD.Show(iThermalLossMethod==THL_Ambient);
DD.Double("Env.Thermal.Loss", "", &m_dEnvironmentLoss, MF_RESULT, MC_Pwr("kW"));
DD.Show(iCoolType);
DD.Double("Cooler.Thermal.Loss", "", &m_dCoolRate, MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate
DD.Double("ReactionHeat", "", &dReactionHeat ,MF_RESULT, MC_Pwr("kW"));
DD.Double("Total.Thermal.Loss", "", &m_dTotThermalLoss, MF_RESULT, MC_Pwr("kW"));
DD.Text("Stream.Enthalpy");
DD.Double("HzIn", "", &m_dHIn, MF_RESULT, MC_Pwr);
DD.Double("HzEvap", "", &m_dHEvap, MF_RESULT, MC_Pwr);
DD.Double("HzOut", "", &m_dHOut, MF_RESULT, MC_Pwr);
DD.Double("HzBal", "", &m_dHBal, MF_RESULT, MC_Pwr);
DD.Show();
DD.Page("Size Inlet");
DD.Long("PSD.Display", "", &iPSD, MF_PARAMETER|MF_SET_ON_CHANGE, DDB2);
const int NumSpecies = gs_MVDefn.Count();
for (int i=0; i<nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i << std::setw(12) << D[i] ;
DD.Double(os.str().c_str(), "", dd[2]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
// DD.Page("Size In");
// for (int i=0; i<nClasses; i++) {
// std::stringstream os;
// os << "Size " << std::setw(3) << i;
// DD.Double(os.str().c_str(), "", dd[4]+i, MF_RESULT|MF_NO_FILING, MC_None);
// }
// DD.Text("");
// DD.Double("Number", "", dd[4]+26, MF_RESULT|MF_NO_FILING, MC_None);
// DD.Double("Area", "", dd[4]+27, MF_RESULT|MF_NO_FILING, MC_None);
// DD.Double("Vol", "", dd[4]+28, MF_RESULT|MF_NO_FILING, MC_None);
// DD.Double("Mass", "", dd[4]+29, MF_RESULT|MF_NO_FILING, MC_None);
DD.Page("Size Tank");
for (int i=0; i<nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[5]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Text("");
DD.Double("Number", "", dd[5]+26, MF_RESULT|MF_NO_FILING, MC_None);
DD.Double("Area", "", dd[5]+27, MF_RESULT|MF_NO_FILING, MC_None);
DD.Double("Vol", "", dd[5]+28, MF_RESULT|MF_NO_FILING, MC_None);
DD.Double("Mass", "", dd[5]+29, MF_RESULT|MF_NO_FILING, MC_None);
DD.Page("Numbers...");
// DD.Page(DDB14[iDType].m_pStr);
DD.Long("DType", "", &iDType, MF_PARAMETER|MF_SET_ON_CHANGE, DDB14);
for (int i=0; i<nClasses; i++) {
std::stringstream os;
os << "Size " << std::setw(3) << i;
DD.Double(os.str().c_str(), "", dd[6]+i, MF_RESULT|MF_NO_FILING, MC_None);
}
DD.Show(iCoolType);
DD.Page("Cooler");
DD.Show(iCoolType==COOL_INTERNAL);
DD.CheckBox("Cooler.On", "", &m_bCoolerOn, MF_PARAMETER);
DD.Long ("Cooling.Type", "", (long*)&iCoolMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB5);
DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_dT));
DD.Double("dT", "", &m_dCooldT, MF_PARAMETER, MC_dT("C"));
DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_dQ));
DD.Double("dQ", "", &m_dCooldQ, MF_PARAMETER, MC_Pwr("kW"));
DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx));
DD.Double("HX.Area", "", &m_dCoolArea, MF_PARAMETER, MC_Area("m^2"));
DD.Double("HX.HTC", "", &m_dCoolHTC, MF_PARAMETER, MC_HTC);
DD.Show(iCoolType==COOL_EXTERNAL || (iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx)));
DD.CheckBox("By.Vol.Flow", "", &m_bByVolFlow, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx));
DD.Double("Cooling.Flow", "", &m_dCoolFlow,
m_bByVolFlow ? MF_RESULT : MF_PARAMETER, MC_Qm("kg/s")); // Internal cooling flow
DD.Double("Int.Vol.Flow", "", &m_dIntCoolVolFlow,
m_bByVolFlow ? MF_PARAMETER : MF_RESULT, MC_Qv("m^3/s")); // By Volume
DD.Double("Hx.UA", "", &m_dUA, MF_RESULT, MC_UA);
DD.Double("Hx.LMTD", "", &m_dLMTD, MF_RESULT, MC_dT);
DD.Double("Water.Flow", "", &m_dCoolWaterFlow, MF_RESULT, MC_Qm("kg/s"));
DD.Double("Water.Vol.Flow", "", &m_dCoolWaterFlowVol, MF_RESULT, MC_Qv);
DD.Double("Water.Tin", "", &m_dCoolWaterTin, MF_RESULT, MC_T("C"));
DD.Double("Water.Tout", "", &m_dCoolWaterTout, MF_RESULT, MC_T("C"));
DD.Double("Liquor.Tin", "", &m_dLiquorTin, MF_RESULT, MC_T("C"));
DD.Double("Liquor.Tout", "", &m_dLiquorTout, MF_RESULT, MC_T("C"));
DD.Show(iCoolType==COOL_EXTERNAL);
DD.Double("Ext.Vol.Flow", "", &m_dExtCoolVolFlow,
m_bByVolFlow ? MF_PARAMETER : MF_RESULT, MC_Qv("m^3/s")); // Ext Cooling.Flow
DD.Double("Ext.Cooling.Flow", "", &m_dExtCoolFlow,
m_bByVolFlow ? MF_RESULT : MF_PARAMETER, MC_Qm("kg/s")); // Ext Cooling.Flow
DD.Double("Ext.Cooling.Temp", "", &m_dExtCoolTemp, MF_RESULT, MC_T("C")); // Ext Cooling.Temp
DD.Double("Ext.Cooling.totHz", "", &m_dCoolOutTotHz , MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate
DD.Show(iCoolType);
DD.Double("Cooling.Rate", "", &m_dCoolRate, MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate
if (!m_bEvapConnected && iEvapMethod!=EVAP_NONE) //if optional Evap is NOT connected and evaporation functionality is required show the output stream
DD.Object(Evap, MDD_RqdPage);
//DD.Show(m_RB.Enabled());
//DD.Page("RB");
//m_RB.BuildDataFields();
//DD.Show();
}
|
[
"[email protected]"
] |
[
[
[
1,
1083
]
]
] |
6d743f9b40bec651f5fdd09869a1c5a48692832b
|
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
|
/Vision/visionRobot/GarbageRecognition.cpp
|
f307caa1be0d1629ca544c8073aa01bfff46be5a
|
[] |
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 | 14,248 |
cpp
|
#include "GarbageRecognition.h"
#include "Prediction.h"
//~ #define BENCHMARK_H
#include <highgui.h>
#include <cv.h>
#include <vector>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Contours.h"
#include "Histogram.h"
#include "Garbage.h"
#include "Windowing.h"
#include "MinimalBoundingRectangle.h"
#include "PredictionParameters.h"
// image preprocessing values
#define THRESHOLD_VALUE 240
#define MORPH_KERNEL_SIZE 1
#define MORPH_DILATE_ITER 2
#define MORPH_ERODE_ITER 1
#define _RED cvScalar (0, 0, 255, 0)
#define _GREEN cvScalar (0, 255, 0, 0)
//contour filters constants
#define MINCONTOUR_AREA 1000
#define MAXCONTOUR_AREA 10000
#define BOXFILTER_TOLERANCE 0.7
#define MINCONTOUR_PERIMETER 2
#define MAXCONTOUR_PERIMETER 1000
#define CONTOUR_RECTANGULAR_MIN_RATIO 1.2
#define CONTOUR_RECTANGULAR_MAX_RATIO 3.0
#define HIST_S_BINS 8
#define HIST_H_BINS 8
#define HIST_MIN 0.7
#define TIME_THRESHOLD 15 //seconds
#define ENABLE_WINDOWING true
#ifdef BENCHMARK_H
extern int focusedFrames;
#endif
namespace utils {
void drawPrediction(IplImage * src,std::list<utils::Garbage*> garbagePrediction);
std::list<utils::Garbage*> garbages;
std::list<utils::Garbage*> garbagePrediction;
IplImage * src_window;
GarbageRecognition::GarbageRecognition(){
this->prediction= new Prediction();
this->window=NULL;
frameNumber=0;
focused=false;
doWindowing=true;
doPrediction=true;
}
GarbageRecognition::~GarbageRecognition(){};
std::list<Garbage*>
GarbageRecognition::getGarbageList(IplImage * src)
{
//~ IplImage * model = cvLoadImage("./colilla-sinBlanco.png",1);
IplImage * copy;
//windowing
if(this->focused){
if(window->currentGarbage->state!=DEAD){
if(src_window!=NULL){
if(window->last_last_window!=NULL)
//cvReleaseImageHeader(&(window->last_last_window));
//logic to release sub-windowing memory
if(window->release_window){
window->last_last_window=window->last_window;
window->last_window=src_window;
}
}
src_window=this->window->getWindow(src);
if(src_window==NULL){
this->focused=false;
delete window;
src_window=src;
}
window->release_window=true;
}
else{
this->focused=false;
delete window;
src_window=src;
}
}else{
src_window=src;
}
//get garbages from vision system
garbages = this->garbageList(src_window,NULL);
if(this->focused){
garbages=this->window->correctGarbages(garbages);
#ifdef BENCHMARK_H
focusedFrames++;
#endif
}
//Feed retrieved garbages to prediction system
if(this->doPrediction)
garbagePrediction= this->prediction->getPrediction(garbages);
else
garbagePrediction=garbages;
//start windowing
if(this->doWindowing && (this->frameNumber % NUMBER_OF_FRAMES_TO_FOCUS) && this->focused==false ){
GarbageHistoric * focusedGarbage=prediction->focusGarbage();
if(focusedGarbage!=NULL){
this->window=new Windowing(focusedGarbage,cvGetSize(src));
this->focused=true;
window->release_window=false;
}
}
drawPrediction(src,garbagePrediction);
//~ cvReleaseImage(&model);
this->frameNumber++;
//return garbages;
return garbagePrediction;
}
std::list<Garbage*>
GarbageRecognition::garbageList(IplImage * src, IplImage * model){
clock_t start = clock();
std::list<Garbage*> garbageList;
std::vector<int> centroid(2);
//~ utils::Histogram * h = new Histogram(HIST_H_BINS,HIST_S_BINS);
//~ CvHistogram * testImageHistogram = h->getHShistogramFromRGB(model);
//gets a frame for setting image size
CvSize srcSize = cvGetSize(src);
CvRect srcRect = cvRect(0,0,srcSize.width,srcSize.height);
//images for HSV conversion
IplImage* hsv = cvCreateImage( srcSize, 8, 3 );
IplImage* h_plane = cvCreateImage( srcSize, 8, 1 );
IplImage* h_plane2 = cvCreateImage( srcSize, 8, 1 );
IplImage* h_planeV ;//= cvCreateImage( srcSize, 8, 1 );
IplImage* s_plane = cvCreateImage( srcSize, 8, 1 );
IplImage* v_plane = cvCreateImage( srcSize, 8, 1 );
//Image for filtering
IplImage * andImage=cvCreateImage(srcSize,8,1);
IplImage * andImageV=cvCreateImage(srcSize,8,1);
//Image for thresholding
IplImage * threshImage=cvCreateImage(srcSize,8,1);
IplImage * threshImageV=cvCreateImage(srcSize,8,1);
//image for Morphing operations(Dilate-erode)
IplImage * morphImage=cvCreateImage(srcSize,8,1);
IplImage * morphImageV=cvCreateImage(srcSize,8,1);
//image for contour-finding operations
IplImage * contourImage=cvCreateImage(srcSize,8,3);
clock_t create=clock();
printf("Time elapsed create Image: %f\n", ((double)create - start) / CLOCKS_PER_SEC);
int frameCounter=1;
int cont_index=0;
//convolution kernel for morph operations
IplConvKernel* element;
CvRect boundingRect;
//contours
CvSeq * contours;
CvSeq * contoursCopy;
//Main loop
//convert image to hsv
cvCvtColor( src, hsv, CV_BGR2HSV );
clock_t conv=clock();
printf("Time elapsed create Image- convert image: %f\n", ((double)conv - create) / CLOCKS_PER_SEC);
cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );
h_planeV=cvCloneImage(h_plane);
h_plane2=cvCloneImage(h_plane);
CvScalar vasosL1 = cvScalar (0, 0, 170);
CvScalar vasosU1 = cvScalar (20, 255, 255);
CvScalar vasosL = cvScalar (40, 0, 170);
CvScalar vasosU = cvScalar (255, 255, 255);
CvScalar colillasL = cvScalar (20, 60, 0);
CvScalar colillasU = cvScalar (40, 255,255);
clock_t inrange=clock();
//~ cvInRangeSalt( hsv,vasosL,vasosU, vasosL1, vasosU1,h_plane );
cvInRangeS( hsv, vasosL1, vasosU1, h_plane );
cvInRangeS( hsv, vasosL, vasosU, h_plane2 );
cvOr(h_plane,h_plane2,h_plane);
printf("inRange %f\n", ((double)clock() - inrange) / CLOCKS_PER_SEC);
cvInRangeS( hsv, colillasL,colillasU,h_planeV);
cvShowImage("inrange vasos",h_plane);
//~ cvShowImage("inrange colillas",h_planeV);
//~ for(int x=0;x<srcSize.width;x++){
//~ for(int y=0;y<srcSize.height;y++){
//~ uchar * hue=&((uchar*) (h_plane->imageData+h_plane->widthStep*y))[x];
//~ uchar * hueV=&((uchar*) (h_planeV->imageData+h_plane->widthStep*y))[x];
//~ uchar * sat=&((uchar*) (s_plane->imageData+s_plane->widthStep*y))[x];
//~ uchar * val=&((uchar*) (v_plane->imageData+v_plane->widthStep*y))[x];
//~ if((*val>170) && (( (*hue)<20 || (*hue)>40) ))
//~ *hue=255;
//~ else
//~ *hue=0;
//filter for cigar filters
//~ if((*hueV>20 && *hueV<40 && *sat>60))
//~ *hueV=255;
//~ else
//~ *hueV=0;
//~ }
//~ }
clock_t color=clock();
printf("Time elapsed create Image - color filter: %f\n", ((double)color - conv) / CLOCKS_PER_SEC);
//--first pipeline
//apply morphologic operations
element = cvCreateStructuringElementEx( MORPH_KERNEL_SIZE*2+1,
MORPH_KERNEL_SIZE*2+1, MORPH_KERNEL_SIZE, MORPH_KERNEL_SIZE,
CV_SHAPE_RECT, NULL);
cvDilate(h_plane,morphImage,element,MORPH_DILATE_ITER);
cvErode(morphImage,morphImage,element,MORPH_ERODE_ITER);
cvThreshold(morphImage,threshImage,100,255,CV_THRESH_BINARY);
clock_t pipe1=clock();
printf("Time elapsed color filter - first pipeline: %f\n", ((double)pipe1 - color) / CLOCKS_PER_SEC);
//-- end first pipeline
//-- start 2nd pipeline-----
cvAnd(h_planeV, v_plane, andImageV);
//apply morphologic operations
cvDilate(andImageV,morphImageV,element,MORPH_DILATE_ITER);
cvErode(morphImageV,morphImageV,element,MORPH_ERODE_ITER);
cvThreshold(morphImageV,threshImageV,100,255,CV_THRESH_BINARY);
//--end second pipeline--
clock_t pipe2=clock();
printf("Time elapsed first pipeline - second pipeline: %f\n", ((double)pipe2 - pipe1) / CLOCKS_PER_SEC);
//get all contours
contours=myFindContours(threshImage);
contoursCopy=contours;
cont_index=0;
//image to write contours on
cvCopy(src,contourImage,0);
//contours for dishes and glasses
while(contours!=NULL){
CvSeq * aContour=getPolygon(contours);
utils::Contours * ct;
if(this->window==NULL)
ct = new Contours(aContour);
else
ct = new Contours(aContour,this->window->window);
//apply filters for vasos
if( ct->perimeterFilter(100,10000) &&
ct->areaFilter(1000,100000) &&
ct->vasoFilter()
){
//get contour bounding box
boundingRect=cvBoundingRect(ct->getContour(),0);
cvRectangle(contourImage,cvPoint(boundingRect.x,boundingRect.y),
cvPoint(boundingRect.x+boundingRect.width,
boundingRect.y+boundingRect.height),
_GREEN,1,8,0);
//if passed filters
ct->printContour(3,cvScalar(127,127,0,0),
contourImage);
centroid=ct->getCentroid();
//build garbage List
utils::MinimalBoundingRectangle * r = new utils::MinimalBoundingRectangle(boundingRect.x,
boundingRect.y,boundingRect.width,boundingRect.height);
utils::Garbage * aGarbage = new utils::Garbage(r,centroid,ct);
//benchmark purposes
aGarbage->isVisualized=true;
aGarbage->isPredicted=false;
aGarbage->isFocused=false;
garbageList.push_back(aGarbage);
}else if( ct->perimeterFilter(100,10000) &&
ct->areaFilter(1000,100000) &&
ct->platoFilter()
){
//get contour bounding box
boundingRect=cvBoundingRect(ct->getContour(),0);
cvRectangle(contourImage,cvPoint(boundingRect.x,boundingRect.y),
cvPoint(boundingRect.x+boundingRect.width,
boundingRect.y+boundingRect.height),
_GREEN,1,8,0);
//if passed filters
ct->printContour(3,cvScalar(127,127,0,0),
contourImage);
centroid=ct->getCentroid();
//build garbage List
utils::MinimalBoundingRectangle * r = new utils::MinimalBoundingRectangle(boundingRect.x,
boundingRect.y,boundingRect.width,boundingRect.height);
utils::Garbage * aGarbage = new utils::Garbage(r,centroid,ct);
//benchmark purposes
aGarbage->isVisualized=true;
aGarbage->isPredicted=false;
aGarbage->isFocused=false;
garbageList.push_back(aGarbage);
}
//delete ct;
cvReleaseMemStorage( &aContour->storage );
contours=contours->h_next;
cont_index++;
}
clock_t vasoyplato=clock();
printf("Time elapsed first pipe2 - vasos y platos: %f\n", ((double)vasoyplato - pipe2) / CLOCKS_PER_SEC);
//2nd pipeline
//release temp images and data
if(contoursCopy!=NULL)
cvReleaseMemStorage( &contoursCopy->storage );
contours=myFindContours(threshImageV);
contoursCopy=contours;
cont_index=0;
while(contours!=NULL){
CvSeq * aContour=getPolygon(contours);
utils::Contours * ct;
if(this->window==NULL)
ct = new Contours(aContour);
else
ct = new Contours(aContour,this->window->window);
//apply filters
if( ct->perimeterFilter(10,800) &&
ct->areaFilter(50,800) &&
//ct->rectangularAspectFilter(CONTOUR_RECTANGULAR_MIN_RATIO, CONTOUR_RECTANGULAR_MAX_RATIO) &&
ct->boxAreaFilter(BOXFILTER_TOLERANCE) &&
//ct->histogramMatchingFilter(src,testImageHistogram, HIST_H_BINS,HIST_S_BINS,HIST_MIN)&&
1){
//get contour bounding box
boundingRect=cvBoundingRect(ct->getContour(),0);
cvRectangle(contourImage,cvPoint(boundingRect.x,boundingRect.y),
cvPoint(boundingRect.x+boundingRect.width,
boundingRect.y+boundingRect.height),
_GREEN,1,8,0);
//if passed filters
ct->printContour(3,cvScalar(127,127,0,0),
contourImage);
centroid=ct->getCentroid();
//build garbage List
utils::MinimalBoundingRectangle * r = new utils::MinimalBoundingRectangle(boundingRect.x,
boundingRect.y,boundingRect.width,boundingRect.height);
utils::Garbage * aGarbage = new utils::Garbage(r,centroid,ct);
//benchmark purposes
aGarbage->isVisualized=true;
aGarbage->isPredicted=false;
aGarbage->isFocused=false;
garbageList.push_back(aGarbage);
}
delete ct;
cvReleaseMemStorage( &aContour->storage );
contours=contours->h_next;
cont_index++;
}
clock_t colillas=clock();
printf("Time elapsed vasosyplatos - colillas: %f\n", ((double)colillas - vasoyplato) / CLOCKS_PER_SEC);
//display found contours
//~ cvShowImage("drawContours",contourImage);
//release temp images and data
if(contoursCopy!=NULL)
cvReleaseMemStorage( &contoursCopy->storage );
cvReleaseStructuringElement(&element);
cvReleaseImage(&threshImage);
cvReleaseImage(&threshImageV);
cvReleaseImage(&morphImage);
cvReleaseImage(&morphImageV);
cvReleaseImage(&contourImage);
cvReleaseImage(&hsv);
cvReleaseImage(&h_plane);
cvReleaseImage(&h_planeV);
cvReleaseImage(&s_plane);
cvReleaseImage(&v_plane);
cvReleaseImage(&andImageV);
cvReleaseImage(&andImage);
clock_t total=clock();
printf("total: %f\n", ((double)total - start) / CLOCKS_PER_SEC);
return garbageList;
}
void drawPrediction(IplImage * src,std::list<Garbage*> garbagePrediction){
CvSize srcSize = cvGetSize(src);
IplImage * predictionImage=cvCreateImage(srcSize,8,3);
cvCopy(src,predictionImage,0);
MinimalBoundingRectangle * boundingRect;
for (std::list<Garbage*>::iterator itGar = garbagePrediction.begin(); itGar != garbagePrediction.end(); itGar++)
{
boundingRect=(*itGar)->boundingBox();
cvRectangle(predictionImage,cvPoint(boundingRect->x,boundingRect->y),
cvPoint(boundingRect->x+boundingRect->width,
boundingRect->y+boundingRect->height),
_RED,1,8,0);
}
cvShowImage("prediction",predictionImage);
cvReleaseImage(&predictionImage);
}
void GarbageRecognition::enablePrediction(){
this->doPrediction=true;
}
void GarbageRecognition::disablePrediction(){
this->doPrediction=false;
}
void GarbageRecognition::enableWindowing(){
this->doWindowing=true;
}
void GarbageRecognition::disableWindowing(){
this->doWindowing=false;
}
} /* End of namespace utils */
|
[
"nuldiego@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
] |
[
[
[
1,
493
]
]
] |
84a7accea4d589f88f2e448715333c2598682d55
|
968aa9bac548662b49af4e2b873b61873ba6f680
|
/e32tools/elf2e32/source/deffile.cpp
|
f3ab8fc05b36c8c7dc5a5057ed3c2ab5436d7a7d
|
[] |
no_license
|
anagovitsyn/oss.FCL.sftools.dev.build
|
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
|
f458a4ce83f74d603362fe6b71eaa647ccc62fee
|
refs/heads/master
| 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 21,689 |
cpp
|
// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// Implementation of the Class DefFile for the elf2e32 tool
// @internalComponent
// @released
//
//
//
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "pl_symbol.h"
#include "deffile.h"
#include "errorhandler.h"
#ifdef __LINUX__
#include "h_utl.h"
#define STRUPR strupr
#else
#define STRUPR _strupr
#endif
using std::cerr;
using std::cout;
using std::endl;
#define SUCCESS 1
#define FAILURE 0
/**
Destructor to release all the allocated memory
@internalComponent
@released
*/
DefFile::~DefFile()
{
if(iSymbolList && iSymbolList->size())
{
SymbolList::iterator aItr = iSymbolList->begin();
SymbolList::iterator last = iSymbolList->end();
Symbol *temp;
while(aItr != last)
{
temp = *aItr;
aItr++;
delete temp;
}
iSymbolList->clear();
}
delete iSymbolList;
}
/**
Function to Get File Size.
@param fptrDef - File pointer to DEF file
@internalComponent
@released
*/
int DefFile::GetFileSize(FILE *fptrDef)
{
int fileSize,status;
status=fseek(fptrDef, 0, SEEK_END);
if(status!=0)
{
throw FileError(FILEREADERROR,iFileName);
}
fileSize=ftell(fptrDef);
rewind(fptrDef);
return fileSize;
}
/**
Function to Open File and read it in memory.
@param defFile - DEF File name
@internalComponent
@released
*/
char* DefFile::OpenDefFile(char * defFile)
{
int fileSize;
char *defFileEntries;
FILE *fptrDef;
iFileName=defFile;
if((fptrDef=fopen(defFile,"rb"))==NULL)
{
throw FileError(FILEOPENERROR,defFile);
}
fileSize=GetFileSize(fptrDef);
if((defFileEntries= new char[fileSize+2]) ==NULL)
{
throw MemoryAllocationError(MEMORYALLOCATIONERROR,defFile);
}
//Getting whole file in memory
if(!fread(defFileEntries, fileSize, 1, fptrDef))
{
throw FileError(FILEREADERROR,defFile);
}
//Adding ENTER at end
*(defFileEntries+fileSize)='\n';
//Adding '\0' at end
*(defFileEntries+fileSize+1)='\0';
fclose(fptrDef);
return defFileEntries;
}
/**
Function to Parse Def File which has been read in buffer.
@param defFileEntries - pointer to def file entries which has been read in buffer
@internalComponent
@released
*/
void DefFile::ParseDefFile(char *defFileEntries)
{
iSymbolList = new SymbolList;
int ordinalNo = 0;
int symbolType=SymbolTypeCode;
int PreviousOrdinal=0;
char MultiLineStatement[1024]="";
bool NAMEorLIBRARYallowed=true;
int LineNum = 0;
bool isComment;
char *lineToken;
int aLineLength = 0, width = 0;
unsigned i;
char *ptrEntry,*ptrEntryType;
char entryType[256];
bool entryFlag;
lineToken=strtok(defFileEntries,"\n");
while(lineToken != NULL)
{
symbolType=SymbolTypeCode;
isComment=false;
entryType[0]='\0';
aLineLength = strlen(lineToken);
LineNum++;
if (lineToken == NULL || lineToken[0]==13)
{
lineToken=strtok(NULL,"\n");
continue;
}
// comment lines
if (lineToken[0] == ';')
{
lineToken=strtok(NULL,"\n");
continue;
}
ptrEntry=lineToken;
if((!strstr(lineToken, "NONAME") && ((ptrEntryType=strstr(lineToken, "NAME")) != NULL)) ||
((ptrEntryType=strstr(lineToken, "EXPORTS")) != NULL) ||
((ptrEntryType=strstr(lineToken, "IMPORTS")) != NULL) ||
((ptrEntryType=strstr(lineToken, "SECTIONS")) != NULL) ||
((ptrEntryType=strstr(lineToken, "LIBRARY")) != NULL) ||
((ptrEntryType=strstr(lineToken, "DESCRIPTION")) != NULL)||
((ptrEntryType=strstr(lineToken, "STACKSIZE")) != NULL)||
((ptrEntryType=strstr(lineToken, "VERSION")) != NULL)
)
{
entryFlag=true;
for(i=0; ptrEntry!=ptrEntryType; i++,ptrEntry++)
{
switch(lineToken[i])
{
case ' ':
case '\t':
continue;
default:
entryFlag=false;
break;
}
if(entryFlag==false)
break;
}
if(entryFlag==false && !strcmp(MultiLineStatement,""))
{
throw DEFFileError(UNRECOGNIZEDTOKEN,iFileName,LineNum,lineToken);
}
if(entryFlag==true)
{
switch(ptrEntryType[0])
{
case 'E':
case 'I':
case 'L':
case 'V':
width=7;
break;
case 'S':
if(ptrEntryType[1]=='E')
width=8;
else
width=9;
break;
case 'N':
width=4;
break;
case 'D':
width=11;
break;
}
}
if(entryFlag==true)
{
for(i=i+width; i<strlen(lineToken); i++)
{
switch(lineToken[i])
{
case ' ':
case '\t':
continue;
case '\r':
case '\0':
break;
default:
entryFlag=false;
break;
}
if(entryFlag==false)
break;
}
}
if(entryFlag==false && !strcmp(MultiLineStatement,""))
{
throw DEFFileError(UNRECOGNIZEDTOKEN,iFileName,LineNum,lineToken+i);
}
if(entryFlag==true)
{
strncpy(entryType, ptrEntryType, width);
entryType[width]='\0';
switch(ptrEntryType[0])
{
case 'E': // check for multi-line sections starting
strcpy(MultiLineStatement, STRUPR(entryType)); // Uppercase token
NAMEorLIBRARYallowed = false;
lineToken = strtok(NULL, "\n" ); // Get the next line
continue;
case 'N':
break;
case 'L':
break;
case 'D':
break;
case 'S':
case 'V':
if(entryType[1]!='E')
{
// set MULTI-LINE statement to OFF
strcpy(MultiLineStatement, STRUPR(entryType)); // Uppercase token
// check single-line statements are specified correctly
// check NAME or LIBRARY statements aren't supplied incorrectly
if (!strcmp(entryType, "NAME") ||
!strcmp(entryType, "LIBRARY")
)
{
if (NAMEorLIBRARYallowed == false)
{
throw DEFFileError(NAMELIBRARYNOTCORRECT,iFileName,LineNum,lineToken);
}
lineToken=strtok(NULL,"\n");
continue;
}
NAMEorLIBRARYallowed = false;
lineToken=strtok(NULL,"\n");
continue;
}
continue;
case 'I':
strcpy(MultiLineStatement, STRUPR(entryType)); // Uppercase token
lineToken = strtok(NULL, "\n" ); // Get the next line
continue;
}
}
}
else
{
if (!strcmp(MultiLineStatement,""))
{
throw DEFFileError(EXPORTSEXPECTED,iFileName,LineNum,lineToken);
}
}
// Get Export entries
if (!strcmp(MultiLineStatement,"EXPORTS"))
{
Symbol aSymbol(NULL, SymbolTypeCode);
if( Tokenize(lineToken, LineNum, aSymbol) )
{
Symbol *newSymbolEntry = new Symbol(aSymbol);
iSymbolList->push_back(newSymbolEntry);
ordinalNo = aSymbol.OrdNum();
//Check for ordinal sequence
if (ordinalNo != PreviousOrdinal+1)
{
throw DEFFileError(ORDINALSEQUENCEERROR,iFileName,LineNum,(char*)aSymbol.SymbolName());
}
PreviousOrdinal = ordinalNo;
}
lineToken=strtok(NULL,"\n");
continue;
}
else if(strcmp(MultiLineStatement,"")!=0)//For entry other than exports
lineToken = strtok(NULL, "\n" ); // Get the next line
}//End of while
}
/**
This Function calls LineToken's Tokenize function.
@param aTokens - Input string at the current line number
@param aLineNum - Current line number
@param aSymbol - Symbol to be populated while parsing the line.
Return value - It returns true if a valid def file entry is found.
@internalComponent
@released
*/
bool DefFile::Tokenize(char* aTokens, int aLineNum, Symbol& aSymbol)
{
/*
* Pattern to match is:
* START\s*(\S+)\s+@\s*(d+)\s*(NONAME)?\s*(R3UNUSED)?\s*(ABSENT)?\s*(;\s*(.*))END
*/
LineToken aLine(iFileName, aLineNum, aTokens, &aSymbol);
return aLine.Tokenize();
}
char * DefFilePatterns[] =
{
"NONAME",//index 0
"DATA",
"R3UNUSED",
"ABSENT"
};
#define DEF_NONAME 0
#define DEF_DATA 1
#define DEF_R3UNUSED 2
#define DEF_ABSENT 3
/**
This constructor creates an instance of LineToken class.
@param aFileName - Def File Name.
@param aLineNum - Current line number
@param aLn - Input string at the current line number
@param aSym - Symbol to be populated while parsing the line.
@internalComponent
@released
*/
LineToken::LineToken(char* aFileName, int aLineNum, char *aLn, Symbol* aSym) : \
iLine(aLn) , iSymbol(aSym) , iOffset(0), iState(EInitState),iFileName(aFileName), iLineNum(aLineNum)
{
}
/**
This function tokenizes the line and populates a symbol entry
if there is one.
Return Value - True, if the current line has a valid def entry.
@internalComponent
@released
*/
bool LineToken::Tokenize()
{
while (1)
{
switch( iState )
{
case EFinalState:
return true;
case EInitState:
if( *(iLine + iOffset) == '\0' ||
*(iLine + iOffset) == '\r' ||
*(iLine + iOffset) == '\n')
{
/*
* Skip empty lines.
*/
return false;
}
else
{
NextToken();
}
break;
default:
NextToken();
break;
}
}
return false;
}
/**
This function parses a line of the def file based on the current
state it is in.
@internalComponent
@released
*/
void LineToken::NextToken()
{
int aCurrentPos = 0;
char *aSymbolName;
switch( iState )
{
case EInitState:
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
if(IsWord(iLine + iOffset, aCurrentPos))
{
SetState(ESymbolName);
}
break;
case ESymbolName:
{
// Get the length of the symbol
IsWord(iLine + iOffset, aCurrentPos);
char *cmt = strchr(iLine + iOffset, ';');
char *aExport = strchr(iLine + iOffset, '=');
if( aExport && (!cmt || (aExport < cmt)) )
{
int aExportPos = aExport - (iLine+ iOffset);
//Check if alias name is also supplied, they should be separated
// by whitespace, i.e., ExportName=SymbolName is valid while,
// ExportName =SymbolName is invalid.
if( aExportPos > aCurrentPos)
{
char *aToken = (iLine + iOffset + aCurrentPos);
throw DEFFileError(UNRECOGNIZEDTOKEN, iFileName, iLineNum, aToken);
}
char* aExportName = new char[aExportPos+1];
strncpy(aExportName, iLine+iOffset, aExportPos);
aExportName[aExportPos] = '\0';
aSymbolName = new char[aCurrentPos - aExportPos + 1];
strncpy(aSymbolName, aExport +1, (aCurrentPos - aExportPos));
aSymbolName[(aCurrentPos - aExportPos-1)] = '\0';
iSymbol->ExportName(aExportName);
}
else
{
aSymbolName = new char[aCurrentPos+1];
strncpy(aSymbolName, iLine+ iOffset, aCurrentPos);
aSymbolName[aCurrentPos] = '\0';
}
iSymbol->SymbolName(aSymbolName);
IncrOffset(aCurrentPos);
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
if(*(iLine+iOffset) == '@')
{
SetState(EAtSymbol);
IncrOffset(1);
}
else
{
/*
* The first non-whitespace entry in a line is assumed to be the
* symbol name and a symbol name might also have a '@' char. Hence
* there MUST be a whitespace between symbol name and '@'.
*/
throw DEFFileError(ATRATEMISSING,iFileName,iLineNum,(iLine+iOffset));
}
}
break;
case EAtSymbol:
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
SetState(EOrdinal);
break;
case EOrdinal:
{
if(!IsDigit(iLine+iOffset, aCurrentPos ) )
{
throw DEFFileError(ORDINALNOTANUMBER, iFileName, iLineNum, (iLine+iOffset));
}
char aTmp[32];
strncpy(aTmp, iLine+iOffset, aCurrentPos);
aTmp[aCurrentPos] = '\0';
int aOrdinal = atoi(aTmp);
iSymbol->SetOrdinal(aOrdinal);
IncrOffset(aCurrentPos);
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
SetState(EOptionals);
}
break;
case EOptionals:
{
int aPrevPatternIndex, aPatternIdx = 0;
aPrevPatternIndex = -1;
while (*(iLine + iOffset) != '\n' || *(iLine + iOffset) != '\r')
{
if(IsPattern(iLine+iOffset, aCurrentPos, aPatternIdx) )
{
switch(aPatternIdx)
{
case DEF_NONAME:
break;
case DEF_DATA:
iSymbol->CodeDataType(SymbolTypeData);
IncrOffset(aCurrentPos);
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
if(IsDigit(iLine+iOffset, aCurrentPos ) )
{
char aSymSz[16];
strncpy(aSymSz, (iLine + iOffset), aCurrentPos);
aSymSz[aCurrentPos] = '\0';
iSymbol->SetSymbolSize(atoi(aSymSz));
}
break;
case DEF_R3UNUSED:
iSymbol->R3Unused(true);
break;
case DEF_ABSENT:
iSymbol->SetAbsent(true);
break;
default:
break;
}
/*
* NONAME , DATA, R3UNUSED and ABSENT, all the 3 are optional. But, if more than
* one of them appear, they MUST appear in that order.
* Else, it is not accepted.
*/
if( aPrevPatternIndex >= aPatternIdx)
{
throw DEFFileError(UNRECOGNIZEDTOKEN, iFileName, iLineNum,(iLine + iOffset));
}
aPrevPatternIndex = aPatternIdx;
IncrOffset(aCurrentPos);
if(IsWhiteSpace((iLine + iOffset), aCurrentPos))
{
IncrOffset(aCurrentPos);
}
}
else
{
if( *(iLine + iOffset) == ';' )
{
SetState(EComment);
IncrOffset(1);
return;
}
else if( *(iLine + iOffset) == '\0' ||
*(iLine + iOffset) == '\r' ||
*(iLine + iOffset) == '\n')
{
SetState(EFinalState);
return;
}
else
{
throw DEFFileError(UNRECOGNIZEDTOKEN, iFileName, iLineNum,(iLine + iOffset));
}
}
}
}
break;
case EComment:
{
if(IsWhiteSpace(iLine + iOffset, aCurrentPos))
{
IncrOffset(aCurrentPos);
}
int aLen = strlen(iLine + iOffset);
if( *(iLine + iOffset + aLen - 1 ) == '\n' || *(iLine + iOffset + aLen - 1 ) == '\r')
aLen -=1;
char * aComment = new char[ aLen + 1];
strncpy( aComment, iLine + iOffset, aLen);
aComment[aLen] = '\0';
IncrOffset(aLen);
iSymbol->Comment(aComment);
SetState(EFinalState);
}
break;
case EFinalState:
return;
default:
break;
}
}
/**
This function returns true if the string starts with one
of the fixed patterns.
It also updates the length and index of this pattern.
@param aChar - Line Token
@param aTill - Length of the pattern
@param aTill - Index of the pattern
Return Value - True, if the string starts with one of the patterns.
@internalComponent
@released
*/
bool LineToken::IsPattern(char* aStr, int& aTill, int& aIndex)
{
int pos = 0;
int aLength;
int size = sizeof(DefFilePatterns)/sizeof(char*);
while(size > pos)
{
aLength = strlen(DefFilePatterns[pos]);
if(!strncmp(aStr, DefFilePatterns[pos], aLength))
{
aTill = aLength;
aIndex = pos;
return true;
}
pos++;
}
return false;
}
/**
This function returns true if the string starts with digits.
It also updates the length of this digit string.
@param aChar - Line Token
@param aTill - Length of the digit string
Return Value - True, if the string starts with digit(s)
@internalComponent
@released
*/
bool LineToken::IsDigit(char *aChar, int &aTill)
{
int pos = 0;
if( aChar[pos] - '0' >= 0 && aChar[pos] - '0' <= 9)
{
pos++;
while(aChar[pos] - '0' >= 0 && aChar[pos] - '0' <= 9)
{
pos++;
}
aTill = pos;
return true;
}
else
{
return false;
}
}
/**
This function returns true if the string starts with white space.
It also updates the length of this white string!
@param aStr - Line Token
@param aTill - Length of the white string
Return Value - True, if the string starts with whitespace
@internalComponent
@released
*/
bool LineToken::IsWhiteSpace(char *aStr, int &aTill)
{
int pos = 0;
switch( aStr[pos] )
{
case ' ':
case '\t':
break;
default:
return false;
}
pos++;
while( aStr[pos])
{
switch(aStr[pos])
{
case ' ':
case '\t':
pos++;
break;
default:
aTill = pos;
return true;
}
}
aTill = pos;
return true;
}
/**
This function returns true if the string starts with non-whitespace.
It also updates the length of this word.
@param aStr - Line Token
@param aTill - Length of the word
Return Value - True, if the string starts with non-whitespace chars.
It also updates the length of the word.
@internalComponent
@released
*/
bool LineToken::IsWord(char *aStr, int &aTill)
{
int pos = 0;
switch( aStr[pos] )
{
case '\0':
case ' ':
case '\t':
case '\r':
case '\n':
return false;
default:
break;
}
pos++;
while( aStr[pos])
{
switch(aStr[pos])
{
case ' ':
case '\t':
case '\r':
case '\n':
aTill = pos;
return true;
default:
pos++;
break;
}
}
aTill = pos;
return true;
}
/**
This function increments the current offset.
@param aOff - increment by this value
@internalComponent
@released
*/
void LineToken::IncrOffset(int aOff)
{
iOffset += aOff;
}
/**
This function sets the state of the tokenizer that is parsing
the line.
@param aState - next state
@internalComponent
@released
*/
void LineToken::SetState(DefStates aState)
{
iState = aState;
}
/**
Function to Read def file and get the internal representation in structure.
@param defFile - DEF File name
@internalComponent
@released
*/
SymbolList* DefFile::ReadDefFile(char *defFile)
{
char *defFileEntries;
defFileEntries=OpenDefFile(defFile);
ParseDefFile(defFileEntries);
delete [] defFileEntries;//Free the memory which was required to read def file
return iSymbolList;
}
/**
Function to get the internal representation of Def File.
@param defFile - DEF File name
@internalComponent
@released
*/
SymbolList* DefFile::GetSymbolEntryList(char *defFile)
{
if(iSymbolList)
{
return iSymbolList;
}
else
{
iSymbolList=ReadDefFile(defFile);
return iSymbolList;
}
}
/**
Function to write DEF file from symbol entry List.
@param fileName - Def file name
@param newSymbolList - pointer to SymbolList which we get as an input for writing in DEF File
@internalComponent
@released
*/
void DefFile::WriteDefFile(char *fileName, SymbolList * newSymbolList)
{
char ordinal[6];
int newDefEntry=0;
FILE *fptr;
if((fptr=fopen(fileName,"wb"))==NULL)
{
throw FileError(FILEOPENERROR,fileName);
}
else
{
SymbolList::iterator aItr = newSymbolList->begin();
SymbolList::iterator last = newSymbolList->end();
Symbol *aSym;
fputs("EXPORTS",fptr);
fputs("\r\n",fptr);
while( aItr != last)
{
aSym = *aItr;
//Do not write now if its a new entry
if(aSym->GetSymbolStatus()==New)
{
newDefEntry=1;
aItr++;
continue;
}
//Make it comment if its missing def entry
if(aSym->GetSymbolStatus()==Missing)
fputs("; MISSING:",fptr);
fputs("\t",fptr);
if((aSym->ExportName()) && strcmp(aSym->SymbolName(),aSym->ExportName())!=0)
{
fputs(aSym->ExportName(),fptr);
fputs("=",fptr);
}
fputs(aSym->SymbolName(),fptr);
fputs(" @ ",fptr);
sprintf(ordinal,"%d",aSym->OrdNum());
fputs(ordinal,fptr);
fputs(" NONAME",fptr);
if(aSym->CodeDataType()==SymbolTypeData) {
fputs(" DATA",fptr);
fputs(" ",fptr);
char aSymSize[16];
sprintf(aSymSize, "%d", aSym->SymbolSize());
fputs(aSymSize,fptr);
}
if(aSym->R3unused())
fputs(" R3UNUSED",fptr);
if(aSym->Absent())
fputs(" ABSENT",fptr);
if(aSym->Comment()!=NULL)
{
fputs(" ; ",fptr);
fputs(aSym->Comment(),fptr);
}
fputs("\r\n",fptr);
aItr++;
}
//This is for writing new def entry in DEF File
if(newDefEntry)
{
fputs("; NEW:",fptr);
fputs("\r\n",fptr);
aItr = newSymbolList->begin();
last = newSymbolList->end();
while( aItr != last)
{
aSym = *aItr;
if(aSym->GetSymbolStatus()!=New)
{
aItr++;
continue;
}
fputs("\t",fptr);
if((aSym->ExportName()) && strcmp(aSym->SymbolName(),aSym->ExportName())!=0)
{
fputs(aSym->ExportName(),fptr);
fputs("=",fptr);
}
fputs(aSym->SymbolName(),fptr);
fputs(" @ ",fptr);
sprintf(ordinal,"%d",aSym->OrdNum());
fputs(ordinal,fptr);
fputs(" NONAME",fptr);
if(aSym->CodeDataType()==SymbolTypeData) {
fputs(" DATA",fptr);
fputs(" ",fptr);
char aSymSize[16];
sprintf(aSymSize, "%d", aSym->SymbolSize());
fputs(aSymSize,fptr);
}
if(aSym->R3unused())
fputs(" R3UNUSED",fptr);
if(aSym->Absent())
fputs(" ABSENT",fptr);
if(aSym->Comment()!=NULL)
{
if(aSym->CodeDataType()!=SymbolTypeCode &&
aSym->CodeDataType()!=SymbolTypeData)
{
fputs(" ; ",fptr);
fputs(aSym->Comment(),fptr);
}
else
{
fputs(" ",fptr);
fputs(aSym->Comment(),fptr);
}
}
fputs("\r\n",fptr);
aItr++;
}
}
fputs("\r\n",fptr);
fclose(fptr);
}
}
|
[
"[email protected]",
"none@none"
] |
[
[
[
1,
465
],
[
467,
467
],
[
469,
469
],
[
471,
472
],
[
476,
480
],
[
487,
1002
]
],
[
[
466,
466
],
[
468,
468
],
[
470,
470
],
[
473,
475
],
[
481,
486
]
]
] |
33fb9c10929ce06ad88a21f2f59e29d7c5143939
|
a2ba072a87ab830f5343022ed11b4ac365f58ef0
|
/ urt-bumpy-q3map2 --username [email protected]/libs/generic/object.cpp
|
57fd76ed8cfb283325e49d1738d4ad6f7424382c
|
[] |
no_license
|
Garey27/urt-bumpy-q3map2
|
7d0849fc8eb333d9007213b641138e8517aa092a
|
fcc567a04facada74f60306c01e68f410cb5a111
|
refs/heads/master
| 2021-01-10T17:24:51.991794 | 2010-06-22T13:19:24 | 2010-06-22T13:19:24 | 43,057,943 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 241 |
cpp
|
#include "object.h"
namespace
{
class Blah
{
int i;
public:
Blah()
{
i = 3;
}
};
void Test()
{
char storage[sizeof(Blah)];
constructor(*reinterpret_cast<Blah*>(storage));
}
}
|
[
"[email protected]"
] |
[
[
[
1,
21
]
]
] |
3a79e8389ffa829a1380ee3215d07ff9a42bb700
|
0033659a033b4afac9b93c0ac80b8918a5ff9779
|
/game/shared/so2/weapon_sobase.cpp
|
cf5c6f1f78266ba1dcf881529c7d1d8d74da863d
|
[] |
no_license
|
jonnyboy0719/situation-outbreak-two
|
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
|
50037e27e738ff78115faea84e235f865c61a68f
|
refs/heads/master
| 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 22,588 |
cpp
|
#include "cbase.h"
#include "weapon_sobase.h"
#include "hl2mp_weapon_parse.h"
#include "npcevent.h"
#include "in_buttons.h"
#ifdef CLIENT_DLL
#include "c_so_player.h"
#else
#include "so_player.h"
// Weapon respawn fix
// http://developer.valvesoftware.com/wiki/Weapon_Respawn_Fix
#include "vphysics/constraints.h"
// Fix CS:S muzzleflashes
// http://developer.valvesoftware.com/wiki/Muzzle_Flash_(CSS_Style)
// Not mentioned in the tutorial, although it appears necessary to get other players' muzzleflashes to work
// Pieced together from various existing DoMuzzleFlash functions and modified from there
#include "te_effect_dispatch.h"
#endif
// Weapon reorigin system
// http://developer.valvesoftware.com/wiki/Adding_Ironsights
// Modified a bit from the wiki version considering our system's purpose
//forward declarations of callbacks used by viewmodel_adjust_enable and viewmodel_adjust_fov
void vm_adjust_enable_callback( IConVar *pConVar, char const *pOldString, float flOldValue );
void vm_adjust_fov_callback( IConVar *pConVar, const char *pOldString, float flOldValue );
ConVar viewmodel_adjust_forward( "viewmodel_adjust_forward", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_right( "viewmodel_adjust_right", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_up( "viewmodel_adjust_up", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_pitch( "viewmodel_adjust_pitch", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_yaw( "viewmodel_adjust_yaw", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_roll( "viewmodel_adjust_roll", "0", FCVAR_REPLICATED );
ConVar viewmodel_adjust_fov( "viewmodel_adjust_fov", "0", FCVAR_REPLICATED, "Note: this feature is not available during any kind of zoom", vm_adjust_fov_callback );
ConVar viewmodel_adjust_enabled( "viewmodel_adjust_enabled", "0", FCVAR_REPLICATED | FCVAR_CHEAT, "enabled viewmodel adjusting", vm_adjust_enable_callback );
IMPLEMENT_NETWORKCLASS_ALIASED( WeaponSOBase, DT_WeaponSOBase )
BEGIN_NETWORK_TABLE( CWeaponSOBase, DT_WeaponSOBase )
#ifdef CLIENT_DLL
// Weapon scope system
RecvPropBool( RECVINFO( m_bIsScoped ) ),
#else
// Weapon scope system
SendPropBool( SENDINFO( m_bIsScoped ) ),
#endif
END_NETWORK_TABLE()
#ifdef CLIENT_DLL
BEGIN_PREDICTION_DATA( CWeaponSOBase )
// Weapon scope system
DEFINE_PRED_FIELD( m_bIsScoped, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), // I believe the client may want this predicted for actually displaying the scope
END_PREDICTION_DATA()
#endif
// Add support for CS:S player animations
// I know there's a better way to replace these animations, but I'm extremely lazy
acttable_t CWeaponSOBase::m_acttable[] =
{
{ ACT_MP_STAND_IDLE, ACT_IDLE, false },
{ ACT_MP_CROUCH_IDLE, ACT_CROUCHIDLE, false },
{ ACT_MP_RUN, ACT_RUN, false },
{ ACT_MP_WALK, ACT_WALK, false },
{ ACT_MP_CROUCHWALK, ACT_RUN_CROUCH, false },
{ ACT_MP_JUMP, ACT_HOP, false },
};
IMPLEMENT_ACTTABLE( CWeaponSOBase );
CWeaponSOBase::CWeaponSOBase()
{
// Weapon scope system
m_bIsScoped = false;
}
void CWeaponSOBase::Spawn( void )
{
BaseClass::Spawn();
// Make weapons that are on the ground blink so that they are easier for players to see
AddEffects( EF_ITEM_BLINK );
}
bool CWeaponSOBase::Holster( CBaseCombatWeapon *pSwitchingTo )
{
if ( BaseClass::Holster(pSwitchingTo) )
{
// Weapon scope system
if ( HasScope() )
ExitScope( false );
return true;
}
return false;
}
bool CWeaponSOBase::Deploy( void )
{
if ( BaseClass::Deploy() )
{
// Weapon scope system
if ( HasScope() )
ExitScope();
return true;
}
return false;
}
// Taken and modified from CWeaponHL2MPBase::Reload
//Tony; override for animation purposes.
bool CWeaponSOBase::Reload( void )
{
bool fRet = DefaultReload( GetMaxClip1(), GetMaxClip2(), ACT_VM_RELOAD );
if ( fRet )
{
// Weapon scope system
// Unscope while reloading
if ( HasScope() )
ExitScope();
ToHL2MPPlayer( GetOwner() )->DoAnimationEvent( PLAYERANIMEVENT_RELOAD );
}
return fRet;
}
void CWeaponSOBase::ItemPostFrame( void )
{
// Weapon scope system
// We're not allowed to scope right now yet we are scoped, so unscope right away!
if ( !CanScope() && m_bIsScoped )
ExitScope();
CSO_Player *pOwner = ToSOPlayer( GetOwner() );
if ( !pOwner )
return;
// Do not allow players to fire weapons on ladders
// http://articles.thewavelength.net/724/
// Do not allow players to fire weapons while sprinting
if ( pOwner->GetHolsteredWeapon() == this )
return;
BaseClass::ItemPostFrame();
}
// The following is taken and modified from CBaseCombatWeapon::PrimaryAttack
void CWeaponSOBase::PrimaryAttack( void )
{
// Weapon scope system
int preShotAmmo = m_iClip1;
// If my clip is empty (and I use clips) start reload
if ( UsesClipsForAmmo1() && !m_iClip1 )
{
Reload();
return;
}
// Only the player fires this way so we can cast
CSO_Player *pPlayer = ToSOPlayer( GetOwner() );
if ( !pPlayer )
return;
pPlayer->DoMuzzleFlash();
SendWeaponAnim( GetPrimaryAttackActivity() );
// player "shoot" animation
pPlayer->SetAnimation( PLAYER_ATTACK1 );
ToSOPlayer( pPlayer )->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_PRIMARY );
FireBulletsInfo_t info;
info.m_vecSrc = pPlayer->Weapon_ShootPosition();
info.m_vecDirShooting = pPlayer->CBasePlayer::GetAutoaimVector( AUTOAIM_SCALE_DEFAULT );
// To make the firing framerate independent, we may have to fire more than one bullet here on low-framerate systems,
// especially if the weapon we're firing has a really fast rate of fire.
info.m_iShots = 0;
float fireRate = GetFireRate();
while ( m_flNextPrimaryAttack <= gpGlobals->curtime )
{
// MUST call sound before removing a round from the clip of a CMachineGun
WeaponSound( SINGLE, m_flNextPrimaryAttack );
m_flNextPrimaryAttack = m_flNextPrimaryAttack + fireRate;
info.m_iShots++;
if ( !fireRate )
break;
}
// Make sure we don't fire more than the amount in the clip
if ( UsesClipsForAmmo1() )
{
info.m_iShots = min( info.m_iShots, m_iClip1 );
m_iClip1 -= info.m_iShots;
}
else
{
info.m_iShots = min( info.m_iShots, pPlayer->GetAmmoCount(m_iPrimaryAmmoType) );
pPlayer->RemoveAmmo( info.m_iShots, m_iPrimaryAmmoType );
}
info.m_flDistance = MAX_TRACE_LENGTH;
info.m_iAmmoType = m_iPrimaryAmmoType;
// Weapon scope system
// Other players should see someone's tracers regardless of whether or not that individual's weapon is scoped, so let's try to do that here...
// ^^^ Doesn't work, probably due to lag compensation or something like that...oh well... ^^^
//#ifdef CLIENT_DLL
// Don't show tracers for weapons that are scoped, which aren't visible (that'd be dumb as the tracers would seemingly come from nowhere)
if ( m_bIsScoped )
info.m_iTracerFreq = 0;
else
info.m_iTracerFreq = 2; // 50% (?)
/*#else
info.m_iTracerFreq = 2; // 50% (?)
#endif*/
#if !defined( CLIENT_DLL )
// Fire the bullets
info.m_vecSpread = pPlayer->GetAttackSpread( this );
#else
//!!!HACKHACK - what does the client want this function for?
info.m_vecSpread = GetActiveWeapon()->GetBulletSpread();
#endif // CLIENT_DLL
pPlayer->FireBullets( info );
if ( !m_iClip1 && (pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0) )
{
// HEV suit - indicate out of ammo condition
pPlayer->SetSuitUpdate( "!HEV_AMO0", FALSE, 0 );
}
//Add our view kick in
AddViewKick();
// Weapon scope system
if ( HasScope() && UnscopeAfterShot() && (preShotAmmo > 0) )
ExitScope(); // done after actually shooting because it is logical and should prevent any unnecessary accuracy changes
}
// Weapon scope system
bool CWeaponSOBase::CanScope( void )
{
// If this weapon doesn't have a scope, how are we expected to use it?
// We really shouldn't have to check for this by the time this function is called, but just in case...
if ( !HasScope() )
return false;
// If this weapon requires the player to unscope after firing, wait until we're allowed to fire again before the scope can be used again
if ( UnscopeAfterShot() && (gpGlobals->curtime < m_flNextPrimaryAttack) )
return false;
CSO_Player *pOwner = ToSOPlayer( GetOwner() );
if ( !pOwner )
return false;
// Do not allow players to fire weapons on ladders
// http://articles.thewavelength.net/724/
// Do not allow players to fire weapons while sprinting
// We should not be allowed to scope while our weapon is holstered (this takes care of conditions like climbing a ladder and sprinting)
if ( pOwner->GetHolsteredWeapon() == this )
return false;
// Scoping while not on the ground is not allowed, because that'd just be silly
if ( !(pOwner->GetFlags() & FL_ONGROUND) )
return false;
return true;
}
// Weapon scope system
void CWeaponSOBase::EnterScope( void )
{
if ( !CanScope() )
return; // don't scope if we're not allowed to right now!
CSO_Player *pOwner = ToSOPlayer( GetOwner() );
if ( !pOwner )
return;
// Only scope and stuff if we have an owner
m_bIsScoped = true;
pOwner->SetFOV( pOwner, GetScopeFOV(), 0.1f ); // zoom
SetWeaponVisible( false ); // hide the view model
m_flNextSecondaryAttack = gpGlobals->curtime + 0.25f; // make a bit of a delay between zooming/unzooming to prevent spam and possibly some bugs
}
// Weapon scope system
void CWeaponSOBase::ExitScope( bool unhideWeapon )
{
m_bIsScoped = false; // unscope regardless of whether or not we have an owner (should prevent some bugs)
CSO_Player *pOwner = ToSOPlayer( GetOwner() );
if ( !pOwner )
return;
pOwner->SetFOV( pOwner, pOwner->GetDefaultFOV(), 0.1f ); // unzoom
if ( unhideWeapon ) // there are some situations where we may not want to do this to prevent interfering with other systems
SetWeaponVisible( true ); // show the view model again
m_flNextSecondaryAttack = gpGlobals->curtime + 0.25f; // make a bit of a delay between zooming/unzooming to prevent spam and possibly some bugs
}
void CWeaponSOBase::SecondaryAttack( void )
{
// Weapon scope system
// Overrides secondary attack of weapons with scopes
// This may not be desired, but that's just how it works, so adjust all scoped weapons accordingly and keep this in mind!
if ( HasScope() )
{
// Toggle scope
if ( m_bIsScoped )
ExitScope();
else
EnterScope();
}
else
{
BaseClass::SecondaryAttack();
}
}
// Weapon accuracy system
float CWeaponSOBase::GetAccuracyModifier()
{
float weaponAccuracy = 1.0f; // by default, don't make any alterations
CSO_Player *pPlayer = ToSOPlayer( GetOwner() );
if ( pPlayer )
{
if( !fabs(pPlayer->GetAbsVelocity().x) && !fabs(pPlayer->GetAbsVelocity().y) ) // player isn't moving
weaponAccuracy *= 0.75f;
else if( !!( pPlayer->GetFlags() & FL_DUCKING ) ) // player is ducking
weaponAccuracy *= 0.80f;
else if( pPlayer->IsWalking() ) // player is walking
weaponAccuracy *= 0.85f;
// Weapon scope system
else if ( m_bIsScoped ) // player's weapon is scoped (snipers override this because they are super-accurate when scoped)
weaponAccuracy *= 0.90f;
}
return weaponAccuracy;
}
// Taken and modified from CBaseCombatWeapon::SetWeaponVisible
void CWeaponSOBase::SetWeaponVisible( bool visible )
{
CBaseViewModel *vm = NULL;
CSO_Player *pOwner = ToSOPlayer( GetOwner() );
if ( pOwner )
vm = pOwner->GetViewModel( m_nViewModelIndex );
if ( visible )
{
// Fix a weapon disappearing bug
// Only having the client do this should fix an issue that makes players' weapons disappear to other players
// In a majority of cases, this is not desired (I actually can't think of a single one where it would be)
#ifdef CLIENT_DLL
RemoveEffects( EF_NODRAW );
#endif
if ( vm )
vm->RemoveEffects( EF_NODRAW );
}
else
{
// Fix a weapon disappearing bug
// Only having the client do this should fix an issue that makes players' weapons disappear to other players
// In a majority of cases, this is not desired (I actually can't think of a single one where it would be)
#ifdef CLIENT_DLL
AddEffects( EF_NODRAW );
#endif
if ( vm )
vm->AddEffects( EF_NODRAW );
}
}
#ifndef CLIENT_DLL
// Fix CS:S muzzleflashes
// http://developer.valvesoftware.com/wiki/Muzzle_Flash_(CSS_Style)
// Not mentioned in the tutorial, although it appears necessary to get other players' muzzleflashes to work
void CWeaponSOBase::DoMuzzleFlash( void )
{
// This might seem like a simple solution to the whole muzzleflash issue, but it took me a whole day to figure out!
// Looks like it works though, so that's good! Well, all's well that ends well...
// ...and another day lost to programming. 'Tis the life. =P
if ( !ShouldDrawMuzzleFlash() )
return; // this weapon shouldn't have a muzzleflash drawn, so don't
int iAttachment = 1;
// Fix dual Beretta 92s muzzleflash issue
if ( ShouldUseAttachment2ForMuzzleFlashes() )
iAttachment = 2;
CEffectData data;
data.m_nAttachmentIndex = iAttachment;
data.m_nEntIndex = entindex();
DispatchEffect( "MuzzleFlash", data );
}
#endif
// Add weapon bob
#if defined( CLIENT_DLL )
#define HL2_BOB_CYCLE_MIN 0.5f // HL2 default is 1.0f
#define HL2_BOB_CYCLE_MAX 0.225f // HL2 default 0.45f
#define HL2_BOB 0.002f
#define HL2_BOB_UP 0.5f
extern float g_lateralBob;
extern float g_verticalBob;
static ConVar cl_bobcycle( "cl_bobcycle","0.8" );
static ConVar cl_bob( "cl_bob","0.002" );
static ConVar cl_bobup( "cl_bobup","0.5" );
// Register these cvars if needed for easy tweaking
static ConVar v_iyaw_cycle( "v_iyaw_cycle", "2", FCVAR_REPLICATED | FCVAR_CHEAT );
static ConVar v_iroll_cycle( "v_iroll_cycle", "0.5", FCVAR_REPLICATED | FCVAR_CHEAT );
static ConVar v_ipitch_cycle( "v_ipitch_cycle", "1", FCVAR_REPLICATED | FCVAR_CHEAT );
static ConVar v_iyaw_level( "v_iyaw_level", "0.3", FCVAR_REPLICATED | FCVAR_CHEAT );
static ConVar v_iroll_level( "v_iroll_level", "0.1", FCVAR_REPLICATED | FCVAR_CHEAT );
static ConVar v_ipitch_level( "v_ipitch_level", "0.3", FCVAR_REPLICATED | FCVAR_CHEAT );
//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float CWeaponSOBase::CalcViewmodelBob( void )
{
static float bobtime;
static float lastbobtime;
float cycle;
CSO_Player *player = ToSOPlayer( GetOwner() );
//Assert( player );
//NOTENOTE: For now, let this cycle continue when in the air, because it snaps badly without it
if ( ( !gpGlobals->frametime ) || ( player == NULL ) )
{
//NOTENOTE: We don't use this return value in our case (need to restructure the calculation function setup!)
return 0.0f;// just use old value
}
//Find the speed of the player
float speed = player->GetLocalVelocity().Length2D();
//FIXME: This maximum speed value must come from the server.
// MaxSpeed() is not sufficient for dealing with sprinting - jdw
speed = clamp( speed, -320, 320 );
float bob_offset = RemapVal( speed, 0, 320, 0.0f, 1.0f );
bobtime += ( gpGlobals->curtime - lastbobtime ) * bob_offset;
lastbobtime = gpGlobals->curtime;
//Calculate the vertical bob
cycle = bobtime - (int)(bobtime/HL2_BOB_CYCLE_MAX)*HL2_BOB_CYCLE_MAX;
cycle /= HL2_BOB_CYCLE_MAX;
if ( cycle < HL2_BOB_UP )
{
cycle = M_PI * cycle / HL2_BOB_UP;
}
else
{
cycle = M_PI + M_PI*(cycle-HL2_BOB_UP)/(1.0 - HL2_BOB_UP);
}
g_verticalBob = speed*0.005f;
g_verticalBob = g_verticalBob*0.3 + g_verticalBob*0.7*sin(cycle);
g_verticalBob = clamp( g_verticalBob, -7.0f, 4.0f );
//Calculate the lateral bob
cycle = bobtime - (int)(bobtime/HL2_BOB_CYCLE_MAX*2)*HL2_BOB_CYCLE_MAX*2;
cycle /= HL2_BOB_CYCLE_MAX*2;
if ( cycle < HL2_BOB_UP )
{
cycle = M_PI * cycle / HL2_BOB_UP;
}
else
{
cycle = M_PI + M_PI*(cycle-HL2_BOB_UP)/(1.0 - HL2_BOB_UP);
}
g_lateralBob = speed*0.005f;
g_lateralBob = g_lateralBob*0.3 + g_lateralBob*0.7*sin(cycle);
g_lateralBob = clamp( g_lateralBob, -7.0f, 4.0f );
//NOTENOTE: We don't use this return value in our case (need to restructure the calculation function setup!)
return 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &origin -
// &angles -
// viewmodelindex -
//-----------------------------------------------------------------------------
void CWeaponSOBase::AddViewmodelBob( CBaseViewModel *viewmodel, Vector &origin, QAngle &angles )
{
Vector forward, right;
AngleVectors( angles, &forward, &right, NULL );
CalcViewmodelBob();
// Apply bob, but scaled down to 40%
VectorMA( origin, g_verticalBob * 0.1f, forward, origin );
// Z bob a bit more
origin[2] += g_verticalBob * 0.1f;
// bob the angles
angles[ ROLL ] += g_verticalBob * 0.5f;
angles[ PITCH ] -= g_verticalBob * 0.4f;
angles[ YAW ] -= g_lateralBob * 0.3f;
VectorMA( origin, g_lateralBob * 0.8f, right, origin );
}
#else
// Server stubs
float CWeaponSOBase::CalcViewmodelBob( void )
{
return 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &origin -
// &angles -
// viewmodelindex -
//-----------------------------------------------------------------------------
void CWeaponSOBase::AddViewmodelBob( CBaseViewModel *viewmodel, Vector &origin, QAngle &angles )
{
}
#endif
// Weapon reorigin system
// http://developer.valvesoftware.com/wiki/Adding_Ironsights
// Modified a bit from the wiki version considering our system's purpose
Vector CWeaponSOBase::GetIronsightPositionOffset( void ) const
{
if( viewmodel_adjust_enabled.GetBool() )
return Vector( viewmodel_adjust_forward.GetFloat(), viewmodel_adjust_right.GetFloat(), viewmodel_adjust_up.GetFloat() );
return GetHL2MPWpnData().vecIronsightPosOffset;
}
QAngle CWeaponSOBase::GetIronsightAngleOffset( void ) const
{
if( viewmodel_adjust_enabled.GetBool() )
return QAngle( viewmodel_adjust_pitch.GetFloat(), viewmodel_adjust_yaw.GetFloat(), viewmodel_adjust_roll.GetFloat() );
return GetHL2MPWpnData().angIronsightAngOffset;
}
float CWeaponSOBase::GetIronsightFOVOffset( void ) const
{
if( viewmodel_adjust_enabled.GetBool() )
return viewmodel_adjust_fov.GetFloat();
return GetHL2MPWpnData().flIronsightFOVOffset;
}
// Weapon reorigin system
// http://developer.valvesoftware.com/wiki/Adding_Ironsights
// Modified a bit from the wiki version considering our system's purpose
void vm_adjust_enable_callback( IConVar *pConVar, char const *pOldString, float flOldValue )
{
ConVarRef sv_cheats( "sv_cheats" );
if( !sv_cheats.IsValid() || sv_cheats.GetBool() )
return;
ConVarRef var( pConVar );
if( var.GetBool() )
var.SetValue( "0" );
}
void vm_adjust_fov_callback( IConVar *pConVar, char const *pOldString, float flOldValue )
{
if( !viewmodel_adjust_enabled.GetBool() )
return;
ConVarRef var( pConVar );
CSO_Player *pPlayer =
#ifdef GAME_DLL
ToSOPlayer( UTIL_GetLocalPlayer() );
#else
ToSOPlayer( C_BasePlayer::GetLocalPlayer() );
#endif
if( !pPlayer )
return;
if( !pPlayer->SetFOV( pPlayer, pPlayer->GetDefaultFOV()+var.GetFloat(), 0.1f ) )
{
Warning( "Could not set FOV\n" );
var.SetValue( "0" );
}
}
// Weapon respawn fix
// http://developer.valvesoftware.com/wiki/Weapon_Respawn_Fix
void CWeaponSOBase::FallInit( void )
{
#ifndef CLIENT_DLL
SetModel( GetWorldModel() );
VPhysicsDestroyObject();
if ( HasSpawnFlags(SF_NORESPAWN) == false )
{
SetMoveType( MOVETYPE_NONE );
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_TRIGGER );
UTIL_DropToFloor( this, MASK_SOLID );
}
else
{
if ( !VPhysicsInitNormal(SOLID_BBOX, GetSolidFlags() | FSOLID_TRIGGER, false) )
{
SetMoveType( MOVETYPE_NONE );
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_TRIGGER );
}
else
{
// Constrained start?
if ( HasSpawnFlags(SF_WEAPON_START_CONSTRAINED) )
{
//Constrain the weapon in place
IPhysicsObject *pReferenceObject, *pAttachedObject;
pReferenceObject = g_PhysWorldObject;
pAttachedObject = VPhysicsGetObject();
if ( pReferenceObject && pAttachedObject )
{
constraint_fixedparams_t fixed;
fixed.Defaults();
fixed.InitWithCurrentObjectState( pReferenceObject, pAttachedObject );
fixed.constraint.forceLimit = lbs2kg( 10000 );
fixed.constraint.torqueLimit = lbs2kg( 10000 );
IPhysicsConstraint *pConstraint = GetConstraint();
pConstraint = physenv->CreateFixedConstraint( pReferenceObject, pAttachedObject, NULL, fixed );
pConstraint->SetGameData( (void *) this );
}
}
}
}
SetPickupTouch();
SetThink( &CWeaponSOBase::FallThink );
SetNextThink( gpGlobals->curtime + 0.1f );
#endif // !CLIENT_DLL
}
// Weapon respawn fix
// http://developer.valvesoftware.com/wiki/Weapon_Respawn_Fix
#ifdef GAME_DLL
void CWeaponSOBase::FallThink(void)
{
// Prevent the common HL2DM weapon respawn bug from happening
// When a weapon is spawned, the following chain of events occurs:
// - Spawn() is called (duh), which then calls FallInit()
// - FallInit() is called, and prepares the weapon's 'Think' function (CBaseCombatWeapon::FallThink())
// - FallThink() is called, and performs several checks before deciding whether the weapon should Materialize()
// - Materialize() is called (the HL2DM version above), which sets the weapon's respawn location.
// The problem occurs when a weapon isn't placed properly by a level designer.
// If the weapon is unable to move from its location (e.g. if its bounding box is halfway inside a wall), Materialize() never gets called.
// Since Materialize() never gets called, the weapon's respawn location is never set, so if a person picks it up, it respawns forever at
// 0 0 0 on the map (infinite loop of fall, wait, respawn, not nice at all for performance and bandwidth!)
if ( HasSpawnFlags(SF_NORESPAWN) == false )
{
if ( GetOriginalSpawnOrigin() == vec3_origin )
{
m_vOriginalSpawnOrigin = GetAbsOrigin();
m_vOriginalSpawnAngles = GetAbsAngles();
}
}
return BaseClass::FallThink();
}
#endif // GAME_DLL
|
[
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
] |
[
[
[
1,
705
]
]
] |
5c03fd5b53b3e5d636157e066eebae7b406269a7
|
44e10950b3bf454080553a5da36bf263e6a62f8f
|
/src/GeneticAlg/ProsumerGeneticAlg.cpp
|
a9d0ad397b26fcd2241fcf5c0566bff482873243
|
[] |
no_license
|
ptrefall/ste6246tradingagent
|
a515d88683bf5f55f862c0b3e539ad6144a260bb
|
89c8e5667aec4c74aef3ffe47f19eb4a1b17b318
|
refs/heads/master
| 2020-05-18T03:50:47.216489 | 2011-12-20T19:02:32 | 2011-12-20T19:02:32 | 32,448,454 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,746 |
cpp
|
#include "ProsumerGeneticAlg.h"
#include <algorithm>
ProsumerGeneticAlg::ProsumerGeneticAlg( GAManager &mgr,
unsigned int populationSize,
double fitness_for_survival_threshold,
double crossover_chance,
unsigned int max_children_from_cross,
double mutation_chance,
double start_saldo,
double economic_capacity_base,
double energy_production_base,
double energy_consumption_base,
double flex_rate_base,
unsigned int policy_base)
: IGeneticAlg<ProsumerGenome>( mgr,
populationSize,
fitness_for_survival_threshold,
crossover_chance,
max_children_from_cross,
mutation_chance
),
start_saldo(start_saldo),
economic_capacity_base(economic_capacity_base),
energy_production_base(energy_production_base),
energy_consumption_base(energy_consumption_base),
flex_rate_base(flex_rate_base),
policy_base(policy_base)
{
}
ProsumerGeneticAlg::~ProsumerGeneticAlg()
{
}
bool ProsumerGeneticAlg::mutate(ProsumerGenome &genome, double chance) const
{
bool genome_was_mutated = false;
Prosumer value = genome.chromosomeValue();
Prosumer temp;
temp.economic_capacity = value.economic_capacity;
temp.energy_production_capacity = value.energy_production_capacity;
temp.energy_consumption = value.energy_consumption;
temp.flexi_rate = value.flexi_rate;
temp.policy = value.policy;
double result = randomize();
if(result <= chance)
{
temp.economic_capacity = (economic_capacity_base*0.5) + randomize()*economic_capacity_base;
genome_was_mutated = true;
}
result = randomize();
if(result <= chance)
{
temp.energy_production_capacity = (energy_production_base*0.5) + randomize()*energy_production_base;
genome_was_mutated = true;
}
result = randomize();
if(result <= chance)
{
temp.energy_consumption = (energy_consumption_base*0.5) + randomize()*energy_consumption_base;
genome_was_mutated = true;
}
result = randomize();
if(result <= chance)
{
temp.flexi_rate = (flex_rate_base*0.5) + randomize()*flex_rate_base;
genome_was_mutated = true;
}
result = randomize();
if(result <= chance)
{
temp.policy = (policy_base*0.5) + randomize()*policy_base;
genome_was_mutated = true;
}
if(genome_was_mutated)
{
Prosumer midpoint;
calcMidpoint(midpoint, value, temp);
Prosumer distance;
calcDistance(distance, value, temp);
calcResult(value, midpoint, distance);
genome.setChromosomeValue(value, true, generation->id);
}
return genome_was_mutated;
}
std::vector<ProsumerGenome*> ProsumerGeneticAlg::crossover(ProsumerGenome &mum, ProsumerGenome &dad, unsigned int child_count, double chance)
{
std::vector<ProsumerGenome*> children;
/*if( mum.chromosomeValue().r == dad.chromosomeValue().r &&
mum.chromosomeValue().g == dad.chromosomeValue().g &&
mum.chromosomeValue().b == dad.chromosomeValue().b )
{
return children;
}*/
double result = randomize();
if(result <= chance)
{
for(unsigned int i = 0; i < child_count; i++)
{
Prosumer midpoint;
calcMidpoint(midpoint, mum.chromosomeValue(), dad.chromosomeValue());
Prosumer distance;
calcDistance(distance, mum.chromosomeValue(), dad.chromosomeValue());
Prosumer res;
calcResult(res, midpoint, distance);
bool duplicate = false;
/*for(unsigned int i = 0; i < children.size(); i++)
{
if( res.r == children[i]->chromosomeValue().r &&
res.g == children[i]->chromosomeValue().g &&
res.b == children[i]->chromosomeValue().b )
{
duplicate = true;
break;
}
}*/
if(duplicate == false)
{
ProsumerGenome *child = new ProsumerGenome( mgr,
res.economic_capacity,
res.energy_production_capacity,
res.energy_consumption,
res.flexi_rate,
res.policy,
start_saldo);
children.push_back(child);
}
}
}
return children;
}
void ProsumerGeneticAlg::calcMidpoint(Prosumer &midpoint, const Prosumer &a, const Prosumer &b) const
{
midpoint.economic_capacity = (a.economic_capacity + b.economic_capacity) / 2.0;
midpoint.energy_production_capacity = (a.energy_production_capacity + b.energy_production_capacity) / 2.0;
midpoint.energy_consumption = (a.energy_consumption + b.energy_consumption) / 2.0;
midpoint.flexi_rate = (a.flexi_rate + b.flexi_rate) / 2.0;
midpoint.policy = (a.policy + b.policy) / 2.0;
}
void ProsumerGeneticAlg::calcDistance(Prosumer &distance, const Prosumer &a, const Prosumer &b) const
{
distance.economic_capacity = (int)fabs((double)a.economic_capacity - (double)b.economic_capacity);
distance.energy_production_capacity = (int)fabs((double)a.energy_production_capacity - (double)b.energy_production_capacity);
distance.energy_consumption = (int)fabs((double)a.energy_consumption - (double)b.energy_consumption);
distance.flexi_rate = (int)fabs((double)a.flexi_rate - (double)b.flexi_rate);
distance.policy = (int)fabs((double)a.policy - (double)b.policy);
}
void ProsumerGeneticAlg::calcResult(Prosumer &result, const Prosumer &midpoint, const Prosumer &distance) const
{
result.economic_capacity = midpoint.economic_capacity + distance.economic_capacity * (randomize()*randomize());
result.energy_production_capacity = midpoint.energy_production_capacity + distance.energy_production_capacity * (randomize()*randomize());
result.energy_consumption = midpoint.energy_consumption + distance.energy_consumption * (randomize()*randomize());
result.flexi_rate = midpoint.flexi_rate + distance.flexi_rate * (randomize()*randomize());
result.policy = midpoint.policy + distance.policy * (randomize()*randomize());
}
ProsumerGenome *ProsumerGeneticAlg::createInitialRandomGenome(unsigned int index, unsigned int population_size)
{
double ec = economic_capacity_base/**0.5) + randomize()*economic_capacity_base*/;
double ep = energy_production_base/**0.5) + randomize()*energy_production_base*/;
double ef = energy_consumption_base/**0.5) + randomize()*energy_consumption_base*/;
double flex = flex_rate_base/**0.5) + randomize()*flex_rate_base*/;
unsigned int policy = policy_base/**0.5) + randomize()*policy_base*/;
return new ProsumerGenome(mgr, ec,ep,ef,flex,policy, start_saldo);
}
std::vector<ProsumerGenome*> ProsumerGeneticAlg::findSurvivors()
{
std::vector<ProsumerGenome*> survivors;
sortPopulation();
for(unsigned int i = 0; i < generation->population->individuals.size(); i++)
{
if(generation->population->individuals[i]->chromosomeValue().saldo > generation->fitness_for_survival_threshold)
survivors.push_back(generation->population->individuals[i]);
}
generation->deaths = generation->population->individuals.size() - survivors.size();
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
//std::cout << "Prosumer Deaths: " << deaths << std::endl;
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
return survivors;
}
void ProsumerGeneticAlg::sortPopulation()
{
std::sort(generation->population->individuals.begin(), generation->population->individuals.end(), ProsumerGenomeSortPredicate<ProsumerGenome>);
}
void ProsumerGeneticAlg::selectBestIndividual()
{
if(generation->population->individuals.empty())
{
generation->bestGenome = 0x0;
return;
}
sortPopulation();
generation->bestGenome = generation->population->individuals[0];
}
|
[
"[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe"
] |
[
[
[
1,
223
]
]
] |
64b5d3f090f94b8eea73967de8887fc26df4661f
|
7e68ef369eff945f581e22595adecb6b3faccd0e
|
/code/minifw/inetaddr.cpp
|
c6354ae80291e3b227278aed2ce6827c3948cacb
|
[] |
no_license
|
kimhmadsen/mini-framework
|
700bb1052227ba18eee374504ff90f41e98738d2
|
d1983a68c6b1d87e24ef55ca839814ed227b3956
|
refs/heads/master
| 2021-01-01T05:36:55.074091 | 2008-12-16T00:33:10 | 2008-12-16T00:33:10 | 32,415,758 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,252 |
cpp
|
#include "StdAfx.h"
#include <windows.h>
#include <winsock.h>
#include "inetaddr.h"
InetAddr::InetAddr(u_short port, u_long address)
{
memset( &addr , 0, sizeof( addr ) );
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
addr.sin_addr.s_addr = htonl( address );
}
InetAddr::InetAddr(u_short port, char* host)
{
//int status;
memset( &addr , 0, sizeof( addr ) );
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
//status = ::inet_aton( host, &addr );
addr.sin_addr.s_addr = inet_addr( host );;
}
InetAddr::InetAddr(u_short port)
{
memset( &addr , 0, sizeof( addr ) );
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
addr.sin_addr.s_addr = htonl( 0 );
}
InetAddr::~InetAddr(void)
{
}
void InetAddr::SetPort( u_short port )
{
addr.sin_port = htons( port );
}
u_short InetAddr::GetPort()
{
// convert to host endianess before returning it.
return ntohs( addr.sin_port );
}
u_long InetAddr::GetIpAddr()
{
// convert to host endianess before returning it.
return ntohl( addr.sin_addr.s_addr );
}
sockaddr* InetAddr::Addr(void)
{
return reinterpret_cast <sockaddr *> (&addr);
}
size_t InetAddr::Size(void)
{
return sizeof( addr );
}
|
[
"kim.hedegaard.madsen@77f6bdef-6155-0410-8b08-fdea0229669f"
] |
[
[
[
1,
64
]
]
] |
cf572a2926bd8be09961cecefc559d45bf42c09d
|
84ca111e2739d866aac5f779824afd1f0bcf2842
|
/PhotoReference.h
|
54d8f64355af57fa7334ba5b507b0f61ee01c22f
|
[] |
no_license
|
radtek/photoupload
|
0193989c016d35de774315acc562598ddb1ccf40
|
0291fd9fbed728aa07e1bebb578da58906fa0b8e
|
refs/heads/master
| 2020-09-27T13:13:47.706353 | 2009-09-24T22:20:11 | 2009-09-24T22:20:11 | 226,525,120 | 1 | 0 | null | 2019-12-07T14:15:57 | 2019-12-07T14:15:56 | null |
UTF-8
|
C++
| false | false | 2,368 |
h
|
#pragma once
class PhotoReference
{
public:
PhotoReference(const CString& path);
virtual ~PhotoReference(void);
private:
CString path;
CString title;
CString text;
CString keywords;
bool dirty;
GUID remoteId;
CString uploadResultMessage;
bool finished;
bool locked; //must only be set from gui thread.
CString lockedUpdateTitle;
CString lockedUpdateText;
public:
#ifdef DEBUG
DWORD ownerThread;
#endif
#define PR_ASSERTOWNER ASSERT(ownerThread == ::GetCurrentThreadId())
static const UINT MAX_DIGITS_TITLE = 4;
static const UINT MAX_PHOTO_NAME_LEN = 50;//sync with db
bool LockedStatus() const { return locked; }
void Lock();
void Unlock();
bool Finished() const { return finished; }
void SetFinished() {
PR_ASSERTOWNER;
#ifdef DEBUG
byte z[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
ASSERT(memcmp(z,&remoteId,16) != 0);
#endif
this->dirty = false;
this->finished = true;
}
const CString& GetPath() const {
// PR_ASSERTOWNER;
return path;
}
// the worker thread gets lockedUpdateTitle, which is ok so long as it doesn't try to
// write to it.
const CString& GetTitle() const {
// We don't need to lock here, since the bg-thread don't change these, and
// the assertions is made on GetPath.
// PR_ASSERTOWNER;
if(LockedStatus())
return lockedUpdateTitle;
return title;
}
const CString& GetText() const {
// see GetTitle:
// PR_ASSERTOWNER;
if(LockedStatus())
return lockedUpdateText;
return text;
}
const CString& GetTitleLocked() const {
PR_ASSERTOWNER;
return title;
}
const CString& GetTextLocked() const {
PR_ASSERTOWNER;
return text;
}
const GUID& GetRemoteId() const {
return this->remoteId;
}
void SetTitle(LPCTSTR);
void SetText(LPCTSTR);
bool GetDirty() {
PR_ASSERTOWNER;
return dirty;
}
void ClearDirty() {
PR_ASSERTOWNER;
this->dirty = false;
}
void SetRemoteId(GUID photoId) {
PR_ASSERTOWNER;
#ifdef DEBUG
byte z[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
ASSERT(memcmp(z,&remoteId,16) == 0);
ASSERT(memcmp(z,&photoId,16) != 0);
#endif
memcpy(&this->remoteId, &photoId, 16);
}
void SetUploadResultMessage(const LPCTSTR msg) {
PR_ASSERTOWNER;
this->uploadResultMessage = msg;
}
public:
int imageIndex;
};
|
[
"[email protected]"
] |
[
[
[
1,
115
]
]
] |
739fe24e3c345046d6191ea603db175953cbd3e1
|
b14d5833a79518a40d302e5eb40ed5da193cf1b2
|
/cpp/extern/crypto++/5.2.1/cryptlib.cpp
|
c4a19b672343e3beab148ca8fcf58fdb95a70711
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-cryptopp"
] |
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 | 20,520 |
cpp
|
// cryptlib.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "cryptlib.h"
#include "misc.h"
#include "filters.h"
#include "algparam.h"
#include "fips140.h"
#include "argnames.h"
#include "fltrimpl.h"
#include <memory>
NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_COMPILE_ASSERT(sizeof(byte) == 1);
CRYPTOPP_COMPILE_ASSERT(sizeof(word16) == 2);
CRYPTOPP_COMPILE_ASSERT(sizeof(word32) == 4);
#ifdef WORD64_AVAILABLE
CRYPTOPP_COMPILE_ASSERT(sizeof(word64) == 8);
#endif
#ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
CRYPTOPP_COMPILE_ASSERT(sizeof(dword) == 2*sizeof(word));
#endif
const std::string BufferedTransformation::NULL_CHANNEL;
const NullNameValuePairs g_nullNameValuePairs;
BufferedTransformation & TheBitBucket()
{
static BitBucket bitBucket;
return bitBucket;
}
Algorithm::Algorithm(bool checkSelfTestStatus)
{
if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
{
if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_NOT_DONE && !PowerUpSelfTestInProgressOnThisThread())
throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_FAILED)
throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed.");
}
}
void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, unsigned int length, int rounds)
{
SetKey(key, length, MakeParameters(Name::Rounds(), rounds));
}
void SimpleKeyingInterface::SetKeyWithIV(const byte *key, unsigned int length, const byte *iv)
{
SetKey(key, length, MakeParameters(Name::IV(), iv));
}
void SimpleKeyingInterface::ThrowIfInvalidKeyLength(const Algorithm &algorithm, unsigned int length)
{
if (!IsValidKeyLength(length))
throw InvalidKeyLength(algorithm.AlgorithmName(), length);
}
void SimpleKeyingInterface::ThrowIfResynchronizable()
{
if (IsResynchronizable())
throw InvalidArgument("SimpleKeyingInterface: this object requires an IV");
}
void SimpleKeyingInterface::ThrowIfInvalidIV(const byte *iv)
{
if (!iv && !(IVRequirement() == INTERNALLY_GENERATED_IV || IVRequirement() == STRUCTURED_IV || !IsResynchronizable()))
throw InvalidArgument("SimpleKeyingInterface: this object cannot use a null IV");
}
const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(const NameValuePairs ¶ms)
{
const byte *iv;
if (params.GetValue(Name::IV(), iv))
ThrowIfInvalidIV(iv);
else
ThrowIfResynchronizable();
return iv;
}
void BlockTransformation::ProcessAndXorMultipleBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, unsigned int numberOfBlocks) const
{
unsigned int blockSize = BlockSize();
while (numberOfBlocks--)
{
ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
inBlocks += blockSize;
outBlocks += blockSize;
if (xorBlocks)
xorBlocks += blockSize;
}
}
void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, unsigned int length)
{
assert(MinLastBlockSize() == 0); // this function should be overriden otherwise
if (length == MandatoryBlockSize())
ProcessData(outString, inString, length);
else if (length != 0)
throw NotImplemented("StreamTransformation: this object does't support a special last block");
}
unsigned int RandomNumberGenerator::GenerateBit()
{
return Parity(GenerateByte());
}
void RandomNumberGenerator::GenerateBlock(byte *output, unsigned int size)
{
while (size--)
*output++ = GenerateByte();
}
word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
{
word32 range = max-min;
const int maxBytes = BytePrecision(range);
const int maxBits = BitPrecision(range);
word32 value;
do
{
value = 0;
for (int i=0; i<maxBytes; i++)
value = (value << 8) | GenerateByte();
value = Crop(value, maxBits);
} while (value > range);
return value+min;
}
void RandomNumberGenerator::DiscardBytes(unsigned int n)
{
while (n--)
GenerateByte();
}
//! see NullRNG()
class ClassNullRNG : public RandomNumberGenerator
{
public:
std::string AlgorithmName() const {return "NullRNG";}
byte GenerateByte() {throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");}
};
RandomNumberGenerator & NullRNG()
{
static ClassNullRNG s_nullRNG;
return s_nullRNG;
}
bool HashTransformation::TruncatedVerify(const byte *digestIn, unsigned int digestLength)
{
ThrowIfInvalidTruncatedSize(digestLength);
SecByteBlock digest(digestLength);
TruncatedFinal(digest, digestLength);
return memcmp(digest, digestIn, digestLength) == 0;
}
void HashTransformation::ThrowIfInvalidTruncatedSize(unsigned int size) const
{
if (size > DigestSize())
throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
}
unsigned int BufferedTransformation::GetMaxWaitObjectCount() const
{
const BufferedTransformation *t = AttachedTransformation();
return t ? t->GetMaxWaitObjectCount() : 0;
}
void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container)
{
BufferedTransformation *t = AttachedTransformation();
if (t)
t->GetWaitObjects(container);
}
void BufferedTransformation::Initialize(const NameValuePairs ¶meters, int propagation)
{
assert(!AttachedTransformation());
IsolatedInitialize(parameters);
}
bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
{
assert(!AttachedTransformation());
return IsolatedFlush(hardFlush, blocking);
}
bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
{
assert(!AttachedTransformation());
return IsolatedMessageSeriesEnd(blocking);
}
byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, unsigned int &size)
{
if (channel.empty())
return CreatePutSpace(size);
else
throw NoChannelSupport();
}
unsigned int BufferedTransformation::ChannelPut2(const std::string &channel, const byte *begin, unsigned int length, int messageEnd, bool blocking)
{
if (channel.empty())
return Put2(begin, length, messageEnd, blocking);
else
throw NoChannelSupport();
}
unsigned int BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *begin, unsigned int length, int messageEnd, bool blocking)
{
if (channel.empty())
return PutModifiable2(begin, length, messageEnd, blocking);
else
return ChannelPut2(channel, begin, length, messageEnd, blocking);
}
bool BufferedTransformation::ChannelFlush(const std::string &channel, bool completeFlush, int propagation, bool blocking)
{
if (channel.empty())
return Flush(completeFlush, propagation, blocking);
else
throw NoChannelSupport();
}
bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
{
if (channel.empty())
return MessageSeriesEnd(propagation, blocking);
else
throw NoChannelSupport();
}
unsigned long BufferedTransformation::MaxRetrievable() const
{
if (AttachedTransformation())
return AttachedTransformation()->MaxRetrievable();
else
return CopyTo(TheBitBucket());
}
bool BufferedTransformation::AnyRetrievable() const
{
if (AttachedTransformation())
return AttachedTransformation()->AnyRetrievable();
else
{
byte b;
return Peek(b) != 0;
}
}
unsigned int BufferedTransformation::Get(byte &outByte)
{
if (AttachedTransformation())
return AttachedTransformation()->Get(outByte);
else
return Get(&outByte, 1);
}
unsigned int BufferedTransformation::Get(byte *outString, unsigned int getMax)
{
if (AttachedTransformation())
return AttachedTransformation()->Get(outString, getMax);
else
{
ArraySink arraySink(outString, getMax);
return TransferTo(arraySink, getMax);
}
}
unsigned int BufferedTransformation::Peek(byte &outByte) const
{
if (AttachedTransformation())
return AttachedTransformation()->Peek(outByte);
else
return Peek(&outByte, 1);
}
unsigned int BufferedTransformation::Peek(byte *outString, unsigned int peekMax) const
{
if (AttachedTransformation())
return AttachedTransformation()->Peek(outString, peekMax);
else
{
ArraySink arraySink(outString, peekMax);
return CopyTo(arraySink, peekMax);
}
}
unsigned long BufferedTransformation::Skip(unsigned long skipMax)
{
if (AttachedTransformation())
return AttachedTransformation()->Skip(skipMax);
else
return TransferTo(TheBitBucket(), skipMax);
}
unsigned long BufferedTransformation::TotalBytesRetrievable() const
{
if (AttachedTransformation())
return AttachedTransformation()->TotalBytesRetrievable();
else
return MaxRetrievable();
}
unsigned int BufferedTransformation::NumberOfMessages() const
{
if (AttachedTransformation())
return AttachedTransformation()->NumberOfMessages();
else
return CopyMessagesTo(TheBitBucket());
}
bool BufferedTransformation::AnyMessages() const
{
if (AttachedTransformation())
return AttachedTransformation()->AnyMessages();
else
return NumberOfMessages() != 0;
}
bool BufferedTransformation::GetNextMessage()
{
if (AttachedTransformation())
return AttachedTransformation()->GetNextMessage();
else
{
assert(!AnyMessages());
return false;
}
}
unsigned int BufferedTransformation::SkipMessages(unsigned int count)
{
if (AttachedTransformation())
return AttachedTransformation()->SkipMessages(count);
else
return TransferMessagesTo(TheBitBucket(), count);
}
unsigned int BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
{
if (AttachedTransformation())
return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
else
{
unsigned int maxMessages = messageCount;
for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
{
unsigned int blockedBytes;
unsigned long transferredBytes;
while (AnyRetrievable())
{
transferredBytes = ULONG_MAX;
blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
if (blockedBytes > 0)
return blockedBytes;
}
if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
return 1;
bool result = GetNextMessage();
assert(result);
}
return 0;
}
}
unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
{
if (AttachedTransformation())
return AttachedTransformation()->CopyMessagesTo(target, count, channel);
else
return 0;
}
void BufferedTransformation::SkipAll()
{
if (AttachedTransformation())
AttachedTransformation()->SkipAll();
else
{
while (SkipMessages()) {}
while (Skip()) {}
}
}
unsigned int BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
{
if (AttachedTransformation())
return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
else
{
assert(!NumberOfMessageSeries());
unsigned int messageCount;
do
{
messageCount = UINT_MAX;
unsigned int blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
if (blockedBytes)
return blockedBytes;
}
while (messageCount != 0);
unsigned long byteCount;
do
{
byteCount = ULONG_MAX;
unsigned int blockedBytes = TransferTo2(target, byteCount, channel, blocking);
if (blockedBytes)
return blockedBytes;
}
while (byteCount != 0);
return 0;
}
}
void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
{
if (AttachedTransformation())
AttachedTransformation()->CopyAllTo(target, channel);
else
{
assert(!NumberOfMessageSeries());
while (CopyMessagesTo(target, UINT_MAX, channel)) {}
}
}
void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
{
if (AttachedTransformation())
AttachedTransformation()->SetRetrievalChannel(channel);
}
unsigned int BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
{
FixedSizeSecBlock<byte, 2> buf;
PutWord(false, order, buf, value);
return ChannelPut(channel, buf, 2, blocking);
}
unsigned int BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
{
FixedSizeSecBlock<byte, 4> buf;
PutWord(false, order, buf, value);
return ChannelPut(channel, buf, 4, blocking);
}
unsigned int BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
{
return ChannelPutWord16(NULL_CHANNEL, value, order, blocking);
}
unsigned int BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
{
return ChannelPutWord32(NULL_CHANNEL, value, order, blocking);
}
unsigned int BufferedTransformation::PeekWord16(word16 &value, ByteOrder order)
{
byte buf[2] = {0, 0};
unsigned int len = Peek(buf, 2);
if (order)
value = (buf[0] << 8) | buf[1];
else
value = (buf[1] << 8) | buf[0];
return len;
}
unsigned int BufferedTransformation::PeekWord32(word32 &value, ByteOrder order)
{
byte buf[4] = {0, 0, 0, 0};
unsigned int len = Peek(buf, 4);
if (order)
value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
else
value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
return len;
}
unsigned int BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
{
return Skip(PeekWord16(value, order));
}
unsigned int BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
{
return Skip(PeekWord32(value, order));
}
void BufferedTransformation::Attach(BufferedTransformation *newOut)
{
if (AttachedTransformation() && AttachedTransformation()->Attachable())
AttachedTransformation()->Attach(newOut);
else
Detach(newOut);
}
void GeneratableCryptoMaterial::GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
{
GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
}
class PK_DefaultEncryptionFilter : public Unflushable<Filter>
{
public:
PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs ¶meters)
: m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
{
Detach(attachment);
}
unsigned int Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
{
FILTER_BEGIN;
m_plaintextQueue.Put(inString, length);
if (messageEnd)
{
{
unsigned int plaintextLength = m_plaintextQueue.CurrentSize();
unsigned int ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
SecByteBlock plaintext(plaintextLength);
m_plaintextQueue.Get(plaintext, plaintextLength);
m_ciphertext.resize(ciphertextLength);
m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
}
FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
}
FILTER_END_NO_MESSAGE_END;
}
RandomNumberGenerator &m_rng;
const PK_Encryptor &m_encryptor;
const NameValuePairs &m_parameters;
ByteQueue m_plaintextQueue;
SecByteBlock m_ciphertext;
};
BufferedTransformation * PK_Encryptor::CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs ¶meters) const
{
return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
}
class PK_DefaultDecryptionFilter : public Unflushable<Filter>
{
public:
PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs ¶meters)
: m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
{
Detach(attachment);
}
unsigned int Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
{
FILTER_BEGIN;
m_ciphertextQueue.Put(inString, length);
if (messageEnd)
{
{
unsigned int ciphertextLength = m_ciphertextQueue.CurrentSize();
unsigned int maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
SecByteBlock ciphertext(ciphertextLength);
m_ciphertextQueue.Get(ciphertext, ciphertextLength);
m_plaintext.resize(maxPlaintextLength);
m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
if (!m_result.isValidCoding)
throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
}
FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
}
FILTER_END_NO_MESSAGE_END;
}
RandomNumberGenerator &m_rng;
const PK_Decryptor &m_decryptor;
const NameValuePairs &m_parameters;
ByteQueue m_ciphertextQueue;
SecByteBlock m_plaintext;
DecodingResult m_result;
};
BufferedTransformation * PK_Decryptor::CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs ¶meters) const
{
return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
}
unsigned int PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
{
std::auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
return SignAndRestart(rng, *m, signature, false);
}
unsigned int PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, unsigned int messageLen, byte *signature) const
{
std::auto_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
m->Update(message, messageLen);
return SignAndRestart(rng, *m, signature, false);
}
unsigned int PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, unsigned int recoverableMessageLength,
const byte *nonrecoverableMessage, unsigned int nonrecoverableMessageLength, byte *signature) const
{
std::auto_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return SignAndRestart(rng, *m, signature, false);
}
bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
{
std::auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
return VerifyAndRestart(*m);
}
bool PK_Verifier::VerifyMessage(const byte *message, unsigned int messageLen, const byte *signature, unsigned int signatureLength) const
{
std::auto_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLength);
m->Update(message, messageLen);
return VerifyAndRestart(*m);
}
DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
{
std::auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
return RecoverAndRestart(recoveredMessage, *m);
}
DecodingResult PK_Verifier::RecoverMessage(byte *recoveredMessage,
const byte *nonrecoverableMessage, unsigned int nonrecoverableMessageLength,
const byte *signature, unsigned int signatureLength) const
{
std::auto_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return RecoverAndRestart(recoveredMessage, *m);
}
void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GeneratePrivateKey(rng, privateKey);
GeneratePublicKey(rng, privateKey, publicKey);
}
void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GenerateStaticPrivateKey(rng, privateKey);
GenerateStaticPublicKey(rng, privateKey, publicKey);
}
void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GenerateEphemeralPrivateKey(rng, privateKey);
GenerateEphemeralPublicKey(rng, privateKey, publicKey);
}
NAMESPACE_END
#endif
|
[
"[email protected]"
] |
[
[
[
1,
687
]
]
] |
302c7c5380a2d16af30a0f743b6f22afa59e8b3c
|
42b849592857850523c3f2a33b8201de23f8dfb9
|
/ui_daconfig.h
|
274d819d8bf8b3f1d7504d794bfc675aded733f2
|
[] |
no_license
|
jemyzhang/M8Calendar_deprecated
|
209e2875a7bcb70281ba65dec80ffc254e2446b6
|
d87773a0cbb724f29248ebd3ee0344226046b4f0
|
refs/heads/master
| 2016-09-06T21:55:08.542592 | 2009-11-08T04:39:57 | 2009-11-08T04:39:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,077 |
h
|
#ifndef _UI_CALENDARDACONFIG_H
#define _UI_CALENDARDACONFIG_H
// include the MZFC library header file
#include <mzfc_inc.h>
#include "../MzCommon/MzConfig.h"
// Main window derived from CMzWndEx
class CalendarDAConfig : public AppConfigIni{
public:
CalendarDAConfig()
:AppConfigIni(L"daconfig.ini"){
InitIniKey();
}
protected:
void InitIniKey(){
IniClockSize.InitKey(L"DaUi",L"ClockSize",65);
IniClockXPos.InitKey(L"DaUi",L"ClockXPos",345);
IniClockYPos.InitKey(L"DaUi",L"ClockYPox",95);
IniSecColor.InitKey(L"DaUi",L"SecColor",0);
IniMinColor.InitKey(L"DaUi",L"MinColor",0);
IniHourColor.InitKey(L"DaUi",L"HourColor",0);
IniRoundColor.InitKey(L"DaUi",L"RoundColor",RGB(255,215,130));
IniAutoTimeout.InitKey(L"DaTimeout",L"AutoTimeOut",10);
}
public:
MzConfig IniSecColor;
MzConfig IniMinColor;
MzConfig IniHourColor;
MzConfig IniRoundColor;
MzConfig IniClockSize;
MzConfig IniClockXPos;
MzConfig IniClockYPos;
MzConfig IniAutoTimeout;
};
#endif /*_UI_CALENDARDACONFIG_H*/
|
[
"jemyzhang@0e50ebb1-d170-7b45-893d-78c2c9fc94b7"
] |
[
[
[
1,
37
]
]
] |
f00b755652017468e657722bfaa27784eceab23f
|
22fb52fc26ab1da21ab837a507524f111df5b694
|
/voxelbrain/undo.cpp
|
c7efe1779a62ce8965cb7957ec5436a756b70531
|
[] |
no_license
|
yangguang-ecnu/voxelbrain
|
b343cec00e7b76bc46cc12723f750185fa84e6d2
|
82e1912ff69998077a5d7ecca9b5b1f9d7c1b948
|
refs/heads/master
| 2021-01-10T01:21:59.902255 | 2009-02-10T05:24:40 | 2009-02-10T05:24:40 | 52,189,505 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 620 |
cpp
|
#include "undo.h"
using namespace std;
void undo::clear(){
cur_step.clear();
the_undo.clear();
};
void undo::add_point(size_t to_insert){
cur_step.push_back(to_insert);
};
void undo::save(){
the_undo.push_back(cur_step);
cur_step.clear();
};
void undo::restore(undo::undo_step & out){
cur_step.clear();
if(the_undo.size()==0)return; //no undo info
undo_step cur(the_undo.back()); //get list pointer
for(undo_step::iterator i = cur.begin(); i != cur.end(); i++){
out.push_back(*i);
};
the_undo.pop_back();
};
bool undo::empty(){
return (the_undo.size()==0);
};
|
[
"konstantin.levinski@04f5dad0-e037-0410-8c28-d9c1d3725aa7"
] |
[
[
[
1,
34
]
]
] |
ca8ecc4c0df9c9bc7084432cb738d19f35ab1cdc
|
4ea18bdd6e29708401219df82fd2ea63fa3e3c59
|
/old/ProgressCircle.cpp
|
b587e160551d943ed1d4efd984b6ab41b0ba54bf
|
[] |
no_license
|
sitc428/fyp3dgame
|
e4a11f027474f0eb52c711ab577034edcae86a17
|
6b06dc8a44d8e057336579c5e11c16b438720e63
|
refs/heads/master
| 2020-04-05T14:54:58.764314 | 2011-01-24T04:16:24 | 2011-01-24T04:16:24 | 32,114,726 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,162 |
cpp
|
#include <irrlicht/irrlicht.h>
#include "ProgressCircle.hpp"
ProgressCircle::ProgressCircle(
irr::scene::ISceneNode *parent,
irr::scene::ISceneManager *smgr,
irr::s32 id,
irr::scene::ISceneCollisionManager* coll,
irr::s32 width,
irr::s32 height,
irr::s32 percentage,
const irr::core::vector3df & position,
irr::video::SColor activeColor,
irr::video::SColor inactiveColor,
irr::video::SColor borderColor
) : irr::scene::ISceneNode(parent, smgr, id, position),
_box(
irr::core::vector3d<irr::f32>(-width / 2.0, -height / 2.0, -1.0),
irr::core::vector3d<irr::f32>(width / 2.0, height / 2.0, 1.0)
),
_coll(coll),
_activeColor(activeColor),
_inactiveColor(inactiveColor),
_borderColor(borderColor),
_dimension(width, height),
_drawBorder(true),
_isVisible(true),
_percentage(percentage)
{
setAutomaticCulling(irr::scene::EAC_OFF);
setMaterialFlag(irr::video::EMF_ZBUFFER, false);
}
ProgressCircle::~ProgressCircle()
{
}
void ProgressCircle::OnRegisterSceneNode()
{
if (_isVisible)
SceneManager->registerNodeForRendering(this, irr::scene::ESNRP_SHADOW);
irr::scene::ISceneNode::OnRegisterSceneNode();
}
void ProgressCircle::render()
{
if(!_coll)
return;
if(!_isVisible)
return;
irr::video::IVideoDriver* driver = SceneManager->getVideoDriver();
irr::scene::ICameraSceneNode* camera = SceneManager->getActiveCamera();
if (!camera || !driver)
return;
irr::core::position2d<irr::s32> pos = _coll->getScreenCoordinatesFrom3DPosition(getAbsolutePosition(), SceneManager->getActiveCamera());
irr::s32 halfWidth = _dimension.Width / 2;
irr::core::rect<irr::s32> absoluteRect(pos, _dimension);
absoluteRect.UpperLeftCorner.X -= halfWidth;
absoluteRect.LowerRightCorner.X -= halfWidth;
irr::core::rect<irr::s32> barRect = absoluteRect;
/*if( _drawBorder )
{
driver->draw2DRectangle(_borderColor, absoluteRect, &absoluteRect);
barRect.UpperLeftCorner.X += 1;
barRect.UpperLeftCorner.Y += 1;
barRect.LowerRightCorner.X -= 1;
barRect.LowerRightCorner.Y -= 1;
}*/
// draw inactive part
driver->draw2DRectangle(_inactiveColor, barRect, &barRect );
// draw active part
barRect.LowerRightCorner.X = barRect.UpperLeftCorner.X + ((barRect.LowerRightCorner.X - barRect.UpperLeftCorner.X) * _percentage) / 100;
driver->draw2DRectangle(_activeColor, barRect, &barRect);
}
const irr::core::aabbox3d<irr::f32> & ProgressCircle::getBoundingBox() const
{
return _box;
}
irr::s32 ProgressCircle::getMaterialCount()
{
return 0;
}
void ProgressCircle::setProgress(irr::s32 percentage)
{
if(percentage < 0)
percentage = 0;
if(percentage > 100)
percentage = 100;
_percentage = percentage;
}
/*
//! sets the color of the progress
void ProgressCircle::setProgressColor(video::SColor color)
{
BarColor = color;
}
//! sets the color of the progress bar background
void ProgressCircle::setBackgroundColor(video::SColor color)
{
BkgColor = color;
}
//! sets the color of the progress bar border
void ProgressCircle::setBorderColor(video::SColor color)
{
borderColor = color;
}*/
|
[
"[email protected]@723dad30-d554-0410-9681-1d1d8597b35f"
] |
[
[
[
1,
123
]
]
] |
453ca26899755605a1e66c06361c97c9b795d41e
|
41efaed82e413e06f31b65633ed12adce4b7abc2
|
/cglib/src/cg/GroupMouseEvent.h
|
affd49cabf9898eb8a7d331d40188983134e7f09
|
[] |
no_license
|
ivandro/AVT---project
|
e0494f2e505f76494feb0272d1f41f5d8f117ac5
|
ef6fe6ebfe4d01e4eef704fb9f6a919c9cddd97f
|
refs/heads/master
| 2016-09-06T03:45:35.997569 | 2011-10-27T15:00:14 | 2011-10-27T15:00:14 | 2,642,435 | 0 | 2 | null | 2016-04-08T14:24:40 | 2011-10-25T09:47:13 |
C
|
UTF-8
|
C++
| false | false | 3,786 |
h
|
// This file is part of CGLib.
//
// CGLib 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.
//
// CGLib 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 CGLib; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Copyright 2007 Carlos Martinho
#ifndef GROUP_MOUSE_EVENT_H
#define GROUP_MOUSE_EVENT_H
#include "Group.h"
#include "IMouseEventListener.h"
namespace cg {
/** cg::GroupMouseEvent is a Group that automatically broadcasts
* mouse events to its inner entities. The 'pre' methods are
* called before sending the event to the inner entities, while
* the 'post' methods are called after.
*/
class GroupMouseEvent : public IGetEntities, public IMouseEventListener {
protected:
/** Called before sending the onMouse event to the group's inner entities.
* \param button One of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON.
* \param state Either GLUT_UP or GLUT_DOWN.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void preOnMouse(int button, int state, int x, int y) {}
/** Called after sending the onMouse event to the group's inner entities.
* \param button One of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON.
* \param state Either GLUT_UP or GLUT_DOWN.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void postOnMouse(int button, int state, int x, int y) {}
/** Called before sending the onMouseMotion event to the group's inner entities.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void preOnMouseMotion(int x, int y) {}
/** Called after sending the onMouseMotion event to the group's inner entities.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void postOnMouseMotion(int x, int y) {}
/** Called before sending the onMousePassiveMotion event to the group's inner entities.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void preOnMousePassiveMotion(int x, int y) {}
/** Called after sending the onMousePassiveMotion event to the group's inner entities.
* \param x The mouse's window relative x coordinate.
* \param y The mouse's window relative y coordinate.
*/
virtual void postOnMousePassiveMotion(int x, int y) {}
public:
IGETENTITIES_IMPLEMENTATION
void onMouse(int button, int state, int x, int y) {
preOnMouse(button,state,x,y);
FOR_EACH_ENTITY(onMouse(button,state,x,y),IMouseEventListener)
postOnMouse(button,state,x,y);
}
void onMouseMotion(int x, int y) {
preOnMouseMotion(x,y);
FOR_EACH_ENTITY(onMouseMotion(x,y),IMouseEventListener)
postOnMouseMotion(x,y);
}
void onMousePassiveMotion(int x, int y) {
preOnMousePassiveMotion(x,y);
FOR_EACH_ENTITY(onMousePassiveMotion(x,y),IMouseEventListener)
postOnMousePassiveMotion(x,y);
}
};
}
#endif // GROUP_MOUSE_EVENT_H
|
[
"Moreira@Moreira-PC.(none)"
] |
[
[
[
1,
95
]
]
] |
2c89d8836d3db47116136500728f8dec8830a4ed
|
d826e0dcc5b51f57101f2579d65ce8e010f084ec
|
/pre/Definition.cpp
|
1b7b99d737fd35e330159c5957f2384750785547
|
[] |
no_license
|
crazyhedgehog/macro-parametric
|
308d9253b96978537a26ade55c9c235e0442d2c4
|
9c98d25e148f894b45f69094a4031b8ad938bcc9
|
refs/heads/master
| 2020-05-18T06:01:30.426388 | 2009-06-26T15:00:02 | 2009-06-26T15:00:02 | 38,305,994 | 0 | 0 | null | null | null | null |
UHC
|
C++
| false | false | 2,456 |
cpp
|
#include ".\Definition.h"
#include <fstream>
#include <uf.h>
//! Error Report Function
int report_error( char *file, int line, char *call, int irc)
{
if (irc)
{
char err[133];
UF_get_fail_message(irc, err);
fprintf(stderr, "\n%s\nerror %d at line %d in %s\n%s\n",
err, irc, line, file, call);
}
return(irc);
}
// ValRndPnt function make small value 3D Point zero
void ValRndPnt(double C[3])
{
int size = 3;
for (int i = 0 ; i<size ; ++i) C[i] = ValRnd(C[i]);
}
// make a value 0 that is near to 0.
double ValRnd(double tmp)
{
if (abs(tmp) < 0.000001) return 0.0;
else if (tmp>0)
{
unsigned int temN = (unsigned int)tmp;
if ((tmp-(double)temN) < 0.000001) return (double)temN;
else if ( ((double)temN+1.0-tmp) < 0.000001 ) return (double)(temN+1);
}
else if(tmp<0)
{
long int tmpN = (long int)tmp;
if (((double)tmpN-tmp) < 0.000001) return (double)tmpN;
else if ((tmp-(double)tmpN+1.0) < 0.000001) return (double)(tmpN-1);
}
return tmp;
}
// ValRndPnt function make small value 3D Point zero
void ValRndPnt6(double C[3])
{
int size = 3;
for (int i = 0 ; i<size ; ++i) C[i] = ValRnd6(C[i]);
}
// make a value 0 that is near to 0.
double ValRnd6(double tmp)
{
double under = tmp - (int)tmp;
long ui = (long)(under*1000000);
tmp = double( (int)tmp + ((double)ui)*0.000001 );
return tmp;
}
int WaitGetEnter(void)
{
char c; scanf("%c", &c);
return c;
}
// Map function
// Translate a Point from the world coordinate to the local coordinate
void Map(const double A[12],double B[3])
{
double C[3];
double D[3];
D[0]=A[0]*A[9]+A[1]*A[10]+A[2]*A[11];
D[1]=A[3]*A[9]+A[4]*A[10]+A[5]*A[11];
D[2]=A[6]*A[9]+A[7]*A[10]+A[8]*A[11];
C[0]=A[0]*B[0]+A[1]*B[1]+A[2]*B[2]-D[0];
C[1]=A[3]*B[0]+A[4]*B[1]+A[5]*B[2]-D[1];
C[2]=A[6]*B[0]+A[7]*B[1]+A[8]*B[2]-D[2];
ValRndPnt(C); // 절대값 1*e-6 이하 값은 0으로 처리
B[0]=C[0];
B[1]=C[1];
B[2]=C[2];
}
// Cir_Map Function
// Translate a arc_center from the world coordinate to the local coordinate
void Cir_Map ( const double A[12], double Center[3] )
{
double D[3];
D[0]=A[0]*A[9]+A[1]*A[10]+A[2]*A[11];
D[1]=A[3]*A[9]+A[4]*A[10]+A[5]*A[11];
D[2]=A[6]*A[9]+A[7]*A[10]+A[8]*A[11];
Center[0] = Center[0] - D[0];
Center[1] = Center[1] - D[1];
Center[2] = Center[2] - D[2];
ValRndPnt(Center);
}
|
[
"surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e"
] |
[
[
[
1,
104
]
]
] |
a0133c4b3ff9fc0f9c602d6d3f4b34629d232bd2
|
942b88e59417352fbbb1a37d266fdb3f0f839d27
|
/src/VX/window.hxx
|
23d17ec8ca943fd12055eff051883ca9d04ff6c9
|
[
"BSD-2-Clause"
] |
permissive
|
take-cheeze/ARGSS...
|
2c1595d924c24730cc714d017edb375cfdbae9ef
|
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
|
refs/heads/master
| 2016-09-05T15:27:26.319404 | 2010-12-13T09:07:24 | 2010-12-13T09:07:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,744 |
hxx
|
//////////////////////////////////////////////////////////////////////////////////
/// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
/// 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.
///
/// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 _WINDOW_VX_HXX_
#define _WINDOW_VX_HXX_
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <string>
#include "bitmap.hxx"
#include "drawable.hxx"
////////////////////////////////////////////////////////////
/// Window class
////////////////////////////////////////////////////////////
class Window : public Drawable
{
public:
static int const WINDOW_FULL_OPEN = 255;
Window(VALUE iid);
~Window();
static bool IsDisposed(VALUE id);
static void New(VALUE id);
static Window& get(VALUE id);
static void Dispose(VALUE id);
void RefreshBitmaps();
void draw(long z);
void draw(long z, Bitmap const& dst_bitmap);
void Update();
VALUE getViewport() const { return viewport_; }
void setViewport(VALUE nviewport);
VALUE getWindowskin() const { return windowskin_; }
void setWindowskin(VALUE nwindowskin) { windowskin_ = nwindowskin; }
VALUE getContents() const { return contents_; }
void setContents(VALUE ncontents) { contents_ = ncontents; }
bool getStretch() const { return stretch_; }
void setStretch(bool nstretch) { stretch_ = nstretch; }
VALUE getCursorRect() const { return cursor_rect_; }
void setCursorRect(VALUE ncursor_rect) { cursor_rect_ = ncursor_rect; }
bool getActive() const { return active_; }
void setActive(bool nactive) { active_ = nactive; }
bool getVisible() const { return visible_; }
void setVisible(bool nvisible) { visible_ = nvisible; }
bool getPause() const { return pause_; }
void setPause(bool npause) { pause_ = npause; }
int getX() const { return x_; }
void setX(int nx) { x_ = nx; }
int getY() const { return y_; }
void setY(int ny) { y_ = ny; }
int getWidth() const { return width_; }
void setWidth(int nwidth) { width_ = nwidth; }
int getHeight() const { return height_; }
void setHeight(int nheight) { height_ = nheight; }
int getZ() const { return z_; }
void setZ(int nz);
int getOx() const { return ox_; }
int getOy() const { return oy_; }
void setOx(int nox) { ox_ = nox; }
void setOy(int noy) { oy_ = noy; }
int getOpacity() const { return opacity_; }
void setOpacity(int nopacity) { opacity_ = nopacity; }
int getBackOpacity() const { return back_opacity_; }
void setBackOpacity(int nback_opacity) { back_opacity_ = nback_opacity; }
int getContentsOpacity() const { return contents_opacity_; }
void setContentsOpacity(int ncontents_opacity) { contents_opacity_ = ncontents_opacity; }
int getOpenness() const { return openness_; }
void setOpenness(int nopenness) { openness_ = nopenness; }
bool isFullOpen() const { return openness_ == WINDOW_FULL_OPEN; }
private:
VALUE id_;
VALUE viewport_; // RGSS2
VALUE windowskin_;
VALUE contents_;
bool stretch_;
VALUE cursor_rect_;
bool active_;
bool visible_;
bool pause_;
int x_;
int y_;
int width_;
int height_;
int z_;
int ox_;
int oy_;
int opacity_;
int back_opacity_;
int contents_opacity_;
int openness_; // RGSS2
int cursor_frame_;
int pause_frame_;
int pause_id_;
}; // class Window
#endif // _WINDOW_VX_HXX_
|
[
"[email protected]"
] |
[
[
[
1,
124
]
]
] |
2a00e3e12fe35d1cb1fba36e2630dec91a9e2611
|
2d22825193eacf3669ac8bd7a857791745a9ead4
|
/HairSimulation/HairSimulation/include/AppUtilities.h
|
db225fb6536cb3158e89c534ff99bd9c2eb28939
|
[] |
no_license
|
dtbinh/com-animation-classprojects
|
557ba550b575c3d4efc248f7984a3faac8f052fd
|
37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e
|
refs/heads/master
| 2021-01-06T20:45:42.613604 | 2009-01-20T00:23:11 | 2009-01-20T00:23:11 | 41,496,905 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 814 |
h
|
#ifndef _APP_UTILITIES_H_
#define _APP_UTILITIES_H_
#include "AppPrerequisites.h"
#include <Ogre.h>
using namespace Ogre;
class Utilities
{
public:
//--------------Static methods----------------------------------------
/** Retrieve vertex data */
static
void getMeshInformation(const Ogre::MeshPtr mesh,
size_t &vertex_count,
Ogre::Vector3* &vertices,
size_t &index_count,
unsigned long* &indices,
const Ogre::Vector3 &position = Vector3::ZERO,
const Ogre::Quaternion &orient = Quaternion::IDENTITY,
const Ogre::Vector3 &scale = Vector3::UNIT_SCALE);
static
float getArea(Vector3& p1, Vector3& p2, Vector3& p3);
static
bool isInList(Vector3& v, std::vector<Vector3> vertexList);
};
#endif
|
[
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
] |
[
[
[
1,
30
]
]
] |
15f96fd7d9a573b6d6425c5714ceb782b601e41a
|
d81bbe5a784c804f59f643fcbf84be769abf2bc9
|
/Gosling/include/GosVisualizer2D.h
|
eed9c840fc37d03d1f4cc6f9d9269b5c029e9ca1
|
[] |
no_license
|
songuke/goslingviz
|
9d071691640996ee88171d36f7ca8c6c86b64156
|
f4b7f71e31429e32b41d7a20e0c151be30634e4f
|
refs/heads/master
| 2021-01-10T03:36:25.995930 | 2010-04-16T08:49:27 | 2010-04-16T08:49:27 | 36,341,765 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 830 |
h
|
#ifndef _GOS_VISUALIZER_2D_
#define _GOS_VISUALIZER_2D_
#include "GosMustHave.h"
#include "GosVisualizer.h"
#include "GosImage.h"
namespace Gos
{
/**
2D effects for visualization. Everything is drawn to an internal buffer.
The buffer is then drawn to window.
*/
class Visualizer2D : public Visualizer
{
public:
Visualizer2D(void);
virtual ~Visualizer2D(void);
public:
/**
Set buffer size. Buffer size should be larger than the rendered rect.
Usually buffer size is set to the area of visualization.
*/
void setBufferSize(int width, int height);
/**
Render to buffer then draw buffer to screen.
*/
void render(Chunk& c, Rect r);
protected:
/**
Render everything into buffer.
*/
virtual void renderBuffer(Chunk& c, Rect r) = 0;
protected:
Image* buffer;
};
}
#endif
|
[
"songuke@00dcdb3d-b287-7056-8bd8-84a1afe327dc"
] |
[
[
[
1,
43
]
]
] |
8ddec13b95160c4249fc016ea736845bc1e9867c
|
07f0b2dcc8370ab0adfe9bf2abebcaffdd1d618c
|
/suffix/Node.cpp
|
d2c618cd188740fff1f559b130a945f263aa0612
|
[] |
no_license
|
piotrjan01/pwaalproject
|
e01f7956e2e2acb3722215695b05371bc328b809
|
dd81bd128c6073c3eb29efbf902edde74c4d8138
|
refs/heads/master
| 2020-04-17T06:07:51.173243 | 2010-01-12T18:20:20 | 2010-01-12T18:20:20 | 33,796,679 | 0 | 0 | null | null | null | null |
WINDOWS-1250
|
C++
| false | false | 1,998 |
cpp
|
/*
* Node.cpp
*
* Implementacja klasy opisanej w pliku nagłówkowym
*
* Created on: 2010-01-07
* Author: Piotr Gwizdała
*/
#include "Node.h"
#include <utility>
Node::Node(SuffixTree* st, Node* suffixNode, Edge* parentEdge) {
this->tree = st;
this->id = st->getNextId();
this->suffixNode = suffixNode;
this->parentEdge = parentEdge;
this->leafCount = 0;
}
char Node::getCharAt(int ind) {
return this->tree->textArray[ind];
}
void Node::addEdge(int charIndex, Edge* edge) {
char c = this->getCharAt(charIndex);
this->nodeEdges[c] = edge;
}
void Node::removeEdge(int charIndex) {
//this->nodeEdges.erase(this->getCharAt(charIndex));
this->nodeEdges.remove(this->getCharAt(charIndex));
}
Edge* Node::findEdge(char c) {
return this->nodeEdges[c];
}
string Node::toString() {
stringstream ss;
ss<<this->id;//<<"\t"<<leafCount;
return ss.str();
}
bool Node::isLeaf() {
return (nodeEdges.size() == 0);
}
Node::~Node() {
}
void Node::updateLeafCount() {
QHash<char, Edge*>::iterator it;
if (isLeaf()) {
leafCount = 1;
return;
}
for (it = nodeEdges.begin(); it != nodeEdges.end(); it++) {
it.value()->endN->updateLeafCount(); //kontynuujemy
leafCount += it.value()->endN->leafCount;
}
}
list<Node*> Node::getAllNodes() {
list<Node*> ret;
ret.push_back(this);
QHash<char, Edge*>::iterator it;
for (it = nodeEdges.begin(); it != nodeEdges.end(); it++) {
list<Node*> ret2 = it.value()->endN->getAllNodes();
ret.splice(ret.end(), ret2);
}
return ret;
}
list<Edge*> Node::getAllEdges() {
list<Edge*> ret;
QHash<char, Edge*>::iterator it;
for (it = nodeEdges.begin(); it != nodeEdges.end(); it++) {
ret.push_back(it.value());
list<Edge*> ret2 = it.value()->endN->getAllEdges();
ret.splice(ret.end(), ret2);
}
return ret;
}
|
[
"gwizdek@ff063b32-fc41-11de-b5bc-ffd2847a4b57"
] |
[
[
[
1,
85
]
]
] |
cf16f406374218ca50087331dac185de4083083f
|
3ea8b8900d21d0113209fd02bd462310bd0fce83
|
/platform.h
|
5d1c87aceb14502da1d1f95c8428cd8fc64ccd7b
|
[] |
no_license
|
LazurasLong/bgmlib
|
56958b7dffd98d78f99466ce37c4abaddc7da5b1
|
a9d557ea76a383fae54dc3729aaea455c258777a
|
refs/heads/master
| 2022-12-04T02:58:36.450986 | 2011-08-16T17:44:46 | 2011-08-16T17:44:46 | null | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 2,565 |
h
|
// Music Room BGM Library
// ----------------------
// platform.h - The most basic includes
// ----------------------
// "©" Nmlgc, 2011
#ifndef BGMLIB_PLATFORM_H
#define BGMLIB_PLATFORM_H
// Definitions
// -----------
#define MIN(a, b) ((a) < (b) ? (a) : (b)) // Minimum
#define MAX(a, b) ((a) > (b) ? (a) : (b)) // Maximum
#define BETWEEN(a, b, c) ((a) > (b) && (a) < (c) ? true : false) // Checks if a is between b and c
#define BETWEEN_EQUAL(a, b, c) ((a) >= (b) && (a) <= (c) ? true : false) // Checks if a is between b and c or is equals b/c
#define SAFE_DELETE(x) {if(x) {delete (x); (x) = NULL;}} // Safe deletion
#define SAFE_DELETE_ARRAY(x) {if(x) {delete[] (x); (x) = NULL;}} // Safe deletion of an array
#define SAFE_FREE(x) {if(x) {free( (x) ); (x) = NULL;}} // Safe deletion of a malloc buffer
#define SINGLETON(Class) public: static Class& Inst() {static Class Inst; return Inst;}
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned char u8;
typedef unsigned int uint;
typedef unsigned long ulong;
// Platform dependant macros
#ifndef WIN32
// Unix File System
#define ZeroMemory(p, s) memset(p, 0, s)
#define DirSlash '/'
#define SlashString "/"
#define OtherDirSlash '\\'
#define OtherSlashString "\\"
const char LineEnd[1] = {'\n'};
const char OtherLineEnd[2] = {'\r', '\n'};
#else
// Windows File System
#define DirSlash '\\'
#define SlashString "\\"
#define OtherDirSlash '/'
#define OtherSlashString "/"
const char LineEnd[2] = {'\r', '\n'};
const char OtherLineEnd[1] = {'\n'};
#define FORMAT_INT64 "%I64d"
#define FORMAT_INT64_TIME "+%I64d"
#endif
const char LineBreak[2] = {'\r', '\n'};
const uchar utf8bom[3] = {0xEF, 0xBB, 0xBF};
const char Moonspace[3] = {(char)0xE3, (char)0x80, (char)0x80}; // Full-width space
// Error codes
enum mrerr
{
ERROR_FILE_ACCESS = -1,
ERROR_GENERIC = 0,
SUCCESS = 1,
};
#define TIMEOUT 5000000 // Short timeout sleeping time
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <fxdefs.h>
#include <FXString.h>
namespace FX
{
class FXFile;
}
#ifdef PROFILING_LIBS
// Enable timeGetTime() and QueryPerformanceCounter() profiling
#include <windows.h>
#include <mmsystem.h>
extern LARGE_INTEGER operator - (const LARGE_INTEGER& a, const LARGE_INTEGER& b);
extern LARGE_INTEGER operator + (const LARGE_INTEGER& a, const LARGE_INTEGER& b);
#endif
using namespace FX;
#endif /* BGMLIB_PLATFORM_H */
|
[
"[email protected]"
] |
[
[
[
1,
89
]
]
] |
c9266ce474fb79e5049c088bf472cb2214ee4114
|
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
|
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_hardware_serial_native.cpp
|
c15741fbb4f7ec178f611220f51b7f562cc16689
|
[
"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,766 |
cpp
|
//-----------------------------------------------------------------------------
//
// ** DO NOT EDIT THIS FILE! **
// This file was generated by a tool
// re-running the tool will overwrite this file.
//
//-----------------------------------------------------------------------------
#include "spot_hardware_serial_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::InternalOpen___VOID,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::InternalClose___VOID,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::Read___I4__SZARRAY_U1__I4__I4,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::Write___I4__SZARRAY_U1__I4__I4,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::InternalDispose___VOID,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::Flush___VOID,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::BytesInBuffer___I4__BOOLEAN,
Library_spot_hardware_serial_native_System_IO_Ports_SerialPort::DiscardBuffer___VOID__BOOLEAN,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Microsoft_SPOT_Hardware_SerialPort =
{
"Microsoft.SPOT.Hardware.SerialPort",
0x36DE26C1,
method_lookup
};
|
[
"[email protected]"
] |
[
[
[
1,
69
]
]
] |
96f6a5f11119c23dad5772209fe3f7e717a45e3a
|
4308e61561bc2b164dffc0b86b38b949d535f775
|
/AAA/LUA_Tests/main.cpp
|
06ffa7a983ded6cb2bc28d2ca0af46cd1954ae4b
|
[] |
no_license
|
GunioRobot/all
|
3526922dfd75047e78521f5716c1db2f3f299c38
|
22f5d77e12070dc6f60e9a39eb3504184360e061
|
refs/heads/master
| 2021-01-22T13:38:14.634356 | 2011-10-30T23:17:30 | 2011-10-30T23:17:30 | 2,995,713 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 664 |
cpp
|
#include <lua/lua.hpp>
#include <vector>
#include <cassert>
#include <algorithm>
std::vector<lua::Script> scripts;
bool running = true;
int lua_finish(lua_State *) {
running = false;
printf("lua_finish called\n");
return 0;
}
int main() {
lua_State* L = lua_open();
luaL_openlibs(L);
lua_register(L, "sleep", lua_sleep);
lua_register(L, "finish", lua_finish);
lua_queue_script(L, "scripts/init.lua");
lua_queue_script(L, "scripts/loop.lua");
float dt = 1.0f;
while (running) {
lua_run_frame(dt);
}
lua_queue_script(L, "scripts/end.lua");
lua_run_frame(dt);lua_run_frame(dt);
lua_close(L);
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
36
]
]
] |
9c5f84838dceddbfb5682db058d099dbec69db08
|
87cfed8101402f0991cd2b2412a5f69da90a955e
|
/daq/daq/src/mwwinsound/SoundDA.h
|
38938c0dd9c2ba34ecd571da1f9a685a1e1c1c26
|
[] |
no_license
|
dedan/clock_stimulus
|
d94a52c650e9ccd95dae4fef7c61bb13fdcbd027
|
890ec4f7a205c8f7088c1ebe0de55e035998df9d
|
refs/heads/master
| 2020-05-20T03:21:23.873840 | 2010-06-22T12:13:39 | 2010-06-22T12:13:39 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,851 |
h
|
// SoundDA.h: Definition of the SoundDA class
//
//////////////////////////////////////////////////////////////////////
// Copyright 1998-2003 The MathWorks, Inc.
// $Revision: 1.1.6.2 $ $Date: 2003/12/04 18:40:18 $
#if !defined(AFX_SOUNDDA_H__602F2105_DF66_11D1_A21D_00A024E7DC56__INCLUDED_)
#define AFX_SOUNDDA_H__602F2105_DF66_11D1_A21D_00A024E7DC56__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#pragma warning(disable:4996) // no warnings: CComModule::UpdateRegistryClass was declared deprecated
#include "resource.h" // main symbols
#include "buflist.h"
#include "adaptorkit.h"
#include "wavein.h"
#include "waveout.h"
#include "daqmex.h"
#include "util.h"
#include "thread.h"
/////////////////////////////////////////////////////////////////////////////
// SoundDA
class SoundDA :
public CSoundDevice,
public ImwOutput,
public CComObjectRoot,
public CComCoClass<SoundDA,&CLSID_SoundDA>
{
CWaveOutDevice _waveOutDevice;
BufferList _BufferList;
bool _running;
IntProp _bitsPerSample; // user settable
IntProp _standardSampleRates;
__int64 _samplesOutput;
__int64 _pointsQueued;
CWaveOutCaps WaveCaps;
UINT _id;
bool _lastBufferGap;
enum { HwChan=1, OUTPUTRANGE };
// static void CALLBACK waveOutProc(HWAVEOUT, UINT, SoundDA*, DWORD, DWORD);
Thread _thread;
int _isDying;
CEvent _BufferDoneEvent;
void CheckBuffersDone();
static unsigned WINAPI ThreadProc(void* pArg);
public:
SoundDA();
~SoundDA();
BOOL IsBufferDone ();
CComPtr<IProp> RegisterProperty(LPWSTR, DWORD);
//HRESULT SetDefaultRange(LPWSTR);
HRESULT SetDaqHwInfo();
static HRESULT WaveOutError(MMRESULT err);
BEGIN_COM_MAP(SoundDA)
COM_INTERFACE_ENTRY(ImwDevice)
COM_INTERFACE_ENTRY(ImwOutput)
END_COM_MAP()
//DECLARE_NOT_AGGREGATABLE(SoundDA)
// Remove the comment from the line above if you don't want your object to
// support aggregation.
DECLARE_REGISTRY(SoundDA,_T("mwwinsound.output.1"),_T("mwwinsound.output"),IDS_SOUNDDA_DESC,THREADFLAGS_BOTH);
// IOutput
public:
STDMETHOD(GetStatus)(hyper *samplesProcessed, BOOL *running);
HRESULT BufferReadyForDevice();
STDMETHOD(FreeBufferData)(BUFFER_ST*);
HRESULT Open(IDaqEngine*, int _id);
STDMETHOD(PutSingleValues)(VARIANT*) { return E_NOTIMPL;}
STDMETHOD(SetProperty)(long user, VARIANT * NewValue);
STDMETHOD(SetChannelProperty)(long User, tagNESTABLEPROP * pChan, VARIANT * NewValue);
STDMETHOD(Start)();
STDMETHOD(Stop)();
STDMETHOD(Trigger)();
};
#endif // !defined(AFX_SOUNDDA_H__602F2105_DF66_11D1_A21D_00A024E7DC56__INCLUDED_)
|
[
"[email protected]"
] |
[
[
[
1,
88
]
]
] |
596887c4b968739810e9c6e0d4b93ccbacb3ac5d
|
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
|
/Poker/Servidor/IteradorRonda.h
|
ed5eebb20365b03e6140624d1d398e437f214ab1
|
[] |
no_license
|
natlehmann/taller-2010-2c-poker
|
3c6821faacccd5afa526b36026b2b153a2e471f9
|
d07384873b3705d1cd37448a65b04b4105060f19
|
refs/heads/master
| 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 543 |
h
|
#ifndef _ITERADOR_RONDA_H_
#define _ITERADOR_RONDA_H_
#include <string>
#include "JugadorModelo.h"
#define MAX_CANTIDAD_JUGADORES 6
class IteradorRonda
{
protected:
JugadorModelo** jugadores;
int indiceInicial;
int indiceCorriente;
int indiceAnterior;
bool iniciado;
public:
IteradorRonda(JugadorModelo** jugadores, int indiceInicial);
virtual ~IteradorRonda(void);
virtual JugadorModelo* getSiguiente();
virtual bool esUltimo();
virtual void reset(int indiceInicial);
};
#endif //_ITERADOR_RONDA_H_
|
[
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296"
] |
[
[
[
1,
27
]
]
] |
c5e7f1c36d3559df71c8ad7aecf98e9a39f8475a
|
d752d83f8bd72d9b280a8c70e28e56e502ef096f
|
/FugueASM/pch.h
|
e30b88a5d53fb9de721a06867e7f8fd29148c24b
|
[] |
no_license
|
apoch/epoch-language.old
|
f87b4512ec6bb5591bc1610e21210e0ed6a82104
|
b09701714d556442202fccb92405e6886064f4af
|
refs/heads/master
| 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 644 |
h
|
//
// The Epoch Language Project
// FUGUE Bytecode assembler/disassembler
//
// Precompiled header - commonly used headers etc.
// All code modules should include this header.
//
#pragma once
#include <string>
#include <sstream>
#include <iostream>
// Platform-specific stuff
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Windows XP or later
#endif
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include "Utility/Exception.h"
#include "Utility/Types/IDTypes.h"
#include "Utility/Types/IntegerTypes.h"
#include "Utility/Types/RealTypes.h"
#include "Utility/Types/EpochTypeIDs.h"
|
[
"[email protected]"
] |
[
[
[
1,
31
]
]
] |
51ebc11a3aeaba66bfc8dffd3d9503cb7a0b8cee
|
6c8c4728e608a4badd88de181910a294be56953a
|
/CommunicationModule/OpensimIM/ChatMessage.h
|
3395195b75a2b0f9a35ffdfc59289dc7617deb01
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
caocao/naali
|
29c544e121703221fe9c90b5c20b3480442875ef
|
67c5aa85fa357f7aae9869215f840af4b0e58897
|
refs/heads/master
| 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,056 |
h
|
// For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_Communication_OpensimIM_ChatMessage_h
#define incl_Communication_OpensimIM_ChatMessage_h
//#include "Foundation.h"
//#include "NetworkEvents.h"
//#include "interface.h"
//#include "ChatSessionParticipant.h"
#include "CommunicationModuleFwd.h"
#include "ChatMessageInterface.h"
namespace OpensimIM
{
class ChatMessage : public Communication::ChatMessageInterface
{
public:
ChatMessage(ChatSessionParticipant* originator, const QDateTime& time_stamp, const QString &text);
virtual ~ChatMessage() {};
virtual Communication::ChatSessionParticipantInterface* GetOriginator() const;
virtual QDateTime GetTimeStamp() const;
virtual QString GetText() const;
private:
ChatSessionParticipant* originator_;
const QDateTime time_stamp_;
const QString text_;
};
} // end of namespace: OpensimIM
#endif // incl_Communication_OpensimIM_ChatMessage_h
|
[
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3"
] |
[
[
[
1,
2
],
[
17,
24
],
[
26,
31
]
],
[
[
3,
5
],
[
10,
10
],
[
13,
16
],
[
25,
25
],
[
32,
34
]
],
[
[
6,
9
],
[
11,
12
]
]
] |
f5543f88f8b6caeb2ddb4a3ad31905a0dec76d29
|
447a1817531f5eff55925709ff1cdde37033cf79
|
/src/map/loaders/quake3_bsp_map.h
|
7b69d970713e5b7f00a287c05f4e61a6f13869d7
|
[] |
no_license
|
Kazade/kazengine
|
63276feef92f7daae5ac10563589bb5b87233644
|
0723eb6f22e651f9ea2d110b00b3f4c5d94465d5
|
refs/heads/master
| 2020-03-31T12:12:58.501020 | 2008-08-14T20:14:44 | 2008-08-14T20:14:44 | 32,983 | 4 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,392 |
h
|
#ifndef QUAKE3_BSP_MAP_H_INCLUDED
#define QUAKE3_BSP_MAP_H_INCLUDED
#include <map>
#include "map/bsp_map.h"
using std::map;
struct quake3_point_i{
int x, y, z;
operator int* () {
return reinterpret_cast<int*>(this);
}
operator const int* () {
return reinterpret_cast<const int*> (this);
}
};
struct quake3_point_3f {
float x, y, z;
};
struct quake3_point_2f {
float x, y;
};
struct quake3_header {
char bsp_id[4];
int version;
};
enum quake3_file_offsets {
iEntitiesOffset = 0,
iTextureOffset,
iPlanesOffset,
iNodesOffset,
iLeafOffset,
iLeafFacesOffset,
iLeafBrushesOffset,
iModelsOffset,
iBrushesOffset,
iBrushesSidesOffset,
iVerticesOffset,
iMeshVerticesOffset,
iShaderFilesOffset,
iFacesOffset,
iLightMapsOffset,
iLightVolumeOffset,
iVisibleDataOffset,
iMaxLumpsOffset
};
struct quake3_file_lump {
int offset;
int length;
};
struct quake3_entity {
map<string, string> attributes;
};
struct quake3_vertex {
quake3_point_3f position; //! Position of vertex
quake3_point_2f texCoord; //! (u,v) Texturecoordinate of detailtexture
quake3_point_2f lightmap; //! (u,v) Texturecoordinate of lightmap
quake3_point_3f normal; //! vertex normale
unsigned char color[4]; //! Color in RGBA
};
//! \struct A face in bsp format info
struct quake3_face {
int texID;
int effect;
int type;
int startVertexIndex;
int totalVertices;
int meshVertexIndex;
int totalMeshVertices;
int lightmapID;
int lightMapCorner[2];
int lightMapSize[2];
quake3_point_3f lightMapPos;
quake3_point_3f lightMapVectors[2];
quake3_point_3f normal;
int size[2];
};
struct quake3_texture {
char file[64];
int flags;
int contents;
};
struct quake3_lightmap {
unsigned char lightMap[128][128][3];
};
struct quake3_bsp_node {
int planeIndex;
int frontIndex;
int backIndex;
quake3_point_i aabbMin;
quake3_point_i aabbMax;
};
struct quake3_bsp_leaf {
int cluster;
int portal;
quake3_point_i aabbMin;
quake3_point_i aabbMax;
int faceIndex;
int totalFaces;
int brushIndex;
int totalBrushes;
};
struct quake3_brush {
int brushside; // First brushside for brush.
int brushside_count; // Number of brushsides for brush.
int texture; // Texture index.
};
struct quake3_plane {
float normal[3];
float dist;
};
struct quake3_map_model {
float mins[3]; // Bounding box min coord.
float maxs[3]; // Bounding box max coord.
int face; // First face for model.
int face_count; // Number of faces for model.
int brush; // First brush for model.
int brush_count; // Number of brushes for model.
};
struct quake3_brushside {
int plane; // Plane index.
int texture; // Texture index.
};
struct quake3_bsp_cluster {
int totalClusters;
int size;
vector<unsigned char> bitSet;
};
struct quake3_effect {
char name[64]; // Effect shader.
int brush; // Brush that generated this effect.
int unknown; // Always 5, except in q3dm8, which has one effect with -1.
};
struct quake3_lightvol {
unsigned char ambient[3];
unsigned char directional[3];
unsigned char dir[2];
};
class quake3_subpatch {
public:
quake3_subpatch();
vector<map_vertex>& getVertices() { return m_vertices; }
map_vertex* get_control_points() { return m_control_points; }
void set_l(int l) { L = l; }
int get_l() { return L; }
void tesselate_vertices();
void calculate_indices();
void append_triangles_to_array(vector<map_vertex>& vertices);
private:
vector<map_vertex> m_vertices;
vector<unsigned int> m_indices;
map_vertex m_control_points[9];
int L;
};
/**
Loads a Quake3 map
*/
class quake3_bsp_map : public bsp_map {
public:
quake3_bsp_map(resource_manager_interface* owning_manager);
file_load_status load(istream& stream);
void unload();
string get_last_error();
private:
bool load_and_check_header(istream& stream);
void read_lumps(istream& stream);
void read_entities(istream& stream);
void read_vertices(istream& stream);
void read_faces(istream& stream);
void read_face_indices(istream& stream);
void read_textures(istream& stream);
void read_lightmaps(istream& stream);
void read_bsp_nodes(istream& stream);
void read_bsp_leaves(istream& stream);
void read_bsp_leaf_faces(istream& stream);
void read_bsp_leaf_brushes(istream& stream);
void read_planes(istream& stream);
void read_models(istream& stream);
void read_brushes(istream& stream);
void read_brushsides(istream& stream);
void read_effects(istream& stream);
void read_lightvols(istream& stream);
void read_visibility_data(istream& stream);
quake3_header m_header;
vector<quake3_file_lump> m_lumps;
vector<quake3_entity> m_entities;
vector<char> m_raw_entity_data;
vector<quake3_vertex> m_raw_vertex_data;
vector<quake3_face> m_raw_face_data;
vector<unsigned int> m_raw_face_index_data;
vector<quake3_texture> m_raw_texture_data;
vector<quake3_lightmap> m_raw_lightmap_data;
vector<quake3_bsp_node> m_raw_bsp_node_data;
vector<quake3_bsp_leaf> m_raw_bsp_leaf_data;
vector<int> m_raw_bsp_leaf_face_data;
vector<int> m_raw_bsp_leaf_brush_data;
vector<quake3_plane> m_raw_plane_data;
vector<quake3_map_model> m_raw_model_data;
vector<quake3_brush> m_raw_brush_data;
vector<quake3_brushside> m_raw_brushsides;
vector<quake3_effect> m_raw_effect_data;
vector<quake3_lightvol> m_raw_lightvol_data;
quake3_bsp_cluster m_raw_cluster_data;
string m_last_error;
template <typename T>
bool read_chunk_into_vector(istream& stream, vector<T>& vec, size_t count, quake3_file_offsets offset);
template <typename T>
void swap_axis(T& v);
void print_statistics();
void do_post_load();
void convert_vertices();
void convert_faces();
void convert_and_load_textures();
void convert_bsp_data();
void add_normal_face(const quake3_face& f);
void add_curved_surface(const quake3_face& f);
void add_mesh_surface(const quake3_face& f);
};
template <typename T>
bool quake3_bsp_map::read_chunk_into_vector(istream& stream, vector<T>& vec, size_t count, quake3_file_offsets offset) {
stream.seekg(m_lumps[offset].offset, std::ios_base::beg);
vec.resize(count);
stream.read(reinterpret_cast<char*>(&vec[0]), count * sizeof(T));
return true;
}
template <typename T>
void quake3_bsp_map::swap_axis(T& v) {
float temp = v.y;
v.y = v.z;
v.z = -temp;
}
#endif // QUAKE3_BSP_MAP_H_INCLUDED
|
[
"luke@helium.(none)"
] |
[
[
[
1,
279
]
]
] |
7d71f87398578952113cb516bd75a59f637f5ef4
|
5ac13fa1746046451f1989b5b8734f40d6445322
|
/minimangalore/Nebula2/code/nebula2/src/gui/nguimessagebox_main.cc
|
4fa5f35100e2aed70e056234fe03ea67cedc64b4
|
[] |
no_license
|
moltenguy1/minimangalore
|
9f2edf7901e7392490cc22486a7cf13c1790008d
|
4d849672a6f25d8e441245d374b6bde4b59cbd48
|
refs/heads/master
| 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,802 |
cc
|
//------------------------------------------------------------------------------
// nguimessagebox_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gui/nguimessagebox.h"
#include "gui/nguievent.h"
#include "gui/nguiserver.h"
#include "gui/nguiskin.h"
#include "gui/nguibutton.h"
nNebulaClass(nGuiMessageBox, "nguiclientwindow");
//------------------------------------------------------------------------------
/**
*/
nGuiMessageBox::nGuiMessageBox() :
okText("Ok"),
cancelText("Cancel"),
type(Ok),
autoSize(false)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nGuiMessageBox::~nGuiMessageBox()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiMessageBox::OnShow()
{
nGuiSkin* skin = nGuiServer::Instance()->GetSkin();
n_assert(skin);
this->SetMovable(true);
this->SetResizable(false);
this->SetCloseButton(false);
if (0 == this->GetDefaultBrush())
{
this->SetDefaultBrush("bgmessagebox");
}
nGuiClientWindow::OnShow();
// get client area layout object
nGuiFormLayout* layout = this->refFormLayout.get();
kernelServer->PushCwd(layout);
// message text field
nGuiTextLabel* textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "TextLabel");
n_assert(textLabel);
textLabel->SetText(this->GetMessageText());
textLabel->SetFont(skin->GetWindowFont());
textLabel->SetColor(skin->GetTextColor());
textLabel->SetClipping(false);
textLabel->SetAlignment(nGuiTextLabel::Center);
textLabel->SetWordBreak(true);
textLabel->SetVCenter(true);
//textfield layout
layout->AttachForm(textLabel, nGuiFormLayout::Top, 0.0f);
if (!this->iconBrush.IsEmpty())
{
// add optional icon
vector2 iconSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize(this->iconBrush.Get());
nGuiButton* iconButton = (nGuiButton*) kernelServer->New("nguibutton", "iconbutton");
n_assert(iconButton);
iconButton->SetDisabledBrush(this->iconBrush.Get());
iconButton->SetMinSize(iconSize);
iconButton->SetMaxSize(iconSize);
iconButton->Disable(); // use it as a icon - so disable it.
iconButton->OnShow();
this->refIconButton = iconButton;
layout->AttachForm(iconButton, nGuiFormLayout::Left, -0.007f);
layout->AttachForm(iconButton, nGuiFormLayout::Top, -0.01f);
//textfield layout
layout->AttachWidget(textLabel, nGuiFormLayout::Left, iconButton, 0.0f);
}
else
{
//textfield layout
layout->AttachForm(textLabel, nGuiFormLayout::Left, 0.0f);
}
vector2 buttonSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("button_n");
// create ok button
if (this->type != NoButtons)
{
if ((OkCancel == this->type) || (Ok == this->type))
{
nGuiTextButton* okButton = (nGuiTextButton*) kernelServer->New("nguitextbutton", "OkButton");
n_assert(okButton);
okButton->SetText(this->GetOkText());
okButton->SetFont(skin->GetButtonFont());
okButton->SetAlignment(nGuiTextButton::Center);
okButton->SetDefaultBrush("button_n");
okButton->SetPressedBrush("button_p");
okButton->SetHighlightBrush("button_h");
okButton->SetMinSize(buttonSize);
okButton->SetMaxSize(buttonSize);
okButton->SetColor(skin->GetButtonTextColor());
if (this->iconBrush.IsEmpty())
{
if (Ok == this->type)
{
layout->AttachPos(okButton, nGuiFormLayout::HCenter, 0.5f);
}
else
{
layout->AttachForm(okButton, nGuiFormLayout::Left, 0.005f);
}
}
else
{
layout->AttachWidget(okButton, nGuiFormLayout::Left, this->refIconButton, 0.005f);
}
layout->AttachForm(okButton, nGuiFormLayout::Bottom, 0.005f);
okButton->OnShow();
this->refOkButton = okButton;
//textfield layout
layout->AttachForm(textLabel, nGuiFormLayout::Right, 0.005f);
layout->AttachWidget(textLabel, nGuiFormLayout::Bottom, okButton, 0.005f);
}
// create cancel button
if (OkCancel == this->type)
{
nGuiTextButton* cancelButton = (nGuiTextButton*) kernelServer->New("nguitextbutton", "CancelButton");
n_assert(cancelButton);
cancelButton->SetText(this->GetCancelText());
cancelButton->SetFont(skin->GetButtonFont());
cancelButton->SetAlignment(nGuiTextButton::Center);
cancelButton->SetDefaultBrush("button_n");
cancelButton->SetPressedBrush("button_p");
cancelButton->SetHighlightBrush("button_h");
cancelButton->SetMinSize(buttonSize);
cancelButton->SetMaxSize(buttonSize);
cancelButton->SetColor(skin->GetButtonTextColor());
layout->AttachForm(cancelButton, nGuiFormLayout::Right, 0.005f);
layout->AttachForm(cancelButton, nGuiFormLayout::Bottom, 0.005f);
cancelButton->OnShow();
this->refCancelButton = cancelButton;
}
}
else
{
//textfield layout
layout->AttachForm(textLabel, nGuiFormLayout::Right, 0.005f);
layout->AttachForm(textLabel, nGuiFormLayout::Bottom, 0.005f);
}
textLabel->OnShow();
this->refTextLabel = textLabel;
kernelServer->PopCwd();
// compute our size
vector2 windowSize;
windowSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize(this->GetDefaultBrush());
if (this->autoSize)
{
vector2 msgSize = textLabel->GetTextExtent() * 1.2f;
if (msgSize.x > windowSize.x)
{
windowSize.x = msgSize.x;
}
if (msgSize.y > windowSize.y)
{
windowSize.y = msgSize.y;
}
}
vector2 windowPos = vector2(0.5f, 0.5f) - (windowSize * 0.5f);
rectangle windowRect(windowPos, windowPos + windowSize);
this->SetMinSize(windowSize);
this->SetMaxSize(windowSize);
this->SetRect(windowRect);
this->UpdateLayout(this->rect);
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiMessageBox::OnHide()
{
if (this->refTextLabel.isvalid())
{
this->refTextLabel->Release();
n_assert(!this->refTextLabel.isvalid());
}
if (this->refOkButton.isvalid())
{
this->refOkButton->Release();
n_assert(!this->refOkButton.isvalid());
}
if (this->refCancelButton.isvalid())
{
this->refCancelButton->Release();
n_assert(!this->refCancelButton.isvalid());
}
if (this->refIconButton.isvalid())
{
this->refIconButton->Release();
n_assert(!this->refIconButton.isvalid());
}
nGuiClientWindow::OnHide();
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiMessageBox::OnEvent(const nGuiEvent& event)
{
// check for Ok
if (this->refOkButton.isvalid())
{
if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refOkButton.get()))
{
this->SetCloseRequested(true);
this->OnOk();
nGuiServer::Instance()->PutEvent(nGuiEvent(this, nGuiEvent::DialogOk));
}
}
if (this->refCancelButton.isvalid())
{
if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refCancelButton.get()))
{
this->SetCloseRequested(true);
this->OnCancel();
nGuiServer::Instance()->PutEvent(nGuiEvent(this, nGuiEvent::DialogCancel));
}
}
nGuiClientWindow::OnEvent(event);
}
//------------------------------------------------------------------------------
/**
Called when the Ok button is pressed. Optionally override this
method in a subclass.
*/
void
nGuiMessageBox::OnOk()
{
// empty
}
//------------------------------------------------------------------------------
/**
Called when the Cancel button is pressed. Optionally override this
method in a subclass.
*/
void
nGuiMessageBox::OnCancel()
{
// empty
}
|
[
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] |
[
[
[
1,
275
]
]
] |
fdd9f92a2df71dcc39c8897725f3555691eb8bd1
|
c702a7cfde317b06c0dba966c8b45918e6127144
|
/Jogador.cpp
|
f2acaa513c6c1ae38bbdc31f26c299c5fe9d10e9
|
[] |
no_license
|
cmdalbem/titiapus
|
1210d2c45a53a5cdfbe1d72e10ef2c5dd87d668d
|
567fc84f8203698e16401f7e178df5bd979adcfb
|
refs/heads/master
| 2021-01-22T14:32:47.033180 | 2010-11-25T13:20:53 | 2010-11-25T13:20:53 | 32,189,770 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 266 |
cpp
|
#include "Jogador.h"
Jogador::Jogador(cor time, tipoJogador novoTipo, Estado &estadoAtual) : meuTime(time), tipo(novoTipo), estadoJogo(estadoAtual){}
Jogador::~Jogador() {}
void Jogador::setaEstadoAtual(Estado &estadoAtual)
{
estadoJogo = estadoAtual;
}
|
[
"lucapus@5e43c5b1-3cc6-e38b-4c49-94f38ad1f185",
"ninja.dalbem@5e43c5b1-3cc6-e38b-4c49-94f38ad1f185"
] |
[
[
[
1,
2
],
[
4,
5
],
[
7,
7
],
[
9,
9
]
],
[
[
3,
3
],
[
6,
6
],
[
8,
8
]
]
] |
65073bcc6395238de80c071315b29a7a5674796b
|
25233569ca21bf93b0d54ca99027938d65dc09d5
|
/Font.cpp
|
74cd84ccd1e7bc6a6079956108d22888bdff0a34
|
[] |
no_license
|
jugg/litestep-module-label
|
6ede7ff5c80c25e1dc611d02ba5dc13559914ddc
|
a75ef94a56d68c2a928bde5bab60318e609b9a10
|
refs/heads/master
| 2021-01-18T09:20:42.000147 | 2004-10-07T12:28:00 | 2004-10-07T12:28:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,891 |
cpp
|
#include "common.h"
#include "Font.h"
Font::Font()
{
hFont = 0;
}
Font::~Font()
{
if(hFont != 0)
DeleteObject(hFont);
}
void Font::configure(const string &prefix, Font *baseFont)
{
shadow = GetRCBoolean(prefix, "FontShadow", baseFont ? baseFont->shadow : false);
shadowColor = GetRCColor(prefix, "FontShadowColor", baseFont ? baseFont->shadowColor : RGB(0, 0, 0));
shadowX = GetRCInt(prefix, "FontShadowX", baseFont ? baseFont->shadowX : 1);
shadowY = GetRCInt(prefix, "FontShadowY", baseFont ? baseFont->shadowY : 1);
name = GetRCString(prefix, "Font", baseFont ? baseFont->name : "Arial");
height = GetRCInt(prefix, "FontHeight", baseFont ? baseFont->height : 15, 0);
color = GetRCColor(prefix, "FontColor", baseFont ? baseFont->color : (shadow ? RGB(255, 255, 255) : RGB(0, 0, 0)));
bold = GetRCBoolean(prefix, "FontBold", baseFont ? baseFont->bold : false);
italic = GetRCBoolean(prefix, "FontItalic", baseFont ? baseFont->italic : false);
}
void Font::apply(HDC hDC, int x, int y, int width, int height, const string &text, unsigned int flags)
{
if(hFont == 0)
createHandle();
RECT r;
r.left = x;
r.top = y;
r.right = x + width;
r.bottom = y + height;
hFont = (HFONT) SelectObject(hDC, hFont);
int bkMode = SetBkMode(hDC, TRANSPARENT);
int textColor = SetTextColor(hDC, color);
DrawTextEx(hDC, (char *) text.c_str(), text.length(), &r, flags | DT_CALCRECT, 0);
int neededHeight = r.bottom - r.top;
int vPad = (height - neededHeight) / 2;
r.left = x;
r.top = y + vPad;
r.right = x + width;
r.bottom = y + neededHeight + vPad;
if(shadow)
{
OffsetRect(&r, (shadowX + 1) / 2, (shadowY + 1) / 2);
SetTextColor(hDC, shadowColor);
DrawTextEx(hDC, (char *) text.c_str(), text.length(), &r, flags, 0);
OffsetRect(&r, -shadowX, -shadowY);
}
SetTextColor(hDC, color);
DrawTextEx(hDC, (char *) text.c_str(), text.length(), &r, flags, 0);
hFont = (HFONT) SelectObject(hDC, hFont);
SetBkMode(hDC, bkMode);
SetTextColor(hDC, textColor);
}
void Font::measure(HDC hDC, const string &text, unsigned int flags, long *width, long *height)
{
hFont = (HFONT) SelectObject(hDC, hFont);
LPSIZE lpsize=new SIZE;
lpsize->cx=300;
lpsize->cy=100;
GetTextExtentPoint32(hDC, text.c_str(), strlen(text.c_str()), lpsize);
hFont = (HFONT) SelectObject(hDC, hFont);
*width=lpsize->cx;
*height=lpsize->cy;
delete lpsize;
}
void Font::setColor(int aColor)
{
color = aColor;
}
void Font::createHandle()
{
LOGFONT lf;
memset(&lf, 0, sizeof(LOGFONT));
StringCchCopy(lf.lfFaceName, LF_FACESIZE, name.c_str());
lf.lfHeight = height;
lf.lfItalic = italic ? TRUE : FALSE;
lf.lfWeight = bold ? FW_BOLD : FW_NORMAL;
lf.lfCharSet = DEFAULT_CHARSET;
if(hFont != 0)
DeleteObject(hFont);
hFont = CreateFontIndirect(&lf);
}
|
[
"[email protected]"
] |
[
[
[
1,
111
]
]
] |
9e0d7b400345dadfd02ed5f8ce3ff83c37f08d7c
|
52ccb019a9fb2187413a976b136ea3b29357505a
|
/bin2h/bin2h.cpp
|
164d38f469586792b02297aa48cdf1b29556e869
|
[] |
no_license
|
TCCinTaiwan/bin2h
|
404de58e87b75e62e7d126d33e594836b34580e7
|
6695a1980aa606cb359b2b54de571118d6d89022
|
refs/heads/master
| 2016-08-12T11:46:57.952666 | 2011-03-02T00:02:12 | 2011-03-02T00:02:12 | 53,474,853 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,675 |
cpp
|
/*
Copyright (c) 2011, Matt Gordon
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of 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 "targetver.h"
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h> //for TEXT macro
#include <tchar.h>
#include <string>
#include <iostream>
#include <fstream>
//map STL string and c-out to TCHAR
typedef std::basic_string<TCHAR> tstring;
#ifdef UNICODE
#define tcout std::wcout
//capital S maps unicode down to ASCII for consistent output format.
static const char* kCommentFormat = "//file auto-generated from %S by bin2h.exe\n";
static const char* kNamespaceFormat = "namespace %S \n{\n";
static const char* kIdentifierFormat = "%S";
#else
#define tcout std::cout
static const char* kCommentFormat = "//file auto-generated from %s by bin2h.exe\n";
static const char* kNamespaceFormat = "namespace %s \n{\n";
static const char* kIdentifierFormat = "%s";
#endif
//prints help to stdout
void Help()
{
std::cout << "bin2h utility v1.01\n\n";
std::cout << "Interprets any file as plain binary data and dumps to a raw C/C++ array.\n";
std::cout << "usage: bin2h <in-file> <out-file> <opt-args>\n\n";
std::cout << "valid optional arguments:\n";
std::cout << "-id=<name> the C array is identified as \"name\". identifier is \"data\" if this argument is not present. bin2h does not check the identifier is valid in C/C++.\n";
std::cout << "-ns=<namespace> causes the data to be wrapped in a namespace. no namespace is inserted if this argument is not used.\n";
}
//checks if main() argument looks like it might be an (optional) argument
bool IsArg(_TCHAR* arg)
{
return (_tcsncmp(arg, TEXT("-"), 1) == 0);
}
struct Arguments
{
tstring ns;
tstring id;
Arguments() : id(TEXT("data")) {}
};
//read in optional arguments from the command line
void ReadArgs(int argc, int start, _TCHAR* argv[], Arguments& outArgs)
{
for(int i=start; i<argc; ++i)
{
if(_tcsncmp(argv[i], TEXT("-id="), 4) == 0)
{
outArgs.id = argv[i] + 4; //highly dubious against TCHARs, but oh well...
}
else if(_tcsncmp(argv[i], TEXT("-ns="), 4) == 0)
{
outArgs.ns = argv[i] + 4;
}
}
}
//so far as tchar-ness goes, the output should always be purely narrow character (native codepage).
//the program itself should compile for either narrow or unicode mode.
int _tmain(int argc, _TCHAR* argv[])
{
//argv 1 should be a valid filename, and argv 2 is optionally something that a output stream
//can be opened against. after that, options.
if(argc < 2 || IsArg(argv[1]))
{
Help();
return 0;
}
bool bFileout = argc >2 && !IsArg(argv[2]);
//check input file can be opened
std::ifstream in(argv[1], std::ios_base::binary);
if(!in.is_open())
{
tcout << L"couldn't open " << argv[1] << L" for reading.\n\n";
Help();
return 0;
}
//check output file can be opened
std::ofstream outfile;
if(bFileout)
{
outfile.open(argv[2], std::ios_base::trunc);
if(!outfile.is_open())
{
tcout << L"couldn't open " << argv[2] << L"for writing.\n\n";
Help();
in.close();
return 0;
}
}
//stream to the output file, or std out if no file was provided
std::ostream& out = outfile.is_open() ? outfile : std::cout;
Arguments A;
ReadArgs(argc, bFileout ? 2:1, argv, A);
//write out pre-amble
//insert a comment to indicate that this file was auto generated from some other file
{
char out_buffer[1024];
int sprintf_count = sprintf_s(out_buffer, kCommentFormat, argv[1]);
out.write(out_buffer, sprintf_count);
}
bool bWroteNamespace = false;
if(!A.ns.empty())
{
char out_buffer[1024];
int sprintf_count = sprintf_s(out_buffer, kNamespaceFormat, A.ns.c_str());
out.write(out_buffer, sprintf_count);
bWroteNamespace = true;
}
//usual cheese to get file size
in.seekg(0, std::ios_base::end);
size_t filesize = in.tellg();
in.seekg(0, std::ios_base::beg);
//same trick as for namespace to get the id out
{
char out_buffer[1024];
int sprintf_count = sprintf_s(out_buffer, kIdentifierFormat, A.id.c_str());
//array size, for use in code
out << "size_t ";
out.write(out_buffer, sprintf_count);
out << "_len = " << filesize << ";" << std::endl;
//and now, the array
out << "unsigned char ";
out.write(out_buffer, sprintf_count);
}
out << "[" << filesize << "]=\n{\n\t";
//stream the data through
int restart = 0;
for(unsigned i=0; i<filesize; )
{
static const size_t bufferLen = 1024;
//buffer has to be unsigned for the sprintf to work as required.
unsigned char in_buffer[bufferLen];
const size_t chunk = i+bufferLen < filesize ? bufferLen : filesize-i;
in.read(reinterpret_cast<char*>(in_buffer), chunk);
for(unsigned j=0; j<chunk; ++j)
{
char out_buffer[128];
sprintf_s(out_buffer, "0x%.2hX,", in_buffer[j]);
out << out_buffer;
++restart;
if(restart > 10)
{
out << "\n\t";
restart = 0;
}
}
i += chunk;
}
//post-amble - close array, then namespace
out << "\n};\n";
if(bWroteNamespace)
{
out << "}//end namespace\n";
}
if(outfile.is_open())
outfile.close();
in.close();
return 0;
}
|
[
"Matt Gordon ([email protected])"
] |
[
[
[
1,
228
]
]
] |
564b71ab12f66110911c046b09072b5907c17df2
|
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
|
/mytesgnikrow --username hotga2801/Project/FaceDetect_V1.3/CascadeClassifier.cpp
|
38f961fc21fca96ae68536802a3bdb462b37a178
|
[] |
no_license
|
taicent/mytesgnikrow
|
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
|
9264faa662454484ade7137ee8a0794e00bf762f
|
refs/heads/master
| 2020-04-06T04:25:30.075548 | 2011-02-17T13:37:16 | 2011-02-17T13:37:16 | 34,991,750 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,058 |
cpp
|
#include "stdafx.h"
#include <fstream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <mmsystem.h>
using namespace std;
#include "IntImage.h"
#include "SimpleClassifier.h"
#include "AdaBoostClassifier.h"
#include "CascadeClassifier.h"
#include "Global.h"
#include "FFS.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CascadeClassifier::CascadeClassifier():count(0),ac(NULL)
{
}
CascadeClassifier::~CascadeClassifier()
{
Clear();
}
void CascadeClassifier::Clear()
{
count = 0;
delete[] ac; ac=NULL;
}
CascadeClassifier& CascadeClassifier::operator=(const CascadeClassifier& source)
{
Clear();
count = source.count;
ac = new AdaBoostClassifier[max_nodes]; ASSERT(ac!=NULL);
for(int i=0;i<count;i++) ac[i] = source.ac[i];
return *this;
}
void CascadeClassifier::ReadFromFile(ifstream& f)
{
Clear();
f>>count; f.ignore(256,'\n');
ac = new AdaBoostClassifier[max_nodes]; ASSERT(ac!=NULL);
for(int i=0;i<count;i++) ac[i].ReadFromFile(f);
}
void CascadeClassifier::WriteToFile(ofstream& f) const
{
f<<count<<endl;
for(int i=0;i<count;i++) ac[i].WriteToFile(f);
}
void CascadeClassifier::LoadDefaultCascade()
{
ifstream f;
f.open(cascade_filename);
ReadFromFile(f);
f.close();
}
void CascadeClassifier::DrawResults(IntImage& image,const vector<CRect>& results) const
{
int i;
unsigned int k;
int x1,x2,y1,y2;
for(k=0;k<results.size();k++)
{
y1 = (results[k].top>=0)?results[k].top:0;
y1 = (results[k].top<image.height)?results[k].top:(image.height-1);
y2 = (results[k].bottom>=0)?results[k].bottom:0;
y2 = (results[k].bottom<image.height)?results[k].bottom:(image.height-1);
x1 = (results[k].left>=0)?results[k].left:0;
x1 = (results[k].left<image.width)?results[k].left:(image.width-1);
x2 = (results[k].right>=0)?results[k].right:0;
x2 = (results[k].right<image.width)?results[k].right:(image.width-1);
for(i=y1;i<=y2;i++)
{
image.data[i][x1] = 255;
image.data[i][x2] = 255;
}
for(i=x1;i<=x2;i++)
{
image.data[y1][i] = 255;
image.data[y2][i] = 255;
}
}
}
const int CascadeClassifier::ApplyImagePatch(const IntImage& im) const
{
for(int i=0;i<count;i++) if(ac[i].ApplyImagePatch(im)==0) return 0;
return 1;
}
void CascadeClassifier::ApplyOriginalSize(IntImage& original,const CString filename)
{
IntImage procface;
IntImage image,square;
REAL sq,ex,value;
int result;
CRect rect;
REAL ratio;
vector<CRect> results;
procface.Copy(original);
ratio = 1.0;
results.clear();
REAL paddedsize = REAL(1)/REAL((sx+1)*(sy+1));
while((procface.height>sx+1) && (procface.width>sy+1))
{
procface.CalcSquareAndIntegral(square,image);
for(int i=0,size_x=image.height-sx;i<size_x;i+=1)
for(int j=0,size_y=image.width-sy;j<size_y;j+=1)
{
ex = image.data[i+sx][j+sy]+image.data[i][j]-image.data[i+sx][j]-image.data[i][j+sy];
if(ex<mean_min || ex>mean_max) continue;
sq = square.data[i+sx][j+sy]+square.data[i][j]-square.data[i+sx][j]-square.data[i][j+sy];
if(sq<sq_min) continue;
ex *= paddedsize;
ex = ex * ex;
sq *= paddedsize;
sq = sq - ex;
ASSERT(sq>=0);
if(sq>0) sq = sqrt(sq); else sq = 1.0;
if(sq<var_min) continue;
result = 1;
for(int k=0;k<count;k++)
{
value = 0.0;
for(int t=0,size=ac[k].count;t<size;t++)
{
REAL f1 = 0;
REAL** p = image.data + i;
SimpleClassifier& s = ac[k].scs[t];
switch(s.type)
{
case 0:
f1 = p[s.x1][j+s.y3] - p[s.x1][j+s.y1] + p[s.x3][j+s.y3] - p[s.x3][j+s.y1]
+ REAL(2)*(p[s.x2][j+s.y1] - p[s.x2][j+s.y3]);
break;
case 1:
f1 = p[s.x3][j+s.y1] + p[s.x3][j+s.y3] - p[s.x1][j+s.y1] - p[s.x1][j+s.y3]
+ REAL(2)*(p[s.x1][j+s.y2] - p[s.x3][j+s.y2]);
break;
case 2:
f1 = p[s.x1][j+s.y1] - p[s.x1][j+s.y3] + p[s.x4][j+s.y3] - p[s.x4][j+s.y1]
+ REAL(3)*(p[s.x2][j+s.y3] - p[s.x2][j+s.y1] + p[s.x3][j+s.y1] - p[s.x3][j+s.y3]);
break;
case 3:
f1 = p[s.x1][j+s.y1] - p[s.x1][j+s.y4] + p[s.x3][j+s.y4] - p[s.x3][j+s.y1]
+ REAL(3)*(p[s.x3][j+s.y2] - p[s.x3][j+s.y3] + p[s.x1][j+s.y3] - p[s.x1][j+s.y2]);
break;
case 4:
f1 = p[s.x1][j+s.y1] + p[s.x1][j+s.y3] + p[s.x3][j+s.y1] + p[s.x3][j+s.y3]
- REAL(2)*(p[s.x2][j+s.y1] + p[s.x2][j+s.y3] + p[s.x1][j+s.y2] + p[s.x3][j+s.y2])
+ REAL(4)*p[s.x2][j+s.y2];
break;
default:
#ifndef DEBUG
__assume(0);
#else
;
#endif
}
if(s.parity!=0)
if(f1<sq*s.thresh)
value += ac[k].alphas[t];
else ;
else
if(f1>=sq*s.thresh)
value += ac[k].alphas[t];
else ;
}
if(value<ac[k].thresh)
{
result = 0;
break;
}
}
if(result!=0)
{
const REAL r = 1.0/ratio;
rect.left = (LONG)(j*r);rect.top = (LONG)(i*r);
rect.right = (LONG)((j+sy)*r);rect.bottom = (LONG)((i+sx)*r);
results.push_back(rect);
}
}
ratio = ratio * REAL(0.8);
procface.Resize(image,REAL(0.8));
SwapIntImage(procface,image);
}
total_fp += results.size();
PostProcess(results,2);
PostProcess(results,0);
DrawResults(original,results);
// original.Save(filename+"_result.JPG");
}
inline int SizeOfRect(const CRect& rect)
{
return rect.Height()*rect.Width();
}
void PostProcess(vector<CRect>& result,const int combine_min)
{
vector<CRect> res1;
vector<CRect> resmax;
vector<int> res2;
bool yet;
CRect rectInter;
for(unsigned int i=0,size_i=result.size();i<size_i;i++)
{
yet = false;
CRect& result_i = result[i];
for(unsigned int j=0,size_r=res1.size();j<size_r;j++)
{
CRect& resmax_j = resmax[j];
if(rectInter.IntersectRect(result_i,resmax_j))
{
if(
SizeOfRect(rectInter)>0.6*SizeOfRect(result_i)
&& SizeOfRect(rectInter)>0.6*SizeOfRect(resmax_j)
)
{
CRect& res1_j = res1[j];
resmax_j.UnionRect(resmax_j,result_i);
res1_j.bottom += result_i.bottom;
res1_j.top += result_i.top;
res1_j.left += result_i.left;
res1_j.right += result_i.right;
res2[j]++;
yet = true;
break;
}
}
}
if(yet==false)
{
res1.push_back(result_i);
resmax.push_back(result_i);
res2.push_back(1);
}
}
for(unsigned int i=0,size=res1.size();i<size;i++)
{
const int count = res2[i];
CRect& res1_i = res1[i];
res1_i.top /= count;
res1_i.bottom /= count;
res1_i.left /= count;
res1_i.right /= count;
}
result.clear();
for(unsigned int i=0,size=res1.size();i<size;i++)
if(res2[i]>combine_min)
result.push_back(res1[i]);
}
void CascadeClassifier::ApplyOriginalSizeForInputBoosting(const CString filename,int& pointer) const
{
IntImage procface;
IntImage image,square;
REAL sq,ex,value;
int result;
CRect rect;
REAL ratio;
procface.Load(filename);
if(procface.height <=0 || procface.width<=0) return;
ratio = 1.0;
REAL paddedsize = REAL(1)/REAL((sx+1)*(sy+1));
while((procface.height>sx+1) && (procface.width>sy+1))
{
procface.CalcSquareAndIntegral(square,image);
for(int i=0,size_x=image.height-sx;i<size_x;i+=bootstrap_increment[bootstrap_level])
for(int j=0,size_y=image.width-sy;j<size_y;j+=bootstrap_increment[bootstrap_level])
{
ex = image.data[i+sx][j+sy]+image.data[i][j]-image.data[i+sx][j]-image.data[i][j+sy];
if(ex<mean_min || ex>mean_max) continue;
sq = square.data[i+sx][j+sy]+square.data[i][j]-square.data[i+sx][j]-square.data[i][j+sy];
if(sq<sq_min) continue;
ex *= paddedsize;
ex = ex * ex;
sq *= paddedsize;
sq = sq - ex;
ASSERT(sq>=0);
if(sq>0) sq = sqrt(sq); else sq = 1.0;
if(sq<var_min) continue;
result = 1;
for(int k=0;k<count;k++)
{
value = 0.0;
for(int t=0,size=ac[k].count;t<size;t++)
value += (ac[k].alphas[t]*ac[k].scs[t].Apply(ac[k].scs[t].GetOneFeatureTranslation(image.data+i,j)/sq));
if(value<ac[k].thresh)
{
result = 0;
break;
}
}
if(result==1)
{
for(int k=1;k<=sx;k++)
for(int t=1;t<=sy;t++)
trainset[pointer].data[k][t]=image.data[i+k][j+t]-image.data[i+k][j]-image.data[i][j+t]+image.data[i][j];
pointer++;
if(pointer==totalcount) return;
}
}
ratio = ratio * bootstrap_resizeratio[bootstrap_level];
procface.Resize(image,bootstrap_resizeratio[bootstrap_level]);
SwapIntImage(procface,image);
}
}
void AppendAdaBoostClassifier(const AdaBoostClassifier& ada)
{
CascadeClassifier cas;
ifstream f;
ofstream of;
f.open(cascade_filename);
cas.ReadFromFile(f);
f.close();
cas.ac[cas.count] = ada;
cas.count++;
of.open(cascade_filename);
cas.WriteToFile(of);
of.close();
}
|
[
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
] |
[
[
[
1,
346
]
]
] |
4559d652c47bca380d8b6eecb1b8cc29507003c1
|
e6abea92f59a1031d94bbcb3cee828da264c04cf
|
/NppPlugins/NppPlugin_ChangeMarker/src/NppPlugin.h
|
ed7c10bca14a8dcbf00a8e6a0caaa978be01591b
|
[] |
no_license
|
bruderstein/nppifacelib_mob
|
5b0ad8d47a19a14a9815f6b480fd3a56fe2c5a39
|
a34ff8b5a64e237372b939106463989b227aa3b7
|
refs/heads/master
| 2021-01-15T18:59:12.300763 | 2009-08-13T19:57:24 | 2009-08-13T19:57:24 | 285,922 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,996 |
h
|
/* NppPlugin.h
*
* This file is part of the Notepad++ Plugin Interface Lib.
* Copyright 2009 Thell Fowler ([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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* These includes provide plugins with functions that enhance the N++ plugin interface.
* The basic interface enhancement provides plugin registration and handle controls.
* The ExtLexer extension provides styler registration and forces N++ to read a styles
* xml, which makes it easy to add 'Global Styles'.
* Both of those also allow for function registration. The basic difference between the
* two function registrations is the base functions display under a separator in the order
* registered, and the ExtLexer registered functions get sorted and display above the
* separator.
*
* The XmlConfig extension makes it easy for a plugin to read/write configuration data in
* the same way that N++ does. So, if the plugin provides styling, the plugins' styles
* xml can also be used for config params.
*
* The Markers extension provides plugins with functions to read and react to the basic
* Notepad++/Scintilla margin and marker settings. For instance if the plugin provides
* a marker the defineMarker function will check for a valid and free marker number to use,
* as well as set the mask information for the margins in both views.
*
* TODO: Two other extensions that would be very nice to have available are dialog related.
* 1) A Preferences dialog hook into the Edit Components panel.
* 2) A Styler Configurator hook to allow widget registration similar to the 'Global
* Overrides' checkboxes.
*
*/
#ifndef NPP_PLUGIN_H
#define NPP_PLUGIN_H
// <--- Notepad++ Plugin Interface Library Includes --->
#include "NppPluginIface.h"
#include "NppPluginIface_msgs.h"
#include "NppPluginIface_XmlConfig.h"
#include "NppPluginIface_Markers.h"
#include "NppPluginIface_CmdMap.h"
#include "NppPluginIface_DocTabMap.h"
#include "NppPluginIface_ActionIndex.h"
#include "NppPluginIface_ActionHistory.h"
//#include "NppPluginIface_ExtLexer.h"
namespace npp_plugin {
// This is the base plugin's default menu item.
void About_func();
} // End: namespace npp_plugin_base
#endif // Include Guard: NPP_PLUGIN_H
|
[
"T B Fowler@2fa2a738-4fc5-9a49-b7e4-8bd4648edc6b"
] |
[
[
[
1,
66
]
]
] |
fabca742c9609ba91e430d554ee44a97ad06d758
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Physics/Collide/Agent/CompoundAgent/ShapeCollection/hkpShapeCollectionAgent.h
|
765fffc72a91eca28be8d709c9b37576faf4272d
|
[] |
no_license
|
blockspacer/transporter-game
|
23496e1651b3c19f6727712a5652f8e49c45c076
|
083ae2ee48fcab2c7d8a68670a71be4d09954428
|
refs/heads/master
| 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,882 |
h
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_SHAPE_COLLECTION_AGENT_H
#define HK_COLLIDE2_SHAPE_COLLECTION_AGENT_H
#include <Physics/Collide/Agent/hkpCollisionAgent.h>
#include <Physics/Collide/Shape/Compound/Collection/hkpShapeCollection.h>
class hkpCollisionDispatcher;
/// This agent handles collisions between hkShapeCollections
/// and other shapes.
class hkpShapeCollectionAgent : public hkpCollisionAgent
{
public:
/// Registers this agent with the collision dispatcher.
static void HK_CALL registerAgent(hkpCollisionDispatcher* dispatcher);
// hkpCollisionAgent interface implementation.
virtual void processCollision(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& result);
// hkpCollisionAgent interface implementation.
virtual void linearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
// hkpCollisionAgent interface implementation.
static void HK_CALL staticLinearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
// hkpCollisionAgent interface implementation.
virtual void getClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& pointDetails);
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, class hkpCdPointCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void getPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void cleanup(hkCollisionConstraintOwner& info);
// hkpCollisionAgent interface implementation.
virtual void updateShapeCollectionFilter( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkCollisionConstraintOwner& constraintOwner );
// hkpCollisionAgent interface implementation.
virtual void invalidateTim(hkpCollisionInput& input);
// hkpCollisionAgent interface implementation.
virtual void warpTime(hkTime oldTime, hkTime newTime, hkpCollisionInput& input);
public:
// Constructor, called by the agent creation functions.
hkpShapeCollectionAgent( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
// Agent creation function used by the hkpCollisionDispatcher.
static hkpCollisionAgent* HK_CALL createListAAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
// Agent creation function used by the hkpCollisionDispatcher.
static hkpCollisionAgent* HK_CALL createListBAgent( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
protected:
struct KeyAgentPair
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpShapeCollectionAgent::KeyAgentPair );
hkpShapeKey m_key;
hkpCollisionAgent* m_agent;
};
int getAgentIndex( hkpShapeKey key );
hkInplaceArray<KeyAgentPair,4> m_agents;
};
#endif // HK_COLLIDE2_SHAPE_COLLECTION_AGENT_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
|
[
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] |
[
[
[
1,
102
]
]
] |
b612f272f8e376473a0a032a3985e982c2fe6f72
|
bda7b365b5952dc48827a8e8d33d11abd458c5eb
|
/SignIn.cpp
|
891a51629a2a14523b55f88f80c9ee4e2ff78eeb
|
[] |
no_license
|
MrColdbird/gameservice
|
3bc4dc3906d16713050612c1890aa8820d90272e
|
009d28334bdd8f808914086e8367b1eb9497c56a
|
refs/heads/master
| 2021-01-25T09:59:24.143855 | 2011-01-31T07:12:24 | 2011-01-31T07:12:24 | 35,889,912 | 3 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 30,991 |
cpp
|
// ======================================================================================
// File : SignIn.cpp
// Author : Li Chen
// Last Change : 07/29/2010 | 15:48:13 PM | Thursday,July
// Description :
// ======================================================================================
#include "stdafx.h"
#include "SignIn.h"
#include "Master.h"
#include "Achievement.h"
#include "Message.h"
#if defined(_PS3)
#include <netex/net.h>
#include <sys/timer.h>
#endif
namespace GameService
{
//--------------------------------------------------------------------------------------
// Static members
//--------------------------------------------------------------------------------------
GS_BOOL SignIn::m_bBeforePressStart = TRUE;
#if !defined(_WINDOWS)
GS_DWORD SignIn::m_dwActiveUserIndex = 0;
#endif
#if defined(_XBOX) || defined(_XENON)
GS_DWORD SignIn::m_dwMinUsers = 0;
GS_DWORD SignIn::m_dwMaxUsers = 4;
GS_BOOL SignIn::m_bRequireOnlineUsers = FALSE;
GS_DWORD SignIn::m_dwSignInPanes = 4;
HANDLE SignIn::m_hNotification = NULL;
GS_DWORD SignIn::m_dwSignedInUserMask = 0;
GS_DWORD SignIn::m_dwNumSignedInUsers = 0;
GS_DWORD SignIn::m_dwOnlineUserMask = 0;
GS_DWORD SignIn::m_dwFirstSignedInUser = (GS_DWORD)-1;
GS_BOOL SignIn::m_bSystemUIShowing = FALSE;
GS_BOOL SignIn::m_bNeedToShowSignInUI = FALSE;
GS_BOOL SignIn::m_bMessageBoxShowing = FALSE;
GS_BOOL SignIn::m_bSigninUIWasShown = FALSE;
XOVERLAPPED SignIn::m_Overlapped = {0};
LPCWSTR SignIn::m_pwstrButtons[2] = { L"Sign In", L"Back" };
MESSAGEBOX_RESULT SignIn::m_MessageBoxResult = {0};
GS_DWORD SignIn::m_LastSignInStateChange = 0;
GS_BOOL SignIn::m_SignInChanged = FALSE;
XUID SignIn::m_InvalidID = INVALID_XUID;
XUID SignIn::m_Xuids [ XUSER_MAX_COUNT ] ={0,0,0,0}; // Local XUIDs
GS_BOOL SignIn::m_bPrivate[ XUSER_MAX_COUNT ] ={0,0,0,0}; // Users consuming private slots
GS_CHAR SignIn::m_cUserName[XUSER_MAX_COUNT][MAX_USER_NAME] =
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,
};
GS_BOOL SignIn::m_bCanNotifyNoProfile = FALSE;
#elif defined(_PS3)
GS_BOOL SignIn::m_bStarNPInProgress = FALSE;
GS_BOOL SignIn::m_bIsStarNPRequestPending = FALSE;
GS_INT SignIn::m_sceNPStatus = SCE_NP_ERROR_NOT_INITIALIZED;
SceNpId SignIn::m_sceNpID =
{
{
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // data
0, // term
{0,0,0} // dummy
},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
};
SceNpOnlineName SignIn::m_sceOnlineName =
{
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // data
0, // term
{0,0,0} // padding
};
SceNpAvatarUrl SignIn::m_sceAvatarUrl =
{
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
0, // term
};
SceNpMyLanguages SignIn::m_sceMyLang =
{
0,0, // language1/2/3
0, // term
{0,0,0,0} // padding
};
SceNpCountryCode SignIn::m_sceCountryCode =
{
{0,0}, // coutry code
0, // term
{0}
};
GS_INT SignIn::m_sceLangCode = 0;
int SignIn::m_UserAge = 0;
#include "Customize/PS3_IDGarden.txt"
// NP POOL
uint8_t G_NPPOOL[SCE_NP_MIN_POOL_SIZE];
#define HTTP_POOL_SIZE (512 * 1024)
#define HTTP_COOKIE_POOL_SIZE (128 * 1024)
#define SSL_POOL_SIZE (300 * 1024)
static CellHttpsData G_caList;
static GS_BYTE* G_HttpPool;
static GS_BYTE* G_HttpCookiePool;
static GS_BYTE* G_SslPool;
#endif
GS_UINT SignIn::m_nNumUsers = 0; // Local users
#if defined(_PS3)
GS_INT SignIn::m_iCheckConnectionSlot = 2;
GS_BOOL SignIn::m_bIsOnline = FALSE;
// callback for signing-in to network
void SignIn::NetSysUtilCbInternal(uint64_t status, uint64_t param, void * userdata)
{
switch (status) {
case CELL_SYSUTIL_NET_CTL_NETSTART_LOADED:
Master::G()->Log("CELL_SYSUTIL_NET_CTL_NETSTART_LOADED");
break;
case CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED:
Master::G()->Log("CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED");
{
struct CellNetCtlNetStartDialogResult result;
int ret=-1;
Master::G()->Log("[GameService] - Network connected");
memset(&result, 0, sizeof(result));
result.size = sizeof(result);
ret = cellNetCtlNetStartDialogUnloadAsync(&result);
if (ret < 0) {
Master::G()->Log("cellNetCtlNetStartDialogUnloadAsync() failed. ret = 0x%x", ret);
}
switch (result.result) {
case 0:
break;
case CELL_NET_CTL_ERROR_NET_NOT_CONNECTED:
Master::G()->Log("CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED result: CELL_NET_CTL_ERROR_NET_NOT_CONNECTED");
break;
default:
Master::G()->Log("CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED result error = 0x%x", result.result);
break;
}
}
break;
case CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED:
Master::G()->Log("CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED");
cellSysutilUnregisterCallback(m_iCheckConnectionSlot);
break;
default:
break;
}
}
// callback for NpManager
void SignIn::NpManagerCallBack(int event, int result, void *arg)
{
(void)result;
switch (event) {
case SCE_NP_MANAGER_STATUS_ONLINE:
Master::G()->Log("[GameService] - <MANAGER CB> online");
{
StartNP();
}
break;
case SCE_NP_MANAGER_STATUS_OFFLINE:
Master::G()->Log("[GameService] - <MANAGER CB> offline");
{
StartNP();
}
break;
case SCE_NP_MANAGER_EVENT_GOT_TICKET:
{
if (result > 0)
{
if (Master::G())
Master::G()->SetTrackingNpTicketSize(result);
}
else
{
Master::G()->Log("SCE_NP_MANAGER_EVENT_GOT_TICKET failed: %x !!!", result);
}
}
break;
default:
Master::G()->Log("<MANAGER CB> event:%d, result:0x%x", event, result);
break;
}
}
// void SignIn::NpBasicSendInitPresence()
// {
// int status = SCE_NP_MANAGER_STATUS_OFFLINE;
// int ret=-1;
// ret = sceNpManagerGetStatus(&status);
// if (ret < 0) {
// Master::G()->Log("sceNpManagerGetStatus() failed. ret = 0x%x", ret);
// }
// switch (status) {
// case SCE_NP_MANAGER_STATUS_ONLINE:
// Master::G()->Log("[basic] send initial presence");
// ret = sceNpBasicSetPresence(NULL, 0);
// if (ret < 0) {
// Master::G()->Log("sceNpBasicSetPresence() failed. ret = 0x%x", ret);
// }
// break;
// default:
// break;
// }
// }
// callback for NpBasic Presence
int SignIn::NpBasicCallBack(int event, int retCode, uint32_t reqId, void *arg)
{
// TODO:
// send instant message
return 0;
}
void SignIn::SignInNP()
{
if (!CheckConnection())
{
StartNP();
}
}
GS_BOOL SignIn::CheckConnection()
{
struct CellNetCtlNetStartDialogParam param;
GS_INT ret = -1;
ret = cellSysutilRegisterCallback(m_iCheckConnectionSlot, SignIn::NetSysUtilCbInternal, NULL);
if (ret != CELL_OK) {
Master::G()->Log("error: cellSysutilRegisterCallback() = 0x%x", ret);
return FALSE;
}
memset(¶m, 0, sizeof(param));
param.size = sizeof(param);
param.type = CELL_NET_CTL_NETSTART_TYPE_NP;
ret = cellNetCtlNetStartDialogLoadAsync(¶m);
if (ret < 0) {
Master::G()->Log("cellNetCtlNetStartDialogLoadAsync() failed. ret = 0x%x", ret);
cellSysutilUnregisterCallback(m_iCheckConnectionSlot);
return FALSE;
}
Master::G()->Log("[net start dialog] start...");
return TRUE;
}
#endif
//--------------------------------------------------------------------------------------
// Name: Initialize()
// Desc: Sets up variables and creates notification listener
//--------------------------------------------------------------------------------------
GS_VOID SignIn::Initialize( GS_DWORD dwMinUsers,
GS_DWORD dwMaxUsers,
GS_BOOL bRequireOnlineUsers,
GS_DWORD dwSignInPanes )
{
#if defined(_XBOX) || defined(_XENON)
// Sanity check inputs
GS_Assert( dwMaxUsers <= 4 && dwMinUsers <= dwMaxUsers );
GS_Assert( dwSignInPanes <= 4 && dwSignInPanes != 3 );
// Assign variables
m_dwMinUsers = dwMinUsers;
m_dwMaxUsers = dwMaxUsers;
m_bRequireOnlineUsers = bRequireOnlineUsers;
m_dwSignInPanes = dwSignInPanes;
m_bCanNotifyNoProfile = FALSE;
// Register our notification listener
m_hNotification = XNotifyCreateListener( XNOTIFY_SYSTEM | XNOTIFY_LIVE );
if( m_hNotification == NULL || m_hNotification == INVALID_HANDLE_VALUE )
{
Master::G()->Log( "Failed to create state notification listener.\n" );
}
QuerySigninStatus();
#elif defined(_PS3)
if (!StartNet())
{
StartNP();
return;
}
if (bRequireOnlineUsers)
{
SignInNP();
}
else
{
StartNP();
}
#endif
}
#if defined(_PS3)
static void
freeCerts(void)
{
if(G_caList.ptr != NULL)
GS_DELETE [] G_caList.ptr;
}
static int
loadCerts(void)
{
char *buf = NULL;
size_t size = 0;
int ret = 0;
ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, NULL, 0, &size);
if(ret < 0){
Master::G()->Log("cellSslCertificateLoader() failed. ret = 0x%x\n", ret);
goto error;
}
memset(&G_caList, 0, sizeof(G_caList));
G_caList.ptr = (char*)GS_NEW GS_BYTE[size];
if(NULL == G_caList.ptr){
Master::G()->Log("malloc failed for cert pinter... \n");
ret = -1;
goto error;
}
buf = (char*)(G_caList.ptr);
G_caList.size = size;
ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, buf, size, NULL);
if(ret < 0){
Master::G()->Log("cellSslCertificateLoader() failed. ret = 0x%x\n", ret);
goto error;
}
return 0;
error:
freeCerts();
return ret;
}
GS_BOOL SignIn::StartNet()
{
GS_INT ret = -1;
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_NET);
if (ret >= 0)
{
ret = sys_net_initialize_network();
if (ret != CELL_OK)
{
Master::G()->Log( "sys_net_initialize_network failed (0x%x)\n", ret );
ret = sys_net_finalize_network();
if (ret < 0)
{
Master::G()->Log("sys_net_finalize_network() failed (0x%x)", ret);
}
ret = cellSysmoduleUnloadModule(CELL_SYSMODULE_NET);
if (ret < 0)
{
Master::G()->Log("cellSysmoduleUnloadModule() failed (0x%x)", ret);
}
return FALSE;
}
}
else
{
return FALSE;
}
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_HTTP);
if (ret < 0) {
Master::G()->Log("cellSysmoduleLoadModule failed (0x%x)", ret);
return FALSE;
}
// NOTE:
// InGameMarketplace init only:
if (Master::G()->IsEnableInGameMarketplace())
{
// init NetCtl
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_HTTPS);
if (ret < 0) {
Master::G()->Log("CELL_SYSMODULE_HTTPS failed. ret = 0x%x", ret);
return FALSE;
}
G_HttpPool = GS_NEW GS_BYTE[HTTP_POOL_SIZE];
if(G_HttpPool == NULL){
Master::G()->Log( "SignIn::StartNet - failed to malloc libhttp memory pool\n");
return FALSE;
}
ret = cellHttpInit(G_HttpPool, HTTP_POOL_SIZE);
if(ret < 0){
Master::G()->Log("cellHttpInit() failed. ret = 0x%x\n", ret);
return FALSE;
}
G_HttpCookiePool = GS_NEW GS_BYTE[HTTP_COOKIE_POOL_SIZE];
if(G_HttpCookiePool == NULL){
Master::G()->Log( "SignIn::StartNet - failed to malloc libhttp memory pool\n");
return FALSE;
}
ret = cellHttpInitCookie(G_HttpCookiePool, HTTP_COOKIE_POOL_SIZE);
if(ret < 0){
Master::G()->Log("cellHttpInitCookie() failed. ret = 0x%x\n", ret);
return FALSE;
}
if (loadCerts() < 0)
return FALSE;
G_SslPool = GS_NEW GS_BYTE[SSL_POOL_SIZE];
if(G_SslPool == NULL){
return FALSE;
}
ret = cellSslInit(G_SslPool, SSL_POOL_SIZE);
if(ret < 0){
Master::G()->Log("cellSslInit() failed. ret = 0x%x\n", ret);
return FALSE;
}
ret = cellHttpsInit(1, &G_caList);
if(ret < 0){
Master::G()->Log("cellHttpsInit() failed. ret = 0x%x\n", ret);
return FALSE;
}
}
// init NetCtl
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_NETCTL);
if (ret < 0) {
Master::G()->Log("CELL_SYSMODULE_SYSUTIL_NETCTL failed. ret = 0x%x", ret);
return FALSE;
}
ret = cellNetCtlInit();
if (ret < 0) {
Master::G()->Log("cellNetCtlInit() failed. ret = 0x%x", ret);
cellSysmoduleUnloadModule(CELL_SYSMODULE_NETCTL);
return FALSE;
}
return TRUE;
}
GS_BOOL SignIn::StartNP()
{
if (m_bStarNPInProgress)
{
m_bIsStarNPRequestPending = TRUE;
return FALSE;
}
sys_ppu_thread_t temp_id;
int ret = -1;
ret = sys_ppu_thread_create(
&temp_id, PS3_StartNP_Thread,
(uintptr_t)(Master::G()), THREAD_PRIO, STACK_SIZE,
0, "GameService StarNP Thread");
if (ret < 0) {
Master::G()->Log("[GameService] - sys_ppu_thread_create() for StartNP failed (%x)", ret);
return FALSE;
}
m_bStarNPInProgress = TRUE;
return TRUE;
}
void SignIn::PS3_StartNP_Thread(uint64_t instance)
{
Master* master = (Master*)instance;
GS_INT ret = -1;
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_SYSUTIL_NP);
if (ret >= 0)
{
ret = sceNpInit(SCE_NP_MIN_POOL_SIZE, G_NPPOOL);
if (ret != CELL_OK && ret != SCE_NP_ERROR_ALREADY_INITIALIZED)
{
master->Log( "sceInit failed (0x%x)\n", ret );
ret = sceNpTerm();
if (ret < 0)
{
master->Log("sceNpTerm() failed (0x%x)", ret);
}
ret = cellSysmoduleUnloadModule(CELL_SYSMODULE_SYSUTIL_NP);
if (ret < 0)
{
master->Log("cellSysmoduleUnloadModule() failed (0x%x)", ret);
}
return;
}
}
else
{
return;
}
// register notification when connection status changed
ret = sceNpManagerRegisterCallback(NpManagerCallBack, NULL);
if (ret < 0) {
master->Log("sceNpManagerRegisterCallback() failed. ret = 0x%x", ret);
}
int npStatus = -2;
ret = sceNpManagerGetStatus(&npStatus);
if (ret == 0)
{
m_bIsOnline = FALSE;
if (SCE_NP_MANAGER_STATUS_ONLINE == npStatus)
{
m_bIsOnline = TRUE;
}
master->Log("[GameService] - sceNpManagerGetStatus: %d", npStatus);
}
ret = sceNpManagerGetNpId(&m_sceNpID);
if (ret < 0) {
master->Log("sceNpManagerGetNpId() failed. ret = 0x%x", ret);
}
Master::G()->Log("[GameService] - GetOnlineId: %s", m_sceNpID.handle.data);
ret = sceNpManagerGetOnlineName(&m_sceOnlineName);
if (ret < 0) {
master->Log("sceNpManagerGetOnlineName() failed. ret = 0x%x", ret);
}
master->Log("[GameService] - GetOnlineName: %s", m_sceOnlineName.data);
ret = sceNpManagerGetAvatarUrl(&m_sceAvatarUrl);
if (ret < 0) {
master->Log("sceNpManagerGetAvatarUrl() failed. ret = 0x%x", ret);
}
master->Log("[GameService] - GetAvatarUrl: %s", m_sceAvatarUrl.data);
ret = sceNpManagerGetMyLanguages(&m_sceMyLang);
if (ret < 0) {
master->Log("sceNpManagerGetMyLanguages() failed. ret = 0x%x", ret);
}
master->Log("[GameService] - GetMyLanguage: %d", m_sceMyLang.language1);
ret = sceNpManagerGetAccountRegion(&m_sceCountryCode, &m_sceLangCode);
if (ret < 0) {
master->Log("sceNpManagerGetAccountRegion() failed. ret = 0x%x", ret);
}
master->Log("[GameService] - GetAccountRegion: %s", m_sceCountryCode.data);
ret = sceNpManagerGetAccountAge(&m_UserAge);
if (ret < 0) {
master->Log("sceNpManagerGetAccountAge() failed. ret = 0x%x", ret);
}
master->Log("[GameService] - GetAccountAge: %d", m_UserAge);
// TODO:
// support sub-signin
master->InitServices();
// if (master->GetAchievementSrv())
// master->GetAchievementSrv()->ReadAchievements(0,0,master->GetAchievementSrv()->GetCountMax());
m_nNumUsers = 1;
//InGameBrowsing Init for trial version
// if(Master::G()->IsTrialVersion())
// {
// #ifdef INGAMEBROWSING
// master->GetInGameBrowsingSrv()->Init();
// #else
// master->GetStoreBrowsingSrv()->Init();
// #endif
// }
// sign in succeed!
// ret = sceNpBasicRegisterContextSensitiveHandler(
// &m_NpCommID, NpBasicCallBack, NULL);
// if (ret < 0) {
// Master::G()->Log("sceNpBasicRegisterHandler() failed. ret = 0x%x", ret);
// sceNpBasicUnregisterHandler();
// }
while (m_bIsStarNPRequestPending)
{
m_bIsStarNPRequestPending = FALSE;
PS3_StartNP_Thread(instance);
}
// NpBasicSendInitPresence();
m_bStarNPInProgress = FALSE;
sys_ppu_thread_exit(0);
}
GS_BOOL SignIn::GetNPStatus()
{
int npStatus = -2;
int ret = sceNpManagerGetStatus(&npStatus);
if (ret == 0 && SCE_NP_MANAGER_STATUS_ONLINE == npStatus)
{
return TRUE;
}
return FALSE;
}
void SignIn::TermNP()
{
//sceNpBasicUnregisterHandler();
sceNpManagerUnregisterCallback();
sceNpManagerTerm();
sceNpTerm();
cellSysmoduleUnloadModule(CELL_SYSMODULE_NET);
}
void SignIn::TermNet()
{
if (Master::G()->IsEnableInGameMarketplace())
{
cellHttpsEnd();
cellSslEnd();
if(G_SslPool != NULL){
GS_DELETE [] G_SslPool;
G_SslPool = NULL;
}
freeCerts();
cellHttpEndCookie();
if(G_HttpCookiePool != NULL){
GS_DELETE [] G_HttpCookiePool;
G_HttpCookiePool = NULL;
}
cellHttpEnd();
if(G_HttpPool != NULL){
GS_DELETE [] G_HttpPool;
G_HttpPool = NULL;
}
}
int ret = cellSysmoduleUnloadModule(CELL_SYSMODULE_HTTP);
if (ret < 0) {
Master::G()->Log("cellSysmoduleUnloadModule failed (0x%x)", ret);
}
cellNetCtlTerm();
cellSysmoduleUnloadModule(CELL_SYSMODULE_NETCTL);
cellSysmoduleUnloadModule(CELL_SYSMODULE_SYSUTIL_NP);
// sys_net_finalize_network();
}
GS_INT SignIn::IsCableConnected()
{
int state = -1;
int ret = cellNetCtlGetState(&state);
if (ret != 0)
{
return 0;
}
return state == CELL_NET_CTL_STATE_IPObtained ? 1 : 0;
}
#endif
#if defined(_XBOX) || defined(_XENON)
//--------------------------------------------------------------------------------------
// Name: QuerySigninStatus()
// Desc: Query signed in status of all users.
//--------------------------------------------------------------------------------------
GS_VOID SignIn::QuerySigninStatus()
{
m_dwSignedInUserMask = 0; m_dwOnlineUserMask = 0;
// Count the signed-in users
m_dwNumSignedInUsers = 0;
m_dwFirstSignedInUser = ( GS_DWORD )-1;
m_nNumUsers = 0;
for( GS_UINT nUser = 0;
nUser < XUSER_MAX_COUNT;
nUser++ )
{
XUSER_SIGNIN_STATE State = XUserGetSigninState( nUser );
if( State != eXUserSigninState_NotSignedIn )
{
// Check whether the user is online
GS_BOOL bUserOnline =
State == eXUserSigninState_SignedInToLive;
m_dwOnlineUserMask |= bUserOnline << nUser;
// If we want Online users only, only count signed-in users
if( !m_bRequireOnlineUsers || bUserOnline )
{
m_dwSignedInUserMask |= ( 1 << nUser );
if( m_dwFirstSignedInUser == ( GS_DWORD )-1 )
{
m_dwFirstSignedInUser = nUser;
}
++m_dwNumSignedInUsers;
}
}
// Retrieve local users
if( IsUserSignedIn( nUser ) )
{
XUserGetXUID( nUser, &m_Xuids[ nUser ] );
m_bPrivate[ nUser ] = FALSE;
m_nNumUsers++;
}
}
// check to see if we need to invoke the signin UI
m_bNeedToShowSignInUI = !AreUsersSignedIn() && !m_bBeforePressStart;
if (m_dwNumSignedInUsers > 0)
{
Master::G()->InitServices();
if (Master::G()->GetAchievementSrv())
Master::G()->GetAchievementSrv()->ReadAchievements(GetActiveUserIndex(),0,Master::G()->GetAchievementSrv()->GetCountMax());
}
}
#endif
//--------------------------------------------------------------------------------------
// Name: Update()
// Desc: Does required per-frame processing for signin
//--------------------------------------------------------------------------------------
GS_DWORD SignIn::Update()
{
#if defined(_XBOX) || defined(_XENON)
GS_Assert( m_hNotification != NULL && m_hNotification != INVALID_HANDLE_VALUE); // ensure Initialize() was called
GS_DWORD dwRet = 0;
// Check for system notifications
GS_DWORD dwNotificationID;
ULONG_PTR ulParam;
//
// For XN_SYS_SIGNINCHANGED, handle the case where the system sends a spurious
// notification. See the FAQ on
// Xbox 360 Central: https://xds.xbox.com/xbox360/nav.aspx?Page=devsupport/sitefaq.htm#misc17
// for a description of the workaround
//
static const GS_DWORD dwTimeBeforeTrustingSignInChangedNotif = 1000;
static GS_DWORD dwQuestionableSigninChangeNotifReceived = GetTickCount();
static GS_UINT cQuestionableSigninChangeNotifReceived = 0;
if( XNotifyGetNext( m_hNotification, 0, &dwNotificationID, &ulParam ) )
{
switch( dwNotificationID )
{
case XN_SYS_SIGNINCHANGED:
m_LastSignInStateChange = GetTickCount();
m_SignInChanged = TRUE;
break;
case XN_SYS_UI:
dwRet |= SYSTEM_UI_CHANGED;
m_bSystemUIShowing = static_cast<GS_BOOL>( ulParam );
if (!m_bSystemUIShowing && !m_bBeforePressStart)
{
if (m_bMessageBoxShowing)
m_bSigninUIWasShown = FALSE;
if (!m_bSigninUIWasShown && !m_bNeedToShowSignInUI)
m_bBeforePressStart = !AreUsersSignedIn();
m_bMessageBoxShowing = FALSE;
}
// check to see if we need to invoke the signin UI
//m_bNeedToShowSignInUI = !AreUsersSignedIn() && !m_bBeforePressStart;
break;
case XN_LIVE_CONNECTIONCHANGED:
{
dwRet |= CONNECTION_CHANGED;
if (ulParam != XONLINE_S_LOGON_CONNECTION_ESTABLISHED)
{
//QuerySigninStatus();
// TODO:
// may need to inform other services connection lost message
}
}
break;
case XN_LIVE_CONTENT_INSTALLED:
{
// notify ContentMgr
Message* msg = Message::Create(EMessage_ContentInstalled);
if (msg)
{
Master::G()->GetMessageMgr()->Send(msg);
}
}
break;
} // switch( dwNotificationID )
} // if( XNotifyGetNext() )
//Jin Yu+
if(m_SignInChanged)
{
GS_DWORD curTime = GetTickCount();
if( (curTime - m_LastSignInStateChange) > 500 )
{
if(!AreUsersSignedIn() && !m_bBeforePressStart)
{
// for script
m_bCanNotifyNoProfile = TRUE;
//jin yu: return to game start set the flag
m_bBeforePressStart = TRUE;
m_bSigninUIWasShown = FALSE;
//StorageDeviceReset();
}
// Query who is signed in
QuerySigninStatus();
if (m_dwNumSignedInUsers > 0)
{
// notify other GameService
Message* msg = Message::Create(EMessage_SignInChanged);
if (msg)
{
msg->AddPayload(1);
Master::G()->GetMessageMgr()->Send(msg);
}
}
m_SignInChanged = FALSE;
}
}
//Jin Yu-
// If there are not enough or too many profiles signed in, display an
// error message box prompting the user to either sign in again or exit the sample
if( !m_bMessageBoxShowing && !m_bSystemUIShowing && m_bSigninUIWasShown && !AreUsersSignedIn() && !m_bBeforePressStart )
{
// TODO:
// Add Xbox system msgbox in SysMsgBox class
//GS_DWORD dwResult;
//ZeroMemory( &m_Overlapped, sizeof( XOVERLAPPED ) );
//WCHAR strMessage[512];
//swprintf_s( strMessage, L"No profile signed in. Please sign in a profile to continue");
//dwResult = XShowMessageBoxUI( XUSER_INDEX_ANY,
// L"Signin Error", // Message box title
// strMessage, // Message
// ARRAYSIZE( m_pwstrButtons ),// Number of buttons
// m_pwstrButtons, // Button captions
// 0, // Button that gets focus
// XMB_ERRORICON, // Icon to display
// &m_MessageBoxResult, // Button pressed result
// &m_Overlapped );
//if( dwResult != ERROR_IO_PENDING )
// Master::G()->Log( "Failed to invoke message box UI, error %d", dwResult );
//m_bSystemUIShowing = TRUE;
//m_bMessageBoxShowing = TRUE;
}
// Wait until the message box is discarded, then either exit or show the signin UI again
if( m_bMessageBoxShowing && XHasOverlappedIoCompleted( &m_Overlapped ) )
{
if( XGetOverlappedResult( &m_Overlapped, NULL, TRUE ) == ERROR_SUCCESS )
{
switch( m_MessageBoxResult.dwButtonPressed )
{
case 0: // Show the signin UI again
ShowSignInUI();
m_bSigninUIWasShown = FALSE;
break;
case 1: // Reboot to the launcher
// XLaunchNewImage( XLAUNCH_KEYWORD_DEFAULT_APP, 0 );
break;
}
}
}
// Check to see if we need to invoke the signin UI
if( !m_bMessageBoxShowing && m_bNeedToShowSignInUI && !m_bSystemUIShowing )
{
m_bNeedToShowSignInUI = FALSE;
GS_DWORD ret = XShowSigninUI(
m_dwSignInPanes,
m_bRequireOnlineUsers ? XSSUI_FLAGS_SHOWONLYONLINEENABLED : 0 );
if( ret != ERROR_SUCCESS )
{
Master::G()->Log( "Failed to invoke signin UI, error %d", ret );
}
else
{
m_bSystemUIShowing = TRUE;
m_bSigninUIWasShown = TRUE;
}
}
return dwRet;
#elif defined(_PS3)
// TODO:
// if player's online status updated,
// handling
cellSysutilCheckCallback();
return 0;
#else
return 0;
#endif
}
#if defined(_XBOX) || defined(_XENON)
//--------------------------------------------------------------------------------------
// Name: CheckPrivilege()
// Desc: Test to see if a user has a required privilege
//--------------------------------------------------------------------------------------
GS_BOOL SignIn::CheckPrivilege( GS_DWORD dwController, XPRIVILEGE_TYPE priv )
{
GS_BOOL bResult;
return
( XUserCheckPrivilege( dwController, priv, &bResult ) == ERROR_SUCCESS ) &&
bResult;
}
#elif defined(_PS3)
#endif
// ========================================================
// GetCurrentUserName
// ========================================================
GS_CHAR* SignIn::GetUserNameStr(GS_UINT iUser)
{
#if defined(_XBOX) || defined(_XENON)
ZeroMemory( m_cUserName[iUser], MAX_USER_NAME );
XUserGetName( iUser, m_cUserName[iUser], MAX_USER_NAME );
return m_cUserName[iUser];
#elif defined(_PS3)
return (GS_CHAR*)m_sceOnlineName.data;
#else
return 0;
#endif
}
// ========================================================
// Show GamerCard
// ========================================================
int GFunc_handler(int result, void* arg)
{
Master::G()->Log("[GameService] - sceNpProfileCallGui handle result: %d", result);
return 0;
}
void SignIn::ShowGamerCardUI(
#if defined(_XBOX) || defined(_XENON)
XUID
#elif defined(_PS3)
SceNpId*
#else
GS_INT
#endif
id)
{
#if defined(_XBOX) || defined(_XENON)
XShowGamerCardUI(GetActiveUserIndex(), id);
#elif defined(_PS3)
void *arg; //User-defined pointer to be passed to
int ret = -1;
ret = sceNpProfileCallGui(id, GFunc_handler,arg,0);
if (ret < 0)
{
Master::G()->Log("[GameService] - sceNpProfileCallGui failed: %d", ret);
}
#endif
}
GS_VOID SignIn::StartGame(GS_UINT userIndex)
{
#if defined(_XBOX) || defined(_XENON)
SetActiveUserIndex(userIndex);
SetBeforePressStart(FALSE);
QuerySigninStatus();
// Rich Presence
#endif
}
} // namespace GameService
|
[
"leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69"
] |
[
[
[
1,
1027
]
]
] |
41715c3dbab28c7935daf2fcf2c672d467878897
|
c3531ade6396e9ea9c7c9a85f7da538149df2d09
|
/Param/include/hj_3rd/hjlib/sparse/type_traits.h
|
51ca60f188df5aa3d5f5801c90bee3faf87d835f
|
[] |
no_license
|
feengg/MultiChart-Parameterization
|
ddbd680f3e1c2100e04c042f8f842256f82c5088
|
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
|
refs/heads/master
| 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 419 |
h
|
#ifndef HJ_TYPE_TRAITS_H_
#define HJ_TYPE_TRAITS_H_
namespace hj { namespace sparse {
template <typename T>
class value_type
{
public:
static const unsigned char type = 'r';
static const unsigned char size = sizeof(T);
};
template <typename T>
class value_type<std::complex<T> >
{
public:
static const unsigned char type = 'c';
static const unsigned char size = sizeof(T);
};
}}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
24
]
]
] |
632edafd11415c68623fc6b112167d0095e73201
|
d249c8f9920b1267752342f77d6f12592cb32636
|
/moteurGraphique/src/Ressource/Mesh/Sphere.h
|
2d604301223a6e87cc945d5d52a1e74a141edf66
|
[] |
no_license
|
jgraulle/stage-animation-physique
|
4c9fb0f96b9f4626420046171ff60f23fe035d5d
|
f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae
|
refs/heads/master
| 2021-12-23T13:46:07.677761 | 2011-03-08T22:47:53 | 2011-03-08T22:47:53 | 33,616,188 | 0 | 0 | null | 2021-10-05T10:41:29 | 2015-04-08T15:41:32 |
C++
|
UTF-8
|
C++
| false | false | 365 |
h
|
/*
* Sphere.h
*
* Created on: 9 f�vr. 2009
* Author: jeremie GRAULLE
*/
#ifndef SPHERE_H_
#define SPHERE_H_
#include "../Mesh.h"
class Sphere : public Mesh {
public:
Sphere(int slices, int stacks);
virtual ~Sphere();
private:
int slices; // nombre de tranches
int stacks; // nombre de paralleles
};
#endif /* SPHERE_H_ */
|
[
"jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb"
] |
[
[
[
1,
22
]
]
] |
9bbcd7de8139a790067002b11be0a70033f1ee1e
|
4b21c2040d16f43b3f9bfcfb23d2240417db659c
|
/src/qtdwm/qtdwm.h
|
2790d7c5946644c8ed2fd0465892e555964fce4c
|
[] |
no_license
|
proDOOMman/qutim-plugin-qml
|
e2dda5b56f6f0b8f3b04ad1756e7a400023a3069
|
7950266bb7a2f456cec4f24bde4f04c7e13225a0
|
refs/heads/master
| 2020-04-05T23:44:25.393393 | 2010-03-16T15:52:56 | 2010-03-16T15:52:56 | 558,377 | 0 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,133 |
h
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Use, modification and distribution is allowed without limitation,
** warranty, liability or support of any kind.
**
****************************************************************************/
#ifndef QTWIN_H
#define QTWIN_H
#include <QColor>
#include <QWidget>
/**
* This is a helper class for using the Desktop Window Manager
* functionality on Windows 7 and Windows Vista. On other platforms
* these functions will simply not do anything.
*/
class WindowNotifier;
class QtDWM
{
public:
static bool enableBlurBehindWindow(QWidget *widget, bool enable = true);
static bool extendFrameIntoClientArea(QWidget *widget,
int left = -1, int top = -1,
int right = -1, int bottom = -1);
static bool isCompositionEnabled();
static QColor colorizatinColor();
private:
static WindowNotifier *windowNotifier();
};
#endif // QTWIN_H
|
[
"prodoomman@timekiller.(none)"
] |
[
[
[
1,
37
]
]
] |
ba9a950342b2adb6fb5dfdd95b2152b47eaa7d4a
|
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
|
/CleanProject/ParticleUniverse/include/ParticleUniverseEmitterTokens.h
|
fb72f07960ab8717b84487364c74cb7d81cdf07e
|
[] |
no_license
|
bahao247/apeengine2
|
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
|
f2617b2a42bdf2907c6d56e334c0d027fb62062d
|
refs/heads/master
| 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,463 |
h
|
/*
-----------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2006-2008 Henry van Merode
Usage of this program is free for non-commercial use and licensed under the
the terms of the GNU Lesser General Public License.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __PU_EMITTER_TOKENS_H__
#define __PU_EMITTER_TOKENS_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseITokenInitialiser.h"
namespace ParticleUniverse
{
/** This class contains the tokens that are needed on an Emitter level.
*/
class _ParticleUniverseExport ParticleEmitterTokens : public ITokenInitialiser
{
public:
ParticleEmitterTokens(void) {};
virtual ~ParticleEmitterTokens(void) {};
/** @see
ITokenInitialiser::setupTokenDefinitions
*/
virtual void setupTokenDefinitions(ITokenRegister* tokenRegister);
protected:
// Tokens which get called during parsing.
class DirectionToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mDirectionToken;
class EmitsToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mEmitsToken;
class AngleToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mAngleToken;
class EmissionRateToken : public IToken
{
virtual void parse(ParticleScriptParser* parser);
virtual void postParse(ParticleScriptParser* parser);
} mEmissionRateToken;
class TimeToLiveToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mTimeToLiveToken;
class MassToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mMassToken;
class VelocityToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mVelocityToken;
class DurationToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mDurationToken;
class RepeatDelayToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mRepeatDelayToken;
class ParticleAllDimensionsToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mParticleAllDimensionsToken;
class ParticleWidthToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mParticleWidthToken;
class ParticleHeightToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mParticleHeightToken;
class ParticleDepthToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mParticleDepthToken;
class AutoDirectionToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mAutoDirectionToken;
class ForceEmissionToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mForceEmissionToken;
class ColourToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mColourToken;
class ColourRangeStartToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mColourRangeStartToken;
class ColourRangeEndToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mColourRangeEndToken;
};
}
#endif
|
[
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
] |
[
[
[
1,
67
]
]
] |
983463648d8b792116bdcdbb85bb4018eaf082b3
|
d7320c9c1f155e2499afa066d159bfa6aa94b432
|
/ghostgproxy/statsdota.h
|
0ab1b267f44444dd171424918b8733635323b7c4
|
[] |
no_license
|
HOST-PYLOS/ghostnordicleague
|
c44c804cb1b912584db3dc4bb811f29f3761a458
|
9cb262d8005dda0150b75d34b95961d664b1b100
|
refs/heads/master
| 2016-09-05T10:06:54.279724 | 2011-02-23T08:02:50 | 2011-02-23T08:02:50 | 32,241,503 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,317 |
h
|
/*
Copyright [2008] [Trevor Hogan]
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.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#ifndef STATSDOTA_H
#define STATSDOTA_H
//
// CStatsDOTA
//
class CDBDotAPlayer;
class CDBGamePlayer;
class CStatsDOTA : public CStats
{
private:
CDBDotAPlayer *m_Players[12];
uint32_t m_Winner;
uint32_t m_Min;
uint32_t m_Sec;
uint32_t m_GameStart;
public:
CStatsDOTA( CBaseGame *nGame );
virtual ~CStatsDOTA( );
virtual void SetWinner(uint32_t winner) { m_Winner = winner; }
virtual bool ProcessAction( CIncomingAction *Action, CGHostDB *DB, CGHost *GHost );
virtual void Save( CGHost *GHost, vector<CDBGamePlayer *>& DBGamePlayers, CGHostDB *DB, uint32_t GameID );
};
#endif
|
[
"fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e",
"[email protected]@4a4c9648-eef2-11de-9456-cf00f3bddd4e"
] |
[
[
[
1,
47
],
[
49,
51
]
],
[
[
48,
48
]
]
] |
12d4c578fb074d27b197bcc9104ef822138df011
|
fb9e54f77ffc505df30396c53375b03c4e952d5c
|
/LLAH.h
|
bd58485e4e7aa15acf032a1c071ca89f39202c22
|
[] |
no_license
|
SPhoenixx/NAM
|
61c4d9b175c437281ed269be405bddc067efc963
|
7555c35d13219896d1b5e86aa1041d2baee58349
|
refs/heads/master
| 2020-12-25T02:30:40.293089 | 2011-07-13T10:02:42 | 2011-07-13T10:02:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,509 |
h
|
/*
This file is part of UCHIYAMARKERS, a software for random dot markers.
Copyright (c) 2011 Hideaki Uchiyama
You can use, copy, modify and re-distribute this software
for non-profit purposes.
*/
#ifndef LLAH_H
#define LLAH_H
#include <vector>
#include <algorithm>
#include <iostream>
#include "mylib/myimage.h"
#include "mylib/mymat.h"
#include "mylib/mylabel.h"
#include "llahparam.h"
#include "bloblist.h"
#include "hashtable.h"
#include "paperlist.h"
#include "paper.h"
typedef std::list<Paper*> visible;
class LLAH
{
public:
void SetHash(Paper* paper, const eblobs *blobs);
void AddPaper(const char *name);
visible* GetVisiblePaper();
void UpdateTracking(Paper* paper, const double repro);
bool FindPaper(const int min, const double repro=5.0);
double ComputeAffine(const blob *target, const combi &nm, const combi &mk) const;
unsigned ComputeIndex(const blob *target, const combi &nm) const;
void ComputeDescriptors(blob *target);
void RetrievebyTracking();
void RetrievebyMatching();
void CoordinateTransform(const double h);
void SetPts();
void Extract(const MyImage &src, int threshold);
void Init(const int iw, const int ih);
void DrawBinary(MyImage &dst) const;
void DrawPts(MyImage &dst) const;
private:
MyImage m_gray;
MyImage m_binary;
MyLabel m_label;
LLAHParam m_param;
BlobList m_bloblist;
HashTable m_table;
HashTable m_trackingtable;
PaperList m_paperlist;
visible m_visible;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
64
]
]
] |
a7ba63b6c842f2fc16f634c3b67e252895b9facd
|
b7c505dcef43c0675fd89d428e45f3c2850b124f
|
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qsortfilterproxymodel.h
|
9b7de967a630526845ad61b197db11f1bac39d6a
|
[
"BSD-2-Clause"
] |
permissive
|
pranet/bhuman2009fork
|
14e473bd6e5d30af9f1745311d689723bfc5cfdb
|
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
|
refs/heads/master
| 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,791 |
h
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSORTFILTERPROXYMODEL_H
#define QSORTFILTERPROXYMODEL_H
#include <QtGui/qabstractproxymodel.h>
#ifndef QT_NO_SORTFILTERPROXYMODEL
#include <QtCore/qregexp.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
class QSortFilterProxyModelPrivate;
class QSortFilterProxyModelLessThan;
class QSortFilterProxyModelGreaterThan;
class Q_GUI_EXPORT QSortFilterProxyModel : public QAbstractProxyModel
{
friend class QSortFilterProxyModelLessThan;
friend class QSortFilterProxyModelGreaterThan;
Q_OBJECT
Q_PROPERTY(QRegExp filterRegExp READ filterRegExp WRITE setFilterRegExp)
Q_PROPERTY(int filterKeyColumn READ filterKeyColumn WRITE setFilterKeyColumn)
Q_PROPERTY(bool dynamicSortFilter READ dynamicSortFilter WRITE setDynamicSortFilter)
Q_PROPERTY(Qt::CaseSensitivity filterCaseSensitivity READ filterCaseSensitivity WRITE setFilterCaseSensitivity)
Q_PROPERTY(Qt::CaseSensitivity sortCaseSensitivity READ sortCaseSensitivity WRITE setSortCaseSensitivity)
Q_PROPERTY(bool isSortLocaleAware READ isSortLocaleAware WRITE setSortLocaleAware)
Q_PROPERTY(int sortRole READ sortRole WRITE setSortRole)
Q_PROPERTY(int filterRole READ filterRole WRITE setFilterRole)
public:
QSortFilterProxyModel(QObject *parent = 0);
~QSortFilterProxyModel();
void setSourceModel(QAbstractItemModel *sourceModel);
QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const;
QItemSelection mapSelectionToSource(const QItemSelection &proxySelection) const;
QItemSelection mapSelectionFromSource(const QItemSelection &sourceSelection) const;
QRegExp filterRegExp() const;
void setFilterRegExp(const QRegExp ®Exp);
int filterKeyColumn() const;
void setFilterKeyColumn(int column);
Qt::CaseSensitivity filterCaseSensitivity() const;
void setFilterCaseSensitivity(Qt::CaseSensitivity cs);
Qt::CaseSensitivity sortCaseSensitivity() const;
void setSortCaseSensitivity(Qt::CaseSensitivity cs);
bool isSortLocaleAware() const;
void setSortLocaleAware(bool on);
int sortColumn() const;
Qt::SortOrder sortOrder() const;
bool dynamicSortFilter() const;
void setDynamicSortFilter(bool enable);
int sortRole() const;
void setSortRole(int role);
int filterRole() const;
void setFilterRole(int role);
public Q_SLOTS:
void setFilterRegExp(const QString &pattern);
void setFilterWildcard(const QString &pattern);
void setFilterFixedString(const QString &pattern);
void clear();
void invalidate();
protected:
virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
virtual bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const;
virtual bool lessThan(const QModelIndex &left, const QModelIndex &right) const;
void filterChanged();
void invalidateFilter();
public:
#ifdef Q_NO_USING_KEYWORD
inline QObject *parent() const { return QObject::parent(); }
#else
using QObject::parent;
#endif
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &child) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
bool setHeaderData(int section, Qt::Orientation orientation,
const QVariant &value, int role = Qt::EditRole);
QMimeData *mimeData(const QModelIndexList &indexes) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent);
bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex());
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex());
void fetchMore(const QModelIndex &parent);
bool canFetchMore(const QModelIndex &parent) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QModelIndex buddy(const QModelIndex &index) const;
QModelIndexList match(const QModelIndex &start, int role,
const QVariant &value, int hits = 1,
Qt::MatchFlags flags =
Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const;
QSize span(const QModelIndex &index) const;
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
QStringList mimeTypes() const;
Qt::DropActions supportedDropActions() const;
private:
Q_DECLARE_PRIVATE(QSortFilterProxyModel)
Q_DISABLE_COPY(QSortFilterProxyModel)
Q_PRIVATE_SLOT(d_func(), void _q_sourceDataChanged(const QModelIndex &source_top_left, const QModelIndex &source_bottom_right))
Q_PRIVATE_SLOT(d_func(), void _q_sourceHeaderDataChanged(Qt::Orientation orientation, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceReset())
Q_PRIVATE_SLOT(d_func(), void _q_sourceLayoutAboutToBeChanged())
Q_PRIVATE_SLOT(d_func(), void _q_sourceLayoutChanged())
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeInserted(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsInserted(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsRemoved(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeInserted(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsInserted(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsRemoved(const QModelIndex &source_parent, int start, int end))
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // QT_NO_SORTFILTERPROXYMODEL
#endif // QSORTFILTERPROXYMODEL_H
|
[
"alon@rogue.(none)"
] |
[
[
[
1,
199
]
]
] |
9a8bce9134a1b873fe56741d43c71775824b452d
|
7745a8d148e55e22dca4955f7ca4e83199495c17
|
/test/test_fusion_hash.cpp
|
586c26828f15957f0e2842f8a1e1c34cfef34024
|
[] |
no_license
|
yak1ex/packrat_qi
|
e6c8058e39a77d8f6c1559c292b52cdb14b8608f
|
423d08e48abf1c06fd5f2acd812295ec6e1b3d11
|
refs/heads/master
| 2020-06-05T02:57:45.157294 | 2011-06-28T17:24:46 | 2011-06-28T17:24:46 | 1,967,192 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,200 |
cpp
|
/***********************************************************************/
/* */
/* test_fusion_hash.cpp: Test code for hash function for Fusion seq. */
/* */
/* Written by Yak! / Yasutaka ATARASHI */
/* */
/* This software is distributed under the terms of */
/* Boost Software License 1.0 */
/* (http://www.boost.org/LICENSE_1_0.txt). */
/* */
/* $Id$ */
/* */
/***********************************************************************/
#include "fusion_hash.hpp"
#include <boost/test/auto_unit_test.hpp>
#include <boost/fusion/include/make_vector.hpp>
#include <boost/array.hpp>
#include <boost/fusion/include/boost_array.hpp>
#include <boost/fusion/include/iterator_range.hpp>
#include <boost/fusion/include/begin.hpp>
#include <boost/fusion/include/end.hpp>
#include <boost/fusion/include/next.hpp>
#include <boost/fusion/include/prior.hpp>
BOOST_AUTO_TEST_CASE(test_vector)
{
using yak::fusion::hash;
hash hasher;
using boost::fusion::make_vector;
BOOST_CHECK_EQUAL(hasher(make_vector(1)), hasher(make_vector(1)));
BOOST_CHECK_EQUAL(hasher(make_vector(1, 3.5)), hasher(make_vector(1, 3.5)));
BOOST_CHECK_EQUAL(hasher(make_vector(1, 3.5, std::string("hoge"))), hasher(make_vector(1, 3.5, std::string("hoge"))));
BOOST_WARN_NE(hasher(make_vector(1)), hasher(make_vector(2)));
BOOST_WARN_NE(hasher(make_vector(1)), hasher(make_vector(1, 3.5)));
BOOST_WARN_NE(hasher(make_vector(1)), hasher(make_vector(1, 3.5, std::string("hoge"))));
}
BOOST_AUTO_TEST_CASE(test_array)
{
using yak::fusion::hash;
hash hasher;
boost::array<int ,3> arr1 = {1, 2, 3};
boost::array<int ,3> arr2 = {1, 2, 3};
boost::array<int ,4> arr3 = {1, 2, 3, 4};
boost::array<int ,4> arr4 = {1, 2, 3, 4};
BOOST_CHECK_EQUAL(hasher(arr1), hasher(arr1));
BOOST_CHECK_EQUAL(hasher(arr1), hasher(arr2));
BOOST_CHECK_EQUAL(hasher(arr3), hasher(arr4));
BOOST_CHECK_EQUAL(hasher(arr3), hasher(arr3));
BOOST_WARN_NE(hasher(arr1), hasher(arr3));
BOOST_WARN_NE(hasher(arr2), hasher(arr4));
}
BOOST_AUTO_TEST_CASE(test_iterator_range)
{
using yak::fusion::hash;
hash hasher;
typedef boost::fusion::vector<int, char, double> v1_type;
typedef boost::fusion::vector<int, char, double, std::string> v2_type;
v1_type v1(1, 'c', 3.5);
v2_type v2(1, 'c', 3.5, std::string("hoge"));
typedef boost::fusion::result_of::begin<v1_type>::type v10_type;
typedef boost::fusion::result_of::end<v1_type>::type v13_type;
typedef boost::fusion::result_of::begin<v2_type>::type v20_type;
typedef boost::fusion::result_of::end<v2_type>::type v24_type;
typedef boost::fusion::result_of::prior<v24_type>::type v23_type;
v10_type v10(boost::fusion::begin(v1));
v13_type v13(boost::fusion::end(v1));
v20_type v20(boost::fusion::begin(v2));
v24_type v24(boost::fusion::end(v2));
v23_type v23(boost::fusion::prior(v24));
BOOST_CHECK_EQUAL(hasher(boost::fusion::iterator_range<v10_type, v13_type>(v10, v13)), hasher(boost::fusion::iterator_range<v10_type, v13_type>(v10, v13)));
BOOST_CHECK_EQUAL(hasher(boost::fusion::iterator_range<v10_type, v13_type>(v10, v13)), hasher(boost::fusion::iterator_range<v20_type, v23_type>(v20, v23)));
BOOST_CHECK_EQUAL(hasher(boost::fusion::iterator_range<v20_type, v23_type>(v20, v23)), hasher(boost::fusion::iterator_range<v20_type, v23_type>(v20, v23)));
BOOST_CHECK_EQUAL(hasher(boost::fusion::iterator_range<v20_type, v24_type>(v20, v24)), hasher(boost::fusion::iterator_range<v20_type, v24_type>(v20, v24)));
BOOST_WARN_NE(hasher(boost::fusion::iterator_range<v20_type, v24_type>(v20, v24)), hasher(boost::fusion::iterator_range<v10_type, v13_type>(v10, v13)));
}
// TODO: test hash_combine
|
[
"[email protected]"
] |
[
[
[
1,
96
]
]
] |
a8f06532b9b57ed885b8331ab29117438e806910
|
a4929304d922f1824e9b067fc1c159812bce04b6
|
/whuser/WeightedDistribution.h
|
152c49006ebf00abbfc5aa67019e8efb8ff6312b
|
[] |
no_license
|
mesta1/longhorn-pokerlab
|
2526fc02f11450861075fbbe636caf62aab86274
|
0bab429dd2ef7d4dba7f6df0a4fd3aeeba214437
|
refs/heads/master
| 2016-09-10T17:58:02.784080 | 2008-08-04T23:30:34 | 2008-08-04T23:30:34 | 34,800,023 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,444 |
h
|
#pragma once
#include <iostream>
using namespace std;
class WeightedDistribution
{
public:
WeightedDistribution(int); // constructor which creates a table of a given size
int rand(); // get a random integer from (0-table_size) using weight distribution
void SetWeight(const int, const double); // set the weight at an index
double GetWeight(int) const; // get the weight at an index
double GetNormalized(int) const; // get the normalized weight at an index
void SetMask(const int, const double); // non-destructively set the opacity at an index
void ClearMask(void); // clear the entire mask (set opacity to 100%)
void Normalize(void); // reevaluate all weights so that weight_total=1;
void Serialize(std::ostream&); // convert weight table to byte stream;
int Unserialize(std::istream&); // read weight table from byte stream;
double operator[](int) const; // get the weight at an index
WeightedDistribution& operator[](int); // set the weight at an index
public:
WeightedDistribution(void); // default constructor
~WeightedDistribution(void);
// Right now the distribution is stored as an array.
// Since the rand() member function operates on an
// array in O(n/2) time on average, this would be better
// implemented as a binomia
double* weight_table;
double* mask_table;
double weight_total;
double mask_total;
int table_size;
};
|
[
"dconrad@50e7afbe-b451-0410-9e05-e1277091fc22"
] |
[
[
[
1,
43
]
]
] |
256172b6cab1297514fa8ac913ceedc37a3db660
|
27167a5a0340fdc9544752bd724db27d3699a9a2
|
/include/dockwins/DotNetTabCtrl.h
|
8e71c67e39318af7ffbf55ebba8f79b345849189
|
[] |
no_license
|
eaglexmw-gmail/wtl-dockwins
|
2b464be3958e1683cd668a10abafb528f43ac695
|
ae307a1978b73bfd2823945068224bb6c01ae350
|
refs/heads/master
| 2020-06-30T21:03:26.075864 | 2011-10-23T12:50:14 | 2011-10-23T12:50:14 | 200,951,487 | 2 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 52,606 |
h
|
#ifndef __DOTNET_TABCTRL_H__
#define __DOTNET_TABCTRL_H__
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CDotNetTabCtrl - Tab control derived from CCustomTabCtrl
// meant to look like the tabs in VS.Net (MDI tabs,
// solution explorer tabs, etc.)
// CDotNetButtonTabCtrl - Tab control derived from CCustomTabCtrl
// meant to look like VS.Net view of HTML with the Design/HTML buttons
//
//
// Written by Daniel Bowen ([email protected]).
// Copyright (c) 2001-2004 Daniel Bowen.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Beware of bugs.
//
// History (Date/Author/Description):
// ----------------------------------
//
// 2005/07/13: Daniel Bowen
// - Namespace qualify the use of more ATL and WTL classes.
//
// 2005/03/14: Daniel Bowen
// - Fix warnings when compiling for 64-bit.
//
// 2004/06/28: Daniel Bowen:
// - Clean up warnings on level 4
//
// 2004/06/21: Peter Carlson:
// - "CanClose" for items.
//
// 2004/04/29: Daniel Bowen
// - Update CDotNetTabCtrlImpl::OnSettingChange so that
// if the color depth is not greater than 8bpp
// (so, 256 colors or less), instead of this
// m_hbrBackground = CDCHandle::GetHalftoneBrush();
// (which makes things unreadable at 256 colors), do this:
// m_hbrBackground.CreateSysColorBrush(COLOR_WINDOW);
// - Support for highlighting items.
// Add CCustomTabItem::GetHighlight/SetHighlight.
// Uses the custom draw state CDIS_MARKED.
//
// 2004/01/06: Daniel Bowen
// - Fix compile issue under ICL thanks to Richard Crossley.
// CDotNetButtonTabCtrl missing template parameters.
//
// 2003/08/01: Daniel Bowen
// - CDotNetButtonTabCtrl can now be used for MDI tabs.
// - There is now a CDotNetButtonTabCtrlImpl, which
// CDotNetButtonTabCtrl inherits from.
// - Reorganize so that CDotNetTabCtrlImpl is broken up a little bit
// more into overridable pieces, and have CDotNetButtonTabCtrlImpl
// inherit from CDotNetTabCtrlImpl. Have CDotNetButtonTabCtrlImpl
// only override the parts of CDotNetTabCtrlImpl needed.
//
// 2003/06/27: Daniel Bowen
// - Replace DECLARE_WND_CLASS with DECLARE_WND_CLASS_EX.
// Use CS_DBLCLKS as the style and COLOR_WINDOW as the brush -
// which essentially means that it doesn't use CS_HREDRAW or CS_VREDRAW now.
//
// 2002/12/05: Daniel Bowen
// - In CDotNetTabCtrlImpl::UpdateLayout_Default,
// the code that calculates nRatioWithSelectionFullSize
// would sometimes get a 0 in the divisor.
// Guard against divide-by-0.
// - Handle WM_SYSCOLORCHANGE in case its broadcast to us
// from a top-level window. Call OnSettingChange.
//
// 2002/11/13: Daniel Bowen
// - CDotNetTabCtrl:
// * Tweaks so that CDotNetTabCtrl matches just a little more
// closely to the tabs in VS.NET (when tabs are on top).
// * Override new "CalcSize_NonClient" method as part of the
// tweaks for CDotNetTabCtrl. Currently, only the left
// and right sides of the client area are adjusted for
// non-client areas (since the drawing code already considers
// non-client areas above and below in its drawing).
// In the future, non-client areas could be accounted for
// in CalcSize_NonClient, and the drawing code could
// be updated appropriately.
// * New CTCS_FLATEDGE style. CDotNetTabCtrl asks about this
// style when drawing the outline around the tab. A good
// use for this style is if you are using the tab control
// for the MDI tabs, and you have your MDIClient drawn flat
// (like VS.NET)
//
// 2002/07/16: Daniel Bowen
// - Fix problem that would cause applications using CDotNetTabCtrl
// with CTCS_CLOSEBUTTON and/or CTCS_SCROLL to not exit "cleanly".
// There were 2 places referencing m_tooltip that needed to
// first check if(m_tooltip.IsWindow()).
//
// 2002/06/12: Daniel Bowen
// - Publish codeproject article. For history prior
// to the release of the article, please see the article
// and the section "Note to previous users"
#ifndef __CUSTOMTABCTRL_H__
#include "CustomTabCtrl.h"
#endif
// NOTE: If you are compiling under VC7, be sure to put the following in
// your precompiled header:
//
//extern "C" const int _fltused = 0;
template<typename T, typename TItem = CCustomTabItem, class TBase = ATL::CWindow, class TWinTraits = CCustomTabCtrlWinTraits>
class CDotNetTabCtrlImpl :
public CCustomTabCtrl<T, TItem, TBase, TWinTraits>
{
protected:
typedef CDotNetTabCtrlImpl<T, TItem, TBase, TWinTraits> thisClass;
typedef CCustomTabCtrl<T, TItem, TBase, TWinTraits> customTabClass;
protected:
CBrush m_hbrBackground;
COLORREF m_clrTextInactiveTab, m_clrSelectedTab;
signed char m_nFontSizeTextTopOffset;
const signed char m_nMinWidthToDisplayText;
// Constructor
public:
CDotNetTabCtrlImpl() :
m_clrTextInactiveTab(::GetSysColor(COLOR_GRAYTEXT)),
m_clrSelectedTab(::GetSysColor(COLOR_BTNFACE)),
m_nFontSizeTextTopOffset(0),
m_nMinWidthToDisplayText(12)
{
}
// Message Handling
public:
DECLARE_WND_CLASS_EX(_T("WTL_DotNetTabCtrl"), CS_DBLCLKS, COLOR_WINDOW)
BEGIN_MSG_MAP(thisClass)
MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
MESSAGE_HANDLER(WM_SYSCOLORCHANGE, OnSettingChange)
CHAIN_MSG_MAP(customTabClass)
END_MSG_MAP()
LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DWORD dwStyle = this->GetStyle();
// Initialize/Reinitialize font
// Visual Studio.Net seems to use the "icon" font for the tabs
LOGFONT lfIcon = { 0 };
::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIcon), &lfIcon, 0);
bool bResetFont = true;
if (!m_font.IsNull())
{
LOGFONT lf = {0};
if (m_font.GetLogFont(&lf))
{
if (lstrcmpi(lf.lfFaceName, lfIcon.lfFaceName) == 0 &&
lf.lfHeight == lfIcon.lfHeight)
{
bResetFont = false;
}
}
}
if (bResetFont)
{
if (!m_font.IsNull()) m_font.DeleteObject();
if (!m_fontSel.IsNull()) m_fontSel.DeleteObject();
HFONT font = m_font.CreateFontIndirect(&lfIcon);
if (font == NULL)
{
m_font.Attach(AtlGetDefaultGuiFont());
}
if (CTCS_BOLDSELECTEDTAB == (dwStyle & CTCS_BOLDSELECTEDTAB))
{
lfIcon.lfWeight = FW_BOLD;
}
font = m_fontSel.CreateFontIndirect(&lfIcon);
if (font == NULL)
{
m_fontSel.Attach(AtlGetDefaultGuiFont());
}
}
// Background brush
if (!m_hbrBackground.IsNull()) m_hbrBackground.DeleteObject();
WTL::CWindowDC dcWindow(NULL);
int nBitsPerPixel = dcWindow.GetDeviceCaps(BITSPIXEL);
if (nBitsPerPixel > 8)
{
//COLORREF clrBtnHilite = ::GetSysColor(COLOR_BTNHILIGHT);
//COLORREF clrBtnFace = ::GetSysColor(COLOR_BTNFACE);
//m_clrBackground =
// RGB( GetRValue(clrBtnFace) + ((GetRValue(clrBtnHilite) - GetRValue(clrBtnFace)) / 3 * 2),
// GetGValue(clrBtnFace) + ((GetGValue(clrBtnHilite) - GetGValue(clrBtnFace)) / 3 * 2),
// GetBValue(clrBtnFace) + ((GetBValue(clrBtnHilite) - GetBValue(clrBtnFace)) / 3 * 2),
// );
//m_hbrBackground.CreateSolidBrush(m_clrBackground);
COLORREF clrBtnFace = ::GetSysColor(COLOR_BTNFACE);
// This is a brave attempt to mimic the algorithm that Visual Studio.Net
// uses to calculate the tab's background color and inactive tab color.
// The other colors that VS.Net uses seems to be standard ones,
// but these two colors are calculated.
BYTE nRed = 0, nGreen = 0, nBlue = 0, nMax = 0;
// Early experiments seemed to reveal that the background color is dependant
// on COLOR_BTNFACE. The following algorithm is just an attempt
// to match several empirical results. I tested with 20 variations
// on COLOR_BTNFACE and kept track of what the tab background became.
// I then brought the numbers into Excel, and started crunching on the numbers
// until I came up with a formula that seems to pretty well match.
nRed = GetRValue(clrBtnFace);
nGreen = GetGValue(clrBtnFace);
nBlue = GetBValue(clrBtnFace);
nMax = (nRed > nGreen) ? ((nRed > nBlue) ? nRed : nBlue) : ((nGreen > nBlue) ? nGreen : nBlue);
const BYTE nMagicBackgroundOffset = (nMax > (0xFF - 35)) ? (BYTE)(0xFF - nMax) : (BYTE)35;
if (nMax == 0)
{
nRed = (BYTE)(nRed + nMagicBackgroundOffset);
nGreen = (BYTE)(nGreen + nMagicBackgroundOffset);
nBlue = (BYTE)(nBlue + nMagicBackgroundOffset);
}
else
{
nRed = (BYTE)(nRed + (nMagicBackgroundOffset * (nRed / (double)nMax) + 0.5));
nGreen = (BYTE)(nGreen + (nMagicBackgroundOffset * (nGreen / (double)nMax) + 0.5));
nBlue = (BYTE)(nBlue + (nMagicBackgroundOffset * (nBlue / (double)nMax) + 0.5));
}
m_hbrBackground.CreateSolidBrush(RGB(nRed, nGreen, nBlue));
// The inactive tab color seems to be calculated in a similar way to
// the tab background, only instead of lightening BNTFACE, it darkens GRAYTEXT.
COLORREF clrGrayText = ::GetSysColor(COLOR_GRAYTEXT);
nRed = GetRValue(clrGrayText);
nGreen = GetGValue(clrGrayText);
nBlue = GetBValue(clrGrayText);
nMax = (nRed > nGreen) ? ((nRed > nBlue) ? nRed : nBlue) : ((nGreen > nBlue) ? nGreen : nBlue);
const BYTE nMagicInactiveOffset = 43;
if (nMax != 0)
{
if (nRed < nMagicInactiveOffset)
nRed = (BYTE)(nRed / 2);
else
nRed = (BYTE)(nRed - (nMagicInactiveOffset * (nRed / (double)nMax) + 0.5));
if (nGreen < nMagicInactiveOffset)
nGreen = (BYTE)(nGreen / 2);
else
nGreen = (BYTE)(nGreen - (nMagicInactiveOffset * (nGreen / (double)nMax) + 0.5));
if (nBlue < nMagicInactiveOffset)
nBlue = (BYTE)(nBlue / 2);
else
nBlue = (BYTE)(nBlue - (nMagicInactiveOffset * (nBlue / (double)nMax) + 0.5));
}
m_clrTextInactiveTab = RGB(nRed, nGreen, nBlue);
}
else
{
m_hbrBackground.CreateSysColorBrush(COLOR_WINDOW);
m_clrTextInactiveTab = ::GetSysColor(COLOR_GRAYTEXT);
}
m_settings.iIndent = 5;
m_settings.iPadding = 4;
m_settings.iMargin = 3;
m_settings.iSelMargin = 3;
int nHeightLogicalUnits = -lfIcon.lfHeight;
// In MSDN for "LOGFONT", they give the following formula for calculating
// the log font height given a point size.
//long lfHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
const int nNominalFontLogicalUnits = 11; // 8 point Tahoma with 96 DPI
m_nFontSizeTextTopOffset = (BYTE)((nHeightLogicalUnits - nNominalFontLogicalUnits) / 2);
T* pT = static_cast<T*>(this);
pT->UpdateLayout();
pT->Invalidate();
return 0;
}
// Overrideables
public:
void DrawBackground(RECT rcClient, LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
// Set up the text color and background mode
dc.SetTextColor(lpNMCustomDraw->clrBtnText);
dc.SetBkMode(TRANSPARENT);
RECT rcClip = {0};
dc.GetClipBox(&rcClip);
if (::EqualRect(&rcClip, &m_rcCloseButton) ||
::EqualRect(&rcClip, &m_rcScrollRight) ||
::EqualRect(&rcClip, &m_rcScrollLeft))
{
// Paint needed in only "other button" area
HBRUSH hOldBrush = dc.SelectBrush(lpNMCustomDraw->hBrushBackground);
dc.PatBlt(rcClip.left, rcClip.top, rcClip.right - rcClip.left, rcClip.bottom - rcClip.top, PATCOPY);
dc.SelectBrush(hOldBrush);
}
else
{
// Paint needed in tab item area or more
// Erase Background
// (do it here instead of a handler for WM_ERASEBKGND
// so that we can do flicker-free drawing with the help
// of COffscreenDrawRect that's in the base class)
// TODO: Don't "erase" entire client area.
// Do a smarter erase of just what needs it
RECT rc = rcClient;
HBRUSH hOldBrush = dc.SelectBrush(lpNMCustomDraw->hBrushBackground);
dc.PatBlt(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY);
dc.SelectBrush(hOldBrush);
// Connect with the client area.
DWORD dwStyle = this->GetStyle();
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
rc.bottom = rc.top + 3;
dc.FillSolidRect(&rc, lpNMCustomDraw->clrBtnFace);
CPen penText;
penText.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnText);
CPenHandle penOld = dc.SelectPen(penText);
dc.MoveTo(rc.left, rc.bottom);
dc.LineTo(rc.right, rc.bottom);
dc.SelectPen(penOld);
}
else
{
int nOrigTop = rc.top;
rc.top = rc.bottom - 2;
dc.FillSolidRect(&rc, lpNMCustomDraw->clrBtnFace);
CPen penHilight;
penHilight.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnHighlight);
CPenHandle penOld = dc.SelectPen(penHilight);
dc.MoveTo(rc.left, rc.top - 1);
dc.LineTo(rc.right, rc.top - 1);
rc.top = nOrigTop;
CPen penShadow, pen3D;
penShadow.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnShadow);
pen3D.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnFace);
dc.SelectPen(penShadow);
dc.MoveTo(rc.left, rc.bottom);
dc.LineTo(rc.left, rc.top);
dc.LineTo(rc.right - 1, rc.top);
if (0 == (dwStyle & CTCS_FLATEDGE))
{
dc.SelectPen(penHilight);
}
dc.LineTo(rc.right - 1, rc.bottom);
dc.SelectPen(pen3D);
dc.MoveTo(rc.right - 2, rc.bottom - 3);
dc.LineTo(rc.right - 2, rc.top);
dc.MoveTo(rc.left + 1, rc.bottom - 3);
dc.LineTo(rc.left + 1, rc.top);
dc.SelectPen(penOld);
}
}
}
void DrawItem_InitBounds(DWORD dwStyle, RECT rcItem, RECT& rcTab, RECT& rcText, int& nIconVerticalCenter)
{
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
rcTab.top += 3;
rcTab.bottom -= 2;
rcText.top = rcTab.top + 1 + m_nFontSizeTextTopOffset;
rcText.bottom = rcItem.bottom;
//nIconVerticalCenter = rcTab.top + (rc.bottom - rcTab.top) / 2;
//nIconVerticalCenter = rcTab.top + rcText.Height() / 2;
nIconVerticalCenter = (rcItem.bottom + rcItem.top) / 2 + rcTab.top / 2;
}
else
{
rcTab.top += 3;
rcTab.bottom -= 2;
rcText.top = rcItem.top + 1 + m_nFontSizeTextTopOffset;
rcText.bottom = rcItem.bottom;
nIconVerticalCenter = (rcItem.bottom + rcItem.top) / 2 + rcTab.top / 2;
}
}
void DrawItem_TabSelected(DWORD dwStyle, LPNMCTCCUSTOMDRAW lpNMCustomDraw, RECT& rcTab)
{
// Tab is selected, so paint tab folder
bool bHighlighted = (CDIS_MARKED == (lpNMCustomDraw->nmcd.uItemState & CDIS_MARKED));
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
rcTab.right--;
if (bHighlighted)
{
dc.FillSolidRect(&rcTab, lpNMCustomDraw->clrHighlight);
}
else
{
dc.FillSolidRect(&rcTab, lpNMCustomDraw->clrSelectedTab);
}
WTL::CPen penText, penHilight;
penText.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnText);
penHilight.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnHighlight);
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
WTL::CPenHandle penOld = dc.SelectPen(penText);
dc.MoveTo(rcTab.right, rcTab.top);
dc.LineTo(rcTab.right, rcTab.bottom);
dc.LineTo(rcTab.left, rcTab.bottom);
dc.SelectPen(penHilight);
dc.LineTo(rcTab.left, rcTab.top - 1);
dc.SelectPen(penOld);
}
else
{
WTL::CPenHandle penOld = dc.SelectPen(penHilight);
dc.MoveTo(rcTab.left, rcTab.bottom - 1);
dc.LineTo(rcTab.left, rcTab.top);
dc.LineTo(rcTab.right, rcTab.top);
dc.SelectPen(penText);
dc.LineTo(rcTab.right, rcTab.bottom);
dc.SelectPen(penOld);
}
}
void DrawItem_TabInactive(DWORD dwStyle, LPNMCTCCUSTOMDRAW lpNMCustomDraw, RECT& rcTab)
{
// Tab is not selected
bool bHighlighted = (CDIS_MARKED == (lpNMCustomDraw->nmcd.uItemState & CDIS_MARKED));
int nItem = (int)lpNMCustomDraw->nmcd.dwItemSpec;
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
if (bHighlighted)
{
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
RECT rcHighlight = {rcTab.left + 1, rcTab.top + 3, rcTab.right - 2, rcTab.bottom - 1};
if (nItem - 1 == m_iCurSel) rcHighlight.left += 1; // Item to the right of the selected tab
dc.FillSolidRect(&rcHighlight, lpNMCustomDraw->clrHighlight);
}
else
{
RECT rcHighlight = {rcTab.left + 1, rcTab.top + 2, rcTab.right - 2, rcTab.bottom - 2};
if (nItem - 1 == m_iCurSel) rcHighlight.left += 1; // Item to the right of the selected tab
dc.FillSolidRect(&rcHighlight, lpNMCustomDraw->clrHighlight);
}
}
// Draw division line on right, unless we're the item
// on the left of the selected tab
if (nItem + 1 == m_iCurSel)
{
// Item just left of selected tab
}
else
{
WTL::CPen pen;
pen.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnShadow);
WTL::CPenHandle penOld = dc.SelectPen(pen);
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
// Important! Be sure and keep within "our" tab area horizontally
dc.MoveTo(rcTab.right - 1, rcTab.top + 3);
dc.LineTo(rcTab.right - 1, rcTab.bottom - 1);
}
else
{
// Important! Be sure and keep within "our" tab area horizontally
dc.MoveTo(rcTab.right - 1, rcTab.top + 2);
dc.LineTo(rcTab.right - 1, rcTab.bottom - 2);
}
dc.SelectPen(penOld);
}
}
void DrawItem_ImageAndText(DWORD /*dwStyle*/, LPNMCTCCUSTOMDRAW lpNMCustomDraw, int nIconVerticalCenter, RECT& rcTab, RECT& rcText)
{
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
bool bHighlighted = (CDIS_MARKED == (lpNMCustomDraw->nmcd.uItemState & CDIS_MARKED));
bool bSelected = (CDIS_SELECTED == (lpNMCustomDraw->nmcd.uItemState & CDIS_SELECTED));
bool bHot = (CDIS_HOT == (lpNMCustomDraw->nmcd.uItemState & CDIS_HOT));
int nItem = (int)lpNMCustomDraw->nmcd.dwItemSpec;
TItem* pItem = this->GetItem(nItem);
HFONT hOldFont = NULL;
if (bSelected)
{
hOldFont = dc.SelectFont(lpNMCustomDraw->hFontSelected);
}
else
{
hOldFont = dc.SelectFont(lpNMCustomDraw->hFontInactive);
}
COLORREF crPrevious = 0;
if (bHighlighted)
{
crPrevious = dc.SetTextColor(lpNMCustomDraw->clrHighlightText);
}
else if (bHot)
{
crPrevious = dc.SetTextColor(lpNMCustomDraw->clrHighlightHotTrack);
}
else if (bSelected)
{
crPrevious = dc.SetTextColor(lpNMCustomDraw->clrTextSelected);
}
else
{
crPrevious = dc.SetTextColor(lpNMCustomDraw->clrTextInactive);
}
//--------------------------------------------
// This is how CDotNetTabCtrlImpl interprets padding, margin, etc.:
//
// M - Margin
// P - Padding
// I - Image
// Text - Tab Text
//
// With image:
// __________________________
//
// | M | I | P | Text | P | M |
// --------------------------
//
// Without image:
// ______________________
//
// | M | P | Text | P | M |
// ----------------------
//rcText.left += (bSelected ? m_settings.iSelMargin : m_settings.iMargin);
rcText.left += m_settings.iMargin;
rcText.right -= m_settings.iMargin;
if (pItem->UsingImage() && !m_imageList.IsNull())
{
// Draw the image.
IMAGEINFO ii = {0};
int nImageIndex = pItem->GetImageIndex();
m_imageList.GetImageInfo(nImageIndex, &ii);
if ((ii.rcImage.right - ii.rcImage.left) < (rcTab.right - rcTab.left))
{
int nImageHalfHeight = (ii.rcImage.bottom - ii.rcImage.top) / 2;
m_imageList.Draw(dc, nImageIndex, rcText.left, nIconVerticalCenter - nImageHalfHeight + m_nFontSizeTextTopOffset, ILD_NORMAL);
}
// Offset on the right of the image.
rcText.left += (ii.rcImage.right - ii.rcImage.left);
}
if (rcText.left + m_nMinWidthToDisplayText < rcText.right)
{
::InflateRect(&rcText, -m_settings.iPadding, 0);
_CSTRING_NS::CString sText = pItem->GetText();
dc.DrawText(sText, sText.GetLength(), &rcText, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_PATH_ELLIPSIS);
}
dc.SetTextColor(crPrevious);
dc.SelectFont(hOldFont);
}
void DrawCloseButton(LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
WTL::CPen penButtons;
penButtons.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrTextInactive);
WTL::CBrush brushArrow;
brushArrow.CreateSolidBrush(lpNMCustomDraw->clrTextInactive);
WTL::CPenHandle penOld = dc.SelectPen(penButtons);
WTL::CBrushHandle brushOld = dc.SelectBrush(brushArrow);
RECT rcX = m_rcCloseButton;
if (ectcMouseDownL_CloseButton == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_CloseButton == (m_dwState & ectcMouseOver))
{
::OffsetRect(&rcX, 1, 1);
}
}
const int sp = 4;
dc.MoveTo(rcX.left + sp + -1, rcX.top + sp);
dc.LineTo(rcX.right - sp - 1, rcX.bottom - sp);
dc.MoveTo(rcX.left + sp, rcX.top + sp);
dc.LineTo(rcX.right - sp, rcX.bottom - sp);
dc.MoveTo(rcX.left + sp - 1, rcX.bottom - sp - 1);
dc.LineTo(rcX.right - sp - 1, rcX.top + sp - 1);
dc.MoveTo(rcX.left + sp, rcX.bottom - sp - 1);
dc.LineTo(rcX.right - sp, rcX.top + sp - 1);
if (ectcMouseDownL_CloseButton == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_CloseButton == (m_dwState & ectcMouseOver))
{
dc.DrawEdge(&m_rcCloseButton, BDR_SUNKENOUTER, BF_RECT);
}
}
else if (ectcHotTrack_CloseButton == (m_dwState & ectcHotTrack))
{
dc.DrawEdge(&m_rcCloseButton, BDR_RAISEDINNER, BF_RECT);
}
dc.SelectBrush(brushOld);
dc.SelectPen(penOld);
}
void DrawScrollButtons(LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
WTL::CPen penButtons;
penButtons.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrTextInactive);
WTL::CBrush brushArrow;
brushArrow.CreateSolidBrush(lpNMCustomDraw->clrTextInactive);
WTL::CPenHandle penOld = dc.SelectPen(penButtons);
WTL::CBrushHandle brushOld = dc.SelectBrush(brushArrow);
RECT rcArrowRight = m_rcScrollRight;
RECT rcArrowLeft = m_rcScrollLeft;
if (ectcMouseDownL_ScrollRight == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_ScrollRight == (m_dwState & ectcMouseOver))
{
if (ectcOverflowRight == (m_dwState & ectcOverflowRight))
{
::OffsetRect(&rcArrowRight, 1, 1);
}
}
}
if (ectcMouseDownL_ScrollLeft == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_ScrollLeft == (m_dwState & ectcMouseOver))
{
if (ectcOverflowLeft == (m_dwState & ectcOverflowLeft))
{
::OffsetRect(&rcArrowLeft, 1, 1);
}
}
}
const int spRight = 5;
const int spLeft = 6;
POINT ptsArrowRight[] =
{
{rcArrowRight.left + spRight, rcArrowRight.top + spRight - 2},
{rcArrowRight.left + spRight, rcArrowRight.bottom - spRight + 1},
{rcArrowRight.right - spRight - 1, (rcArrowRight.bottom + m_rcScrollRight.top) / 2},
{rcArrowRight.left + spRight, rcArrowRight.top + spRight - 2}
};
if (ectcOverflowRight != (m_dwState & ectcOverflowRight))
{
dc.Polyline(ptsArrowRight, 4);
}
else
{
dc.Polygon(ptsArrowRight, 4);
if (ectcMouseDownL_ScrollRight == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_ScrollRight == (m_dwState & ectcMouseOver))
{
dc.DrawEdge(&m_rcScrollRight, BDR_SUNKENOUTER, BF_RECT);
}
}
else if (ectcHotTrack_ScrollRight == (m_dwState & ectcHotTrack))
{
dc.DrawEdge(&m_rcScrollRight, BDR_RAISEDINNER, BF_RECT);
}
}
POINT ptsArrowLeft[] =
{
{rcArrowLeft.right - spLeft, rcArrowLeft.top + spLeft - 3},
{rcArrowLeft.right - spLeft, rcArrowLeft.bottom - spLeft + 2},
{rcArrowLeft.left + spLeft - 1, (rcArrowLeft.bottom + m_rcScrollLeft.top) / 2},
{rcArrowLeft.right - spLeft, rcArrowLeft.top + spLeft - 3}
};
if (ectcOverflowLeft != (m_dwState & ectcOverflowLeft))
{
dc.Polyline(ptsArrowLeft, 4);
}
else
{
dc.Polygon(ptsArrowLeft, 4);
if (ectcMouseDownL_ScrollLeft == (m_dwState & ectcMouseDown))
{
if (ectcMouseOver_ScrollLeft == (m_dwState & ectcMouseOver))
{
dc.DrawEdge(&m_rcScrollLeft, BDR_SUNKENOUTER, BF_RECT);
}
}
else if (ectcHotTrack_ScrollLeft == (m_dwState & ectcHotTrack))
{
dc.DrawEdge(&m_rcScrollLeft, BDR_RAISEDINNER, BF_RECT);
}
}
dc.SelectBrush(brushOld);
dc.SelectPen(penOld);
}
// Overrides for painting from CCustomTabCtrl
public:
void InitializeDrawStruct(LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
//DWORD dwStyle = this->GetStyle();
lpNMCustomDraw->hFontInactive = m_font;
lpNMCustomDraw->hFontSelected = m_fontSel;
lpNMCustomDraw->hBrushBackground = m_hbrBackground;
lpNMCustomDraw->clrTextSelected = ::GetSysColor(COLOR_BTNTEXT);
lpNMCustomDraw->clrTextInactive = m_clrTextInactiveTab;
lpNMCustomDraw->clrSelectedTab = m_clrSelectedTab;
lpNMCustomDraw->clrBtnFace = ::GetSysColor(COLOR_BTNFACE);
lpNMCustomDraw->clrBtnShadow = ::GetSysColor(COLOR_BTNSHADOW);
lpNMCustomDraw->clrBtnHighlight = ::GetSysColor(COLOR_BTNHIGHLIGHT);
lpNMCustomDraw->clrBtnText = ::GetSysColor(COLOR_BTNTEXT);
lpNMCustomDraw->clrHighlight = ::GetSysColor(COLOR_HIGHLIGHT);
#if WINVER >= 0x0500
lpNMCustomDraw->clrHighlightHotTrack = ::GetSysColor(COLOR_HOTLIGHT);
#else
lpNMCustomDraw->clrHighlightHotTrack = ::GetSysColor(COLOR_HIGHLIGHT);
#endif
lpNMCustomDraw->clrHighlightText = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
}
void DoPrePaint(RECT rcClient, LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
T* pT = static_cast<T*>(this);
pT->DrawBackground(rcClient, lpNMCustomDraw);
}
void DoItemPaint(LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
T* pT = static_cast<T*>(this);
bool bSelected = (CDIS_SELECTED == (lpNMCustomDraw->nmcd.uItemState & CDIS_SELECTED));
// NOTE: lpNMCustomDraw->nmcd.rc is in logical coordinates
RECT& rcItem = lpNMCustomDraw->nmcd.rc;
DWORD dwStyle = pT->GetStyle();
RECT rcTab = rcItem;
RECT rcText = rcItem;
int nIconVerticalCenter = 0;
pT->DrawItem_InitBounds(dwStyle, rcItem, rcTab, rcText, nIconVerticalCenter);
if (bSelected)
{
pT->DrawItem_TabSelected(dwStyle, lpNMCustomDraw, rcTab);
}
else
{
pT->DrawItem_TabInactive(dwStyle, lpNMCustomDraw, rcTab);
}
pT->DrawItem_ImageAndText(dwStyle, lpNMCustomDraw, nIconVerticalCenter, rcTab, rcText);
}
void DoPostPaint(RECT /*rcClient*/, LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
T* pT = static_cast<T*>(this);
DWORD dwStyle = this->GetStyle();
if (0 == (dwStyle & (CTCS_CLOSEBUTTON | CTCS_SCROLL)))
{
return;
}
// Close Button
if (CTCS_CLOSEBUTTON == (dwStyle & CTCS_CLOSEBUTTON))
{
if ((m_iCurSel >= 0) && ((size_t)m_iCurSel < m_Items.GetCount()))
{
TItem* pItem = m_Items[m_iCurSel];
ATLASSERT(pItem != NULL);
if ((pItem != NULL) && pItem->CanClose())
{
pT->DrawCloseButton(lpNMCustomDraw);
}
}
}
// Scroll Buttons
if (CTCS_SCROLL == (dwStyle & CTCS_SCROLL))
{
pT->DrawScrollButtons(lpNMCustomDraw);
}
}
// Overrides from CCustomTabCtrl
public:
void CalcSize_NonClient(LPRECT prcTabItemArea)
{
// account for "non-client" areas
// TODO: For the short term, we will use this
// for the non-client areas on the left and right.
// The drawing code for the tabs already accounts
// for the "non-client" areas on the top and bottom, and
// would need to be updated if we account for it here.
// Tab item rect methods also would need to be
// updated to account for the non-client areas
// on top and bottom (and effected drawing code
// would need to be updated).
DWORD dwStyle = this->GetStyle();
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
// TODO: Update to actually specify the
// non-client areas, and adjust all of the
// effected drawing code, as well as
// tab item rect related things
//prcTabItemArea->top += 3;
}
else
{
prcTabItemArea->left += 2;
prcTabItemArea->right -= 2;
// TODO: Update to actually specify the top and bottom
// non-client areas, and adjust all of the
// effected drawing code, as well as
// tab item rect related things
//prcTabItemArea->top += 1;
//// We would have bottom as 3, but we want the
//// selected tab to actually paint over highlight part
//prcTabItemArea->bottom -= 2;
}
}
void CalcSize_CloseButton(LPRECT prcTabItemArea)
{
//int nButtonSizeX = ::GetSystemMetrics(SM_CXSMSIZE);
//int nButtonSizeY = ::GetSystemMetrics(SM_CYSMSIZE);
// NOTE: After several tests, VS.Net does NOT depend on
// any system metric for the button size, so neither will we.
int nButtonSizeX = 15;
int nButtonSizeY = 15;
if ((prcTabItemArea->right - prcTabItemArea->left) < nButtonSizeX)
{
::SetRectEmpty(&m_rcCloseButton);
return;
}
m_rcCloseButton = *prcTabItemArea;
DWORD dwStyle = this->GetStyle();
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
m_rcCloseButton.top += 3;
m_rcCloseButton.right -= 3;
}
else
{
m_rcCloseButton.top += 1;
m_rcCloseButton.bottom -= 2;
m_rcCloseButton.right -= 2;
}
m_rcCloseButton.top = (m_rcCloseButton.bottom + m_rcCloseButton.top - nButtonSizeY) / 2;
m_rcCloseButton.bottom = m_rcCloseButton.top + nButtonSizeY;
m_rcCloseButton.left = m_rcCloseButton.right - (nButtonSizeX);
if (m_tooltip.IsWindow())
{
m_tooltip.SetToolRect(m_hWnd, (UINT)ectcToolTip_Close, &m_rcCloseButton);
}
// Adjust the tab area
prcTabItemArea->right = m_rcCloseButton.left;
}
void CalcSize_ScrollButtons(LPRECT prcTabItemArea)
{
//int nButtonSizeX = ::GetSystemMetrics(SM_CXSMSIZE);
//int nButtonSizeY = ::GetSystemMetrics(SM_CYSMSIZE);
// NOTE: After several tests, VS.Net does NOT depend on
// any system metric for the button size, so neither will we.
int nButtonSizeX = 15;
int nButtonSizeY = 15;
if ((prcTabItemArea->right - prcTabItemArea->left) < nButtonSizeX)
{
::SetRectEmpty(&m_rcScrollRight);
::SetRectEmpty(&m_rcScrollLeft);
return;
}
RECT rcScroll = *prcTabItemArea;
DWORD dwStyle = this->GetStyle();
if (CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
{
rcScroll.top += 3;
if (0 == (dwStyle & CTCS_CLOSEBUTTON))
{
rcScroll.right -= 3;
}
}
else
{
rcScroll.top += 1;
rcScroll.bottom -= 2;
if (0 == (dwStyle & CTCS_CLOSEBUTTON))
{
rcScroll.right -= 2;
}
}
rcScroll.top = (rcScroll.bottom + rcScroll.top - nButtonSizeY) / 2;
rcScroll.bottom = rcScroll.top + nButtonSizeY;
m_rcScrollRight = rcScroll;
m_rcScrollLeft = rcScroll;
m_rcScrollRight.left = m_rcScrollRight.right - nButtonSizeX;
m_rcScrollLeft.right = m_rcScrollRight.left;
m_rcScrollLeft.left = m_rcScrollLeft.right - nButtonSizeX;
if (m_tooltip.IsWindow())
{
m_tooltip.SetToolRect(m_hWnd, (UINT)ectcToolTip_ScrollRight, &m_rcScrollRight);
m_tooltip.SetToolRect(m_hWnd, (UINT)ectcToolTip_ScrollLeft, &m_rcScrollLeft);
}
// Adjust the tab area
prcTabItemArea->right = m_rcScrollLeft.left;
}
void UpdateLayout_Default(RECT rcTabItemArea)
{
long nMinInactiveWidth = 0x7FFFFFFF;
long nMaxInactiveWidth = 0;
//DWORD dwStyle = this->GetStyle();
WTL::CClientDC dc(m_hWnd);
//HFONT hOldFont = dc.SelectFont(lpNMCustomDraw->hFontInactive);
HFONT hOldFont = dc.SelectFont(m_font);
LONG nTabAreaWidth = (rcTabItemArea.right - rcTabItemArea.left);
RECT rcItem = rcTabItemArea;
// rcItem.top and rcItem.bottom aren't really going to change
// Recalculate tab positions and widths
// See DrawItem_ImageAndText for a discussion of how CDotNetTabCtrlImpl
// interprets margin, padding, etc.
size_t nCount = m_Items.GetCount();
int xpos = m_settings.iIndent;
HFONT hRestoreNormalFont = NULL;
for (size_t i = 0; i < nCount; ++i)
{
bool bSelected = ((int)i == m_iCurSel);
if (bSelected)
{
//hRestoreNormalFont = dc.SelectFont(lpNMCustomDraw->hFontSelected);
hRestoreNormalFont = dc.SelectFont(m_fontSel);
}
TItem* pItem = m_Items[i];
ATLASSERT(pItem != NULL);
rcItem.left = rcItem.right = xpos;
//rcItem.right += ((bSelected ? m_settings.iSelMargin : m_settings.iMargin));
rcItem.right += m_settings.iMargin;
if (pItem->UsingImage() && !m_imageList.IsNull())
{
IMAGEINFO ii = {0};
int nImageIndex = pItem->GetImageIndex();
m_imageList.GetImageInfo(nImageIndex, &ii);
rcItem.right += (ii.rcImage.right - ii.rcImage.left);
}
if (pItem->UsingText())
{
RECT rcText = {0};
_CSTRING_NS::CString sText = pItem->GetText();
dc.DrawText(sText, sText.GetLength(), &rcText, DT_SINGLELINE | DT_CALCRECT);
rcItem.right += (rcText.right - rcText.left) + (m_settings.iPadding * 2);
}
rcItem.right += m_settings.iMargin;
pItem->SetRect(rcItem);
xpos += (rcItem.right - rcItem.left);
if (hRestoreNormalFont != NULL)
{
dc.SelectFont(hRestoreNormalFont);
hRestoreNormalFont = NULL;
}
if (!bSelected)
{
if ((rcItem.right - rcItem.left) < nMinInactiveWidth)
{
nMinInactiveWidth = (rcItem.right - rcItem.left);
}
if ((rcItem.right - rcItem.left) > nMaxInactiveWidth)
{
nMaxInactiveWidth = (rcItem.right - rcItem.left);
}
}
}
xpos += m_settings.iIndent;
if (xpos > nTabAreaWidth && nCount > 0 && m_iCurSel >= 0)
{
// Our desired widths are more than the width of the client area.
// We need to have some or all of the tabs give up some real estate
// We'll try to let the selected tab have its fully desired width.
// If it can't, we'll make all the tabs the same width.
RECT rcSelected = m_Items[m_iCurSel]->GetRect();
LONG nSelectedWidth = (rcSelected.right - rcSelected.left);
long cxClientInactiveTabs = nTabAreaWidth - (m_settings.iIndent * 2) - nSelectedWidth;
long cxDesiredInactiveTabs = xpos - (m_settings.iIndent * 2) - nSelectedWidth;
double nRatioWithSelectionFullSize = 0.0;
if (cxDesiredInactiveTabs != 0)
{
nRatioWithSelectionFullSize = (double)(cxClientInactiveTabs) / (double)(cxDesiredInactiveTabs);
}
long nInactiveSameSizeWidth = (m_nMinWidthToDisplayText + (m_settings.iMargin * 2) + (m_settings.iPadding));
if (cxClientInactiveTabs > (nInactiveSameSizeWidth * (long)(nCount - 1)))
{
// There should be enough room to display the entire contents of
// the selected tab plus something for the inactive tabs
bool bMakeInactiveSameSize = ((nMinInactiveWidth * nRatioWithSelectionFullSize) < nInactiveSameSizeWidth);
xpos = m_settings.iIndent;
for (size_t i = 0; i < nCount; ++i)
{
TItem* pItem = m_Items[i];
ATLASSERT(pItem != NULL);
RECT rcItemDesired = pItem->GetRect();
rcItem.left = rcItem.right = xpos;
if ((int)i == m_iCurSel)
{
rcItem.right += (rcItemDesired.right - rcItemDesired.left);
}
else
{
if (bMakeInactiveSameSize && (nCount != 1))
{
rcItem.right += (long)((cxClientInactiveTabs / (nCount - 1)) + 0.5);
}
else
{
rcItem.right += (long)(((rcItemDesired.right - rcItemDesired.left) * nRatioWithSelectionFullSize) + 0.5);
}
}
pItem->SetRect(rcItem);
xpos += (rcItem.right - rcItem.left);
}
}
else
{
// We're down pretty small, so just make all the tabs the same width
int cxItem = (nTabAreaWidth - (m_settings.iIndent * 2)) / (int)nCount;
xpos = m_settings.iIndent;
for (size_t i = 0; i < nCount; ++i)
{
rcItem.left = rcItem.right = xpos;
rcItem.right += cxItem;
m_Items[i]->SetRect(rcItem);
xpos += (rcItem.right - rcItem.left);
}
}
}
dc.SelectFont(hOldFont);
}
void UpdateLayout_ScrollToFit(RECT rcTabItemArea)
{
//DWORD dwStyle = this->GetStyle();
// When we scroll to fit, we ignore what's passed in for the
// tab item area rect, and use the client rect instead
RECT rcClient;
this->GetClientRect(&rcClient);
WTL::CClientDC dc(m_hWnd);
//HFONT hOldFont = dc.SelectFont(lpNMCustomDraw->hFontInactive);
HFONT hOldFont = dc.SelectFont(m_font);
RECT rcItem = rcClient;
// rcItem.top and rcItem.bottom aren't really going to change
// Recalculate tab positions and widths
// See DrawItem_ImageAndText for a discussion of how CDotNetTabCtrlImpl
// interprets margin, padding, etc.
size_t nCount = m_Items.GetCount();
int xpos = m_settings.iIndent;
HFONT hRestoreNormalFont = NULL;
for (size_t i = 0; i < nCount; ++i)
{
bool bSelected = ((int)i == m_iCurSel);
if (bSelected)
{
//hRestoreNormalFont = dc.SelectFont(lpNMCustomDraw->hFontSelected);
hRestoreNormalFont = dc.SelectFont(m_fontSel);
}
TItem* pItem = m_Items[i];
ATLASSERT(pItem != NULL);
rcItem.left = rcItem.right = xpos;
//rcItem.right += ((bSelected ? m_settings.iSelMargin : m_settings.iMargin));
rcItem.right += m_settings.iMargin;
if (pItem->UsingImage() && !m_imageList.IsNull())
{
IMAGEINFO ii = {0};
int nImageIndex = pItem->GetImageIndex();
m_imageList.GetImageInfo(nImageIndex, &ii);
rcItem.right += (ii.rcImage.right - ii.rcImage.left);
}
if (pItem->UsingText())
{
RECT rcText = {0};
_CSTRING_NS::CString sText = pItem->GetText();
dc.DrawText(sText, sText.GetLength(), &rcText, DT_SINGLELINE | DT_CALCRECT);
rcItem.right += (rcText.right - rcText.left) + (m_settings.iPadding * 2);
}
rcItem.right += m_settings.iMargin;
pItem->SetRect(rcItem);
xpos += (rcItem.right - rcItem.left);
if (hRestoreNormalFont != NULL)
{
dc.SelectFont(hRestoreNormalFont);
hRestoreNormalFont = NULL;
}
}
xpos += m_settings.iIndent;
// If we've been scrolled to the left, and resize so
// there's more client area to the right, adjust the
// scroll offset accordingly.
if ((xpos + m_iScrollOffset) < rcTabItemArea.right)
{
m_iScrollOffset = (rcTabItemArea.right - xpos);
}
dc.SelectFont(hOldFont);
}
};
template <class TItem = CCustomTabItem>
class CDotNetTabCtrl :
public CDotNetTabCtrlImpl<CDotNetTabCtrl<TItem>, TItem>
{
protected:
typedef CDotNetTabCtrl thisClass;
typedef CDotNetTabCtrlImpl<CDotNetTabCtrl<TItem>, TItem> baseClass;
// Constructors:
public:
CDotNetTabCtrl()
{
}
public:
DECLARE_WND_CLASS_EX(_T("WTL_DotNetTabCtrl"), CS_DBLCLKS, COLOR_WINDOW)
//We have nothing special to add.
//BEGIN_MSG_MAP(thisClass)
// CHAIN_MSG_MAP(baseClass)
//END_MSG_MAP()
};
template<typename T, typename TItem = CCustomTabItem, class TBase = ATL::CWindow, class TWinTraits = CCustomTabCtrlWinTraits>
class CDotNetButtonTabCtrlImpl :
public CDotNetTabCtrlImpl<T, TItem, TBase, TWinTraits>
{
protected:
typedef CDotNetButtonTabCtrlImpl<T, TItem, TBase, TWinTraits> thisClass;
typedef CDotNetTabCtrlImpl<T, TItem, TBase, TWinTraits> baseClass;
// Constructor
public:
CDotNetButtonTabCtrlImpl()
{
// We can't use a member initialization list to initialize
// members of our base class, so do it explictly by assignment here.
m_clrTextInactiveTab = ::GetSysColor(COLOR_BTNTEXT);
m_clrSelectedTab = ::GetSysColor(COLOR_WINDOW);
}
// Message Handling
public:
DECLARE_WND_CLASS_EX(_T("WTL_DotNetButtonTabCtrl"), CS_DBLCLKS, COLOR_WINDOW)
BEGIN_MSG_MAP(thisClass)
MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
MESSAGE_HANDLER(WM_SYSCOLORCHANGE, OnSettingChange)
CHAIN_MSG_MAP(baseClass)
END_MSG_MAP()
LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DWORD dwStyle = this->GetStyle();
// Initialize/Reinitialize font
// Visual Studio.Net seems to use the "icon" font for the tabs
LOGFONT lfIcon = { 0 };
::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIcon), &lfIcon, 0);
bool bResetFont = true;
if (!m_font.IsNull())
{
LOGFONT lf = {0};
if (m_font.GetLogFont(&lf))
{
if (lstrcmpi(lf.lfFaceName, lfIcon.lfFaceName) == 0 &&
lf.lfHeight == lfIcon.lfHeight)
{
bResetFont = false;
}
}
}
if (bResetFont)
{
if (!m_font.IsNull()) m_font.DeleteObject();
if (!m_fontSel.IsNull()) m_fontSel.DeleteObject();
HFONT font = m_font.CreateFontIndirect(&lfIcon);
if (font == NULL)
{
m_font.Attach(AtlGetDefaultGuiFont());
}
if (CTCS_BOLDSELECTEDTAB == (dwStyle & CTCS_BOLDSELECTEDTAB))
{
lfIcon.lfWeight = FW_BOLD;
}
font = m_fontSel.CreateFontIndirect(&lfIcon);
if (font == NULL)
{
m_fontSel.Attach(AtlGetDefaultGuiFont());
}
}
// Background brush
if (!m_hbrBackground.IsNull()) m_hbrBackground.DeleteObject();
m_hbrBackground.CreateSysColorBrush(COLOR_BTNFACE);
m_settings.iIndent = 5;
m_settings.iPadding = 4;
m_settings.iMargin = 3;
m_settings.iSelMargin = 3;
T* pT = static_cast<T*>(this);
pT->UpdateLayout();
pT->Invalidate();
return 0;
}
// Overrides for painting from CDotNetTabCtrlImpl
public:
void DrawBackground(RECT /*rcClient*/, LPNMCTCCUSTOMDRAW lpNMCustomDraw)
{
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
// Set up the text color and background mode
dc.SetTextColor(lpNMCustomDraw->clrBtnText);
dc.SetBkMode(TRANSPARENT);
// Erase Background
// (do it here instead of a handler for WM_ERASEBKGND
// so that we can do flicker-free drawing with the help
// of COffscreenDrawRect that's in the base class)
// Note: Because the "erase" part is very simple, and only coloring
// it with the background color, we can do a smarter erase.
// Instead of erasing the whole client area (which might be clipped),
// We'll just ask the HDC for the clip box.
RECT rc = {0};
//GetClientRect(&rc);
dc.GetClipBox(&rc);
HBRUSH hOldBrush = dc.SelectBrush(lpNMCustomDraw->hBrushBackground);
dc.PatBlt(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY);
dc.SelectBrush(hOldBrush);
}
void DrawItem_InitBounds(DWORD /*dwStyle*/, RECT /*rcItem*/, RECT& rcTab, RECT& /*rcText*/, int& nIconVerticalCenter)
{
rcTab.top += 3;
rcTab.bottom -= 3;
nIconVerticalCenter = (rcTab.bottom + rcTab.top) / 2;
}
void DrawItem_TabSelected(DWORD /*dwStyle*/, LPNMCTCCUSTOMDRAW lpNMCustomDraw, RECT& rcTab)
{
// Tab is selected, so paint as select
bool bHighlighted = (CDIS_MARKED == (lpNMCustomDraw->nmcd.uItemState & CDIS_MARKED));
WTL::CDCHandle dc(lpNMCustomDraw->nmcd.hdc);
WTL::CPen penOutline;
WTL::CBrush brushSelected;
if (bHighlighted)
{
penOutline.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrBtnHighlight);
brushSelected.CreateSolidBrush(lpNMCustomDraw->clrHighlight);
}
else
{
penOutline.CreatePen(PS_SOLID, 1, lpNMCustomDraw->clrHighlight);
brushSelected.CreateSolidBrush(lpNMCustomDraw->clrSelectedTab);
}
HPEN hOldPen = dc.SelectPen(penOutline);
HBRUSH hOldBrush = dc.SelectBrush(brushSelected);
dc.Rectangle(&rcTab);
dc.SelectPen(hOldPen);
dc.SelectBrush(hOldBrush);
}
};
template <class TItem = CCustomTabItem>
class CDotNetButtonTabCtrl :
public CDotNetButtonTabCtrlImpl<CDotNetButtonTabCtrl<TItem>, TItem>
{
protected:
typedef CDotNetButtonTabCtrl<TItem> thisClass;
typedef CDotNetButtonTabCtrlImpl<CDotNetButtonTabCtrl<TItem>, TItem> baseClass;
// Constructors:
public:
CDotNetButtonTabCtrl()
{
}
public:
DECLARE_WND_CLASS_EX(_T("WTL_DotNetButtonTabCtrl"), CS_DBLCLKS, COLOR_WINDOW)
//We have nothing special to add.
//BEGIN_MSG_MAP(thisClass)
// CHAIN_MSG_MAP(baseClass)
//END_MSG_MAP()
};
#endif // __DOTNET_TABCTRL_H__
|
[
"[email protected]"
] |
[
[
[
1,
1390
]
]
] |
f5ab8d748a6d272505505854403068e79a8b8cab
|
5d35825d03fbfe9885316ec7d757b7bcb8a6a975
|
/src/ResultManager.cpp
|
88b3c3a3508ad1998360f70f20a85c25a1ceb715
|
[] |
no_license
|
jjzhang166/3D-Landscape-linux
|
ce887d290b72ebcc23386782dd30bdd198db93ef
|
4f87eab887750e3dc5edcb524b9e1ad99977bd94
|
refs/heads/master
| 2023-03-15T05:24:40.303445 | 2010-03-25T00:23:43 | 2010-03-25T00:23:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,196 |
cpp
|
#include "ResultManager.h"
ResultManager::ResultManager(Engine3D *engine3D)
{
this->engine3D = engine3D;
}
void ResultManager::render(QPainter *painter)
{
for(int i = 0; i < this->engine3D->foundDestinations.size(); i++)
{
//project the point to the screen
GLdouble xd, yd, zd;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
this->engine3D->setSearchCamera();
GLdouble modelMatrix[16];
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glFrustum(this->engine3D->fleft, this->engine3D->fright,
this->engine3D->fbottom, this->engine3D->ftop,
this->engine3D->fnear, this->engine3D->ffar);
GLdouble projMatrix[16];
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
glViewport(0,0,(GLsizei)this->engine3D->screenw,
(GLsizei)this->engine3D->screenh);
int viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
glPopMatrix();
gluProject(
this->engine3D->foundDestinations[i]->coords.x,
this->engine3D->foundDestinations[i]->coords.y,
this->engine3D->foundDestinations[i]->coords.z,
modelMatrix,
projMatrix,
viewport,
&xd,
&yd,
&zd);
this->resultItems[i]->render(painter,
xd, this->engine3D->height() - yd);
}
}
void ResultManager::processMouseClick(int x, int y)
{
for(int i = 0; i < this->resultItems.size(); i++)
{
if(this->resultItems[i]->isInside(x, y))
{
if(i < this->engine3D->foundDestinations.size())
{
cout << "Clicked destination name: " <<
this->engine3D->foundDestinations[i]->name << endl;
this->engine3D->menuManager->hideMenuImmediate();
this->engine3D->menuManager->setRoot();
this->engine3D->startDescensionToDestination(
this->engine3D->foundDestinations[i]->coords,
this->engine3D->foundDestinations[i]->nodeCoords);
break;
}
}
}
}
void ResultManager::addChild(QString label)
{
QSize mainWidgetSize = this->engine3D->size();
this->resultItems.append(new ResultItem(
mainWidgetSize.height()/20, mainWidgetSize.height()/20, label));
}
void ResultManager::resize(QSize mainWidgetSize)
{
for(int i = 0; i < this->resultItems.size(); i++)
{
this->resultItems[i]->width = mainWidgetSize.height()/10;
this->resultItems[i]->height = mainWidgetSize.height()/10;
}
}
void ResultManager::deleteItems()
{
for(int i = 0; i < this->resultItems.size(); i++)
{
delete this->resultItems[i];
}
this->resultItems.clear();
}
ResultManager::~ResultManager()
{
this->deleteItems();
}
|
[
"[email protected]"
] |
[
[
[
1,
107
]
]
] |
f6e5e6fbe105c3fba224d034909f9d3607f0cb8a
|
a01b67b20207e2d31404262146763d3839ee833d
|
/trunk/Projet/tags/Monofin_20090606_release/Drawing/extremitypoint.h
|
73d650b8b753bcc90f1c7942be9f590a906bd4ec
|
[] |
no_license
|
BackupTheBerlios/qtfin-svn
|
49b59747b6753c72a035bf1e2e95601f91f5992c
|
ee18d9eb4f80a57a9121ba32dade96971196a3a2
|
refs/heads/master
| 2016-09-05T09:42:14.189410 | 2010-09-21T17:34:43 | 2010-09-21T17:34:43 | 40,801,620 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,028 |
h
|
#ifndef EXTREMITYPOINT_H
#define EXTREMITYPOINT_H
#include "boundingpoint.h"
class BoundingPoint;
class ExtremityPoint: public BoundingPoint{
public:
/**
* Defines the type of the item as an int (by default,
* all the others items have the value UserType as type, except
* the BoundingPoint)
**/
enum{Type = BoundingPoint::Type + 1};
/**
* Constructs an extremity point of the monofin only by calling the
* constructor of BoundingPoint with the same arguments.
*@param coord the QPointF which will give the coordinates (x,y)
* to create the extremity point
*@param scene a pointer to the Painting scene
* in which the point is placed
**/
ExtremityPoint(const QPointF& coord, PaintingScene* scene);
/**
* Makes the extremity point moving to the coordinates of the given QPointF,
* but ONLY along the extremity axis of the scene in the zone where points
* can move (see PaintingScene::pointsBoundingZone). If the magnet is
* activated in the scene, the function can use it to move the point only
* on the intersections of the grid, depending on the parameter.
* It also calls the function move() of the lines if they exist.
*@param p the new coordinates of the bounding point as a QPointF
*@param useMagnetIfActivated if true, the point will be placed on the
* intersections of the grid, but ONLY if the magnet is activated on the
* scene ; if false, the point is placed just as described before
**/
void moveTo(const QPointF& p, bool useMagnetIfActivated = true);
/**
* Returns the type of the extremity point as an int. This int is different
* of UserType. It is used by the scene to make a difference between
* a BoundingPoint and an ExtremityPoint.
*@return the type of the item as an int
**/
int type() const{return Type;}
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
};
#endif // EXTREMITYPOINT_H
|
[
"kryptos@314bda93-af5c-0410-b653-d297496769b1"
] |
[
[
[
1,
54
]
]
] |
09edb43ef4bc99cd4f8f3367d9cb859cdc0645d1
|
e3a67b819e6c8072ea587f070214c2c075b2dee3
|
/IntegratedImpedanceSensingSystem/RobotControl.cpp
|
e5e6f2d614ee6c043c4ec3b2de495631ec41c805
|
[] |
no_license
|
pmanandhar1452/ImpedanceSensingSystem
|
46f32a57d3c19ebc011c539746fab5facf5e0c71
|
0c4a0472c75f280857d549630fabb881c452e791
|
refs/heads/master
| 2021-01-17T16:43:17.019071 | 2011-11-15T01:40:45 | 2011-11-15T01:40:45 | 62,420,080 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,680 |
cpp
|
/*
* RobotControl.cpp
*
* Created on: Oct 15, 2008
* Author: PManandhar
*/
#include "RobotControl.h"
#include "LoggerTime.h"
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <QFile>
#include <QDebug>
#include "Global.h"
RobotControl::RobotControl():
port("COM1"), is_time_synced(false),
is_recording(false), posTimer(this), moveTimer(this)
{
connect(&posTimer, SIGNAL(timeout()), this, SLOT(writePos()));
connect(&moveTimer, SIGNAL(timeout()), this, SLOT(moveTimeout()));
initPort();
}
class SleeperThread: public QThread {
public:
SleeperThread(int ms): ms(ms) { }
protected:
virtual void run () {
usleep(ms);
}
private:
const int ms;
};
void sleepMs (int ms) {
SleeperThread s(ms);
s.start();
s.wait();
}
void RobotControl::initPort ()
{
port.setBaudRate(BAUD57600);
port.setFlowControl(FLOW_OFF);
port.setParity(PAR_NONE);
port.setDataBits(DATA_8);
port.setStopBits(STOP_2);
bool status = port.open(QIODevice::ReadWrite|QIODevice::Unbuffered);
qDebug() << "Port Open Status: " << status;
sleepMs(1000);
}
void RobotControl::retrySynchronizeTime()
{
//port.close();
//initPort();
synchronizeTime();
}
void RobotControl::release15 ()
{
const char * buffer = "m 15\n";
port.write(buffer, strlen(buffer));
}
void RobotControl::flex15 ()
{
const char * buffer = "m -15\n";
port.write(buffer, strlen(buffer));
}
void RobotControl::flex(int angle, int speed)
{
setSpeed(speed);
char buffer[100];
sprintf(buffer,"m %d\n", angle);
//bool writeStatus =
port.write(buffer, strlen(buffer));
//qDebug() << "Flex write status: " << writeStatus;
}
void RobotControl::setSpeed(int s)
{
char buffer[100];
sprintf(buffer, "s %d\n", s);
port.write(buffer, strlen(buffer));
}
void RobotControl::moveSine(int cycles)
{
char buffer[100];
sprintf(buffer, "b %d\n", cycles);
port.write(buffer, strlen(buffer));
}
void RobotControl::setAmplitude(int a)
{
char buffer[100];
sprintf(buffer, "a %d\n", a);
port.write(buffer, strlen(buffer));
}
RobotControl::~RobotControl() {
stopPosRecording();
port.close();
}
void RobotControl::setPosReporting(bool v)
{
char buffer[100];
sprintf(buffer, "p %d\n", v ? 1: 0);
port.write(buffer, strlen(buffer));
port.flush();
}
void RobotControl::synchronizeTime()
{
char buffer[1000];
bool writeStatus;
sprintf(buffer, "t %d\n", LoggerTime::timer());
writeStatus = port.write(buffer, strlen(buffer));
port.flush();
sleepMs(200);
//qDebug() << "Writing to port: " << buffer << " Stauts: " << writeStatus;
int count = 0;
const int C_MAX = 100;
is_time_synced = false;
while (!is_time_synced && count < C_MAX)
{
sprintf(buffer, "t %d\n", LoggerTime::timer());
writeStatus = port.write(buffer, strlen(buffer));
sleepMs(200);
//qDebug() << "Writing to port: " << buffer << " Stauts: " << writeStatus;
RobotOutput output = parse_robot_out();
if (output.type == TIMESTAMP)
{
is_time_synced = true;
delta_time = output.param2 - output.param1;
}
++count;
}
}
RobotControl::RobotOutput RobotControl::parse_robot_out()
{
const long N = 1000;
RobotOutput output;
char buffer[N];
qint64 n = port.readLine(buffer, N);
if (n < 3 || (buffer[1] != ':'))
{
output.type = INVALID;
}
else
{
switch(*buffer) {
case 'p':
output.type = POSITION;
break;
case 't':
output.type = TIMESTAMP;
break;
case 'm':
output.type = MOVE;
break;
case 's':
output.type = SPEED;
break;
}
scan_params(buffer, &output);
}
//qDebug() << output.type << ":" << output.param1 << "," <<
// output.param2;
return output;
}
void RobotControl::scan_params (char * buffer, RobotOutput * output)
{
int pos = 2;
output->param1 = 0;
bool neg = false;
if (buffer[pos] == '-') {
neg = true;
pos++;
}
while(buffer[pos] != ',')
{
int v = buffer[pos] - '0';
if (v < 0 || v > 9) {
output->type = INVALID;
return;
}
output->param1 = output->param1*10 + v;
++pos;
}
if (neg) output->param1 = -output->param1;
++pos;
output->param2 = 0;
while(buffer[pos] != ';')
{
int v = buffer[pos] - '0';
if (v < 0 || v > 9) {
output->type = INVALID;
return;
}
output->param2 = output->param2*10 + v;
++pos;
}
}
bool RobotControl::isTimeSynced()
{
return is_time_synced;
}
long RobotControl::getDeltaTime()
{
return delta_time;
}
void RobotControl::startPosRecording(QList<PositionMeasurement> * pM)
{
pMmt = pM;
if (!is_time_synced) return;
stopPosRecording();
stopEvents();
setPosReporting(true);
is_recording = true;
posTimer.start(200);
startEvents();
}
void RobotControl::startEvents()
{
events = getEventList();
if (events.size() == 0) return;
moveIndex = 0;
moveTimer.setSingleShot(true);
moveTimer.start(events.value(0).StartTime*1000);
}
void RobotControl::stopPosRecording()
{
posTimer.stop();
stopEvents();
is_recording = false;
setPosReporting(false);
}
void RobotControl::stopEvents()
{
moveTimer.stop();
}
void RobotControl::writePos()
{
if (!is_recording) return;
int count = 0;
const int C_MAX = 10;
while (count < C_MAX)
{
RobotOutput output = parse_robot_out();
if (output.type == POSITION)
{
PositionMeasurement m;
m.t = output.param2 - delta_time;
m.pos = output.param1;
pMmt->append(m);
}
++count;
}
}
bool RobotControl::isRecording()
{
return is_recording;
}
QVector<RoboticArmEvent> RobotControl::getEventList()
{
Global * g = Global::instance();
int N = g->getNumEvents();
QVector<RoboticArmEvent> l(N);
srand(g->getSeed());
int t = 0;
const int dt = g->getTimeBetweenEvents();
const int dt_sd = g->getTimeBetweenEventsSD();
const int amean = g->getMechAmp();
const int a_sd = g->getMechAmpSD();
const int sp = g->getRbtSpeed();
const int sp_sd = g->getRbtSpeedSD();
const int nc = g->getMechCycles();
const int nc_sd = g->getMechCyclesSD();
for (int i = 0; i < N; i++)
{
t = t + getUniformRnd(dt, dt_sd);
l[i].StartTime = t;
l[i].Amplitude = getUniformRnd(amean, a_sd);
if (l[i].Amplitude < 1) l[i].Amplitude = 1;
l[i].Speed = getUniformRnd(sp, sp_sd);
if (l[i].Speed < 1) l[i].Speed = 1;
if (l[i].Speed > 100) l[i].Speed = 100;
l[i].NCycles = getUniformRnd(nc, nc_sd);
if (l[i].NCycles < 1) l[i].NCycles = 1;
}
return l;
}
int RobotControl::getUniformRnd(int mean, int SD)
{
double range = sqrt(12)*(double)SD/2.0;
int M = round(mean - range);
int N = round(mean + range);
return M + rand() / (RAND_MAX / (N - M + 1) + 1);
}
QString RoboticArmEvent::toQString() {
QString str = QString("{ %1 s, %2 cycles, %3 steps, %4 sp }")
.arg(StartTime).arg(NCycles).arg(Amplitude).arg(Speed);
return str;
}
void RobotControl::moveTimeout()
{
setSpeed(events.value(moveIndex).Speed);
setAmplitude(events.value(moveIndex).Amplitude);
moveSine(events.value(moveIndex).NCycles);
moveIndex++;
if (moveIndex >= events.size()) return;
long deltaT =
events.value(moveIndex).StartTime -
events.value(moveIndex-1).StartTime;
moveTimer.start(deltaT*1000);
}
|
[
"jaa_saaymi@d83832b1-3638-4858-8a38-9f153b6b3474"
] |
[
[
[
1,
341
]
]
] |
e6ec86069f46d7d4f7d301f834feba220978b15d
|
b207b13659b33b7d6b7b721fc7db811465e6d932
|
/old2/types/error_macros.h
|
27be34d77bf455ceba4103d1b41fdc218691b707
|
[] |
no_license
|
BackupTheBerlios/reshaked-svn
|
c99570088cb79a2b1900115a3d1f5a9c095f59d5
|
d9a6b614b3d8aa486d8b5bf05e46fe564476dae4
|
refs/heads/master
| 2020-06-02T18:17:32.828688 | 2008-08-20T17:28:16 | 2008-08-20T17:28:16 | 40,818,420 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,852 |
h
|
#ifndef ERROR_MACROS_H
#define ERROR_MACROS_H
#include <signal.h>
#include <iostream>
#include "version.h"
#ifdef WIN32_ENABLED
#define RAISE_SIGNAL
#endif
#ifdef POSIX_ENABLED
#define RAISE_SIGNAL if (getenv("ABORT_ON_ERROR")) abort();
#endif
#define ERR_FAIL_INDEX(m_index,m_size) \
{if ((m_index)<0 || (m_index)>=(m_size)) { \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << "index out of size: " << m_index << "(" << m_size << ")" << std::endl; \
RAISE_SIGNAL \
return; \
}} \
#define ERR_FAIL_INDEX_V(m_index,m_size,m_retval) \
{if ((m_index)<0 || (m_index)>=(m_size)) { \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << "index out of size: " << m_index << "(" << m_size << ")" << std::endl; \
RAISE_SIGNAL \
return (m_retval); \
}} \
#define ERR_FAIL_COND(m_cond) \
{ if ( m_cond ) { \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << #m_cond " failed." << std::endl; \
RAISE_SIGNAL \
return; \
} } \
#define ERR_FAIL_COND_V(m_cond,m_retval) \
{ if ( m_cond ) { \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << #m_cond " failed." << std::endl; \
RAISE_SIGNAL \
return m_retval; \
} } \
#define ERR_CONTINUE(m_cond) \
{ if ( m_cond ) { \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << #m_cond " failed." << std::endl; \
RAISE_SIGNAL \
continue; \
} } \
#define ERR_PRINT(m_string) \
{ \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << m_string << std::endl; \
RAISE_SIGNAL \
} \
#define WARN_PRINT(m_string) \
{ \
std::cout << " *** ERROR *** " << __FILE__ << ":" << __LINE__ << " - " << m_string << std::endl; \
RAISE_SIGNAL \
} \
#endif
|
[
"reduz@f29b5cec-baf9-0310-81f7-bdff227380de"
] |
[
[
[
1,
72
]
]
] |
a3ffc57ba6334416290e0cb1f12a836a32d541ee
|
bd89d3607e32d7ebb8898f5e2d3445d524010850
|
/adaptationlayer/dataport/dataport_csy/inc/dppif.inl
|
fafbeb56a490b856ee0210b9d2e6bfa700e61fc6
|
[] |
no_license
|
wannaphong/symbian-incubation-projects.fcl-modemadaptation
|
9b9c61ba714ca8a786db01afda8f5a066420c0db
|
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
|
refs/heads/master
| 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,531 |
inl
|
/*
* Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "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:
*
*/
// ---------------------------------------------------------
// CDpPif::PipeState
// This method returns pipe state.
// ---------------------------------------------------------
//
inline CDpPif::TDpPipeState CDpPif::PipeState()
{
return iPipeState;
}
// ---------------------------------------------------------
// CDpPif::PipeHandle
// This method returns pipe handle.
// ---------------------------------------------------------
//
inline TUint8 CDpPif::PipeHandle()
{
return iPipeHandle;
}
// ---------------------------------------------------------
// CDpPif::SetPipeHandle
// This method sets pipe handle.
// ---------------------------------------------------------
//
inline void CDpPif::SetPipeHandle(
const TUint8 aPipeHandle )
{
iPipeHandle = aPipeHandle;
}
#ifdef PIPECAMP_DATAPORT_PNS_PEP_STATUS_IND_PHONET_ADDRESS_FROM_PNS_PEP_CTRL_REQ // 20100523_1300
inline void CDpPif::SetPipeControllerDeviceIdentifier(
const TUint8 aDeviceId )
{
iPipeControllerDevId = aDeviceId;
}
inline void CDpPif::SetPipeControllerObjectIdentifier(
const TUint8 aObjectId )
{
iPipeControllerObjId = aObjectId;
}
inline TUint8 CDpPif::GetPipeControllerDeviceIdentifier()
{
return iPipeControllerDevId;
}
inline TUint8 CDpPif::GetPipeControllerObjectIdentifier()
{
return iPipeControllerObjId;
}
#endif
// ---------------------------------------------------------
// CDpPif::SetPipeState
// This method sets pipe state.
// ---------------------------------------------------------
//
inline void CDpPif::SetPipeState(
const TDpPipeState aPipeState )
{
iPipeState = aPipeState;Notify();
}
// ---------------------------------------------------------
// CDpPif::PifState
// This method returns pif state.
// ---------------------------------------------------------
//
inline CDpPif::TDpPifState CDpPif::PifState()
{
return iPifState;
}
// End of File
|
[
"dalarub@localhost",
"mikaruus@localhost"
] |
[
[
[
1,
50
],
[
74,
95
]
],
[
[
51,
73
]
]
] |
b8e936c7f56c58dcc3cb602730d07b107c85538a
|
f4b649f3f48ad288550762f4439fcfffddc08d0e
|
/eRacer/Source/Game/State.h
|
2a654f6d2f3617f615860421486fdc56bfe0ee36
|
[] |
no_license
|
Knio/eRacer
|
0fa27c8f7d1430952a98ac2896ab8b8ee87116e7
|
65941230b8bed458548a920a6eac84ad23c561b8
|
refs/heads/master
| 2023-09-01T16:02:58.232341 | 2010-04-26T23:58:20 | 2010-04-26T23:58:20 | 506,897 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 284 |
h
|
/**
Interface defination for game states
*/
#ifndef STATE_H_
#define STATE_H_
#include "Core/Time.h"
class State
{
public:
State() {};
virtual ~State() {};
virtual void Tick(Time &t) { }
virtual void Activate() {}
virtual void Deactivate() {}
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
22
]
]
] |
c93cd5368adfb17386c9d21a15c752ede86b1ba8
|
d8f64a24453c6f077426ea58aaa7313aafafc75c
|
/GUI/TexturedGUIButton.h
|
306c4514199ba7220c67ed725690e47b8aa63333
|
[] |
no_license
|
dotted/wfto
|
5b98591645f3ddd72cad33736da5def09484a339
|
6eebb66384e6eb519401bdd649ae986d94bcaf27
|
refs/heads/master
| 2021-01-20T06:25:20.468978 | 2010-11-04T21:01:51 | 2010-11-04T21:01:51 | 32,183,921 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 646 |
h
|
#ifndef TEXTURED_GUI_BUTTON
#define TEXTURED_GUI_BUTTON
#include "GUIButton.h"
namespace GUI
{
class CTexturedGUIButton: public CBasicGUIButton
{
public:
CTexturedGUIButton(GLfloat x_pos, GLfloat y_pos, GLfloat z_pos, GLfloat width, GLfloat height, char *caption, GLuint texture);
virtual ~CTexturedGUIButton();
virtual GLvoid on_mouse_over();
virtual GLvoid on_mouse_down();
virtual GLvoid on_mouse_up();
virtual GLvoid on_mouse_out();
virtual GLvoid on_mouse_click();
virtual GLvoid draw();
GLvoid set_texture(GLuint texture);
private:
GLuint texture;
};
}
#endif // TEXTURED_GUI_BUTTON
|
[
"[email protected]"
] |
[
[
[
1,
27
]
]
] |
afc3b6718d2a3b3a1dc82a8411f8b453190617b4
|
eda410906c2ec64689d8c0b84f3c2862f469144b
|
/DropSendCore/data/entities/sentfile.h
|
348fa2a3c53dd16c713990098743f2396da65978
|
[] |
no_license
|
redbox/Dropsend
|
640ea157a2caec88aa145f5bdc7fa85db95203a5
|
8fe4b4478616b9850b55011a506653026a28f7da
|
refs/heads/master
| 2020-06-02T20:54:18.301786 | 2010-09-06T16:16:05 | 2010-09-06T16:16:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,523 |
h
|
#ifndef SENTFILE_H
#define SENTFILE_H
#include <QString>
#include "./../filewithsender.h"
namespace dropsend {
namespace data {
namespace dao {
namespace remoteserver {
/// Used for implementing "Abstract factory" design pattern.
class RemoteServerSentFileDAO;
}
}
}
}
namespace dropsend {
namespace data {
namespace entities {
/**
* @class SentFile
* @brief Contains info about user's sent files. Has recipient ID. Data model class.
* Inherited from FileWithSender.
* @see dropsend::data::FileWithSender
**/
class SentFile : public FileWithSender
{
/**
* @brief Used for implementing "Abstract factory" design pattern.
**/
friend class dao::remoteserver::RemoteServerSentFileDAO;
public:
/**
* @brief Initializes a new instance of the dropsend::data::entities::SentFile class.
**/
SentFile();
/**
* @brief Gets recipient ID.
**/
int getRecipientId() const;
private:
/**
* @brief Recipient's ID.
**/
int recipient_id_;
};
}
}
}
#endif // SENTFILE_H
|
[
"[email protected]"
] |
[
[
[
1,
53
]
]
] |
b9719cd8a59cc9032ad13e9a80b6aa37d06d99b4
|
4d54b591fcefe7a728f1549392c95786700c3b91
|
/main.cpp
|
ca564d0935ceed883493c017c501474a4f1676ba
|
[] |
no_license
|
nayyden/openUberShader
|
e51780242a5db95700d35c827614d4a97b0582b2
|
3ad5e5aacc2637ff3cef4f66b842fffac5604bf3
|
refs/heads/master
| 2021-01-13T01:55:59.143401 | 2011-05-18T22:40:29 | 2011-05-18T22:40:29 | 1,611,367 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 865 |
cpp
|
//|||||||||||||||||||||||||||||||||||||||||||||||
#include "App.hpp"
//|||||||||||||||||||||||||||||||||||||||||||||||
#if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
//|||||||||||||||||||||||||||||||||||||||||||||||
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char **argv)
#endif
{
try
{
App app;
app.startDemo();
}
catch(std::exception& e)
{
#if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
fprintf(stderr, "An exception has occurred: %s\n", e.what());
#endif
}
return 0;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
|
[
"[email protected]"
] |
[
[
[
1,
35
]
]
] |
a830024e843d6cec2de69b099277e93a0b04780c
|
cce8a4b559cf619b9a5c741b47428af43487c8f6
|
/Baigiang/Bai4/FirstMFCGL/FirstMFCGL.cpp
|
41f4f74456bb32fd5aa566ac3e850e75afaee1b4
|
[] |
no_license
|
dtbinh/mophongrobot
|
00cfdfc6787d941bdd69d8888c8f6fd9a6e1eca5
|
4b8cb5f6b7a998a6e13453499e7190a96e965dd9
|
refs/heads/master
| 2021-01-10T12:23:33.743554 | 2011-10-31T04:11:40 | 2011-10-31T04:11:40 | 48,972,243 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,922 |
cpp
|
// FirstMFCGL.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "FirstMFCGL.h"
#include "MainFrm.h"
#include "FirstMFCGLDoc.h"
#include "FirstMFCGLView.h"
#pragma warning ( disable : 4566 )
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CFirstMFCGLApp
BEGIN_MESSAGE_MAP(CFirstMFCGLApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CFirstMFCGLApp::OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
// CFirstMFCGLApp construction
CFirstMFCGLApp::CFirstMFCGLApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CFirstMFCGLApp object
CFirstMFCGLApp theApp;
// CFirstMFCGLApp initialization
BOOL CFirstMFCGLApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CFirstMFCGLDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CFirstMFCGLView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
return TRUE;
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// App command to run the dialog
void CFirstMFCGLApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CFirstMFCGLApp message handlers
|
[
"[email protected]"
] |
[
[
[
1,
149
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.