blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8de7ed05de525da5be816f44a40cf1b771f55e9d | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /DDEPrint/MFCDDE.CPP | cacaee836e80c51cb85abe537cb44542b4e03e9c | [] | no_license | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,608 | cpp | /*
* File: mfcdde.cc
* Purpose: DDE class for MFC
* Author: Julian Smart
*/
// For compilers that support precompilation, includes "wx.h".
#include "stdafx.h"
#include "windows.h"
// #include "wx_utils.h"
#include "mfcdde.h"
#include <ddeml.h>
#ifdef WIN32
#define _EXPORT /**/
#else
#define _EXPORT _export
#endif
static CDDEConnection *DDEFindConnection(HCONV hConv);
static void DDEDeleteConnection(HCONV hConv);
static CDDEServer *DDEFindServer(const CString& s);
extern "C" HDDEDATA EXPENTRY _EXPORT _DDECallback(
WORD wType,
WORD wFmt,
HCONV hConv,
HSZ hsz1,
HSZ hsz2,
HDDEDATA hData,
DWORD lData1,
DWORD lData2);
// Add topic name to atom table before using in conversations
static HSZ DDEAddAtom(const CString& string);
static HSZ DDEGetAtom(const CString& string);
static void DDEPrintError(void);
static DWORD DDEIdInst = 0L;
static CDDEConnection *DDECurrentlyConnecting = NULL;
static CMapStringToOb DDEAtomTable;
static CObList DDEObjects;
char *DDEDefaultIPCBuffer = NULL;
int DDEDefaultIPCBufferSize = 0;
//static bool bDisconnected = false;
/*
* Initialization
*
*/
//BOOL DDEInitialized = FALSE;
void DDEInitialize()
{
if (DDEIdInst)//DDEInitialized)
return;
//DDEInitialized = TRUE;
// Should insert filter flags
DdeInitialize(&DDEIdInst, (PFNCALLBACK)MakeProcInstance(
(FARPROC)_DDECallback, AfxGetInstanceHandle()),
APPCLASS_STANDARD,
0L);
}
/*
* CleanUp
*/
void DDECleanUp()
{
if (DDEIdInst != 0)
{
DdeUninitialize(DDEIdInst);
DDEIdInst = 0;
}
if (DDEDefaultIPCBuffer)
delete [] DDEDefaultIPCBuffer ;
}
CDDEObject::CDDEObject(void)
{
service_name = "";
DDEObjects.AddTail(this);
}
CDDEObject::~CDDEObject(void)
{
POSITION pos = DDEObjects.Find(this);
if (pos)
DDEObjects.RemoveAt(pos);
pos = connections.GetHeadPosition();
CDDEConnection *connection = NULL;
while (pos && (connection = (CDDEConnection *)connections.GetNext(pos)))
{
connection->OnDisconnect(); // may delete the node implicitly
}
// If any left after this, delete them
pos = connections.GetHeadPosition();
connection = NULL;
while (pos && (connection = (CDDEConnection *)connections.GetNext(pos)))
{
delete connection;
}
}
// Global find connection
static CDDEConnection *DDEFindConnection(HCONV hConv)
{
CDDEObject *obj = NULL;
POSITION pos = DDEObjects.GetHeadPosition();
while (pos && (obj = (CDDEObject *)DDEObjects.GetNext(pos)))
{
CDDEConnection *connection = obj->FindConnection(hConv);
if (connection)
return connection;
}
return NULL;
/*
wxNode *node = DDEObjects.First();
CDDEConnection *found = NULL;
while (node && !found)
{
CDDEObject *object = (CDDEObject *)node->Data();
found = object->FindConnection(hConv);
node = node->Next();
}
return found;
*/
}
// Global delete connection
static void DDEDeleteConnection(HCONV hConv)
{
CDDEObject *obj = NULL;
BOOL found = FALSE;
POSITION pos = DDEObjects.GetHeadPosition();
while (!found && pos && (obj = (CDDEObject *)DDEObjects.GetNext(pos)))
{
found = obj->DeleteConnection(hConv);
}
/*
wxNode *node = DDEObjects.First();
BOOL found = FALSE;
while (node && !found)
{
CDDEObject *object = (CDDEObject *)node->Data();
found = object->DeleteConnection(hConv);
node = node->Next();
}
*/
}
CDDEConnection *CDDEObject::FindConnection(HCONV conv)
{
POSITION pos = connections.GetHeadPosition();
CDDEConnection *connection = NULL;
while (pos && (connection = (CDDEConnection *)connections.GetNext(pos)))
{
if (connection->hConv == conv)
return connection;
}
return NULL;
}
// Only delete the entry in the map, not the actual connection
BOOL CDDEObject::DeleteConnection(HCONV conv)
{
POSITION pos = connections.GetHeadPosition();
POSITION oldPos = pos;
CDDEConnection *connection = NULL;
while (pos && (connection = (CDDEConnection *)connections.GetNext(pos)))
{
if (connection->hConv == conv)
{
connections.RemoveAt(oldPos);
return TRUE;
}
oldPos = pos;
}
return FALSE;
}
// Find a server from a service name
static CDDEServer *DDEFindServer(const CString& s)
{
CDDEObject *obj = NULL;
POSITION pos = DDEObjects.GetHeadPosition();
while (pos && (obj = (CDDEObject *)DDEObjects.GetNext(pos)))
{
if (obj->service_name == s)
return (CDDEServer *)obj;
}
return NULL;
/*
wxNode *node = DDEObjects.First();
CDDEServer *found = NULL;
while (node && !found)
{
CDDEObject *object = (CDDEObject *)node->Data();
if (object->service_name == s)
found = (CDDEServer *)object;
else node = node->Next();
}
return found;
*/
}
/*
* Server
*
*/
CDDEServer::CDDEServer(void)
{
}
BOOL CDDEServer::Create(const CString& server_name)
{
service_name = server_name;
HSZ serviceName = DdeCreateStringHandle(DDEIdInst, (const char *)server_name, CP_WINANSI);
if (DdeNameService(DDEIdInst, serviceName, NULL, DNS_REGISTER) == 0)
{
DDEPrintError();
return FALSE;
}
return TRUE;
}
CDDEServer::~CDDEServer(void)
{
if (service_name != "")
{
HSZ serviceName = DdeCreateStringHandle(DDEIdInst, (const char *)service_name, CP_WINANSI);
if (DdeNameService(DDEIdInst, serviceName, NULL, DNS_UNREGISTER) == 0)
{
DDEPrintError();
}
}
}
CDDEConnection *CDDEServer::OnAcceptConnection(const CString& /* topic */)
{
return new CDDEConnection;
}
/*
* Client
*
*/
CDDEClient::CDDEClient(void)
{
}
CDDEClient::~CDDEClient(void)
{
POSITION pos = connections.GetHeadPosition();
CDDEConnection *connection = NULL;
while (pos && (connection = (CDDEConnection *)connections.GetNext(pos)))
{
delete connection; // Deletes entry in connections implicitly
}
}
BOOL CDDEClient::ValidHost(const CString& /* host */)
{
return TRUE;
}
CDDEConnection *CDDEClient::MakeConnection(const CString& /* host */, const CString& server_name, const CString& topic)
{
HSZ serviceName = DdeCreateStringHandle(DDEIdInst, (const char *)server_name, CP_WINANSI);
HSZ topic_atom = DdeCreateStringHandle(DDEIdInst, (const char *)topic, CP_WINANSI);
HCONV hConv = DdeConnect(DDEIdInst, serviceName, topic_atom, (PCONVCONTEXT)NULL);
BOOL rt = DdeFreeStringHandle(DDEIdInst, serviceName);
rt = DdeFreeStringHandle(DDEIdInst, topic_atom);
if (hConv == NULL)
return NULL;
else
{
CDDEConnection *connection = OnMakeConnection();
if (connection)
{
connection->hConv = hConv;
connection->topic_name = topic;
connection->client = this;
connections.AddTail(connection);
// bDisconnected = true;
return connection;
}
else return NULL;
}
}
CDDEConnection *CDDEClient::OnMakeConnection(void)
{
return new CDDEConnection;
}
/*
* Connection
*/
CDDEConnection::CDDEConnection(char *buffer, int size)
{
if (buffer == NULL)
{
if (DDEDefaultIPCBuffer == NULL)
DDEDefaultIPCBuffer = new char[DDEDefaultIPCBufferSize];
buf_ptr = DDEDefaultIPCBuffer;
buf_size = DDEDefaultIPCBufferSize;
}
else
{
buf_ptr = buffer;
buf_size = size;
}
topic_name = "";
client = NULL;
server = NULL;
hConv = NULL;
sending_data = NULL;
}
CDDEConnection::CDDEConnection(void)
{
hConv = NULL;
sending_data = NULL;
server = NULL;
client = NULL;
if (DDEDefaultIPCBuffer == NULL)
DDEDefaultIPCBuffer = new char[DDEDefaultIPCBufferSize];
buf_ptr = DDEDefaultIPCBuffer;
buf_size = DDEDefaultIPCBufferSize;
topic_name = "";
}
CDDEConnection::~CDDEConnection(void)
{
CDDEObject *obj = NULL;
if (server)
obj = server;
else obj = client;
if (obj)
{
POSITION pos = obj->connections.Find(this);
if (pos)
obj->connections.RemoveAt(pos);
}
}
// Calls that CLIENT can make
BOOL CDDEConnection::Disconnect(void)
{
DDEDeleteConnection(hConv);
return DdeDisconnect(hConv);
}
BOOL CDDEConnection::Execute(char *data, int size, int format)
{
DWORD result;
if (size < 0)
size = strlen(data);
size ++;
HDDEDATA rt = DdeClientTransaction((LPBYTE)data, size, hConv,
NULL, format, XTYP_EXECUTE, 5000, &result);
if (!rt)
{
/*if (bDisconnected)
return TRUE;*/
printf("Warning: DDE result is 0x%x\n", DdeGetLastError(DDEIdInst));
printf("Failed to exe cmd: %s\n", data);
}
return (rt ? TRUE : FALSE);
}
char *CDDEConnection::Request(const CString& item, int *size, int format)
{
DWORD result;
HSZ atom = DDEGetAtom(item);
HDDEDATA returned_data = DdeClientTransaction(NULL, 0, hConv,
atom, format, XTYP_REQUEST, 5000, &result);
DWORD len = DdeGetData(returned_data, (LPBYTE)(buf_ptr), buf_size, 0);
DdeFreeDataHandle(returned_data);
if (size) *size = (int)len;
if (len > 0)
{
return buf_ptr;
}
else return NULL;
}
BOOL CDDEConnection::Poke(const CString& item, char *data, int size, int format)
{
DWORD result;
if (size < 0)
size = strlen(data);
size ++;
HSZ item_atom = DDEGetAtom(item);
return (DdeClientTransaction((LPBYTE)data, size, hConv,
item_atom, format, XTYP_POKE, 5000, &result) ? TRUE : FALSE);
}
BOOL CDDEConnection::StartAdvise(const CString& item)
{
DWORD result;
HSZ atom = DDEGetAtom(item);
return (DdeClientTransaction(NULL, 0, hConv,
atom, CF_TEXT, XTYP_ADVSTART, 5000, &result) ? TRUE : FALSE);
}
BOOL CDDEConnection::StopAdvise(const CString& item)
{
DWORD result;
HSZ atom = DDEGetAtom(item);
return (DdeClientTransaction(NULL, 0, hConv,
atom, CF_TEXT, XTYP_ADVSTOP, 5000, &result) ? TRUE : FALSE);
}
// Calls that SERVER can make
BOOL CDDEConnection::Advise(const CString& item, char *data, int size, int format)
{
if (size < 0)
size = strlen(data);
size ++;
HSZ item_atom = DDEGetAtom(item);
HSZ topic_atom = DDEGetAtom(topic_name);
sending_data = data;
data_size = size;
data_type = format;
return DdePostAdvise(DDEIdInst, topic_atom, item_atom);
}
void CDDEConnection::Notify(BOOL /* notify */)
{
}
BOOL CDDEConnection::OnDisconnect(void)
{
delete this;
return TRUE;
}
#define DDERETURN HDDEDATA
HDDEDATA EXPENTRY _EXPORT _DDECallback(
WORD wType,
WORD wFmt,
HCONV hConv,
HSZ hsz1,
HSZ hsz2,
HDDEDATA hData,
DWORD /* lData1 */,
DWORD /* lData2 */)
{
switch (wType)
{
case XTYP_CONNECT:
{
char topic_buf[100];
char server_buf[100];
DdeQueryString(DDEIdInst, hsz1, (LPSTR)topic_buf, sizeof(topic_buf),
CP_WINANSI);
DdeQueryString(DDEIdInst, hsz2, (LPSTR)server_buf, sizeof(topic_buf),
CP_WINANSI);
CDDEServer *server = DDEFindServer(server_buf);
if (server)
{
CDDEConnection *connection =
server->OnAcceptConnection(CString(topic_buf));
if (connection)
{
connection->server = server;
server->connections.AddTail(connection);
connection->hConv = 0;
connection->topic_name = topic_buf;
DDECurrentlyConnecting = connection;
return (DDERETURN)TRUE;
}
}
else return (DDERETURN)0;
break;
}
case XTYP_CONNECT_CONFIRM:
{
if (DDECurrentlyConnecting)
{
DDECurrentlyConnecting->hConv = hConv;
DDECurrentlyConnecting = NULL;
return (DDERETURN)TRUE;
}
else return 0;
break;
}
case XTYP_DISCONNECT:
{
//InterlockedExchange((long*)&bDisconnected, 1);
//CDDEConnection *connection = DDEFindConnection(hConv);
//if (connection && connection->OnDisconnect())
//{
// DDEDeleteConnection(hConv); // Delete mapping: hConv => connection
// return (DDERETURN)TRUE;
//}
//else return (DDERETURN)0;
return (DDERETURN)TRUE;
break;
}
case XTYP_EXECUTE:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
DWORD len = DdeGetData(hData, (LPBYTE)(connection->buf_ptr), connection->buf_size, 0);
DdeFreeDataHandle(hData);
if (connection->OnExecute(connection->topic_name, connection->buf_ptr, (int)len, wFmt))
return (DDERETURN)DDE_FACK;
else
return (DDERETURN)DDE_FNOTPROCESSED;
} else return (DDERETURN)DDE_FNOTPROCESSED;
break;
}
case XTYP_REQUEST:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
char item_name[200];
DdeQueryString(DDEIdInst, hsz2, (LPSTR)item_name, sizeof(item_name),
CP_WINANSI);
int user_size = -1;
char *data = connection->OnRequest(connection->topic_name, CString(item_name), &user_size, wFmt);
if (data)
{
if (user_size < 0) user_size = strlen(data);
HDDEDATA handle = DdeCreateDataHandle(DDEIdInst,
(LPBYTE)data, user_size + 1, 0, hsz2, wFmt, 0);
return (DDERETURN)handle;
} else return (DDERETURN)0;
} else return (DDERETURN)0;
break;
}
case XTYP_POKE:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
char item_name[200];
DdeQueryString(DDEIdInst, hsz2, (LPSTR)item_name, sizeof(item_name),
CP_WINANSI);
DWORD len = DdeGetData(hData, (LPBYTE)(connection->buf_ptr), connection->buf_size, 0);
DdeFreeDataHandle(hData);
connection->OnPoke(connection->topic_name, CString(item_name), connection->buf_ptr, (int)len, wFmt);
return (DDERETURN)DDE_FACK;
} else return (DDERETURN)DDE_FNOTPROCESSED;
break;
}
case XTYP_ADVSTART:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
char item_name[200];
DdeQueryString(DDEIdInst, hsz2, (LPSTR)item_name, sizeof(item_name),
CP_WINANSI);
return (DDERETURN)connection->OnStartAdvise(connection->topic_name, CString(item_name));
} else return (DDERETURN)0;
break;
}
case XTYP_ADVSTOP:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
char item_name[200];
DdeQueryString(DDEIdInst, hsz2, (LPSTR)item_name, sizeof(item_name),
CP_WINANSI);
return (DDERETURN)connection->OnStopAdvise(connection->topic_name, CString(item_name));
} else return (DDERETURN)0;
break;
}
case XTYP_ADVREQ:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection && connection->sending_data)
{
HDDEDATA data = DdeCreateDataHandle(DDEIdInst,
(LPBYTE)connection->sending_data,
connection->data_size, 0, hsz2, connection->data_type, 0);
connection->sending_data = NULL;
return (DDERETURN)data;
} else return (DDERETURN)NULL;
break;
}
case XTYP_ADVDATA:
{
CDDEConnection *connection = DDEFindConnection(hConv);
if (connection)
{
char item_name[200];
DdeQueryString(DDEIdInst, hsz2, (LPSTR)item_name, sizeof(item_name),
CP_WINANSI);
DWORD len = DdeGetData(hData, (LPBYTE)(connection->buf_ptr), connection->buf_size, 0);
DdeFreeDataHandle(hData);
if (connection->OnAdvise(connection->topic_name, CString(item_name), connection->buf_ptr, (int)len, wFmt))
return (DDERETURN)DDE_FACK;
else
return (DDERETURN)DDE_FNOTPROCESSED;
} else return (DDERETURN)DDE_FNOTPROCESSED;
break;
}
}
return 0;
}
// Atom table stuff
static HSZ DDEAddAtom(const CString& string)
{
HSZ atom = DdeCreateStringHandle(DDEIdInst, (const char *)string, CP_WINANSI);
// DDEAtomTable.Append(string, (CObject *)atom);
DDEAtomTable.SetAt(string, (CObject *)atom);
return atom;
}
static HSZ DDEGetAtom(const CString& string)
{
CObject *data = NULL;
if (DDEAtomTable.Lookup(string, data))
{
return (HSZ)data;
}
else
{
return DDEAddAtom(string);
}
/*
wxNode *node = DDEAtomTable.Find(string);
if (node)
return (HSZ)node->Data();
else
{
DDEAddAtom(string);
return (HSZ)(DDEAtomTable.Find(string)->Data());
}
*/
}
void DDEPrintError(void)
{
char *err = NULL;
switch (DdeGetLastError(DDEIdInst))
{
case DMLERR_ADVACKTIMEOUT:
err = "A request for a synchronous advise transaction has timed out.";
break;
case DMLERR_BUSY:
err = "The response to the transaction caused the DDE_FBUSY bit to be set.";
break;
case DMLERR_DATAACKTIMEOUT:
err = "A request for a synchronous data transaction has timed out.";
break;
case DMLERR_DLL_NOT_INITIALIZED:
err = "A DDEML function was called without first calling the DdeInitialize function,\n\ror an invalid instance identifier\n\rwas passed to a DDEML function.";
break;
case DMLERR_DLL_USAGE:
err = "An application initialized as APPCLASS_MONITOR has\n\rattempted to perform a DDE transaction,\n\ror an application initialized as APPCMD_CLIENTONLY has \n\rattempted to perform server transactions.";
break;
case DMLERR_EXECACKTIMEOUT:
err = "A request for a synchronous execute transaction has timed out.";
break;
case DMLERR_INVALIDPARAMETER:
err = "A parameter failed to be validated by the DDEML.";
break;
case DMLERR_LOW_MEMORY:
err = "A DDEML application has created a prolonged race condition.";
break;
case DMLERR_MEMORY_ERROR:
err = "A memory allocation failed.";
break;
case DMLERR_NO_CONV_ESTABLISHED:
err = "A client's attempt to establish a conversation has failed.";
break;
case DMLERR_NOTPROCESSED:
err = "A transaction failed.";
break;
case DMLERR_POKEACKTIMEOUT:
err = "A request for a synchronous poke transaction has timed out.";
break;
case DMLERR_POSTMSG_FAILED:
err = "An internal call to the PostMessage function has failed. ";
break;
case DMLERR_REENTRANCY:
err = "Reentrancy problem.";
break;
case DMLERR_SERVER_DIED:
err = "A server-side transaction was attempted on a conversation\n\rthat was terminated by the client, or the server\n\rterminated before completing a transaction.";
break;
case DMLERR_SYS_ERROR:
err = "An internal error has occurred in the DDEML.";
break;
case DMLERR_UNADVACKTIMEOUT:
err = "A request to end an advise transaction has timed out.";
break;
case DMLERR_UNFOUND_QUEUE_ID:
err = "An invalid transaction identifier was passed to a DDEML function.\n\rOnce the application has returned from an XTYP_XACT_COMPLETE callback,\n\rthe transaction identifier for that callback is no longer valid.";
break;
default:
err = "Unrecognised error type.";
break;
}
//MessageBox(NULL, (LPCSTR)err, "DDE Error", MB_OK | MB_ICONINFORMATION);
}
| [
"greatfoolbear@756bb6b0-a119-0410-8338-473b6f1ccd30"
] | [
[
[
1,
764
]
]
] |
070dd5a5dda9e3d18171d433081d46f0964071b0 | b38ab5dcfb913569fc1e41e8deedc2487b2db491 | /libraries/SoftFX/header/Hue.hpp | 0d6dec7b9f2ec98cd388bd79578f807296456696 | [] | no_license | santosh90n/Fury2 | dacec86ab3972952e4cf6442b38e66b7a67edade | 740a095c2daa32d33fdc24cc47145a1c13431889 | refs/heads/master | 2020-03-21T00:44:27.908074 | 2008-10-16T07:09:17 | 2008-10-16T07:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,027 | hpp | const Word Hue_Unit = 600;
const Word Hue_Min = 0;
const Word Hue_Max = (Hue_Unit * 6) - 1;
const Word Saturation_Min = 0;
const Word Saturation_Max = 2550;
const Word Value_Min = 0;
const Word Value_Max = 2550;
class HSVA {
public:
short Hue;
short Saturation;
short Value;
Byte Alpha;
private:
Byte Padding;
public:
HSVA() {
this->setValuesFast(Hue_Min, Saturation_Min, Value_Min, 0);
}
HSVA(Pixel Color) {
this->setPixel(Color);
}
HSVA(int h, int s, int v) {
this->setValuesFast(h, s, v, 255);
}
HSVA(int h, int s, int v, int a) {
this->setValuesFast(h, s, v, a);
}
Pixel getPixel() {
if (Value <= Value_Min) return Pixel(0, 0, 0, Alpha);
if ((Value >= Value_Max) && (Saturation <= Saturation_Min)) return Pixel(255, 255, 255, Alpha);
if (Value > Value_Max) Value = Value_Max;
if (Saturation > Saturation_Max) Saturation = Saturation_Max;
int segment, remainder, range, color_range, a, b, c, rb;
range = Value * 255 / Value_Max;
if (Saturation <= Saturation_Min) return Pixel(range, range, range, Alpha);
segment = Hue / Hue_Unit;
remainder = Hue - (segment * Hue_Unit);
color_range = (Saturation) * range / Saturation_Max;
c = (Saturation_Max - Saturation) * range / Saturation_Max;
b = (remainder * color_range) / Hue_Unit + c;
rb = color_range - b + c + c;
a = color_range + c;
switch (segment) {
case 0:
return Pixel(a,b,c,Alpha);
case 1:
return Pixel(rb,a,c,Alpha);
case 2:
return Pixel(c,a,b,Alpha);
case 3:
return Pixel(c,rb,a,Alpha);
case 4:
return Pixel(b,c,a,Alpha);
case 5:
return Pixel(a,c,rb,Alpha);
default:
return Pixel(0,0,0,0);
}
}
void setPixel(Pixel NewColor) {
int max, min;
max = _Max(NewColor[::Red], _Max(NewColor[::Green], NewColor[::Blue]));
min = _Min(NewColor[::Red], _Min(NewColor[::Green], NewColor[::Blue]));
if (max == min) {
setValuesFast(Hue_Min, Saturation_Min, min * Value_Max / 255, NewColor[::Alpha]);
return;
} else if (max == 0) {
setValuesFast(Hue_Min, Saturation_Min, Value_Min, NewColor[::Alpha]);
return;
}
int v = max * Value_Max / 255;
int b = (max - min);
int s = b * Saturation_Max / max;
int h, d;
if (NewColor[::Red] == max) {
d = NewColor[::Green] - NewColor[::Blue];
h = d * Hue_Unit / b;
} else if (NewColor[::Green] == max) {
d = NewColor[::Blue] - NewColor[::Red];
h = (d * Hue_Unit / b) + (2 * Hue_Unit);
} else {
d = NewColor[::Red] - NewColor[::Green];
h = (d * Hue_Unit / b) + (4 * Hue_Unit);
}
Hue = h;
Saturation = s;
Value = v;
Alpha = NewColor[::Alpha];
// setValues(h, s, v, NewColor[::Alpha]);
return;
}
inline void setValues(int h, int s, int v, int a) {
Hue = WrapValue(h, Hue_Min, Hue_Max);
Saturation = ClipValue(s, Saturation_Min, Saturation_Max);
Value = ClipValue(v, Value_Min, Value_Max);
Alpha = ClipByte(a);
}
inline void setValuesFast(int h, int s, int v, int a) {
Hue = WrapValue(h, Hue_Min, Hue_Max);
Saturation = s;
Value = v;
Alpha = a;
}
inline void clip() {
Hue = WrapValue(Hue, Hue_Min, Hue_Max);
Saturation = ClipValue(Saturation, Saturation_Min, Saturation_Max);
Value = ClipValue(Value, Value_Min, Value_Max);
Alpha = ClipByte(Alpha);
}
inline void setHue(int h) {
Hue = WrapValue(h, Hue_Min, Hue_Max);
}
inline void setSaturation(int s) {
Saturation = ClipValue(s, Saturation_Min, Saturation_Max);
}
inline void setValue(int v) {
Value = ClipValue(v, Value_Min, Value_Max);
}
inline void setAlpha(int a) {
Alpha = ClipByte(a);
}
};
inline Pixel adjustHSV(Pixel Input, int HueOffset, int SaturationOffset, int ValueOffset) {
int max, min;
int h, s, v;
max = _Max(Input[::Red], _Max(Input[::Green], Input[::Blue]));
min = _Min(Input[::Red], _Min(Input[::Green], Input[::Blue]));
if (max == min) {
h = Hue_Min;
s = Saturation_Min;
v = (min * Value_Max / 255);
} else if (max == 0) {
h = Hue_Min;
s = Saturation_Min;
v = Value_Min;
} else {
v = max * Value_Max / 255;
int b = (max - min);
s = b * Saturation_Max / max;
int d;
if (Input[::Red] == max) {
d = Input[::Green] - Input[::Blue];
h = d * Hue_Unit / b;
} else if (Input[::Green] == max) {
d = Input[::Blue] - Input[::Red];
h = (d * Hue_Unit / b) + (2 * Hue_Unit);
} else {
d = Input[::Red] - Input[::Green];
h = (d * Hue_Unit / b) + (4 * Hue_Unit);
}
}
h = WrapValue(h + HueOffset, Hue_Min, Hue_Max);
v += ValueOffset;
s += SaturationOffset;
if (v <= Value_Min) return Pixel(0, 0, 0, Input[::Alpha]);
if ((v >= Value_Max) && (s <= Saturation_Min)) return Pixel(255, 255, 255, Input[::Alpha]);
if (v > Value_Max) v = Value_Max;
if (s > Saturation_Max) s = Saturation_Max;
int segment, remainder, range, color_range, a, b, c, rb;
range = v * 255 / Value_Max;
if (s <= Saturation_Min) return Pixel(range, range, range, Input[::Alpha]);
segment = h / Hue_Unit;
remainder = h - (segment * Hue_Unit);
color_range = (s) * range / Saturation_Max;
c = (Saturation_Max - s) * range / Saturation_Max;
b = (remainder * color_range) / Hue_Unit + c;
rb = color_range - b + c + c;
a = color_range + c;
switch (segment) {
case 0:
return Pixel(a,b,c,Input[::Alpha]);
case 1:
return Pixel(rb,a,c,Input[::Alpha]);
case 2:
return Pixel(c,a,b,Input[::Alpha]);
case 3:
return Pixel(c,rb,a,Input[::Alpha]);
case 4:
return Pixel(b,c,a,Input[::Alpha]);
case 5:
return Pixel(a,c,rb,Input[::Alpha]);
default:
return Pixel(0,0,0,0);
}
} | [
"janus@1af785eb-1c5d-444a-bf89-8f912f329d98"
] | [
[
[
1,
202
]
]
] |
7cfea62d56d348f470e54ac566772bfad2ed9991 | faaac39c2cc373003406ab2ac4f5363de07a6aae | / zenithprime/src/controller/BattleBoard/BBPhysics.cpp | 9375d56ff6e938ddecbef142977c4922ca6f14db | [] | no_license | mgq812/zenithprime | 595625f2ec86879eb5d0df4613ba41a10e3158c0 | 3c8ff4a46fb8837e13773e45f23974943a467a6f | refs/heads/master | 2021-01-20T06:57:05.754430 | 2011-02-05T17:20:19 | 2011-02-05T17:20:19 | 32,297,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | cpp | #include "BBPhysics.h"
BBPhysics::BBPhysics()
{
pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
if ( pPhysicsSDK != NULL ){
pPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect ("localhost", 5425);
}
else
return;
NxSceneDesc sceneDesc;
sceneDesc.gravity.set ( 0, 0, 0 );
pScene = pPhysicsSDK->createScene(sceneDesc);
NxPlaneShapeDesc planeDesc;
// plane equation : ax + by + cz + d = 0
planeDesc.normal = NxVec3 ( 0, 1, 0 );
planeDesc.d = 0.0f;
//planeDesc.userData = "BOARD";
// actor descriptor with collection of shapes
NxActorDesc actorDesc;
actorDesc.shapes.pushBack( &planeDesc );
actorDesc.userData = "BOARD";
// NxScene creates actor and returns a pointer.
pActor = pScene->createActor( actorDesc );
//pActor->userData = "BOARD";
}
BBPhysics::~BBPhysics(){
pPhysicsSDK->release();
}
NxRaycastHit BBPhysics::CastRay(float x, float y, float z, float dx, float dy, float dz){
NxRay worldRay;
worldRay.orig = NxVec3(x,y,z);
worldRay.dir = NxVec3(dx,dy,dz);
worldRay.dir.normalize(); //Important!!
NxRaycastHit hit;
pScene->raycastClosestShape(worldRay,NX_ALL_SHAPES, hit);
return hit;
}
| [
"[email protected]@2c223db4-e1a0-a0c7-f360-d8b483a75394",
"[email protected]@2c223db4-e1a0-a0c7-f360-d8b483a75394",
"mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394"
] | [
[
[
1,
16
],
[
30,
34
]
],
[
[
17,
21
],
[
23,
25
],
[
27,
28
],
[
35,
43
],
[
45,
46
]
],
[
[
22,
22
],
[
26,
26
],
[
29,
29
],
[
44,
44
]
]
] |
7b5def4eb5c5998cea66c46f12316505713f3801 | ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc | /computer_graphics/lab3/Src/Application/camera.h | fec2b59008eba570075ac0be202bb00d99399360 | [] | no_license | smi13/semester07 | 6789be72d74d8d502f0a0d919dca07ad5cbaed0d | 4d1079a446269646e1a0e3fe12e8c5e74c9bb409 | refs/heads/master | 2021-01-25T09:53:45.424234 | 2011-01-07T16:08:11 | 2011-01-07T16:08:11 | 859,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #ifndef _camera_h
#define _camera_h
#include <d3dx9.h>
namespace cg_labs
{
class Camera
{
public:
virtual void rotate( float dx, float dy ) = 0;
virtual void move( int dx, int dz ) = 0;
virtual void updateMatrix() = 0;
D3DXVECTOR3 getEyePos();
D3DXVECTOR3 getLookAt();
D3DXVECTOR3 getUpVec();
D3DXMATRIXA16 *getMatrix();
protected:
void _buildMatrix();
D3DXVECTOR3 _eyePos, _lookAt;
D3DXMATRIXA16 _matrix;
};
}
#endif /* _camera_h */ | [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
a1eae519a39ff6749d0504673fa978faf6674e66 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/ISound.cpp | e2b7617ae3efc2ab0e48584c03faec9bcdb881ed | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: ISound.cpp
Version: 0.01
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "ISound.h"
namespace nGENE
{
ISound::ISound(const SOUND_DESC& _desc):
m_Desc(_desc)
{
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
25
]
]
] |
d4668dbf7918ce9c2219453b84b887303ad006fe | adac3837d0242936ee697daa7dc2a8ffdf4da08b | /performance/throughput/OpenSplice/C/listener/qos_file_format.h | f940ae8b5c87cf83f8fb81e8d402105b3162c235 | [] | no_license | DOCGroup/DDS_Test | 7fb89d13df0b3fc775f794212b58aa3550620eec | 1f82d597f35ea74d46784e27c8b9bae78370c9fc | refs/heads/master | 2023-07-22T20:43:17.811097 | 2008-10-23T17:37:34 | 2008-10-23T17:37:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,174 | h | // Author: Hieu Nguyen
// June 19th, 2006
#ifndef __QOS_FILE_FORMAT_H
#define __QOS_FILE_FORMAT_H
#include <string>
using std::string;
// Define classes that manage the Qos file's keys naming format.
// To change the format, edit qos_file_format.cpp
namespace QosFormat {
class DomainParticipantQosKeys {
public:
static string get_user_data_key () { return user_data; }
static string get_entity_factory_key () { return entity_factory; }
private:
static const string user_data;
static const string entity_factory;
};
class TopicQosKeys {
public:
static string get_topic_data_key () { return topic_data; }
static string get_durability_kind_key () { return durability_kind; }
static string get_durability_service_cleanup_delay_key () { return durability_service_cleanup_delay; }
static string get_deadline_key () { return deadline; }
static string get_latency_budget_key () { return latency_budget; }
static string get_liveliness_kind_key () { return liveliness_kind; }
static string get_liveliness_lease_duration_key () { return liveliness_lease_duration; }
static string get_reliability_kind_key () { return reliability_kind; }
static string get_reliability_max_blocking_time_key () { return reliability_max_blocking_time; }
static string get_destination_order_key () { return destination_order; }
static string get_history_kind_key () { return history_kind; }
static string get_history_depth_key () { return history_depth; }
static string get_resource_limits_max_samples_key () { return resource_limits_max_samples; }
static string get_resource_limits_max_instances_key () { return resource_limits_max_instances; }
static string get_resource_limits_max_samples_per_instance_key () { return resource_limits_max_samples_per_instance; }
static string get_transport_priority_key () { return transport_priority; }
static string get_lifespan_key () { return lifespan; }
static string get_ownership_key () { return ownership; }
private:
static const string topic_data;
static const string durability_kind;
static const string durability_service_cleanup_delay;
static const string deadline;
static const string latency_budget;
static const string liveliness_kind;
static const string liveliness_lease_duration;
static const string reliability_kind;
static const string reliability_max_blocking_time;
static const string destination_order;
static const string history_kind;
static const string history_depth;
static const string resource_limits_max_samples;
static const string resource_limits_max_instances;
static const string resource_limits_max_samples_per_instance;
static const string transport_priority;
static const string lifespan;
static const string ownership;
};
class PublisherQosKeys {
public:
static string get_presentation_access_scope_key () { return presentation_access_scope; }
static string get_presentation_coherent_access_key () { return presentation_coherent_access; }
static string get_presentation_ordered_access_key () { return presentation_ordered_access; }
static string get_partition_key () { return partition; }
static string get_group_data_key () { return group_data; }
static string get_entity_factory_key () { return entity_factory; }
private:
static const string presentation_access_scope;
static const string presentation_coherent_access;
static const string presentation_ordered_access;
static const string partition;
static const string group_data;
static const string entity_factory;
};
class SubscriberQosKeys {
public:
static string get_presentation_access_scope_key () { return presentation_access_scope; }
static string get_presentation_coherent_access_key () { return presentation_coherent_access; }
static string get_presentation_ordered_access_key () { return presentation_ordered_access; }
static string get_partition_key () { return partition; }
static string get_group_data_key () { return group_data; }
static string get_entity_factory_key () { return entity_factory; }
private:
static const string presentation_access_scope;
static const string presentation_coherent_access;
static const string presentation_ordered_access;
static const string partition;
static const string group_data;
static const string entity_factory;
};
class DataWriterQosKeys {
public:
static string get_durability_kind_key () { return durability_kind; }
static string get_durability_service_cleanup_delay_key () { return durability_service_cleanup_delay; }
static string get_deadline_key () { return deadline; }
static string get_latency_budget_key () { return latency_budget; }
static string get_liveliness_kind_key () { return liveliness_kind; }
static string get_liveliness_lease_duration_key () { return liveliness_lease_duration; }
static string get_reliability_kind_key () { return reliability_kind; }
static string get_reliability_max_blocking_time_key () { return reliability_max_blocking_time; }
static string get_destination_order_key () { return destination_order; }
static string get_history_kind_key () { return history_kind; }
static string get_history_depth_key () { return history_depth; }
static string get_resource_limits_max_samples_key () { return resource_limits_max_samples; }
static string get_resource_limits_max_instances_key () { return resource_limits_max_instances; }
static string get_resource_limits_max_samples_per_instance_key () { return resource_limits_max_samples_per_instance; }
static string get_transport_priority_key () { return transport_priority; }
static string get_lifespan_key () { return lifespan; }
static string get_user_data_key () { return user_data; }
static string get_ownership_strength_key () { return ownership_strength; }
static string get_writer_data_lifecycle_key () { return writer_data_lifecycle; }
private:
static const string durability_kind;
static const string durability_service_cleanup_delay;
static const string deadline;
static const string latency_budget;
static const string liveliness_kind;
static const string liveliness_lease_duration;
static const string reliability_kind;
static const string reliability_max_blocking_time;
static const string destination_order;
static const string history_kind;
static const string history_depth;
static const string resource_limits_max_samples;
static const string resource_limits_max_instances;
static const string resource_limits_max_samples_per_instance;
static const string transport_priority;
static const string lifespan;
static const string user_data;
static const string ownership_strength;
static const string writer_data_lifecycle;
};
class DataReaderQosKeys {
public:
static string get_durability_kind_key () { return durability_kind; }
static string get_durability_service_cleanup_delay_key () { return durability_service_cleanup_delay; }
static string get_deadline_key () { return deadline; }
static string get_latency_budget_key () { return latency_budget; }
static string get_liveliness_kind_key () { return liveliness_kind; }
static string get_liveliness_lease_duration_key () { return liveliness_lease_duration; }
static string get_reliability_kind_key () { return reliability_kind; }
static string get_reliability_max_blocking_time_key () { return reliability_max_blocking_time; }
static string get_destination_order_key () { return destination_order; }
static string get_history_kind_key () { return history_kind; }
static string get_history_depth_key () { return history_depth; }
static string get_resource_limits_max_samples_key () { return resource_limits_max_samples; }
static string get_resource_limits_max_instances_key () { return resource_limits_max_instances; }
static string get_resource_limits_max_samples_per_instance_key () { return resource_limits_max_samples_per_instance; }
static string get_user_data_key () { return user_data; }
static string get_time_based_filter_key () { return time_based_filter; }
static string get_reader_data_lifecycle_key () { return reader_data_lifecycle; }
private:
static const string durability_kind;
static const string durability_service_cleanup_delay;
static const string deadline;
static const string latency_budget;
static const string liveliness_kind;
static const string liveliness_lease_duration;
static const string reliability_kind;
static const string reliability_max_blocking_time;
static const string destination_order;
static const string history_kind;
static const string history_depth;
static const string resource_limits_max_samples;
static const string resource_limits_max_instances;
static const string resource_limits_max_samples_per_instance;
static const string user_data;
static const string time_based_filter;
static const string reader_data_lifecycle;
};
//#include "qos_file_format.cpp"
} // end of namespace QosFormat
#endif /* __QOS_FILE_FORMAT_H */
| [
"hnguyen@b83e41e9-5108-4780-9bb0-1723f710b6d8",
"[email protected]"
] | [
[
[
1,
197
],
[
199,
202
]
],
[
[
198,
198
]
]
] |
e87981a9f7d26ddb9ecbb55a6be7dd7132f9b208 | 2e6bb5ab6f8ad09f30785c386ce5ac66258df252 | /project/HappyHunter/Effect/Bubble.cpp | f5dc684280d199f37f710f74b6881e5d1bbcc4bf | [] | no_license | linfuqing/happyhunter | 961061f84947a91256980708357b583c6ad2c492 | df38d8a0872b3fd2ea0e1545de3ed98434c12c5e | refs/heads/master | 2016-09-06T04:00:30.779303 | 2010-08-26T15:41:09 | 2010-08-26T15:41:09 | 34,051,578 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,195 | cpp | #include "StdAfx.h"
#include "Bubble.h"
using namespace zerO;
CBubble::CBubble(void) :
m_fSpeed(0.0f),
m_fHight(0.0f),
m_fOffsetHight(0),
m_fFlotage(0.06f),
m_fOffsetRadius(0),
m_uStep(0),
m_Acceleration(0.0f, 0.0f, 0.0f),
m_Source(0.0f, 0.0f, 0.0f),
m_Direction(0.0f, 0.0f, 1.0f)
{
}
CBubble::~CBubble(void)
{
}
///
// 气泡的初始化
///
void InitParicleBubble(CParticleSystem<BUBBLEPARAMETERS>::LPPARTICLE pParticle)
{
CBubble* pParent = (CBubble*)pParticle->pPARENT;
pParticle->Parameter.bIsFree = false;
pParticle->Parameter.Velocity = pParent->GetAcceleration();
pParticle->Vertex.Color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pParticle->Vertex.Position = pParent->GetSource();
zerO::FLOAT fHight = pParent->GetHight();
zerO::UINT fOffsetHight = pParent->GetOffsetHight();
zerO::FLOAT fOffsetRadius = pParent->GetOffsetRadius();
if(fOffsetRadius)
{
switch(pParent->GetOffsetType())
{
case CBubble::RANDOM_CUBE :
pParticle->Vertex.Position.x += ( (zerO::FLOAT)rand() ) / RAND_MAX * fOffsetRadius - fOffsetRadius * 0.5f;
pParticle->Vertex.Position.y = 0;
pParticle->Vertex.Position.z += ( (zerO::FLOAT)rand() ) / RAND_MAX * fOffsetRadius - fOffsetRadius * 0.5f;
break;
case CBubble::RANDOM_CIRCLE :
zerO::FLOAT fRandom = (zerO::FLOAT)rand() / RAND_MAX, fSin = sin(fRandom), fCos = cos(fRandom);
pParticle->Vertex.Position.x += fOffsetRadius * fCos - fOffsetRadius * 0.5f;
pParticle->Vertex.Position.z += fOffsetRadius * fSin - fOffsetRadius * 0.5f;
break;
}
}
}
////
// 粒子更新
////
void UpdateParticleBubble(CParticleSystem<BUBBLEPARAMETERS>::LPPARTICLE pParticle)
{
CBubble* pParent = (CBubble*)pParticle->pPARENT;
pParticle->Parameter.Velocity.y += pParent->GetFlotage();
//pParticle->Parameter.Velocity.x += (zerO::FLOAT)(rand() % 20 - 10 ) / 100;
//pParticle->Parameter.Velocity.z += (zerO::FLOAT)(rand() % 20 - 10 ) / 100;
pParticle->Vertex.Position += pParticle->Parameter.Velocity;
}
///
// 粒子销毁判断
///
bool IsParticleDestroyBubble(CParticleSystem<BUBBLEPARAMETERS>::LPPARTICLE pParticle)
{
return pParticle->Vertex.Position.y > 2000 || pParticle->Parameter.bIsFree;
}
zerO::INT g_nBubbleIndex;
///
// 粒子渲染前行为 渲染粒子的尾巴
// 返回:单个粒子渲染次数
///
zerO::UINT GetParticleRenderStepBubble(const CParticleSystem<BUBBLEPARAMETERS>::PARTICLE& Particle)
{
return 1;
}
///
// 粒子渲染
///
bool SetParticleRenderDataBubble(const CParticleSystem<BUBBLEPARAMETERS>::PARTICLE& Particle, CParticleSystem<BUBBLEPARAMETERS>::PARTICLEVERTEX& Vertex)
{
Vertex.Position = Particle.Vertex.Position;
Vertex.Color = Particle.Vertex.Color;
return true;
}
///
// 构建函数
// uMaxNum 弹夹的大小,每次最大能发射多少子弹
// uFlush 每次渲染的最大数量
// uDiscard Buffer的容量
// fSize 粒子的大小
// 返回 成功返回true, 失败返回false.
///
bool CBubble::Create(zerO::UINT uMaxNum, zerO::UINT uFlush, zerO::UINT uDiscard, zerO::FLOAT fSize)
{
D3DCAPS9 Caps;
DEVICE.GetDeviceCaps(&Caps);
if(!zerO::CParticleSystem<BUBBLEPARAMETERS>::Create(
0, uMaxNum, uFlush, uDiscard, fSize, /*2.0f*/Caps.MaxPointSize, 0.0f, 0.0f, 0.0f, 1.0f,
InitParicleBubble, UpdateParticleBubble, IsParticleDestroyBubble, GetParticleRenderStepBubble, SetParticleRenderDataBubble))
return false;
return true;
}
void CBubble::Update()
{
__BuildAcceleration();
CParticleSystem<BUBBLEPARAMETERS>::Update();
m_uNumEmitedPerFrame = 0;
}
void CBubble::Render(zerO::CRenderQueue::LPRENDERENTRY pEntry, zerO::UINT32 uFlag)
{
DEVICE.SetRenderState(D3DRS_ZWRITEENABLE, false );
DEVICE.SetRenderState(D3DRS_ALPHABLENDENABLE, true );
DEVICE.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
DEVICE.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
CParticleSystem::Render(pEntry, uFlag);
DEVICE.SetRenderState(D3DRS_ALPHABLENDENABLE, false );
DEVICE.SetRenderState(D3DRS_ZWRITEENABLE , true );
} | [
"linfuqing0@c6a4b443-94a6-74e8-d042-0855a5ab0aac"
] | [
[
[
1,
154
]
]
] |
13f47f4aeafd704ad7444806887fd57d9a2191d3 | 2d22825193eacf3669ac8bd7a857791745a9ead4 | /hw2/MotionGraph.cpp | 5bc26440db59d063ad1efadafb28e87130f8bed4 | [] | 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 | ISO-8859-1 | C++ | false | false | 22,647 | cpp | #include "MotionGraph.h"
#include "iostream"
#include "skeleton.h"
#include "fstream"
#include "transform.h"
#include "Math3D.h"
#include <stdlib.h>
#include <time.h>
#define NUM_BONES_IN_ASF_FILE 100
using namespace std;
float m_jointWeights[NUM_BONES_IN_ASF_FILE];
float GetFacingAngle(Vector3 Ori)
{
Matrix4 m = m.FromEulerAngle(Ori*deg2rad);
return RADTODEG(atan2(m[8], m[10]));
}
double FrameDistance(Posture& p0, Posture& p1)
{
double dist = 0;
return dist;
}
MotionGraph::MotionGraph()
{
offset = 0;
m_NumMotions = 0;
m_pPostures = NULL;
m_LocalMinima.reserve(2000);
m_Vertices = NULL;
m_BufferIndex = 0;
m_MaxSCCRoot = NULL;
}
MotionGraph::MotionGraph(char *amc_filename, float scale,Skeleton * pActor2)
{
pActor = pActor2;
// m_NumDOFs = actor.m_NumDOFs;
offset = 0;
m_NumFrames = 0;
m_pPostures = NULL;
readAMCfile(amc_filename, scale);
m_EndFrames[0] = m_NumFrames-1;
m_NumMotions = 1;
}
MotionGraph::~MotionGraph()
{
}
void MotionGraph::Concatenate(Motion& m1)
{
Posture* new_Postures;
new_Postures = new Posture [m_NumFrames + m1.m_NumFrames];
for(int i=0; i<m_NumFrames; i++)
new_Postures[i] = m_pPostures[i];
for(int i=m_NumFrames ; i < m_NumFrames + m1.m_NumFrames; i++)
new_Postures[i] = m1.m_pPostures[i-m_NumFrames];
delete [] m_pPostures;
m_NumFrames += m1.m_NumFrames;
m_EndFrames[m_NumMotions] = m_NumFrames-1;
m_NumMotions++;
m_pPostures = new_Postures;
}
/*
* [DONE] Compute pose difference
* [DONE] Do pruning
*/
void MotionGraph::Construct()
{
int i, j;
double* pData;
// Allocate pose difference matrix
m_PoseDifference = (double**)malloc(m_NumFrames*sizeof(double*) + m_NumFrames*m_NumFrames*sizeof(double));
for (i=0, pData = (double*)(m_PoseDifference+m_NumFrames); i < m_NumFrames; i++, pData+=m_NumFrames)
m_PoseDifference[i] = pData;
// Initialize pose difference matrix
for (i=0; i<m_NumFrames; i++)
for(j=0; j<m_NumFrames; j++)
m_PoseDifference[i][j] = -1.0f;
computePoseDifference();
// Find local minimum in search windows
findLocalMinimum();
// Create graph structure
createGraphStructure();
//Do pruning
findSCC();
}
/*
* Put the pose sequence into buffer when encounter transition.
* Parameter : "data" store pose vector that is pose sequence from previous transion to current transition.
*/
void MotionGraph::Transition(std::vector<Posture>& data)
{
// for reference, you can replace with your code here
if(buffer.empty())
{
for(int i=0;i<data.size();i++)
buffer.push_back(data[i]);
}
else
{
Posture old_end;
Posture new_start;
Posture end;
double angle; // angle difference between old_end and new_start
old_end = buffer[buffer.size()-1];
new_start = data[0];
angle = GetFacingAngle(old_end.bone_rotation[0]) - GetFacingAngle(new_start.bone_rotation[0]);
int len = data.size();
if(len > TRANS_NUMS)
len = TRANS_NUMS;
end = data[len-1];
if(len <= 2)
{
if(buffer.size() >= TRANS_NUMS)
{
Posture front;
front = buffer[buffer.size()-TRANS_NUMS];
new_start.Rotate(angle);
for(int i=1;i<TRANS_NUMS;i++)
{
// Blend front and new_start in different ratio as temp
Posture temp = Slerp((float)i/(TRANS_NUMS-1), front, new_start);
Posture source;
source = buffer[buffer.size()-TRANS_NUMS+i];
temp.root_pos.x = source.root_pos.x;
temp.root_pos.z = source.root_pos.z;
// Blend poses in buffer with temp
buffer[buffer.size()-TRANS_NUMS+i] = Slerp((float)i/(TRANS_NUMS-1), source, temp);
}
}
else
{
// interpolation
new_start.Rotate(angle);
for(int k=1;k<TRANS_NUMS-1;k++)
{
Posture temp;
// Blend old_end and new_start in different ratio as temp
temp = Slerp((float)k/(TRANS_NUMS-1), old_end, new_start);
temp.root_pos.x = old_end.root_pos.x;
temp.root_pos.z = old_end.root_pos.z;
buffer.push_back(temp);
}
}
len = 0;
}
end.Rotate(angle);
for(int k=1;k<data.size();k++)
{
Posture p;
if(k < len)
{
Posture temp;
temp = Slerp((float)k/(len-1), old_end,end);
Posture source;
source = data[k];
source.Rotate(angle);
temp.root_pos.x = source.root_pos.x;
temp.root_pos.z = source.root_pos.z;
p = Slerp((float)k/(len-1), temp, source);
p.bone_rotation[0] = source.bone_rotation[0];
}
else
{
p = data[k];
p.Rotate(angle);
}
Vector3 disp = p.root_pos - new_start.root_pos;
Matrix4 RyTrans = Matrix4::Yrotate(angle * deg2rad);
disp = RyTrans * disp;
p.root_pos.x = old_end.root_pos.x + disp.x;
p.root_pos.z = old_end.root_pos.z + disp.z;
buffer.push_back(p);
}
}
}
void MotionGraph::Transition1(std::vector<Posture>& data)
{
if(buffer.empty())
{
for(int i=0;i<data.size();i++)
buffer.push_back(data[i]);
}
else
{
Posture old_end, new_start, new_end;
double angle;
int len;
len = data.size();
if (len > TRANS_NUMS)
len = TRANS_NUMS;
old_end = buffer[buffer.size() - 1];
new_end = data[len - 1];
new_start = data[0];
angle = GetFacingAngle(old_end.bone_rotation[0]) - GetFacingAngle(new_start.bone_rotation[0]);
if (len <= 2)
{
if (buffer.size() >= TRANS_NUMS)
{
Posture front;
front = buffer[buffer.size() -TRANS_NUMS];
new_start.Rotate(angle);
for(int i=1; i<TRANS_NUMS; i++)
{
// Blend front and new_start in different ratio as temp
Posture temp = Slerp((float)i/(TRANS_NUMS-1), front, new_start);
Posture source;
source = buffer[buffer.size()-TRANS_NUMS+i];
temp.bone_translation[0].x = source.bone_translation[0].x;
temp.bone_translation[0].z = source.bone_translation[0].z;
// Blend poses in buffer with temp
buffer[buffer.size()-TRANS_NUMS+i] = Slerp((float)i/(TRANS_NUMS-1), source, temp);
}
}
else
{
new_start.Rotate(angle);
for (int k=1; k<TRANS_NUMS-1; k++)
{
Posture temp;
temp = Slerp((float)k/TRANS_NUMS, old_end, new_start);
temp.bone_translation[0].x = old_end.bone_translation[0].x;
temp.bone_translation[0].z = old_end.bone_translation[0].z;
buffer.push_back(temp);
}
}
len = 0;
}
Posture p, source;
new_end.Rotate(angle);
for (int i=0; i<data.size(); i++)
{
source = data[i];
if (i < len)
{
Posture temp;
temp = Slerp((float)i/len, old_end,new_end);
// orientation
source.Rotate(angle);
temp.bone_translation[0].x = source.bone_translation[0].x;
temp.bone_translation[0].z = source.bone_translation[0].z;
p = Slerp((float)i/len, buffer[buffer.size()-i-1], source);
p.bone_rotation[0] = source.bone_rotation[0];
}
else
{
// orientation
p = data[i];
p.Rotate(angle);
}
// Displacement
Vector3 disp = data[i].bone_translation[0] - new_start.bone_translation[0];
Matrix4 RyTrans = Matrix4::Yrotate(angle*deg2rad);
disp = RyTrans*disp;
p.bone_translation[0].x = old_end.bone_translation[0].x + disp.x;
p.bone_translation[0].z = old_end.bone_translation[0].z + disp.z;
buffer.push_back(p);
}
}
}
int MotionGraph::NextJump(int index)
{
int i, adjSize, next = -1;
int defaultFrame;
MotionVertex *curVertex, *adjVertex, *nextFrameVertex;
double accProb = 0.0f, Prob;
//srand(time(NULL));
Prob = double(rand() % 1000) / 1000.0;
if (Prob < 0.0 || Prob > 1.0)
{
cout << "Prob error!" << endl;
exit(1);
}
curVertex = &m_Vertices[index];
adjSize = curVertex->m_AdjVertices.size();
for (i = 0; i < adjSize; i++)
{
adjVertex = curVertex->m_AdjVertices[i];
if (adjVertex->m_InSCC)
{
// If only 1 adjVertex in SCC, return it
if (curVertex->m_NumSCCAdj == 1)
return adjVertex->m_FrameIndex;
if (curVertex->m_NextFrameInSCC) // next frame is in SCC
{
if (adjVertex->m_FrameIndex == (curVertex->m_FrameIndex + 1) &&
adjVertex->m_MotionIndex == curVertex->m_MotionIndex)
accProb += 0.5f;
else
accProb += (0.5/(double)(curVertex->m_NumSCCAdj - 1));
}
else // next frame is not in SCC, each adjVertex has the same chance
{
accProb += (1.0/(double)curVertex->m_NumSCCAdj);
}
/*
if (accProb > 1.0f)
{
cout << "accProb error:accProb=" << accProb << endl;
system("PAUSE");
}*/
if (accProb >= Prob)
{
next = adjVertex->m_FrameIndex;
return next;
}
defaultFrame = adjVertex->m_FrameIndex;
}
}
return defaultFrame;
}
// Traverse motion graph
int MotionGraph::Traverse(int current, bool& jump)
{
jump = false;
int next = 0;
/*
vector<Posture> v;
v.push_back(m_pPostures[current]);
if(buffer.size() < 1000)
{
//Transition(v);
buffer.push_back(m_pPostures[current]);
}*/
next = NextJump(current);
if (next == -1)
{
cout << "NextJump error" << endl;
exit(1);
}
return next;
}
// Traverse motion graph
int MotionGraph::Traverse1(int current, bool& jump)
{
jump = false;
int next = 0, curr = current;
int i;
vector<Posture> poseVector;
while ( (buffer.size() - m_BufferIndex) < TRANS_NUMS)
{
poseVector.push_back(m_pPostures[curr]);
next = NextJump(curr);
if (m_Vertices[current].m_MotionIndex == m_Vertices[next].m_MotionIndex &&
next == (current + 1))
{
}
else
{
Transition1(poseVector);
poseVector.clear();
}
curr = next;
}
return curr;
}
int MotionGraph::GenerateMotion(int total_frames, int start_frame, char* filename)
{
Motion outMotion(total_frames, pActor);
int next = start_frame;
while(buffer.size() < total_frames)
next = NextJump(next);
for(int i=0;i<total_frames;i++)
{
buffer[i].root_pos = buffer[i].bone_translation[0];
outMotion.SetPosture(i, buffer[i]);
}
outMotion.writeAMCfile(filename, MOCAP_SCALE);
return next;
}
void MotionGraph::printJumpIdx(int current, int next )
{
int i, cur_clipIdx, cur_frameIdx, next_clipIdx, next_frameIdx;
for(i=0; i<m_NumMotions; i++)
{
if( m_EndFrames[i] >= current )
break;
}
cur_clipIdx = i;
if(i > 0)
cur_frameIdx = current - m_EndFrames[i-1];
else
cur_frameIdx = current;
for(i=0; i<m_NumMotions; i++)
{
if( m_EndFrames[i] >= next )
break;
}
next_clipIdx = i;
if(i>0)
next_frameIdx = next-m_EndFrames[i-1];
else
next_frameIdx = next;
//printf("jump from ( %d, %d ) to %d, %d\n", frame no, cur_clipIdx, cur_frameIdx, next_clipIdx, next_frameIdx);
printf("jump from ( %d, %d ) to ( %d, %d )\n", cur_clipIdx, cur_frameIdx, next_clipIdx, next_frameIdx);
}
void MotionGraph::setActor(Skeleton *pActor)
{
this->pActor = pActor;
}
/*
* Define pose difference as Dij = d(pi, pj ) + £hd(vi, vj ).
* d(pi, pj ) : weighted differences of joint angles,
* d(vi, vj ) : weighted differences of joint velocities
* [TODO] Preserve dynamics
*/
void MotionGraph::computePoseDifference()
{
int i, j;
Posture *p1, *p2;
double tmp;
// Compute joint velocities
for (i=0, j=0; i<m_NumFrames; i++)
{
if (i != m_EndFrames[j])
{
m_pPostures[i].computeJointVelocities(m_pPostures[i+1], true);
}
else
{
m_pPostures[i].computeJointVelocities(m_pPostures[i-1], false);
j++;
}
}
for (i=0; i < m_NumFrames; i++)
{
p1 = &m_pPostures[i];
for (j=0; j < m_NumFrames; j++)
{
p2 = &m_pPostures[j];
if (m_PoseDifference[j][i] >= 0.0f)
m_PoseDifference[i][j] = m_PoseDifference[j][i];
else
{
// Diff of joint orientation
m_PoseDifference[i][j] = Posture::compareJointAngles(*p1, *p2);
// Diff of joint velocity
m_PoseDifference[i][j] += (double)VELOCITY_WEIGHT * Posture::compareJointVelocities(*p1, *p2);
}
//cout << "dist[" << i << "][" << j << "]=" << m_PoseDifference[i][j] << endl;
}
printf("%2.2f %%completed\n",(double) i/(m_NumFrames-1)*100);
}
}
/*
* Find local minimum of each window in the pose difference matrix
*/
void MotionGraph::findLocalMinimum()
{
int i, j, p, q;
const int winSize = 50;
int rowBound, colBound;
double localMin;
int minI, minJ;
/*
// For statisitics
int cnt = 0;
double min = 9999.0f, max = 0.0f, sum = 0.0f;
*/
for (i = 0; i < m_NumFrames; i += winSize)
for (j = 0; j < m_NumFrames; j += winSize)
{
if (i+winSize < m_NumFrames)
rowBound = i+winSize;
else
rowBound = m_NumFrames;
if (j+winSize < m_NumFrames)
colBound = j+winSize;
else
colBound = m_NumFrames;
// Search inside a window
localMin = 9999.0f;
for (p = i; p < rowBound; p++)
for (q = j; q < colBound; q++)
{
if (p == q)
continue;
if (m_PoseDifference[p][q] < localMin)
{
localMin = m_PoseDifference[p][q];
minI = p;
minJ = q;
}
}
if (localMin < Threshold)
{
m_LocalMinima.push_back(pair<int, int>(minI, minJ));
}
/*
// Gather statistics
if (localMin < min)
min = localMin;
if (localMin > max)
max = localMin;
sum += localMin;
cnt++;*/
}
/*
cout << "min = " << min << endl;
cout << "max = " << max << endl;
cout << "avg = " << sum / (double) cnt << endl;
system("PAUSE");*/
}
void MotionGraph::createGraphStructure()
{
int i, j;
MotionVertex* pVertex;
// Allocate motion vertices
m_Vertices = new MotionVertex[m_NumFrames];
pVertex = m_Vertices;
for (i = 0, j = 0; i < m_NumFrames; i++)
{
pVertex = &m_Vertices[i];
pVertex->m_MotionIndex = j;
pVertex->m_FrameIndex = i;
// Connect edges of vertex in same motion
if (i != m_EndFrames[j])
pVertex->m_AdjVertices.push_back(&m_Vertices[i+1]);
else
{
j++;
}
}
/*
for (i = 0, j = 0; i < m_NumFrames; i++)
{
pVertex = &m_Vertices[i];
if (i != m_EndFrames[j])
if (pVertex->m_AdjVertices.size() == 0)
{
cout << "adj Exception : i=" << i << endl;
system("PAUSE");
}
else
j++;
}
*/
// Connect edges for local minima
int size = (int) m_LocalMinima.size();
std::pair<int, int> *pLocalMin;
for (i = 0; i < size; i++)
{
pLocalMin = &m_LocalMinima[i];
m_Vertices[pLocalMin->first].m_AdjVertices.push_back(&m_Vertices[pLocalMin->second]);
}
}
void MotionGraph::DFS(bool SCCOrder)
{
int i;
int time = 0;
MotionVertex* pVertex;
if (m_Vertices == NULL)
{
cout << "Exception in DFS():m_Vertices is null" << endl;
exit(1);
}
for (i=0; i<m_NumFrames; i++)
{
pVertex = &m_Vertices[i];
pVertex->m_Color = MotionVertex::WHITE;
pVertex->m_Pi = NULL;
}
if (!SCCOrder)
for (i=0; i<m_NumFrames; i++)
{
pVertex = &m_Vertices[i];
if(pVertex->m_Color == MotionVertex::WHITE)
{
DFS_Visit(pVertex, &time, false);
}
}
else
for (i=(int)m_SCCQueue.size()-1; i>=0; i--)
{
pVertex = &m_Vertices[i];
if(pVertex->m_Color == MotionVertex::WHITE)
{
DFS_Visit(pVertex, &time, true);
}
}
}
void MotionGraph::DFS_Visit(MotionVertex* u, int* time, bool SCCOrder)
{
int i, size;
MotionVertex* v;
u->m_Color = MotionVertex::GRAY;
(*time) = (*time) + 1;
u->m_DTime = *time;
if (!SCCOrder) // Traverse G
{
size = u->m_AdjVertices.size();
for (i = 0; i < size; i++)
{
v = u->m_AdjVertices[i];
if (v->m_Color == MotionVertex::WHITE)
{
v->m_Pi = u;
DFS_Visit(v, time, SCCOrder);
}
}
}
else // Traverse G^T
{
size = u->m_TransposeAdjVertices.size();
for (i = 0; i < size; i++)
{
v = u->m_TransposeAdjVertices[i];
if (v->m_Color == MotionVertex::WHITE)
{
v->m_Pi = u;
DFS_Visit(v, time, SCCOrder);
}
}
}
u->m_Color = MotionVertex::BLACK;
(*time) = (*time) + 1;
u->m_FTime = *time;
if (!SCCOrder)
m_SCCQueue.push_back(u);
}
void MotionGraph::findSCC()
{
int i, j, size;
MotionVertex* v;
int order;
int maxInterval = 0;
DFS(false);
// compute transpose graph
for (i = 0; i < m_NumFrames; i++)
{
v = &m_Vertices[i];
size = v->m_AdjVertices.size();
for (j = 0; j < size; j++)
{
v->m_AdjVertices[j]->m_TransposeAdjVertices.push_back(v);
}
}
// Do DFS on transpose graph in decreasing FTime order
DFS(true);
// Find the largest SCC
for (i=0; i<m_NumFrames; i++)
{
v = &m_Vertices[i];
if (v->m_Pi == NULL && v->m_AdjVertices.size())
if ((v->m_FTime - v->m_DTime) > maxInterval)
{
maxInterval = (v->m_FTime - v->m_DTime);
m_MaxSCCRoot = v;
}
}
if (!m_MaxSCCRoot)
{
cout << "Motion graph has no large SCC" <<endl;
system("PAUSE");
exit(1);
}
// Identify all vertices in SCC
for (i=0; i<m_NumFrames; i++)
{
v = &m_Vertices[i];
if ( (v->m_DTime >= m_MaxSCCRoot->m_DTime) &&
(v->m_FTime <= m_MaxSCCRoot->m_FTime) )
{
if (v->m_AdjVertices.size() > 0)
v->m_InSCC = true;
}
}
for (i=0; i<m_NumFrames; i++)
{
v = &m_Vertices[i];
if (v->m_InSCC)
{
v->computeNumSCCAdj();
if ( ((v->m_FrameIndex + 1) < m_NumFrames) &&
(m_Vertices[v->m_FrameIndex + 1].m_MotionIndex == v->m_MotionIndex) &&
(m_Vertices[v->m_FrameIndex + 1].m_InSCC) )
{
v->m_NextFrameInSCC = true;
}
}
}
}
inline double getPieceLength(double* start, double* end)
{
double x = end[0]-start[0];
double z = end[2]-start[2];
return sqrt(x*x+z*z);
}
void MotionGraph::doPathSynthesis(vector<double*>& line)
{
double lineLen=0.0f, pathLen=0.0f;
int i;
vector<Posture> poseVector;
int current, next;
Vector3 goal, currentPos, nextPos;
MotionVertex *nextVertex, *currentVertex, *tempVertex;
Vector3 dir, zAxis(0.0, 0.0, 1.0);
Posture *lastPose;
int len;
if (!buffer.empty())
buffer.clear();
// Align position to the start point of the line
current = m_MaxSCCRoot->m_FrameIndex;
buffer.push_back(m_pPostures[current]);
buffer[0].bone_translation[0].x = line[0][0];
buffer[0].bone_translation[0].z = line[0][2];
lastPose = &buffer[buffer.size()-1];
if (line.size() < 5)
len = line.size();
else
len = 2;
goal.set(line[len-1][0], line[len-1][1], line[len-1][2]);
dir = goal - lastPose->bone_translation[0];
dir.y = 0;
dir.normalize();
double angle = dir.getAngleFromZAxis(dir) - GetFacingAngle(lastPose->bone_rotation[0]);
lastPose->Rotate(angle);
//cout << "angle:" << dir.getAngleFromZAxis(dir) << endl;
for (i=0; i<line.size()-1; i++)
{
// Extract a piece of line
lineLen += getPieceLength(line[i], line[i+1]);
if ( i + 10 < line.size())
goal.set(line[i+1][0], line[i+1][1], line[i+1][2]);
else
goal.set(line[i+1][0], line[i+1][1], line[i+1][2]);
while(pathLen < lineLen)
{
currentPos = buffer[buffer.size()-1].bone_translation[0];
// adjust orientation of the last frame in buffer
lastPose = &buffer[buffer.size()-1];
dir = goal - lastPose->bone_translation[0];
dir.y = 0;
dir.normalize();
double angle = dir.getAngleFromZAxis(dir) - GetFacingAngle(lastPose->bone_rotation[0]);
lastPose->Rotate(angle);
// Search for the posture that minimize
// the distance between root and line node
// Select next frame index
next = NextJumpPS(current, goal);
nextVertex = &m_Vertices[next];
currentVertex = &m_Vertices[current];
//------------do transition-----------------
if(nextVertex->m_MotionIndex == currentVertex->m_MotionIndex &&
nextVertex->m_FrameIndex == currentVertex->m_FrameIndex + 1)
{
poseVector.push_back(m_pPostures[current]);
}
poseVector.push_back(m_pPostures[nextVertex->m_FrameIndex]);
// Take the next frames as edge
for (int j=0; j<TRANS_NUMS-1; j++)
{
tempVertex = &m_Vertices[nextVertex->m_FrameIndex+j];
if (tempVertex->m_InSCC &&
tempVertex->m_MotionIndex == nextVertex->m_MotionIndex)
{
poseVector.push_back(m_pPostures[nextVertex->m_FrameIndex+j]);
current = nextVertex->m_FrameIndex+j;
}
else
break;
}
Transition1(poseVector);
poseVector.clear();
//---------------------------------------------
// Record positions
nextPos = buffer[buffer.size()-1].bone_translation[0];
nextPos.y = 0.0f;
currentPos.y = 0.0f;
pathLen += (nextPos-currentPos).length();
}
printf("Path synthesis...%2.2f%%\n", (double)i/(line.size()-1)*100);
}
m_BufferIndex = 0;
cout << "lineLen:" << lineLen << ", pathLen:" << pathLen << endl;
}
int MotionGraph::NextJumpPS(int index, Vector3& goal)
{
int i, j, adjSize, next = -1;
MotionVertex *curVertex, *adjVertex, *nextVertex;
int adjFrameIndex, adjMotionIndex;
vector<Posture> poseVector;
double currentError, minError = 99999.0f;
curVertex = &m_Vertices[index];
adjSize = curVertex->m_AdjVertices.size();
// For each adjVertex, find an edge and transit it
// Then compute errors and do comparison
for (i=0; i<adjSize; i++)
{
adjVertex = curVertex->m_AdjVertices[i];
if (adjVertex->m_InSCC)
{
adjFrameIndex = adjVertex->m_FrameIndex;
adjMotionIndex = adjVertex->m_MotionIndex;
if(adjMotionIndex == curVertex->m_MotionIndex &&
adjFrameIndex == curVertex->m_FrameIndex + 1)
{
poseVector.push_back(m_pPostures[index]);
}
poseVector.push_back(m_pPostures[adjFrameIndex]);
// Take the next frames as edge
for (j=0; j<TRANS_NUMS-1; j++)
{
nextVertex = &m_Vertices[adjFrameIndex+j];
if (nextVertex->m_InSCC &&
nextVertex->m_MotionIndex == adjMotionIndex)
{
poseVector.push_back(m_pPostures[adjFrameIndex+j]);
}
else
break;
}
m_BufferIndex = buffer.size()-1;
// Check the transition result to compare errors
Transition1(poseVector);
// Error
currentError = (goal - buffer[buffer.size()-1].bone_translation[0]).norm();
if (currentError < minError)
{
minError = currentError;
next = adjFrameIndex;
}
// Recovery the motion buffer
while(buffer.size() > m_BufferIndex+1)
buffer.pop_back();
poseVector.clear();
}
}
if (next == -1)
{
cout << "Exception in NextJumpSP()" << endl;
system("PAUSE");
exit(1);
}
return next;
} | [
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
] | [
[
[
1,
974
]
]
] |
561fcbe6e638d32961d3258696a6daa2b6ec2465 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/gui/AppConfig.cpp | de519ef48332d485d5525123c07bbe518f2b511e | [] | no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,395 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "App.h"
#include "MainFrame.h"
#include "Plugins.h"
#include "MemoryCardFile.h"
#include "Utilities/IniInterface.h"
#include <wx/stdpaths.h>
#include "DebugTools/Debug.h"
//////////////////////////////////////////////////////////////////////////////////////////
// PathDefs Namespace -- contains default values for various pcsx2 path names and locations.
//
// Note: The members of this namespace are intended for default value initialization only.
// Most of the time you should use the path folder assignments in Conf() instead, since those
// are user-configurable.
//
namespace PathDefs
{
namespace Base
{
const wxDirName& Snapshots()
{
static const wxDirName retval( L"snaps" );
return retval;
}
const wxDirName& Savestates()
{
static const wxDirName retval( L"sstates" );
return retval;
}
const wxDirName& MemoryCards()
{
static const wxDirName retval( L"memcards" );
return retval;
}
const wxDirName& Settings()
{
static const wxDirName retval( L"inis" );
return retval;
}
const wxDirName& Plugins()
{
static const wxDirName retval( L"plugins" );
return retval;
}
const wxDirName& Logs()
{
static const wxDirName retval( L"logs" );
return retval;
}
const wxDirName& Dumps()
{
static const wxDirName retval( L"dumps" );
return retval;
}
const wxDirName& Themes()
{
static const wxDirName retval( L"themes" );
return retval;
}
};
// Specifies the root folder for the application install.
// (currently it's the CWD, but in the future I intend to move all binaries to a "bin"
// sub folder, in which case the approot will become "..")
const wxDirName& AppRoot()
{
static const wxDirName retval( L"." );
return retval;
}
// Specifies the main configuration folder.
wxDirName GetUserLocalDataDir()
{
#ifdef __LINUX__
// Note: GetUserLocalDataDir() on linux return $HOME/.pcsx2 unfortunately it does not follow the XDG standard
// So we re-implement it, to follow the standard.
wxDirName user_local_dir;
wxString xdg_home_value;
if( wxGetEnv(L"XDG_CONFIG_HOME", &xdg_home_value) ) {
if ( xdg_home_value.IsEmpty() ) {
// variable exist but it is empty. So use the default value
user_local_dir = (wxDirName)Path::Combine( wxStandardPaths::Get().GetUserConfigDir() , wxDirName( L".config/pcsx2" ));
} else {
user_local_dir = (wxDirName)Path::Combine( xdg_home_value, pxGetAppName());
}
} else {
// variable do not exist
user_local_dir = (wxDirName)Path::Combine( wxStandardPaths::Get().GetUserConfigDir() , wxDirName( L".config/pcsx2" ));
}
return user_local_dir;
#else
return wxDirName(wxStandardPaths::Get().GetUserLocalDataDir());
#endif
}
// Fetches the path location for user-consumable documents -- stuff users are likely to want to
// share with other programs: screenshots, memory cards, and savestates.
wxDirName GetDocuments( DocsModeType mode )
{
switch( mode )
{
case DocsFolder_User: return (wxDirName)Path::Combine( wxStandardPaths::Get().GetDocumentsDir(), pxGetAppName() );
//case DocsFolder_CWD: return (wxDirName)wxGetCwd();
case DocsFolder_Custom: return CustomDocumentsFolder;
jNO_DEFAULT
}
return wxDirName();
}
wxDirName GetDocuments()
{
return GetDocuments( DocsFolderMode );
}
wxDirName GetSnapshots()
{
return GetDocuments() + Base::Snapshots();
}
wxDirName GetBios()
{
return GetDocuments() + wxDirName( L"bios" );
}
wxDirName GetSavestates()
{
return GetDocuments() + Base::Savestates();
}
wxDirName GetMemoryCards()
{
return GetDocuments() + Base::MemoryCards();
}
wxDirName GetPlugins()
{
return AppRoot() + Base::Plugins();
}
wxDirName GetSettings()
{
return GetDocuments() + Base::Settings();
}
wxDirName GetThemes()
{
return AppRoot() + Base::Themes();
}
wxDirName GetLogs()
{
return GetDocuments() + Base::Logs();
}
wxDirName Get( FoldersEnum_t folderidx )
{
switch( folderidx )
{
case FolderId_Plugins: return GetPlugins();
case FolderId_Settings: return GetSettings();
case FolderId_Bios: return GetBios();
case FolderId_Snapshots: return GetSnapshots();
case FolderId_Savestates: return GetSavestates();
case FolderId_MemoryCards: return GetMemoryCards();
case FolderId_Logs: return GetLogs();
case FolderId_Documents: return CustomDocumentsFolder;
jNO_DEFAULT
}
return wxDirName();
}
};
wxDirName& AppConfig::FolderOptions::operator[]( FoldersEnum_t folderidx )
{
switch( folderidx )
{
case FolderId_Plugins: return Plugins;
case FolderId_Settings: return SettingsFolder;
case FolderId_Bios: return Bios;
case FolderId_Snapshots: return Snapshots;
case FolderId_Savestates: return Savestates;
case FolderId_MemoryCards: return MemoryCards;
case FolderId_Logs: return Logs;
case FolderId_Documents: return CustomDocumentsFolder;
jNO_DEFAULT
}
return Plugins; // unreachable, but suppresses warnings.
}
const wxDirName& AppConfig::FolderOptions::operator[]( FoldersEnum_t folderidx ) const
{
return const_cast<FolderOptions*>( this )->operator[]( folderidx );
}
bool AppConfig::FolderOptions::IsDefault( FoldersEnum_t folderidx ) const
{
switch( folderidx )
{
case FolderId_Plugins: return UseDefaultPlugins;
case FolderId_Settings: return UseDefaultSettingsFolder;
case FolderId_Bios: return UseDefaultBios;
case FolderId_Snapshots: return UseDefaultSnapshots;
case FolderId_Savestates: return UseDefaultSavestates;
case FolderId_MemoryCards: return UseDefaultMemoryCards;
case FolderId_Logs: return UseDefaultLogs;
case FolderId_Documents: return false;
jNO_DEFAULT
}
return false;
}
void AppConfig::FolderOptions::Set( FoldersEnum_t folderidx, const wxString& src, bool useDefault )
{
switch( folderidx )
{
case FolderId_Plugins:
Plugins = src;
UseDefaultPlugins = useDefault;
break;
case FolderId_Settings:
SettingsFolder = src;
UseDefaultSettingsFolder = useDefault;
break;
case FolderId_Bios:
Bios = src;
UseDefaultBios = useDefault;
break;
case FolderId_Snapshots:
Snapshots = src;
UseDefaultSnapshots = useDefault;
break;
case FolderId_Savestates:
Savestates = src;
UseDefaultSavestates = useDefault;
break;
case FolderId_MemoryCards:
MemoryCards = src;
UseDefaultMemoryCards = useDefault;
break;
case FolderId_Logs:
Logs = src;
UseDefaultLogs = useDefault;
break;
case FolderId_Documents:
CustomDocumentsFolder = src;
break;
jNO_DEFAULT
}
}
// --------------------------------------------------------------------------------------
// Default Filenames
// --------------------------------------------------------------------------------------
namespace FilenameDefs
{
wxFileName GetConfig()
{
// TODO : ini extension on Win32 is normal. Linux ini filename default might differ
// from this? like pcsx2_conf or something ... ?
return pxGetAppName() + L".ini";
}
wxFileName GetUsermodeConfig()
{
return wxFileName( L"usermode.ini" );
}
const wxFileName& Memcard( uint port, uint slot )
{
static const wxFileName retval[2][4] =
{
{
wxFileName( L"Mcd001.ps2" ),
wxFileName( L"Mcd003.ps2" ),
wxFileName( L"Mcd005.ps2" ),
wxFileName( L"Mcd007.ps2" ),
},
{
wxFileName( L"Mcd002.ps2" ),
wxFileName( L"Mcd004.ps2" ),
wxFileName( L"Mcd006.ps2" ),
wxFileName( L"Mcd008.ps2" ),
}
};
IndexBoundsAssumeDev( L"FilenameDefs::Memcard", port, 2 );
IndexBoundsAssumeDev( L"FilenameDefs::Memcard", slot, 4 );
return retval[port][slot];
}
};
wxString AppConfig::FullpathTo( PluginsEnum_t pluginidx ) const
{
return Path::Combine( Folders.Plugins, BaseFilenames[pluginidx] );
}
// returns true if the filenames are quite absolutely the equivalent. Works for all
// types of filenames, relative and absolute. Very important that you use this function
// rather than any other type of more direct string comparison!
bool AppConfig::FullpathMatchTest( PluginsEnum_t pluginId, const wxString& cmpto ) const
{
// Implementation note: wxFileName automatically normalizes things as needed in it's
// equality comparison implementations, so we can do a simple comparison as follows:
return wxFileName(cmpto).SameAs( FullpathTo(pluginId) );
}
wxDirName GetLogFolder()
{
return UseDefaultLogs ? PathDefs::GetLogs() : Logs;
}
wxDirName GetSettingsFolder()
{
if( wxGetApp().Overrides.SettingsFolder.IsOk() )
return wxGetApp().Overrides.SettingsFolder;
return UseDefaultSettingsFolder ? PathDefs::GetSettings() : SettingsFolder;
}
wxString GetSettingsFilename()
{
wxFileName fname( wxGetApp().Overrides.SettingsFile.IsOk() ? wxGetApp().Overrides.SettingsFile : FilenameDefs::GetConfig() );
return GetSettingsFolder().Combine( fname ).GetFullPath();
}
wxString AppConfig::FullpathToBios() const { return Path::Combine( Folders.Bios, BaseFilenames.Bios ); }
wxString AppConfig::FullpathToMcd( uint slot ) const
{
return Path::Combine( Folders.MemoryCards, Mcd[slot].Filename );
}
AppConfig::AppConfig()
: MainGuiPosition( wxDefaultPosition )
, SysSettingsTabName( L"Cpu" )
, McdSettingsTabName( L"none" )
, AppSettingsTabName( L"Plugins" )
, GameDatabaseTabName( L"none" )
, DeskTheme( L"default" )
{
LanguageId = wxLANGUAGE_DEFAULT;
RecentIsoCount = 12;
Listbook_ImageSize = 32;
Toolbar_ImageSize = 24;
Toolbar_ShowLabels = true;
#ifdef __WXMSW__
McdCompressNTFS = true;
#endif
EnableSpeedHacks = false;
EnableGameFixes = false;
CdvdSource = CDVDsrc_Iso;
// To be moved to FileMemoryCard pluign (someday)
for( uint slot=0; slot<8; ++slot )
{
Mcd[slot].Enabled = !FileMcd_IsMultitapSlot(slot); // enables main 2 slots
Mcd[slot].Filename = FileMcd_GetDefaultName( slot );
}
}
// ------------------------------------------------------------------------
void AppConfig::LoadSaveUserMode( IniInterface& ini, const wxString& cwdhash )
{
ScopedIniGroup path( ini, cwdhash );
// timestamping would be useful if we want to auto-purge unused entries after
// a period of time. Dunno if it's needed.
/*wxString timestamp_now( wxsFormat( L"%s %s",
wxDateTime::Now().FormatISODate().c_str(), wxDateTime::Now().FormatISOTime().c_str() )
);
ini.GetConfig().Write( L"Timestamp", timestamp_now );*/
static const wxChar* DocsFolderModeNames[] =
{
L"User",
L"Custom",
};
if( ini.IsLoading() )
{
// HACK! When I removed the CWD option, the option became the cause of bad
// crashes. This detects presence of CWD, and replaces it with a custom mode
// that points to the CWD.
//
// The ini contents are rewritten and the CWD is removed. So after 0.9.7 is released,
// this code is ok to be deleted/removed. :) --air
wxString oldmode( ini.GetConfig().Read( L"DocumentsFolderMode", L"User" ) );
if( oldmode == L"CWD")
{
ini.GetConfig().Write( L"DocumentsFolderMode", L"Custom" );
ini.GetConfig().Write( L"CustomDocumentsFolder", Path::Normalize(wxGetCwd()) );
}
}
ini.EnumEntry( L"DocumentsFolderMode", DocsFolderMode, DocsFolderModeNames, DocsFolder_User );
ini.Entry( L"UseDefaultSettingsFolder", UseDefaultSettingsFolder, true );
ini.Entry( L"CustomDocumentsFolder", CustomDocumentsFolder, (wxDirName)Path::Normalize(wxGetCwd()) );
ini.Entry( L"SettingsFolder", SettingsFolder, PathDefs::GetSettings() );
ini.Flush();
}
// ------------------------------------------------------------------------
void AppConfig::LoadSaveMemcards( IniInterface& ini )
{
AppConfig defaults;
ScopedIniGroup path( ini, L"MemoryCards" );
for( uint slot=0; slot<2; ++slot )
{
ini.Entry( wxsFormat( L"Slot%u_Enable", slot+1 ),
Mcd[slot].Enabled, defaults.Mcd[slot].Enabled );
ini.Entry( wxsFormat( L"Slot%u_Filename", slot+1 ),
Mcd[slot].Filename, defaults.Mcd[slot].Filename );
}
for( uint slot=2; slot<8; ++slot )
{
int mtport = FileMcd_GetMtapPort(slot)+1;
int mtslot = FileMcd_GetMtapSlot(slot)+1;
ini.Entry( wxsFormat( L"Multitap%u_Slot%u_Enable", mtport, mtslot ),
Mcd[slot].Enabled, defaults.Mcd[slot].Enabled );
ini.Entry( wxsFormat( L"Multitap%u_Slot%u_Filename", mtport, mtslot ),
Mcd[slot].Filename, defaults.Mcd[slot].Filename );
}
}
void AppConfig::LoadSaveRootItems( IniInterface& ini )
{
AppConfig defaults;
IniEntry( MainGuiPosition );
IniEntry( SysSettingsTabName );
IniEntry( McdSettingsTabName );
IniEntry( AppSettingsTabName );
IniEntry( GameDatabaseTabName );
ini.EnumEntry( L"LanguageId", LanguageId, NULL, defaults.LanguageId );
IniEntry( RecentIsoCount );
IniEntry( DeskTheme );
IniEntry( Listbook_ImageSize );
IniEntry( Toolbar_ImageSize );
IniEntry( Toolbar_ShowLabels );
IniEntry( CurrentIso );
IniEntry( CurrentELF );
IniEntry( EnableSpeedHacks );
IniEntry( EnableGameFixes );
#ifdef __WXMSW__
IniEntry( McdCompressNTFS );
#endif
ini.EnumEntry( L"CdvdSource", CdvdSource, CDVD_SourceLabels, defaults.CdvdSource );
}
// ------------------------------------------------------------------------
void AppConfig::LoadSave( IniInterface& ini )
{
LoadSaveRootItems( ini );
LoadSaveMemcards( ini );
// Process various sub-components:
ProgLogBox .LoadSave( ini, L"ProgramLog" );
Folders .LoadSave( ini );
BaseFilenames .LoadSave( ini );
GSWindow .LoadSave( ini );
Framerate .LoadSave( ini );
// Load Emulation options and apply some defaults overtop saved items, which are regulated
// by the PCSX2 UI.
EmuOptions.LoadSave( ini );
if( ini.IsLoading() )
EmuOptions.GS.LimitScalar = Framerate.NominalScalar;
ini.Flush();
}
// ------------------------------------------------------------------------
AppConfig::ConsoleLogOptions::ConsoleLogOptions()
: DisplayPosition( wxDefaultPosition )
, DisplaySize( wxSize( 680, 560 ) )
, Theme(L"Default")
{
Visible = true;
AutoDock = true;
FontSize = 8;
}
void AppConfig::ConsoleLogOptions::LoadSave( IniInterface& ini, const wxChar* logger )
{
ConsoleLogOptions defaults;
ScopedIniGroup path( ini, logger );
IniEntry( Visible );
IniEntry( AutoDock );
IniEntry( DisplayPosition );
IniEntry( DisplaySize );
IniEntry( FontSize );
IniEntry( Theme );
}
void AppConfig::FolderOptions::ApplyDefaults()
{
if( UseDefaultPlugins ) Plugins = PathDefs::GetPlugins();
if( UseDefaultBios ) Bios = PathDefs::GetBios();
if( UseDefaultSnapshots ) Snapshots = PathDefs::GetSnapshots();
if( UseDefaultSavestates ) Savestates = PathDefs::GetSavestates();
if( UseDefaultMemoryCards ) MemoryCards = PathDefs::GetMemoryCards();
if( UseDefaultLogs ) Logs = PathDefs::GetLogs();
}
// ------------------------------------------------------------------------
AppConfig::FolderOptions::FolderOptions()
: Plugins ( PathDefs::GetPlugins() )
, Bios ( PathDefs::GetBios() )
, Snapshots ( PathDefs::GetSnapshots() )
, Savestates ( PathDefs::GetSavestates() )
, MemoryCards ( PathDefs::GetMemoryCards() )
, Logs ( PathDefs::GetLogs() )
, RunIso( PathDefs::GetDocuments() ) // raw default is always the Documents folder.
, RunELF( PathDefs::GetDocuments() ) // raw default is always the Documents folder.
{
bitset = 0xffffffff;
}
void AppConfig::FolderOptions::LoadSave( IniInterface& ini )
{
FolderOptions defaults;
ScopedIniGroup path( ini, L"Folders" );
if( ini.IsSaving() )
{
ApplyDefaults();
}
IniBitBool( UseDefaultPlugins );
IniBitBool( UseDefaultSettings );
IniBitBool( UseDefaultBios );
IniBitBool( UseDefaultSnapshots );
IniBitBool( UseDefaultSavestates );
IniBitBool( UseDefaultMemoryCards );
IniBitBool( UseDefaultLogs );
IniEntry( Plugins );
IniEntry( Bios );
IniEntry( Snapshots );
IniEntry( Savestates );
IniEntry( MemoryCards );
IniEntry( Logs );
IniEntry( RunIso );
IniEntry( RunELF );
if( ini.IsLoading() )
{
ApplyDefaults();
//if( DocsFolderMode != DocsFolder_CWD )
{
for( int i=0; i<FolderId_COUNT; ++i )
operator[]( (FoldersEnum_t)i ).Normalize();
}
}
}
// ------------------------------------------------------------------------
const wxFileName& AppConfig::FilenameOptions::operator[]( PluginsEnum_t pluginidx ) const
{
IndexBoundsAssumeDev( L"Filename[Plugin]", pluginidx, PluginId_Count );
return Plugins[pluginidx];
}
void AppConfig::FilenameOptions::LoadSave( IniInterface& ini )
{
ScopedIniGroup path( ini, L"Filenames" );
static const wxFileName pc( L"Please Configure" );
for( int i=0; i<PluginId_Count; ++i )
ini.Entry( tbl_PluginInfo[i].GetShortname(), Plugins[i], pc );
ini.Entry( L"BIOS", Bios, pc );
}
// ------------------------------------------------------------------------
AppConfig::GSWindowOptions::GSWindowOptions()
{
CloseOnEsc = true;
DefaultToFullscreen = false;
AlwaysHideMouse = false;
DisableResizeBorders = false;
DisableScreenSaver = true;
AspectRatio = AspectRatio_4_3;
WindowSize = wxSize( 640, 480 );
WindowPos = wxDefaultPosition;
IsMaximized = false;
IsFullscreen = false;
}
void AppConfig::GSWindowOptions::SanityCheck()
{
// Ensure Conformation of various options...
WindowSize.x = std::max( WindowSize.x, 8 );
WindowSize.x = std::min( WindowSize.x, wxGetDisplayArea().GetWidth()-16 );
WindowSize.y = std::max( WindowSize.y, 8 );
WindowSize.y = std::min( WindowSize.y, wxGetDisplayArea().GetHeight()-48 );
// Make sure the upper left corner of the window is visible enought o grab and
// move into view:
if( !wxGetDisplayArea().Contains( wxRect( WindowPos, wxSize( 48,48 ) ) ) )
WindowPos = wxDefaultPosition;
if( (uint)AspectRatio >= (uint)AspectRatio_MaxCount )
AspectRatio = AspectRatio_4_3;
}
void AppConfig::GSWindowOptions::LoadSave( IniInterface& ini )
{
ScopedIniGroup path( ini, L"GSWindow" );
GSWindowOptions defaults;
IniEntry( CloseOnEsc );
IniEntry( DefaultToFullscreen );
IniEntry( AlwaysHideMouse );
IniEntry( DisableResizeBorders );
IniEntry( DisableScreenSaver );
IniEntry( WindowSize );
IniEntry( WindowPos );
IniEntry( IsMaximized );
IniEntry( IsFullscreen );
static const wxChar* AspectRatioNames[] =
{
L"Stretch",
L"4:3",
L"16:9",
};
ini.EnumEntry( L"AspectRatio", AspectRatio, AspectRatioNames, defaults.AspectRatio );
if( ini.IsLoading() ) SanityCheck();
}
// ----------------------------------------------------------------------------
AppConfig::FramerateOptions::FramerateOptions()
{
NominalScalar = 1.0;
TurboScalar = 2.0;
SlomoScalar = 0.50;
SkipOnLimit = false;
SkipOnTurbo = false;
}
void AppConfig::FramerateOptions::SanityCheck()
{
// Ensure Conformation of various options...
NominalScalar .ConfineTo( 0.05, 10.0 );
TurboScalar .ConfineTo( 0.05, 10.0 );
SlomoScalar .ConfineTo( 0.05, 10.0 );
}
void AppConfig::FramerateOptions::LoadSave( IniInterface& ini )
{
ScopedIniGroup path( ini, L"Framerate" );
FramerateOptions defaults;
IniEntry( NominalScalar );
IniEntry( TurboScalar );
IniEntry( SlomoScalar );
IniEntry( SkipOnLimit );
IniEntry( SkipOnTurbo );
}
wxFileConfig* OpenFileConfig( const wxString& filename )
{
return new wxFileConfig( wxEmptyString, wxEmptyString, filename, wxEmptyString, wxCONFIG_USE_RELATIVE_PATH );
}
void RelocateLogfile()
{
g_Conf->Folders.Logs.Mkdir();
wxString newlogname( Path::Combine( g_Conf->Folders.Logs.ToString(), L"emuLog.txt" ) );
if( (emuLog != NULL) && (emuLogName != newlogname) )
{
Console.WriteLn( L"\nRelocating Logfile...\n\tFrom: %s\n\tTo : %s\n", emuLogName.c_str(), newlogname.c_str() );
wxGetApp().DisableDiskLogging();
fclose( emuLog );
emuLog = NULL;
}
if( emuLog == NULL )
{
emuLogName = newlogname;
emuLog = fopen( emuLogName.ToUTF8(), "wb" );
}
wxGetApp().EnableAllLogging();
}
// Parameters:
// overwrite - this option forces the current settings to overwrite any existing settings that might
// be saved to the configured ini/settings folder.
//
void AppConfig_OnChangedSettingsFolder( bool overwrite )
{
//if( DocsFolderMode != DocsFolder_CWD )
PathDefs::GetDocuments().Mkdir();
GetSettingsFolder().Mkdir();
const wxString iniFilename( GetSettingsFilename() );
if( overwrite )
{
if( wxFileExists( iniFilename ) && !wxRemoveFile( iniFilename ) )
throw Exception::AccessDenied(iniFilename).SetBothMsgs(wxLt("Failed to overwrite existing settings file; permission was denied."));
}
// Bind into wxConfigBase to allow wx to use our config internally, and delete whatever
// comes out (cleans up prev config, if one).
delete wxConfigBase::Set( OpenFileConfig( iniFilename ) );
GetAppConfig()->SetRecordDefaults();
if( !overwrite )
AppLoadSettings();
AppApplySettings();
}
// --------------------------------------------------------------------------------------
// pxDudConfig
// --------------------------------------------------------------------------------------
// Used to handle config actions prior to the creation of the ini file (for example, the
// first time wizard). Attempts to save ini settings are simply ignored through this
// class, which allows us to give the user a way to set everything up in the wizard, apply
// settings as usual, and only *save* something once the whole wizard is complete.
//
class pxDudConfig : public wxConfigBase
{
protected:
wxString m_empty;
public:
virtual ~pxDudConfig() {}
virtual void SetPath(const wxString& ) {}
virtual const wxString& GetPath() const { return m_empty; }
virtual bool GetFirstGroup(wxString& , long& ) const { return false; }
virtual bool GetNextGroup (wxString& , long& ) const { return false; }
virtual bool GetFirstEntry(wxString& , long& ) const { return false; }
virtual bool GetNextEntry (wxString& , long& ) const { return false; }
virtual size_t GetNumberOfEntries(bool ) const { return 0; }
virtual size_t GetNumberOfGroups(bool ) const { return 0; }
virtual bool HasGroup(const wxString& ) const { return false; }
virtual bool HasEntry(const wxString& ) const { return false; }
virtual bool Flush(bool ) { return false; }
virtual bool RenameEntry(const wxString&, const wxString& ) { return false; }
virtual bool RenameGroup(const wxString&, const wxString& ) { return false; }
virtual bool DeleteEntry(const wxString&, bool bDeleteGroupIfEmpty = true) { return false; }
virtual bool DeleteGroup(const wxString& ) { return false; }
virtual bool DeleteAll() { return false; }
protected:
virtual bool DoReadString(const wxString& , wxString *) const { return false; }
virtual bool DoReadLong(const wxString& , long *) const { return false; }
virtual bool DoWriteString(const wxString& , const wxString& ) { return false; }
virtual bool DoWriteLong(const wxString& , long ) { return false; }
};
static pxDudConfig _dud_config;
// --------------------------------------------------------------------------------------
// AppIniSaver / AppIniLoader
// --------------------------------------------------------------------------------------
class AppIniSaver : public IniSaver
{
public:
AppIniSaver();
virtual ~AppIniSaver() throw() {}
};
class AppIniLoader : public IniLoader
{
public:
AppIniLoader();
virtual ~AppIniLoader() throw() {}
};
AppIniSaver::AppIniSaver()
: IniSaver( (GetAppConfig() != NULL) ? *GetAppConfig() : _dud_config )
{
}
AppIniLoader::AppIniLoader()
: IniLoader( (GetAppConfig() != NULL) ? *GetAppConfig() : _dud_config )
{
}
void AppLoadSettings()
{
if( wxGetApp().Rpc_TryInvoke(AppLoadSettings) ) return;
AppIniLoader loader;
ConLog_LoadSaveSettings( loader );
SysTraceLog_LoadSaveSettings( loader );
g_Conf->LoadSave( loader );
if( !wxFile::Exists( g_Conf->CurrentIso ) )
g_Conf->CurrentIso.clear();
sApp.DispatchEvent( loader );
}
void AppSaveSettings()
{
// If multiple SaveSettings messages are requested, we want to ignore most of them.
// Saving settings once when the GUI is idle should be fine. :)
static u32 isPosted = false;
if( !wxThread::IsMain() )
{
if( AtomicExchange(isPosted, true) )
wxGetApp().PostIdleMethod( AppSaveSettings );
return;
}
if( !wxFile::Exists( g_Conf->CurrentIso ) )
g_Conf->CurrentIso.clear();
sApp.GetRecentIsoManager().Add( g_Conf->CurrentIso );
AtomicExchange( isPosted, false );
AppIniSaver saver;
g_Conf->LoadSave( saver );
ConLog_LoadSaveSettings( saver );
SysTraceLog_LoadSaveSettings( saver );
sApp.DispatchEvent( saver );
}
// Returns the current application configuration file. This is preferred over using
// wxConfigBase::GetAppConfig(), since it defaults to *not* creating a config file
// automatically (which is typically highly undesired behavior in our system)
wxConfigBase* GetAppConfig()
{
return wxConfigBase::Get( false );
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
924
]
]
] |
d928b256a53426c6583e974cb0311d0a7699cdf5 | 8fd82049c092a6b80f63f402aca243096eb7b3c8 | /MFCMailClient/MFCMailClient/SMTP.h | e0253f0a2109b35a3b8d53b95e30ee9ac10ea853 | [] | no_license | phucnh/laptrinhmang-k52 | 47965acb82750b600b543cc5c43d00f59ce5bc54 | b27a8a02f9ec8bf953b617402dce37293413bb0f | refs/heads/master | 2021-01-18T22:22:24.692192 | 2010-12-09T02:00:10 | 2010-12-09T02:00:10 | 32,262,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,180 | h | #if !defined(AFX_SMTP_H__55DE48CB_BEA4_11D1_870E_444553540000__INCLUDED_)
#define AFX_SMTP_H__55DE48CB_BEA4_11D1_870E_444553540000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include <afxsock.h>
#include <atltime.h> // MFC time extensions
#include <afxtempl.h>
#include "MailMessage.h"
#include "Mime.h"
#define SMTP_PORT 25 // Standard port for SMTP servers
#define RESPONSE_BUFFER_SIZE 3
#define GENERIC_SUCCESS 0
#define SYSTEM_STATUS 211
#define HELP_MESSAGE 214
#define SERVER_AVAILABLE 220
#define QUIT_SUCCESS 221
#define CONNECT_SUCCESS 250
#define INPUT_DATA 354
#define SERVER_NA 421
#define MAILBOX_NA 450
#define PROCESS_ERROR 451
#define SYSTEM_ERRSTORAGE 452
#define SYNTAX_ERROR 500
#define SYNERROR_ARGUMENT 501
#define COMMAND_NOTIMPLEMENT 502
#define COMMAND_BADSEQUENCE 503
#define COMMAND_PARAMNOTIMPL 504
#define MAILBOX_NOTFOUND 550
#define USER_NOTLOCAL 551
#define EXCEEDED_STORAGEALLOCATION 552
#define MAILBOX_NAMENOTALLOWED 553
#define TRANSACTION_FAILED 554
class CSMTP
{
public:
CSMTP( LPCTSTR szSMTPServerName, UINT nPort = SMTP_PORT );
//phuc add 20101028
CSMTP( );
// end phuc add 20101028
virtual ~CSMTP();
void SetServerProperties( LPCTSTR sServerHostName, UINT nPort = SMTP_PORT );
BOOL Connect();
CString GetServerHostName();
UINT GetPort();
BOOL Disconnect();
CString GetLastError();
virtual BOOL FormatMailMessage( MailHeader* msg );
BOOL SendMessage( MailHeader* msg );
BOOL SendMessage(MailHeader* msg, CMimeMessage* mime);
private:
BOOL get_response( UINT response_expected );
BOOL transmit_message( MailHeader* msg );
BOOL transmit_message(MailHeader* msg, CMimeMessage* mime);
CString prepare_body( MailHeader* msg );
BOOL prepare_header( MailHeader* msg);
CString m_Error;
BOOL m_Connected;
UINT m_Port;
CString m_IpAddress;
CSocket m_Server;
protected:
struct response_code
{
UINT nResponse; // Response we're looking for
TCHAR* sMessage; // Error message if we don't get it
};
TCHAR response_buf[ RESPONSE_BUFFER_SIZE ];
static response_code response_table[];
};
#endif | [
"nguyenhongphuc.hut@e1f3f65c-33eb-5b6a-8ef2-7789ca584060"
] | [
[
[
1,
86
]
]
] |
4aefc59555187501536936cc1751166c3b332efc | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/persistence2/engine/core/include/SaveAble.h | 06cde17d36b231883eb85caf371b09e6383606de | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,810 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
/// Basis jedes Objektes im Spiel, welches veränderlich ist und einen abspeicherbaren Status haben soll
#ifndef __SaveAble_H__
#define __SaveAble_H__
#include "CorePrerequisites.h"
#include "Properties.h"
namespace rl
{
class SaveAble;
class _RlCoreExport SaveAblePtr : public Ogre::SharedPtr<SaveAble>
{
};
typedef std::pair<CeGuiString, SaveAblePtr> SaveAbleReference;
class _RlCoreExport SaveAble : public PropertyHolder
{
public:
SaveAble(const CeGuiString &id, bool isSaveAble = true);
~SaveAble();
void setSaveAble(bool enable);
bool isSaveAble();
virtual const Property getProperty(const CeGuiString& key) const;
virtual void setProperty(const CeGuiString& key, const Property& value);
virtual PropertyKeys getAllPropertyKeys() const;
SaveAblePtr getParent() const { return mParentSaveAble.second; };
CeGuiString getId() const;
protected:
SaveAbleReference mParentSaveAble;
std::map<CeGuiString, SaveAblePtr> mChildrenSaveAbles;
CeGuiString mId;
bool mIsSaveAble;
};
}
#endif
| [
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
61
]
]
] |
02d508baf506ea909ef1c359cac4071fef5d7655 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/idcoder3to4.hpp | 5d090ab02d86a54f6a180e1076d8385f6be06928 | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,009 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IdCoder3To4.pas' rev: 6.00
#ifndef IdCoder3To4HPP
#define IdCoder3To4HPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <IdException.hpp> // Pascal unit
#include <IdCoder.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Idcoder3to4
{
//-- type declarations -------------------------------------------------------
#pragma pack(push, 4)
struct TIdCardinalBytes
{
union
{
struct
{
unsigned Whole;
};
struct
{
Byte Byte1;
Byte Byte2;
Byte Byte3;
Byte Byte4;
};
};
} ;
#pragma pack(pop)
class DELPHICLASS TIdASCIICoder;
class PASCALIMPLEMENTATION TIdASCIICoder : public Idcoder::TIdCoder
{
typedef Idcoder::TIdCoder inherited;
protected:
AnsiString FCodingTable;
int FCodeTableLength;
int __fastcall GetTableIndex(const char AChar);
virtual void __fastcall SetCodingTable(AnsiString NewTable);
public:
__property AnsiString CodingTable = {read=FCodingTable, write=SetCodingTable};
__fastcall virtual TIdASCIICoder(Classes::TComponent* AOwner);
public:
#pragma option push -w-inl
/* TIdCoder.Destroy */ inline __fastcall virtual ~TIdASCIICoder(void) { }
#pragma option pop
};
class DELPHICLASS TId3To4Coder;
class PASCALIMPLEMENTATION TId3To4Coder : public TIdASCIICoder
{
typedef TIdASCIICoder inherited;
protected:
void __fastcall Code3To4(Byte In1, Byte In2, Byte In3, Byte &Out1, Byte &Out2, Byte &Out3, Byte &Out4);
void __fastcall Code4To3(const Byte AIn1, const Byte AIn2, const Byte AIn3, const Byte AIn4, Byte &AOut1, Byte &AOut2, Byte &AOut3);
AnsiString __fastcall CodeLine3To4();
AnsiString __fastcall CompleteLine3To4();
AnsiString __fastcall CodeLine4To3();
public:
__fastcall virtual TId3To4Coder(Classes::TComponent* AOwner);
__fastcall virtual ~TId3To4Coder(void);
};
class DELPHICLASS TIdBase64Encoder;
typedef TIdBase64Encoder* *PIdBase64Encoder;
class PASCALIMPLEMENTATION TIdBase64Encoder : public TId3To4Coder
{
typedef TId3To4Coder inherited;
protected:
virtual void __fastcall Coder(void);
virtual void __fastcall CompleteCoding(void);
public:
__fastcall virtual TIdBase64Encoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdBase64Encoder(void);
};
class DELPHICLASS TIdBase64Decoder;
typedef TIdBase64Decoder* *PIdBase64Decoder;
class PASCALIMPLEMENTATION TIdBase64Decoder : public TId3To4Coder
{
typedef TId3To4Coder inherited;
protected:
virtual void __fastcall Coder(void);
virtual void __fastcall CompleteCoding(void);
public:
__fastcall virtual TIdBase64Decoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdBase64Decoder(void);
};
class DELPHICLASS TIdUUEncoder;
typedef TIdUUEncoder* *PIdUUEncoder;
class PASCALIMPLEMENTATION TIdUUEncoder : public TId3To4Coder
{
typedef TId3To4Coder inherited;
protected:
bool FTableNeeded;
bool FIsFirstRound;
int FPrivilege;
virtual void __fastcall Coder(void);
virtual void __fastcall CompleteCoding(void);
virtual void __fastcall OutputHeader(void);
public:
__fastcall virtual TIdUUEncoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdUUEncoder(void);
virtual void __fastcall SetCodingTable(AnsiString NewTable);
void __fastcall SetPrivilege(int Priv);
__property int Privilege = {read=FPrivilege, write=SetPrivilege, nodefault};
__property bool TableNeeded = {read=FTableNeeded, write=FTableNeeded, nodefault};
};
class DELPHICLASS TIdUUDecoder;
typedef TIdUUDecoder* *PIdUUDecoder;
class PASCALIMPLEMENTATION TIdUUDecoder : public TId3To4Coder
{
typedef TId3To4Coder inherited;
protected:
bool FError;
bool FCompleted;
Classes::TStringList* FErrList;
int FState;
int FRealBufferSize;
bool FIsFirstRound;
int FPrivilege;
virtual void __fastcall Coder(void);
virtual void __fastcall CompleteCoding(void);
virtual void __fastcall CheckForHeader(int DataSize);
public:
__fastcall virtual TIdUUDecoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdUUDecoder(void);
virtual void __fastcall SetCodingTable(AnsiString NewTable);
void __fastcall SetPrivilege(int Priv);
__property int Privilege = {read=FPrivilege, write=SetPrivilege, nodefault};
};
class DELPHICLASS TIdXXEncoder;
typedef TIdXXEncoder* *PIdXXEncoder;
class PASCALIMPLEMENTATION TIdXXEncoder : public TIdUUEncoder
{
typedef TIdUUEncoder inherited;
public:
__fastcall virtual TIdXXEncoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdXXEncoder(void);
};
class DELPHICLASS TIdXXDecoder;
typedef TIdXXDecoder* *PIdXXDecoder;
class PASCALIMPLEMENTATION TIdXXDecoder : public TIdUUDecoder
{
typedef TIdUUDecoder inherited;
public:
__fastcall virtual TIdXXDecoder(Classes::TComponent* AOwner);
__fastcall virtual ~TIdXXDecoder(void);
};
class DELPHICLASS EIdTableNotFound;
class PASCALIMPLEMENTATION EIdTableNotFound : public Idexception::EIdException
{
typedef Idexception::EIdException inherited;
public:
#pragma option push -w-inl
/* Exception.Create */ inline __fastcall EIdTableNotFound(const AnsiString Msg) : Idexception::EIdException(Msg) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIdTableNotFound(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Idexception::EIdException(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIdTableNotFound(int Ident)/* overload */ : Idexception::EIdException(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIdTableNotFound(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Idexception::EIdException(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIdTableNotFound(const AnsiString Msg, int AHelpContext) : Idexception::EIdException(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIdTableNotFound(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Idexception::EIdException(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIdTableNotFound(int Ident, int AHelpContext)/* overload */ : Idexception::EIdException(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIdTableNotFound(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Idexception::EIdException(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIdTableNotFound(void) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
static const Shortint CTL3To4 = 0x40;
static const Shortint HalfCodeTable = 0x20;
extern PACKAGE AnsiString Base64CodeTable;
extern PACKAGE AnsiString UUCodeTable;
extern PACKAGE AnsiString XXCodeTable;
#define UUTable "TABLE"
#define UUBegin "BEGIN "
#define UUEnd "END"
static const Word minPriv = 0x258;
static const Word maxPriv = 0x31f;
static const Shortint UUStarted = 0x0;
static const Shortint UUTableBegun = 0x1;
static const Shortint UUTableOneLine = 0x2;
static const Shortint UUTableBeenRead = 0x3;
static const Shortint UUDataStarted = 0x4;
static const Shortint UUBEGINFound = 0x5;
static const Shortint UUPrivilegeFound = 0x6;
static const Shortint UUInitialLength = 0x8;
static const Shortint UULastCharFound = 0x9;
static const Shortint UUENDFound = 0xa;
static const bool UUErrTableNotAtEnd = false;
#define UUErrIncompletePrivilege "Not enough chars for three-digit Privilege"
#define UUErrIncompletePrivilege2 "Too many chars for three-digit Privilege"
#define UUErrorPivilageNotNumeric "Privilege chars not numeric"
#define UUErrorNoBEGINAfterTABLE "No BEGIN statement followed a TABLE"
#define UUErrorDataEndWithoutEND " Data ended without an END statment"
extern PACKAGE AnsiString __fastcall Base64Encode(const AnsiString s);
} /* namespace Idcoder3to4 */
using namespace Idcoder3to4;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // IdCoder3To4
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
276
]
]
] |
75d35ddb2d36c90b2f2646ec37b3b170b6c13990 | aaf23f851e5c0ae43eb60c2d1a9f05462d7b964c | /src/huawei_a1/src/interface.hpp | 961c8fcae3044c3eb4e37444c973008f172154bf | [] | no_license | ismailwissam/bill-parser | 28ccb68857cb7d6be04207534e7250da82b5c55f | 5e195d606fcbbb1f69cbe148dde2413450d381fb | refs/heads/master | 2021-01-10T10:25:20.175318 | 2010-09-20T02:20:37 | 2010-09-20T02:20:37 | 50,747,248 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,560 | hpp | #ifndef MODULE_INTERFACE_HPP
#define MODULE_INTERFACE_HPP
#include <memory>
extern "C"
{
/*!
* 多线程版本的初始化、释放
*/
int InitMT();
void UninitMT(int handle);
/*!
* 返回话单类型
*/
const char* GetTypeName(int type_idx);
/*!
* 返回话单类型的每项字段类型
*/
const char* GetItemName(int type_idx, int item_idx);
/********************************************************************
* *
* 一下函数中 *MT为多线程版本,比单线程版本第一个参数多了句柄参数 *
* *
********************************************************************/
/*!
* 解析话单入口(不允许同时解析两个话单文件)
*/
bool ParseFile(const char* file_name);
bool ParseFileMT(int handle, const char* file_name);
/*!
* 获取下一条话单内容
*/
bool FetchNextBill();
bool FetchNextBillMT(int handle);
/*!
* 当前解析出的话单类型
*/
int CurBillType();
int CurBillTypeMT(int handle);
/*!
* 当前解析出的话单名称
*/
const char* CurBillName();
const char* CurBillNameMT(int handle);
/*!
* 获得话单某项内容
*/
const char* GetItemData(const char* item_name);
const char* GetItemDataMT(int handle, const char* item_name);
/*
* 主解析函数
*/
int huawei_a1(char * in_file_name, char * out_file_name, int * rec_num);
}
#endif //MODULE_INTERFACE_HPP
| [
"ewangplay@81b94f52-7618-9c36-a7be-76e94dd6e0e6"
] | [
[
[
1,
70
]
]
] |
c4c17575af41129e3be199cbb272d01e8b86e054 | 9b781f66110d82c4918feffeeee3740d6b9dcc73 | /Motion Graphs/Graph.cpp | da9a07cc84d6a544f3988301ef2a3f7bc3eb6fdc | [] | no_license | vanish87/Motion-Graphs | 3c41cbb4ae838e2dce1172a56dfa00b8fe8f12cf | 6eab48f3625747d838f2f8221705a1dba154d8ca | refs/heads/master | 2021-01-23T05:34:56.297154 | 2011-06-10T09:53:15 | 2011-06-10T09:53:15 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 16,026 | cpp | #include "stdafx.h"
#include "Graph.h"
/*
* Contructors and Destructors
*/
Graph::Graph(){
this->entity = NULL;
this->indexes = NULL;
this->nNodes = 0;
}
Graph::Graph(Ogre::Entity *e){
this->entity = e;
this->indexes = NULL;
this->nNodes = 0;
}
Graph::~Graph(){
}
/*
* Methods
*/
/**
* Adiciona o novo nodo ao grafo e atribui-lhe um ID (incremental)
*/
int Graph::addNode(gNode *node){
node->setID(this->nNodes);
this->nodes.push_back(node);
this->nNodes++;
return node->getID();
}
/**
* Verifica se aquele nodo já está introduzido no grafo
* @return NULL caso não exista ou retorna o próprio nodo
*
gNode* Graph::existNode(gNode *node){
for(int i = 0 ; i < this->nNodes ; i++){
if(node->getID() == this->nodes[i].getID()) return this->getNode(i);
}
return NULL;
}
/**
* retorna o nodo na posicao pretendida ou nulo caso essa posicao nao exista
*/
gNode *Graph::getNode(int node){
if(node >= this->nNodes || node < 0) return NULL;
else return this->nodes.at(node);
}
void Graph::constructGraph(Ninja motions, int nMotions, float threshold, int nCoincidents){
if(nMotions == 0) return;
this->initIndexes(motions,nMotions);
sNinja::iterator it;
int i,j,nRelations = 0;
for(it = motions->begin() , i = 0 ; it != motions->end() ; it++, i++){
gNode *n1 = new gNode();
gNode *n2 = new gNode();
Edge *e = new Edge(n2,it->first);
n1->addEdge(e);
int lastPos = it->second->getNPointClouds()-1;
this->indexes[i][0] = this->addNode(n1);
this->indexes[i][lastPos] = this->addNode(n2);
}
this->map = new dMap(nMotions);
this->map->setNSteps(nCoincidents);
this->map->setThreshold(threshold);
this->map->constructMap(motions, nMotions);
for(i = 0 ; i < this->map->getNRelations() ; i++){
std::string m1 = *this->map->relations[i][0];
std::string m2 = *this->map->relations[i][1];
int index1 = -1, index2 = -1;
for(it = motions->begin(), j = 0 ; it != motions->end() ; it++, j++){
if(it->first.compare(m1) == 0) index1 = j;
if(it->first.compare(m2) == 0) index2 = j;
}
if(index1 != -1 && index2 != -1){
std::vector<int> min1,min2;
nRelations = this->map->getMinimuns(i,&min1,&min2);
for(j = 0 ; j < nRelations ; j++){
if(this->indexes[i][min1[j]] < 0 || this->indexes[i][min1[j]] > this->nNodes){
gNode *n = new gNode();
this->indexes[i][min1[j]] = this->addNode(n);
}
if(this->indexes[i][min2[j]] < 0 || this->indexes[i][min2[j]] > this->nNodes){
gNode *n = new gNode();
this->indexes[i][min2[j]] = this->addNode(n);
}
this->createTransition(m1,this->indexes[i][min1[j]],min1[j],m2,this->indexes[i][min2[j]],min2[j],
j,this->map->getNSteps(),motions->at(m1)->getNPointClouds(),motions->at(m2)->getNPointClouds());
}
}
}
int k;
FILE *f;
if((f = fopen("indexes.txt","w")) == NULL) return;
for(it = motions->begin(), i = 0 ; it != motions->end() ; it++, i++){
int sep = 1;
for(j = 0 ; j < it->second->getNPointClouds() ; j++){
fprintf(f,"%d, ",this->indexes[i][j]);
if(this->indexes[i][j] != -1){
bool done = false;
for(k = j + 1 ; k < it->second->getNPointClouds() && !done ; k++){
if(this->indexes[i][k] != -1){
this->splitAnimation(it->first,sep,this->indexes[i][j],j,this->indexes[i][k],k,it->second->getNPointClouds());
sep++;
done = true;
}
}
}
}
fprintf(f,"\n");
}
fclose(f);
}
void Graph::createAnimation(std::string newName, std::string originaAnimation,
int frame1, int frame2, int totalFrames){
Ogre::Animation *animation = this->entity->getSkeleton()->getAnimation(originaAnimation);
float length = animation->getLength();
float tInit = ((float)((float)frame1 * length)) / ((float)totalFrames);
float tEnd = ((float)((float)frame2 * length)) / ((float)totalFrames);
float newDuration = tEnd - tInit;
float timeStep = newDuration / ((float)(frame2 - frame1));
Ogre::Animation *newAnimation = this->entity->getSkeleton()->createAnimation(newName,newDuration);
Ogre::Animation::NodeTrackIterator trackIterator = animation->getNodeTrackIterator();
while(trackIterator.hasMoreElements()){
Ogre::NodeAnimationTrack* track = trackIterator.getNext();
Ogre::NodeAnimationTrack* newTrack = newAnimation->createNodeTrack(track->getHandle(), track->getAssociatedNode());
short numFrames = frame2 - frame1;
for(float keyFrameTime = 0.0; keyFrameTime < newDuration; keyFrameTime += timeStep){
Ogre::TransformKeyFrame* transformedKFrame = track->createNodeKeyFrame(keyFrameTime);
track->getInterpolatedKeyFrame(keyFrameTime,transformedKFrame);
Ogre::Real newTime = newDuration - (transformedKFrame->getTime() - tInit);
Ogre::TransformKeyFrame* newKFrame = newTrack->createNodeKeyFrame(newTime);
newKFrame->setScale(transformedKFrame->getScale());
newKFrame->setRotation(transformedKFrame->getRotation());
newKFrame->setTranslate(transformedKFrame->getTranslate());
}
}
}
/**
* Frame1 < Frame2
*/
void Graph::splitAnimation(std::string name, int separation,
int node1, int frame1,
int node2, int frame2, int totalFrames){
std::stringstream ss;
ss << name << "_" << separation;
std::string label = ss.str();
this->getNode(node1)->addEdge(new Edge(this->getNode(node2),label));
this->createAnimation(label,name,frame1,frame2,totalFrames);
}
/*
e1 e3 e4
1-------------->2 1----->5------->2
----> \ e7
\
3-------------->4 3-------->6---->4
e2 e5 e6
*/
void Graph::createTransition(std::string m1, int node1, int frame1,
std::string m2, int node2, int frame2,
int transiction,int range, int totalFrames1, int totalFrames2){
std::stringstream ss;
ss << m1 << "_" ;
ss << m2 << "_" << transiction;
std::string newName = ss.str();
this->getNode(node1)->addEdge(new Edge(this->getNode(node2),newName));
this->createAnimation("aux_blend_animation_1",m1,frame1,frame1 + range,totalFrames1);
this->createAnimation("aux_blend_animation_2",m2,frame2 - range,frame2,totalFrames2);
Ogre::Animation *animation1 = this->entity->getSkeleton()->getAnimation("aux_blend_animation_1");
Ogre::Animation *animation2 = this->entity->getSkeleton()->getAnimation("aux_blend_animation_2");
float length = (animation1->getLength() > animation2->getLength()) ? animation2->getLength() : animation1->getLength();
float timeStep = length / ((float)(range));
Ogre::Animation *newAnimation = this->entity->getSkeleton()->createAnimation(newName,length);
Ogre::Animation::NodeTrackIterator trackIterator1 = animation1->getNodeTrackIterator();
Ogre::Animation::NodeTrackIterator trackIterator2 = animation2->getNodeTrackIterator();
while(trackIterator1.hasMoreElements() && trackIterator2.hasMoreElements()){
Ogre::NodeAnimationTrack* track1 = trackIterator1.getNext();
Ogre::NodeAnimationTrack* track2 = trackIterator2.getNext();
//DUBIDAS Handle e AssociatedNode de quem? 1 ou 2?
Ogre::NodeAnimationTrack* newTrack = newAnimation->createNodeTrack(track1->getHandle(), track1->getAssociatedNode());
float weight = 1.0;
int i = 0;
for(float keyFrameTime = 0.0; keyFrameTime < length; keyFrameTime += timeStep , weight -= (float)(1.0/(float)range)){
Ogre::TransformKeyFrame* keyFrame1 = track1->createNodeKeyFrame(keyFrameTime);
Ogre::TransformKeyFrame* keyFrame2 = track2->createNodeKeyFrame(keyFrameTime);
track1->getInterpolatedKeyFrame(keyFrameTime,keyFrame1);
track2->getInterpolatedKeyFrame(keyFrameTime,keyFrame2);
//Ogre::NodeAnimationTrack* auxTrack = newAnimation->createNodeTrack(track1->getHandle() + 1 , track1->getAssociatedNode());
//Ogre::TransformKeyFrame* newKFrame1 = auxTrack->createNodeKeyFrame(0.0);
//Ogre::TransformKeyFrame* newKFrame2 = auxTrack->createNodeKeyFrame(1.0);
//newKFrame1->setScale(keyFrame1->getScale());
//newKFrame1->setRotation(keyFrame1->getRotation());
//newKFrame1->setTranslate(keyFrame1->getTranslate());
////FALTA APLICAR TRANSLACAO
//newKFrame2->setScale(keyFrame2->getScale());
//newKFrame2->setRotation(keyFrame2->getRotation());
//newKFrame2->setTranslate(keyFrame2->getTranslate());
Ogre::Real newTime = length - keyFrameTime;
//Ogre::TransformKeyFrame* keyFrameInt = track1->createNodeKeyFrame(newTime);
//auxTrack->getInterpolatedKeyFrame(weight,keyFrameInt);
Ogre::TransformKeyFrame* newKFrame = newTrack->createNodeKeyFrame(newTime);
newKFrame->setScale(keyFrame1->getScale());
PointCloud *p1 = this->map->motions->at(m1)->getPointCloud(frame1);
PointCloud *p2 = this->map->motions->at(m1)->getPointCloud(frame1);
float x = 0 , y = 0 , teta = 0;
this->map->calculateTransformation(p1,p2,&teta,&x,&y);
float alpha = 2.0 * powf(((float)(i+1)/(float)(frame2-frame1)),3) - 3.0* powf(((float)(i+1)/(float)(frame2-frame1)),2) + 1.0;
i++;
Ogre::Quaternion rotation1 = keyFrame1->getRotation();
Ogre::Quaternion rotation2 = keyFrame2->getRotation();
Ogre::Quaternion rotation = Ogre::Quaternion::Slerp(alpha,rotation1,rotation2);
Ogre::Vector3 translation = keyFrame1->getTranslate();
translation.x += x;
translation.y += y;
newKFrame->setRotation(rotation);
newKFrame->setTranslate(translation);
//track1->removeAllKeyFrames();
//newAnimation->destroyNodeTrack(track1->getHandle() + 1);
}
}
this->entity->getSkeleton()->removeAnimation("aux_blend_animation_1");
this->entity->getSkeleton()->removeAnimation("aux_blend_animation_2");
//get animations to start blending
//Ogre::Animation *animation1_ptr = this->entity->getSkeleton()->getAnimation(m1);
//Ogre::Animation *animation2_ptr = this->entity->getSkeleton()->getAnimation(m2);
////apply 2D transformation to second motion (is this the best way to do it?)
////no... but its the only one we got (NOT DONE)
//Ogre::Animation * animation2_trans2d = animation2_ptr->clone(m2);
//
//for(int i=0;i < animation2_ptr->getNumNodeTracks(); i++)
//{
// for(int j = 0; j <= animation2_ptr->getNodeTrack(i)->getNumKeyFrames(); j++)
// {
// //get point clouds from original animation in the key frame
// PointCloud * p1 = new PointCloud();
// PointCloud * p2 = new PointCloud();
// //TODO: animation2_ptr->getNodeTrack(i)->getnode
// }
//}
////create a new raw animation
//Ogre::Animation *newAnimation = animation1_ptr->clone(newName); //use m1 or m2 i guess
//newAnimation->destroyAllTracks();
////blend anim1 with anim2_trans2d and output the result to newAnimation
////should we be careful about the animation times ?
//for(int i=0;i < animation1_ptr->getNumNodeTracks(); i++)
//{
// newAnimation->createNodeTrack(i,animation1_ptr->getNodeTrack(i)->getAssociatedNode());
// //iterate through each keyframe in animation1 and blend it with animation2
// for(int j = frame1, aux = 0; j <= frame2; j++, aux++)
// {
// //create new nodetrack in new animation
// animation1_ptr->getNodeTrack(i)->createNodeKeyFrame(
// animation1_ptr->getNodeTrack(i)->getNodeKeyFrame(j)->getTime() -
// animation1_ptr->getNodeTrack(i)->getNodeKeyFrame(frame1)->getTime());
// //get rotations and slerp them to new animatons
// Ogre::Quaternion quat1 = animation1_ptr->getNodeTrack(i)->getNodeKeyFrame(j)->getRotation();
// Ogre::Quaternion quat2 = animation2_trans2d->getNodeTrack(i)->getNodeKeyFrame(j)->getRotation();
// float alpha = 2 * powf(((i+1)/(frame2-frame1)),3) - 3* powf(((i+1)/(frame2-frame1)),2) + 1;
// newAnimation->getNodeTrack(i)->getNodeKeyFrame(aux)->setRotation(Ogre::Quaternion::Slerp(alpha,quat1,quat2)); //what is this first value? weight? alpha?
// //get root position and interpolate it linearly
// float ix,iy,iz; // where is root ?!?! need to find it...
// int root = 0;
// Ogre::Vector3 vec1 = animation1_ptr->getNodeTrack(root)->createNodeKeyFrame(j)->getTranslate();
// Ogre::Vector3 vec2 = animation2_trans2d->getNodeTrack(root)->createNodeKeyFrame(j)->getTranslate();
// ix = vec1.x + (j/(frame2-frame1)) *(vec2.x - vec1.x);
// iy = vec1.y + (j/(frame2-frame1)) *(vec2.y - vec1.y);
// iz = vec1.z + (j/(frame2-frame1)) *(vec2.z - vec1.z);
// newAnimation->getNodeTrack(root)->getNodeKeyFrame(j)->setTranslate(Ogre::Vector3(ix,iy,iz));
// }
//}
////TODO criar animação com o newName entre frame1 de m1 e frame2 de m2
///*
//true,this->motionGraph->getMotion(
//&motions->at(map.relations[i][0]),&motions->at(map.relations[i][0]),
//pts1[j],pts2[j]-nCoincidents,pts1[j] + nCoincidents,pts2[j])));
//*/
}
void Graph::initIndexes(Ninja motions, int nMotions){
int maxFrames = -1;
sNinja::iterator it;
for(it = motions->begin() ; it != motions->end() ; it++){
if(it->second->getNPointClouds() > maxFrames)
maxFrames = it->second->getNPointClouds();
}
maxFrames *= 1.5;
this->indexes = (int**)malloc(sizeof(int*) * nMotions);
for(int i = 0 ; i < nMotions ; i++){
this->indexes[i] = (int*)malloc(sizeof(int) * maxFrames);
}
for(int i = 0 ; i < nMotions ; i++){
for(int j = 0 ; j < maxFrames ; j++){
this->indexes[i][j] = -1;
}
}
}
void Graph::printGraph(char *path){
FILE *fp = NULL;
FILE *fp2 = NULL;
Edge* eAux;
gNode* gAux;
if((fp = fopen(path,"w")) == NULL) return ;
if((fp2 = fopen("cenas.txt","w")) == NULL) return ;
fprintf(fp,"digraph G {\n");
fprintf(fp,"subgraph cluster0{\n");
fprintf(fp,"style=filled;\n");
fprintf(fp,"color= red;\n");
fprintf(fp,"node [ fillcolor =white color = black style=filled shape = hexagon] ; \n");
int ac = 0;
for(int i = 0 ; i < this->nNodes ; i++){
ac += this->getNode(i)->getNEdges();
}
fprintf(fp2,"%d\n%d\n",this->nNodes,ac);
for(int i = 0 ; i < this->nNodes ; i++){
gAux = this->getNode(i);
if(gAux){
for(int j = 0 ; j < gAux->getNEdges() ; j++){
eAux = gAux->getEdge(j);
if(eAux){
int id = gAux->getID();
int idDest = 0;
gNode *gDest = eAux->getDestionation();
std::string anim = eAux->getLabel();
const char *name = NULL;
if(id < 0){
id = -101010101;
}
if(!gDest){
idDest = -101010101;
}
else{
try{
idDest = gDest->getID();
}
catch (exception &e){
idDest = -1;
}
if(idDest < 0){
idDest = -101010101;
}
}
if(anim.size() > 0){
name = anim.data();
}
else name = "NONAMENONAMENONAMENONAME";
fprintf(fp2,"%d %d\n",gAux->getID(),gDest->getID());
fprintf(fp,"\t\"%d\" -> \"%d\" [label = \"%s\"];\n",id,idDest,name);
//gAux->getID(),
//(eAux->getDestionation()) ? eAux->getDestionation()->getID() : -10101010101,
//eAux->getLabel().data());
//this->nodes[i].getID(),
//this->nodes[i].getEdge(j)->getDestionation()->getID(),
//this->nodes[i].getEdge(j)->getLabel().data());
}
}
}
}
fprintf(fp,"}}\n");
fclose(fp);
fclose(fp2);
}
bool Graph::removeNode(int i)
{
nodes.erase( nodes.begin() + i);
nNodes--;
return true;
}
bool Graph::changeNode(int i, gNode *node)
{
nodes[i] = node;
return true;
} | [
"onumis@6a9b4378-2129-4827-95b0-0a0a1e71ef92",
"mariojgpinto@6a9b4378-2129-4827-95b0-0a0a1e71ef92",
"necrolife@6a9b4378-2129-4827-95b0-0a0a1e71ef92"
] | [
[
[
1,
1
]
],
[
[
2,
142
],
[
145,
147
],
[
149,
155
],
[
157,
157
],
[
159,
159
],
[
161,
162
],
[
164,
164
],
[
166,
166
],
[
168,
175
],
[
177,
179
],
[
181,
181
],
[
184,
194
],
[
196,
196
],
[
198,
198
],
[
201,
301
],
[
303,
305
],
[
307,
309
],
[
311,
321
],
[
323,
324
],
[
326,
326
],
[
328,
330
],
[
332,
333
],
[
335,
337
],
[
339,
345
],
[
347,
349
],
[
351,
352
],
[
354,
356
],
[
358,
359
],
[
361,
363
],
[
365,
365
],
[
367,
368
],
[
371,
376
],
[
379,
380
],
[
382,
490
]
],
[
[
143,
144
],
[
148,
148
],
[
156,
156
],
[
158,
158
],
[
160,
160
],
[
163,
163
],
[
165,
165
],
[
167,
167
],
[
176,
176
],
[
180,
180
],
[
182,
183
],
[
195,
195
],
[
197,
197
],
[
199,
200
],
[
302,
302
],
[
306,
306
],
[
310,
310
],
[
322,
322
],
[
325,
325
],
[
327,
327
],
[
331,
331
],
[
334,
334
],
[
338,
338
],
[
346,
346
],
[
350,
350
],
[
353,
353
],
[
357,
357
],
[
360,
360
],
[
364,
364
],
[
366,
366
],
[
369,
370
],
[
377,
378
],
[
381,
381
]
]
] |
65103a3fed23777ba9da4bd99a834f58924b5120 | 639935f06898b0b93582e2809410230d3ef1469a | /src/ofxCLD/src/ETF.cpp | 77488ee49d2fa368edc14f36a694c268241dadad | [] | no_license | mikebaumgart/GAmuza | ef757bee511f8018396daeb618f1b24e436c9256 | 6388f66b8878c443d4c1e744d4f0ae8abfb91524 | refs/heads/master | 2021-05-26T13:26:48.893273 | 2011-12-22T23:10:30 | 2011-12-22T23:10:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,730 | cpp | #include "ETF.h"
#include "imatrix.h"
void ETF::set(imatrix& image)
{
int i, j;
double MAX_VAL = 1020.;
double v[2];
max_grad = -1.;
for (i = 1; i < Nr - 1; i++) {
for (j = 1; j < Nc - 1; j++) {
////////////////////////////////////////////////////////////////
p[i][j].tx = (image[i+1][j-1] + 2*(double)image[i+1][j] + image[i+1][j+1]
- image[i-1][j-1] - 2*(double)image[i-1][j] - image[i-1][j+1]) / MAX_VAL;
p[i][j].ty = (image[i-1][j+1] + 2*(double)image[i][j+1] + image[i+1][j+1]
- image[i-1][j-1] - 2*(double)image[i][j-1] - image[i+1][j-1]) / MAX_VAL;
/////////////////////////////////////////////
v[0] = p[i][j].tx;
v[1] = p[i][j].ty;
p[i][j].tx = -v[1];
p[i][j].ty = v[0];
//////////////////////////////////////////////
p[i][j].mag = sqrt(p[i][j].tx * p[i][j].tx + p[i][j].ty * p[i][j].ty);
if (p[i][j].mag > max_grad) {
max_grad = p[i][j].mag;
}
}
}
for (i = 1; i <= Nr - 2; i++) {
p[i][0].tx = p[i][1].tx;
p[i][0].ty = p[i][1].ty;
p[i][0].mag = p[i][1].mag;
p[i][Nc - 1].tx = p[i][Nc - 2].tx;
p[i][Nc - 1].ty = p[i][Nc - 2].ty;
p[i][Nc - 1].mag = p[i][Nc - 2].mag;
}
for (j = 1; j <= Nc - 2; j++) {
p[0][j].tx = p[1][j].tx;
p[0][j].ty = p[1][j].ty;
p[0][j].mag = p[1][j].mag;
p[Nr - 1][j].tx = p[Nr - 2][j].tx;
p[Nr - 1][j].ty = p[Nr - 2][j].ty;
p[Nr - 1][j].mag = p[Nr - 2][j].mag;
}
p[0][0].tx = ( p[0][1].tx + p[1][0].tx ) / 2;
p[0][0].ty = ( p[0][1].ty + p[1][0].ty ) / 2;
p[0][0].mag = ( p[0][1].mag + p[1][0].mag ) / 2;
p[0][Nc-1].tx = ( p[0][Nc-2].tx + p[1][Nc-1].tx ) / 2;
p[0][Nc-1].ty = ( p[0][Nc-2].ty + p[1][Nc-1].ty ) / 2;
p[0][Nc-1].mag = ( p[0][Nc-2].mag + p[1][Nc-1].mag ) / 2;
p[Nr-1][0].tx = ( p[Nr-1][1].tx + p[Nr-2][0].tx ) / 2;
p[Nr-1][0].ty = ( p[Nr-1][1].ty + p[Nr-2][0].ty ) / 2;
p[Nr-1][0].mag = ( p[Nr-1][1].mag + p[Nr-2][0].mag ) / 2;
p[Nr - 1][Nc - 1].tx = ( p[Nr - 1][Nc - 2].tx + p[Nr - 2][Nc - 1].tx ) / 2;
p[Nr - 1][Nc - 1].ty = ( p[Nr - 1][Nc - 2].ty + p[Nr - 2][Nc - 1].ty ) / 2;
p[Nr - 1][Nc - 1].mag = ( p[Nr - 1][Nc - 2].mag + p[Nr - 2][Nc - 1].mag ) / 2;
normalize();
}
void ETF::set2(imatrix& image)
{
int i, j;
double MAX_VAL = 1020.;
double v[2];
max_grad = -1.;
imatrix tmp(Nr, Nc);
for (i = 1; i < Nr - 1; i++) {
for (j = 1; j < Nc - 1; j++) {
////////////////////////////////////////////////////////////////
p[i][j].tx = (image[i+1][j-1] + 2*(double)image[i+1][j] + image[i+1][j+1]
- image[i-1][j-1] - 2*(double)image[i-1][j] - image[i-1][j+1]) / MAX_VAL;
p[i][j].ty = (image[i-1][j+1] + 2*(double)image[i][j+1] + image[i+1][j+1]
- image[i-1][j-1] - 2*(double)image[i][j-1] - image[i+1][j-1]) / MAX_VAL;
/////////////////////////////////////////////
v[0] = p[i][j].tx;
v[1] = p[i][j].ty;
//////////////////////////////////////////////
tmp[i][j] = sqrt(p[i][j].tx * p[i][j].tx + p[i][j].ty * p[i][j].ty);
if (tmp[i][j] > max_grad) {
max_grad = tmp[i][j];
}
}
}
for (i = 1; i <= Nr - 2; i++) {
tmp[i][0] = tmp[i][1];
tmp[i][Nc - 1] = tmp[i][Nc - 2];
}
for (j = 1; j <= Nc - 2; j++) {
tmp[0][j] = tmp[1][j];
tmp[Nr - 1][j] = tmp[Nr - 2][j];
}
tmp[0][0] = ( tmp[0][1] + tmp[1][0] ) / 2;
tmp[0][Nc-1] = ( tmp[0][Nc-2] + tmp[1][Nc-1] ) / 2;
tmp[Nr-1][0] = ( tmp[Nr-1][1] + tmp[Nr-2][0] ) / 2;
tmp[Nr - 1][Nc - 1] = ( tmp[Nr - 1][Nc - 2] + tmp[Nr - 2][Nc - 1] ) / 2;
imatrix gmag(Nr, Nc);
// normalize the magnitude
for (i = 0; i < Nr; i++) {
for (j = 0; j < Nc; j++) {
tmp[i][j] /= max_grad;
gmag[i][j] = round(tmp[i][j] * 255.0);
}
}
for (i = 1; i < Nr - 1; i++) {
for (j = 1; j < Nc - 1; j++) {
////////////////////////////////////////////////////////////////
p[i][j].tx = (gmag[i+1][j-1] + 2*(double)gmag[i+1][j] + gmag[i+1][j+1]
- gmag[i-1][j-1] - 2*(double)gmag[i-1][j] - gmag[i-1][j+1]) / MAX_VAL;
p[i][j].ty = (gmag[i-1][j+1] + 2*(double)gmag[i][j+1] + gmag[i+1][j+1]
- gmag[i-1][j-1] - 2*(double)gmag[i][j-1] - gmag[i+1][j-1]) / MAX_VAL;
/////////////////////////////////////////////
v[0] = p[i][j].tx;
v[1] = p[i][j].ty;
p[i][j].tx = -v[1];
p[i][j].ty = v[0];
//////////////////////////////////////////////
p[i][j].mag = sqrt(p[i][j].tx * p[i][j].tx + p[i][j].ty * p[i][j].ty);
if (p[i][j].mag > max_grad) {
max_grad = p[i][j].mag;
}
}
}
for (i = 1; i <= Nr - 2; i++) {
p[i][0].tx = p[i][1].tx;
p[i][0].ty = p[i][1].ty;
p[i][0].mag = p[i][1].mag;
p[i][Nc - 1].tx = p[i][Nc - 2].tx;
p[i][Nc - 1].ty = p[i][Nc - 2].ty;
p[i][Nc - 1].mag = p[i][Nc - 2].mag;
}
for (j = 1; j <= Nc - 2; j++) {
p[0][j].tx = p[1][j].tx;
p[0][j].ty = p[1][j].ty;
p[0][j].mag = p[1][j].mag;
p[Nr - 1][j].tx = p[Nr - 2][j].tx;
p[Nr - 1][j].ty = p[Nr - 2][j].ty;
p[Nr - 1][j].mag = p[Nr - 2][j].mag;
}
p[0][0].tx = ( p[0][1].tx + p[1][0].tx ) / 2;
p[0][0].ty = ( p[0][1].ty + p[1][0].ty ) / 2;
p[0][0].mag = ( p[0][1].mag + p[1][0].mag ) / 2;
p[0][Nc-1].tx = ( p[0][Nc-2].tx + p[1][Nc-1].tx ) / 2;
p[0][Nc-1].ty = ( p[0][Nc-2].ty + p[1][Nc-1].ty ) / 2;
p[0][Nc-1].mag = ( p[0][Nc-2].mag + p[1][Nc-1].mag ) / 2;
p[Nr-1][0].tx = ( p[Nr-1][1].tx + p[Nr-2][0].tx ) / 2;
p[Nr-1][0].ty = ( p[Nr-1][1].ty + p[Nr-2][0].ty ) / 2;
p[Nr-1][0].mag = ( p[Nr-1][1].mag + p[Nr-2][0].mag ) / 2;
p[Nr - 1][Nc - 1].tx = ( p[Nr - 1][Nc - 2].tx + p[Nr - 2][Nc - 1].tx ) / 2;
p[Nr - 1][Nc - 1].ty = ( p[Nr - 1][Nc - 2].ty + p[Nr - 2][Nc - 1].ty ) / 2;
p[Nr - 1][Nc - 1].mag = ( p[Nr - 1][Nc - 2].mag + p[Nr - 2][Nc - 1].mag ) / 2;
normalize();
}
inline void make_unit(double& vx, double& vy)
{
double mag = sqrt( vx*vx + vy*vy );
if (mag != 0.0) {
vx /= mag;
vy /= mag;
}
}
void ETF::normalize()
{
int i, j;
for (i = 0; i < Nr; i++) {
for (j = 0; j < Nc; j++) {
make_unit(p[i][j].tx, p[i][j].ty);
p[i][j].mag /= max_grad;
}
}
}
void ETF::Smooth(int half_w, int M)
{
int i, j, k;
int MAX_GRADIENT = -1;
double weight;
int s, t;
int x, y;
double mag_diff;
int image_x = getRow();
int image_y = getCol();
ETF e2;
e2.init(image_x, image_y);
e2.copy(*this);
double v[2], w[2], g[2];
double angle;
double factor;
for (k = 0; k < M; k++) {
////////////////////////
// horizontal
for (j = 0; j < image_y; j++) {
for (i = 0; i < image_x; i++) {
g[0] = g[1] = 0.0;
v[0] = p[i][j].tx;
v[1] = p[i][j].ty;
for (s = -half_w; s <= half_w; s++) {
////////////////////////////////////////
x = i+s; y = j;
if (x > image_x-1) x = image_x-1;
else if (x < 0) x = 0;
if (y > image_y-1) y = image_y-1;
else if (y < 0) y = 0;
////////////////////////////////////////
mag_diff = p[x][y].mag - p[i][j].mag;
//////////////////////////////////////////////////////
w[0] = p[x][y].tx;
w[1] = p[x][y].ty;
////////////////////////////////
factor = 1.0;
angle = v[0] * w[0] + v[1] * w[1];
if (angle < 0.0) {
factor = -1.0;
}
weight = mag_diff + 1;
//////////////////////////////////////////////////////
g[0] += weight * p[x][y].tx * factor;
g[1] += weight * p[x][y].ty * factor;
}
make_unit(g[0], g[1]);
e2[i][j].tx = g[0];
e2[i][j].ty = g[1];
}
}
this->copy(e2);
/////////////////////////////////
// vertical
for (j = 0; j < image_y; j++) {
for (i = 0; i < image_x; i++) {
g[0] = g[1] = 0.0;
v[0] = p[i][j].tx;
v[1] = p[i][j].ty;
for (t = -half_w; t <= half_w; t++) {
////////////////////////////////////////
x = i; y = j+t;
if (x > image_x-1) x = image_x-1;
else if (x < 0) x = 0;
if (y > image_y-1) y = image_y-1;
else if (y < 0) y = 0;
////////////////////////////////////////
mag_diff = p[x][y].mag - p[i][j].mag;
//////////////////////////////////////////////////////
w[0] = p[x][y].tx;
w[1] = p[x][y].ty;
////////////////////////////////
factor = 1.0;
///////////////////////////////
angle = v[0] * w[0] + v[1] * w[1];
if (angle < 0.0) factor = -1.0;
/////////////////////////////////////////////////////////
weight = mag_diff + 1;
//////////////////////////////////////////////////////
g[0] += weight * p[x][y].tx * factor;
g[1] += weight * p[x][y].ty * factor;
}
make_unit(g[0], g[1]);
e2[i][j].tx = g[0];
e2[i][j].ty = g[1];
}
}
this->copy(e2);
}
////////////////////////////////////////////
}
| [
"[email protected]"
] | [
[
[
1,
296
]
]
] |
2a2f95c51538e83596f7e1193f6771d289aecfca | 816df3b6bae7300b52a1277cb62bf3b0ffe8b3cd | /src/emu/video.h | a25cf07e0c44b65e7d8bd872c12a689af1ad5e7f | [] | no_license | swarzesherz/mame-test | d42295f79aa79044c929c03d95af50f81d640975 | 1fd7634e0571916490897b35773a88acfdbf0072 | refs/heads/master | 2018-12-28T11:16:24.604162 | 2010-08-04T04:32:02 | 2010-08-04T04:32:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,563 | h | /***************************************************************************
video.h
Core MAME video routines.
****************************************************************************
Copyright Aaron Giles
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 'MAME' 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 AARON GILES ''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 AARON GILES BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#pragma once
#ifndef __EMU_H__
#error Dont include this file directly; include emu.h instead.
#endif
#ifndef __VIDEO_H__
#define __VIDEO_H__
//**************************************************************************
// CONSTANTS
//**************************************************************************
// number of levels of frameskipping supported
const int FRAMESKIP_LEVELS = 12;
const int MAX_FRAMESKIP = FRAMESKIP_LEVELS - 2;
// screen types
enum screen_type_enum
{
SCREEN_TYPE_INVALID = 0,
SCREEN_TYPE_RASTER,
SCREEN_TYPE_VECTOR,
SCREEN_TYPE_LCD
};
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// forward references
class render_target;
struct render_texture;
class screen_device;
// callback that is called to notify of a change in the VBLANK state
typedef void (*vblank_state_changed_func)(screen_device &device, void *param, bool vblank_state);
// ======================> screen_device_config
class screen_device_config : public device_config
{
friend class screen_device;
// construction/destruction
screen_device_config(const machine_config &mconfig, const char *tag, const device_config *owner, UINT32 clock);
public:
// allocators
static device_config *static_alloc_device_config(const machine_config &mconfig, const char *tag, const device_config *owner, UINT32 clock);
virtual device_t *alloc_device(running_machine &machine) const;
// configuration readers
screen_type_enum screen_type() const { return m_type; }
int width() const { return m_width; }
int height() const { return m_height; }
const rectangle &visible_area() const { return m_visarea; }
bool oldstyle_vblank_supplied() const { return m_oldstyle_vblank_supplied; }
attoseconds_t refresh() const { return m_refresh; }
attoseconds_t vblank() const { return m_vblank; }
bitmap_format format() const { return m_format; }
float xoffset() const { return m_xoffset; }
float yoffset() const { return m_yoffset; }
float xscale() const { return m_xscale; }
float yscale() const { return m_yscale; }
// indexes to inline data
enum
{
INLINE_TYPE,
INLINE_FORMAT,
INLINE_REFRESH,
INLINE_VBLANK,
INLINE_WIDTH,
INLINE_HEIGHT,
INLINE_VIS_MINX,
INLINE_VIS_MAXX,
INLINE_VIS_MINY,
INLINE_VIS_MAXY,
INLINE_XOFFSET,
INLINE_XSCALE,
INLINE_YOFFSET,
INLINE_YSCALE,
INLINE_OLDVBLANK
};
private:
// device_config overrides
virtual void device_config_complete();
virtual bool device_validity_check(const game_driver &driver) const;
// configuration data
screen_type_enum m_type; // type of screen
int m_width, m_height; // default total width/height (HTOTAL, VTOTAL)
rectangle m_visarea; // default visible area (HBLANK end/start, VBLANK end/start)
bool m_oldstyle_vblank_supplied; // MDRV_SCREEN_VBLANK_TIME macro used
attoseconds_t m_refresh; // default refresh period
attoseconds_t m_vblank; // duration of a VBLANK
bitmap_format m_format; // bitmap format
float m_xoffset, m_yoffset; // default X/Y offsets
float m_xscale, m_yscale; // default X/Y scale factor
};
// ======================> screen_device
class screen_device : public device_t
{
friend class screen_device_config;
friend resource_pool_object<screen_device>::~resource_pool_object();
// construction/destruction
screen_device(running_machine &_machine, const screen_device_config &config);
virtual ~screen_device();
public:
// information getters
const screen_device_config &config() const { return m_config; }
screen_type_enum screen_type() const { return m_config.m_type; }
int width() const { return m_width; }
int height() const { return m_height; }
const rectangle &visible_area() const { return m_visarea; }
bitmap_format format() const { return m_config.m_format; }
// dynamic configuration
void configure(int width, int height, const rectangle &visarea, attoseconds_t frame_period);
void set_visible_area(int min_x, int max_x, int min_y, int max_y);
// beam positioning and state
int vpos() const;
int hpos() const;
bool vblank() const { return attotime_compare(timer_get_time(machine), m_vblank_end_time) < 0; }
bool hblank() const { int curpos = hpos(); return (curpos < m_visarea.min_x || curpos > m_visarea.max_x); }
// timing
attotime time_until_pos(int vpos, int hpos = 0) const;
attotime time_until_vblank_start() const { return time_until_pos(m_visarea.max_y + 1); }
attotime time_until_vblank_end() const;
attotime time_until_update() const { return (machine->config->m_video_attributes & VIDEO_UPDATE_AFTER_VBLANK) ? time_until_vblank_end() : time_until_vblank_start(); }
attotime scan_period() const { return attotime_make(0, m_scantime); }
attotime frame_period() const { return (this == NULL || !started()) ? k_default_frame_period : attotime_make(0, m_frame_period); };
UINT64 frame_number() const { return m_frame_number; }
// updating
bool update_partial(int scanline);
void update_now();
// additional helpers
void save_snapshot(mame_file *fp);
void register_vblank_callback(vblank_state_changed_func vblank_callback, void *param);
bitmap_t *alloc_compatible_bitmap(int width = 0, int height = 0) { return auto_bitmap_alloc(machine, (width == 0) ? m_width : width, (height == 0) ? m_height : height, m_config.m_format); }
// internal to the video system
bool update_quads();
void update_burnin();
// globally accessible constants
static const int k_default_frame_rate = 60;
static const attotime k_default_frame_period;
private:
// device-level overrides
virtual void device_start();
virtual void device_post_load();
// internal helpers
void realloc_screen_bitmaps();
static TIMER_CALLBACK( static_vblank_begin_callback ) { reinterpret_cast<screen_device *>(ptr)->vblank_begin_callback(); }
void vblank_begin_callback();
static TIMER_CALLBACK( static_vblank_end_callback ) { reinterpret_cast<screen_device *>(ptr)->vblank_end_callback(); }
void vblank_end_callback();
static TIMER_CALLBACK( static_scanline0_callback ) { reinterpret_cast<screen_device *>(ptr)->scanline0_callback(); }
public: // temporary
void scanline0_callback();
private:
static TIMER_CALLBACK( static_scanline_update_callback ) { reinterpret_cast<screen_device *>(ptr)->scanline_update_callback(param); }
void scanline_update_callback(int scanline);
void finalize_burnin();
// internal state
const screen_device_config &m_config;
// dimensions
int m_width; // current width (HTOTAL)
int m_height; // current height (VTOTAL)
rectangle m_visarea; // current visible area (HBLANK end/start, VBLANK end/start)
// textures and bitmaps
render_texture * m_texture[2]; // 2x textures for the screen bitmap
bitmap_t * m_bitmap[2]; // 2x bitmaps for rendering
bitmap_t * m_burnin; // burn-in bitmap
UINT8 m_curbitmap; // current bitmap index
UINT8 m_curtexture; // current texture index
INT32 m_texture_format; // texture format of bitmap for this screen
bool m_changed; // has this bitmap changed?
INT32 m_last_partial_scan; // scanline of last partial update
// screen timing
attoseconds_t m_frame_period; // attoseconds per frame
attoseconds_t m_scantime; // attoseconds per scanline
attoseconds_t m_pixeltime; // attoseconds per pixel
attoseconds_t m_vblank_period; // attoseconds per VBLANK period
attotime m_vblank_start_time; // time of last VBLANK start
attotime m_vblank_end_time; // time of last VBLANK end
emu_timer * m_vblank_begin_timer; // timer to signal VBLANK start
emu_timer * m_vblank_end_timer; // timer to signal VBLANK end
emu_timer * m_scanline0_timer; // scanline 0 timer
emu_timer * m_scanline_timer; // scanline timer
UINT64 m_frame_number; // the current frame number
struct callback_item
{
callback_item * m_next;
vblank_state_changed_func m_callback;
void * m_param;
};
callback_item * m_callback_list; // list of VBLANK callbacks
#ifdef USE_SCALE_EFFECTS
public:
// scale effect rendering
void video_init_scale_effect();
void video_exit_scale_effect();
private:
void free_scale_bitmap();
void convert_palette_to_32(const bitmap_t *src, bitmap_t *dst, const rectangle *visarea, UINT32 palettebase);
void convert_palette_to_15(const bitmap_t *src, bitmap_t *dst, const rectangle *visarea, UINT32 palettebase);
void texture_set_scale_bitmap(const rectangle *visarea, UINT32 palettebase);
void realloc_scale_bitmaps();
// scaler dimensions
int use_work_bitmap;
int scale_depth;
int scale_xsize;
int scale_ysize;
int scale_bank_offset;
bitmap_t * scale_bitmap[2];
bitmap_t * work_bitmap[2];
int scale_dirty[2];
#endif /* USE_SCALE_EFFECTS */
};
// device type definition
extern const device_type SCREEN;
//**************************************************************************
// SCREEN DEVICE CONFIGURATION MACROS
//**************************************************************************
#define MDRV_SCREEN_ADD(_tag, _type) \
MDRV_DEVICE_ADD(_tag, SCREEN, 0) \
MDRV_SCREEN_TYPE(_type)
#define MDRV_SCREEN_MODIFY(_tag) \
MDRV_DEVICE_MODIFY(_tag)
#define MDRV_SCREEN_FORMAT(_format) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_FORMAT, _format)
#define MDRV_SCREEN_TYPE(_type) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_TYPE, SCREEN_TYPE_##_type)
#define MDRV_SCREEN_RAW_PARAMS(_pixclock, _htotal, _hbend, _hbstart, _vtotal, _vbend, _vbstart) \
MDRV_DEVICE_INLINE_DATA64(screen_device_config::INLINE_REFRESH, HZ_TO_ATTOSECONDS(_pixclock) * (_htotal) * (_vtotal)) \
MDRV_DEVICE_INLINE_DATA64(screen_device_config::INLINE_VBLANK, ((HZ_TO_ATTOSECONDS(_pixclock) * (_htotal) * (_vtotal)) / (_vtotal)) * ((_vtotal) - ((_vbstart) - (_vbend)))) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_WIDTH, _htotal) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_HEIGHT, _vtotal) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MINX, _hbend) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MAXX, (_hbstart) - 1) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MINY, _vbend) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MAXY, (_vbstart) - 1)
#define MDRV_SCREEN_REFRESH_RATE(_rate) \
MDRV_DEVICE_INLINE_DATA64(screen_device_config::INLINE_REFRESH, HZ_TO_ATTOSECONDS(_rate))
#define MDRV_SCREEN_VBLANK_TIME(_time) \
MDRV_DEVICE_INLINE_DATA64(screen_device_config::INLINE_VBLANK, _time) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_OLDVBLANK, true)
#define MDRV_SCREEN_SIZE(_width, _height) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_WIDTH, _width) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_HEIGHT, _height)
#define MDRV_SCREEN_VISIBLE_AREA(_minx, _maxx, _miny, _maxy) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MINX, _minx) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MAXX, _maxx) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MINY, _miny) \
MDRV_DEVICE_INLINE_DATA16(screen_device_config::INLINE_VIS_MAXY, _maxy)
#define MDRV_SCREEN_DEFAULT_POSITION(_xscale, _xoffs, _yscale, _yoffs) \
MDRV_DEVICE_INLINE_DATA32(screen_device_config::INLINE_XOFFSET, (INT32)((_xoffs) * (double)(1 << 24))) \
MDRV_DEVICE_INLINE_DATA32(screen_device_config::INLINE_XSCALE, (INT32)((_xscale) * (double)(1 << 24))) \
MDRV_DEVICE_INLINE_DATA32(screen_device_config::INLINE_YOFFSET, (INT32)((_yoffs) * (double)(1 << 24))) \
MDRV_DEVICE_INLINE_DATA32(screen_device_config::INLINE_YSCALE, (INT32)((_yscale) * (double)(1 << 24)))
//**************************************************************************
// FUNCTION PROTOTYPES
//**************************************************************************
/* ----- core implementation ----- */
/* core initialization */
void video_init(running_machine *machine);
/* ----- global rendering ----- */
/* update the screen, handling frame skipping and rendering */
void video_frame_update(running_machine *machine, int debug);
/* ----- throttling/frameskipping/performance ----- */
/* are we skipping the current frame? */
int video_skip_this_frame(void);
/* get/set the speed factor as an integer * 100 */
int video_get_speed_factor(void);
void video_set_speed_factor(int speed);
/* return text to display about the current speed */
const char *video_get_speed_text(running_machine *machine);
/* return the current effective speed percentage */
double video_get_speed_percent(running_machine *machine);
/* get/set the current frameskip (-1 means auto) */
int video_get_frameskip(void);
void video_set_frameskip(int frameskip);
/* get/set the current throttle */
int video_get_throttle(void);
void video_set_throttle(int throttle);
/* get/set the current fastforward state */
int video_get_fastforward(void);
void video_set_fastforward(int fastforward);
/* ----- snapshots ----- */
/* save a snapshot of a given screen */
void screen_save_snapshot(running_machine *machine, device_t *screen, mame_file *fp);
/* save a snapshot of all the active screens */
void video_save_active_screen_snapshots(running_machine *machine);
/* ----- movie recording ----- */
int video_mng_is_movie_active(running_machine *machine);
void video_mng_begin_recording(running_machine *machine, const char *name);
void video_mng_end_recording(running_machine *machine);
void video_avi_begin_recording(running_machine *machine, const char *name);
void video_avi_end_recording(running_machine *machine);
void video_avi_add_sound(running_machine *machine, const INT16 *sound, int numsamples);
/* ----- configuration helpers ----- */
/* select a view for a given target */
int video_get_view_for_target(running_machine *machine, render_target *target, const char *viewname, int targetindex, int numtargets);
/* ----- debugging helpers ----- */
/* assert if any pixels in the given bitmap contain an invalid palette index */
void video_assert_out_of_range_pixels(running_machine *machine, bitmap_t *bitmap);
//**************************************************************************
// INLINE HELPERS
//**************************************************************************
//-------------------------------------------------
// screen_count - return the number of
// video screen devices in a machine_config
//-------------------------------------------------
inline int screen_count(const machine_config &config)
{
return config.m_devicelist.count(SCREEN);
}
//-------------------------------------------------
// screen_first - return the first
// video screen device config in a machine_config
//-------------------------------------------------
inline const screen_device_config *screen_first(const machine_config &config)
{
return downcast<screen_device_config *>(config.m_devicelist.first(SCREEN));
}
//-------------------------------------------------
// screen_next - return the next
// video screen device config in a machine_config
//-------------------------------------------------
inline const screen_device_config *screen_next(const screen_device_config *previous)
{
return downcast<screen_device_config *>(previous->typenext());
}
//-------------------------------------------------
// screen_count - return the number of
// video screen devices in a machine
//-------------------------------------------------
inline int screen_count(running_machine &machine)
{
return machine.m_devicelist.count(SCREEN);
}
//-------------------------------------------------
// screen_first - return the first
// video screen device in a machine
//-------------------------------------------------
inline screen_device *screen_first(running_machine &machine)
{
return downcast<screen_device *>(machine.m_devicelist.first(SCREEN));
}
//-------------------------------------------------
// screen_next - return the next
// video screen device in a machine
//-------------------------------------------------
inline screen_device *screen_next(screen_device *previous)
{
return downcast<screen_device *>(previous->typenext());
}
#endif /* __VIDEO_H__ */
| [
"[email protected]"
] | [
[
[
1,
500
]
]
] |
bba28caad0a278fcc4454428a53a2f6e5399606a | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/fusion/test/cons_tests.cpp | 3994834cb93849c329776a7b18ecdd60628d5e5b | [
"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 | 2,436 | cpp | /*=============================================================================
Copyright (c) 2003 Joel de Guzman
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <string>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/fusion/sequence/cons.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/spirit/fusion/algorithm/for_each.hpp>
#include <boost/spirit/fusion/algorithm/filter.hpp>
#include <boost/spirit/fusion/sequence/io.hpp>
#include <boost/spirit/fusion/sequence/tuple.hpp>
#include <boost/spirit/fusion/sequence/equal_to.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/lambda.hpp>
int
main()
{
std::cout << boost::fusion::tuple_open('[');
std::cout << boost::fusion::tuple_close(']');
std::cout << boost::fusion::tuple_delimiter(", ");
/// Testing cons
{
std::string hello("hello");
boost::fusion::cons<int,boost::fusion::cons<std::string> > ns =
boost::fusion::make_cons(1, boost::fusion::make_cons(hello));
BOOST_TEST((*boost::fusion::begin(ns) == 1));
BOOST_TEST((*boost::fusion::next(boost::fusion::begin(ns)) == hello));
*boost::fusion::begin(ns) += 1;
*boost::fusion::next(boost::fusion::begin(ns)) += ' ';
BOOST_TEST((*boost::fusion::begin(ns) == 2));
BOOST_TEST((*boost::fusion::next(boost::fusion::begin(ns)) == hello + ' '));
boost::fusion::for_each(ns, boost::lambda::_1 += ' ');
BOOST_TEST((*boost::fusion::begin(ns) == 2 + ' '));
BOOST_TEST((*boost::fusion::next(boost::fusion::begin(ns)) == hello + ' ' + ' '));
}
{
boost::fusion::tuple<int, float> t(1, 1.1f);
boost::fusion::cons<int, boost::fusion::cons<float> > nf =
boost::fusion::make_cons(1, boost::fusion::make_cons(1.1f));
BOOST_TEST((t == nf));
BOOST_TEST((boost::fusion::tuple<int>(1) == boost::fusion::filter(nf, boost::is_same<boost::mpl::_,int>())));
std::cout << nf << std::endl;
std::cout << boost::fusion::filter(nf, boost::is_same<boost::mpl::_,int>()) << std::endl;
}
return boost::report_errors();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
63
]
]
] |
cbaf72841bb502b7daf5f673934771850c778cc1 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Instance_HallsOfStone.cpp | 8d20f5471261e1a428239e3f0143a4c23a4254c3 | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,835 | cpp | /*
* Sun++ Scripts for Ascent Based MMORPG Server
* Copyright (C) 2008 Sun++ Team <http://www.sunplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
#include "Base.h"
/* To-Do:
http://wotlk.wowhead.com/?zone=4264
*/
//Dark Rune Stormcaller
#define CN_DR_STORMCALLER 27984
#define STORMCALLER_LIGHTNINGBOLT 12167
#define STORMCALLER_SHADOWWORD 15654
class DarkRuneStormcallerAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneStormcallerAI, MoonScriptCreatureAI);
DarkRuneStormcallerAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(STORMCALLER_LIGHTNINGBOLT, Target_RandomPlayer, 60, 3, 6);
AddSpell(STORMCALLER_SHADOWWORD, Target_RandomPlayer, 16, 0, 12);
}
};
//Iron Golem Custodian
#define CN_GOLEM_CUSTODIAN 27985
#define CUSTODIAN_CRUSH_ARMOR 33661 //Suden armor?
#define CUSTODIAN_GROUND_SMASH 12734 //STUN
class IronGolemCustodianAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(IronGolemCustodianAI, MoonScriptCreatureAI);
IronGolemCustodianAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(CUSTODIAN_CRUSH_ARMOR, Target_Current, 50, 0, 5);
AddSpell(CUSTODIAN_GROUND_SMASH, Target_ClosestPlayer, 20, 0, 14);
}
};
//Dark Rune Protector
#define CN_DR_PROTECTOR 27983
#define PROTECTOR_CHARGE 22120
#define PROTECTOR_CLAVE 42724
class DarkRuneProtectorAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneProtectorAI, MoonScriptCreatureAI);
DarkRuneProtectorAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(PROTECTOR_CHARGE, Target_RandomPlayerNotCurrent, 20, 0, 14, 10);
AddSpell(PROTECTOR_CLAVE, Target_Current, 35, 0, 8);
}
};
//Lesser Air Elemental
#define CN_LASSER_AIR_ELEMENTAL 28384
#define ELEMENTAL_LIGHTNING_BOLT 15801
class LesserAirElementalAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(LesserAirElementalAI, MoonScriptCreatureAI);
LesserAirElementalAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(ELEMENTAL_LIGHTNING_BOLT, Target_RandomPlayerNotCurrent, 20, 3, 14);
}
};
//Dark Rune Worker
#define CN_DR_WORKER 27961
#define WORKER_ENRAGE 51499 //not really enrage :)
#define WORKER_PIERCE_ARMOR 46202
class DarkRuneWorkerAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneWorkerAI, MoonScriptCreatureAI);
DarkRuneWorkerAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(WORKER_ENRAGE, Target_Self, 5, 0, 60, 10);
AddSpell(WORKER_PIERCE_ARMOR, Target_Current, 35, 0, 45);
}
};
//Dark Rune Warrior
#define CN_DR_WARRIOR 27960
#define WARRIOR_CLAVE 42724
#define WARRIOR_HEROIC_STRIKE 53395
class DarkRuneWarriorAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneWarriorAI, MoonScriptCreatureAI);
DarkRuneWarriorAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(WARRIOR_CLAVE, Target_Current, 15, 0, 8);
AddSpell(WARRIOR_HEROIC_STRIKE, Target_Current, 35, 0, 12);
}
};
//Dark Rune Theurgist
#define CN_DR_THEURGIST 27963
#define THEURGIST_BLAST_WAVE 22424 //Cast on self 12466
#define THEURGIST_FIREBOLT 12466 //Random target?
#define THEURGIST_IRON_MIGHT 51484 //Cast on self, some kind of enrage.
class DarkRuneTheurgistAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneTheurgistAI, MoonScriptCreatureAI);
DarkRuneTheurgistAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(THEURGIST_BLAST_WAVE, Target_Self, 22, 0, 25);
AddSpell(THEURGIST_FIREBOLT, Target_RandomPlayer, 40, 3, 6);
AddSpell(THEURGIST_IRON_MIGHT, Target_Self, 5, 0, 60);
}
};
//Dark Rune Shaper
#define CN_DR_SHAPER 27965
#define SHAPER_RAY 51496 //Debuff
class DarkRuneShaperAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneShaperAI, MoonScriptCreatureAI);
DarkRuneShaperAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(SHAPER_RAY, Target_RandomPlayer, 35, 1.5, 12);
}
};
//Dark Rune Scholar
#define CN_DR_SCHOLAR 27964
#define SCHOLAR_SILANCE 51612 //not rly silance but something like it :)
class DarkRuneScholarAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneScholarAI, MoonScriptCreatureAI);
DarkRuneScholarAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(SCHOLAR_SILANCE, Target_RandomPlayerNotCurrent, 35, 2.5, 12);
}
};
//Dark Rune Giant
#define CN_DR_GIANT 27969
#define GIANT_FIST 51494 //also some kind of enrage
#define GIANT_STOMP 51493 //Knockback
class DarkRuneGiantAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneGiantAI, MoonScriptCreatureAI);
DarkRuneGiantAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(GIANT_FIST, Target_Self, 3, 2, 40);
AddSpell(GIANT_STOMP, Target_RandomPlayer, 35, 0, 14, 0, 10);
}
};
/*
//Dark Rune Elementalist
#define CN_DR_ELEMENTALIST 27962
#define ELEMENTALIST_ARCANE_HASTE 32693 //Should cast at 40% hp
#define ELEMENTALIST_LIGHTNING_BOLT 53314
#define ELEMENTALIST_LIGHTNING_SHIELD 51776 //on enter combant
#define ELEMENTALIST_SUMMON_AIR_ELEMENTAL 51475 //Summons creature 28384 AI is included here
//Dark Rune Controller
#define CN_DR_CONTROLLER 27966
#define CONTROLLER_ENRAGE 51805 //some kind of enrage, stuck up to 3 times
//#define CONTROLLER_MIND_CONTROL 51503 //NOT WORKING
#define CONTROLLER_SUMMON_SHARDLING 51507 //Summons 27974 no AI needed
*/
//Raging Construct
#define CN_RAGING_CONSTRUCT 27970
#define RAGING_CLAVE 28168
#define RAGING_POTENT_JOLT 51819 // he should stack this in about every 6 seconds or something
class DarkRuneConstructAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkRuneConstructAI, MoonScriptCreatureAI);
DarkRuneConstructAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(RAGING_POTENT_JOLT, Target_Self, 95, 0, 8);
AddSpell(RAGING_CLAVE, Target_Current, 30, 0, 9, 0, 10);
}
};
//Lightning Construct
#define CN_LIGHTNING_CONSTRUCT 27972
#define LIGHTNING_CHAIN_LIGHTNING 52383
#define LIGHTNING_ELECTRICAL_OVERLOAD 52341 //explode?
class DarkLightningConstructAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(DarkLightningConstructAI, MoonScriptCreatureAI);
DarkLightningConstructAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(LIGHTNING_ELECTRICAL_OVERLOAD, Target_Self, 5, 1.5, 14);
AddSpell(LIGHTNING_CHAIN_LIGHTNING, Target_Current, 30, 3, 8, 0, 30);
}
};
//Forged Iron Trogg
#define CN_FI_TRAGG 27979
#define TRAGG_SHOCK 50900
class ForgedIronTroggAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(ForgedIronTroggAI, MoonScriptCreatureAI);
ForgedIronTroggAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(LIGHTNING_CHAIN_LIGHTNING, Target_RandomPlayer, 30, 2, 8, 0, 10);
}
};
//Maiden of Grief BOSS
/*Aggro:
* You shouldn't have come...now you will die!
Kill:
* Why must it be this way?
* You had it coming!
* My burden grows heavier.
* This is your own fault!
Stun:
* So much lost time... that you'll never get back!
Death:
* I hope you all rot! I never...wanted...this.*/ // haha found BrantX on wowhead :p
/*Tactics:
This fight works similar to Maiden of Virtue in Karazhan.
She occasionally drops a big void zone instead of consecration, and puts a magical debuff dealing shadow damage instead of holy firing.
She also casts Shock of Sorrow, which deals 1750 to 2250 shadow damage and incapacitates all group members for 10 seconds.
This ability has a 4 second cast time. If the healer is positioned near a void zone, the healer can jump into it to avoid being incapacitated for the full duration. */
/*#define BOSS_MAIDEN_OF_GRIEF 27975
#define MAIDEN_PILLAR_OF_WOE 50761 //apply at long/min range (all in that void zone should get it )
#define MAIDEN_SHOCK_OF_SORROW 50760
#define MAIDEN_STORM_OF_GRIEF 27975
class MaidenOfGriefAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(MaidenofGriefAI, MoonScriptCreatureAI);
MaidenofGriefAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
//"So much lost time... that you'll never get back! " on SHOCK_OF_SORROW
AddSpell(MAIDEN_SHOCK_OF_SORROW, Target_RandomPlayer, 5, 0, 20, 30, 0, false, "So much lost time... that you'll never get back!")
//EMOTES
AddEmote(Event_OnCombatStart, "You shouldn't have come...now you will die! ", Text_Yell);
AddEmote(Event_OnTargetDied, "My burden grows heavier.", Text_Yell);
AddEmote(Event_OnTargetDied, "This is your own fault!", Text_Yell);
AddEmote(Event_OnTargetDied, "You had it coming!", Text_Yell);
AddEmote(Event_OnTargetDied, "Why must it be this way?", Text_Yell);
AddEmote(Event_OnDied, "I hope you all rot! I never...wanted...this.", Text_Yell);
}
}; */
void SetupHallsOfStone(ScriptMgr * mgr)
{
//mgr->register_creature_script(BOSS_MAIDEN_OF_GRIEF, &MaidenOfGriefAI::Create);
mgr->register_creature_script(CN_DR_STORMCALLER, &DarkRuneStormcallerAI::Create);
mgr->register_creature_script(CN_GOLEM_CUSTODIAN, &IronGolemCustodianAI::Create);
mgr->register_creature_script(CN_DR_PROTECTOR, &DarkRuneProtectorAI::Create);
mgr->register_creature_script(CN_LASSER_AIR_ELEMENTAL, &LesserAirElementalAI::Create);
mgr->register_creature_script(CN_DR_WORKER, &DarkRuneWorkerAI::Create);
mgr->register_creature_script(CN_DR_THEURGIST, &DarkRuneTheurgistAI::Create);
mgr->register_creature_script(CN_DR_SHAPER, &DarkRuneShaperAI::Create);
mgr->register_creature_script(CN_DR_SCHOLAR, &DarkRuneScholarAI::Create);
mgr->register_creature_script(CN_DR_GIANT, &DarkRuneGiantAI::Create);
mgr->register_creature_script(CN_RAGING_CONSTRUCT, &DarkRuneConstructAI::Create);
mgr->register_creature_script(CN_LIGHTNING_CONSTRUCT, &DarkLightningConstructAI::Create);
mgr->register_creature_script(CN_FI_TRAGG, &ForgedIronTroggAI::Create);
} | [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
309
]
]
] |
a2caeea3f6d97d406ed3e599a1c7933ba9ed9c2b | df5277b77ad258cc5d3da348b5986294b055a2be | /GameEngineV0.35/Source/Core.h | f03eee72a89319394d4083e564d7deedb73a3c1d | [] | no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | h | ///////////////////////////////////////////////////////////////////////////////////////
///
/// \file Core.h
/// Defines the CoreEngine.
/// Authors: Benjamin Ellinger, Chris Peters
/// Copyright 2009, Digipen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////////////
#pragma once //Makes sure this header is only included once
#include "System.h"
namespace Framework
{
///The core manages all the systems in the game. Updating them, routing messages, and
///destroying them when the game ends.
class CoreEngine
{
public:
CoreEngine();
~CoreEngine();
///Update all the systems until the game is no longer active.
void GameLoop();
///Destroy all systems in reverse order that they were added.
void DestroySystems();
///Broadcasts a message to all systems.
void BroadcastMessage(Message* m);
///Adds a new system to the game.
void AddSystem(ISystem* system);
///Adds a system currently on the systems vec to the inactive systems vec
void SleepSystem(ISystem* system);
///Initializes all systems in the game.
void Initialize();
double GetTime( void ) { return TotalTime; }
private:
//Tracks all the systems the game uses
std::vector<ISystem*> Systems;
std::vector<ISystem*> InactiveSystems;
//The last time the game was updated
double LastTime;
double TotalTime;
//Is the game running (true) or being shut down (false)?
bool GameActive;
};
///Message to tell the game to quit
class MessageQuit : public Message
{
public:
MessageQuit() : Message(Mid::Quit) {};
};
///Signals all systems to activate or deactivate the display of debug data.
class ToggleDebugDisplay : public Message
{
public:
bool DebugActive;
ToggleDebugDisplay(bool debugActive)
: Message(Mid::ToggleDebugInfo) , DebugActive(debugActive) {};
};
//A global pointer to the instance of the core
extern CoreEngine* CORE;
} | [
"rziugy@af704e40-745a-32bd-e5ce-d8b418a3b9ef",
"westleyargentum@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
] | [
[
[
1,
29
],
[
32,
38
],
[
40,
65
]
],
[
[
30,
31
],
[
39,
39
]
]
] |
3e565fcc9baadf084d10c41073d7817a727a86aa | d9bee9a69d72decfd3d2761582e582295b7fa29c | /Genr/GenR/Objectes/Camara.h | 441e3deb0ad7706c547158d7e066da66ed91b13b | [] | no_license | Joan10/Estructures-b-siques | b70281c5d0de80e8d1abc8a329ddc7bb1109542c | c819cf632f80ba2d16841db7a5f6f0efea9a5aab | refs/heads/master | 2021-01-16T23:07:28.796114 | 2011-09-26T22:23:17 | 2011-09-26T22:23:17 | 1,934,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | h | #ifndef CAMARA_H
#define CAMARA_H
#include "../taulell.h"
#include "../objecte.h"
class Camara : public Objecte
{
public:
Camara( int ampl, int alc, Taulell *Tref);
~Camara();
// void Pinta();
Punt getInfEsq()
{
return InfEsq;
}
Punt getSupDret()
{
return SupDret;
}
void assignaForma();
void Pinta();
virtual void Mou(Punt Desti);
private:
/**********************
Definim variables.
Posicions, no píxels.
***********************/
Punt InfEsq;
Punt SupDret;
int amplada;
int alcada;
/*******************
Mides en píxels d'un quadre.
*******************/
static const int amplada_quadre = 20;
static const int alcada_quadre = 20;
/**********************
Taulell associat a la càmara
***********************/
Taulell *T;
};
#endif // CAMARA_H
| [
"joan@joan-desktop.(none)"
] | [
[
[
1,
56
]
]
] |
59fd7f2f083ebd2450fd036e2a5bcd67a79bb094 | 677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f | /SolidSBCTestSDKTools/SolidSBCTestSDKTools.cpp | 9cd5316bb758c1bcd5b3f7a6125b789f1399f952 | [] | no_license | M0WA/SolidSBC | 0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419 | 3e9682e90a22650e12338785c368ed69a9cac18b | refs/heads/master | 2020-04-19T14:40:36.625222 | 2011-12-02T01:50:05 | 2011-12-02T01:50:05 | 168,250,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | cpp |
// SolidSBCTestSDKTools.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "SolidSBCTestSDKTools.h"
#include "SolidSBCTestSDKToolsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CSolidSBCTestSDKToolsApp
BEGIN_MESSAGE_MAP(CSolidSBCTestSDKToolsApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CSolidSBCTestSDKToolsApp construction
CSolidSBCTestSDKToolsApp::CSolidSBCTestSDKToolsApp()
{
::AfxInitRichEdit2();
}
// The one and only CSolidSBCTestSDKToolsApp object
CSolidSBCTestSDKToolsApp theApp;
// CSolidSBCTestSDKToolsApp initialization
BOOL CSolidSBCTestSDKToolsApp::InitInstance()
{
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();
// Create the shell manager, in case the dialog contains
// any shell tree view or shell list view controls.
CShellManager *pShellManager = new CShellManager;
SetRegistryKey(_T("mo-sys-sdktools"));
CSolidSBCTestSDKToolsDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Delete the shell manager created above.
if (pShellManager != NULL)
{
delete pShellManager;
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"admin@bd7e3521-35e9-406e-9279-390287f868d3"
] | [
[
[
1,
78
]
]
] |
8d0c4c86e4fdc094b24e0c9d5d124510d0b4a667 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/range/size_type.hpp | 1429fd3b84274196d47826d1a847f7e4d92e9a7a | [
"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 | 1,463 | 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_RANGE_SIZE_TYPE_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_RANGE_SIZE_TYPE_HPP_INCLUDED
#include <cbear.berlios.de/range/traits.hpp>
namespace cbear_berlios_de
{
namespace range
{
template<class Container>
struct size_type { typedef typename traits<Container>::size_type type; };
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
39
]
]
] |
805253e849c49b4fd79f255989ac17dcce70f1c2 | ea613c6a4d531be9b5d41ced98df1a91320c59cc | /7-Zip/CPP/7zip/UI/FileManager/PanelItems.cpp | 4b9986db5061463b8fbe6d0999326e24f1bc7995 | [] | no_license | f059074251/interested | 939f938109853da83741ee03aca161bfa9ce0976 | b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2 | refs/heads/master | 2021-01-15T14:49:45.217066 | 2010-09-16T10:42:30 | 2010-09-16T10:42:30 | 34,316,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,210 | cpp | // PanelItems.cpp
#include "StdAfx.h"
#include "../../../../C/Sort.h"
#include "Common/StringConvert.h"
#include "Windows/Menu.h"
#include "Windows/PropVariant.h"
#include "Windows/PropVariantConversions.h"
#include "../../PropID.h"
#include "resource.h"
#include "LangUtils.h"
#include "Panel.h"
#include "PropertyName.h"
#include "RootFolder.h"
using namespace NWindows;
static int GetColumnAlign(PROPID propID, VARTYPE varType)
{
switch(propID)
{
case kpidCTime:
case kpidATime:
case kpidMTime:
return LVCFMT_LEFT;
}
switch(varType)
{
case VT_UI1:
case VT_I2:
case VT_UI2:
case VT_I4:
case VT_INT:
case VT_UI4:
case VT_UINT:
case VT_I8:
case VT_UI8:
case VT_BOOL:
return LVCFMT_RIGHT;
case VT_EMPTY:
case VT_I1:
case VT_FILETIME:
case VT_BSTR:
return LVCFMT_LEFT;
default:
return LVCFMT_CENTER;
}
}
void CPanel::InitColumns()
{
if (_needSaveInfo)
SaveListViewInfo();
_listView.DeleteAllItems();
_selectedStatusVector.Clear();
ReadListViewInfo();
PROPID sortID;
/*
if (_listViewInfo.SortIndex >= 0)
sortID = _listViewInfo.Columns[_listViewInfo.SortIndex].PropID;
*/
sortID = _listViewInfo.SortID;
_ascending = _listViewInfo.Ascending;
_properties.Clear();
_needSaveInfo = true;
UInt32 numProperties;
_folder->GetNumberOfProperties(&numProperties);
int i;
for (i = 0; i < (int)numProperties; i++)
{
CMyComBSTR name;
PROPID propID;
VARTYPE varType;
if (_folder->GetPropertyInfo(i, &name, &propID, &varType) != S_OK)
throw 1;
if (propID == kpidIsDir)
continue;
CItemProperty prop;
prop.Type = varType;
prop.ID = propID;
prop.Name = GetNameOfProperty(propID, name);
prop.Order = -1;
prop.IsVisible = true;
prop.Width = 100;
_properties.Add(prop);
}
// InitColumns2(sortID);
for (;;)
if (!_listView.DeleteColumn(0))
break;
int order = 0;
for(i = 0; i < _listViewInfo.Columns.Size(); i++)
{
const CColumnInfo &columnInfo = _listViewInfo.Columns[i];
int index = _properties.FindItemWithID(columnInfo.PropID);
if (index >= 0)
{
CItemProperty &item = _properties[index];
item.IsVisible = columnInfo.IsVisible;
item.Width = columnInfo.Width;
if (columnInfo.IsVisible)
item.Order = order++;
continue;
}
}
for(i = 0; i < _properties.Size(); i++)
{
CItemProperty &item = _properties[i];
if (item.Order < 0)
item.Order = order++;
}
_visibleProperties.Clear();
for (i = 0; i < _properties.Size(); i++)
{
const CItemProperty &prop = _properties[i];
if (prop.IsVisible)
_visibleProperties.Add(prop);
}
// _sortIndex = 0;
_sortID = kpidName;
/*
if (_listViewInfo.SortIndex >= 0)
{
int sortIndex = _properties.FindItemWithID(sortID);
if (sortIndex >= 0)
_sortIndex = sortIndex;
}
*/
_sortID = _listViewInfo.SortID;
for (i = 0; i < _visibleProperties.Size(); i++)
{
InsertColumn(i);
}
}
void CPanel::InsertColumn(int index)
{
const CItemProperty &prop = _visibleProperties[index];
LV_COLUMNW column;
column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM | LVCF_ORDER;
column.cx = prop.Width;
column.fmt = GetColumnAlign(prop.ID, prop.Type);
column.iOrder = prop.Order;
column.iSubItem = index;
column.pszText = (wchar_t *)(const wchar_t *)prop.Name;
_listView.InsertColumn(index, &column);
}
void CPanel::RefreshListCtrl()
{
RefreshListCtrl(UString(), -1, true, UStringVector());
}
int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData);
void CPanel::GetSelectedNames(UStringVector &selectedNames)
{
selectedNames.Clear();
CRecordVector<UInt32> indices;
GetSelectedItemsIndices(indices);
selectedNames.Reserve(indices.Size());
for (int i = 0; i < indices.Size(); i++)
selectedNames.Add(GetItemRelPath(indices[i]));
/*
for (int i = 0; i < _listView.GetItemCount(); i++)
{
const int kSize = 1024;
WCHAR name[kSize + 1];
LVITEMW item;
item.iItem = i;
item.pszText = name;
item.cchTextMax = kSize;
item.iSubItem = 0;
item.mask = LVIF_TEXT | LVIF_PARAM;
if (!_listView.GetItem(&item))
continue;
int realIndex = GetRealIndex(item);
if (realIndex == kParentIndex)
continue;
if (_selectedStatusVector[realIndex])
selectedNames.Add(item.pszText);
}
*/
selectedNames.Sort();
}
void CPanel::SaveSelectedState(CSelectedState &s)
{
s.FocusedName.Empty();
s.SelectedNames.Clear();
s.FocusedItem = _listView.GetFocusedItem();
{
if (s.FocusedItem >= 0)
{
int realIndex = GetRealItemIndex(s.FocusedItem);
if (realIndex != kParentIndex)
s.FocusedName = GetItemRelPath(realIndex);
/*
const int kSize = 1024;
WCHAR name[kSize + 1];
LVITEMW item;
item.iItem = focusedItem;
item.pszText = name;
item.cchTextMax = kSize;
item.iSubItem = 0;
item.mask = LVIF_TEXT;
if (_listView.GetItem(&item))
focusedName = item.pszText;
*/
}
}
GetSelectedNames(s.SelectedNames);
}
void CPanel::RefreshListCtrl(const CSelectedState &s)
{
bool selectFocused = s.SelectFocused;
if (_mySelectMode)
selectFocused = true;
RefreshListCtrl(s.FocusedName, s.FocusedItem, selectFocused, s.SelectedNames);
}
void CPanel::RefreshListCtrlSaveFocused()
{
CSelectedState state;
SaveSelectedState(state);
RefreshListCtrl(state);
}
void CPanel::SetFocusedSelectedItem(int index, bool select)
{
UINT state = LVIS_FOCUSED;
if (select)
state |= LVIS_SELECTED;
_listView.SetItemState(index, state, state);
if (!_mySelectMode && select)
{
int realIndex = GetRealItemIndex(index);
if (realIndex != kParentIndex)
_selectedStatusVector[realIndex] = true;
}
}
void CPanel::RefreshListCtrl(const UString &focusedName, int focusedPos, bool selectFocused,
const UStringVector &selectedNames)
{
_dontShowMode = false;
LoadFullPathAndShow();
// OutputDebugStringA("=======\n");
// OutputDebugStringA("s1 \n");
CDisableTimerProcessing timerProcessing(*this);
if (focusedPos < 0)
focusedPos = 0;
_listView.SetRedraw(false);
// m_RedrawEnabled = false;
LVITEMW item;
ZeroMemory(&item, sizeof(item));
_listView.DeleteAllItems();
_selectedStatusVector.Clear();
// _realIndices.Clear();
_startGroupSelect = 0;
_selectionIsDefined = false;
// m_Files.Clear();
// _folder.Release();
if (!_folder)
{
// throw 1;
SetToRootFolder();
}
_headerToolBar.EnableButton(kParentFolderID, !IsRootFolder());
CMyComPtr<IFolderSetFlatMode> folderSetFlatMode;
_folder.QueryInterface(IID_IFolderSetFlatMode, &folderSetFlatMode);
if (folderSetFlatMode)
folderSetFlatMode->SetFlatMode(BoolToInt(_flatMode));
if (_folder->LoadItems() != S_OK)
return;
InitColumns();
// OutputDebugString(TEXT("Start Dir\n"));
UInt32 numItems;
_folder->GetNumberOfItems(&numItems);
bool showDots = _showDots && !IsRootFolder();
_listView.SetItemCount(numItems + (showDots ? 1 : 0));
_selectedStatusVector.Reserve(numItems);
int cursorIndex = -1;
CMyComPtr<IFolderGetSystemIconIndex> folderGetSystemIconIndex;
if (!IsFSFolder() || _showRealFileIcons)
_folder.QueryInterface(IID_IFolderGetSystemIconIndex, &folderGetSystemIconIndex);
if (showDots)
{
UString itemName = L"..";
item.iItem = _listView.GetItemCount();
if (itemName.CompareNoCase(focusedName) == 0)
cursorIndex = item.iItem;
item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
int subItem = 0;
item.iSubItem = subItem++;
item.lParam = kParentIndex;
item.pszText = (wchar_t *)(const wchar_t *)itemName;
UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY;
item.iImage = _extToIconMap.GetIconIndex(attrib, itemName);
if (item.iImage < 0)
item.iImage = 0;
if(_listView.InsertItem(&item) == -1)
return;
}
// OutputDebugStringA("S1\n");
for(UInt32 i = 0; i < numItems; i++)
{
UString itemName = GetItemName(i);
const UString relPath = GetItemRelPath(i);
if (relPath.CompareNoCase(focusedName) == 0)
cursorIndex = _listView.GetItemCount();
bool selected = false;
if (selectedNames.FindInSorted(relPath) >= 0)
selected = true;
_selectedStatusVector.Add(selected);
item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
if (!_mySelectMode)
if (selected)
{
item.mask |= LVIF_STATE;
item.state = LVIS_SELECTED;
}
int subItem = 0;
item.iItem = _listView.GetItemCount();
item.iSubItem = subItem++;
item.lParam = i;
UString correctedName;
if (itemName.Find(L" ") >= 0)
{
int pos = 0;
for (;;)
{
int posNew = itemName.Find(L" ", pos);
if (posNew < 0)
{
correctedName += itemName.Mid(pos);
break;
}
correctedName += itemName.Mid(pos, posNew - pos);
correctedName += L" ... ";
pos = posNew;
while (itemName[++pos] == ' ');
}
item.pszText = (wchar_t *)(const wchar_t *)correctedName;
}
else
item.pszText = (wchar_t *)(const wchar_t *)itemName;
NCOM::CPropVariant prop;
_folder->GetProperty(i, kpidAttrib, &prop);
UInt32 attrib = 0;
if (prop.vt == VT_UI4)
attrib = prop.ulVal;
else if (IsItemFolder(i))
attrib |= FILE_ATTRIBUTE_DIRECTORY;
bool defined = false;
if (folderGetSystemIconIndex)
{
folderGetSystemIconIndex->GetSystemIconIndex(i, &item.iImage);
defined = (item.iImage > 0);
}
if (!defined)
{
if (_currentFolderPrefix.IsEmpty())
{
int iconIndexTemp;
GetRealIconIndex(itemName + WCHAR_PATH_SEPARATOR, attrib, iconIndexTemp);
item.iImage = iconIndexTemp;
}
else
{
item.iImage = _extToIconMap.GetIconIndex(attrib, itemName);
}
}
if (item.iImage < 0)
item.iImage = 0;
if(_listView.InsertItem(&item) == -1)
return; // error
}
// OutputDebugStringA("End2\n");
if(_listView.GetItemCount() > 0 && cursorIndex >= 0)
SetFocusedSelectedItem(cursorIndex, selectFocused);
_listView.SortItems(CompareItems, (LPARAM)this);
if (cursorIndex < 0 && _listView.GetItemCount() > 0)
{
if (focusedPos >= _listView.GetItemCount())
focusedPos = _listView.GetItemCount() - 1;
SetFocusedSelectedItem(focusedPos, showDots);
}
// m_RedrawEnabled = true;
_listView.EnsureVisible(_listView.GetFocusedItem(), false);
_listView.SetRedraw(true);
_listView.InvalidateRect(NULL, true);
// OutputDebugStringA("End1\n");
/*
_listView.UpdateWindow();
*/
}
void CPanel::GetSelectedItemsIndices(CRecordVector<UInt32> &indices) const
{
indices.Clear();
/*
int itemIndex = -1;
while ((itemIndex = _listView.GetNextItem(itemIndex, LVNI_SELECTED)) != -1)
{
LPARAM param;
if (_listView.GetItemParam(itemIndex, param))
indices.Add(param);
}
*/
for (int i = 0; i < _selectedStatusVector.Size(); i++)
if (_selectedStatusVector[i])
indices.Add(i);
HeapSort(&indices.Front(), indices.Size());
}
void CPanel::GetOperatedItemIndices(CRecordVector<UInt32> &indices) const
{
GetSelectedItemsIndices(indices);
if (!indices.IsEmpty())
return;
if (_listView.GetSelectedCount() == 0)
return;
int focusedItem = _listView.GetFocusedItem();
if (focusedItem >= 0)
{
if(_listView.GetItemState(focusedItem, LVIS_SELECTED) == LVIS_SELECTED)
{
int realIndex = GetRealItemIndex(focusedItem);
if (realIndex != kParentIndex)
indices.Add(realIndex);
}
}
}
void CPanel::GetAllItemIndices(CRecordVector<UInt32> &indices) const
{
indices.Clear();
UInt32 numItems;
if (_folder->GetNumberOfItems(&numItems) == S_OK)
for (UInt32 i = 0; i < numItems; i++)
indices.Add(i);
}
void CPanel::GetOperatedIndicesSmart(CRecordVector<UInt32> &indices) const
{
GetOperatedItemIndices(indices);
if (indices.IsEmpty() || (indices.Size() == 1 && indices[0] == (UInt32)(Int32)-1))
GetAllItemIndices(indices);
}
/*
void CPanel::GetOperatedListViewIndices(CRecordVector<UInt32> &indices) const
{
indices.Clear();
int numItems = _listView.GetItemCount();
for (int i = 0; i < numItems; i++)
{
int realIndex = GetRealItemIndex(i);
if (realIndex >= 0)
if (_selectedStatusVector[realIndex])
indices.Add(i);
}
if (indices.IsEmpty())
{
int focusedItem = _listView.GetFocusedItem();
if (focusedItem >= 0)
indices.Add(focusedItem);
}
}
*/
void CPanel::EditItem()
{
int focusedItem = _listView.GetFocusedItem();
if (focusedItem < 0)
return;
int realIndex = GetRealItemIndex(focusedItem);
if (realIndex == kParentIndex)
return;
if (!IsItemFolder(realIndex))
EditItem(realIndex);
}
void CPanel::OpenFocusedItemAsInternal()
{
int focusedItem = _listView.GetFocusedItem();
if (focusedItem < 0)
return;
int realIndex = GetRealItemIndex(focusedItem);
if (IsItemFolder(realIndex))
OpenFolder(realIndex);
else
OpenItem(realIndex, true, false);
}
void CPanel::OpenSelectedItems(bool tryInternal)
{
CRecordVector<UInt32> indices;
GetOperatedItemIndices(indices);
if (indices.Size() > 20)
{
MessageBoxErrorLang(IDS_TOO_MANY_ITEMS, 0x02000606);
return;
}
int focusedItem = _listView.GetFocusedItem();
if (focusedItem >= 0)
{
int realIndex = GetRealItemIndex(focusedItem);
if (realIndex == kParentIndex && (tryInternal || indices.Size() == 0) &&
_listView.GetItemState(focusedItem, LVIS_SELECTED) == LVIS_SELECTED)
indices.Insert(0, realIndex);
}
bool dirIsStarted = false;
for(int i = 0; i < indices.Size(); i++)
{
UInt32 index = indices[i];
// CFileInfo &aFile = m_Files[index];
if (IsItemFolder(index))
{
if (!dirIsStarted)
{
if (tryInternal)
{
OpenFolder(index);
dirIsStarted = true;
break;
}
else
OpenFolderExternal(index);
}
}
else
OpenItem(index, (tryInternal && indices.Size() == 1), true);
}
}
UString CPanel::GetItemName(int itemIndex) const
{
if (itemIndex == kParentIndex)
return L"..";
NCOM::CPropVariant prop;
if (_folder->GetProperty(itemIndex, kpidName, &prop) != S_OK)
throw 2723400;
if (prop.vt != VT_BSTR)
throw 2723401;
return prop.bstrVal;
}
UString CPanel::GetItemPrefix(int itemIndex) const
{
if (itemIndex == kParentIndex)
return UString();
NCOM::CPropVariant prop;
if (_folder->GetProperty(itemIndex, kpidPrefix, &prop) != S_OK)
throw 2723400;
UString prefix;
if (prop.vt == VT_BSTR)
prefix = prop.bstrVal;
return prefix;
}
UString CPanel::GetItemRelPath(int itemIndex) const
{
return GetItemPrefix(itemIndex) + GetItemName(itemIndex);
}
UString CPanel::GetItemFullPath(int itemIndex) const
{
return _currentFolderPrefix + GetItemRelPath(itemIndex);
}
bool CPanel::IsItemFolder(int itemIndex) const
{
if (itemIndex == kParentIndex)
return true;
NCOM::CPropVariant prop;
if (_folder->GetProperty(itemIndex, kpidIsDir, &prop) != S_OK)
throw 2723400;
if (prop.vt == VT_BOOL)
return VARIANT_BOOLToBool(prop.boolVal);
if (prop.vt == VT_EMPTY)
return false;
return false;
}
UINT64 CPanel::GetItemSize(int itemIndex) const
{
if (itemIndex == kParentIndex)
return 0;
NCOM::CPropVariant prop;
if (_folder->GetProperty(itemIndex, kpidSize, &prop) != S_OK)
throw 2723400;
if (prop.vt == VT_EMPTY)
return 0;
return ConvertPropVariantToUInt64(prop);
}
void CPanel::ReadListViewInfo()
{
_typeIDString = GetFolderTypeID();
if (!_typeIDString.IsEmpty())
::ReadListViewInfo(_typeIDString, _listViewInfo);
}
void CPanel::SaveListViewInfo()
{
int i;
for(i = 0; i < _visibleProperties.Size(); i++)
{
CItemProperty &prop = _visibleProperties[i];
LVCOLUMN winColumnInfo;
winColumnInfo.mask = LVCF_ORDER | LVCF_WIDTH;
if (!_listView.GetColumn(i, &winColumnInfo))
throw 1;
prop.Order = winColumnInfo.iOrder;
prop.Width = winColumnInfo.cx;
}
CListViewInfo viewInfo;
// PROPID sortPropID = _properties[_sortIndex].ID;
PROPID sortPropID = _sortID;
_visibleProperties.Sort();
for(i = 0; i < _visibleProperties.Size(); i++)
{
const CItemProperty &prop = _visibleProperties[i];
CColumnInfo columnInfo;
columnInfo.IsVisible = prop.IsVisible;
columnInfo.PropID = prop.ID;
columnInfo.Width = prop.Width;
viewInfo.Columns.Add(columnInfo);
}
for(i = 0; i < _properties.Size(); i++)
{
const CItemProperty &prop = _properties[i];
if (!prop.IsVisible)
{
CColumnInfo columnInfo;
columnInfo.IsVisible = prop.IsVisible;
columnInfo.PropID = prop.ID;
columnInfo.Width = prop.Width;
viewInfo.Columns.Add(columnInfo);
}
}
// viewInfo.SortIndex = viewInfo.FindColumnWithID(sortPropID);
viewInfo.SortID = sortPropID;
viewInfo.Ascending = _ascending;
if (!_listViewInfo.IsEqual(viewInfo))
{
::SaveListViewInfo(_typeIDString, viewInfo);
_listViewInfo = viewInfo;
}
}
bool CPanel::OnRightClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActiveate, LRESULT &result)
{
if(itemActiveate->hdr.hwndFrom == HWND(_listView))
return false;
POINT point;
::GetCursorPos(&point);
ShowColumnsContextMenu(point.x, point.y);
result = TRUE;
return true;
}
void CPanel::ShowColumnsContextMenu(int x, int y)
{
CMenu menu;
CMenuDestroyer menuDestroyer(menu);
menu.CreatePopup();
const int kCommandStart = 100;
for(int i = 0; i < _properties.Size(); i++)
{
const CItemProperty &prop = _properties[i];
UINT flags = MF_STRING;
if (prop.IsVisible)
flags |= MF_CHECKED;
if (i == 0)
flags |= MF_GRAYED;
menu.AppendItem(flags, kCommandStart + i, prop.Name);
}
int menuResult = menu.Track(TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, x, y, _listView);
if (menuResult >= kCommandStart && menuResult <= kCommandStart + _properties.Size())
{
int index = menuResult - kCommandStart;
CItemProperty &prop = _properties[index];
prop.IsVisible = !prop.IsVisible;
if (prop.IsVisible)
{
int prevVisibleSize = _visibleProperties.Size();
prop.Order = prevVisibleSize;
_visibleProperties.Add(prop);
InsertColumn(prevVisibleSize);
}
else
{
int visibleIndex = _visibleProperties.FindItemWithID(prop.ID);
_visibleProperties.Delete(visibleIndex);
/*
if (_sortIndex == index)
{
_sortIndex = 0;
_ascending = true;
}
*/
if (_sortID == prop.ID)
{
_sortID = kpidName;
_ascending = true;
}
_listView.DeleteColumn(visibleIndex);
}
}
}
void CPanel::OnReload()
{
RefreshListCtrlSaveFocused();
OnRefreshStatusBar();
}
void CPanel::OnTimer()
{
if (!_processTimer)
return;
CMyComPtr<IFolderWasChanged> folderWasChanged;
if (_folder.QueryInterface(IID_IFolderWasChanged, &folderWasChanged) != S_OK)
return;
Int32 wasChanged;
if (folderWasChanged->WasChanged(&wasChanged) != S_OK)
return;
if (wasChanged == 0)
return;
OnReload();
}
| [
"[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d"
] | [
[
[
1,
805
]
]
] |
8c592be2be61db95a676094c8c3e1ecfe1580e26 | 5914cd9c29d20cd1dae6e76df4aa8ed50688ebee | /Networks/genacje_salzmamy_connector.cpp | 7f14dae52f482031725f32f42b6122f04d40c12e | [] | no_license | nagyistoce/cs462genacje-salzmamy-networks | 86f03cf5ba1f26d3a7dd9da9a9a6a2670040bf56 | da50f8ba7b727fcde9dd9cf4d88ca0e6b76c41b8 | refs/heads/master | 2016-09-05T15:25:54.497672 | 2011-12-13T01:16:54 | 2011-12-13T01:16:54 | 32,271,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,767 | cpp | #include "genacje_salzmamy_connector.h"
Connector :: Connector () {
cout << "default constructor called\n";
}
Connector :: Connector (int port_num) {
// set display for encrypted data
cin.ignore(2048, '\n');
char print = 'x';
do {
cout << "Print encrypted data? (y/n): " << endl;
cin >> print;
} while (print != 'y' || print != 'n');
if (print == 'y') {
print_encrypted = true;
} else {
print_encrypted = false;
}
crc = new CCRC32();
crc->Initialize();
addr_len = sizeof (struct sockaddr);
numbytes = 0;
port = port_num;
he = NULL;
key = new Blowfish ();
msg_size = DEFAULTPKTSIZE +TAILSIZE; // default size for establishing connection
memset(buf, '\0', MAXPKTSIZE); // edited
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons (port); // short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset (& (my_addr.sin_zero), '\0', 8); // zero the rest of the struct
if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) == -1) {
cout << "Failed to create socket. Terminating...\n";
exit (1);
}
if (bind (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr)) == -1) {
cout << "Failed to bind socket. Terminating...\n";
exit (1);
}
}
Connector :: Connector (char * receiver, int port_num) {
crc = new CCRC32();
crc->Initialize();
print_encrypted = false;
numbytes = 0;
port = port_num;
addr_len = sizeof (struct sockaddr);
key = new Blowfish ();
msg_size = DEFAULTPKTSIZE+TAILSIZE; // default size for establishing connection
memset(buf, '\0', MAXPKTSIZE); // edited
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons(port); // short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct
if ((he = gethostbyname (receiver)) == NULL) { // get the host info
cout << "Bad host name entered; Terminating..."<<endl;
exit(1);
}
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons (port); // short, network byte order
their_addr.sin_addr = *((struct in_addr *) he -> h_addr);
memset (& (their_addr.sin_zero), '\0', 8); // zero the rest of the struct
if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) == -1) {
cout << "Socket creation failed; Terminating..." << endl;
exit (1);
}
}
Connector :: ~Connector () {
close (sockfd);
delete (key);
delete (crc);
}
bool Connector :: listen () {
memset(buf, '\0', msg_size);
if ((numbytes = recvfrom (sockfd, buf, msg_size, 0, (struct sockaddr *) & their_addr, (socklen_t *) & addr_len)) == -1) {
cout << "Error in listen(): Failed to receive. Terminating...\n";
exit (1);
}
/*
if (print_encrypted) {
cout << "Encrypted message received: " << buf << endl;
}
*/
key -> Decrypt((void *) buf, msg_size);
buf [numbytes] = '\0';
cout << "Decrypted message received: " << buf << endl;
//printf ("%d bytes received\n", numbytes);
// CRC
unsigned long received_crc = 0;
memcpy(&received_crc, &buf[msg_size-TAILSIZE], sizeof(unsigned long));
unsigned long expected_crc = crc->FullCRC((const unsigned char*)buf, (unsigned long) msg_size-TAILSIZE);
//cout << "CRC received: " << received_crc << endl;
//cout << "CRC expected: " << expected_crc << endl;
if (received_crc == expected_crc) {
cout << "CRC: Valid packet!" << endl;
return true;
} else {
cout << "Invalid packet... may be valid if cross architecture." << endl;
return false;
}
}
void Connector :: send (char * msg) {
char msg_copy [msg_size];
memset(msg_copy, '\0', msg_size); // clear it out.
memcpy (msg_copy, msg, msg_size-TAILSIZE);
// CRC before we encrypt and send...
unsigned long c = crc->FullCRC((const unsigned char*)msg_copy, (unsigned long) msg_size-TAILSIZE);
memcpy(&msg_copy[msg_size-TAILSIZE], &c, sizeof(long)); // fill in the crc slot
cout << "Unencrypted message to send: " << msg_copy << endl;
//cout << "CRC value: " << (unsigned long)c << endl;
key -> Encrypt((void *) msg_copy, msg_size);
/*
if (print_encrypted) {
cout << "Encrypted message to send: " << msg_copy << endl;
}*/
if ((numbytes = sendto(sockfd, msg_copy, msg_size, 0, (struct sockaddr *)
& their_addr, sizeof (struct sockaddr))) == -1) {
cout << "Error in send(): Failed to send. Terminating...\n";
exit(1);
}
//cout << numbytes << " bytes sent." << endl;
}
void Connector :: send_unencrypted (char * msg) {
char msg_copy [msg_size];
memset(msg_copy, '\0', msg_size); // clear it out.
memcpy (msg_copy, msg, msg_size-TAILSIZE); // copy user's msg
cout << "Unencrypted message to send: " << msg_copy << endl;
// CRC before we send...
unsigned long c = crc->FullCRC((const unsigned char*)msg_copy, (unsigned long) msg_size-TAILSIZE);
memcpy(&msg_copy[msg_size-TAILSIZE], &c, sizeof(long)); // fill in the crc slot
//cout << "CRC value: " << c << endl;
if ((numbytes = sendto(sockfd, msg_copy, msg_size, 0, (struct sockaddr *) & their_addr, sizeof (struct sockaddr))) == -1) {
cout << "Error in send_unencrypted(): Failed to send. Terminating...\n";
exit(1);
}
}
char * Connector :: get_msg () {
return buf;
}
void Connector::set_print_encrypted(bool print) {
print_encrypted = print;
if (print) {
cout << "Connector: Encrypted sends and receives will be displayed.\n";
} else {
cout << "Connector: Encrypted data will not be displayed.\n";
}
}
void Connector :: set_key (char * passwd) {
key -> Set_Passwd(passwd);
cout << "Encryption password set to: " << passwd << endl;
}
void Connector :: set_msg_size (int size) {
if (size+TAILSIZE > MAXPKTSIZE) {
cout << "Error! Packet size too high... aborting..." << endl;
exit(1);
}
// the user will only be able to use [size] bytes of the send/rcv buffer
msg_size = (size+ TAILSIZE); // compensates for the CRC and end of string char;
}
int Connector :: get_msg_size () {
return msg_size-TAILSIZE; // return how many bytes the user may send as data
}
| [
"[email protected]@79cf5116-dcd4-c039-58dd-6f4206d1403f"
] | [
[
[
1,
219
]
]
] |
44c35570af3240e519cd0b7479b45f590e3158b1 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/gui/app/Popup_animate_application_setting.h | 33aab3acf56e0400e50554b97b02cc91da2855ef | [] | no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | h | /* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: Popup_color_map_frame.h 258 2007-12-05 14:40:50Z miklosb $
*/
#ifndef POPUP_ANIMATE_APPLICATION_SETTING_H
#define POPUP_ANIMATE_APPLICATION_SETTING_H
#include <QtGui/QFrame>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QGridLayout>
#include <QtGui/QPushButton>
#include <QtGui/QSlider>
#include <gui/app/static/Application_settings.h>
class Popup_animate_application_setting : public QFrame {
Q_OBJECT
public:
Popup_animate_application_setting(QWidget* parent);
void set_application_variable(QString& application_variable_name, Application_setting_type type);
private slots:
void animate_up();
void animate_down();
void from_changed(const QString & text);
void until_changed(const QString & text);
void steps_changed(const QString & text);
void slider_value_changed(int value );
signals:
void application_variable_changed(const QString& app_variable_name);
private:
void resize_slider();
QGridLayout* gridLayout;
QLabel* val_label;
QLabel* title_label;
QLineEdit* from;
QLineEdit* until;
QLineEdit* steps;
QSlider* slider;
QPushButton* forward_button, *back_button;
QString application_variable_name;
Application_setting_type type;
};
#endif //POPUP_ANIMATE_APPLICATION_SETTING_H | [
"balint.miklos@localhost"
] | [
[
[
1,
58
]
]
] |
054fe5121039e8a89529c2d8875cb1307423ce78 | 1fcbf9df9587c331eda6cfd86966070413088322 | /include/cTestEnviroment.h | 8eddce9e224088cf297b22d9957fb8a2f02b9163 | [] | no_license | xytis/ccSim | 9c1d962adf0bc8a2a21622a49f9afd3d6330e19f | 2e0b6b343a08d01091da0ff542896f8eaaea43e8 | refs/heads/master | 2020-05-14T16:10:29.387148 | 2011-01-06T15:06:36 | 2011-01-06T15:06:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | h | #ifndef CTESTENVIROMENT_H_INCLUDED
#define CTESTENVIROMENT_H_INCLUDED
namespace DoI
{
class cTestEnviroment
{
public:
private:
/**
* Čia sudėsim visus operatorius, kuriuos paeliui taikysim kiekvienam blokui.
*/
vector<aMechanics *>operators;
/**
* Čia pagrindinis blokų masyvas. Jame kartu ir lauko vertės užslėptos, kad būtų galima
* taikyti operatorius.
*/
vector<cAbstractBlock *>blocks;
/**
* Elektrinio lauko sąrašo pradžią ir pabaigą, kad galima būtų skaičiuoti el. lauką nelendant į blocks.
*/
cField * field_begin;
cField * field_end;
};
};
#endif // CTESTENVIROMENT_H_INCLUDED
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
ae83da694ecf3653bed67934fe57392076a7e720 | 2bcfdc7adc9d794391e0f79e4dab5c481ca5a09b | /applications/hac-widgets/designer/src/customwidgetinterface.cpp | 9821dde864d66c93f775a80fc299762c80ec6fcf | [] | no_license | etop-wesley/hac | 592912a7c4023ba8bd2c25ae5de9c18d90c79b0b | ab82cb047ed15346c25ce01faff00815256b00b7 | refs/heads/master | 2021-01-02T22:45:32.603368 | 2010-09-01T08:38:01 | 2010-09-01T08:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,102 | cpp | #include "customwidgetinterface.h"
#include <QtCore/QtPlugin>
CustomWidgetInterface::CustomWidgetInterface(QObject *parent)
: QObject(parent),
m_initialized(false),
m_isContainer(false),
m_name(""),
m_include(""),
m_toolTip(""),
m_whatsThis(""),
m_domXml(""),
m_icon(QIcon())
{
}
/*
* Initializes the widget for use with the specified formEditor interface.
* Sets up extensions and other features for custom widgets.
* Custom container extensions (see QDesignerContainerExtension)
* and task menu extensions (see QDesignerTaskMenuExtension)
* should be set up in this function.
*/
void CustomWidgetInterface::initialize(QDesignerFormEditorInterface *formEditor)
{
Q_UNUSED(formEditor);
if (m_initialized)
return;
// Add extension registrations, etc. here
m_initialized = true;
}
/*
* Returns true if the widget has been initialized, otherwise returns false.
* Reimplementations usually check whether the initialize( ) function
* has been called and return the result of this test.
*/
bool CustomWidgetInterface::isInitialized() const
{
return m_initialized;
}
/*
* Returns a new instance of the custom widget, with the given parent.
* the default implemention return Null.
*/
QWidget * CustomWidgetInterface::createWidget(QWidget *parent)
{
Q_UNUSED(parent)
return NULL;
}
/*
* Returns the class name of the custom widget supplied by the interface.
* The name returned must be identical to the class name
* used for the custom widget.
*/
QString CustomWidgetInterface::name() const
{
return m_name;
}
/*
* Returns the name of the group to which the custom widget belongs.
*/
QString CustomWidgetInterface::group() const
{
return m_group;
}
/*
* Returns the icon used to represent the custom widget in Qt Designer's widget box.
*/
QIcon CustomWidgetInterface::icon() const
{
return m_icon;
}
/*
* Returns a short description of the widget that can be used
* by Qt Designer in a tool tip.
*/
QString CustomWidgetInterface::toolTip() const
{
return m_toolTip;
}
/*
* Returns a description of the widget that can be used
* by Qt Designer in "What's This?" help for the widget.
*/
QString CustomWidgetInterface::whatsThis() const
{
return m_whatsThis;
}
/*
* True if the widget will be used to hold child widgets; otherwise false.
*/
bool CustomWidgetInterface::isContainer() const
{
return m_isContainer;
}
/*
* Returns the XML that is used to describe the custom widget's properties to Qt Designer.
*/
QString CustomWidgetInterface::domXml() const
{
return m_domXml;
}
/*
* Returns the path to the include file that uic uses when creating code for the custom widget.
* The header file that must be included in applications that use this widget.
* This information is stored in .ui files and will be used by uic
* to create a suitable #includes statement in the code it generates
* for the form containing the custom widget.
*/
QString CustomWidgetInterface::includeFile() const
{
return m_include;
}
| [
"wesley@debian.(none)"
] | [
[
[
1,
129
]
]
] |
5a359757c7d7e96586c7f01ad8a9a53b5c84962c | 27d65f4910de0a270fa657fbaec9bf854debe22c | /Stack (C++)/Stack.hpp | 27be5fc8cda706d6e1473a2530417422c7298ad4 | [] | no_license | MMSequeira/iscte-iul-dcti-pa | 52678bda68fb225ee442d41bfb00b4ec6124799e | 4e2ab6f6a69c136f82d5d2396d8108246677c452 | refs/heads/master | 2021-01-01T19:16:40.684632 | 2010-11-30T22:33:16 | 2010-11-30T22:33:16 | 33,122,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,744 | hpp | #ifndef STACK_HPP_
#define STACK_HPP_
#include <cassert>
#include <algorithm>
template <typename I>
class Stack {
public:
typedef I Item;
Stack()
: capacity(10), number_of_items(0), items(new Item[capacity]) {
cout << "Constructing stack!" << endl;
}
Stack(Stack const& originalStack)
: capacity(originalStack.capacity),
number_of_items(originalStack.number_of_items),
items(new Item[capacity]) {
for(int i = 0; i != number_of_items; ++i)
items[i] = originalStack.items[i];
cout << "Constructing stack by copy!" << endl;
}
~Stack() {
cout << "Destroying stack!" << endl;
delete[] items;
}
bool isEmpty() {
return size() == 0;
}
int size() {
return number_of_items;
}
Item top() {
assert(!isEmpty());
return items[number_of_items - 1];
}
void push(Item const& newItem) {
if(number_of_items == capacity)
increaseCapacity();
items[number_of_items] = newItem;
++number_of_items;
}
void pop() {
// TODO Shrink array capacity to half whenever possible.
assert(!isEmpty());
--number_of_items;
}
void swap(Stack& anotherStack) {
std::swap(capacity, anotherStack.capacity);
std::swap(number_of_items, anotherStack.number_of_items);
std::swap(items, anotherStack.items);
}
Stack& operator=(Stack const& modelStack) {
Stack clone{modelStack};
swap(clone);
return *this;
}
private:
void increaseCapacity() {
capacity *= 2;
Item* new_items = new Item[capacity];
for(int i = 0; i != number_of_items; ++i)
new_items[i] = items[i];
delete[] items;
items = new_items;
}
int capacity;
int number_of_items;
Item *items;
};
#endif /* STACK_HPP_ */
| [
"[email protected]@672aaf38-5943-b58a-8c72-bd47800389a2"
] | [
[
[
1,
95
]
]
] |
44b10d83c8efbb4fb799f982fd7ea44f9ab1ed7f | b799c972367cd014a1ffed4288a9deb72f590bec | /project/NetServices/drv/serial/usb/UsbSerial.cpp | 23d7123cea4d88c5448aecfea1ea86b020b1eb86 | [] | no_license | intervigilium/csm213a-embedded | 647087de8f831e3c69e05d847d09f5fa12b468e6 | ae4622be1eef8eb6e4d1677a9b2904921be19a9e | refs/heads/master | 2021-01-13T02:22:42.397072 | 2011-12-11T22:50:37 | 2011-12-11T22:50:37 | 2,832,079 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,570 | cpp |
/*
Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "rpc.h"
#include "UsbSerial.h"
//#define __DEBUG
#include "dbg/dbg.h"
#include "netCfg.h"
#if NET_USB_SERIAL
namespace mbed {
#define BUF_LEN 64
#define FLUSH_TMOUT 100000 //US
UsbSerial::UsbSerial(UsbDevice* pDevice, int epIn, int epOut, const char* name /*= NULL*/) : Stream(name), m_epIn(pDevice, epIn, true, USB_BULK, BUF_LEN), m_epOut(pDevice, epOut, false, USB_BULK, BUF_LEN),
m_pInCbItem(NULL), m_pInCbMeth(NULL), m_pOutCbItem(NULL), m_pOutCbMeth(NULL)
{
m_inBufEven = new char[BUF_LEN];
m_inBufOdd = new char[BUF_LEN];
m_pInBufPos = m_inBufUsr = m_inBufEven;
m_inBufTrmt = m_inBufOdd;
m_outBufEven = new char[BUF_LEN];
m_outBufOdd = new char[BUF_LEN];
m_pOutBufPos = m_outBufUsr = m_outBufEven;
m_outBufTrmt = m_outBufOdd;
m_inBufLen = m_outBufLen = 0;
DBG("Starting RX'ing on in ep\n");
m_timeout = false;
m_epIn.setOnCompletion(this, &UsbSerial::onEpInTransfer);
m_epOut.setOnCompletion(this, &UsbSerial::onEpOutTransfer);
startRx();
}
UsbSerial::~UsbSerial()
{
delete[] m_inBufEven;
delete[] m_inBufOdd;
delete[] m_outBufEven;
delete[] m_outBufOdd;
}
void UsbSerial::baud(int baudrate) {
//
}
void UsbSerial::format(int bits, int parity, int stop) {
//
}
#if 0 //For doc only
template <class T>
void attach(T* pCbItem, void (T::*pCbMeth)())
{
m_pCbItem = (CDummy*) pCbItem;
m_pCbMeth = (void (CDummy::*)()) pCbMeth;
}
#endif
int UsbSerial::_getc() {
NVIC_DisableIRQ(US_TICKER_TIMER_IRQn);
NVIC_DisableIRQ(USB_IRQn);
char c;
c = *m_pInBufPos;
m_pInBufPos++;
NVIC_EnableIRQ(USB_IRQn);
NVIC_EnableIRQ(US_TICKER_TIMER_IRQn);
return c;
}
int UsbSerial::_putc(int c) {
NVIC_DisableIRQ(US_TICKER_TIMER_IRQn);
NVIC_DisableIRQ(USB_IRQn);
if( (m_pOutBufPos - m_outBufUsr) < BUF_LEN )
{
*m_pOutBufPos = (char) c;
m_pOutBufPos++;
}
else
{
DBG("NO WAY!!!\n");
}
#if 1
if( (m_pOutBufPos - m_outBufUsr) >= BUF_LEN ) //Must flush
{
if(m_timeout)
m_txTimeout.detach();
startTx();
}
else
{
/*if(m_timeout)
m_txTimeout.detach();
m_timeout = true;
m_txTimeout.attach_us(this, &UsbSerial::startTx, FLUSH_TMOUT);*/
if(!m_timeout)
{
m_timeout = true;
m_txTimeout.attach_us(this, &UsbSerial::startTx, FLUSH_TMOUT);
}
}
#endif
//startTx();
NVIC_EnableIRQ(USB_IRQn);
NVIC_EnableIRQ(US_TICKER_TIMER_IRQn);
return c;
}
int UsbSerial::readable() {
NVIC_DisableIRQ(US_TICKER_TIMER_IRQn);
NVIC_DisableIRQ(USB_IRQn);
int res;
if( (m_pInBufPos - m_inBufUsr) < m_inBufLen )
{
//DBG("\r\nREADABLE\r\n");
res = true;
}
else
{
//DBG("\r\nNOT READABLE\r\n");
startRx(); //Try to swap packets & start another transmission
res = ((m_pInBufPos - m_inBufUsr) < m_inBufLen )?true:false;
}
NVIC_EnableIRQ(USB_IRQn);
NVIC_EnableIRQ(US_TICKER_TIMER_IRQn);
return (bool)res;
}
int UsbSerial::writeable() {
NVIC_DisableIRQ(US_TICKER_TIMER_IRQn);
NVIC_DisableIRQ(USB_IRQn);
// DBG("\r\nWRITEABLE???\r\n");
int res = (bool)( (m_pOutBufPos - m_outBufUsr) < BUF_LEN);
NVIC_EnableIRQ(USB_IRQn);
NVIC_EnableIRQ(US_TICKER_TIMER_IRQn);
return res;
}
void UsbSerial::onReadable()
{
if(m_pInCbItem && m_pInCbMeth)
(m_pInCbItem->*m_pInCbMeth)();
}
void UsbSerial::onWriteable()
{
if(m_pOutCbItem && m_pOutCbMeth)
(m_pOutCbItem->*m_pOutCbMeth)();
}
void UsbSerial::onEpInTransfer()
{
int len = m_epIn.status();
DBG("RX transfer completed w len=%d\n",len);
startRx();
if(len > 0)
onReadable();
}
void UsbSerial::onEpOutTransfer()
{
int len = m_epOut.status();
DBG("TX transfer completed w len=%d\n",len);
if(m_timeout)
m_txTimeout.detach();
startTx();
if(len > 0)
onWriteable();
}
void UsbSerial::startTx()
{
DBG("Transfer>\n");
m_timeout = false;
// m_txTimeout.detach();
if(!(m_pOutBufPos - m_outBufUsr))
{
DBG("?!?!?\n");
return;
}
if( m_epOut.status() == USBERR_PROCESSING )
{
//Wait & retry
//m_timeout = true;
//m_txTimeout.attach_us(this, &UsbSerial::startTx, FLUSH_TMOUT);
DBG("Ep is busy...\n");
return;
}
if( m_epOut.status() < 0 )
{
DBG("Tx trying again...\n");
m_epOut.transfer((volatile uint8_t*)m_outBufTrmt, m_outBufLen);
return;
}
m_outBufLen = m_pOutBufPos - m_outBufUsr;
//Swap buffers
volatile char* swapBuf = m_outBufUsr;
m_outBufUsr = m_outBufTrmt;
m_outBufTrmt = swapBuf;
m_epOut.transfer((volatile uint8_t*)m_outBufTrmt, m_outBufLen);
m_pOutBufPos = m_outBufUsr;
}
void UsbSerial::startRx()
{
if( (m_pInBufPos - m_inBufUsr) < m_inBufLen )
{
//User buf is not empty, cannot swap now...
return;
}
int len = m_epIn.status();
if( len == USBERR_PROCESSING )
{
//Previous transmission not completed
return;
}
if( len < 0 )
{
DBG("Rx trying again...\n");
m_epIn.transfer((volatile uint8_t*)m_inBufTrmt, BUF_LEN); //Start another transmission
return;
}
m_inBufLen = len;
//Swap buffers
volatile char* swapBuf = m_inBufUsr;
m_inBufUsr = m_inBufTrmt;
m_inBufTrmt = swapBuf;
m_pInBufPos = m_inBufUsr;
DBG("Starting new transfer\n");
m_epIn.transfer((volatile uint8_t*)m_inBufTrmt, BUF_LEN); //Start another transmission
}
#ifdef MBED_RPC
const struct rpc_method *UsbSerial::get_rpc_methods() {
static const rpc_method methods[] = {
{ "readable", rpc_method_caller<int, UsbSerial, &UsbSerial::readable> },
{ "writeable", rpc_method_caller<int, UsbSerial, &UsbSerial::writeable> },
RPC_METHOD_SUPER(Stream)
};
return methods;
}
struct rpc_class *UsbSerial::get_rpc_class() {
static const rpc_function funcs[] = {
/*{ "new", rpc_function_caller<const char*, UsbDevice*, int, int, const char*, Base::construct<UsbSerial,UsbDevice*,int,int,const char*> > },*/ //RPC is buggy
RPC_METHOD_END
};
static rpc_class c = { "UsbSerial", funcs, NULL };
return &c;
}
#endif
} // namespace mbed
#endif
| [
"[email protected]"
] | [
[
[
1,
300
]
]
] |
15618d71f14b1654ed1672f8f279b533e4dcf82f | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/include/helper/EdgeAnimSprite.h | 1de07a184acb5d9cd1c27ea15ed56c7387cea5ad | [] | no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,592 | h | /*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef EDGE_ANIMSPRITE_H
#define EDGE_ANIMSPRITE_H
#include "EdgeDataStream.h"
#include <string>
#include <vector>
#include <map>
using std::string;
using std::vector;
using std::map;
namespace Edge
{
class Image;
struct AnimInfo
{
char name[64];
float speed;
int play_count;
int frame_count;
int start_f, end_f;
};
struct FrameInfo
{
char file[256];
float x, y, w, h;
};
/**
* AnimState
*
*/
class AnimState
{
public:
/**
* animation resources
*
*/
struct AnimRes
{
AnimRes( Image *image = 0, float x = 0, float y = 0, float w = 0, float h = 0 ) :
mImage( image ), mX( x ), mY( y ), mW( w ), mH( h )
{
}
Image *mImage;
float mX, mY, mW, mH;
};
/// resources container
typedef vector<AnimRes*> AnimResList;
public:
/**
* Construct a AnimState, reads data from buffer.
*
*/
AnimState( const AnimInfo *animInfo, const FrameInfo *frameInfo );
/**
* Destructor
*
*/
~AnimState();
/**
* update the animation, if finished return true
*
*/
bool update( float dt );
/**
* normal render
*
*/
void render( float x, float y );
/**
* reset the state
*
*/
void reset();
public:
/// anim name
string mName;
/// speed
float mSpeed;
/// play count
int mPlayCount;
/// frame count
int mFrameCount;
/// animation resources
AnimResList mAnimRes;
/// current frame
int mCurFrame;
/// current play count
int mCurCount;
/// current time
float mCurTime;
/// whether the animation is finished
bool mbFinished;
};
/**
* AnimSprite will manage a 2d frame animation.
*
*
*/
class AnimSprite
{
public:
/**
* animation name list
*
*/
typedef vector<string> AnimNameList;
/**
* animation state list
*
*/
typedef map<string, AnimState*> AnimStateList;
public:
/**
*
*
*/
AnimSprite( const string &name );
/**
*
*
*/
~AnimSprite();
/**
* create an animation sprite
*
*/
bool create( DataStreamPtr &stream );
/**
* release, called by the destructor
*
*/
void release();
/**
* get animation state name list
*
*/
AnimNameList &getAnimNameList();
/**
* set current animation
*
*/
void setCurAnim( const string &name );
/**
* set the current animation state's speed
*
* @param speed frame change time
*/
void setCurAnimSpeed( float speed );
/**
* update the animation, it the animation is finished, it returns true
*
*/
bool update( float dt );
/**
* render the animation, here i only provide a default rendering, if you want to
* do more complex rendering, you can access the current animation state's image.
*
*/
void render( float x, float y );
/**
* get the current animation state's image, so you can render the animtion more complexly.
*
*/
Image *getCurFrameImage();
/**
* get this animation sprite name
*
*/
string &getName() { return mName; }
protected:
/// animation states
AnimStateList mAnimStates;
/// animation name list
AnimNameList mAnimNames;
/// current animation
AnimState *mCurAnimState;
/// name
string mName;
};
}
#endif | [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
] | [
[
[
1,
234
]
]
] |
c63909ff1c5a31fb2bd948798ae2151134632182 | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Teki/Boss/Ookami/OokamiStraightAttack.h | fe31ccf44b4814b23d7f49ca9fd0feda26cd4390 | [] | no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | h | #include <string>
#include <vector>
#include <exception>
using namespace std;
#ifndef __OokamiStraightAttack_h__
#define __OokamiStraightAttack_h__
// #include "ActionState.h"
// #include "OokamiBaseAction.h"
class ActionState;
class OokamiBaseAction;
class OokamiStraightAttack;
class OokamiStraightAttack: public OokamiBaseAction
{
public: void BuildState(ActionState* rPrevState);
public: void OnEnter();
public: bool Update();
public: void OnExit();
};
#endif
| [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
] | [
[
[
1,
28
]
]
] |
9100717f8fcf40c736c3136dc28b35876d8b8a66 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/inc/gui/nguibrush.h | 39021c8fccaf093951ce0bf33633818b481ceef4 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,340 | h | #ifndef N_GUIBRUSH_H
#define N_GUIBRUSH_H
//------------------------------------------------------------------------------
/**
@brief A brush object which caches the pointer to the GUI resource inside
a skin object.
(C) 2004 RadonLabs GmbH
*/
#include "kernel/ntypes.h"
#include "util/nstring.h"
#include "kernel/nref.h"
class nGuiResource;
class nGuiSkin;
//------------------------------------------------------------------------------
class nGuiBrush
{
public:
/// constructor
nGuiBrush();
/// constructor with name
nGuiBrush(const char* n);
/// destructor
~nGuiBrush();
/// set brush name
void SetName(const char * n);
/// get brush name
const nString& GetName() const;
/// get cached gui resource pointer of the brush
nGuiResource* GetGuiResource();
private:
/// load resource
bool Load();
/// unload resource
void Unload();
/// return true if loaded
bool IsLoaded() const;
nString name;
nRef<nGuiSkin> refSkin;
nGuiResource* guiResource;
};
//------------------------------------------------------------------------------
/**
*/
inline
nGuiBrush::nGuiBrush() :
guiResource(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
inline
nGuiBrush::nGuiBrush(const char* n) :
name(n),
guiResource(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
inline
nGuiBrush::~nGuiBrush()
{
if (this->IsLoaded())
{
this->Unload();
}
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nGuiBrush::SetName(const char * n)
{
this->name.Set(n);
if (this->IsLoaded())
{
this->Unload();
}
}
//------------------------------------------------------------------------------
/**
*/
inline
const nString&
nGuiBrush::GetName() const
{
return this->name;
}
//------------------------------------------------------------------------------
/**
*/
inline
bool
nGuiBrush::IsLoaded() const
{
return (0 != this->guiResource);
}
//------------------------------------------------------------------------------
#endif
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
116
]
]
] |
eef38b09547eee800b00dfa255a4c0a656f5b395 | 110f8081090ba9591d295d617a55a674467d127e | /tests/MemoryStreamTest.cpp | f2c398f7684c9b4b6887d8a6d77dbacb9d850e2f | [] | no_license | rayfill/cpplib | 617bcf04368a2db70aea8b9418a45d7fd187d8c2 | bc37fbf0732141d0107dd93bcf5e0b31f0d078ca | refs/heads/master | 2021-01-25T03:49:26.965162 | 2011-07-17T15:19:11 | 2011-07-17T15:19:11 | 783,979 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | #include <cppunit/extensions/HelperMacros.h>
#include <IO/MemoryStream.hpp>
class MemoryStreamTest : public CppUnit::TestFixture
{
private:
CPPUNIT_TEST_SUITE(MemoryStreamTest);
CPPUNIT_TEST(basicStreamTest);
CPPUNIT_TEST_SUITE_END();
public:
void basicStreamTest()
{
MemoryStream ms;
ms << "test" << std::endl;
std::vector<char> buffer = ms.getMemory();
CPPUNIT_ASSERT(buffer[0] == 't');
CPPUNIT_ASSERT(buffer[1] == 'e');
CPPUNIT_ASSERT(buffer[2] == 's');
CPPUNIT_ASSERT(buffer[3] == 't');
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MemoryStreamTest );
| [
"bpokazakijr@287b3242-7fab-264f-8401-8509467ab285"
] | [
[
[
1,
26
]
]
] |
08620629c2ba9ecb4cecfbbc13f8c4633e058636 | 4506e6ceb97714292c3250023b634c3a07b73d5b | /rpg2kdevSDK/SDK/CRpgArray.h | c27560a505ef13ccb9ccf4dc6c34f466170369f6 | [] | no_license | take-cheeze/rpgtukuru-iphone | 76f23ddfe015018c9ae44b5e887cf837eb061bdf | 3447dbfab84ed1f17e46e9d6936c28b766dadd36 | refs/heads/master | 2016-09-05T10:47:30.461471 | 2011-11-01T09:45:19 | 2011-11-01T09:45:19 | 1,151,984 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,898 | h | /**
@file
@brief ツクール仕様の配列(1次元と2次元)を扱うクラス。\n
配列の中身をバッファとして直接格納する。\n
ツクールの配列の要素番号は1〜だが、内部では自動的に0〜で扱う。
@author sue445
*/
#ifndef _INC_CRPGARRAY
#define _INC_CRPGARRAY
#include <vector>
#include <string>
#include "sueLib/smart_buffer.h"
#include "sueLib/CMapTable.h"
using namespace sueLib;
/// 1次元配列
class CRpgArray1 : private CMapTable< smart_buffer, 1 >
{
private:
int m_nMaxCol; ///< 列の最大数
public:
CRpgArray1() : m_nMaxCol(0){} ///< デフォルトコンストラクタ
~CRpgArray1(){} ///< デストラクタ
void Init(){ Release(); m_nMaxCol = 0; } ///< 配列を初期化
unsigned int GetMaxSize() const{ return m_nMaxCol; } ///< 配列の最大要素数を返す
int GetNumber(int col, int def=0) const; ///< 整数を取得
bool GetFlag( int col, bool def=false) const; ///< bool型フラグを取得
std::string GetString(int col, const std::string& def = "") const; ///< 文字列を取得
smart_buffer GetData( int col) const; ///< バッファを取得
void SetNumber(int col, int data); ///< 整数をセット
void SetFlag( int col, bool data); ///< bool型フラグをセット
void SetString(int col, const std::string& data); ///< 文字列をセット
void SetData( int col, const smart_buffer& buf); ///< バッファをセット
};
/// 2次元配列
class CRpgArray2 : private CMapTable< smart_buffer, 2 >
{
private:
int m_nMaxCol; ///< 列の最大数
int m_nMaxRow; ///< 行の最大数
public:
CRpgArray2() : m_nMaxCol(0), m_nMaxRow(0){} ///< デフォルトコンストラクタ
~CRpgArray2(){} ///< デストラクタ
void Init(){ Release(); m_nMaxCol = m_nMaxRow = 0; } ///< 初期化
unsigned int GetMaxCol() const { return m_nMaxCol; } ///< 配列の列数を取得
unsigned int GetMaxRow() const { return m_nMaxRow; } ///< 配列の行数を取得
int GetNumber(int row, int col, int def=0) const; ///< 整数を取得
bool GetFlag( int row, int col, bool def=false) const; ///< bool型フラグを取得
std::string GetString(int row, int col, const std::string& def="") const; ///< 文字列を取得
smart_buffer GetData( int row, int col) const; ///< バッファを取得
void SetNumber(int row, int col, int data); ///< 整数をセット
void SetFlag( int row, int col, bool data); ///< bool型フラグをセット
void SetString(int row, int col, const std::string& data); ///< 文字列をセット
void SetData( int row, int col, const smart_buffer& buf); ///< バッファをセット
};
#endif
| [
"project.kuto@07b74652-1305-11df-902e-ef6c94960d2c"
] | [
[
[
1,
69
]
]
] |
217dd1b3afe40a0695f8259d22ff8c0aa890c1dd | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/src/EduNetConnect/AbstractEntityReplicaConnection.h | f793576bddd79ee6e5452b76e69cfa25dfaa87f7 | [] | no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,763 | h | #ifndef __ABSTRACTENTITYREPLICACONNECTION_H__
#define __ABSTRACTENTITYREPLICACONNECTION_H__
//-----------------------------------------------------------------------------
// Copyright (c) 2009, Jan Fietz, Cyrus Preuss
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of EduNetGames nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "EduNetCommon/EduNetCommon.h"
#include "EduNetConnect/EduNetConnect.h"
#include "OpenSteerUT/AbstractPluginUtilities.h"
#include "OpenSteerUT/AbstractEntityFactory.h"
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class AbstractEntityReplicaConnection : public RakNet::Connection_RM3 , public OpenSteer::PluginAccessor_t
{
public:
AbstractEntityReplicaConnection(SystemAddress _systemAddress, RakNetGUID _guid,
class OpenSteer::AbstractPlugin* pkAbstractPlugin) :
RakNet::Connection_RM3( _systemAddress, _guid )
{
this->setPlugin( pkAbstractPlugin );
};
virtual ~AbstractEntityReplicaConnection() {}
virtual RakNet::Replica3 *AllocReplica(RakNet::BitStream *allocationId,
RakNet::ReplicaManager3 *replicaManager3);
};
//-----------------------------------------------------------------------------
typedef OpenSteer::PluginAccessorMixin<RakNet::ReplicaManager3> TPluginReplicaManager;
//-----------------------------------------------------------------------------
class AbstractEntityReplicaManager : public TPluginReplicaManager
{
// replica manager interface
virtual RakNet::Connection_RM3* AllocConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID) const
{
return ET_NEW AbstractEntityReplicaConnection( systemAddress, rakNetGUID, this->getPlugin() );
}
virtual void DeallocConnection(RakNet::Connection_RM3 *connection) const
{
ET_DELETE connection;
}
};
//-----------------------------------------------------------------------------
class AbstractEntityReplicaFactory : public OpenSteer::EntityFactory
{
ET_DECLARE_BASE( OpenSteer::EntityFactory );
public:
AbstractEntityReplicaFactory(AbstractEntityReplicaManager* pkManager):
m_pkReplicaManager( pkManager ) {}
virtual OpenSteer::AbstractEntity* createEntity( OpenSteer::EntityClassId ) const;
virtual OpenSteer::AbstractVehicle* createVehicle( OpenSteer::EntityClassId classId ) const;
virtual bool destroyEntity( OpenSteer::AbstractEntity* pkEntity ) const;
virtual bool ownsEntity( OpenSteer::AbstractEntity* pkEntity ) const;
virtual bool destroyVehicle( OpenSteer::AbstractVehicle* pkVehicle ) const;
OpenSteer::AbstractEntity* createEntity( OpenSteer::EntityClassId,
osAbstractPlugin* pkPlugin ) const;
protected:
virtual class AbstractEntityReplica* createEntityReplica(
OpenSteer::AbstractPlugin* pPlugin,
OpenSteer::EntityClassId classId,
bool bIsRemoteObject, bool bClientReplica) const;
private:
class AbstractEntityReplicaManager* m_pkReplicaManager;
mutable DataStructures::Map<OpenSteer::InstanceTracker::Id, RakNet::Replica3* > m_uidMap;
};
//-----------------------------------------------------------------------------
class AbstractEntityCCReplicaFactory : public AbstractEntityReplicaFactory
{
ET_DECLARE_BASE( AbstractEntityReplicaFactory );
public:
AbstractEntityCCReplicaFactory(AbstractEntityReplicaManager* pkManager):
BaseClass( pkManager ) {}
protected:
virtual AbstractEntityReplica* createEntityReplica( OpenSteer::AbstractPlugin* pPlugin,
OpenSteer::EntityClassId classId,
bool bIsRemoteObject, bool bClientReplica) const;
};
//-----------------------------------------------------------------------------
class AbstractEntitySSReplicaFactory : public AbstractEntityReplicaFactory
{
ET_DECLARE_BASE( AbstractEntityReplicaFactory );
public:
AbstractEntitySSReplicaFactory(AbstractEntityReplicaManager* pkManager):
BaseClass( pkManager ) {}
protected:
virtual AbstractEntityReplica* createEntityReplica( OpenSteer::AbstractPlugin* pPlugin,
OpenSteer::EntityClassId classId,
bool bIsRemoteObject, bool bClientReplica) const;
};
#endif // __ABSTRACTENTITYREPLICACONNECTION_H__ | [
"janfietz@localhost"
] | [
[
[
1,
130
]
]
] |
c5d226a4499d8c108c471b462396203a79fdb800 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/multiplayer/ricochet/dlls/cbase.cpp | 14ae53ea65d41c828eaa7590c35e02f3cddec342 | [] | no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,049 | cpp | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "saverestore.h"
#include "client.h"
#include "decals.h"
#include "gamerules.h"
#include "game.h"
void EntvarsKeyvalue( entvars_t *pev, KeyValueData *pkvd );
extern "C" void PM_Move ( struct playermove_s *ppmove, int server );
extern "C" void PM_Init ( struct playermove_s *ppmove );
extern "C" char PM_FindTextureType( char *name );
void OnFreeEntPrivateData(edict_s *pEdict);
extern Vector VecBModelOrigin( entvars_t* pevBModel );
extern DLL_GLOBAL Vector g_vecAttackDir;
extern DLL_GLOBAL int g_iSkillLevel;
static DLL_FUNCTIONS gFunctionTable =
{
GameDLLInit, //pfnGameInit
DispatchSpawn, //pfnSpawn
DispatchThink, //pfnThink
DispatchUse, //pfnUse
DispatchTouch, //pfnTouch
DispatchBlocked, //pfnBlocked
DispatchKeyValue, //pfnKeyValue
DispatchSave, //pfnSave
DispatchRestore, //pfnRestore
DispatchObjectCollsionBox, //pfnAbsBox
SaveWriteFields, //pfnSaveWriteFields
SaveReadFields, //pfnSaveReadFields
SaveGlobalState, //pfnSaveGlobalState
RestoreGlobalState, //pfnRestoreGlobalState
ResetGlobalState, //pfnResetGlobalState
ClientConnect, //pfnClientConnect
ClientDisconnect, //pfnClientDisconnect
ClientKill, //pfnClientKill
ClientPutInServer, //pfnClientPutInServer
ClientCommand, //pfnClientCommand
ClientUserInfoChanged, //pfnClientUserInfoChanged
ServerActivate, //pfnServerActivate
ServerDeactivate, //pfnServerDeactivate
PlayerPreThink, //pfnPlayerPreThink
PlayerPostThink, //pfnPlayerPostThink
StartFrame, //pfnStartFrame
ParmsNewLevel, //pfnParmsNewLevel
ParmsChangeLevel, //pfnParmsChangeLevel
GetGameDescription, //pfnGetGameDescription Returns string describing current .dll game.
PlayerCustomization, //pfnPlayerCustomization Notifies .dll of new customization for player.
SpectatorConnect, //pfnSpectatorConnect Called when spectator joins server
SpectatorDisconnect, //pfnSpectatorDisconnect Called when spectator leaves the server
SpectatorThink, //pfnSpectatorThink Called when spectator sends a command packet (usercmd_t)
Sys_Error, //pfnSys_Error Called when engine has encountered an error
PM_Move, //pfnPM_Move
PM_Init, //pfnPM_Init Server version of player movement initialization
PM_FindTextureType, //pfnPM_FindTextureType
SetupVisibility, //pfnSetupVisibility Set up PVS and PAS for networking for this client
UpdateClientData, //pfnUpdateClientData Set up data sent only to specific client
AddToFullPack, //pfnAddToFullPack
CreateBaseline, //pfnCreateBaseline Tweak entity baseline for network encoding, allows setup of player baselines, too.
RegisterEncoders, //pfnRegisterEncoders Callbacks for network encoding
GetWeaponData, //pfnGetWeaponData
CmdStart, //pfnCmdStart
CmdEnd, //pfnCmdEnd
ConnectionlessPacket, //pfnConnectionlessPacket
GetHullBounds, //pfnGetHullBounds
CreateInstancedBaselines, //pfnCreateInstancedBaselines
InconsistentFile, //pfnInconsistentFile
AllowLagCompensation, //pfnAllowLagCompensation
};
NEW_DLL_FUNCTIONS gNewDLLFunctions =
{
OnFreeEntPrivateData, //pfnOnFreeEntPrivateData
GameDLLShutdown, //pfnGameShutdown
ShouldCollide, //pfnShouldCollide
};
static void SetObjectCollisionBox( entvars_t *pev );
int GetEntityAPI( DLL_FUNCTIONS *pFunctionTable, int interfaceVersion )
{
if ( !pFunctionTable || interfaceVersion != INTERFACE_VERSION )
{
return FALSE;
}
memcpy( pFunctionTable, &gFunctionTable, sizeof( DLL_FUNCTIONS ) );
return TRUE;
}
int GetEntityAPI2( DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion )
{
if ( !pFunctionTable || *interfaceVersion != INTERFACE_VERSION )
{
// Tell engine what version we had, so it can figure out who is out of date.
*interfaceVersion = INTERFACE_VERSION;
return FALSE;
}
memcpy( pFunctionTable, &gFunctionTable, sizeof( DLL_FUNCTIONS ) );
return TRUE;
}
int GetNewDLLFunctions(NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion)
{
if(!pFunctionTable || *interfaceVersion != NEW_DLL_FUNCTIONS_VERSION)
{
*interfaceVersion = NEW_DLL_FUNCTIONS_VERSION;
return FALSE;
}
memcpy(pFunctionTable, &gNewDLLFunctions, sizeof(gNewDLLFunctions));
return TRUE;
}
int DispatchSpawn( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
// Initialize these or entities who don't link to the world won't have anything in here
pEntity->pev->absmin = pEntity->pev->origin - Vector(1,1,1);
pEntity->pev->absmax = pEntity->pev->origin + Vector(1,1,1);
pEntity->Spawn();
// Try to get the pointer again, in case the spawn function deleted the entity.
// UNDONE: Spawn() should really return a code to ask that the entity be deleted, but
// that would touch too much code for me to do that right now.
pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity )
{
if ( g_pGameRules && !g_pGameRules->IsAllowedToSpawn( pEntity ) )
return -1; // return that this entity should be deleted
if ( pEntity->pev->flags & FL_KILLME )
return -1;
}
// Handle global stuff here
if ( pEntity && pEntity->pev->globalname )
{
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( pEntity->pev->globalname );
if ( pGlobal )
{
// Already dead? delete
if ( pGlobal->state == GLOBAL_DEAD )
return -1;
else if ( !FStrEq( STRING(gpGlobals->mapname), pGlobal->levelName ) )
pEntity->MakeDormant(); // Hasn't been moved to this level yet, wait but stay alive
// In this level & not dead, continue on as normal
}
else
{
// Spawned entities default to 'On'
gGlobalState.EntityAdd( pEntity->pev->globalname, gpGlobals->mapname, GLOBAL_ON );
// ALERT( at_console, "Added global entity %s (%s)\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->globalname) );
}
}
}
return 0;
}
void DispatchKeyValue( edict_t *pentKeyvalue, KeyValueData *pkvd )
{
if ( !pkvd || !pentKeyvalue )
return;
EntvarsKeyvalue( VARS(pentKeyvalue), pkvd );
// If the key was an entity variable, or there's no class set yet, don't look for the object, it may
// not exist yet.
if ( pkvd->fHandled || pkvd->szClassName == NULL )
return;
// Get the actualy entity object
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentKeyvalue);
if ( !pEntity )
return;
pEntity->KeyValue( pkvd );
}
// HACKHACK -- this is a hack to keep the node graph entity from "touching" things (like triggers)
// while it builds the graph
BOOL gTouchDisabled = FALSE;
void DispatchTouch( edict_t *pentTouched, edict_t *pentOther )
{
if ( gTouchDisabled )
return;
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentTouched);
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE( pentOther );
if ( pEntity && pOther && ! ((pEntity->pev->flags | pOther->pev->flags) & FL_KILLME) )
pEntity->Touch( pOther );
}
void DispatchUse( edict_t *pentUsed, edict_t *pentOther )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentUsed);
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE(pentOther);
if (pEntity && !(pEntity->pev->flags & FL_KILLME) )
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
}
void DispatchThink( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
if ( FBitSet( pEntity->pev->flags, FL_DORMANT ) )
ALERT( at_error, "Dormant entity %s is thinking!!\n", STRING(pEntity->pev->classname) );
pEntity->Think();
}
}
void DispatchBlocked( edict_t *pentBlocked, edict_t *pentOther )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE( pentBlocked );
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE( pentOther );
if (pEntity)
pEntity->Blocked( pOther );
}
void DispatchSave( edict_t *pent, SAVERESTOREDATA *pSaveData )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity && pSaveData )
{
ENTITYTABLE *pTable = &pSaveData->pTable[ pSaveData->currentIndex ];
if ( pTable->pent != pent )
ALERT( at_error, "ENTITY TABLE OR INDEX IS WRONG!!!!\n" );
if ( pEntity->ObjectCaps() & FCAP_DONT_SAVE )
return;
// These don't use ltime & nextthink as times really, but we'll fudge around it.
if ( pEntity->pev->movetype == MOVETYPE_PUSH )
{
float delta = pEntity->pev->nextthink - pEntity->pev->ltime;
pEntity->pev->ltime = gpGlobals->time;
pEntity->pev->nextthink = pEntity->pev->ltime + delta;
}
pTable->location = pSaveData->size; // Remember entity position for file I/O
pTable->classname = pEntity->pev->classname; // Remember entity class for respawn
CSave saveHelper( pSaveData );
pEntity->Save( saveHelper );
pTable->size = pSaveData->size - pTable->location; // Size of entity block is data size written to block
}
}
void OnFreeEntPrivateData(edict_s *pEdict)
{
if(pEdict && pEdict->pvPrivateData)
{
((CBaseEntity*)pEdict->pvPrivateData)->~CBaseEntity();
}
}
// Find the matching global entity. Spit out an error if the designer made entities of
// different classes with the same global name
CBaseEntity *FindGlobalEntity( string_t classname, string_t globalname )
{
edict_t *pent = FIND_ENTITY_BY_STRING( NULL, "globalname", STRING(globalname) );
CBaseEntity *pReturn = CBaseEntity::Instance( pent );
if ( pReturn )
{
if ( !FClassnameIs( pReturn->pev, STRING(classname) ) )
{
ALERT( at_console, "Global entity found %s, wrong class %s\n", STRING(globalname), STRING(pReturn->pev->classname) );
pReturn = NULL;
}
}
return pReturn;
}
int DispatchRestore( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity && pSaveData )
{
entvars_t tmpVars;
Vector oldOffset;
CRestore restoreHelper( pSaveData );
if ( globalEntity )
{
CRestore tmpRestore( pSaveData );
tmpRestore.PrecacheMode( 0 );
tmpRestore.ReadEntVars( "ENTVARS", &tmpVars );
// HACKHACK - reset the save pointers, we're going to restore for real this time
pSaveData->size = pSaveData->pTable[pSaveData->currentIndex].location;
pSaveData->pCurrentData = pSaveData->pBaseData + pSaveData->size;
// -------------------
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( tmpVars.globalname );
// Don't overlay any instance of the global that isn't the latest
// pSaveData->szCurrentMapName is the level this entity is coming from
// pGlobla->levelName is the last level the global entity was active in.
// If they aren't the same, then this global update is out of date.
if ( !FStrEq( pSaveData->szCurrentMapName, pGlobal->levelName ) )
return 0;
// Compute the new global offset
oldOffset = pSaveData->vecLandmarkOffset;
CBaseEntity *pNewEntity = FindGlobalEntity( tmpVars.classname, tmpVars.globalname );
if ( pNewEntity )
{
// ALERT( at_console, "Overlay %s with %s\n", STRING(pNewEntity->pev->classname), STRING(tmpVars.classname) );
// Tell the restore code we're overlaying a global entity from another level
restoreHelper.SetGlobalMode( 1 ); // Don't overwrite global fields
pSaveData->vecLandmarkOffset = (pSaveData->vecLandmarkOffset - pNewEntity->pev->mins) + tmpVars.mins;
pEntity = pNewEntity;// we're going to restore this data OVER the old entity
pent = ENT( pEntity->pev );
// Update the global table to say that the global definition of this entity should come from this level
gGlobalState.EntityUpdate( pEntity->pev->globalname, gpGlobals->mapname );
}
else
{
// This entity will be freed automatically by the engine. If we don't do a restore on a matching entity (below)
// or call EntityUpdate() to move it to this level, we haven't changed global state at all.
return 0;
}
}
if ( pEntity->ObjectCaps() & FCAP_MUST_SPAWN )
{
pEntity->Restore( restoreHelper );
pEntity->Spawn();
}
else
{
pEntity->Restore( restoreHelper );
pEntity->Precache( );
}
// Again, could be deleted, get the pointer again.
pEntity = (CBaseEntity *)GET_PRIVATE(pent);
#if 0
if ( pEntity && pEntity->pev->globalname && globalEntity )
{
ALERT( at_console, "Global %s is %s\n", STRING(pEntity->pev->globalname), STRING(pEntity->pev->model) );
}
#endif
// Is this an overriding global entity (coming over the transition), or one restoring in a level
if ( globalEntity )
{
// ALERT( at_console, "After: %f %f %f %s\n", pEntity->pev->origin.x, pEntity->pev->origin.y, pEntity->pev->origin.z, STRING(pEntity->pev->model) );
pSaveData->vecLandmarkOffset = oldOffset;
if ( pEntity )
{
UTIL_SetOrigin( pEntity->pev, pEntity->pev->origin );
pEntity->OverrideReset();
}
}
else if ( pEntity && pEntity->pev->globalname )
{
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( pEntity->pev->globalname );
if ( pGlobal )
{
// Already dead? delete
if ( pGlobal->state == GLOBAL_DEAD )
return -1;
else if ( !FStrEq( STRING(gpGlobals->mapname), pGlobal->levelName ) )
{
pEntity->MakeDormant(); // Hasn't been moved to this level yet, wait but stay alive
}
// In this level & not dead, continue on as normal
}
else
{
ALERT( at_error, "Global Entity %s (%s) not in table!!!\n", STRING(pEntity->pev->globalname), STRING(pEntity->pev->classname) );
// Spawned entities default to 'On'
gGlobalState.EntityAdd( pEntity->pev->globalname, gpGlobals->mapname, GLOBAL_ON );
}
}
}
return 0;
}
void DispatchObjectCollsionBox( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
pEntity->SetObjectCollisionBox();
}
else
SetObjectCollisionBox( &pent->v );
}
void SaveWriteFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount )
{
CSave saveHelper( pSaveData );
saveHelper.WriteFields( pname, pBaseData, pFields, fieldCount );
}
void SaveReadFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount )
{
CRestore restoreHelper( pSaveData );
restoreHelper.ReadFields( pname, pBaseData, pFields, fieldCount );
}
edict_t * EHANDLE::Get( void )
{
if (m_pent)
{
if (m_pent->serialnumber == m_serialnumber)
return m_pent;
else
return NULL;
}
return NULL;
};
edict_t * EHANDLE::Set( edict_t *pent )
{
m_pent = pent;
if (pent)
m_serialnumber = m_pent->serialnumber;
return pent;
};
EHANDLE :: operator CBaseEntity *()
{
return (CBaseEntity *)GET_PRIVATE( Get( ) );
};
CBaseEntity * EHANDLE :: operator = (CBaseEntity *pEntity)
{
if (pEntity)
{
m_pent = ENT( pEntity->pev );
if (m_pent)
m_serialnumber = m_pent->serialnumber;
}
else
{
m_pent = NULL;
m_serialnumber = 0;
}
return pEntity;
}
EHANDLE :: operator int ()
{
return Get() != NULL;
}
CBaseEntity * EHANDLE :: operator -> ()
{
return (CBaseEntity *)GET_PRIVATE( Get( ) );
}
// give health
int CBaseEntity :: TakeHealth( float flHealth, int bitsDamageType )
{
if (!pev->takedamage)
return 0;
// heal
if ( pev->health >= pev->max_health )
return 0;
pev->health += flHealth;
if (pev->health > pev->max_health)
pev->health = pev->max_health;
return 1;
}
// inflict damage on this entity. bitsDamageType indicates type of damage inflicted, ie: DMG_CRUSH
int CBaseEntity :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
Vector vecTemp;
if (!pev->takedamage)
return 0;
// UNDONE: some entity types may be immune or resistant to some bitsDamageType
// if Attacker == Inflictor, the attack was a melee or other instant-hit attack.
// (that is, no actual entity projectile was involved in the attack so use the shooter's origin).
if ( pevAttacker == pevInflictor )
{
vecTemp = pevInflictor->origin - ( VecBModelOrigin(pev) );
}
else
// an actual missile was involved.
{
vecTemp = pevInflictor->origin - ( VecBModelOrigin(pev) );
}
// this global is still used for glass and other non-monster killables, along with decals.
g_vecAttackDir = vecTemp.Normalize();
// save damage based on the target's armor level
// figure momentum add (don't let hurt brushes or other triggers move player)
if ((!FNullEnt(pevInflictor)) && (pev->movetype == MOVETYPE_WALK || pev->movetype == MOVETYPE_STEP) && (pevAttacker->solid != SOLID_TRIGGER) )
{
Vector vecDir = pev->origin - (pevInflictor->absmin + pevInflictor->absmax) * 0.5;
vecDir = vecDir.Normalize();
float flForce = flDamage * ((32 * 32 * 72.0) / (pev->size.x * pev->size.y * pev->size.z)) * 5;
if (flForce > 1000.0)
flForce = 1000.0;
pev->velocity = pev->velocity + vecDir * flForce;
}
// do the damage
pev->health -= flDamage;
if (pev->health <= 0)
{
Killed( pevAttacker, GIB_NORMAL );
return 0;
}
return 1;
}
void CBaseEntity :: Killed( entvars_t *pevAttacker, int iGib )
{
pev->takedamage = DAMAGE_NO;
pev->deadflag = DEAD_DEAD;
UTIL_Remove( this );
}
CBaseEntity *CBaseEntity::GetNextTarget( void )
{
if ( FStringNull( pev->target ) )
return NULL;
edict_t *pTarget = FIND_ENTITY_BY_TARGETNAME ( NULL, STRING(pev->target) );
if ( FNullEnt(pTarget) )
return NULL;
return Instance( pTarget );
}
// Global Savedata for Delay
TYPEDESCRIPTION CBaseEntity::m_SaveData[] =
{
DEFINE_FIELD( CBaseEntity, m_pGoalEnt, FIELD_CLASSPTR ),
DEFINE_FIELD( CBaseEntity, m_pfnThink, FIELD_FUNCTION ), // UNDONE: Build table of these!!!
DEFINE_FIELD( CBaseEntity, m_pfnTouch, FIELD_FUNCTION ),
DEFINE_FIELD( CBaseEntity, m_pfnUse, FIELD_FUNCTION ),
DEFINE_FIELD( CBaseEntity, m_pfnBlocked, FIELD_FUNCTION ),
};
int CBaseEntity::Save( CSave &save )
{
if ( save.WriteEntVars( "ENTVARS", pev ) )
return save.WriteFields( "BASE", this, m_SaveData, ARRAYSIZE(m_SaveData) );
return 0;
}
int CBaseEntity::Restore( CRestore &restore )
{
int status;
status = restore.ReadEntVars( "ENTVARS", pev );
if ( status )
status = restore.ReadFields( "BASE", this, m_SaveData, ARRAYSIZE(m_SaveData) );
if ( pev->modelindex != 0 && !FStringNull(pev->model) )
{
Vector mins, maxs;
mins = pev->mins; // Set model is about to destroy these
maxs = pev->maxs;
PRECACHE_MODEL( (char *)STRING(pev->model) );
SET_MODEL(ENT(pev), STRING(pev->model));
UTIL_SetSize(pev, mins, maxs); // Reset them
}
return status;
}
// Initialize absmin & absmax to the appropriate box
void SetObjectCollisionBox( entvars_t *pev )
{
if ( (pev->solid == SOLID_BSP) &&
(pev->angles.x || pev->angles.y|| pev->angles.z) )
{ // expand for rotation
float max, v;
int i;
max = 0;
for (i=0 ; i<3 ; i++)
{
v = fabs( pev->mins[i]);
if (v > max)
max = v;
v = fabs( pev->maxs[i]);
if (v > max)
max = v;
}
for (i=0 ; i<3 ; i++)
{
pev->absmin[i] = pev->origin[i] - max;
pev->absmax[i] = pev->origin[i] + max;
}
}
else
{
pev->absmin = pev->origin + pev->mins;
pev->absmax = pev->origin + pev->maxs;
}
pev->absmin.x -= 1;
pev->absmin.y -= 1;
pev->absmin.z -= 1;
pev->absmax.x += 1;
pev->absmax.y += 1;
pev->absmax.z += 1;
}
void CBaseEntity::SetObjectCollisionBox( void )
{
::SetObjectCollisionBox( pev );
}
int CBaseEntity :: Intersects( CBaseEntity *pOther )
{
if ( pOther->pev->absmin.x > pev->absmax.x ||
pOther->pev->absmin.y > pev->absmax.y ||
pOther->pev->absmin.z > pev->absmax.z ||
pOther->pev->absmax.x < pev->absmin.x ||
pOther->pev->absmax.y < pev->absmin.y ||
pOther->pev->absmax.z < pev->absmin.z )
return 0;
return 1;
}
void CBaseEntity :: MakeDormant( void )
{
SetBits( pev->flags, FL_DORMANT );
// Don't touch
pev->solid = SOLID_NOT;
// Don't move
pev->movetype = MOVETYPE_NONE;
// Don't draw
SetBits( pev->effects, EF_NODRAW );
// Don't think
pev->nextthink = 0;
// Relink
UTIL_SetOrigin( pev, pev->origin );
}
int CBaseEntity :: IsDormant( void )
{
return FBitSet( pev->flags, FL_DORMANT );
}
BOOL CBaseEntity :: IsInWorld( void )
{
// position
if (pev->origin.x >= 4096) return FALSE;
if (pev->origin.y >= 4096) return FALSE;
if (pev->origin.z >= 4096) return FALSE;
if (pev->origin.x <= -4096) return FALSE;
if (pev->origin.y <= -4096) return FALSE;
if (pev->origin.z <= -4096) return FALSE;
// speed
if (pev->velocity.x >= 2000) return FALSE;
if (pev->velocity.y >= 2000) return FALSE;
if (pev->velocity.z >= 2000) return FALSE;
if (pev->velocity.x <= -2000) return FALSE;
if (pev->velocity.y <= -2000) return FALSE;
if (pev->velocity.z <= -2000) return FALSE;
return TRUE;
}
int CBaseEntity::ShouldToggle( USE_TYPE useType, BOOL currentState )
{
if ( useType != USE_TOGGLE && useType != USE_SET )
{
if ( (currentState && useType == USE_ON) || (!currentState && useType == USE_OFF) )
return 0;
}
return 1;
}
int CBaseEntity :: DamageDecal( int bitsDamageType )
{
if ( pev->rendermode == kRenderTransAlpha )
return -1;
if ( pev->rendermode != kRenderNormal )
return DECAL_BPROOF1;
return DECAL_GUNSHOT1 + RANDOM_LONG(0,4);
}
// NOTE: szName must be a pointer to constant memory, e.g. "monster_class" because the entity
// will keep a pointer to it after this call.
CBaseEntity * CBaseEntity::Create( char *szName, const Vector &vecOrigin, const Vector &vecAngles, edict_t *pentOwner )
{
edict_t *pent;
CBaseEntity *pEntity;
pent = CREATE_NAMED_ENTITY( MAKE_STRING( szName ));
if ( FNullEnt( pent ) )
{
ALERT ( at_console, "NULL Ent in Create!\n" );
return NULL;
}
pEntity = Instance( pent );
pEntity->pev->owner = pentOwner;
pEntity->pev->origin = vecOrigin;
pEntity->pev->angles = vecAngles;
DispatchSpawn( pEntity->edict() );
return pEntity;
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
] | [
[
[
1,
796
]
]
] |
97a87bf26a479581b5a8d0e2afc2951dcc035a2c | 1584e139552d36bbbcc461deb81c22a06d42b713 | /server/server.h | 5afbae64f5a8235f852232eaefd5d0fc5a8ffbcd | [] | no_license | joshmg/battle | fd458da8be387ff0b4f80f0d2029759cd3fabe30 | 14ab71d903fe0bcf7c3285169026b4f96a186309 | refs/heads/master | 2020-05-18T17:20:00.768647 | 2010-09-28T04:34:34 | 2010-09-28T04:34:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,395 | h | // File: server.h
// Written by Joshua Green
#ifndef SERVER_H
#define SERVER_H
#include "../shared/character.h"
#include "../shared/connection/connection.h"
#include "../shared/str/str.h"
#include <string>
#include <vector>
#include <map>
#include <ctime>
class server;
void recv_branch(void*);
void disc_branch(void*);
struct ping_data;
class server {
private:
static int SERVER_COUNT;
int _id;
std::map<std::string, void (*)(int, int, std::string&)> _actions;
std::map<int, p2p*> _connections;
std::map<int, character*> _characters;
std::map<int, ping_data> _pings;
bool _shutting_down;
bool _battle_server;
public:
server();
~server();
int size() const;
void shutdown(int);
bool is_shutting_down();
int id();
void add_action(const std::string&, void (*)(int, int, std::string&));
void add_connection(p2p*); // Adds the connection to the server's connection list.
// Transmits the new server code to the connection.
// Transmits the new id to the conneciton.
// Creates a new ping within the server's ping list.
void remove_connection(int, bool close_connection=true); // Removes the connection from the server's connection list,
// if close_connection is true (default) the connection is
// closed.
// If the server is a battle server, a message is transmitted
// to the other connections, reporting the connection removal.
// Removes the connection's ping from the server's ping list.
bool has_connection_id(int);
p2p* get_connection(int) const;
void recv(int, std::string&, std::string&);
void add_character(int, character*); // Adds the character to the server's character list.
// If the character's ID existed previously, the old pointer is deleted.
// Loads the character's darkmatter from the database (invokes character
// class's member function: load_dmatter())
void remove_character(int, bool deallocate_mem=true); // Removes the character from the server's character list,
// if deallocate_mem is true (default) the character (and
// its dark matter) is erased from memory.
character* get_character(int) const; // Returns the pointer to the character referenced by id.
// If the id does not have an associated character, 0 is returned.
std::map<int, character*> get_char_map();
void change_client_id(int old_id, int new_id); // Changes all of the necessary associations from one id to another.
// Informs the client of the change (updates server code and toon id).
std::multimap<int, darkmatter*> available_dmatter; // <database class id, darkmatter*>
void operator++(int);
void ping(int);
time_t pong(int);
void enable_battle(bool=true);
bool is_battle_server() const;
void save(int toon_id=-1) const;
};
struct ping_data {
time_t send_t;
time_t recv_t;
ping_data() {
send_t = 0;
recv_t = 0;
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
94
]
]
] |
03d7acfa443591183633f4bc2229dd83aa618ff4 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SESceneGraph/SEBoxBV.h | 01b8fe5959d16749a549f052a50ae95b551e5087 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,230 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_BoxBV_H
#define Swing_BoxBV_H
#include "SEFoundationLIB.h"
#include "SEPlatforms.h"
#include "SEBoundingVolume.h"
#include "SEBox3.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20080330
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEBoxBV : public SEBoundingVolume
{
SE_DECLARE_RTTI;
SE_DECLARE_NAME_ID;
SE_DECLARE_STREAM;
public:
SEBoxBV(void); // center(0,0,0), axes(1,0,0),(0,1,0),(0,0,1), extents 1,1,1
SEBoxBV(const SEBox3f& rBox);
virtual ~SEBoxBV(void);
virtual int GetBVType(void) const;
// 所有BV都要定义中点和半径.
virtual void SetCenter(const SEVector3f& rCenter);
virtual SEVector3f GetCenter(void) const;
virtual void SetRadius(float fRadius);
virtual float GetRadius(void) const;
inline SEBox3f& Box(void);
inline const SEBox3f& GetBox(void) const;
// 根据传入顶点集合创建BV.
virtual void ComputeFromData(const SEVector3fArray* pVertices);
virtual void ComputeFromData(const SEVertexBuffer* pVBuffer);
// 变换BV(从模型空间到世界空间).
virtual void TransformBy(const SETransformation& rTransform,
SEBoundingVolume* pResult);
// 判断BV是否在平面正半空间(平面法线所指向的空间),相交,负半空间,
// 相应的返回值为+1,0,-1.
virtual int OnWhichSide(const SEPlane3f& rPlane) const;
// 测试BV是否和射线相交,不计算交点,射线方向必须为单位向量.
virtual bool TestIntersection(const SERay3f& rRay) const;
// 测试是否和另一个BV相交.
virtual bool TestIntersection(const SEBoundingVolume* pInput) const;
// 用另一个BV复制出自己.
virtual void CopyFrom(const SEBoundingVolume* pInput);
// 当前BV增长,包含传入的BV和之前的自己.
virtual void GrowToContain(const SEBoundingVolume* pInput);
// 是否包含传入点.
virtual bool Contains(const SEVector3f& rPoint) const;
protected:
SEBox3f m_Box;
};
#include "SEBoxBV.inl"
typedef SESmartPointer<SEBoxBV> SEBoxBVPtr;
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
96
]
]
] |
6b64b9b21c6a1f5507cd731008908efb1be0f462 | 90c0655f3ad1e3ce9f0822eda11bd6be58a29f57 | /src/Simulador.cpp | 81de69216faf9b31a6bba204dd72723a26e9c202 | [] | no_license | rocanaan/proj-aguiar-2011 | 46cb8f68f6701bd7f499f21687ce8d0e3d6d111a | fcb13adcca01c1472c53caffe22c0f3ebafe9a10 | refs/heads/master | 2021-01-01T16:39:05.692522 | 2011-07-05T03:31:41 | 2011-07-05T03:31:41 | 34,010,824 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 27,549 | cpp | ///////////////////////////////////////////////////////
/*
Avaliação e Desempenho
Trabalho de Simulação
Alunos:
Luiz Filipe de Sá Estrella DRE: 107390627
Fernando de Mesentier Silva DRE: 107390520
Rodrigo de Moura Canaan DRE: 107362200
Vinicius José Serva Pereira DRE: 106050355
*/
///////////////////////////////////////////////////////
#include "include\Simulador.h"
#include <math.h>
#define FILA_1 1
#define FILA_2 2
#define INTERROMPIDO 1
#define N_INTERROMPIDO 0
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-----------------------------------Contrutores & Destrutor-----------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Simulador::Simulador(double ptaxa_chegada, double ptaxa_servico, bool deterministico, bool dois_por_vez, bool interrupcao_forcada, int semente)
{
/*
No modo "dois por vez" e de "interrupção forçada", trabalhamos com
metade da taxa de chegada fornecida pelo usuário. Assim mantemos a taxa efetiva igual a que foi dada
*/
if(dois_por_vez or interrupcao_forcada)
taxa_chegada = ptaxa_chegada/2;
else
taxa_chegada = ptaxa_chegada;
taxa_servico = ptaxa_servico;
Setup(semente, deterministico);
acumulaW1 = 0.0;
acumulaT1 = 0.0;
acumulaW2 = 0.0;
acumulaT2 = 0.0;
acumula_quadradoW1 = 0.0;
acumula_quadradoW2 = 0.0;
/*
Inicia as variáveis que acumulam o (numero de pessoas * tempo) de cada região do sistema
*/
Nq1_parcial = 0.0;
Nq2_parcial = 0.0;
N1_parcial = 0.0;
N2_parcial = 0.0;
}
Simulador::Simulador()
{
}
Simulador::~Simulador()
{
//Destrutor
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------Funções Membro-------------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Função principal do simulador, executa a simulação.
*/
void Simulador::Roda(int num_clientes_por_rodada, int rodada_atual, bool debug, bool deterministico, bool determina_transiente, bool dois_por_vez, string nome_pasta, bool guardar_estatisticas, bool interrupcao_forcada, bool mostrar_resultados)
{
int num_servicos_tipo_1_rodada_atual = 0;
int num_servicos_tipo_2_rodada_atual = 0;
double tempo_inicio_rodada = tempo_atual;
if(dois_por_vez)
{
cout << "Rodando em modo dois por vez" << endl;
}
/*
Loop principal do simulador.
Enquanto o número total de clientes que queremos servir for maior que o número de clientes já servidos por completo, rodamos a simulação
*/
while(num_clientes_por_rodada > num_servicos_tipo_2_rodada_atual)
{
/*
O primeiro evento é selecionado
*/
Evento evento_atual = filaEventos.top();
/*
Ele é retirado da Fila
*/
filaEventos.pop();
double tempo_desde_evento_anterior = evento_atual.GetTempoAcontecimento()-tempo_atual;
tempo_atual=evento_atual.GetTempoAcontecimento();
if(debug)
{
cout << endl << "Evento sendo tratado: Evento do tipo " << evento_atual.GetNome() << " no instante " << tempo_atual << endl;
cout << "A fila de Eventos tem tamanho " << filaEventos.size() << " apos remover o evento atual" << endl;
cout << "Status do sistema (antes de resolver o evento):" << endl;
if(servidor_vazio)
cout << " O servidor esta vazio" << endl;
else
cout << " O cliente numero " << cliente_em_servico.GetID() << " esta em servico, vindo da fila " << cliente_em_servico.GetFila() <<endl;
cout << " Numero de pessoas na fila 1: " << fila1.size() << endl;
cout << " Numero de pessoas na fila 2: " << fila2.size() << endl;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////COLETA DE DADOS/////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
/* Para cada uma das variaveis Nq1, Nq2, N1 e N2,
calcula a "area sob a curva" desde o ultimo evento, multiplicando
o valor da variavel pelo tamanho do intervalo entre o evento anterior
e o evento atual.
Como entre eventos nada muda no servidor, cada uma dessas variaveis
permaneceu constante
Nq1 e Nq2 sao o numero de pessoas nas filas de espera 1 e 2, respectivamente
N1 e N2 sao o numero de pessoas esperando cada tipo de servico na fila
Ni = Nqi + 1 se houver um cliente vindo da fila i no servidor
Ni = Nqi caso contrario
No final da simulacao, teremos a área sob a curva de cada uma dessas variaveis.
Faltara dividir pelo tempo total decorrido para calcular a media.
*/
if (rodada_atual != 0)
{
Nq1_parcial += fila1.size()*tempo_desde_evento_anterior;
Nq2_parcial += fila2.size()*tempo_desde_evento_anterior;
if (!servidor_vazio)
{
if (cliente_em_servico.GetFila() == 1)
{
N1_parcial += (1+fila1.size())*tempo_desde_evento_anterior;
N2_parcial += fila2.size()*tempo_desde_evento_anterior;
}
else
{
N1_parcial += fila1.size()*tempo_desde_evento_anterior;
N2_parcial += (1+fila2.size())*tempo_desde_evento_anterior;
}
}
else
{
N1_parcial += fila1.size()*tempo_desde_evento_anterior;
N2_parcial += fila2.size()*tempo_desde_evento_anterior;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////FIM DA COLETA DE DADOS//////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Tratamos aqui o evento do tipo nova chegada.
Se o caso deterministico interrupcao_forcada estiver ligado também temos a possibilidade de entrar no condicional com uma chegada_artificial
*/
if(evento_atual.GetTipo() == nova_chegada or evento_atual.GetTipo() == chegada_artificial)
{
/*
Condição para tratar a interrupção presente no sistema.
Se o servidor estiver ocupado e este cliente for da fila 2 então o cliente que acabou de chegar irá interromper este serviço
*/
if(!servidor_vazio && cliente_em_servico.GetFila() == FILA_2)
{
Evento evento_destruido = filaEventos.top();
/*
No caso de interrupcao_forcada, é necessário realizar o método RemoveTerminoServico() para remover o evento correto,
pois não temos garantia de que o evento a ser removido é o do topo, pois pode haver mais de um evento de chega
na heap por vez.
*/
if(interrupcao_forcada){
evento_destruido = RemoveTerminoServico();
if(debug)
{
cout << " Evento sendo destruido: : Evento do tipo " << evento_destruido.GetNome() << " marcado para o instante " << evento_destruido.GetTempoAcontecimento()<< endl;
}
}
else{
/*
Remove o Evento de Término de serviço gerado por este cliente da fila 2.
Como no modo de execução normal guardamos apenas um evento de chegada e um de término de serviço
por vez na fila de enventos, e a chegada atual já foi removida nesse ponto de execução
do programa, mas a próxima chegada ainda não foi adicionada, podemos garantir que o
evento de término de serviço que devemos cancelar vai estar no topo da heap.
*/
filaEventos.pop();
if(debug)
{
cout << " Evento sendo destruido: : Evento do tipo " << evento_destruido.GetTipo() << " marcado para o instante " << evento_destruido.GetTempoAcontecimento()<< endl;
}
}
/*
Marca o cliente como sendo um cliente Interrompido
*/
cliente_em_servico.Interromper();
/*
O tempo restante para finalizar seu servico é guardado
*/
cliente_em_servico.SetTempoRestante(evento_destruido.GetTempoAcontecimento() - tempo_atual);
/*
Cliente que foi interrompido volta a ser o primeiro da fila 2.
*/
fila2.push_front(cliente_em_servico);
/*
Deixa o servidor vazio
*/
servidor_vazio = true;
}
/*
O novo cliente começa na fila 1
*/
Cliente cliente_atual = Cliente(id_proximo_cliente,tempo_atual,FILA_1, rodada_atual);
if(servidor_vazio)
{
cliente_atual.SetDiretoAoServidor(true);
}
id_proximo_cliente++;
/*
Coloca o novo cliente na fila 1
*/
fila1.push(cliente_atual);
if(evento_atual.GetTipo() == nova_chegada)
{
Evento proxChegada = Evento(nova_chegada,tempo_atual+gerador->GeraTempoExponencial(taxa_chegada, deterministico));//Agenda o Evento para a próxima chegada
filaEventos.push(proxChegada);
if(debug)
{
cout << " Agendando proxima chegada para o instante " << proxChegada.GetTempoAcontecimento() << endl;
}
}
if(debug)
{
cout << " Inserindo o cliente " << cliente_atual.GetID() << " na fila 1" << endl;
}
if(dois_por_vez and evento_atual.GetTipo() == nova_chegada)
{
Evento artificial = Evento(chegada_artificial,tempo_atual);
filaEventos.push(artificial);
if(debug)
{
cout << " Agendando chegada artificial para o instante " << artificial.GetTempoAcontecimento() << endl;
}
}
if(interrupcao_forcada and evento_atual.GetTipo() == nova_chegada)
{
Evento artificial = Evento(chegada_artificial,tempo_atual+gerador->GeraTempoExponencial(taxa_servico*2/3, deterministico));
filaEventos.push(artificial);
if(debug)
{
cout << " Agendando chegada artificial para o instante " << artificial.GetTempoAcontecimento() << endl;
}
}
}//Se o Evento, que está sendo tratado no momento, for do termino_de_servico
else if (evento_atual.GetTipo() == termino_de_servico)
{
if(cliente_em_servico.GetFila() == FILA_1)
{
cliente_em_servico.SetFila(FILA_2);//O cliente que irá terminar o serviço agora é definido como da fila 2
cliente_em_servico.SetInstanteChegada2(tempo_atual);
fila2.push_back(cliente_em_servico);// Coloca o cliente na fila 2
//Se a fila 2 só tem o próprio cliente e não tem ninguem em serviço, quer dizer que o cliente da fila 2 será atendido direto
if(fila2.size() == 1 && fila1.empty())
fila2.back().SetDiretoAoServidor(true);
else
fila2.back().SetDiretoAoServidor(false);
if(debug)
{
cout << " Fim de servico na fila 1. Inserindo cliente " << cliente_em_servico.GetID() << " na fila 2" << endl;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////COLETA DE DADOS/////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Verifica se o cliente em serviço é da rodada(coloração usada) em que estamos, pois só esse cliente entra nos dados desta rodada
*/
if((cliente_em_servico.GetRodadaPertencente() == rodada_atual or determina_transiente) and rodada_atual != 0)
{
if(!cliente_em_servico.GetDiretoAoServidor())
cliente_W1 = cliente_em_servico.W1();
else
cliente_W1 = 0;
acumulaW1 += cliente_W1;
acumulaT1 += cliente_em_servico.T1();
acumula_quadradoW1 += cliente_W1*cliente_W1;
if(debug)
{
cout << " Dados do cliente " << cliente_em_servico.GetID() << ": W1 = " << cliente_W1 << ", T1 = " << cliente_em_servico.T1() << endl;
}
num_servicos_tipo_1_rodada_atual ++;
total_clientes_servidos_uma_vez ++;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////FIM DA COLETA DE DADOS//////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
//Acabou os 2 serviços do cliente, logo marcamos mais um cliente servido totalmente
if(debug)
{
cout <<" Fim de servico na fila 2. Removendo cliente " << cliente_em_servico.GetID() << " do sistema" << endl;
}
cliente_em_servico.SetInstanteSaida(tempo_atual);
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////COLETA DE DADOS/////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
//Verifica se o cliente em serviço é da rodada(coloração usada) em que estamos, pois só esse cliente entra nos dados desta rodada
if((cliente_em_servico.GetRodadaPertencente() == rodada_atual or determina_transiente) and rodada_atual != 0)
{
total_clientes_servidos_duas_vezes ++;
num_servicos_tipo_2_rodada_atual ++;
if(cliente_em_servico.VerificaInterrompido() == N_INTERROMPIDO && cliente_em_servico.GetDiretoAoServidor())
cliente_W2 = 0;
else
cliente_W2 = cliente_em_servico.W2();
acumulaW2 += cliente_W2;
acumulaT2 += cliente_em_servico.T2();
acumula_quadradoW2 += cliente_W2*cliente_W2;
if(debug)
{
cout << " Dados do cliente " << cliente_em_servico.GetID() << ": W2 = " << cliente_W2 << ", T2 = " << cliente_em_servico.T2() << endl;
}
}
if(rodada_atual == 0)
num_servicos_tipo_2_rodada_atual ++;
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////FIM DA COLETA DE DADOS//////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
//
servidor_vazio = true;//Como alguem foi servido marcamos o servidor como vazio
}
/*
Se não tem ninguem no servidor
*/
if(servidor_vazio == true )
{
//Fila 1 tem prioridade
if(!fila1.empty())
{
cliente_em_servico = fila1.front();//O primeiro cliente da fila 1 entra em servico
fila1.pop();//O cliente é removido da fila 1
servidor_vazio = false;//O servidor agora está ocupado
double duracao = gerador->GeraTempoExponencial(taxa_servico, deterministico);
Evento proxTerminoServico = Evento(termino_de_servico,tempo_atual+duracao);//Agendar evento de termino de servico
filaEventos.push(proxTerminoServico);
cliente_em_servico.SetDuracaoPrimeiroServico(duracao);
if(debug)
{
cout << " Transferindo cliente " << cliente_em_servico.GetID() << " da fila 1 para o servidor." << endl;
cout << " Agendando termino do primeiro servico do cliente " << cliente_em_servico.GetID() <<" para o instante " << proxTerminoServico.GetTempoAcontecimento() << endl;;
}
}
else if(!fila2.empty())
{
cliente_em_servico = fila2.front();
fila2.pop_front();
servidor_vazio = false;
//Se o cliente, que veio da fila 2, não foi interrompido, gere para ele o seu tempo de serviço
if(cliente_em_servico.VerificaInterrompido() == N_INTERROMPIDO)
{
double duracao = gerador->GeraTempoExponencial(taxa_servico,deterministico);
Evento proxTerminoServico = Evento(termino_de_servico,tempo_atual+duracao);//Agenda evento de termino de servico
filaEventos.push(proxTerminoServico);
cliente_em_servico.SetDuracaoSegundoServico(duracao);
if(debug)
{
cout << " Transferindo cliente " << cliente_em_servico.GetID() << " da fila 2 para o servidor." << endl;
cout << " Agendando termino do segundo servico do cliente " << cliente_em_servico.GetID() << " para o instante " << proxTerminoServico.GetTempoAcontecimento() << endl;
}
}
else
{
Evento proxTerminoServico = Evento(termino_de_servico,tempo_atual+cliente_em_servico.GetTempoRestante());//Agenda evento de termino de servico, com o tempo restante de servico do cliente que foi interrompido
filaEventos.push(proxTerminoServico);
if(debug)
{
cout << " Inserindo cliente " << cliente_em_servico.GetID() << " da fila 2 no servidor. Este cliente ja foi interrompido alguma vez." << endl;
cout << " Agendando termino do segundo servico do cliente " << cliente_em_servico.GetID() << " para " << proxTerminoServico.GetTempoAcontecimento() << endl;
}
}
}
}
if(debug)
cout << "A fila de Eventos tem tamanho " << filaEventos.size() << endl;
}
if( rodada_atual != 0)
{
if(!determina_transiente)
{
CalculaResultados(num_servicos_tipo_2_rodada_atual, num_servicos_tipo_1_rodada_atual, tempo_atual - tempo_inicio_rodada, rodada_atual, mostrar_resultados, nome_pasta, guardar_estatisticas);
}
else
{
CalculaResultados(total_clientes_servidos_duas_vezes, total_clientes_servidos_uma_vez, tempo_atual, rodada_atual, mostrar_resultados, nome_pasta, guardar_estatisticas);
}
}
}
void Simulador::CalculaResultados(int n, int servidos1, double t, int rodada, bool mostrar_resultados, string nome_pasta, bool guardar_estatisticas)
{
/*
Divide cada uma das variaveis de fila Nq1, Nq2, N1 e N2 pelo tempo da rodada
para obter a media de cada uma delas
*/
E_Nq1.push_back(Nq1_parcial/t);
E_Nq2.push_back(Nq2_parcial/t);
E_N1.push_back(N1_parcial/t);
E_N2.push_back(N2_parcial/t);
/*
Divide cada um dos acumuladores dos clientes pelo numero de clientes servidos
*/
double EW1 = acumulaW1/servidos1;
double ET1 = acumulaT1/servidos1;
double EW2 = acumulaW2/n;
double ET2 = acumulaT2/n;
E_W1.push_back(EW1);
E_T1.push_back(ET1);
E_W2.push_back(EW2);
E_T2.push_back(ET2);
/*
O estimador da variância é dado por (1/(n-1)) * somatório de ( ( Xi - Xmédio)^2) para cada amostra i, se forem feitas n amostras
mas
somatório de ( ( Xi - Xmédio)^2) para cada amostra i =
somatório de ( ( Xi^2 - 2Xi*Xmédio + Xmedio^2)) para cada amostra i
passando o somatório para dentro, temos
somatório de ( Xi^2) para cada amostra i - 2* somatório de ( Xi*Xmedio) para cada amostra i + somatório de (Xmédio)^2) para cada amostra i
= acumula_quadradoX - 2*acumulaX*E[X] + n*E[X]^2
mas E[X] = acumulaX/n, logo -2*acumulaX*E[X] = -2*E(X)^2*n
e (numero de amostras)*E[X]^2 = acumulaX^2/n
Assim, V(X) = (acumula_quadradoX - 2*acumulaX^2/n + acumulaX^2/n) * 1/(n-1)
V(X) = (aumula_quadradoX - acumulaX^2/n) * 1/(n-1)
para X = W1 ou X = W2
*/
V_W1.push_back((acumula_quadradoW1 - EW1*EW1*servidos1)/(servidos1-1));
V_W2.push_back((acumula_quadradoW2 - EW2*EW2*n)/(n-1));
if(mostrar_resultados)
{
cout << endl <<endl << endl << "Imprimindo resultados da rodada "<< rodada <<" :"<< endl;
cout << " E[W1] = " << E_W1.back() << endl;
cout << " E[T1] = " << E_T1.back() << endl;
cout << " V[W1] = " << V_W1.back() << endl;
cout << " E[Nq1] = " << E_Nq1.back() << endl;
cout << " E[N1] = " << E_N1.back() << endl << endl;
cout << " E[W2] = " << E_W2.back() << endl;
cout << " E[T2] = " << E_T2.back() << endl;
cout << " V[W2] = " << V_W2.back() << endl;
cout << " E[Nq2] = " << E_Nq2.back() << endl;
cout << " E[N2] = " << E_N2.back() << endl;
}
if(guardar_estatisticas)
GeraDadosGrafico(rodada, E_N1.back(), E_N2.back(), E_Nq1.back(), E_Nq2.back(), E_W1.back(), E_W2.back(), E_T1.back(), E_T2.back(), V_W1.back(),V_W2.back(), nome_pasta);
}
/*
Limpa os resultados da rodada guardados pelo simulador.
Deve ser usada entre as rodadas para garantir que só consideramos
em cada rodada dados que tem origem em clientes daquela rodada
*/
void Simulador::LimpaResultadosParciais()
{
acumulaW1 = 0.0;
acumulaT1 = 0.0;
acumulaW2 = 0.0;
acumulaT2 = 0.0;
Nq1_parcial = 0.0;
Nq2_parcial = 0.0;
N1_parcial = 0.0;
N2_parcial = 0.0;
acumula_quadradoW1 = 0.0;
acumula_quadradoW2 = 0.0;
}
void Simulador::Setup(int semente, bool deterministico)
{
total_clientes_servidos_uma_vez =0;
total_clientes_servidos_duas_vezes = 0;
gerador = GeradorTempoExponencial::GetInstancia();
/*
Se definimos alguma semente, então usar ela no gerador
*/
if (semente > 0)
gerador->DefinirSemente(semente);
servidor_vazio = true;
id_proximo_cliente = 0;
tempo_atual = 0.0;
/*
Limpa a heap de eventos, as filas e os dados
*/
while(!filaEventos.empty()) filaEventos.pop();
while(!fila1.empty()) fila1.pop();
fila2.clear();
while(!E_N1.empty()) E_N1.pop_back();
while(!E_N2.empty()) E_N2.pop_back();
while(!E_Nq1.empty()) E_Nq1.pop_back();
while(!E_Nq2.empty()) E_Nq2.pop_back();
while(!E_W1.empty()) E_W1.pop_back();
while(!E_W2.empty()) E_W2.pop_back();
while(!E_T1.empty()) E_T1.pop_back();
while(!E_T2.empty()) E_T2.pop_back();
while(!E_T1.empty()) E_T1.pop_back();
while(!E_T2.empty()) E_T2.pop_back();
while(!V_W1.empty()) V_W1.pop_back();
while(!V_W2.empty()) V_W2.pop_back();
/*
Coloca o primeiro evendo na "heap" de eventos
*/
filaEventos.push(Evento(nova_chegada,gerador->GeraTempoExponencial(taxa_chegada, deterministico)));
}
void Simulador::GeraDadosGrafico(int rodada, double pN1, double pN2, double pNq1, double pNq2, double pW1, double pW2, double pT1, double pT2, double pV_W1, double pV_W2, string nome_pasta)
{
ofstream outputFile;
string temp_pasta = nome_pasta;
nome_pasta.append("/N1.txt");
char *arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pN1 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/N2.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pN2 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/Nq1.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pNq1 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/Nq2.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pNq2 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/W1.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pW1 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/W2.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pW2 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/T1.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pT1 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/T2.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pT2 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/V_W1.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pV_W1 << endl;
outputFile.close();
nome_pasta = temp_pasta;
nome_pasta.append("/V_W2.txt");
arquivo = (char*)nome_pasta.c_str();
outputFile.open(arquivo, ios::app);
outputFile << rodada <<"\t"<< pV_W2 << endl;
outputFile.close();
}
/*
Essa função é necessária para remover eventos de término de serviço da fila de eventos
quando rodamos o programa no modo "dois por vez", pois nesse modo não temos garantia
que o serviço a ser destruído está no topo da fila de eventos, mas sabemos que é o único
evento do tipo "termino de servico" na fila.
Essa funçao varre a fila (remove o primeiro elemento e guarda numa fila temporária)
até encontrar o evento de término de serviço, então deleta esse evento e insere ordenadamente
os eventos removidos até ali, exceto o que realmente deveria ter sido removido
*/
Evento Simulador::RemoveTerminoServico(){
priority_queue<Evento, vector<Evento>, greater<Evento> > filaTemp;
Evento topo = filaEventos.top();
while(topo.GetTipo() != termino_de_servico){
cout << "oi" << endl;
filaTemp.push(filaEventos.top());
filaEventos.pop();
topo = filaEventos.top();
}
filaEventos.pop();
while(!filaTemp.empty()){
filaEventos.push(filaTemp.top());
filaTemp.pop();
}
return topo;
}
vector<double> Simulador::GetE_Nq1()
{
return E_Nq1;
}
vector<double> Simulador::GetE_Nq2()
{
return E_Nq2;
}
vector<double> Simulador::GetE_N1()
{
return E_N1;
}
vector<double> Simulador::GetE_N2()
{
return E_N2;
}
vector<double> Simulador::GetE_W1()
{
return E_W1;
}
vector<double> Simulador::GetE_T1()
{
return E_T1;
}
vector<double> Simulador::GetE_W2()
{
return E_W2;
}
vector<double> Simulador::GetE_T2()
{
return E_T2;
}
vector<double> Simulador::GetV_W1()
{
return V_W1;
}
vector<double> Simulador::GetV_W2()
{
return V_W2;
}
| [
"[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951",
"[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951",
"[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951",
"rocanaan@cedf45fa-8354-0ca4-fa20-ed59a3261951"
] | [
[
[
1,
19
],
[
21,
32
],
[
34,
35
],
[
37,
41
],
[
47,
47
],
[
49,
56
],
[
61,
61
],
[
63,
66
],
[
70,
91
],
[
95,
95
],
[
97,
97
],
[
102,
102
],
[
104,
107
],
[
109,
118
],
[
122,
123
],
[
126,
129
],
[
131,
133
],
[
137,
139
],
[
151,
151
],
[
154,
176
],
[
178,
178
],
[
180,
180
],
[
185,
188
],
[
190,
195
],
[
197,
199
],
[
203,
204
],
[
206,
206
],
[
212,
212
],
[
218,
220
],
[
225,
247
],
[
250,
253
],
[
256,
259
],
[
265,
265
],
[
271,
274
],
[
280,
280
],
[
286,
286
],
[
290,
290
],
[
297,
297
],
[
299,
302
],
[
307,
307
],
[
309,
311
],
[
313,
318
],
[
321,
333
],
[
336,
337
],
[
340,
343
],
[
348,
348
],
[
350,
351
],
[
355,
362
],
[
367,
369
],
[
371,
373
],
[
375,
375
],
[
377,
380
],
[
382,
383
],
[
386,
393
],
[
395,
395
],
[
397,
399
],
[
401,
413
],
[
415,
415
],
[
421,
423
],
[
425,
431
],
[
433,
433
],
[
435,
435
],
[
438,
438
],
[
441,
443
],
[
445,
447
],
[
449,
452
],
[
454,
457
],
[
459,
462
],
[
464,
465
],
[
467,
475
],
[
478,
488
],
[
490,
492
],
[
504,
511
],
[
513,
514
],
[
516,
517
],
[
519,
519
],
[
526,
528
],
[
530,
532
],
[
537,
537
],
[
540,
543
],
[
545,
545
],
[
551,
552
],
[
554,
557
],
[
559,
562
],
[
564,
567
],
[
569,
626
],
[
628,
640
],
[
642,
647
],
[
649,
654
],
[
656,
661
],
[
663,
668
],
[
670,
675
],
[
677,
682
],
[
684,
691
],
[
720,
759
]
],
[
[
20,
20
],
[
33,
33
],
[
36,
36
],
[
42,
46
],
[
48,
48
],
[
57,
60
],
[
62,
62
],
[
67,
69
],
[
92,
94
],
[
96,
96
],
[
98,
101
],
[
103,
103
],
[
108,
108
],
[
121,
121
],
[
124,
125
],
[
130,
130
],
[
134,
136
],
[
140,
150
],
[
152,
153
],
[
177,
177
],
[
179,
179
],
[
181,
184
],
[
189,
189
],
[
196,
196
],
[
200,
202
],
[
205,
205
],
[
207,
211
],
[
213,
217
],
[
221,
224
],
[
248,
249
],
[
254,
255
],
[
260,
264
],
[
266,
270
],
[
275,
279
],
[
281,
285
],
[
287,
289
],
[
291,
296
],
[
304,
306
],
[
308,
308
],
[
312,
312
],
[
319,
320
],
[
334,
335
],
[
338,
339
],
[
344,
347
],
[
349,
349
],
[
352,
354
],
[
364,
366
],
[
370,
370
],
[
374,
374
],
[
376,
376
],
[
381,
381
],
[
384,
385
],
[
394,
394
],
[
396,
396
],
[
400,
400
],
[
414,
414
],
[
416,
417
],
[
420,
420
],
[
424,
424
],
[
432,
432
],
[
434,
434
],
[
436,
437
],
[
440,
440
],
[
444,
444
],
[
448,
448
],
[
453,
453
],
[
458,
458
],
[
463,
463
],
[
466,
466
],
[
476,
477
],
[
489,
489
],
[
493,
503
],
[
512,
512
],
[
515,
515
],
[
518,
518
],
[
520,
525
],
[
529,
529
],
[
533,
536
],
[
538,
539
],
[
544,
544
],
[
546,
550
],
[
553,
553
],
[
558,
558
],
[
563,
563
],
[
568,
568
],
[
627,
627
],
[
641,
641
],
[
648,
648
],
[
655,
655
],
[
662,
662
],
[
669,
669
],
[
676,
676
],
[
683,
683
],
[
692,
719
]
],
[
[
119,
120
],
[
298,
298
],
[
303,
303
],
[
363,
363
],
[
419,
419
],
[
439,
439
]
],
[
[
418,
418
]
]
] |
9ca03fff2d153b708b09b279ade2a332a7a2dadb | b369aabb8792359175aedfa50e949848ece03180 | /src/glWin/ViewFormGL.cpp | abdc540e014f45c2e4cc86694fb0ed454c8e16a3 | [] | no_license | LibreGamesArchive/magiccarpet | 6d49246817ab913f693f172fcfc53bf4cc153842 | 39210d57096d5c412de0f33289fbd4d08c20899b | refs/heads/master | 2021-05-08T02:00:46.182694 | 2009-01-06T20:25:36 | 2009-01-06T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,800 | cpp | ///////////////////////////////////////////////////////////////////////////////
// ViewFormGL.cpp
// ==============
// View component of OpenGL dialog window
//
// AUTHORL Song Ho Ahn ([email protected])
// CREATED: 2006-07-10
// UPDATED: 2006-08-15
///////////////////////////////////////////////////////////////////////////////
#include "ViewFormGL.h"
#include "resource.h"
#include "Log.h"
using namespace Win;
///////////////////////////////////////////////////////////////////////////////
// default ctor
///////////////////////////////////////////////////////////////////////////////
ViewFormGL::ViewFormGL()
{
}
///////////////////////////////////////////////////////////////////////////////
// default dtor
///////////////////////////////////////////////////////////////////////////////
ViewFormGL::~ViewFormGL()
{
}
///////////////////////////////////////////////////////////////////////////////
// initialize all controls
// To add new controls:
// 1. add a wrapper member variable to ViewFormGL.h
// 2. insert a call to set() here
// 3. Handle a button click in ControllerFormGL::command()
///////////////////////////////////////////////////////////////////////////////
void ViewFormGL::initControls(HWND handle)
{
// set all controls
buttonAnimate.set(handle, IDC_ANIMATE);
radioFill.set(handle, IDC_FILL);
radioWireframe.set(handle, IDC_WIREFRAME);
radioPoint.set(handle, IDC_POINT);
trackbarRed.set(handle, IDC_RED);
trackbarGreen.set(handle, IDC_GREEN);
trackbarBlue.set(handle, IDC_BLUE);
buttonTest.set(handle, IDC_BUTTON1);
// initial state
radioFill.check();
trackbarRed.setRange(0, 255);
trackbarRed.setPos(0);
trackbarGreen.setRange(0, 255);
trackbarGreen.setPos(0);
trackbarBlue.setRange(0, 255);
trackbarBlue.setPos(0);
}
///////////////////////////////////////////////////////////////////////////////
// update caption of animate button
///////////////////////////////////////////////////////////////////////////////
void ViewFormGL::animate(bool flag)
{
if(flag)
buttonAnimate.setText(L"Stop");
else
buttonAnimate.setText(L"Animate");
}
///////////////////////////////////////////////////////////////////////////////
// update trackbars
///////////////////////////////////////////////////////////////////////////////
void ViewFormGL::updateTrackbars(HWND handle, int position)
{
if(handle == trackbarRed.getHandle())
{
trackbarRed.setPos(position);
}
else if(handle == trackbarGreen.getHandle())
{
trackbarGreen.setPos(position);
}
else if(handle == trackbarBlue.getHandle())
{
trackbarBlue.setPos(position);
}
}
| [
"[email protected]"
] | [
[
[
1,
94
]
]
] |
f29f1a37cd7fcc19612645213ece4ca87a66a51e | a7513d1fb4865ea56dbc1fcf4584fb552e642241 | /shiftable_files/osal/windows/osal_windows.cpp | 1d07596192ce37e4b4613b2317683ddf7f1c7cde | [
"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 | 4,417 | cpp | ///////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2010, Universidad de Alcala //
// //
// See accompanying LICENSE.TXT //
// //
///////////////////////////////////////////////////////////////////
/*
osal_windows.cpp
----------------
Implementation of a concrete OSAL (Operating System Abstraction
Layer) that provides memory-mapped files in Windows.
// NOTE: the file mapping object is created/destroyed
every time. The exact maximum size is specified
on creation. Though, this is probably flushing
all pages on resize... Keeping the file mapping
object all the time (creating/destroying only
the map views), would be more efficient. The
drawback is that, in this case, specifying a
huge maximum size would consume too much
virtual address space.
*/
#include "../../detail/assert.hpp"
#include "osal_windows.hpp"
#include "../osal_memory.hpp"
using namespace shiftable_files;
using namespace shiftable_files::detail;
file * file::new_file (file_type type)
{
switch (type)
{
case ft_true_file: return new true_file;
case ft_virtual_file: return new virtual_file;
default: return NULL;
}
}
bool true_file::open (const char * name, open_mode mode)
{
LARGE_INTEGER size;
shf_assert (!m_open);
shf_assert (!m_mapped);
shf_assert (!m_pmap);
shf_assert (mode==om_create_or_wipe_contents ||
mode==om_open_existing_or_fail);
if (!name || !*name)
return false;
m_hfile = CreateFileA
(name,
GENERIC_READ | GENERIC_WRITE,
0, // Exclusive access
NULL, // No security attr., no inherit
mode==om_create_or_wipe_contents ?
CREATE_ALWAYS : OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_RANDOM_ACCESS,
NULL); // No template
if (m_hfile == INVALID_HANDLE_VALUE)
return false;
if (!GetFileSizeEx(m_hfile,&size) ||
size.HighPart ||
size.LowPart > MAX_SIZE)
{
CloseHandle (m_hfile);
m_hfile = INVALID_HANDLE_VALUE;
return false;
}
m_size = size.LowPart;
m_open = true;
return true;
}
void true_file::close ()
{
shf_assert (m_open);
shf_assert (!m_mapped);
CloseHandle (m_hfile);
init ();
}
uint32_t true_file::size ()
{
return m_size;
}
bool true_file::resize (uint32_t size)
{
LARGE_INTEGER large_size;
shf_assert (m_open);
shf_assert (!m_mapped);
shf_assert (size!=m_size);
large_size.HighPart = 0;
large_size.LowPart = size;
if (!SetFilePointerEx (m_hfile, large_size,
NULL, FILE_BEGIN) ||
!SetEndOfFile (m_hfile))
return false;
m_size = size;
return true;
}
int8_t * true_file::map ()
{
shf_assert (m_open);
shf_assert (!m_mapped);
shf_assert (!m_pmap);
shf_assert (m_size);
m_hmap = CreateFileMapping
(m_hfile,
NULL, // No inherit
PAGE_READWRITE,
0, // Size (high)
m_size, // Size (low)
NULL); // Name of mapping
if (m_hmap == NULL)
return NULL;
m_pmap = (int8_t*) MapViewOfFile
(m_hmap,
FILE_MAP_ALL_ACCESS,
0, // Offset (high)
0, // Offset (low)
m_size);
if (m_pmap)
m_mapped = true;
else
{
CloseHandle (m_hmap);
m_hmap = INVALID_HANDLE_VALUE;
}
return m_pmap;
}
void true_file::unmap ()
{
shf_assert (m_open);
shf_assert (m_mapped);
shf_assert (m_pmap);
UnmapViewOfFile (m_pmap);
CloseHandle (m_hmap);
m_hmap = INVALID_HANDLE_VALUE;
m_pmap = NULL;
m_mapped = false;
}
true_file::~true_file ()
{
shf_assert (!m_open);
shf_assert (!m_mapped);
shf_assert (!m_pmap);
if (m_mapped) unmap ();
if (m_open) close ();
}
| [
"martin@ROBOTITO"
] | [
[
[
1,
178
]
]
] |
56a1ffe923eedfc5f7ed402012b3b0bad2ada94d | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/addons/pa/PUComponent/interface/CParticleInterface.h | cccc2226855955182da288efa86625903606014c | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | h | #ifndef __Orz_CParticleInterface__
#define __Orz_CParticleInterface__
#include <orz/Toolkit_Component_Task/Component/ComponentInterface.h>
namespace Ogre
{
class SceneNode;
}
namespace Orz
{
class CParticleInterface: public ComponentInterface
{
private:
typedef boost::function<bool (const std::string &/* name*/, Ogre::SceneNode * /* sn*/)> EnableFunction;
typedef boost::function<bool (TimeType i)> UpdateFunction;
typedef boost::function<void (void)> DisableFunction;
public:
EnableFunction enable;
UpdateFunction update;
DisableFunction disable;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
d3c5ba36580bc3c29345be4aee03b0a2ae18ad70 | ec08c0140c4f315a53222c23911d0f6cb1220521 | /headers/Graph.h | 83d92feae68cea70d96a8930a68cb2b9b0fb19be | [] | no_license | nikolnikon/nonintersecting-segments | 5a39643f8d3a93ef8bf90a1f00910f7c71fe74d7 | 8a309a63c2d51f7f78ae94756dde262c3b32c243 | refs/heads/master | 2021-01-10T06:24:11.404832 | 2009-12-15T22:20:27 | 2009-12-15T22:20:27 | 43,052,489 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,931 | h | #ifndef GRAPH_H
#define GRAPH_H
#include <list>
#include <map>
#include <stack>
#include <vector>
namespace GraphSpace
{
class BaseNode;
class BaseEdge;
//class Intersections;
class Graph
{
public:
Graph() : iNodeCount(0), iEdgeCount(0) {}
~Graph();
void addNode(BaseNode *pAn);
void addEdge(BaseNode *pAn_1, BaseNode *pAn_2);
void removeNode(BaseNode *pAn);
void removeEdge(BaseNode *pAn_1, BaseNode *pAn_2);
const BaseNode* node(int numNode) const;
int nodeCount() const {return iNodeCount; };
//BaseNode* node(int numNode) const;
//const BaseNode* incidentNodes(const BaseNode *cpAn_1, const BaseNode *cpAn_2);
void incidentEdges(const BaseNode *cpAn, std::list<const BaseNode*> &rIncEdges);
private:
int iNodeCount;
int iEdgeCount;
std::map<int, BaseNode*> mapNodes;
std::map<int, BaseEdge*> mapEdges;
};
class BaseNode
{
public:
friend void Graph::addEdge(BaseNode *pAn_1, BaseNode *pAn_2);
friend void Graph::removeEdge(BaseNode *pBn_1, BaseNode *pBn_2);
BaseNode(int numNode) : iNumNode(numNode) {}
virtual ~BaseNode() {}
int numNode() const { return iNumNode; }
void adjacentNodes(std::list<int> &rResult) const;
bool operator==(const BaseNode &rhs) const;
void printAdjNodes() const;
private:
//void addAdjacentNode(const BaseNode *cpAn); // private позволяет осуществить только парное добаление смежных вершин
int iNumNode;
std::list<int> lstAdjacentNodes;
};
//bool operator<(const BaseEdge &lhs, const BaseEdge &rhs) const;
class BaseEdge
{
public:
BaseEdge(const BaseNode *cpAn_1, const BaseNode *cpAn_2);
virtual ~BaseEdge() {}
private:
int iNumEdge;
const BaseNode *fstNode;
const BaseNode *sndNode;
};
class MaxIndependentSet
{
public:
MaxIndependentSet() : iMaxMaxIndSet(0) {}
~MaxIndependentSet();
void findMaxIndependentSet(const Graph &rGr, std::list<int> &result);
private:
// сожержит множества Qk- и Qk+ для каждого шага k
struct NodeSet
{
NodeSet() {}
NodeSet(const std::list<int> &list_1, const std::list<int> &list_2) : NotCandidateNodes(list_1), CandidateNodes(list_2) {}
std::list<int> NotCandidateNodes; // содержит множество вершин Qk-
std::list<int> CandidateNodes; // содержит множество вершин Qk+
};
bool returnCondition(int k, const Graph &crGr, std::list<int> &adjNodes) const;
int candidate(int k, const Graph &crGr, std::list<int> &adjNodes) const;
std::list<int> lstIndSet; // используется в качестве стека
std::vector<std::list<int>*> vecMaxIndSets;
int iMaxMaxIndSet;
//std::list<int> lstMaxMaxIndSet;
std::vector<NodeSet*> vecNodeSet;
};
}
#endif
| [
"nikolnikon@localhost"
] | [
[
[
1,
98
]
]
] |
604fdfc34938b2e37070ceb3d2a41928cef1ac66 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Manager/EntityVisitorMemFun3.h | c5391495747060e1dfc570cec075251e4b3dd7ce | [] | no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,931 | h | /*******************************************************************************/
/**
* @file EntityVisitorMemFun3.h.
*
* @brief 3引数関数ポインタ訪問者クラス定義.
*
* @date 2008/07/16.
*
* @version 1.00.
*
* @author Kentarou Nisimura.
*/
/******************************************************************************/
#ifndef _NGLENTITYVISITORMEMFUN3_H_
#define _NGLENTITYVISITORMEMFUN3_H_
#include "IEntityVisitor.h"
namespace Ngl{
/**
* @class EntityVisitorMemFun3.
* @brief 3引数関数ポインタ訪問者クラス.
* @tparam Entity 訪問した要素.
* @tparam First 引数1の型.
* @tparam Second 引数2の型.
* @tparam Third 引数3の型.
* @tparam MemFun 訪問関数ポインタ( void 関数( 引数1, 引数2, 引数3 ) ).
*/
template
<
typename Entity,
typename First,
typename Second,
typename Third,
typename void (Entity::*MenFun)( First, Second, Third )
>
class EntityVisitorMemFun3 : public IEntityVisitor<Entity*>
{
public:
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] first 引数1.
* @param[in] second 引数2.
* @param[in] third 引数3.
*/
EntityVisitorMemFun3( First first, Second second, Third third ) :
first_( first ),
second_( second ),
third_( third )
{}
/*=========================================================================*/
/**
* @brief 訪問する
*
* @param[in] entity 要素.
* @return なし.
*/
void visit( Entity* entity )
{
( entity->*MemFun )( first_, second_, third_ );
}
private:
/** 第一引数 */
First first_;
/** 第二引数 */
Second second_;
/** 第三引数 */
Third third_;
};
} // namespace Ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
] | [
[
[
1,
86
]
]
] |
ab569c9afaae1b1964de66f4fba2f373be0ee9b2 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /ScheduleKiller/source/Model/inc/Rule.h | ee09659d8f8f7163cd6179c7d2f1425f53de6ffc | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,159 | h | /*
============================================================================
Name : Rule.h
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CRule declaration
============================================================================
*/
#ifndef RULE_H
#define RULE_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include "MacroUtil.h"
// CLASS DECLARATION
/**
* CRule
*
*/
class CRule : public CBase
{
public:
// Constructors and destructor
/**
* Destructor.
*/
~CRule();
/**
* Two-phased constructor.
*/
static CRule* NewL();
/**
* Two-phased constructor.
*/
static CRule* NewLC();
private:
/**
* Constructor for performing 1st stage construction
*/
CRule();
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL();
public:
TUid GetUid() const {return iUid;};
void SetUid(const TUid& aUid) {iUid = aUid; };
TPtrC GetName() const {if (iName) return iName->Des(); else return KNullDesC();};
void SetName(const TDesC& aName) {SAFE_DELETE(iName);iName = aName.AllocL();};
TPtrC GetRuleName() const {if (iRuleName) return iRuleName->Des(); else return KNullDesC();};
void SetRuleName(const TDesC& aName) {SAFE_DELETE(iRuleName);iRuleName = aName.AllocL();};
TInt GetType() const {return iType;};
void SetType(const TInt& aType) {iType = aType;};
TTime GetClock() const {return iClock;};
void SetClock(const TTime& aTime) {iClock = aTime;};
TInt GetCountDown() const {return iCountDown;};
void SetCountDown(const TInt& aCountDown) {iCountDown = aCountDown;};
TInt IsLunchRun() const {return iLunch;};
void SetLunchRun(const TInt& aLunch) {iLunch = aLunch;};
void IncreaseFavCount() {iFavCount++;};
TInt GetFavCount() const {return iFavCount;};
void SetFavCount(const TInt& aCount) {iFavCount = aCount;};
private:
TUid iUid;
HBufC* iName;
HBufC* iRuleName;
TInt iType;
TTime iClock;
TInt iCountDown;
TInt iLunch; //是否启动运行
TInt iFavCount; //运行次数
};
#endif // RULE_H
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
94
]
]
] |
9ed0133baadd7ff4778ed750eddfef430515bd8c | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/daolib/Model/MMH/EMAS.h | b2891be69a377bf3c448f288e56ef8ad235b9db2 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | h |
/**********************************************************************
*<
FILE: EMAS.h
DESCRIPTION: MMH File Format
HISTORY:
*> Copyright (c) 2009, All Rights Reserved.
**********************************************************************/
#pragma once
#include "MMH/MMHCommon.h"
#include "GFF/GFFField.h"
#include "GFF/GFFList.h"
#include "GFF/GFFStruct.h"
namespace DAO {
using namespace GFF;
namespace MMH {
///////////////////////////////////////////////////////////////////
class EMAS
{
protected:
GFFStructRef impl;
static ShortString type;
public:
EMAS(GFFStructRef owner);
static const ShortString& Type() { return type; }
const ShortString& get_type() const { return type; }
GFFListRef get_children() const;
};
typedef ValuePtr<EMAS> EMASPtr;
typedef ValueRef<EMAS> EMASRef;
} //namespace MMH
} //namespace DAO
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
] | [
[
[
1,
47
]
]
] |
1031da4794fc5890962707f8ad64e226eb35af97 | cfa6cdfaba310a2fd5f89326690b5c48c6872a2a | /References/XML/Sources/XMLite_demo/TestXMLiteDlg.cpp | 0233ae65b31a86c835ff40049e45c1d3de92b6db | [] | no_license | asdlei00/project-jb | 1cc70130020a5904e0e6a46ace8944a431a358f6 | 0bfaa84ddab946c90245f539c1e7c2e75f65a5c0 | refs/heads/master | 2020-05-07T21:41:16.420207 | 2009-09-12T03:40:17 | 2009-09-12T03:40:17 | 40,292,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,247 | cpp | // TestXMLiteDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TestXMLite.h"
#include "TestXMLiteDlg.h"
#include "XMLite.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTestXMLiteDlg dialog
CTestXMLiteDlg::CTestXMLiteDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTestXMLiteDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTestXMLiteDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTestXMLiteDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTestXMLiteDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTestXMLiteDlg, CDialog)
//{{AFX_MSG_MAP(CTestXMLiteDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
ON_BN_CLICKED(IDC_BUTTON5, OnButton5)
ON_BN_CLICKED(IDC_BUTTON6, OnButton6)
ON_BN_CLICKED(IDC_BUTTON7, OnButton7)
ON_BN_CLICKED(IDC_BUTTON8, OnButton8)
ON_BN_CLICKED(IDC_BUTTON9, OnButton9)
ON_BN_CLICKED(IDC_BUTTON10, OnButton10)
ON_BN_CLICKED(IDC_BUTTON11, OnButton11)
ON_BN_CLICKED(IDC_BUTTON12, OnButton12)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTestXMLiteDlg message handlers
BOOL CTestXMLiteDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CTestXMLiteDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTestXMLiteDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTestXMLiteDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
//Test. 1: Simple Plane XML Parse
void CTestXMLiteDlg::OnButton1()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<AddressBook description=\"book of bro\">\
<Person type='me'><Name>Cho,Kyung Min</Name><Nick>bro</Nick></Person>\
<Person type='friend'><Name>Baik,Ji Hoon</Name><Nick>bjh</Nick></Person>\
<Person type=friend><Name>Bak,Gun Joo</Name><Nick>dichter</Nick></Person>\
<Information count='3'/>\
</AddressBook>");
XNode xml;
if( xml.Load( sxml ) )
AfxMessageBox(xml.GetXML());
else
AfxMessageBox(_T("error"));
}
//Test. 2: Get Child Elements, Attributes
void CTestXMLiteDlg::OnButton2()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<AddressBook description=\"book of bro\">\
<Person type='me'><Name>Cho,Kyung Min</Name><Nick>bro</Nick></Person>\
<Person type='friend'><Name>Baik,Ji Hoon</Name><Nick>bjh</Nick></Person>\
<Person type=friend><Name>Bak,Gun Joo</Name><Nick>dichter</Nick></Person>\
<Information count='3'/>\
</AddressBook>");
XNode xml;
if( xml.Load( sxml ) == NULL )
{
AfxMessageBox(_T("error"));
return;
}
int i;
XNodes childs;
// DOM tree Childs Traveling
// method 1: Using GetChildCount() and GetChild()
// Result: Person, Person, Person, Information
LPXNode child;
for( i = 0 ; i < xml.GetChildCount(); i++)
{
child = xml.GetChild(i);
AfxMessageBox( child->GetXML() );
}
// method 2: LPXNodes and GetChilds() ( same result with method 1 )
// Result: Person, Person, Person, Information
childs = xml.GetChilds();
for( i = 0 ; i < childs.size(); i++)
AfxMessageBox( childs[i]->GetXML() );
// method 3: Selected Childs with GetChilds()
// Result: Person, Person, Person
childs = xml.GetChilds(_T("Person") );
for( i = 0 ; i < childs.size(); i++)
{
AfxMessageBox( childs[i]->GetXML() );
}
// method 4: Get Attribute Vaule of Child
// Result: 3
AfxMessageBox( xml.GetChildAttrValue( _T("Information"), _T("count") ) );
int count = XStr2Int( xml.GetChildAttrValue( _T("Information"), _T("count") ));
ASSERT( count == 3 );
}
//Test. 3: DOM Modify
void CTestXMLiteDlg::OnButton3()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<AddressBook description=\"book of bro\">\
<Person type='me'><Name>Cho,Kyung Min</Name><Nick>bro</Nick></Person>\
<Person type='friend'><Name>Baik,Ji Hoon</Name><Nick>bjh</Nick></Person>\
<Person type=friend><Name>Bak,Gun Joo</Name><Nick>dichter</Nick></Person>\
<Information count='3'/>\
</AddressBook>");
XNode xml;
xml.Load( sxml );
// remove 'bro node'
LPXNode child_bro = xml.GetChild(0);
xml.RemoveChild( child_bro );
AfxMessageBox(xml.GetXML());
}
//Test. 4: Error Handling
void CTestXMLiteDlg::OnButton4()
{
// TODO: Add your control notification handler code here
CString serror_xml;
serror_xml = _T("<XML>\
<NoCloseTag type='me'><Name>Cho,Kyung Min</Name><Nick>bro</Nick>\
</XML>");
XNode xml;
PARSEINFO pi;
if( xml.Load( serror_xml, &pi ) == NULL )
AfxMessageBox(_T("error") );
if( pi.erorr_occur ) // is error_occur?
{
//result: '<NoCloseTag> ... </XML>' is not wel-formed.
AfxMessageBox( pi.error_string );
AfxMessageBox( xml.GetXML() );
}
else
ASSERT(FALSE);
}
//Test. 5: Entity and Escape Char Test
void CTestXMLiteDlg::OnButton5()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<XML>\
<TAG attr='<\\'asdf\\\">'>asdf</TAG>\
</XML>");
XNode xml;
PARSEINFO pi;
pi.escape_value = '\\';
xml.Load( sxml, &pi );
AfxMessageBox( xml.GetXML() );
}
//Test. 6: Configurate Parse and Display
void CTestXMLiteDlg::OnButton6()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<XML>\
<TAG attr=' qwer '> asdf </TAG>\
</XML>");
XNode xml;
xml.Load( sxml );
AfxMessageBox( xml.GetXML() );
PARSEINFO pi;
pi.trim_value = true; // trim value
xml.Load( sxml, &pi );
AfxMessageBox( xml.GetXML() );
DISP_OPT opt;
opt.newline = false; // no new line
AfxMessageBox( xml.GetXML( &opt ) );
}
//Test. 6: Using Custom Entity Table
void CTestXMLiteDlg::OnButton7()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<XML>\
<TAG attr='&asdf>'></TAG>\
</XML>");
// customized entity list
static const XENTITY entity_table[] = {
{ '<', _T("<"), 4 } ,
{ '&', _T("&"), 5 }
};
XENTITYS entitys( (LPXENTITY)entity_table, 2 ) ;
PARSEINFO pi;
XNode xml;
pi.entity_value = true; // force to use custom entitys
pi.entitys = &entitys;
xml.Load( sxml, &pi );
AfxMessageBox( xml.GetXML() );
DISP_OPT opt;
opt.entitys = &entitys;
opt.reference_value = true; // force to use custom entitys
AfxMessageBox( xml.GetXML( &opt ) );
}
void CTestXMLiteDlg::OnButton8()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<XML>\
<TAG attr='c:\\\\myaa'>asdf</TAG>\
</XML>");
XNode xml;
PARSEINFO pi;
pi.escape_value = '\\';
xml.Load( sxml, &pi );
AfxMessageBox( xml.GetXML() );
AfxMessageBox( xml.GetChildAttrValue("TAG", "attr") );
}
void CTestXMLiteDlg::OnButton9()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<AddressBook description=\"book of bro\">\
<Person type='me'><Name>Cho,Kyung Min</Name><Nick>bro</Nick></Person>\
<Person type='friend'><Name>Baik,Ji Hoon</Name><Nick>bjh</Nick></Person>\
<Person type=friend><Name>Bak,Gun Joo</Name><Nick>dichter</Nick></Person>\
<Information count='3'/>\
</AddressBook>");
XNode xml;
xml.Load( sxml );
AfxMessageBox( xml.GetXML() );
XNode xml2;
xml2.CopyNode( &xml );
AfxMessageBox( xml2.GetXML() );
XNode xml3;
//same with xml3 = xml;
xml3.CopyBranch( &xml );
AfxMessageBox( xml3.GetXML() );
XNode xml4;
//same with xml3.CopyBranch( &xml );
xml4.AppendChildBranch( &xml );
AfxMessageBox( xml4.GetXML() );
}
void CTestXMLiteDlg::OnButton10()
{
// TODO: Add your control notification handler code here
CString sxml;
sxml = _T("<?xml version='1.0'?>\
<!-- comment -->\
<![CDATA[some data]]>\
<a>\
<![CDATA[some data]]>\
value\
<![CDATA[some data2]]>\
</a><!-- comment2-->");
XNode xml;
xml.Load( sxml );
AfxMessageBox( xml.GetXML() );
}
void CTestXMLiteDlg::OnButton11()
{
// TODO: Add your control notification handler code here
CString sXML = "\
<html>\
<body width='100'>\
Some times I got say...\
<font name='system' size='1'/>\
<a href='http://www.a.com' target=_blank>\
<HR>\
Thanks\
</body>\
</html>";
XDoc xml;
PARSEINFO pi;
pi.force_parse = true;
if( xml.Load( sXML, &pi ) )
{
LPXNode root = xml.GetRoot();
//root->AppendChild( _T("child"), _T("value") );
AfxMessageBox( xml.GetXML() );
}
// you can't not parse without force_parse on un-welformed xml!
XNode node;
if( node.Load( sXML ) )
{
AfxMessageBox( node.GetXML() );
}
}
void CTestXMLiteDlg::OnButton12()
{
// TODO: Add your control notification handler code here
CString sXML = "\
<A>\
<B>\
<C/>\
<D/>\
</B>\
</A>";
XNode node;
if( node.Load( sXML ) )
{
AfxMessageBox( node.GetXML() );
LPXNode found = NULL;
found = node.Find( _T("D") );
if( found )
{
AfxMessageBox( found->GetXML() );
}
}
}
| [
"[email protected]"
] | [
[
[
1,
499
]
]
] |
6e4fdae7a59353dc191595ee50064289b817aba6 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Ray.cpp | f1f38e2262692cfe6b686317acdcc16507e7f788 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | cpp | #include <Halak/PCH.h>
#include <Halak/Ray.h>
#include <Halak/Matrix4.h>
#include <Halak/Rectangle.h>
namespace Halak
{
const Ray Ray::Empty;
Ray Ray::FromScreenSpace(Point point, const Matrix4& viewTransform, const Matrix4& projectionTransform, const Rectangle& viewport)
{
const Vector3 v(+(((static_cast<float>(point.X) * 2.0f) / static_cast<float>(viewport.Width)) - 1.0f) / projectionTransform.M00,
-(((static_cast<float>(point.Y) * 2.0f) / static_cast<float>(viewport.Height)) - 1.0f) / projectionTransform.M11,
1.0f);
const Matrix4 inversedViewTransform = Matrix4::Inversion(viewTransform);
Vector3 direction((v.X * inversedViewTransform.M00) + (v.Y * inversedViewTransform.M10) + (v.Z * inversedViewTransform.M20),
(v.X * inversedViewTransform.M01) + (v.Y * inversedViewTransform.M11) + (v.Z * inversedViewTransform.M21),
(v.X * inversedViewTransform.M02) + (v.Y * inversedViewTransform.M12) + (v.Z * inversedViewTransform.M22));
direction.Normalize();
const Vector3 origin(inversedViewTransform.M30, inversedViewTransform.M31, inversedViewTransform.M32);
return Ray(origin, direction, 1.0f);
}
} | [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
466bd8ec50cc2299c6564504e2e746b84469ce90 | eec70a1718c685c0dbabeee59eb7267bfaece58c | /Sense Management Irrlicht AI/PlayState.cpp | 7d71238d4f1d607fd0ca95edf80c31dfca29cb07 | [] | no_license | mohaider/sense-management-irrlicht-ai | 003939ee770ab32ff7ef3f5f5c1b77943a4c7489 | c5ef02f478d00a4957a294254fc4f3920037bd7a | refs/heads/master | 2020-12-24T14:44:38.254964 | 2011-05-19T14:29:53 | 2011-05-19T14:29:53 | 32,393,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,334 | cpp |
#include <stdio.h>
#include "Game.h"
#include "PlayState.h"
#include "GameObjectFactory.h"
#include "Player.h"
#include "AIObject.h"
#include "EventHandler.h"
#include "MessageSender.h"
#include "SoundManager.h"
#include "SplashState.h"
#include "Collision.h"
#include "RegionalSenseManager.h"
#include <assert.h>
#include <iostream>
PlayState PlayState::m_PlayState;
bool PlayState::Init()
{
// Drawn when the player is dead
TheIrrlichtObject::Instance()->GetIrrlichtDevice()->getGUIEnvironment()->addImage(
TheIrrlichtObject::Instance()->GetVideoDriver()->getTexture("assets/textures/blood.png"),
core::position2d<s32>(0,0));
// Create the walls for wall avoidance
for(unsigned int i = 0; i < TheGame::Instance()->GetBoundingBoxes().size(); ++i )
{
collision::Create4WallsFrombox(TheGame::Instance()->GetBoundingBoxes()[i]->getTransformedBoundingBox());
}
// Start the music and ambient sound effects
SoundManager::Instance()->PlayMusic("assets/sounds/music1.wav");
SoundManager::Instance()->PlaySound("assets/sounds/crickets.wav", -1, -1, 100);
// hide the mouse cursor
TheIrrlichtObject::Instance()->GetIrrlichtDevice()->getCursorControl()->setVisible(false);
// load the player object
ThePlayer::Instance()->Load(NULL);
// load all the game objects from a file
File f;
if (!f.Open("assets/config.txt"))
{
return false;
}
while (!f.EndOfFile())
{
std::string typeName;
f.GetString(&typeName);
if (typeName.empty() || typeName[0] == '#')
{
return true;
}
std::cout<< typeName << " Type Object Created" << "\n";
GameObject* pMyNewObject =
TheGameObjectFactory::Instance()->Create(typeName);
if (!pMyNewObject)
{
return false;
}
if (!pMyNewObject->Load(&f))
{
return false;
}
int id = TheGame::Instance()->GetNextID();
TheGame::Instance()->AddGameObject(id, pMyNewObject);
TheGame::Instance()->IncrementNextID();
// If its an AI object then put it in the AI map
if(pMyNewObject->GetTypeName() == "AIObject")
{
int ai_id = TheGame::Instance()->GetNextID_AI();
AIObject* aiObject = dynamic_cast<AIObject*>(pMyNewObject);
aiObject->SetID(ai_id);
TheGame::Instance()->AddAIObject(ai_id, aiObject);
TheGame::Instance()->IncrementNextID_AI();
}
}
printf("Main Game State Initialised Succesfully");
return true;
}
// Free textures and memory
void PlayState::Clean()
{
}
// Pause this state
void PlayState::Pause()
{
}
// Resume this state
void PlayState::Resume()
{
}
// Handle events // player input and exit
void PlayState::HandleEvents()
{
ThePlayer::Instance()->HandleInput();
if(TheEventReceiver::Instance()->IsKeyDown(KEY_ESCAPE))
{
exit(0);
}
if(TheEventReceiver::Instance()->IsKeyDown(KEY_RETURN))
{
// when the player dies, press enter to reset and try again
if(ThePlayer::Instance()->GetDead())
{
for(Game::GameObjects::iterator it = TheGame::Instance()->GetGameObjects().begin(); it != TheGame::Instance()->GetGameObjects().end(); ++it)
{
GameObject* p = it->second;
p->Reset();
}
ThePlayer::Instance()->Reset();
ThePlayer::Instance()->SetDead(false);
}
}
}
// Update the state // and player
void PlayState::Update(float dt)
{
for(Game::GameObjects::const_iterator it = TheGame::Instance()->GetGameObjects().begin(); it != TheGame::Instance()->GetGameObjects().end(); ++it)
{
GameObject* p = it->second;
p->Update(dt);
}
ThePlayer::Instance()->Update(dt);
// send AI messages that are in queue
TheMessageSender::Instance()->SendDelayedMessages();
// update the sound manager
SoundManager::Instance()->Update();
// move the camera
TheGame::Instance()->MoveCameraControl();
}
// Render the state // this is done through the scene graph of irrlicht
void PlayState::Draw()
{
TheIrrlichtObject::Instance()->GetVideoDriver()->beginScene(true, true, SColor(255, 0, 0, 0));
TheIrrlichtObject::Instance()->GetSceneManager()->drawAll();
// if the player is dead, draw the game over screen
if(ThePlayer::Instance()->GetDead())
{
TheIrrlichtObject::Instance()->GetIrrlichtDevice()->getGUIEnvironment()->drawAll();
}
TheIrrlichtObject::Instance()->GetVideoDriver()->endScene();
}
| [
"[email protected]@2228f7ce-bb98-ac94-67a7-be962254a327"
] | [
[
[
1,
166
]
]
] |
c403f93c90417b9c03a276a108c88faccb9c7735 | 828c44fe5fd08218b857677ffb9f4545803e7112 | /cob_utilities/common/include/cob_utilities/IniFile.h | da9a3b691fbde68f24b6e42164ea3f0671fd2d7f | [] | no_license | attilaachenbach/cob_common | aabb3163997a32921f3a8ecc08c95ce09070e270 | 8b96f4987e972c9c0e897793dbd69062cd769d8d | refs/heads/master | 2020-05-30T23:24:18.044158 | 2011-05-17T07:38:46 | 2011-05-17T07:38:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,878 | h | /****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_common
* ROS package name: inifiles_old
* Description:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Christian Connette, email:[email protected]
* Supervised by: Christian Connette, email:[email protected]
*
* Date of creation: Feb 2009
* ToDo: Remove it!
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#ifndef _Inifile_H
#define _Inifile_H
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
//-------------------------------------------------------------------
/**
* Used to store persistend program configuration in INI-Files.
* The INI-File is organized into sections and Keys (variables) like
* ordinary Windows INI-Files.
* The write functions create a temporary file in the root directory.
* If there is no write permission in this directory, they don't work.
* @par sections:
* identifcator between '[' and ']', a section headline must not have blanks
* at the beginning neither right after or before the '[ ]'.
*
* @par sections contains keys:
* identificator followed by '=' and the value, no blanks at the
* beginning of the line, nor after the '=' sign or between key
* and '=' sign. the pBuf will contain the eventual blanks after
* the '=' sign.
*
* @par example:
* @code
* [section1]
*
* key11=234
* key12=yellow submarine
* key13=13.5
*
* [section2]
*
* key21=
* key22=13
* @endcode
*
* \ingroup UtilitiesModul
*/
class IniFile
{
public:
/**
* Default constructor.
*/
IniFile();
/**
* Constructor.
* @param fileName file name.
*/
IniFile(std::string fileName);
~IniFile();
/**
* Sets file path of ini-file.
* Also verifies that file exists.
* @param fileName file name
* @param strIniFileUsedBy the name of the source file using the ini-file.
* This name will be printed if an error occurs.
* @param bCreate if true: create new file if the file does not exist (default: false)
* @return 0 if file exists or new file has been created sucesfully
*/
int SetFileName(std::string fileName, std::string strIniFileUsedBy = "", bool bCreate = false);
/**
* Write character string to INI-File.
* Like Windows Fn WriteProfileString().
* Comments in the same line as the variables will be deleted during write operations.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param StrToWrite null ended string to write.
* @param bWarnIfNotfound print a warning message if the section is not found and therefore is created newly.
*/
int WriteKeyString(const char* pSect, const char* pKey, const std::string* pStrToWrite, bool bWarnIfNotfound = true);
/**
* Write integer to INI-File.
* Like Windows Fn WriteProfileInt().
* Comments in the same line as the variables will be deleted during write operations.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param nValue integer to write.
* @param bWarnIfNotfound print a warning message if the section is not found and therefore is created newly.
*/
int WriteKeyInt(const char* pSect,const char* pKey,int nValue, bool bWarnIfNotfound = true);
/**
* Write double to INI-File.
* Comments in the same line as the variables will be deleted during write operations.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param dValue double to write.
* @param StringLen total length of string into which the double will be converted
* @param decimals of double to store
* @param bWarnIfNotfound print a warning message if the section is not found and therefore is created newly.
*/
int WriteKeyDouble(const char* pSect,const char* pKey,double dValue,int StringLen=12,int decimals=5, bool bWarnIfNotfound = true);
/**
* Read boolean from INI-File.
* The value writen will be either 'true' or 'false'.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to boolean which will contain the value of the key.
* If the section or the key is not found, the value of *pValue remains unchanged
* @param bWarnIfNotfound print a warning message if the section is not found and therefore is created newly.
*/
int WriteKeyBool(const char* pSect, const char* pKey, bool bValue, bool bWarnIfNotfound = true);
/**
* Read character string from INI-File.
* Like Windows Fn GetProfileString().
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pStrToRead will contain string read
* If the section or the key is not found, the value of *pStrToRead remains unchanged
*/
int GetKeyString(const char* pSect,const char* pKey, std::string* pStrToRead,
bool bWarnIfNotfound = true);
/**
* Read integer from INI-File.
* Like Windows Fn GetProfileInt().
*/
int GetKeyInt(const char* pSect,const char* pKey,int* pValue,
bool bWarnIfNotfound = true);
/**
* Read long from INI-File.
*/
int GetKeyLong(const char* pSect,const char* pKey,long* pValue,
bool bWarnIfNotfound = true);
/**
* Read boolean from INI-File.
* The value can be either 'true' or 'false'.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to boolean which will contain the value of the key.
* If the section or the key is not found, the value of *pValue remains unchanged
*/
int GetKeyBool(const char* pSect, const char* pKey, bool* pValue,
bool bWarnIfNotfound = true);
/**
* Read double from INI-File.
* Current accuracy: 9 chars!!
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to double which will contain the value of the key.
* If the section or the key is not found, the vlaue of *pValue remains unchanged
*/
int GetKeyDouble(const char* pSect,const char* pKey,double* pValue,
bool bWarnIfNotfound = true);
/**
* Read double from INI-File.
* Current accuracy: 9 chars!!
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to double which will contain the value of the key.
* If the section or the key is not found, the vlaue of *pValue remains unchanged
*/
int GetKeyDouble(const char* pSect,const char* pKey,double* pValue, double dDefault,
bool bWarnIfNotfound = true);
/**
* Read character string from INI-File.
* Like Windows Fn GetProfileString().
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param StrToRead will contain string read
* If the section or the key is not found, the value of *pStrToRead remains unchanged
*/
int GetKey(const char* pSect,const char* pKey, std::string* pStrToRead, bool bWarnIfNotfound = true);
/**
* Read integer from INI-File.
* Like Windows Fn GetProfileInt().
*/
int GetKey(const char* pSect,const char* pKey,int* pValue, bool bWarnIfNotfound = true);
/**
* Read boolean from INI-File.
* The value can be either 'true' or 'false'.
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to boolean which will contain the value of the key.
* If the section or the key is not found, the value of *pValue remains unchanged
*/
int GetKey(const char* pSect, const char* pKey, bool* pValue, bool bWarnIfNotfound = true);
/**
* Read double from INI-File.
* Current accuracy: 9 chars!!
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pValue pointer to double which will contain the value of the key.
* If the section or the key is not found, the vlaue of *pValue remains unchanged
*/
int GetKey(const char* pSect,const char* pKey,double* pValue, bool bWarnIfNotfound = true);
/**
* Find the section name after the given section.
* If prevSect is NULL, get the first section name.
* @param pSect pointer to a null ended string which will contain the section title without '[' and ']'.
* @param prevSect pointer to a null ended string contraing the previous section title without '[' and ']'.
* @param bWarnIfNotfound print a warning message if the section is not found.
* If the section is not found, the value of *sect is not defined.
*/
int FindNextSection(std::string* pSect, std::string prevSect, bool bWarnIfNotfound = true);
private:
int FindSection(const char* sect, bool bWarnIfNotfound = true);
int FindKey(const char* skey, bool bWarnIfNotfound = true);
int FindNextLine(std::vector<char>& NewLine, int& CharInd);
/**
* Write character string to INI-File.
* Like Windows Fn WriteProfileString().
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pBuf null ended string to write.
* @param bWarnIfNotfound print a warning message if the section is not found and therefore is created newly.
*/
int WriteKeyValue(const char* pSect,const char* pKey,const char* pBuf, bool bWarnIfNotfound = true);
/**
* Read character string from INI-File.
* Like Windows Fn GetProfileString().
* @param pSect pointer to a null ended string containing the section title without '[' and ']'
* @param pKey pointer to a null ended string containing the key
* @param pBuf pointer to a character buffer of length lenBuf string which will
* contain the value of the key.
* If the section or the key is not found, the vlaue of *pBuf remains unchanged
* @param lenBuf the maximal length of szBuf (including terminating \0).
* @return the length of the string read or RF_E if error
*/
int GetKeyValue(const char* pSect,const char* pKey, char* pBuf, int lenBuf,
bool bWarnIfNotfound = true);
/**
* Skips chars in line until Endchar.
* return: - Nr of chars skipped if successful
* - RF_E if end of line (\n) or end of file before Endchar is found
*/
int SkipLineUntil(FILE* pFile, const char EndChar);
/**
* Reads chars in line until Endchar into string.
* return: - Nr of chars read if successful
* - RF_E if end of line (\n) or end of file before Endchar is found.
* In this case, the string will contain the chars read so far.
*/
int ReadLineUntil(FILE* pFile, const char EndChar, std::string& ReadIntoStr);
bool m_bFileOK;
/**
* Vector to store the chars of the most recently read line.
*/
std::vector<char> m_CurLine;
/**
* Size of the vector CurLine.
*/
const int m_vectorSize;
/**
* Index of the current character in the current line.
*/
int m_CurCharInd;
std::string m_fileName;
std::string m_strIniFileUsedBy; //used for debug to inidcate user class of ini-file
FILE* f;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
341
]
]
] |
d891ea6711f75f91b8bd334945d49f77f433203c | 55f0fcc198d4646235e75c0eff6fc6d3fad85313 | /zenilib/src/application.cxx | 68bf11c73740b84960795834640fffee037c325f | [] | no_license | ernieg/493final | b6484ea3d09801404a15ee1df974004cb9dffe14 | 83c9527c3d289dad5496b1fd0eb45bffba09f1d5 | refs/heads/master | 2021-01-01T16:13:08.191675 | 2011-04-19T22:04:11 | 2011-04-19T22:04:11 | 32,241,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 251 | cxx | /* This file is part of the Zenipex Library.
* Copyleft (C) 2008 Mitchell Keith Bloch a.k.a. bazald
*
* This source file is simply under the public domain.
*/
#include "zenilib.h"
#include "Gamestate_One.cpp"
#include "Tutorial_State.cpp"
| [
"[email protected]@68425394-8837-c440-6ca7-5483a7d6cf0c"
] | [
[
[
1,
10
]
]
] |
82b3d4d03a4d60172c6dc808d716dd90734fad6f | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/Terrain/TerrainPatch.h | dbe9b875bd773039374e4bfbfa8ba9d8fa4c988b | [] | no_license | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,449 | h | #pragma once
#include "TerrainVertex.h"
#include "QuadTree.h"
namespace P3D
{
namespace World
{
class Terrain;
const Scalar TERRAIN_ERROR_THRESHOLD = 0.2f;
/*
NxN piece of terrain.
Has index buffer.
*/
class TerrainPatch : public QuadTreeLeaf
{
friend class Terrain;
public:
static const int LOD_LEVELS = 5;
static const int PATCH_SIZE = (1 << LOD_LEVELS) + 1; // 2 ^ LOD_LEVELS + 1
static const int MAX_INDICES_COUNT = (2 * (PATCH_SIZE - 1) * (PATCH_SIZE + 1) - 2) + PATCH_SIZE * 5;
typedef ushort IndexType;
public:
TerrainPatch(Terrain* parent, int x, int y);
~TerrainPatch();
/*
Inherited from QuadTreeLeaf.
*/
override const AABB& CalculateBoundingBox();
/*
Inherited from QuadTreeLeaf.
Do nothing.
*/
override void DeleteQuadNode() {};
/*
Render the patch.
All visibility check already has been done.
*/
void Render();
protected:
Terrain* _parent;
ushort _x, _y; // location in the complete terrain
float _LOD;
byte _tessalationLevel;
byte _curTessalationLevel; // lod of the current IB
ushort _indecesCount; // how many indices to render
IndexType _indexOffset;
Vector _center; // center of the patch
clock_t _nextUpdate;
// byte mask with more detailes sides of current mesh
enum
{
SIDE_LEFT = (1 << 1),
SIDE_RIGHT = (1 << 2),
SIDE_UP = (1 << 3),
SIDE_DOWN = (1 << 4)
};
byte _meshSides;
// neightbors
TerrainPatch* _up;
TerrainPatch* _down;
TerrainPatch* _left;
TerrainPatch* _right;
// build index buffer for curent LOD value.
void RebuildIndexBuffer(bool print = false);
// Calculate and store LOD value (from 0.0 for best mesh to LOD_LEVELS for worst)
void CalculateLOD(const Transform& fromCameraSpace);
// make patches with common side have lods differ no more than by 1
inline bool NormalizeLOD()
{
int l = LOD_LEVELS, r = LOD_LEVELS, u = LOD_LEVELS, d = LOD_LEVELS;
if (_left && _left->LastVisibleTick == LastVisibleTick) l = _left->_tessalationLevel;
if (_right && _right->LastVisibleTick == LastVisibleTick) r = _right->_tessalationLevel;
if (_up && _up->LastVisibleTick == LastVisibleTick) u = _up->_tessalationLevel;
if (_down && _down->LastVisibleTick == LastVisibleTick) d = _down->_tessalationLevel;
int nt = Min(Min(l + 1, r + 1), Min(u + 1, d + 1));
if (_tessalationLevel > nt)
{
_tessalationLevel = nt;
return true;
} else
return false;
}
/*
Return true when current LOD changed or any neighborns LOD changed.
*/
inline bool ShouldRebuidIB() const
{
if (_tessalationLevel != _curTessalationLevel) return true;
byte newMeshSides = 0;
if ((_up!=NULL) && (_up->LastVisibleTick == LastVisibleTick) && (_up->_tessalationLevel < _tessalationLevel))
newMeshSides |= SIDE_UP;
if ((_down!=NULL) && (_down->LastVisibleTick == LastVisibleTick) && (_down->_tessalationLevel < _tessalationLevel))
newMeshSides |= SIDE_DOWN;
if ((_left!=NULL) && (_left->LastVisibleTick == LastVisibleTick) && (_left->_tessalationLevel < _tessalationLevel))
newMeshSides |= SIDE_LEFT;
if ((_right!=NULL) && (_right->LastVisibleTick == LastVisibleTick) && (_right->_tessalationLevel < _tessalationLevel))
newMeshSides |= SIDE_RIGHT;
return (newMeshSides != _meshSides);
}
};
}
} | [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
] | [
[
[
1,
130
]
]
] |
84eb149ee81ea5458c416abafbd90ee7ca3f0799 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/unit_stream.cpp | 2ee0b5fc7e5610fc5d172a490ecf44e5b7cf8010 | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,079 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/unit_stream.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Unit_stream
//
Unit_stream::
Unit_stream (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::String (e, f, c)
{
}
Unit_stream::
Unit_stream (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::String (a, f, c)
{
}
Unit_stream::
Unit_stream (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::String (s, e, f, c)
{
}
Unit_stream* Unit_stream::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Unit_stream (*this, f, c);
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Unit_stream& i)
{
return o << static_cast< const ::xml_schema::String& > (i);
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Unit_stream& i)
{
e << static_cast< const ::xml_schema::String& > (i);
}
void
operator<< (::xercesc::DOMAttr& a, const Unit_stream& i)
{
a << static_cast< const ::xml_schema::String& > (i);
}
void
operator<< (::xml_schema::ListStream& l,
const Unit_stream& i)
{
l << static_cast< const ::xml_schema::String& > (i);
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
] | [
[
[
1,
148
]
]
] |
221b8f37ed251742551ea2b4cf9b3e501930ffc9 | 80716d408715377e88de1fc736c9204b87a12376 | /TspLib3/Src/Request.cpp | c8d1ac86275dce35c74dd1e3fff255a15a813dd8 | [] | no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 19,040 | cpp | /******************************************************************************/
//
// REQUEST.CPP - Source file for the TSPIRequest base class
//
// Copyright (C) 1994-2004 JulMar Entertainment Technology, Inc.
// All rights reserved
//
// This file contains all the code to manage the asynchronous request
// objects which are dynamically allocated for each TSP request generated
// by TAPI.
//
// This source code is intended only as a supplement to the
// TSP++ Class Library product documentation. This source code cannot
// be used in part or whole in any form outside the TSP++ library.
//
/******************************************************************************/
/*---------------------------------------------------------------------------*/
// INCLUDE FILES
/*---------------------------------------------------------------------------*/
#include "stdafx.h"
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::CTSPIRequest
//
// Constructor for the CTSPIRequest object
//
CTSPIRequest::CTSPIRequest(LPCTSTR pszType) : CTSPIBaseObject(),
m_iReqType(0), m_iReqState(STATE_NOTPROCESSED), m_dwRequestId(0xffffffff),
m_pConnOwner(NULL), m_pAddress(NULL), m_pCall(NULL), m_fResponseSent(false),
m_lResult(-1), m_hevtWait(NULL), m_dwStateTime(0), m_pszType(pszType)
{
}// CTSPIRequest::CTSPIRequest()
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::CTSPIRequest
//
// Copy Constructor for the CTSPIRequest object
//
CTSPIRequest::CTSPIRequest(const CTSPIRequest& src) : CTSPIBaseObject(src)
{
m_iReqState = src.m_iReqState;
m_iReqType = src.m_iReqType;
m_dwRequestId = src.m_dwRequestId;
m_pConnOwner = src.m_pConnOwner;
m_pAddress = src.m_pAddress;
m_pCall = src.m_pCall;
m_fResponseSent = src.m_fResponseSent;
m_lResult = src.m_lResult;
m_hevtWait = NULL;
m_pszType = src.m_pszType;
// Increment the CALL object reference count indicating that we have
// requests associated with it.
if (m_pCall != NULL)
m_pCall->AddRef();
}// CTSPIRequest::CTSPIRequest()
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::~CTSPIRequest
//
// Destructor for the request class
//
CTSPIRequest::~CTSPIRequest()
{
#ifdef _DEBUG
_TSP_DTRACEX(TRC_REQUESTS, _T("Destroying %s"), Dump().c_str());
#endif
// Make sure all threads are unblocked
UnblockThreads();
// Release a reference on the call object this
// request is attached to.
if (m_pCall != NULL)
m_pCall->DecRef();
}// CTSPIRequest::~CTSPIRequest
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::Init
//
// Initialize a CTSPIRequest object for a line/address/call
//
void CTSPIRequest::Init(
CTSPILineConnection* pConn, // Connection for this request
CTSPIAddressInfo* pAddr, // Address line for this request
CTSPICallAppearance* pCall, // Call appearance
int iReqType, // Request type (REQTYPE_xxx)
DRV_REQUESTID dwReqId) // Asynch request id from TAPI
{
// Assign our owners based on the input available.
if (pCall != NULL)
{
m_pCall = pCall;
m_pConnOwner = m_pCall->GetLineOwner();
m_pAddress = m_pCall->GetAddressOwner();
// Increment the CALL object reference count indicating that we have
// requests associated with it.
m_pCall->AddRef();
}
else if (pAddr != NULL)
{
m_pAddress = pAddr;
m_pConnOwner = m_pAddress->GetLineOwner();
}
else
{
m_pConnOwner = pConn;
_TSP_ASSERTE(m_pConnOwner != NULL);
}
// Assign the TYPE of request and the asynch request id.
m_iReqType = iReqType;
m_dwRequestId = dwReqId;
#ifdef _DEBUG
_TSP_DTRACEX(TRC_REQUESTS, _T("Created %s"), Dump().c_str());
#endif
}// TSPIRequest::Init
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::Init
//
// Initialize a CTSPIRequest object for a phone request.
//
void CTSPIRequest::Init(
CTSPIPhoneConnection* pConn, // Connection for this request
int iReqType, // Request type (REQTYPE_xxx)
DRV_REQUESTID dwReqId) // Asynch request id from TAPI
{
m_pConnOwner = pConn;
_TSP_ASSERTE(m_pConnOwner != NULL);
m_iReqType = iReqType;
m_dwRequestId = dwReqId;
#ifdef _DEBUG
_TSP_DTRACEX(TRC_REQUESTS, _T("Created %s"), Dump().c_str());
#endif
}// TSPIRequest::Init
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::UnblockThreads
//
// Force any waiting threads to unblock and resume execution.
//
void CTSPIRequest::UnblockThreads()
{
// If we have an event created with this request AND
// it is currently not signaled then signal it to unblock
// any waiters.
CEnterCode sLock(this);
if (m_hevtWait != NULL)
{
// If we potentially have threads waiting on this object,
// then unblock them and give up our timeslice so we are guarenteed
// that the other threads are awoken.
if (WaitForSingleObject(m_hevtWait, 0) == WAIT_TIMEOUT)
{
SetEvent(m_hevtWait);
sLock.Unlock();
Sleep(0);
sLock.Lock();
}
// Delete the event.
CloseHandle(m_hevtWait);
m_hevtWait = NULL;
}
}// CTSPIRequest::UnblockThreads
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::Complete
//
// This causes the request to be completed. It is invoked by
// the device when the request is finished.
//
void CTSPIRequest::Complete (LONG lResult, bool fSendTapiNotification)
{
#ifdef _DEBUG
_TSP_DTRACEX(TRC_REQUESTS, _T("Completing [0x%lx] %s"), lResult, Dump().c_str());
#endif
// Mark this as completed.
if (m_fResponseSent == false)
m_fResponseSent = fSendTapiNotification;
m_lResult = lResult;
// Tell the connection, address, and call that the request completed.
if (m_pConnOwner != NULL)
m_pConnOwner->OnRequestComplete (this, lResult);
if (m_pAddress != NULL)
m_pAddress->OnRequestComplete (this, lResult);
if (m_pCall != NULL)
m_pCall->OnRequestComplete (this, lResult);
// If the request failed, call our virtual "failure" function
if (lResult != 0)
Failed(lResult);
// If we have waiting threads, then unblock them and give them a chance to run.
UnblockThreads();
}// CTSPIRequest::Complete
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::WaitForCompletion
//
// This function pauses the current thread waiting for this request
// to complete.
//
LONG CTSPIRequest::WaitForCompletion(DWORD dwMsecs)
{
// Wait until a final result is given.
if (m_lResult == -1L)
{
// Create an event if necessary. Make sure to unlock the
// request before we actually block the thread.
CEnterCode sLock(this);
if (m_hevtWait == NULL)
m_hevtWait = CreateEvent(NULL, TRUE, FALSE, NULL);
sLock.Unlock();
// Wait for the event to be set by the CTSPIRequest::Complete() function.
#ifdef _DEBUG
_TSP_DTRACEX(TRC_THREADS, _T("Pausing thread 0x%lx on request %s"), GetCurrentThreadId(), Dump().c_str());
#endif
if (WaitForSingleObject (m_hevtWait, dwMsecs) == WAIT_TIMEOUT)
return -1L;
}
return m_lResult;
}// CTSPIRequest::WaitForCompletion
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::EnterState
//
// Thread-safe entry for processing requests. Returns true if the
// current state of the request is "iLookForState" and then sets the
// state to "iNextState" to stop any other threads from locking packet.
//
bool CTSPIRequest::EnterState(int iLookForState, int iNextState)
{
_TSP_ASSERTE(iLookForState != iNextState);
_TSP_ASSERTE(m_iReqState != 0xdddddddd); // Deleted request.
CEnterCode sLock(this, false);
if (sLock.Lock(50))
{
if (m_iReqState == iLookForState)
{
SetState(iNextState);
return true;
}
}
return false;
}// CTSPIRequest::EnterState
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::Failed
//
// This is a virtual function called when a request fails. It gives the
// request an opportunity to perform cleanup on failure.
//
void CTSPIRequest::Failed(LONG /*lResult*/)
{
/* Do nothing */
}// CTSPIRequest::Failed
///////////////////////////////////////////////////////////////////////////
// RTForward::Failed
//
// Delete our call appearance when a forward request fails.
//
void RTForward::Failed(LONG /*lResult*/)
{
// Delete the call if the forwarding request failed and we never
// notified TAPI about call-state changes.
CTSPICallAppearance* pConsult = GetConsultationCall();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTForward::Failed
///////////////////////////////////////////////////////////////////////////
// RTSetupTransfer::Failed
//
// Delete our call appearance when the request fails.
//
void RTSetupTransfer::Failed(LONG /*lResult*/)
{
// Delete the call if the transfer request failed and we never
// notified TAPI about call-state changes.
CTSPICallAppearance* pConsult = GetConsultationCall();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTSetupTransfer::Failed
///////////////////////////////////////////////////////////////////////////
// RTCompleteTransfer::Failed
//
// Delete our call appearance when the request fails.
//
void RTCompleteTransfer::Failed(LONG /*lResult*/)
{
CTSPIConferenceCall* pConf = GetConferenceCall();
if (pConf != NULL &&
(pConf->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConf->GetAddressOwner()->RemoveCallAppearance(pConf);
// Reset the related conference call of the other two calls.
if (GetCallInfo() != NULL)
GetCallInfo()->SetConferenceOwner(NULL);
if (GetConsultationCall() != NULL)
GetConsultationCall()->SetConferenceOwner(NULL);
}// RTCompleteTransfer::Failed
///////////////////////////////////////////////////////////////////////////
// RTPrepareAddToConference::Failed
//
// Delete our call appearance when the request fails.
//
void RTPrepareAddToConference::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetConsultationCall();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTPrepareAddToConference::Failed
///////////////////////////////////////////////////////////////////////////
// RTSetupConference::Failed
//
// Delete our call appearance when the request fails.
//
void RTSetupConference::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetConsultationCall();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
// Unattach our original call if present.
pConsult = GetOriginalCall();
if (pConsult != NULL)
pConsult->SetConferenceOwner(NULL);
// And idle the conference.
CTSPIConferenceCall* pConf = GetConferenceCall();
if (pConf != NULL &&
(pConf->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConf->GetAddressOwner()->RemoveCallAppearance(pConf);
else
pConf->SetCallState(LINECALLSTATE_IDLE);
}// RTSetupConference::Failed
///////////////////////////////////////////////////////////////////////////
// RTMakeCall::Failed
//
// Delete our call appearance when the request fails.
//
void RTMakeCall::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetCallInfo();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTMakeCall::Failed
///////////////////////////////////////////////////////////////////////////
// RTPickup::Failed
//
// Delete our call appearance when the request fails.
//
void RTPickup::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetCallInfo();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTPickup::Failed
///////////////////////////////////////////////////////////////////////////
// RTUnpark::Failed
//
// Delete our call appearance when the request fails.
//
void RTUnpark::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetCallInfo();
if (pConsult != NULL &&
(pConsult->GetCallFlags() & CTSPICallAppearance::_InitNotify) == 0)
pConsult->GetAddressOwner()->RemoveCallAppearance(pConsult);
}// RTUnpark::Failed
///////////////////////////////////////////////////////////////////////////
// RTDropCall::Failed
//
// Unmark the drop flag when the request fails.
//
void RTDropCall::Failed(LONG /*lResult*/)
{
CTSPICallAppearance* pConsult = GetCallInfo();
CEnterCode sLock (pConsult);
pConsult->m_dwFlags &= ~CTSPICallAppearance::_IsDropped;
}// RTDropCall::Failed
///////////////////////////////////////////////////////////////////////////
// RTGenerateDigits::Failed
//
// Cancel the generation request when it fails.
//
void RTGenerateDigits::Failed(LONG /*lResult*/)
{
GetLineOwner()->Send_TAPI_Event(GetCallInfo(),
LINE_GENERATE, LINEGENERATETERM_CANCEL,
GetIdentifier(), GetTickCount());
}// RTGenerateDigits::Failed
///////////////////////////////////////////////////////////////////////////
// RTGenerateTone::Failed
//
// Cancel the generation request when it fails.
//
void RTGenerateTone::Failed(LONG /*lResult*/)
{
GetLineOwner()->Send_TAPI_Event(GetCallInfo(), LINE_GENERATE, LINEGENERATETERM_CANCEL, GetIdentifier(), GetTickCount());
}// RTGenerateDigits::Failed
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTForward::~RTForward
//
// Destructor for the lineForward request object
//
RTForward::~RTForward()
{
if (m_parrForwardInfo != NULL)
std::for_each(m_parrForwardInfo->begin(), m_parrForwardInfo->end(), MEM_FUNV(&TSPIFORWARDINFO::DecUsage));
FreeMem(m_lpCallParams);
}// RTForward::~RTForward
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTMakeCall::~RTMakeCall
//
// Destructor for the MakeCall event
//
RTMakeCall::~RTMakeCall()
{
FreeMem(m_lpCallParams);
}// RTMakeCall::~RTMakeCall
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTSetupConference::~RTSetupConference
//
// Destructor for the RTSetupConference object
//
RTSetupConference::~RTSetupConference()
{
FreeMem(m_lpCallParams);
}// RTSetupConference::~RTSetupConference
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTSetupTransfer::~RTSetupTransfer
//
// Destructor for the RTSetupTransfer object
//
RTSetupTransfer::~RTSetupTransfer()
{
FreeMem(m_lpCallParams);
}// RTSetupTransfer::~RTSetupTransfer
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTSetMediaControl::~RTSetMediaControl
//
// Request to manage the lineSetMediaControl event
//
RTSetMediaControl::~RTSetMediaControl()
{
// Decrement the reference count on the media control structure
if (m_pMediaControl != NULL)
m_pMediaControl->DecUsage();
}// RTSetMediaControl::~RTSetMediaControl
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTPrepareAddToConference::~RTPrepareAddToConference
//
// Constructor for the RTPrepareAddToConference object
//
RTPrepareAddToConference::~RTPrepareAddToConference()
{
FreeMem(m_lpCallParams);
}// RTPrepareAddToConference::~RTPrepareAddToConference
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTGenerateTone::~RTGenerateTone
//
// Destructor - delete tone list.
//
RTGenerateTone::~RTGenerateTone()
{
delete m_parrTones;
}// RTGenerateTone::~RTGenerateTone
///////////////////////////////////////////////////////////////////////////
// RTSetAgentGroup::~RTSetAgentGroup
//
// Destructor for the lineSetAgentGroup request.
//
RTSetAgentGroup::~RTSetAgentGroup()
{
delete m_parrGroups;
}// RTSetAgentGroup::~RTSetAgentGroup
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// RTSetButtonInfo::~RTSetButtonInfo
//
// Destructor for the phoneSetButtonInfo request
//
RTSetButtonInfo::~RTSetButtonInfo()
{
FreeMem(m_lpbi);
}// RTSetButtonInfo::~RTSetButtonInfo
#ifdef _DEBUG
///////////////////////////////////////////////////////////////////////////
// CTSPIRequest::Dump
//
// Debug method to dump out the TSPI Request block
//
TString CTSPIRequest::Dump() const
{
TStringStream outstm;
outstm << _T("0x") << hex << reinterpret_cast<DWORD>(this) << _T(" ");
LPCTSTR pszName = GetRequestName();
if (pszName == NULL)
pszName = _T("(Unknown Type)");
outstm << _T("0x") << hex << m_iReqType << _T(" ") << pszName << endl;
outstm << _T(" DRV_REQUESTID=0x") << hex << m_dwRequestId;
outstm << _T(",RefCnt=") << GetRefCount();
outstm << _T(",State=");
switch (m_iReqState)
{
case STATE_INITIAL: outstm << _T("Initial"); break;
case STATE_IGNORE: outstm << _T("Processing"); break;
case STATE_NOTPROCESSED: outstm << _T("Not Started"); break;
case STATE_COMPLETED: outstm << _T("Completed"); break;
default: outstm << _T("0x") << hex << m_iReqState; break;
}
outstm << _T(",ResponseSent=") << (m_fResponseSent) ? _T("Y") : _T("N");
if (m_pCall != NULL) outstm << endl << _T(" Call:") << m_pCall->Dump();
outstm << endl << _T(" Owner:") << m_pConnOwner->Dump() << endl;
return (outstm.str());
}// CTSPIRequest::Dump
#endif // _DEBUG
| [
"Owner@.(none)"
] | [
[
[
1,
589
]
]
] |
e9ae30dc612430259893936e8a357182c5b0b67b | bf19f77fdef85e76a7ebdedfa04a207ba7afcada | /NewAlpha/TMNT Tactics Tech Demo/Source/Animation.cpp | 4ff0b0c1828aeea514b9006d08b48db58d487e96 | [] | no_license | marvelman610/tmntactis | 2aa3176d913a72ed985709843634933b80d7cb4a | a4e290960510e5f23ff7dbc1e805e130ee9bb57d | refs/heads/master | 2020-12-24T13:36:54.332385 | 2010-07-12T08:08:12 | 2010-07-12T08:08:12 | 39,046,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,405 | cpp | ////////////////////////////////////////////////////////
// File Name : "CAnimation.cpp"
//
// Author : Matthew Di Matteo (MD)
//
// Purpose : This file provides a way to set and control
// the animations of the game objects
////////////////////////////////////////////////////////
#include "Animation.h"
#include <fstream>
#include <exception>
using namespace std;
#include "CSGD_TextureManager.h"
#include "Game.h" // in case of error, throw back to main menu
#include "MainMenuState.h" // same as above
CAnimation::CAnimation(void)
{
m_nTotalFrames = 0;
m_nCurrFrame = 0;
m_fTimeWaited = 0;
m_bIsPlaying = false;
m_bIsLooping = true;
bFacingLeft = false;
m_fSpeed = 1.0f;
m_nImageID = -1;
m_pFrames = NULL;
}
CAnimation::~CAnimation(void)
{
/*if (m_pFrames)
{
delete[] m_pFrames;
}*/
}
void CAnimation::Play()
{
Reset();
m_bIsPlaying = true;
//////////////////////////////////////////////////////////////////////////
// TEMP
//m_bIsLooping = true;
}
void CAnimation::Stop()
{
m_bIsPlaying = false;
}
void CAnimation::Resume()
{
m_bIsPlaying = true;
}
void CAnimation::Reset()
{
m_nCurrFrame = 0;
}
void CAnimation::Load(const char* FileName, int numFrame, float duration, bool Looping)
{
int nDuration;
char bIsLooping[128] = "true ";
char filebuff[128];
ifstream ifs;
ifs.exceptions(~ios_base::goodbit);
try
{
ifs.open(FileName, ios_base::in| ios_base::binary);
if (ifs.is_open())
{
unsigned char size;
int numSize;
ifs.read(reinterpret_cast<char *>(&numSize),4);
for(int i = 1; i <= numFrame && i <= numSize;i++)
{
ifs.read(reinterpret_cast<char *>(&m_nTotalFrames),4);
ifs.read(reinterpret_cast<char *>(&size),1);
ZeroMemory(filebuff,128);
ifs.read(filebuff,size);
m_nAnimName = filebuff; //2
ifs.read(reinterpret_cast<char *>(&size),1);
ZeroMemory(filebuff,128);
ifs.read(filebuff,size);
char temp[128];
sprintf_s(temp, _countof(temp),"Resources/Images/%s", filebuff);
CSGD_TextureManager* tm = CSGD_TextureManager::GetInstance();
m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture(temp, D3DCOLOR_XRGB(255,255,255));
ifs.read(reinterpret_cast<char *>(&size),1);
ZeroMemory(filebuff,128);
ifs.read(filebuff,size);
m_nTriggerName = filebuff; // flying
ifs.read(reinterpret_cast<char *>(&size),1);
ZeroMemory(filebuff,128);
ifs.read(filebuff,size);
m_nTriggerType = filebuff; //particle
ifs.read(reinterpret_cast<char *>(&size),1);
ZeroMemory(filebuff,128);
ifs.read(filebuff,size);
//if(strcmp(filebuff,bIsLooping))
m_bIsLooping = true;
//else
// m_bIsLooping = false;
ifs.read(reinterpret_cast<char *>(&nDuration),4); //0.35
//m_fDuration = nDuration / 1000.0f;
m_pFrames = new sFrame[m_nTotalFrames];
for(int j = 0; j < m_nTotalFrames; j++)
{
ifs.read(reinterpret_cast<char *>(&(m_pFrames[j].nFrameX)),4);
ifs.read(reinterpret_cast<char *>(&m_pFrames[j].nFrameY),4);
ifs.read(reinterpret_cast<char *>(&m_pFrames[j].nFrameWidth),4);
ifs.read(reinterpret_cast<char *>(&m_pFrames[j].nFrameHeight),4);
ifs.read(reinterpret_cast<char *>(&m_pFrames[j].nAnchorX),4);
ifs.read(reinterpret_cast<char *>(&m_pFrames[j].nAnchorY),4);
m_pFrames[j].nAnchorX = m_pFrames[j].nAnchorX - m_pFrames[j].nFrameX;
m_pFrames[j].nAnchorY = m_pFrames[j].nAnchorY - m_pFrames[j].nFrameY;
}
if(i != numFrame)
{
delete[] m_pFrames;
m_pFrames = NULL;
}
if(i == numFrame)
{
m_fDuration = duration;
m_bIsLooping = Looping;
}
}
}
else
{
char szBuffer[128];
sprintf_s(szBuffer, "Failed to open file: %s", FileName );
MessageBox(0, szBuffer, "Error.", MB_OK);
CGame::GetInstance()->ChangeState(CMainMenuState::GetInstance());
}
}
catch (ios_base::failure &)
{
if (!ifs.eof())
throw;
}
ifs.close();
}
void CAnimation::Update(float fElapsedtime)
{
if(!m_bIsPlaying)
return;
m_fTimeWaited += fElapsedtime * m_fSpeed;
if(m_fTimeWaited > m_fDuration)
{
m_nCurrFrame++;
//m_fTimeWaited = 0;
m_fTimeWaited -= m_fDuration;
if(m_nCurrFrame >= m_nTotalFrames)
{
if(m_bIsLooping)
m_nCurrFrame = 0;
else
{
Stop();
m_nCurrFrame = m_nTotalFrames-1;
}
}
}
}
void CAnimation::Render(int posx, int posy, float posZ, float scale, DWORD dwColor)
{
if(m_nImageID !=-1)
{
RECT frame = {m_pFrames[m_nCurrFrame].nFrameX, m_pFrames[m_nCurrFrame].nFrameY,
m_pFrames[m_nCurrFrame].nFrameX + m_pFrames[m_nCurrFrame].nFrameWidth, m_pFrames[m_nCurrFrame].nFrameY+m_pFrames[m_nCurrFrame].nFrameHeight};
float fScaleX = scale;
if(bFacingLeft) // flip
{
//manipulate scale and pos
fScaleX *=-1;
posx += int(m_pFrames[m_nCurrFrame].nFrameWidth*scale);
}
//draw stuff to screen
CSGD_TextureManager::GetInstance()->DrawWithZSort(m_nImageID, posx-m_pFrames[m_nCurrFrame].nAnchorX, posy - m_pFrames[m_nCurrFrame].nAnchorY, posZ,
fScaleX,
scale,
&frame,
0, 0,0, dwColor);
int test = 0;
}
}
void CAnimation::Unload()
{
if(m_pFrames)
{
delete[] m_pFrames;
m_pFrames = NULL;
}
} | [
"AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"marvelman610@7dc79cba-3e6d-11de-b8bc-ddcf2599578a"
] | [
[
[
1,
28
],
[
31,
31
],
[
33,
51
],
[
53,
65
],
[
67,
118
],
[
120,
121
],
[
123,
123
],
[
126,
127
],
[
129,
147
],
[
153,
153
],
[
155,
172
],
[
174,
197
],
[
199,
212
],
[
214,
222
],
[
228,
228
]
],
[
[
29,
30
],
[
32,
32
],
[
52,
52
],
[
66,
66
],
[
119,
119
],
[
122,
122
],
[
124,
125
],
[
128,
128
],
[
148,
152
],
[
154,
154
],
[
173,
173
],
[
198,
198
],
[
213,
213
],
[
223,
227
]
]
] |
74d761b79598f12e2a2e384ce7023540535ef54e | 63fc6506b8e438484a013b3c341a1f07f121686b | /addons/ofxVectorMath/example/testApp.h | 91d3b27621263176ad642af4f6ceaf1f8ec84466 | [] | no_license | progen/ofx-dev | c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8 | 45125fcab657715abffc7e84819f8097d594e28c | refs/heads/master | 2021-01-20T07:15:39.755316 | 2009-03-03T22:33:37 | 2009-03-03T22:33:37 | 140,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#define OF_ADDON_USING_OFXVECTORMATH
#include "ofAddons.h"
#define MAX_N_PTS 1500
class testApp : public ofSimpleApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased (int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased();
ofxVec3f pts[MAX_N_PTS];
int nPts;
ofxVec3f rotateAmount; // amount to rotate in x,y,z;
float speedOfRotation; // speed;
// a grid helpful for seeing the rotation
ofxVec3f xAxisMin;
ofxVec3f xAxisMax;
ofxVec3f yAxisMin;
ofxVec3f yAxisMax;
ofxVec3f zAxisMin;
ofxVec3f zAxisMax;
bool bDrawnAnything;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
43f4c2c7840e5816c0d62d398e9e1137b95c4193 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D11/D3D11ComputeShader.h | e2c683abdc0b2763c2830084a722ff6fb80479c9 | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 846 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "D3D11DeviceChild.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D11 {
using namespace System;
/// <summary>
/// A compute-shader class manages an executable program (a compute shader) that controls the compute-shader stage.
/// <para>(Also see DirectX SDK: ID3D11ComputeShader)</para>
/// </summary>
public ref class ComputeShader :
public Microsoft::WindowsAPICodePack::DirectX::Direct3D11::DeviceChild
{
public:
internal:
ComputeShader()
{
}
internal:
ComputeShader(ID3D11ComputeShader* pNativeID3D11ComputeShader)
{
Attach(pNativeID3D11ComputeShader);
}
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
31
]
]
] |
64b867ae0ef8ffa8b558c06c9fc98a127f8fee2e | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/SynchronizedStringPool.hpp | edb1c76dddbfbacefba61e22e8ce64ac4620a788 | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,285 | hpp | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: SynchronizedStringPool.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(SYNCHRONIZEDSTRINGPOOL_HPP)
#define SYNCHRONIZEDSTRINGPOOL_HPP
#include <xercesc/framework/MemoryManager.hpp>
#include <xercesc/util/StringPool.hpp>
#include <xercesc/util/Mutexes.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//
// This class provides a synchronized string pool implementation.
// This will necessarily be slower than the regular StringPool, so it
// should only be used when updates need to be made in a thread-safe
// way. Updates will be made on datastructures local to this object;
// all queries that don't involve mutation will first be directed at
// the StringPool implementation with which this object is
// constructed.
class XMLUTIL_EXPORT XMLSynchronizedStringPool : public XMLStringPool
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
XMLSynchronizedStringPool
(
const XMLStringPool * constPool
, const unsigned int modulus = 109
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
virtual ~XMLSynchronizedStringPool();
// -----------------------------------------------------------------------
// Pool management methods
// -----------------------------------------------------------------------
virtual unsigned int addOrFind(const XMLCh* const newString);
virtual bool exists(const XMLCh* const newString) const;
virtual bool exists(const unsigned int id) const;
virtual void flushAll();
virtual unsigned int getId(const XMLCh* const toFind) const;
virtual const XMLCh* getValueForId(const unsigned int id) const;
virtual unsigned int getStringCount() const;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLSynchronizedStringPool(const XMLSynchronizedStringPool&);
XMLSynchronizedStringPool& operator=(const XMLSynchronizedStringPool&);
// -----------------------------------------------------------------------
// private data members
// fConstPool
// the pool whose immutability we're protecting
// fMutex
// mutex to permit synchronous updates of our StringPool
const XMLStringPool* fConstPool;
XMLMutex fMutex;
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
85
]
]
] |
790276db9f23f0e40676b20bcaed8b79510845d2 | 75e75a56904ca987dc24a601526b6a3987aaa3ef | /imas-patcher/mif.cc | 5068d5a4a3e3ecd4cdf799af4d4a06196b2fca4a | [] | no_license | Waldenth/imas-psp | 630af722a80a7db5202ba6f0057855f83f9d533f | 88110ee37efdc5fd59f1b86ba7a42af217d5a03f | refs/heads/master | 2023-06-15T07:43:38.212195 | 2009-09-08T04:45:55 | 2009-09-08T04:45:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,678 | cc | #include "mif.h"
MifFile::MifFile(rwops *rw){
QString line;
int count;
line=rw->readline();
QRegExp first("(//)?MIF\\s*(\\d+)\\s*");
QRegExp lines("^\\{\\s*(\\d+),\\s*(\\d+),\\s*(\\d+),\\s*(\\d+),\\s*(\\d+),\\s*(\\d+)\\},\\s*");
ASSUME(first.exactMatch(line),"not a proper MIF file");
count=first.cap(2).toInt();
for(int i=0;i<count;i++){
line=rw->readline();
ASSUME(lines.indexIn(line)!=-1,QString("line %1: couldn't parse").arg(rw->line()));
MifFileNode *node=new MifFileNode;
node->x=lines.cap(1).toInt();
node->y=lines.cap(2).toInt();
node->w=lines.cap(3).toInt();
node->h=lines.cap(4).toInt();
node->a=lines.cap(5).toInt();
node->b=lines.cap(6).toInt();
node->index=i;
nodes.append(node);
}
error:
return;
}
QByteArray MifFile::spit(){
QByteArray res;
QByteArray dd;
dd=QString("MIF%1\n").arg(nodes.count(),5).toAscii();
res+=dd;
for(int i=0;i<nodes.count();i++){
MifFileNode *node=nodes.at(i);
dd=QString("{%1,%2,%3,%4,%5,%6},\n")
.arg(node->x,4).arg(node->y,4).arg(node->w,4)
.arg(node->h,4).arg(node->a,4).arg(node->b,4)
.toAscii();
res+=dd;
}
return res;
}
static quint32 colors_array[]={
#include "mif-colors.c.inc"
};
static QHash<quint32,int> colors;
static bool mifSortBySize(const MifFileNode *a,const MifFileNode *b){
int sd=a->w*a->h-b->w*b->h;
if(sd!=0) return sd<0;
return a->index<b->index;
}
MifConversionResult MifFile::read(QImage picture){
QList<MifFileNode *> remap=nodes;
qSort(remap.begin(),remap.end(),mifSortBySize);
QHash<quint64,MifFileNode *> map,aliases;
int i;
MifConversionResult res={0,0};
QList<MifFileNode *> new_nodes;
if(colors.isEmpty()){
for(uint i=0;i<sizeof(colors_array)/sizeof(colors_array[0]);i++){
colors.insert(colors_array[i],i);
}
}
for(i=0;i<nodes.count();i++){
MifFileNode *node=nodes.at(i);
MifFileNode *new_node=new MifFileNode;
new_node->x=new_node->y=0x7fffffff;
new_node->w=new_node->h=-1;
new_node->index=node->index;
new_nodes.append(new_node);
}
QImage image=picture.convertToFormat(QImage::Format_ARGB32);
for(int y=0,h=image.height();y<h;y++){
uchar *d=image.scanLine(y);
for(int x=0,w=image.width();x<w;x++){
if(d[x*4+3]!=0xff) continue;
quint32 color=*(quint32 *)(d+x*4)&0x00ffffff;
int index=colors.value(color,-1);
ASSUME(index!=-1 && index<new_nodes.count(),QString("Unexpected color #%1 at (%2,%3)")
.arg(color,8,16,QChar('0')).arg(x).arg(y));
MifFileNode *new_node=new_nodes.at(index);
if(new_node->x>x) new_node->x=x;
if(new_node->y>y) new_node->y=y;
if(new_node->w<x) new_node->w=x;
if(new_node->h<y) new_node->h=y;
}
}
for(i=0;i<nodes.count();i++){
remap.append(nodes.at(i));
}
for(i=0;i<remap.count();i++){
MifFileNode *node=remap.at(i);
quint64 key=(((quint64)node->x)<<32)+(node->y);
if(map.contains(key)){
aliases.insert(key,map.value(key));
} else{
map.insert(key,node);
}
}
for(i=0;i<new_nodes.count();i++){
MifFileNode *new_node=new_nodes.at(i);
MifFileNode *node=nodes.at(i);
quint64 key=(((quint64)node->x)<<32)+(node->y);
MifFileNode *alias=aliases.value(key);
if(alias && alias!=node && alias->x!=0x7fffffff){
node->x=alias->x; node->y=alias->y;
res.remapped++;
} else if(new_node->w>0){
node->x=new_node->x; node->y=new_node->y;
node->w=new_node->w-new_node->x+1;
node->h=new_node->h-new_node->y+1;
} else{
res.skipped++;
}
delete new_node;
}
error:
return res;
}
MifFile::~MifFile(){
CLEAR_LIST(nodes);
}
| [
"andrey.osenenko@4c7d9dce-195d-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
157
]
]
] |
ca2b2e97bf790c549ed46fa35b1d168fdf692196 | 2bf221bc84477471c79e47bdb758776176202e0a | /plc/polaczenia.cpp | 344a2affc428081b82dece73035469e344d0fdb8 | [] | no_license | uraharasa/plc-programming-simulator | 9613522711f6f9b477c5017e7e1dd0237316a3f4 | a03e068db8b9fdee83ae4db8fe3666f0396000ef | refs/heads/master | 2016-09-06T12:01:02.666354 | 2011-08-14T08:36:49 | 2011-08-14T08:36:49 | 34,528,882 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,179 | cpp | #include "polaczenia.h"
#include "okno_glowne.h"
polaczenie_szeregowe::polaczenie_szeregowe(element * jeden, element * dwa): pierwszy(jeden), drugi(dwa), kasowany(FALSE)
{
nazwa = L"polaczenie_szeregowe";
}
polaczenie_szeregowe::~polaczenie_szeregowe()
{
if (!kasowany)
{
if (pierwszy)
delete pierwszy;
if (drugi)
delete drugi;
}
}
void polaczenie_szeregowe::podaj_rozmiar(int & szerokosc, int & wysokosc, int)
{
pierwszy->podaj_rozmiar(szerokosc, wysokosc);
int temp1, temp2;
drugi->podaj_rozmiar(temp1, temp2);
szerokosc+=temp1;
if (temp2>wysokosc)
wysokosc = temp2;
}
int polaczenie_szeregowe::dzialaj(int wejscie)
{
return drugi->dzialaj(pierwszy->dzialaj(wejscie));
}
void polaczenie_szeregowe::narysuj(HDC kontekst, int, int x, int y)
{
pierwszy->narysuj(kontekst, RYSUJ_NAZWE|RYSUJ_ADRES, x, y);
int szerokosc, wysokosc;
pierwszy->podaj_rozmiar(szerokosc, wysokosc);
drugi->narysuj(kontekst, RYSUJ_NAZWE|RYSUJ_ADRES, x+szerokosc, y);
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc)-20, akt_program_LD->mapuj_y(y)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc), akt_program_LD->mapuj_y(y)+Y_WYJSCIA);
}
void polaczenie_szeregowe::dodaj_hotspot(int x, int y)
{
int szer, wys;
pierwszy->podaj_rozmiar(szer, wys);
pierwszy->dodaj_hotspot(x, y);
drugi->dodaj_hotspot(x+szer, y);
}
ZDARZENIE polaczenie_szeregowe::edytuj(int x, int y, ZDARZENIE zdarzenie, element * &edytowany)
{
int temp_x, temp_y, temp2_x, temp2_y;
pierwszy->podaj_rozmiar(temp_x, temp_y);
if ((x<temp_x)&&(y<temp_y))
{
switch (pierwszy->edytuj(x, y, zdarzenie, edytowany))
{
case NIC_NIE_ROB:
return NIC_NIE_ROB;
case SKASUJ_MNIE:
delete pierwszy;
edytowany = drugi;
kasowany = TRUE;
return ZASTAP_MNIE;
case ZASTAP_MNIE:
delete pierwszy;
pierwszy = edytowany;
return NIC_NIE_ROB;
case ZASTAP_MNIE_I_NIE_KASUJ:
pierwszy = edytowany;
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
drugi->podaj_rozmiar(temp2_x, temp2_y);
if ((x<temp2_x+temp_x)&&(y<temp2_y)&&(x>=temp_x))
{
switch (drugi->edytuj(x-temp_x, y, zdarzenie, edytowany))
{
case NIC_NIE_ROB:
return NIC_NIE_ROB;
case SKASUJ_MNIE:
delete drugi;
edytowany = pierwszy;
kasowany = TRUE;
return ZASTAP_MNIE;
case ZASTAP_MNIE:
delete drugi;
drugi = edytowany;
return NIC_NIE_ROB;
case ZASTAP_MNIE_I_NIE_KASUJ:
drugi = edytowany;
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
void polaczenie_szeregowe::zapisz(FILE * plik)
{
fwrite(nazwa.c_str(), 2, nazwa.length()+1, plik);
pierwszy->zapisz(plik);
drugi->zapisz(plik);
}
polaczenie_szeregowe::polaczenie_szeregowe(FILE * plik)
{
nazwa = L"polaczenie_szeregowe";
pierwszy = akt_narzedzia->rozpoznaj_i_wczytaj(plik);
drugi = akt_narzedzia->rozpoznaj_i_wczytaj(plik);
}
polaczenie_rownolegle::polaczenie_rownolegle(element * jeden, element * dwa): pierwszy(jeden), drugi(dwa), kasowany(FALSE)
{
nazwa = L"polaczenie_rownolegle";
}
polaczenie_rownolegle::~polaczenie_rownolegle()
{
if (!kasowany)
{
if (pierwszy)
delete pierwszy;
if (drugi)
delete drugi;
}
}
void polaczenie_rownolegle::podaj_rozmiar(int & szerokosc, int & wysokosc, int)
{
pierwszy->podaj_rozmiar(szerokosc, wysokosc);
int temp1, temp2;
drugi->podaj_rozmiar(temp1, temp2);
wysokosc+=temp2;
if (temp1>szerokosc)
szerokosc = temp1;
}
int polaczenie_rownolegle::dzialaj(int wejscie)
{
if (pierwszy->dzialaj(wejscie) + drugi->dzialaj(wejscie))
return 1;
else
return 0;
}
void polaczenie_rownolegle::narysuj(HDC kontekst, int, int x, int y)
{
pierwszy->narysuj(kontekst, RYSUJ_NAZWE|RYSUJ_ADRES, x, y);
int szerokosc1, wysokosc1, szerokosc2, wysokosc2;
pierwszy->podaj_rozmiar(szerokosc1, wysokosc1);
drugi->podaj_rozmiar(szerokosc2, wysokosc2);
drugi->narysuj(kontekst, RYSUJ_NAZWE|RYSUJ_ADRES, x, y+wysokosc1);
if (szerokosc1>szerokosc2)
{
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc2)-20, akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-10, akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA);
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-20, akt_program_LD->mapuj_y(y)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-10, akt_program_LD->mapuj_y(y)+Y_WYJSCIA);
}
if (szerokosc2>=szerokosc1)
{
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-20, akt_program_LD->mapuj_y(y)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc2)-10, akt_program_LD->mapuj_y(y)+Y_WYJSCIA);
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc2)-20, akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc2)-10, akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA);
szerokosc1 = szerokosc2;
}
MoveToEx(kontekst, akt_program_LD->mapuj_x(x), akt_program_LD->mapuj_y(y)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x), akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA);
MoveToEx(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-10, akt_program_LD->mapuj_y(y)+Y_WYJSCIA, NULL);
LineTo(kontekst, akt_program_LD->mapuj_x(x+szerokosc1)-10, akt_program_LD->mapuj_y(y+wysokosc1)+Y_WYJSCIA);
}
void polaczenie_rownolegle::dodaj_hotspot(int x, int y)
{
int szer, wys;
pierwszy->podaj_rozmiar(szer, wys);
pierwszy->dodaj_hotspot(x, y);
drugi->dodaj_hotspot(x, y+wys);
}
ZDARZENIE polaczenie_rownolegle::edytuj(int x, int y, ZDARZENIE zdarzenie, element * &edytowany)
{
int temp_x, temp_y, temp2_x, temp2_y;
pierwszy->podaj_rozmiar(temp_x, temp_y);
if ((x<temp_x)&&(y<temp_y))
{
switch (pierwszy->edytuj(x, y, zdarzenie, edytowany))
{
case NIC_NIE_ROB:
return NIC_NIE_ROB;
case SKASUJ_MNIE:
delete pierwszy;
edytowany = drugi;
kasowany = TRUE;
return ZASTAP_MNIE;
case ZASTAP_MNIE:
delete pierwszy;
pierwszy = edytowany;
return NIC_NIE_ROB;
case ZASTAP_MNIE_I_NIE_KASUJ:
pierwszy = edytowany;
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
drugi->podaj_rozmiar(temp2_x, temp2_y);
if ((x<temp2_x)&&(y<temp_y+temp2_y)&&(y>=temp_y))
{
switch (drugi->edytuj(x, y-temp_y, zdarzenie, edytowany))
{
case NIC_NIE_ROB:
return NIC_NIE_ROB;
case SKASUJ_MNIE:
delete drugi;
edytowany = pierwszy;
kasowany = TRUE;
return ZASTAP_MNIE;
case ZASTAP_MNIE:
delete drugi;
drugi = edytowany;
return NIC_NIE_ROB;
case ZASTAP_MNIE_I_NIE_KASUJ:
drugi = edytowany;
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
return NIC_NIE_ROB;
}
void polaczenie_rownolegle::zapisz(FILE * plik)
{
fwrite(nazwa.c_str(), 2, nazwa.length()+1, plik);
pierwszy->zapisz(plik);
drugi->zapisz(plik);
}
polaczenie_rownolegle::polaczenie_rownolegle(FILE * plik)
{
nazwa = L"polaczenie_rownolegle";
pierwszy = akt_narzedzia->rozpoznaj_i_wczytaj(plik);
drugi = akt_narzedzia->rozpoznaj_i_wczytaj(plik);
}
| [
"[email protected]@2c618d7f-f323-8192-d80b-44f770db81a5"
] | [
[
[
1,
252
]
]
] |
712211b09b1d74e66695275efa0b347c9ef06c61 | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /Healthcare/Client/Test/MainDlg.cpp | 47effe8f4f35133d2c980085e6b710402a6d3720 | [] | no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 10,378 | cpp | #include "stdafx.h"
#include "MainDlg.h"
#include "MainFrm.h"
#include "RakPeerInterface.h"
#include "Network.h"
IMPLEMENT_DYNAMIC(MainDlg, CDialog)
MainDlg::MainDlg(CWnd* pParent /*=NULL*/) : CDialog(MainDlg::IDD, pParent)
{
}
MainDlg::~MainDlg()
{
}
void MainDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_DATA_LIST, _dataList);
DDX_Control(pDX, IDC_USER_LIST, _userList);
DDX_Control(pDX, IDC_USERDATA_LIST, _userDataList);
DDX_Control(pDX, IDC_IMAGE, _image);
DDX_Control(pDX, IDC_COMBO_YEAR, _yearList);
DDX_Control(pDX, IDC_COMBO_MONTH, _monthList);
DDX_Control(pDX, IDC_COMBO_DAY, _dayList);
DDX_Control(pDX, IDC_COMBO_HOUR, _hourList);
}
BEGIN_MESSAGE_MAP(MainDlg, CDialog)
ON_WM_SIZE()
ON_WM_CREATE()
ON_WM_DESTROY()
ON_LBN_SELCHANGE(IDC_USER_LIST, &MainDlg::OnLbnSelchangeUserList)
ON_CBN_SELCHANGE(IDC_COMBO_HOUR, &MainDlg::OnCbnSelchangeComboHour)
END_MESSAGE_MAP()
BOOL MainDlg::OnInitDialog()
{
CDialog::OnInitDialog();
if( Network::GetInstance()._isHost )
{
_userList.ShowWindow( TRUE );
_userDataList.ShowWindow( TRUE );
_image.ShowWindow( TRUE );
}
else
{
_userList.ShowWindow( FALSE );
_userDataList.ShowWindow( FALSE );
_image.ShowWindow( FALSE );
}
{
LV_COLUMN lvColumn;
wchar_t * headerName[3] = { L"시간", L"혈류량", L"온도" };
for( int i = 0; i < 3; i++ )
{
lvColumn.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_CENTER;
lvColumn.pszText = headerName[i];
lvColumn.iSubItem = i;
lvColumn.cx = 70;
_dataList.InsertColumn( i, &lvColumn );
}
_dataList.SetExtendedStyle( LVS_EX_FULLROWSELECT );
}
{
LV_COLUMN lvColumn;
wchar_t * headerName[2] = { L"항목", L"내용" };
for( int i = 0; i < 2; i++ )
{
lvColumn.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_CENTER;
lvColumn.pszText = headerName[i];
lvColumn.iSubItem = i;
lvColumn.cx = 70*(i+1);
_userDataList.InsertColumn( i, &lvColumn );
}
_userDataList.SetExtendedStyle( LVS_EX_FULLROWSELECT );
}
m_wndView = new CTestView;
// 프레임의 클라이언트 영역을 차지하는 뷰를 만듭니다.
if (!m_wndView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
CRect(0, 0, 800, 300), this, AFX_IDW_PANE_FIRST, NULL))
{
TRACE0("보기 창을 만들지 못했습니다.\n");
return -1;
}
//
{
CTime t = CTime::GetCurrentTime();
int year = t.GetYear();
int month = t.GetMonth();
int day = t.GetDay();
int hour = t.GetHour();
int curSel = 0;
int index = 0;
for(int num = 2000; num < 2009; num++, index++)
{
CString itemText;
itemText.Format(L"%d 년", num);
_yearList.AddString( itemText );
if( num == year )
{
curSel = index;
}
}
_yearList.SetCurSel( curSel );
index = 0;
for(int num = 1; num < 13; num++, index++)
{
CString itemText;
if( num < 10 )
{
itemText.Format(L"0%d 월", num);
}
else
{
itemText.Format(L"%d 월", num);
}
_monthList.AddString( itemText );
if( num == month )
{
curSel = index;
}
}
_monthList.SetCurSel(curSel);
index = 0;
for(int num = 1; num < 32; num++,index++)
{
CString itemText;
if( num < 10 )
{
itemText.Format(L"0%d 일", num);
}
else
{
itemText.Format(L"%d 일", num);
}
_dayList.AddString( itemText );
if( num == day )
{
curSel = index;
}
}
_dayList.SetCurSel(curSel);
index = 0;
for(int num = 0; num < 24; num++,index++)
{
CString itemText;
if( num < 10 )
{
itemText.Format(L"0%d 시", num);
}
else
{
itemText.Format(L"%d 시", num);
}
_hourList.AddString( itemText );
if( num == hour )
{
curSel = index;
}
}
_hourList.SetCurSel(curSel);
}
_userList.SetCurSel( 0 );
OnLbnSelchangeUserList();
OnCbnSelchangeComboHour();
return TRUE; // return TRUE unless you set the focus to a control
}
BOOL MainDlg::Init( CWnd* parent )
{
//
m_mainFrame = (CMainFrame*)parent;
//
this->Create( IDD_FORMVIEW, parent );
this->SetParent( parent );
this->ShowWindow( true );
CRect rect;
parent->GetClientRect( rect );
this->MoveWindow( 0, 0, 800, 600, TRUE );
return true;
}
void MainDlg::Update( void )
{
}
void MainDlg::RefreshControls()
{
// 유저 인포 데이터 갱신
int index = _userList.GetCurSel();
_userList.ResetContent();
UserList & userInfoList = Network::GetInstance().GetUserInfoList();
int count = userInfoList.size();
for( int num = 0; num < count; num++ )
{
UserInfo & userInfo = userInfoList[ num ];
CString name(userInfo._userName.c_str());
_userList.AddString( (LPTSTR)(LPCTSTR)(name) );
_userList.SetItemData( num, atoi(userInfo._userNo.c_str()) );
}
_userList.SetCurSel( index );
// 유저 데이터 갱신
_dataList.DeleteAllItems();
UserDataList & userDataList = Network::GetInstance().GetUserDataList();
count = userDataList.size();
for(int num = 0; num<count; num++)
{
UserData & data = userDataList[ num ];
CString yearStr;
_yearList.GetLBText( _yearList.GetCurSel(), yearStr );
CString monthStr;
_monthList.GetLBText( _monthList.GetCurSel(), monthStr );
CString dayStr;
_dayList.GetLBText( _dayList.GetCurSel(), dayStr );
CString hourStr;
_hourList.GetLBText( _hourList.GetCurSel(), hourStr );
std::string curYear = data._year + " 년";
std::string curMonth = data._month + " 월";
std::string curDay = data._day + " 일";
std::string curHour = data._hour + " 시";
if( CString(curYear.c_str()) == yearStr &&
CString(curMonth.c_str()) == monthStr &&
CString(curDay.c_str()) == dayStr &&
CString(curHour.c_str()) == hourStr )
{
std::string addStr = data._min + " 분";
CString itemText1( addStr.c_str() );
LV_ITEM lvItem;
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText1;
_dataList.InsertItem(&lvItem);
addStr = data._value + " 회";
CString itemText2( addStr.c_str() );
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText2;
_dataList.SetItem(&lvItem);
addStr = data._temp + " 도";
CString itemText3( addStr.c_str() );
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 2;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText3;
_dataList.SetItem(&lvItem);
}
}
}
void MainDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
}
int MainDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void MainDlg::OnLbnSelchangeUserList()
{
int curindex = _userList.GetCurSel();
if( curindex >= 0 )
{
int userNo = (int)_userList.GetItemData( curindex );
UserList & userInfoList = Network::GetInstance().GetUserInfoList();
int index = Network::GetInstance().GetIndexForUserNo( userNo );
UserInfo & userInfo = userInfoList[ index ];
std::string picPath = "../Test/pic/" + userInfo._pic;
CString age( userInfo._age.c_str() );
CString sex( userInfo._sex.c_str() );
CString tall( userInfo._tall.c_str() );
CString weight( userInfo._weight.c_str() );
CString blood( userInfo._blood.c_str() );
CString tel( userInfo._tel.c_str() );
CString pic( picPath.c_str() );
_userDataList.DeleteAllItems();
LV_ITEM lvItem;
CString itemText;
itemText = "나이";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)age;
_userDataList.SetItem(&lvItem);
itemText = "성별";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 1;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 1;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)sex;
_userDataList.SetItem(&lvItem);
itemText = "키";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 2;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 2;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)tall;
_userDataList.SetItem(&lvItem);
itemText = "몸무게";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 3;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 3;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)weight;
_userDataList.SetItem(&lvItem);
itemText = "혈액형";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 4;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 4;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)blood;
_userDataList.SetItem(&lvItem);
itemText = "전화";
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 5;
lvItem.iSubItem = 0;
lvItem.pszText = (LPTSTR)(LPCTSTR)itemText;
_userDataList.InsertItem(&lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 5;
lvItem.iSubItem = 1;
lvItem.pszText = (LPTSTR)(LPCTSTR)tel;
_userDataList.SetItem(&lvItem);
HBITMAP hBmp = (HBITMAP)LoadImage(NULL, pic, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
_image.SetBitmap( hBmp );
//
m_wndView->SetUserNo( userNo );
//
OnCbnSelchangeComboHour();
}
}
void MainDlg::OnCbnSelchangeComboHour()
{
if( Network::GetInstance()._isHost )
{
int curindex = _userList.GetCurSel();
if( curindex >= 0 )
{
int userNo = (int)_userList.GetItemData( curindex );
Network::GetInstance().ReqGetUserDataSend( userNo );
}
}
else
{
int userNo = Network::GetInstance()._myUserNo;
Network::GetInstance().ReqGetUserDataSend( userNo );
}
}
| [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
] | [
[
[
1,
440
]
]
] |
ffbc306a4c8bc228525cd1e6b4fd302f685e69e3 | 9d6d89a97c85abbfce7e2533d133816480ba8e11 | /src/Engine/Exception/ExceptionBadRessource.cpp | ea8a65324bc1da7949bfa2ab0d7bb1f9d1c390b4 | [] | no_license | polycraft/Bomberman-like-reseau | 1963b79b9cf5d99f1846a7b60507977ba544c680 | 27361a47bd1aa4ffea972c85b3407c3c97fe6b8e | refs/heads/master | 2020-05-16T22:36:22.182021 | 2011-06-09T07:37:01 | 2011-06-09T07:37:01 | 1,564,502 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include "ExceptionBadRessource.h"
namespace Engine
{
ExceptionBadRessource::ExceptionBadRessource() throw()
{
//ctor
}
ExceptionBadRessource::~ExceptionBadRessource() throw()
{
//dtor
}
const char* ExceptionBadRessource::what() const throw()
{
return "Bad type for this ressource";
}
}
| [
"[email protected]",
"bastien@Bastien.(none)"
] | [
[
[
1,
4
],
[
6,
9
],
[
11,
19
]
],
[
[
5,
5
],
[
10,
10
]
]
] |
e5c67b593b036eca41404922a2ed8fbe1393b394 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/Game/GameDll/Environment/BattleDust.cpp | accbbbf23c433ac066e0c995471e0be9d01d6981 | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,693 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2007.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Battle dust system (aka Fog of War)
-------------------------------------------------------------------------
History:
- 01:03:2007: Created by Steve Humphreys
*************************************************************************/
#include "StdAfx.h"
#include "BattleDust.h"
#include "Game.h"
#include "GameCVars.h"
#include "GameRules.h"
#include "IRenderAuxGeom.h"
#include "IEntitySystem.h"
#include "CryPath.h"
//////////////////////////////////////////////////////////////////////////
// CBattleEvent
//////////////////////////////////////////////////////////////////////////
CBattleEvent::CBattleEvent()
: m_worldPos(Vec3(0,0,0))
, m_radius(0)
, m_peakRadius(0)
, m_lifetime(1)
, m_lifeRemaining(1)
, m_numParticles(0)
, m_pParticleEffect(NULL)
, m_entityId(0)
{
}
CBattleEvent::~CBattleEvent()
{
}
bool CBattleEvent::Init(IGameObject *pGameObject)
{
SetGameObject(pGameObject);
if(!GetGameObject()->BindToNetwork())
return false;
if(GetEntity())
m_entityId = GetEntity()->GetId();
if(gEnv->bServer && g_pGame->GetGameRules())
{
CBattleDust* pBD = g_pGame->GetGameRules()->GetBattleDust();
if(pBD)
pBD->NewBattleArea(this);
}
return true;
}
//------------------------------------------------------------------------
void CBattleEvent::PostInit(IGameObject *pGameObject)
{
GetGameObject()->EnableUpdateSlot(this, 0);
}
//------------------------------------------------------------------------
void CBattleEvent::Release()
{
// once this object is released it must also be removed from the list in CBattleDust
if(gEnv->bServer && g_pGame && g_pGame->GetGameRules())
{
CBattleDust* pBD = g_pGame->GetGameRules()->GetBattleDust();
if(pBD)
pBD->RemoveBattleArea(this);
}
delete this;
}
//------------------------------------------------------------------------
void CBattleEvent::FullSerialize(TSerialize ser)
{
ser.BeginGroup("BattleEvent");
ser.Value("worldPos", m_worldPos);
ser.Value("numParticles", m_numParticles);
ser.Value("radius", m_radius);
ser.Value("m_peakRadius", m_peakRadius);
ser.Value("m_lifetime", m_lifetime);
ser.Value("m_lifeRemaining", m_lifeRemaining);
ser.EndGroup();
if(ser.IsReading())
{
m_pParticleEffect = NULL;
m_entityId = (GetEntity() != NULL) ? GetEntity()->GetId() : 0;
}
}
bool CBattleEvent::NetSerialize( TSerialize ser, EEntityAspects aspect, uint8 profile, int flags )
{
if (aspect == PROPERTIES_ASPECT)
{
ser.Value("worldPos", m_worldPos, 'wrld');
ser.Value("numParticles", m_numParticles, 'iii');
}
return true;
}
void CBattleEvent::Update(SEntityUpdateContext &ctx, int updateSlot)
{
IEntity* pEntity = GetEntity();
if(pEntity)
{
Matrix34 tm = pEntity->GetWorldTM();
tm.SetTranslation(m_worldPos);
pEntity->SetWorldTM(tm);
if(m_numParticles > 0 && !m_pParticleEffect)
{
// attach the particle effect to this entity now
m_pParticleEffect = gEnv->pParticleManager->FindEffect(g_pGameCVars->g_battleDust_effect->GetString());
if (m_pParticleEffect)
{
pEntity->LoadParticleEmitter(0, m_pParticleEffect, 0, true, true);
Matrix34 tm = IParticleEffect::ParticleLoc(Vec3(0,0,0));
pEntity->SetSlotLocalTM(0, tm);
}
}
if(m_pParticleEffect)
{
SEntitySlotInfo info;
pEntity->GetSlotInfo(0, info);
if(info.pParticleEmitter)
{
SpawnParams sp;
sp.fCountScale = (float)m_numParticles/60.0f;
info.pParticleEmitter->SetSpawnParams(sp);
}
}
if(g_pGameCVars->g_battleDust_debug != 0)
{
if(g_pGameCVars->g_battleDust_debug >= 2)
{
if(m_numParticles > 0)
{
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_worldPos, m_numParticles, ColorF(0.0f,1.0f,0.0f,0.2f));
}
else
{
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_worldPos, 0.5f, ColorF(1.0f,0.0f,0.0f,0.2f));
}
}
else
{
if(m_numParticles > 0)
{
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_worldPos, 0.5f, ColorF(0.0f,1.0f,0.0f,0.2f));
}
else
{
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_worldPos, 0.5f, ColorF(1.0f,0.0f,0.0f,0.2f));
}
}
}
}
}
//-------------------------------------------------------------------------
void CBattleEvent::GetMemoryUsage(ICrySizer * s) const
{
s->Add(*this);
}
//////////////////////////////////////////////////////////////////////////
// CBattleDust
//////////////////////////////////////////////////////////////////////////
CBattleDust::CBattleDust()
{
m_entitySpawnPower = 0.0f;
m_defaultLifetime = 0.0f;
m_maxLifetime = 0.0f;
m_maxEventPower = 0.0f;
m_pBattleEventClass = NULL;
m_minParticleCount = 0;
m_maxParticleCount = 0;
m_distanceBetweenEvents = 0;
m_maxBattleEvents = 0;
// load xml file and process it
if(!gEnv->bServer)
return;
ReloadXml();
}
CBattleDust::~CBattleDust()
{
}
void CBattleDust::ReloadXml()
{
// first empty out the previous stuff
m_weaponPower.clear();
m_explosionPower.clear();
m_vehicleExplosionPower.clear();
m_bulletImpactPower.clear();
IXmlParser* pxml = g_pGame->GetIGameFramework()->GetISystem()->GetXmlUtils()->CreateXmlParser();
if(!pxml)
return;
XmlNodeRef node = GetISystem()->LoadXmlFromFile(PathUtil::GetGameFolder() + "/Scripts/GameRules/BattleDust.xml");
if(!node)
return;
XmlNodeRef paramsNode = node->findChild("params");
if(paramsNode)
{
paramsNode->getAttr("fogspawnpower", m_entitySpawnPower);
paramsNode->getAttr("defaultlifetime", m_defaultLifetime);
paramsNode->getAttr("maxlifetime", m_maxLifetime);
paramsNode->getAttr("maxeventpower", m_maxEventPower);
paramsNode->getAttr("minparticlecount", m_minParticleCount);
paramsNode->getAttr("maxparticlecount", m_maxParticleCount);
paramsNode->getAttr("distancebetweenevents", m_distanceBetweenEvents);
}
XmlNodeRef eventsNode = node->findChild("events");
if(eventsNode)
{
// corresponds to the eBDET_ShotFired event
XmlNodeRef shotNode = eventsNode->findChild("shotfired");
if(shotNode)
{
for (int i = 0; i < shotNode->getChildCount(); ++i)
{
XmlNodeRef weaponNode = shotNode->getChild(i);
if(weaponNode)
{
XmlString name;
float power = 1.0f;
float lifetime = 1.0f;
weaponNode->getAttr("name", name);
weaponNode->getAttr("power", power);
weaponNode->getAttr("lifetime", lifetime);
if(!strcmp(name, "default"))
{
m_defaultWeapon.m_power = power;
m_defaultWeapon.m_lifetime = lifetime;
}
else
{
SBattleEventParameter param;
param.m_name = name;
param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
param.m_power = power;
param.m_lifetime = lifetime;
m_weaponPower.push_back(param);
}
}
}
}
XmlNodeRef explodeNode = eventsNode->findChild("explosion");
if(explodeNode)
{
for(int i=0; i < explodeNode->getChildCount(); ++i)
{
XmlNodeRef explosiveNode = explodeNode->getChild(i);
if(explosiveNode)
{
XmlString name;
float power = 1.0f;
float lifetime = 1.0f;
explosiveNode->getAttr("name", name);
explosiveNode->getAttr("power", power);
explosiveNode->getAttr("lifetime", lifetime);
if(!strcmp(name, "default"))
{
m_defaultExplosion.m_power = power;
m_defaultExplosion.m_lifetime = lifetime;
}
else
{
SBattleEventParameter param;
param.m_name = name;
param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
param.m_power = power;
param.m_lifetime = lifetime;
m_explosionPower.push_back(param);
}
}
}
}
XmlNodeRef vehicleExplodeNode = eventsNode->findChild("vehicleexplosion");
if(vehicleExplodeNode)
{
for(int i=0; i < vehicleExplodeNode->getChildCount(); ++i)
{
XmlNodeRef vehicleNode = vehicleExplodeNode->getChild(i);
if(vehicleNode)
{
XmlString name;
float power = 1.0f;
float lifetime = 1.0f;
vehicleNode->getAttr("name", name);
vehicleNode->getAttr("power", power);
vehicleNode->getAttr("lifetime", lifetime);
if(!strcmp(name, "default"))
{
m_defaultVehicleExplosion.m_power = power;
m_defaultVehicleExplosion.m_lifetime = lifetime;
}
else
{
SBattleEventParameter param;
param.m_name = name;
param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
param.m_power = power;
param.m_lifetime = lifetime;
m_vehicleExplosionPower.push_back(param);
}
}
}
}
XmlNodeRef impactNode = eventsNode->findChild("bulletimpact");
if(impactNode)
{
for(int i=0; i < impactNode->getChildCount(); ++i)
{
XmlNodeRef impact = impactNode->getChild(i);
if(impact)
{
XmlString name;
float power = 1.0f;
float lifetime = 1.0f;
impact->getAttr("name", name);
impact->getAttr("power", power);
impact->getAttr("lifetime", lifetime);
if(!strcmp(name, "default"))
{
m_defaultBulletImpact.m_power = power;
m_defaultBulletImpact.m_lifetime = lifetime;
}
else
{
SBattleEventParameter param;
param.m_name = name;
param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
param.m_lifetime = lifetime;
param.m_power = power;
m_bulletImpactPower.push_back(param);
}
}
}
}
}
}
void CBattleDust::RecordEvent(EBattleDustEventType event, Vec3 worldPos, const IEntityClass* pClass)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if(!g_pGameCVars->g_battleDust_enable)
return;
if(!gEnv->bServer)
return;
// this typically means the xml file failed to load. Turn off the dust.
if(m_maxParticleCount == 0)
return;
SBattleEventParameter param;
if(!GetEventParams(event, pClass, param))
return;
if(param.m_power == 0 || worldPos.IsEquivalent(Vec3(0,0,0)))
return;
if(m_pBattleEventClass == NULL)
m_pBattleEventClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass( "BattleEvent" );
// first check if we need a new event
bool newEvent = true;
for(std::list<EntityId>::iterator it = m_eventIdList.begin(); it != m_eventIdList.end(); ++it)
{
EntityId areaId = (*it);
CBattleEvent *pBattleArea = FindEvent(areaId);
if(pBattleArea && CheckIntersection(pBattleArea, worldPos, param.m_power))
{
// don't need a new event as this one is within an existing one. Just merge them.
MergeAreas(pBattleArea, worldPos, param.m_power);
pBattleArea->m_lifeRemaining += param.m_lifetime;
pBattleArea->m_lifetime = pBattleArea->m_lifeRemaining;
pBattleArea->m_lifetime = CLAMP(pBattleArea->m_lifetime, 0.0f, m_maxLifetime);
pBattleArea->m_lifeRemaining = CLAMP(pBattleArea->m_lifeRemaining, 0.0f, m_maxLifetime);
newEvent = false;
break;
}
}
if(newEvent)
{
IEntitySystem * pEntitySystem = gEnv->pEntitySystem;
SEntitySpawnParams esp;
esp.id = 0;
esp.nFlags = 0;
esp.pClass = m_pBattleEventClass;
if (!esp.pClass)
return;
esp.pUserData = NULL;
esp.sName = "BattleDust";
esp.vPosition = worldPos;
// when CBattleEvent is created it will add itself to the list
IEntity * pEntity = pEntitySystem->SpawnEntity( esp );
if(pEntity)
{
// find the just-added entity in the list, and set it's properties
IGameObject* pGO = g_pGame->GetIGameFramework()->GetGameObject(pEntity->GetId());
if(pGO)
{
CBattleEvent* pNewEvent = static_cast<CBattleEvent*>(pGO->QueryExtension("BattleEvent"));
if(pNewEvent)
{
pNewEvent->m_radius = param.m_power;
pNewEvent->m_peakRadius = param.m_power;
pNewEvent->m_lifetime = param.m_lifetime;
pNewEvent->m_lifeRemaining = param.m_lifetime;
pNewEvent->m_worldPos = worldPos;
pNewEvent->m_lifetime = CLAMP(pNewEvent->m_lifetime, 0.0f, m_maxLifetime);
pNewEvent->m_lifeRemaining = CLAMP(pNewEvent->m_lifeRemaining, 0.0f, m_maxLifetime);
pGO->ChangedNetworkState(CBattleEvent::PROPERTIES_ASPECT);
}
}
}
}
}
void CBattleDust::NewBattleArea(CBattleEvent* pEvent)
{
if(!g_pGameCVars->g_battleDust_enable)
return;
if (pEvent)
{
m_eventIdList.push_back(pEvent->GetEntityId());
}
}
void CBattleDust::RemoveBattleArea(CBattleEvent* pEvent)
{
if(pEvent)
{
stl::find_and_erase(m_eventIdList, pEvent->GetEntityId());
}
}
void CBattleDust::Update()
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if(!g_pGameCVars->g_battleDust_enable)
{
RemoveAllEvents();
return;
}
if(!gEnv->bServer)
return;
if(g_pGameCVars->g_battleDust_debug != 0)
{
float col[] = {1,1,1,1};
gEnv->pRenderer->Draw2dLabel(50, 40, 2.0f, col, false, "Num BD areas: %d (max %d)", (int32)m_eventIdList.size(), m_maxBattleEvents);
}
float ypos = 60.0f;
// go through the list of areas, remove any which are too small
m_maxBattleEvents = MAX(m_maxBattleEvents, m_eventIdList.size());
std::list<EntityId>::iterator next;
std::list<EntityId>::iterator it = m_eventIdList.begin();
for(; it != m_eventIdList.end(); it = next)
{
next = it; ++next;
EntityId areaId = (*it);
CBattleEvent *pBattleArea = FindEvent(areaId);
if(!pBattleArea)
continue;
if(pBattleArea->m_lifetime > 0.0f)
{
pBattleArea->m_lifeRemaining -= gEnv->pTimer->GetFrameTime();
pBattleArea->m_radius = pBattleArea->m_peakRadius * (pBattleArea->m_lifeRemaining / pBattleArea->m_lifetime);
}
if(g_pGameCVars->g_battleDust_debug != 0)
{
float col[] = {1,1,1,1};
gEnv->pRenderer->Draw2dLabel(50, ypos, 1.4f, col, false, "Area: (%.2f, %.2f, %.2f), Radius: %.2f/%.2f, Particles: %.0f, Lifetime: %.2f/%.2f", pBattleArea->m_worldPos.x, pBattleArea->m_worldPos.y, pBattleArea->m_worldPos.z, pBattleArea->m_radius, pBattleArea->m_peakRadius, pBattleArea->m_numParticles, pBattleArea->m_lifeRemaining, pBattleArea->m_lifetime);
ypos += 10.0f;
}
if(pBattleArea->m_lifeRemaining < 0.0f)
{
// remove it (NB this will also call RemoveBattleArea(), which will remove it from the list)
gEnv->pEntitySystem->RemoveEntity(areaId);
}
else
{
if(pBattleArea->GetEntity())
{
UpdateParticlesForArea(pBattleArea);
}
}
}
}
void CBattleDust::RemoveAllEvents()
{
// go through the list and remove all entities (eg if user switches off battledust)
std::list<EntityId>::iterator next;
std::list<EntityId>::iterator it = m_eventIdList.begin();
for(; it != m_eventIdList.end(); it = next)
{
next = it; ++next;
EntityId areaId = (*it);
// remove it (NB this will also call RemoveBattleArea(), which will remove it from the list)
gEnv->pEntitySystem->RemoveEntity(areaId);
}
}
bool CBattleDust::GetEventParams(EBattleDustEventType event, const IEntityClass* pClass, SBattleEventParameter& out)
{
if(!g_pGameCVars->g_battleDust_enable)
return false;
switch(event)
{
case eBDET_ShotFired:
out = m_defaultWeapon;
if(pClass != NULL)
{
// find weapon name in list.
for(int i=0; i<m_weaponPower.size(); ++i)
{
if(pClass == m_weaponPower[i].m_pClass)
{
out = m_weaponPower[i];
return true;
}
}
}
break;
case eBDET_Explosion:
out = m_defaultExplosion;
if(pClass != NULL)
{
for(int i=0; i<m_explosionPower.size(); ++i)
{
if(pClass == m_explosionPower[i].m_pClass)
{
out = m_explosionPower[i];
return true;
}
}
}
break;
case eBDET_VehicleExplosion:
out = m_defaultVehicleExplosion;
if(pClass != NULL)
{
for(int i=0; i<m_vehicleExplosionPower.size(); ++i)
{
if(pClass == m_vehicleExplosionPower[i].m_pClass)
{
out = m_vehicleExplosionPower[i];
return true;
}
}
}
break;
case eBDET_ShotImpact:
out = m_defaultBulletImpact;
if(pClass != NULL)
{
for(int i=0; i<m_bulletImpactPower.size(); ++i)
{
if(pClass == m_bulletImpactPower[i].m_pClass)
{
out = m_bulletImpactPower[i];
return true;
}
}
}
break;
default:
break;
}
return (out.m_power != 0);
}
bool CBattleDust::CheckForMerging(CBattleEvent* pEvent)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if(!g_pGameCVars->g_battleDust_enable)
return false;
if(!pEvent)
return false;
if(!gEnv->bServer)
return false;
// check if area can merge with nearby areas
for(std::list<EntityId>::iterator it = m_eventIdList.begin(); it != m_eventIdList.end(); ++it)
{
EntityId areaId = (*it);
CBattleEvent *pBattleArea = FindEvent(areaId);
if(!pBattleArea)
continue;
if(CheckIntersection(pEvent, pBattleArea->m_worldPos, pBattleArea->m_radius) && pBattleArea->m_radius > 0 && (pBattleArea != pEvent) && pBattleArea->GetEntity())
{
MergeAreas(pBattleArea, pEvent->m_worldPos, pEvent->m_radius);
return true;
}
}
return false;
}
bool CBattleDust::MergeAreas(CBattleEvent* pExisting, Vec3& pos, float radius)
{
if(!pExisting)
return false;
// increase the size of existing area to take into account toAdd which overlaps.
// NB we don't need the new volume to completely enclose both starting volumes,
// so for now:
// - new centre pos is the average position, weighted by initial radius
// - new radius is total of the two starting radii
float totalRadii = pExisting->m_radius + radius;
float oldFraction = pExisting->m_radius / totalRadii;
float newFraction = radius / totalRadii;
pExisting->m_worldPos = (oldFraction * pExisting->m_worldPos) + (newFraction * pos);
pExisting->m_radius = CLAMP(totalRadii, 0.0f, m_maxEventPower);
pExisting->m_peakRadius = pExisting->m_radius;
// position has moved, so need to serialize
if(pExisting->GetGameObject())
{
pExisting->GetGameObject()->ChangedNetworkState(CBattleEvent::PROPERTIES_ASPECT);
}
return true;
}
void CBattleDust::UpdateParticlesForArea(CBattleEvent* pEvent)
{
float oldParticleCount = pEvent->m_numParticles;
float fraction = CLAMP((pEvent->m_radius - m_entitySpawnPower) / (m_maxEventPower - m_entitySpawnPower), 0.0f, 1.0f);
pEvent->m_numParticles = LERP(m_minParticleCount, m_maxParticleCount, fraction);
if(pEvent->GetGameObject() && oldParticleCount != pEvent->m_numParticles)
{
pEvent->GetGameObject()->ChangedNetworkState(CBattleEvent::PROPERTIES_ASPECT);
}
}
bool CBattleDust::CheckIntersection(CBattleEvent* pEventOne, Vec3& pos, float radius)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if(!pEventOne)
return false;
Vec3 centreToCentre = pos - pEventOne->m_worldPos;
float sumRadiiSquared = (radius * radius) + (pEventOne->m_radius * pEventOne->m_radius);
float distanceSquared = centreToCentre.GetLengthSquared();
return ((distanceSquared < sumRadiiSquared) && (distanceSquared < m_distanceBetweenEvents*m_distanceBetweenEvents));
}
void CBattleDust::Serialize(TSerialize ser)
{
if(ser.GetSerializationTarget() != eST_Network)
{
ser.BeginGroup("BattleDust");
int amount = m_eventIdList.size();
ser.Value("AmountOfBattleEvents", amount);
std::list<EntityId>::iterator begin = m_eventIdList.begin();
std::list<EntityId>::iterator end = m_eventIdList.end();
if(ser.IsReading())
{
m_eventIdList.clear();
for(int i = 0; i < amount; ++i)
{
EntityId id = 0;
ser.BeginGroup("BattleEventId");
ser.Value("BattleEventId", id);
ser.EndGroup();
m_eventIdList.push_back(id);
}
}
else
{
for(; begin != end; ++begin)
{
EntityId id = (*begin);
ser.BeginGroup("BattleEventId");
ser.Value("BattleEventId", id);
ser.EndGroup();
}
}
ser.EndGroup();
}
}
CBattleEvent* CBattleDust::FindEvent(EntityId id)
{
IGameObject *pBattleEventGameObject = g_pGame->GetIGameFramework()->GetGameObject(id);
if(pBattleEventGameObject)
{
return static_cast<CBattleEvent*>(pBattleEventGameObject->QueryExtension("BattleEvent"));
}
return NULL;
} | [
"[email protected]"
] | [
[
[
1,
759
]
]
] |
4498dd2141b2f78b5c53bdad3d82c0a53909268a | e2bbf1e9ccbfea663803cb692d6b6754f37ca3d8 | /MoreOBs/MoreOBs/includes.h | 41a90555d2e1baa033cb137eb07d5d1d11a5f125 | [] | no_license | binux/moreobs | 65efa6143f49a15ee1cdb0eea38670d808415e97 | 8f2319b6d76573c0054fcd40304b620e38527f4c | refs/heads/master | 2021-01-10T14:09:48.174517 | 2010-08-10T07:53:46 | 2010-08-10T07:53:46 | 46,993,885 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | h | #ifndef INCLUDES_H
#define INCLUDES_H
//boost
#include <boost/foreach.hpp>
#include <boost/cstdint.hpp>
typedef boost::int8_t int8_t ;
typedef boost::int_least8_t int_least8_t ;
typedef boost::int_fast8_t int_fast8_t ;
typedef boost::uint8_t uint8_t ;
typedef boost::uint_least8_t uint_least8_t ;
typedef boost::uint_fast8_t uint_fast8_t ;
typedef boost::int16_t int16_t ;
typedef boost::int_least16_t int_least16_t ;
typedef boost::int_fast16_t int_fast16_t ;
typedef boost::uint16_t uint16_t ;
typedef boost::uint_least16_t uint_least16_t ;
typedef boost::uint_fast16_t uint_fast16_t ;
typedef boost::int32_t int32_t ;
typedef boost::int_least32_t int_least32_t ;
typedef boost::int_fast32_t int_fast32_t ;
typedef boost::uint32_t uint32_t ;
typedef boost::uint_least32_t uint_least32_t ;
typedef boost::uint_fast32_t uint_fast32_t ;
#define foreach BOOST_FOREACH
// STL
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <map>
//#include <set>
#include <string>
#include <vector>
#include <list>
using namespace std;
typedef vector<unsigned char> BYTEARRAY;
// time
uint32_t GetCTime( ); // ctime
uint32_t GetTime( ); // seconds
uint32_t GetTicks( ); // milliseconds
// output
#define DEBUG_LEVEL_ERROR 1
#define DEBUG_LEVEL_WARN 2
#define DEBUG_LEVEL_MESSAGE 3
#define DEBUG_LEVEL_PACKET 4
#define DEBUG_LEVEL_PACKET_RECV 5
#define DEBUG_LEVEL_PACKET_SEND 6
void CONSOLE_Print( string message , uint32_t level = DEBUG_LEVEL_MESSAGE );
void DEBUG_Print( string message , uint32_t level = DEBUG_LEVEL_MESSAGE );
void DEBUG_Print( BYTEARRAY b , uint32_t level = DEBUG_LEVEL_MESSAGE );
#endif | [
"17175297.hk@dc2ccb66-e3a1-11de-9043-17b7bd24f792"
] | [
[
[
1,
71
]
]
] |
1e804b10f47fa354f831aadde749e4c99f964736 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/JointPulley.h | 1e295814598ac70b7c58c518a8598ea002e351fe | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,271 | h | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: JointPulley.h
Version: 0.02
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_JOINTPULLEY_H_
#define __INC_JOINTPULLEY_H_
#include "Joint.h"
#include "JointFactory.h"
namespace nGENE
{
/// JointPulley flags
enum nGENEDLL JOINT_PULLEY_FLAGS
{
JPF_IS_RIGID = (1 << 0),
JPF_MOTOR_ENABLED = (1 << 1),
};
/// Spherical Joint descriptor.
typedef struct nGENEDLL SPulleyJointDesc: public SJointDesc
{
Vector3 pulley1; ///< 1st pulley position in world space
Vector3 pulley2; ///< 2nd pulley position in world space
Real distance; ///< The rest length of the rope between objects [0; infinity)
Real stiffness; ///< [0;1]
Real transmission; ///< Transmission ratio [0;1]
dword flags;
SPulleyJointDesc():
distance(0.0f),
stiffness(1.0f),
transmission(1.0f),
flags(0)
{}
} PULLEY_JOINT_DESC;
/** Pulley joint.
@par
This kind of Joint simulates a rope between two bodies
passing over 2 pulleys.
@par
Use object of SPulleyJointDesc when creating this Joint
to describe its features.
*/
class nGENEDLL JointPulley: public Joint
{
EXPOSE_TYPE
private:
/// PhysX pulley descriptor
NxPulleyJointDesc* m_pPulleyDesc;
/// Pointer to the pulley joint.
NxPulleyJoint* m_pPulley;
public:
JointPulley(NxScene* _scene, SJointDesc& _desc);
virtual ~JointPulley();
void init();
void cleanup();
/// Sets Joint motor.
void setMotor(const MOTOR_DESC& _motor);
/// Returns Joint motor.
MOTOR_DESC getMotor();
/// Specifies whether motor should be enabled.
void setMotorEnabled(bool _value);
/// Checks if motor is enabled.
bool isMotorEnabled();
NxJointDesc* getJointDesc();
};
/// Factory to be used for creating spherical joints.
class nGENEDLL JointPulleyFactory: public JointFactory
{
public:
JointPulleyFactory();
~JointPulleyFactory();
Joint* createJoint(NxScene* _scene, JOINT_DESC& _desc);
};
}
#endif | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
101
]
]
] |
f3424ea8d3da91a3b9d88415d371d17a34d39ce0 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/WorkLayer/NatTraversal/NatSocket.h | 6b9d48fc1a394e590c7d1761ce8be63d543cb464 | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,139 | h |
#pragma once
//#include "emule.h"
#include "Preferences.h"
#include "Log.h"
#include "AsyncSocketEx.h"
#include "EMSocket.h"
#include "CLientUDPSocket.h"
#include "Packets.h"
#include "opcodes.h"
////////////////////////////////////////////////////////////////////////////
#define OP_VC_NAT_HEADER 0xf1
#define OP_NAT_SYNC 0xE1
#define OP_NAT_PING 0xE2
#define OP_NAT_REGISTER 0xE4
#define OP_NAT_FAILED 0xE5
#define OP_NAT_REPING 0xE8
#define OP_NAT_SYNC2 0xE9
#define OP_NAT_DATA 0xEA // data segment with a part of the stream
#define OP_NAT_ACK 0xEB // data segment acknowledgement
#define OP_NAT_RST 0xEF // connection closed
////////////////////////////////////////////////////////////////////////////
// Nat config packet tags
#define NTT_VERSION 0x01
#define NTT_MSS_SIZE 0x02
#define NTT_NAT_TYPE 0x11
#define NTT_FIX_PORT 0x12
#define NTT_BUDDY_ID 0xB0
#define NTT_BUDDY_IP 0xB1
#define NTT_BUDDY_PORT 0xB2
#define CT_NAT_TUNNELING 0xE1 // NEO: NATT - [NatTraversal]
#define CT_NEO_FEATURES 'N' // NEO: NMP - [NeoModProt]
#define CT_EMULE_BUDDYID 0xE2 // NEO: NATS - [NatSupport]
const DWORD TM_KEEPALIVE = 20; // 20 seconds
#include "../AsyncSocketEx.h"
class CDataHandler
{
public:
virtual int SendPacket(DWORD ip, WORD port, uchar opcode, const uchar * data, int len) = NULL;
};
#pragma pack(1)
struct sUserModeTCPConfig{
sUserModeTCPConfig(uint32 IP, uint16 Port)
{
TargetIP = IP;
TargetPort = Port;
Version = 0;
MaxSegmentSize = 0;
MaxUploadBufferSize = 0;
MaxDownloadBufferSize = 0;
}
uint32 TargetIP;
uint16 TargetPort;
uint8 Version;
uint32 MaxSegmentSize;
uint32 MaxUploadBufferSize;
uint32 MaxDownloadBufferSize;
};
#pragma pack()
#pragma pack(1)
struct sTransferBufferEntry{
sTransferBufferEntry(uint32 size, const BYTE* data, uint32 Nr)
{
uSize = size;
pBuffer = new BYTE[uSize+1];
memcpy(pBuffer,data,size);
uSequenceNr = Nr;
uSendCount = 0;
uSendTime = 0;
}
~sTransferBufferEntry() { delete [] pBuffer; }
BYTE* pBuffer; // buffered data
uint32 uSize; // data size, <= max segment size
uint32 uSequenceNr; // segment sequence number
uint8 uSendCount; // we will not try resending the packet for ever just a few times
uint32 uSendTime; // time when we send the packet for the RTT and resend timeout
};
#pragma pack()
typedef CRBMap<uint32,sTransferBufferEntry*> TransferBuffer;
///////////////////////////////////////////////////////////////////////////////
// CNatSocket
class CNatSocket// : public CAbstractSocket
{
friend class CNatThread;
public:
enum TraversalType
{
Traversal_none,
Traversal_bysvr,
Traversal_bybuddy,
Traversal_byexchangesource
};
TraversalType m_TraversalType;
CNatSocket(CAsyncSocketEx* Parent);
virtual ~CNatSocket();
// set new User Mode TCP Sonfigurations
void SetConfig(sUserModeTCPConfig* UserModeTCPConfig);
bool IsConfig() {return m_UserModeTCPConfig != NULL;}
//Notifies a listening socket that it can accept pending connection requests by calling Accept.
//virtual void OnAccept(int /*nErrorCode*/) {ASSERT(0);} // this sockets do not listen
//Notifies a socket that the socket connected to it has closed.
virtual void OnClose(int nErrorCode) {if(m_Parent) m_Parent->OnClose(nErrorCode);}
//Notifies a connecting socket that the connection attempt is complete, whether successfully or in error.
virtual void OnConnect(int nErrorCode) {if(m_Parent) m_Parent->OnConnect(nErrorCode);}
//Notifies a listening socket that there is data to be retrieved by calling Receive.
virtual void OnReceive(int nErrorCode) {if(m_Parent) m_Parent->OnReceive(nErrorCode);}
//Notifies a socket that it can send data by calling Send.
virtual void OnSend(int nErrorCode) {if(m_Parent) m_Parent->OnSend(nErrorCode);}
virtual int SendPacket(uchar opcode, const uchar * data, int len);
//Operations
//----------
uchar * GetUserHash()
{
return m_UserHash;
}
#ifdef _DEBUG
void TestBuffer();
#endif
//Establishes a connection to a peer socket.
virtual BOOL Connect(LPCSTR /*lpszHostAddress*/, UINT /*nHostPort*/) { ASSERT(0); return 0; }
virtual BOOL Connect(const SOCKADDR* /*lpSockAddr*/, int /*nSockAddrLen*/) { ASSERT(0); return 0; }
//Receives data from the socket.
int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
//Sends data to a connected socket.
virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
uint32 GetTargetIP() {return m_UserModeTCPConfig ? m_UserModeTCPConfig->TargetIP : 0;}
uint16 GetTargetPort() {return m_UserModeTCPConfig ? m_UserModeTCPConfig->TargetPort : 0;}
void SetTargetAddr(DWORD ip, WORD port)
{
if(m_UserModeTCPConfig)
{
m_UserModeTCPConfig->TargetIP = ip;
m_UserModeTCPConfig->TargetPort = port;
}
}
DWORD GetTimeout()
{
return m_dwTimeToCheck;
}
CAsyncSocketEx * GetParent() const
{
return m_Parent;
}
bool ProcessDataPacket(const BYTE* packet, UINT size);
void ProcessAckPacket(const BYTE* packet, UINT size);
DWORD m_dwConnAskNumber;
void DumpData();
void RenewNatSock();
static int SendPacket(DWORD ip, WORD port, uchar opcode, const uchar * data, int len);
static int SendPacket(DWORD ip, WORD port, const uchar * data, int len);
protected:
DWORD m_dwSendKeepalive, m_dwRecvKeepalive;
DWORD m_dwTimeToCheck;
void CheckForTimeOut();
sUserModeTCPConfig* m_UserModeTCPConfig; // our general settings
#ifdef _DEBUG
virtual void AssertValid() const { }
virtual void Dump(CDumpContext& /*dc*/) const { }
#endif
private:
void SendBufferedSegment(sTransferBufferEntry* BufferEntry);
void SendAckPacket(uint32 uSequenceNr);
//UpStream
//--------
#if defined(REGULAR_TCP)
uint8 m_uDuplicatedACKCount; // count dupplicated ack's if we recive 3 it means we must resend the next segment (Fast Retransmission)
#endif
//uint32 m_uCongestionWindow; // our estimated congestion window
uint32 m_uAdvertisedWindow; // the window size advertised in the last recived ACK
//uint32 m_uCongestionThreshold; // used for slow start and fast recovery
uint32 m_uPendingWindowSize; // the amount of segments currently being on the network
uint32 m_uLastSentSequenceNr; // number of last sent segment
uint32 m_uUploadBufferSize;
TransferBuffer m_UploadBuffer; // Note: unfortunatly the CRBMap does not have a FindFirstKeyBefoure function
// so for the uplaod buffer I reverse the map direction by using mapkey = UINT_MAX-key ;)
//DowmStream
//----------
uint32 m_uLastAcknowledgeSequenceNr; // last sequence number completly pased to the CEMsocket
uint32 m_uMaxSendSequenceNr;
uint32 m_uLastRecvSequenceNr;
#if defined(REGULAR_TCP)
bool m_bSegmentMissing;
#endif
uint32 m_uCurrentSegmentPosition;
uint32 m_uDownloadBufferSize;
bool m_bReNotifyWindowSize;
TransferBuffer m_DownloadBuffer;
//Attributes
uint8 m_ShutDown;
CAsyncSocketEx * m_Parent;
uchar m_UserHash[16];
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
240
]
]
] |
c4175beed0cb6df34b608a6d4d747bba6396a28d | 9b3df03cb7e134123cf6c4564590619662389d35 | /Scene.h | 10ec2942582bec526954ce94658a8560b4f26362 | [] | no_license | CauanCabral/Computacao_Grafica | a32aeff2745f40144a263c16483f53db7375c0ba | d8673aed304573415455d6a61ab31b68420b6766 | refs/heads/master | 2016-09-05T16:48:36.944139 | 2010-12-09T19:32:05 | 2010-12-09T19:32:05 | null | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 2,382 | h | #ifndef __Scene_h
#define __Scene_h
//[]------------------------------------------------------------------------[]
//| |
//| GVSG Graphics Classes |
//| Version 1.0 |
//| |
//| CopyrightŪ 2007, Paulo Aristarco Pagliosa |
//| All Rights Reserved. |
//| |
//[]------------------------------------------------------------------------[]
//
// OVERVIEW: Scene.h
// ========
// Class definition for scene.
#ifndef __Actor_h
#include "Actor.h"
#endif
#ifndef __Light_h
#include "Light.h"
#endif
namespace Graphics
{ // begin namespace Graphics
//////////////////////////////////////////////////////////
//
// Scene: scene class
// =====
class Scene: public NameableObject
{
public:
Color backgroundColor;
Color ambientLight;
// Constructor
Scene(const wchar_t* name = 0):
NameableObject(name),
backgroundColor(Color::black),
ambientLight(Color::gray),
IOR(1)
{
// do nothing
}
// Destructor
virtual ~Scene();
REAL getIOR() const
{
return IOR;
}
void setIOR(REAL ior)
{
IOR = ior > 0 ? ior : 0;
}
int getNumberOfActors() const
{
return actors.size();
}
ActorIterator getActorIterator() const
{
return ActorIterator(actors);
}
int getNumberOfLights() const
{
return lights.size();
}
LightIterator getLightIterator() const
{
return LightIterator(lights);
}
void addActor(Actor*);
void deleteActor(Actor*);
void deleteActors();
void addLight(Light*);
void deleteLight(Light*);
void deleteLights();
void deleteAll()
{
deleteActors();
deleteLights();
}
Actor* findActor(Model*) const;
BoundingBox getBoundingBox() const
{
return boundingBox;
}
BoundingBox computeBoundingBox();
protected:
BoundingBox boundingBox;
REAL IOR;
// Scene components
Actors actors;
Lights lights;
DECLARE_SERIALIZABLE(Scene);
}; // Scene
} // end namespace Graphics
#endif // __Scene_h
| [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
fce22de53e574d7f327dcfda46aeca7e2c020944 | 9b84a00178af5e52d1b44650b09dc76c86a24e1a | /3D World/origin/collisionhandler.cpp | c1a53dce30d5917294906fb73cc29e3baae50090 | [] | no_license | churchmf/Origin | fd7da0fb7f0b28caa6163116785ef5ee176aef47 | 902428e75f4263617986cb1843f76dc6fdd6dc77 | refs/heads/master | 2021-03-12T23:00:03.781560 | 2011-03-10T17:30:19 | 2011-03-10T17:30:19 | 1,457,306 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,642 | cpp | #include "originwindow.h"
bool OriginWindow::checkCollisionWithAll(QList<MyPoint> before, QList<MyPoint> after, MyPoint objPos)
{
// Assume the same number of points before and after the move
int numPoints = before.size();
// Check if there is a collision between any of the points and any objects
for (int i=0; i < numPoints; i++)
{
MyPoint linePoint0 = before.at(i);
MyPoint linePoint1 = after.at(i);
// Check for collisions with each prop in the scene.
for(int j=0; j<scene.propcount; j++)
{
MyObject& prop = scene.prop[j];
//Don't collide with self
if (prop.position.equals(objPos))
continue;
// Check for collisions with each triangular plane of the prop.
for(unsigned int k=0; k<prop.nPlanes; k++)
{
// Get the triangular plane.
MyPlane plane = prop.planes[k];
// Get the object's position.
MyPoint propPos = prop.position;
// Get points on the triangular plane.
MyPoint p1 = prop.points[plane.pids[0]].plus(propPos);
MyPoint p2 = prop.points[plane.pids[1]].plus(propPos);
MyPoint p3 = prop.points[plane.pids[2]].plus(propPos);
// Compute the point of intersection.
MyPoint intersectionPoint;
// Check that the intersection point is within the triangular plane:
if(lineTriangleCollision(p1, p2, p3, linePoint0, linePoint1, intersectionPoint))
{
//printf("collision with prop at (%f,%f,%f)\n",propPos.x,propPos.y,propPos.z);
return true;
}
}
}
// Check for collisions with each object in the scene.
for(int j=0; j<scene.objcount; j++)
{
// Get the Object.
MyObject& sceneObject = scene.obj[j];
//Don't collide with self
if (sceneObject.position.equals(objPos))
continue;
// Check for collisions with each triangular plane of the object.
for(unsigned int k=0; k<sceneObject.nPlanes; k++)
{
// Get the triangular plane.
MyPlane plane = sceneObject.planes[k];
// Get the sceneObject's position.
MyPoint objectPos = sceneObject.position;
// Get points on the triangular plane.
MyPoint p1 = sceneObject.points[plane.pids[0]].plus(objectPos);
MyPoint p2 = sceneObject.points[plane.pids[1]].plus(objectPos);
MyPoint p3 = sceneObject.points[plane.pids[2]].plus(objectPos);
// Compute the point of intersection.
MyPoint intersectionPoint;
// Check that the intersection point is within the boundaries of the triangular plane:
if(lineTriangleCollision(p1, p2, p3, linePoint0, linePoint1, intersectionPoint))
{
//printf("collision with object at (%f,%f,%f)\n",objectPos.x,objectPos.y,objectPos.z);
return true;
}
}
}
}
return false;
}
bool OriginWindow::lineTriangleCollision(MyPoint& TP1, MyPoint& TP2, MyPoint& TP3, MyPoint& LP1, MyPoint& LP2, MyPoint& HitPos)
{
MyPoint normal, IntersectPos;
// Find Triangle Normal
normal = TP2.minus(TP1).cross(TP3.minus(TP1));
normal.normalize(); // not really needed
// Find distance from LP1 and LP2 to the plane defined by the triangle
float Dist1 = (LP1.minus(TP1)).dot( normal );
float Dist2 = (LP2.minus(TP1)).dot( normal );
if ( (Dist1 * Dist2) >= 0.0f) return false; // line doesn't cross the triangle.
if ( Dist1 == Dist2) return false;// line and plane are parallel
// Find point on the line that intersects with the plane
IntersectPos = LP1.plus(LP2.minus(LP1).times(-Dist1/(Dist2-Dist1)));
// Find if the intersection point lies inside the triangle by testing it against all edges
MyPoint vTest;
vTest = normal.cross(TP2.minus(TP1));
if(vTest.dot(IntersectPos.minus(TP1)) < 0.0f) return false;
vTest = normal.cross(TP3.minus(TP2));
if(vTest.dot(IntersectPos.minus(TP2)) < 0.0f) return false;
vTest = normal.cross(TP1.minus(TP3));
if(vTest.dot(IntersectPos.minus(TP1)) < 0.0f) return false;
HitPos = IntersectPos;
return true;
}
| [
"[email protected]@f47709aa-00b5-e8d7-f572-541f4cbca54f"
] | [
[
[
1,
115
]
]
] |
cf7f44d7a56c6c0e5b9c3ac799b427f754dc9cf6 | 81344a13313d27b6af140bc8c9b77c9c2e81fee2 | /SmsDaemon/soapClient.cpp | e7cddd68519159f2ab2b6ec17a36f14cae345392 | [] | no_license | radtek/aitop | 169912e43a6d2bc4018219634d13dc786fa28a31 | a2a89859d0d912b0844593972a2310798573219f | refs/heads/master | 2021-01-01T03:57:19.378394 | 2008-06-17T16:03:19 | 2008-06-17T16:03:19 | 58,142,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,981 | cpp | /* soapClient.cpp
Generated by gSOAP 2.7.10 from aitop.h
Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved.
This part of the software is released under one of the following licenses:
GPL, the gSOAP public license, or Genivia's license for commercial use.
*/
#include "soapH.h"
SOAP_SOURCE_STAMP("@(#) soapClient.cpp ver 2.7.10 2008-06-17 15:53:32 GMT")
SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__send(struct soap *soap, const char *soap_endpoint, const char *soap_action, int _cp_USCOREid, int _serviceid, char *_usernumber, int _timelen, char *_content, int &_sendReturn)
{ struct ns1__send soap_tmp_ns1__send;
struct ns1__sendResponse *soap_tmp_ns1__sendResponse;
if (!soap_endpoint)
soap_endpoint = "http://220.194.56.196:9058/calldownsms/services/SendSmsService";
if (!soap_action)
soap_action = "";
soap->encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/";
soap_tmp_ns1__send._cp_USCOREid = _cp_USCOREid;
soap_tmp_ns1__send._serviceid = _serviceid;
soap_tmp_ns1__send._usernumber = _usernumber;
soap_tmp_ns1__send._timelen = _timelen;
soap_tmp_ns1__send._content = _content;
soap_begin(soap);
soap_serializeheader(soap);
soap_serialize_ns1__send(soap, &soap_tmp_ns1__send);
if (soap_begin_count(soap))
return soap->error;
if (soap->mode & SOAP_IO_LENGTH)
{ if (soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send(soap, &soap_tmp_ns1__send, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap))
return soap->error;
}
if (soap_end_count(soap))
return soap->error;
if (soap_connect(soap, soap_endpoint, soap_action)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send(soap, &soap_tmp_ns1__send, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap_closesock(soap);
soap_default_int(soap, &_sendReturn);
if (soap_begin_recv(soap)
|| soap_envelope_begin_in(soap)
|| soap_recv_header(soap)
|| soap_body_begin_in(soap))
return soap_closesock(soap);
soap_tmp_ns1__sendResponse = soap_get_ns1__sendResponse(soap, NULL, "ns1:sendResponse", "");
if (soap->error)
{ if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2)
return soap_recv_fault(soap);
return soap_closesock(soap);
}
if (soap_body_end_in(soap)
|| soap_envelope_end_in(soap)
|| soap_end_recv(soap))
return soap_closesock(soap);
_sendReturn = soap_tmp_ns1__sendResponse->_sendReturn;
return soap_closesock(soap);
}
SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__send_(struct soap *soap, const char *soap_endpoint, const char *soap_action, int _cp_USCOREid, int _serviceid, char *_usernumber, int _timelen, char *_content, int &_sendReturn)
{ struct ns1__send_ soap_tmp_ns1__send_;
struct ns1__send_Response *soap_tmp_ns1__send_Response;
if (!soap_endpoint)
soap_endpoint = "http://220.194.56.196:9058/calldownsms/services/SendSmsService";
if (!soap_action)
soap_action = "";
soap->encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/";
soap_tmp_ns1__send_._cp_USCOREid = _cp_USCOREid;
soap_tmp_ns1__send_._serviceid = _serviceid;
soap_tmp_ns1__send_._usernumber = _usernumber;
soap_tmp_ns1__send_._timelen = _timelen;
soap_tmp_ns1__send_._content = _content;
soap_begin(soap);
soap_serializeheader(soap);
soap_serialize_ns1__send_(soap, &soap_tmp_ns1__send_);
if (soap_begin_count(soap))
return soap->error;
if (soap->mode & SOAP_IO_LENGTH)
{ if (soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send_(soap, &soap_tmp_ns1__send_, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap))
return soap->error;
}
if (soap_end_count(soap))
return soap->error;
if (soap_connect(soap, soap_endpoint, soap_action)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send_(soap, &soap_tmp_ns1__send_, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap_closesock(soap);
soap_default_int(soap, &_sendReturn);
if (soap_begin_recv(soap)
|| soap_envelope_begin_in(soap)
|| soap_recv_header(soap)
|| soap_body_begin_in(soap))
return soap_closesock(soap);
soap_tmp_ns1__send_Response = soap_get_ns1__send_Response(soap, NULL, "ns1:send-Response", "");
if (soap->error)
{ if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2)
return soap_recv_fault(soap);
return soap_closesock(soap);
}
if (soap_body_end_in(soap)
|| soap_envelope_end_in(soap)
|| soap_end_recv(soap))
return soap_closesock(soap);
_sendReturn = soap_tmp_ns1__send_Response->_sendReturn;
return soap_closesock(soap);
}
SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__send__(struct soap *soap, const char *soap_endpoint, const char *soap_action, int _cp_USCOREid, int _serviceid, char *_usernumber, int _timelen, char *_content, int &_sendReturn)
{ struct ns1__send__ soap_tmp_ns1__send__;
struct ns1__send__Response *soap_tmp_ns1__send__Response;
if (!soap_endpoint)
soap_endpoint = "http://220.194.56.196:9058/calldownsms/services/SendSmsService";
if (!soap_action)
soap_action = "";
soap->encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/";
soap_tmp_ns1__send__._cp_USCOREid = _cp_USCOREid;
soap_tmp_ns1__send__._serviceid = _serviceid;
soap_tmp_ns1__send__._usernumber = _usernumber;
soap_tmp_ns1__send__._timelen = _timelen;
soap_tmp_ns1__send__._content = _content;
soap_begin(soap);
soap_serializeheader(soap);
soap_serialize_ns1__send__(soap, &soap_tmp_ns1__send__);
if (soap_begin_count(soap))
return soap->error;
if (soap->mode & SOAP_IO_LENGTH)
{ if (soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send__(soap, &soap_tmp_ns1__send__, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap))
return soap->error;
}
if (soap_end_count(soap))
return soap->error;
if (soap_connect(soap, soap_endpoint, soap_action)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__send__(soap, &soap_tmp_ns1__send__, "ns1:send", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap_closesock(soap);
soap_default_int(soap, &_sendReturn);
if (soap_begin_recv(soap)
|| soap_envelope_begin_in(soap)
|| soap_recv_header(soap)
|| soap_body_begin_in(soap))
return soap_closesock(soap);
soap_tmp_ns1__send__Response = soap_get_ns1__send__Response(soap, NULL, "ns1:send--Response", "");
if (soap->error)
{ if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2)
return soap_recv_fault(soap);
return soap_closesock(soap);
}
if (soap_body_end_in(soap)
|| soap_envelope_end_in(soap)
|| soap_end_recv(soap))
return soap_closesock(soap);
_sendReturn = soap_tmp_ns1__send__Response->_sendReturn;
return soap_closesock(soap);
}
SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__sendFailed(struct soap *soap, const char *soap_endpoint, const char *soap_action, int _cp_USCOREid, int _serviceid, char *_usernumber, char *_content, int &_sendFailedReturn)
{ struct ns1__sendFailed soap_tmp_ns1__sendFailed;
struct ns1__sendFailedResponse *soap_tmp_ns1__sendFailedResponse;
if (!soap_endpoint)
soap_endpoint = "http://220.194.56.196:9058/calldownsms/services/SendSmsService";
if (!soap_action)
soap_action = "";
soap->encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/";
soap_tmp_ns1__sendFailed._cp_USCOREid = _cp_USCOREid;
soap_tmp_ns1__sendFailed._serviceid = _serviceid;
soap_tmp_ns1__sendFailed._usernumber = _usernumber;
soap_tmp_ns1__sendFailed._content = _content;
soap_begin(soap);
soap_serializeheader(soap);
soap_serialize_ns1__sendFailed(soap, &soap_tmp_ns1__sendFailed);
if (soap_begin_count(soap))
return soap->error;
if (soap->mode & SOAP_IO_LENGTH)
{ if (soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__sendFailed(soap, &soap_tmp_ns1__sendFailed, "ns1:sendFailed", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap))
return soap->error;
}
if (soap_end_count(soap))
return soap->error;
if (soap_connect(soap, soap_endpoint, soap_action)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__sendFailed(soap, &soap_tmp_ns1__sendFailed, "ns1:sendFailed", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap_closesock(soap);
soap_default_int(soap, &_sendFailedReturn);
if (soap_begin_recv(soap)
|| soap_envelope_begin_in(soap)
|| soap_recv_header(soap)
|| soap_body_begin_in(soap))
return soap_closesock(soap);
soap_tmp_ns1__sendFailedResponse = soap_get_ns1__sendFailedResponse(soap, NULL, "ns1:sendFailedResponse", "");
if (soap->error)
{ if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2)
return soap_recv_fault(soap);
return soap_closesock(soap);
}
if (soap_body_end_in(soap)
|| soap_envelope_end_in(soap)
|| soap_end_recv(soap))
return soap_closesock(soap);
_sendFailedReturn = soap_tmp_ns1__sendFailedResponse->_sendFailedReturn;
return soap_closesock(soap);
}
SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__sendnote(struct soap *soap, const char *soap_endpoint, const char *soap_action, char *_typeName, int _spID, int _serviceID, char *_userNumber, int _rank, int &_sendnoteReturn)
{ struct ns1__sendnote soap_tmp_ns1__sendnote;
struct ns1__sendnoteResponse *soap_tmp_ns1__sendnoteResponse;
if (!soap_endpoint)
soap_endpoint = "http://220.194.56.196:9058/calldownsms/services/SendSmsService";
if (!soap_action)
soap_action = "";
soap->encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/";
soap_tmp_ns1__sendnote._typeName = _typeName;
soap_tmp_ns1__sendnote._spID = _spID;
soap_tmp_ns1__sendnote._serviceID = _serviceID;
soap_tmp_ns1__sendnote._userNumber = _userNumber;
soap_tmp_ns1__sendnote._rank = _rank;
soap_begin(soap);
soap_serializeheader(soap);
soap_serialize_ns1__sendnote(soap, &soap_tmp_ns1__sendnote);
if (soap_begin_count(soap))
return soap->error;
if (soap->mode & SOAP_IO_LENGTH)
{ if (soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__sendnote(soap, &soap_tmp_ns1__sendnote, "ns1:sendnote", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap))
return soap->error;
}
if (soap_end_count(soap))
return soap->error;
if (soap_connect(soap, soap_endpoint, soap_action)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| soap_put_ns1__sendnote(soap, &soap_tmp_ns1__sendnote, "ns1:sendnote", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap_closesock(soap);
soap_default_int(soap, &_sendnoteReturn);
if (soap_begin_recv(soap)
|| soap_envelope_begin_in(soap)
|| soap_recv_header(soap)
|| soap_body_begin_in(soap))
return soap_closesock(soap);
soap_tmp_ns1__sendnoteResponse = soap_get_ns1__sendnoteResponse(soap, NULL, "ns1:sendnoteResponse", "");
if (soap->error)
{ if (soap->error == SOAP_TAG_MISMATCH && soap->level == 2)
return soap_recv_fault(soap);
return soap_closesock(soap);
}
if (soap_body_end_in(soap)
|| soap_envelope_end_in(soap)
|| soap_end_recv(soap))
return soap_closesock(soap);
_sendnoteReturn = soap_tmp_ns1__sendnoteResponse->_sendnoteReturn;
return soap_closesock(soap);
}
/* End of soapClient.cpp */
| [
"[email protected]"
] | [
[
[
1,
301
]
]
] |
b7a117795aa1c8a4c95401e5ac10705f5a8717fc | 023a090afcb760e5e516594fb37675fa5d392dfd | /src/FlashLite21LauncherAppUi.cpp | 6b89b88599840bee37d86b7bf0c2a672fc8504f2 | [] | no_license | abdul/flashlite-launcher-symbian-s60 | fb583e7f284e6feedc9f6dfcaa565addae25b814 | f8ff90eb2814521dda91bc728cd297c7de212ced | refs/heads/master | 2016-09-05T21:22:58.881709 | 2010-07-30T05:19:24 | 2010-07-30T05:19:24 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,400 | cpp | /*
============================================================================
Name : CFlashLite21LauncherAppUi.cpp
Author : Abdul Qabiz
Copyright : © 2007-2008 Abdul Qabiz (http://www.abdulqabiz.com)
Description : CFlashLite21LauncherAppUi implementation
============================================================================
*/
// INCLUDE FILES
#include "FlashLite21LauncherAppui.h"
//#include "FlashLite21LauncherContainer.h"
#include <FlashLite21Launcher.rsg>
#include "FlashLite21Launcher.hrh"
#include "FlashLite21LauncherConstants.h"
#include <avkon.hrh>
#include <aknnotewrappers.h>
#include <aknnotewrappers.h>
#include <apgcli.h>
#include <e32Keys.h>
#include <uikon.hrh>
// ================= MEMBER FUNCTIONS =======================
//
// ----------------------------------------------------------
// CFlashLite21LauncherAppUi::ConstructL()
//
// ----------------------------------------------------------
//
void CFlashLite21LauncherAppUi::ConstructL()
{
BaseConstructL();
//timer
iWaitTimer = CPeriodic::NewL( KWaitCallBackPriority );
TThreadId id;
RApaLsSession ls;
User::LeaveIfError(ls.Connect());
TApaAppInfo appinfo;
TInt KError = ls.GetAppInfo(appinfo, KUidFlash21);
CleanupClosePushL(ls);
if(KError == KErrNone)
{
//Search for open player
TFileName fnAppPath = appinfo.iFullName;
TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
TApaTask task = taskList.FindApp( KUidFlash21 );
if(task.Exists()) //If player is already running
{
TInt err = task.SwitchOpenFile( KLitSwfFileToLaunch );
if(err == KErrNone)
{
//everything is fine
} else
{
//any error
}
task.BringToForeground();
}
else
{
if(KError == KErrNone) //the player is not running so we launch it
{
TInt result = ls.StartDocument(fnAppPath,id);
if (result!=KErrNone)
{
//any error
}
else
{
if ( iWaitTimer->IsActive())
{
iWaitTimer->Cancel();
}
TCallBack callback( WaitTimerCallbackL, this );
iWaitTimer->Start( ( TTimeIntervalMicroSeconds32 ) KMaxWaitTime,
( TTimeIntervalMicroSeconds32 ) KMaxWaitTime,
callback );
}
CleanupStack::PopAndDestroy(); // Destroy cmd
}
}
}
else
{
//FlashPlayer not installed
}
/*iAppContainer = new (ELeave) CFlashLite21LauncherContainer;
iAppContainer->SetMopParent( this );
iAppContainer->ConstructL( ClientRect() );
AddToStackL( iAppContainer );*/
}
// ----------------------------------------------------
// CFlashLite21LauncherAppUi::~CFlashLite21LauncherAppUi()
// Destructor
// Frees reserved resources
// ----------------------------------------------------
//
CFlashLite21LauncherAppUi::~CFlashLite21LauncherAppUi()
{
delete iWaitTimer;
}
// -----------------------------------------------------------------------------
// CAknExNoteContainer::WaitTimerCallbackL()
// Callback function for deleting wait note.
// -----------------------------------------------------------------------------
//
TInt CFlashLite21LauncherAppUi::WaitTimerCallbackL( TAny* aThis )
{
CFlashLite21LauncherAppUi* app = static_cast<CFlashLite21LauncherAppUi*>( aThis );
app->iWaitTimer->Cancel();
app->LaunchSWF();
app->Exit ();
return 0;
}
// -----------------------------------------------------------------------------
// CTwitterLauncherAppContainer::LaunchSWF()
// method to open SWF file in FlashLite player.
// -----------------------------------------------------------------------------
//
void CFlashLite21LauncherAppUi::LaunchSWF ()
{
//Search for open player
TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
TApaTask task = taskList.FindApp( KUidFlash21 );
if( task.Exists()) //If player is already running
{
TInt err = task.SwitchOpenFile( KLitSwfFileToLaunch );
if(err == KErrNone)
{
//everything is fine
} else
{
//any error
}
task.BringToForeground();
}
}
// ------------------------------------------------------------------------------
// CFlashLite21LauncherAppUi::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
// This function is called by the EIKON framework just before it displays
// a menu pane. Its default implementation is empty, and by overriding it,
// the application can set the state of menu items dynamically according
// to the state of application data.
// ------------------------------------------------------------------------------
//
void CFlashLite21LauncherAppUi::DynInitMenuPaneL(
TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/)
{
}
// ----------------------------------------------------
// CFlashLite21LauncherAppUi::HandleKeyEventL(
// const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
// takes care of key event handling
// ----------------------------------------------------
//
TKeyResponse CFlashLite21LauncherAppUi::HandleKeyEventL(
const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/)
{
return EKeyWasNotConsumed;
}
// ----------------------------------------------------
// CFlashLite21LauncherAppUi::HandleCommandL(TInt aCommand)
// takes care of command handling
// ----------------------------------------------------
//
void CFlashLite21LauncherAppUi::HandleCommandL(TInt aCommand)
{
switch ( aCommand )
{
case EAknSoftkeyBack:
case EEikCmdExit:
{
Exit();
break;
}
case EFlashLite21LauncherCmdAppTest:
{
// Info message shown only in the emulator
iEikonEnv->InfoMsg(_L("test"));
// Load localized message from the resource file
HBufC* message = CEikonEnv::Static()->AllocReadResourceLC(R_MESSAGE_TEXT);
// Show information note dialog
CAknInformationNote* note = new (ELeave) CAknInformationNote;
note->ExecuteLD(message->Des());
CleanupStack::PopAndDestroy(message);
break;
}
// TODO: Add Your command handling code here
default:
break;
}
}
| [
"[email protected]"
] | [
[
[
1,
216
]
]
] |
2420aecc5cacdcce8c1c6db658dfea430d1d43cf | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/include/Gwen/Controls/SplitterBar.h | 681280fd04d7d0112b533cb76cb47591eac0efdf | [
"MIT",
"Zlib"
] | permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | #pragma once
#include "Gwen/Gwen.h"
#include "Gwen/Controls/Base.h"
#include "Gwen/Controls/Dragger.h"
namespace Gwen
{
namespace Controls
{
class GWEN_EXPORT SplitterBar : public ControlsInternal::Dragger
{
public:
GWEN_CONTROL( SplitterBar, ControlsInternal::Dragger );
void Render( Skin::Base* skin );
void Layout( Skin::Base* skin );
};
}
} | [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
] | [
[
[
1,
20
]
]
] |
3a946b9639d441e55f4303aca469b80e364da561 | e419dcb4a688d0c7b743c52c2d3c4c2edffc3ab8 | /Reports/Week01/Plane.cpp | edc604aa6f70831147b65a46a372ff988935a7e0 | [] | no_license | Jazzinghen/DTU-Rendering | d7f833c01836fadb4401133d8a5c17523e04bf49 | b03692ce19d0ea765d61e88e19cd8113da99b7fe | refs/heads/master | 2021-01-01T15:29:49.250365 | 2011-12-20T00:49:32 | 2011-12-20T00:49:32 | 2,505,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,844 | cpp | // 02562 Rendering Framework
// Written by Jeppe Revall Frisvad, 2011
// Copyright (c) DTU Informatics 2011
#include <optix_world.h>
#include "HitInfo.h"
#include "Plane.h"
using namespace optix;
bool intersect_plane(const float3& normal, float d, const Ray& r, float& distance)
{
if ( dot( normal, r.direction ) == 0 ) return false;
distance = -( dot( r.origin, normal ) + d )/dot( r.direction, normal);
// setup returned structure
return ( distance > 0.01 );
}
bool Plane::intersect(const Ray& r, HitInfo& hit, unsigned int prim_idx) const
{
// Implement ray-plane intersection here.
// It is fine to intersect with the front-facing side of the plane only.
//
// Input: r (the ray to be checked for intersection)
// prim_idx (index of the primitive element in a collection, not used here)
//
// Output: hit.has_hit (true if the ray intersects the plane, false otherwise)
// hit.dist (distance from the ray origin to the intersection point)
// hit.geometric_normal (the normalized normal of the plane)
// hit.shading_normal (the normalized normal of the plane)
// hit.material (pointer to the material of the plane)
// (hit.texcoord) (texture coordinates of intersection point, not needed for Week 1)
//
// Return: True if the ray intersects the plane, false otherwise
//
// Relevant data fields that are available (see Plane.h and OptiX math library reference)
// r.origin (ray origin)
// r.direction (ray direction)
// r.tmin (minimum intersection distance allowed)
// r.tmax (maximum intersection distance allowed)
// onb (orthonormal basis of the plane)
// material (material of the plane)
//
// Hint: The OptiX math library has a function dot(v, w) which returns
// the dot product of the vectors v and w.
float distance = 0;
if( intersect_plane( get_normal(), d, r, distance ) )
{
hit.has_hit = true;
hit.dist = distance;
hit.geometric_normal = normalize( get_normal() );
hit.shading_normal = normalize( get_normal() );
hit.material = &get_material();
hit.position = r.origin + distance * r.direction;
return true;
}
else
{
hit.has_hit = false;
return false;
}
}
void Plane::transform(const Matrix4x4& m)
{
onb = Onb(normalize(make_float3(m*make_float4(onb.m_normal, 0.0f))));
position = make_float3(m*make_float4(position, 1.0f));
d = -dot(position, onb.m_normal);
}
Aabb Plane::compute_bbox() const
{
return Aabb(make_float3(-1e37f), make_float3(1e37f));
}
| [
"[email protected]"
] | [
[
[
1,
76
]
]
] |
11510b1a4b07e4e36708d98682cc200a4f1de203 | e2f961659b90ff605798134a0a512f9008c1575b | /Example-12/MODEL_SCAL.INC | 1e1ad2acce143c88e41883e07fee49bd017edf70 | [] | no_license | bs-eagle/test-models | 469fe485a0d9aec98ad06d39b75901c34072cf60 | d125060649179b8e4012459c0a62905ca5235ba7 | refs/heads/master | 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | inc | SWOF
0 0 1 3.5
0.25 0 1 3
0.3 0.002 0.81 2.9
0.35 0.008 0.64 2.5
0.4 0.018 0.49 1.9
0.45 0.032 0.36 1.5
0.5 0.05 0.25 1.1
0.55 0.072 0.16 1
0.6 0.098 0.09 0.8
0.65 0.128 0.04 0.5
0.7 0.162 0.01 0.4
0.75 0.2 0 0.4
1 0.2 0 0
/
SGOF
0 0 1 0
0.25 0 1 0.1
0.3 0.002 0.81 0.2
0.35 0.008 0.64 0.4
0.4 0.018 0.49 0.9
0.45 0.032 0.36 1.5
0.5 0.05 0.25 2.2
0.55 0.072 0.16 2.9
0.6 0.098 0.09 3.5
0.65 0.128 0.04 4.2
0.7 0.162 0.01 5.4
0.75 0.2 0 6.8
1 0.2 0 8
/
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
bac45b70f6d5effe3808cf55388b8d74b1f4e73f | b3b0c727bbafdb33619dedb0b61b6419692e03d3 | /Source/Calculator/LWUI/LWUI.h | 30cb1877a4c119ef6de7d46e25cb195250755f4c | [] | no_license | testzzzz/hwccnet | 5b8fb8be799a42ef84d261e74ee6f91ecba96b1d | 4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113 | refs/heads/master | 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 493 | h | // LWUI.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CLWUIApp:
// 有关此类的实现,请参阅 LWUI.cpp
//
class CLWUIApp : public CWinApp
{
public:
CLWUIApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CLWUIApp theApp; | [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
760e1a4272a1361ffdbf92052b3f45cf87b87eb4 | 52db451b6b354993000a4a808e9d046dff4c956f | /src/win_state.cpp | d8d6539e0c2db8356221fc097db8623b44c5c008 | [] | no_license | PuffNSting/Poker | a4b0263c27911291c6ce7148d22c1c137af457d3 | b1c606980af32b325fdf7398f30d6364c0097034 | refs/heads/master | 2021-01-15T22:29:18.718588 | 2011-12-23T03:02:07 | 2011-12-23T03:02:07 | 3,032,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,723 | cpp | #include "../include/win_state.h"
win_state::win_state(vector<Card> &cards)
{
int cards_size = cards.size();
vector<Card> holder;
//Sort cards in ascending order
sort(cards.begin(), cards.end());
// High card
high_card = cards[cards_size-1].get_value();
win_level = 0;
// Pair
for (int i = 0; i < cards_size - 1; i++) {
if (cards[i].get_value() == cards[i+1].get_value()) {
high_card = cards[i].get_value();
win_level = 1;
}
}
// Two pair
for (int i = 0; i < cards_size - 3; i++) {
if (cards[i].get_value() == cards[i+1].get_value() && cards[i+2].get_value() == cards[i+3].get_value()) {
high_card = cards[i+2].get_value();
win_level = 2;
}
}
// Trips
for (int i = 0; i < cards_size - 2; i++) {
if (cards[i].get_value() == cards[i+1].get_value() && cards[i].get_value() == cards[i+2].get_value()) {
high_card = cards[i].get_value();
win_level = 3;
}
}
// Straight
bool ace_flag = false;
if (cards[cards_size-1].get_value() == 12) {
ace_flag = true;
cards.insert(cards.begin(), Card(0,cards[cards_size-1].get_suite()));
}
for (int i = 0; i < cards_size - 4; i++) {
if (cards[i].get_value() == cards[i+1].get_value() - 1) {
if (cards[i+1].get_value() == cards[i+2].get_value() - 1) {
if (cards[i+2].get_value() == cards[i+3].get_value() - 1) {
if (cards[i+3].get_value() == cards[i+4].get_value() - 1) {
high_card = cards[i+4].get_value();
win_level = 4;
}
}
}
}
}
if (ace_flag) {
cards.erase(cards.begin());
}
// Flush
int counter = 1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < cards_size; j++) {
if (cards[j].get_suite() == i) {
counter++;
if (counter >= 5) {
high_card = cards[j].get_value();
win_level = 5;
}
}
else {
counter = 1;
}
}
}
// Full house
vector<Card> temp;
for (int i = 0; i < cards_size; i++) {
temp.push_back(cards[i]);
}
bool trips = false;
bool pair = false;
int index, temp_hc;
for (int i = 0; i < temp.size() - 2; i++) {
if (temp[i].get_value() == temp[i+1].get_value() && temp[i].get_value() == temp[i+2].get_value()) {
trips = true;
temp_hc = temp[i].get_value();
index = i;
}
}
if (trips) {
holder.resize(0);
for (int i = index; i < index+3; i++) {
holder.push_back(temp[i]);
}
temp.erase(temp.begin()+index, temp.begin()+index+3);
for (int i = 0; i < temp.size() - 1; i++) {
if (temp[i].get_value() == temp[i+1].get_value()) {
pair = true;
}
}
}
if (pair && trips) {
win_level = 6;
high_card = temp_hc;
}
// Quads
for (int i = 0; i < cards_size - 4; i++) {
if (cards[i].get_value() == cards[i+1].get_value() && cards[i].get_value() == cards[i+2].get_value() && cards[i].get_value() == cards[i+3].get_value()) {
high_card = cards[i].get_value();
win_level = 7;
}
}
// Add these in later... so rare that statistically won't matter if non existant
// Straight flush
// Royal flush
}
| [
"[email protected]"
] | [
[
[
1,
122
]
]
] |
105112c0936a36daeb1e11bd7e56951aaa308e74 | 95d583eacc45df62b6b6459e2ec79404686cb2b1 | /source/Comando.cpp | fa4131189e7d0c11f15e656a8a693c2661bb78dc | [] | no_license | sebasrodriguez/teoconj | 81a917c57724a718e6288798f7c58863a1dad523 | aee99839a8ddb293b0ed1402dfe72b80dbfe0af0 | refs/heads/master | 2021-01-01T15:36:42.773692 | 2010-03-13T01:04:12 | 2010-03-13T01:04:12 | 32,334,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,297 | cpp | #include "Comando.h"
void getComandoList(ListaString &l)
{
ListaStringInsBack(l, "add");
ListaStringInsBack(l, "create");
ListaStringInsBack(l, "difference");
ListaStringInsBack(l, "equals");
ListaStringInsBack(l, "exit");
ListaStringInsBack(l, "help");
ListaStringInsBack(l, "included");
ListaStringInsBack(l, "intersection");
ListaStringInsBack(l, "listall");
ListaStringInsBack(l, "load");
ListaStringInsBack(l, "member");
ListaStringInsBack(l, "remove");
ListaStringInsBack(l, "save");
ListaStringInsBack(l, "show");
ListaStringInsBack(l, "union");
ListaStringInsBack(l, "clear");
}
bool validateComando(string cmd)
{
ListaString comandos;
ListaStringCreate(comandos);
getComandoList(comandos);
bool valid = false;
while (!valid && comandos != NULL)
{
valid = streq(cmd, comandos->info);
comandos = comandos->sig;
}
return valid;
}
Comando getComandoFromString(string s)
{
Comando cmd;
if (equalComandoString(ADD, s)) cmd = ADD;
else if (equalComandoString(CREATE, s)) cmd = CREATE;
else if (equalComandoString(DIFFERENCE, s)) cmd = DIFFERENCE;
else if (equalComandoString(EQUALS, s)) cmd = EQUALS;
else if (equalComandoString(EXIT, s)) cmd = EXIT;
else if (equalComandoString(HELP, s)) cmd = HELP;
else if (equalComandoString(INCLUDED, s)) cmd = INCLUDED;
else if (equalComandoString(INTERSECTION, s)) cmd = INTERSECTION;
else if (equalComandoString(LISTALL, s)) cmd = LISTALL;
else if (equalComandoString(LOAD, s)) cmd = LOAD;
else if (equalComandoString(MEMBER, s)) cmd = MEMBER;
else if (equalComandoString(REMOVE, s)) cmd = REMOVE;
else if (equalComandoString(SAVE, s)) cmd = SAVE;
else if (equalComandoString(SHOW, s)) cmd = SHOW;
else if (equalComandoString(UNION, s)) cmd = UNION;
else if (equalComandoString(CLEAR, s)) cmd = CLEAR;
return cmd;
}
bool equalComandoString(Comando cmd, string s)
{
string c;
strcrear(c);
getComandoString(cmd, c);
return streq(c, s);
}
void getComandoString(Comando cmd, string &s)
{
switch (cmd)
{
case ADD:
strcop(s, "add");
break;
case CREATE:
strcop(s, "create");
break;
case DIFFERENCE:
strcop(s, "difference");
break;
case EQUALS:
strcop(s, "equals");
break;
case EXIT:
strcop(s, "exit");
break;
case HELP:
strcop(s, "help");
break;
case INCLUDED:
strcop(s, "included");
break;
case INTERSECTION:
strcop(s, "intersection");
break;
case LISTALL:
strcop(s, "listall");
break;
case LOAD:
strcop(s, "load");
break;
case MEMBER:
strcop(s, "member");
break;
case REMOVE:
strcop(s, "remove");
break;
case SAVE:
strcop(s, "save");
break;
case SHOW:
strcop(s, "show");
break;
case UNION:
strcop(s, "union");
break;
case CLEAR:
strcop(s, "clear");
break;
default:
strcop(s, "");
}
}
| [
"srpabliyo@861ad466-0edf-11df-a223-d798cd56f61e",
"sebasrodriguez@861ad466-0edf-11df-a223-d798cd56f61e"
] | [
[
[
1,
2
],
[
5,
22
],
[
25,
28
],
[
33,
36
],
[
39,
39
],
[
56,
58
],
[
63,
66
],
[
121,
124
]
],
[
[
3,
4
],
[
23,
24
],
[
29,
32
],
[
37,
38
],
[
40,
55
],
[
59,
62
],
[
67,
120
]
]
] |
d51e93e75e14eec06a445b9a035034670619697f | 80716d408715377e88de1fc736c9204b87a12376 | /OnSipCore/XmlPrettyPrint.cpp | ebc6bef3f3ecee0a686c9e6377a6f2ef965fa70e | [] | no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | cpp |
#include "stdafx.h"
#include "xmlprettyprint.h"
#define INDENT " "
//static
tstring XmlPrettyPrint::prettyPrint(Tag *t)
{
return prettyPrint(t,"");
}
//static
tstring XmlPrettyPrint::prettyPrint(Tag *t,const tstring& indent)
{
std::string xml = indent + "<";
if( !t->prefix().empty() )
{
xml += t->prefix();
xml += ':';
}
xml += t->name();
if( !t->attributes().empty() )
{
Tag::AttributeList::const_iterator it_a = t->attributes().begin();
for( ; it_a != t->attributes().end(); ++it_a )
{
xml += (*it_a)->xml();
}
}
if ( t->children().empty() && t->cdata().empty() )
{
xml += "/>\r\n";
}
else
{
xml += ">\r\n";
const TagList tags = t->children();
std::list<Tag*>::const_iterator it_n = tags.begin();
for( ; it_n != tags.end(); ++it_n )
{
Tag* t = (*it_n);
tstring xx = prettyPrint(t,indent+INDENT);
xml += xx;
}
if ( !t->cdata().empty() )
xml += indent + INDENT + t->cdata() + "\r\n";
xml += indent + "</";
if( !t->prefix().empty() )
{
xml += t->prefix();
xml += ':';
}
xml += t->name();
xml += ">\r\n";
}
return xml;
}
//virtual
void XmlPrettyPrint::handleTag(gloox::Tag *tag)
{
m_prints.push_back( prettyPrint(tag,"") );
}
tstring XmlPrettyPrint::prettyPrint(const tstring& xml)
{
if ( m_parser.get() == NULL )
m_parser.reset( new Parser(this) );
// Clear any previous strings
m_prints.clear();
tstring temp = xml;
// Do the parse, this will result in calls to handleTag()
m_parser->feed(temp);
// Concatenate each of the xml tags
tstring ret;
std::list<tstring>::iterator iter = m_prints.begin();
while ( iter != m_prints.end() )
{
ret += *iter;
iter++;
}
return ret;
}
| [
"Owner@.(none)"
] | [
[
[
1,
93
]
]
] |
a8d1a5bb865b486ae9be2271b2efaea9649f9262 | 0c930838cc851594c9eceab6d3bafe2ceb62500d | /include/jflib/timeseries/expr.hpp | e170be38426691573302aba8052514c56030a781 | [
"BSD-3-Clause"
] | permissive | quantmind/jflib | 377a394c17733be9294bbf7056dd8082675cc111 | cc240d2982f1f1e7e9a8629a5db3be434d0f207d | refs/heads/master | 2021-01-19T07:42:43.692197 | 2010-04-19T22:04:51 | 2010-04-19T22:04:51 | 439,289 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,335 | hpp |
#ifndef __TIMESERIE_EXPR_HPP__
#define __TIMESERIE_EXPR_HPP__
#include <jflib/timeseries/timeseries_base.hpp>
#include <jflib/timeseries/traits/base.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
namespace jflib { namespace timeseries {
template<class TS>
class timeseries_expression_holder_base {
public:
typedef TS tstype;
typedef typename tstype::size_type size_type;
virtual size_type size() = 0;
};
template<class E, class TS>
class timeseries_expression_holder: public timeseries_expression_holder_base<TS> {
typedef timeseries_expression_holder_base<TS> super;
typedef typename E::tstype otherts;
//BOOST_STATIC_ASSERT(boost::is_same<TS,otherts>::value);
public:
typedef E expression;
typedef typename super::tstype tstype;
typedef typename tstype::size_type size_type;
timeseries_expression_holder(const expression& e):m_e(e){}
private:
expression m_e;
};
template<class TS>
class tsexpression {
typedef timeseries_expression_holder_base<TS> holder_type;
public:
typedef TS tstype;
typedef typename tstype::size_type size_type;
template<class E>
tsexpression(const E& expr):m_expr(new timeseries_expression_holder<E,tstype>(expr)){}
tsexpression(const tsexpression& rhs):m_expr(rhs.m_expr){}
size_type size() const {return m_expr->size();}
size_type series() const {return m_expr->series();}
private:
boost::shared_ptr<holder_type> m_expr;
};
template<class E>
class timeseries_expression: public timeseries_expression_holder<E, typename E::tstype> {
typedef timeseries_expression_holder<E, typename E::tstype> super;
public:
typedef typename super::tstype tstype;
typedef E expression_type;
super& as_expr() {return *this;}
const super& as_expr() const {return *this;}
BOOST_UBLAS_INLINE
const expression_type &operator () () const {
return *static_cast<const expression_type *> (this);
}
BOOST_UBLAS_INLINE
expression_type &operator () () {
return *static_cast<expression_type *> (this);
}
};
template<class Key, class T, class Tag, unsigned F, bool M>
class timeseries_reference: public timeseries_expression<timeseries_reference<Key,T,Tag,F,M> > {
public:
typedef timeseries<Key,T,Tag,F,M> tstype;
typedef typename tstype::size_type size_type;
timeseries_reference(const tstype& ts):m_ts(ts){}
timeseries_reference(const timeseries_reference& ts):m_ts(ts.m_ts){}
size_type size() const {return m_ts.size();}
size_type series() const {return m_ts.series();}
tstype& expression() {return m_ts;}
const tstype& expression() const {return m_ts;}
private:
tstype m_ts;
};
template<class E1, class E2, class F>
class timeseries_binary: public timeseries_expression<timeseries_binary<E1,E2,F> > {
typedef E1 expression1_type;
typedef E2 expression2_type;
typedef F functor_type;
typedef typename E1::size_type size_type;
public:
BOOST_UBLAS_INLINE
timeseries_binary(const expression1_type &e1, const expression2_type &e2):m_e1(e1),m_e2(e2){}
BOOST_UBLAS_INLINE
size_type size() const {return BOOST_UBLAS_SAME(m_e1.size(), m_e2.size());}
private:
expression1_type m_e1;
expression2_type m_e2;
};
}}
#endif // __TIMESERIE_EXPR_HPP__
| [
"[email protected]"
] | [
[
[
1,
124
]
]
] |
86b533d1150a63f14d43e8839d2ef76d55bb90b9 | 3a577d02f876776b22e2bf1c0db12a083f49086d | /vba2/gba2/gba/Mode5.cpp | 9aae6d213f194a3d8a67b3382e904cd8e73556f5 | [] | no_license | xiaoluoyuan/VisualBoyAdvance-2 | d19565617b26e1771f437842dba5f0131d774e73 | cadd2193ba48e1846b45f87ff7c36246cd61b6ee | refs/heads/master | 2021-01-10T01:19:23.884491 | 2010-05-12T09:59:37 | 2010-05-12T09:59:37 | 46,539,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,418 | cpp | /* VisualBoyAdvance 2
Copyright (C) 2009-2010 VBA development team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GBA.h"
#include "GBAGfx.h"
void mode5RenderLine()
{
if(DISPCNT & 0x0080) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
u16 *palette = (u16 *)paletteRAM;
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen16Bit160(BG2CNT, BG2X_L, BG2X_H,
BG2Y_L, BG2Y_H, BG2PA, BG2PB,
BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed,
line2);
}
gfxDrawSprites(lineOBJ);
u32 background;
background = (READ16LE(&palette[0]) | 0x30000000);
for(int x = 0; x < 240; x++) {
u32 color = background;
u8 top = 0x20;
if(line2[x] < color) {
color = line2[x];
top = 0x04;
}
if((u8)(lineOBJ[x]>>24) < (u8)(color >>24)) {
color = lineOBJ[x];
top = 0x10;
}
if((top & 0x10) && (color & 0x00010000)) {
// semi-transparent OBJ
u32 back = background;
u8 top2 = 0x20;
if(line2[x] < back) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
void mode5RenderLineNoWindow()
{
if(DISPCNT & 0x0080) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
u16 *palette = (u16 *)paletteRAM;
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen16Bit160(BG2CNT, BG2X_L, BG2X_H,
BG2Y_L, BG2Y_H, BG2PA, BG2PB,
BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed,
line2);
}
gfxDrawSprites(lineOBJ);
u32 background;
background = (READ16LE(&palette[0]) | 0x30000000);
for(int x = 0; x < 240; x++) {
u32 color = background;
u8 top = 0x20;
if(line2[x] < color) {
color = line2[x];
top = 0x04;
}
if((u8)(lineOBJ[x]>>24) < (u8)(color >>24)) {
color = lineOBJ[x];
top = 0x10;
}
if(!(color & 0x00010000)) {
switch((BLDMOD >> 6) & 3) {
case 0:
break;
case 1:
{
if(top & BLDMOD) {
u32 back = background;
u8 top2 = 0x20;
if(line2[x] < back) {
if(top != 0x04) {
back = line2[x];
top2 = 0x04;
}
}
if((u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) {
if(top != 0x10) {
back = lineOBJ[x];
top2 = 0x10;
}
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
}
}
break;
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
} else {
// semi-transparent OBJ
u32 back = background;
u8 top2 = 0x20;
if(line2[x] < back) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
void mode5RenderLineAll()
{
if(DISPCNT & 0x0080) {
for(int x = 0; x < 240; x++) {
lineMix[x] = 0x7fff;
}
gfxLastVCOUNT = VCOUNT;
return;
}
u16 *palette = (u16 *)paletteRAM;
if(layerEnable & 0x0400) {
int changed = gfxBG2Changed;
if(gfxLastVCOUNT > VCOUNT)
changed = 3;
gfxDrawRotScreen16Bit160(BG2CNT, BG2X_L, BG2X_H,
BG2Y_L, BG2Y_H, BG2PA, BG2PB,
BG2PC, BG2PD,
gfxBG2X, gfxBG2Y, changed,
line2);
}
gfxDrawSprites(lineOBJ);
gfxDrawOBJWin(lineOBJWin);
bool inWindow0 = false;
bool inWindow1 = false;
if(layerEnable & 0x2000) {
u8 v0 = WIN0V >> 8;
u8 v1 = WIN0V & 255;
inWindow0 = ((v0 == v1) && (v0 >= 0xe8));
if(v1 >= v0)
inWindow0 |= (VCOUNT >= v0 && VCOUNT < v1);
else
inWindow0 |= (VCOUNT >= v0 || VCOUNT < v1);
}
if(layerEnable & 0x4000) {
u8 v0 = WIN1V >> 8;
u8 v1 = WIN1V & 255;
inWindow1 = ((v0 == v1) && (v0 >= 0xe8));
if(v1 >= v0)
inWindow1 |= (VCOUNT >= v0 && VCOUNT < v1);
else
inWindow1 |= (VCOUNT >= v0 || VCOUNT < v1);
}
u8 inWin0Mask = WININ & 0xFF;
u8 inWin1Mask = WININ >> 8;
u8 outMask = WINOUT & 0xFF;
u32 background;
background = (READ16LE(&palette[0]) | 0x30000000);
for(int x = 0; x < 240; x++) {
u32 color = background;
u8 top = 0x20;
u8 mask = outMask;
if(!(lineOBJWin[x] & 0x80000000)) {
mask = WINOUT >> 8;
}
if(inWindow1) {
if(gfxInWin1[x])
mask = inWin1Mask;
}
if(inWindow0) {
if(gfxInWin0[x]) {
mask = inWin0Mask;
}
}
if((mask & 4) && (line2[x] < color)) {
color = line2[x];
top = 0x04;
}
if((mask & 16) && ((u8)(lineOBJ[x]>>24) < (u8)(color >>24))) {
color = lineOBJ[x];
top = 0x10;
}
if(color & 0x00010000) {
// semi-transparent OBJ
u32 back = background;
u8 top2 = 0x20;
if((mask & 4) && line2[x] < back) {
back = line2[x];
top2 = 0x04;
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
else {
switch((BLDMOD >> 6) & 3) {
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
} else if(mask & 32) {
switch((BLDMOD >> 6) & 3) {
case 0:
break;
case 1:
{
if(top & BLDMOD) {
u32 back = background;
u8 top2 = 0x20;
if((mask & 4) && line2[x] < back) {
if(top != 0x04) {
back = line2[x];
top2 = 0x04;
}
}
if((mask & 16) && (u8)(lineOBJ[x]>>24) < (u8)(back >> 24)) {
if(top != 0x10) {
back = lineOBJ[x];
top2 = 0x10;
}
}
if(top2 & (BLDMOD>>8))
color = gfxAlphaBlend(color, back,
coeff[COLEV & 0x1F],
coeff[(COLEV >> 8) & 0x1F]);
}
}
break;
case 2:
if(BLDMOD & top)
color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]);
break;
case 3:
if(BLDMOD & top)
color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]);
break;
}
}
lineMix[x] = color;
}
gfxBG2Changed = 0;
gfxLastVCOUNT = VCOUNT;
}
| [
"spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0"
] | [
[
[
1,
379
]
]
] |
ead4e1548a4cbf4e13ab1b87bb92a4f8400475da | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /FLVGServer/PublishPointFormView.cpp | b6b37ac37d07c72f7acfc181dd757d1904102df9 | [] | no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,585 | cpp | // PublishPointFormView.cpp : implementation file
//
#include "stdafx.h"
#include "XDigitalLifeServerApp.h"
#include "PublishPointFormView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CPublishPointFormView
IMPLEMENT_DYNCREATE(CPublishPointFormView, CXTMainFormView)
CPublishPointFormView::CPublishPointFormView()
: CXTMainFormView(CPublishPointFormView::IDD)
{
//{{AFX_DATA_INIT(CPublishPointFormView)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_pSetting = NULL;
m_bInitialized = FALSE;
m_wideFont.CreateFont(Frame_Height, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
700, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
_T("Arial"));
m_thinFont.CreateFont(Frame_Height - 2, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
_T("Arial"));
}
CPublishPointFormView::~CPublishPointFormView()
{
}
void CPublishPointFormView::DoDataExchange(CDataExchange* pDX)
{
CXTMainFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPublishPointFormView)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPublishPointFormView, CXTMainFormView)
//{{AFX_MSG_MAP(CPublishPointFormView)
ON_WM_SIZE()
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPublishPointFormView diagnostics
#ifdef _DEBUG
void CPublishPointFormView::AssertValid() const
{
CXTMainFormView::AssertValid();
}
void CPublishPointFormView::Dump(CDumpContext& dc) const
{
CXTMainFormView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CPublishPointFormView message handlers
void CPublishPointFormView::OnInitialUpdate()
{
if(!m_bInitialized)
{
m_jpgBackGround.Load(IDR_BACKGROUND);
}
CXTMainFormView::OnInitialUpdate();
RecalcLayout();
}
void CPublishPointFormView::OnSize(UINT nType, int cx, int cy)
{
CXTMainFormView::OnSize(nType, cx, cy);
SetScaleToFitSize(CSize(cx, cy));
RecalcLayout();
}
void CPublishPointFormView::RecalcLayout()
{
if(m_bInitialized)
{
}
}
void CPublishPointFormView::InitSetting(XDLS_Setting *pSetting)
{
m_pSetting = pSetting;
}
void CPublishPointFormView::Server_Run()
{
}
void CPublishPointFormView::Server_Stop()
{
}
void CPublishPointFormView::OnTimerWork(UINT nID)
{
if(nID == TIMERID_TWOSECOND)
{
CClientDC dc(this);
OnDrawInfo(&dc);
}
}
void CPublishPointFormView::OnPaint()
{
CPaintDC dc(this); // device context for painting
OnDrawInfo(&dc);
// Do not call CXTMainFormView::OnPaint() for painting messages
}
void CPublishPointFormView::OnDrawInfo(CDC *pDC)
{
CRect rc;
CXTPClientRect rcClient(this);
CXTPBufferDC dc(pDC->GetSafeHdc(), rcClient);
if(m_jpgBackGround.IsLoad())
{
CSize sz = m_jpgBackGround.GetImageSize(&dc);
int row = rcClient.Width() / sz.cx + 1;
int col = rcClient.Height()/ sz.cy + 1;
for(int r = 0; r < row; r ++)
{
for(int c = 0; c < col; c ++)
{
rc.SetRect(r * sz.cx, c * sz.cy,
(r + 1) * sz.cx, (c + 1) * sz.cy);
m_jpgBackGround.Render(&dc, rc);
}
}
}
CFont *pOldFont = dc.SelectObject(&m_wideFont);
int oldBkMode = dc.SetBkMode(TRANSPARENT);
dc.SetBkMode(oldBkMode);
dc.SelectObject(pOldFont);
}
void CPublishPointFormView::Wnd_Active(BOOL bActive)
{
} | [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
] | [
[
[
1,
182
]
]
] |
eed7095957e64f915c316b5665e76d00f6bbf5ba | 191d4160cba9d00fce9041a1cc09f17b4b027df5 | /ZeroLag2/KUILib/Include/wtlhelper/whthreadnotify.h | e71168c9bf2a2f8fa400b7579cafad1843d0e216 | [] | no_license | zapline/zero-lag | f71d35efd7b2f884566a45b5c1dc6c7eec6577dd | 1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4 | refs/heads/master | 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | h | #pragma once
template <class T, DWORD t_dwElapse = 1000>
class CThreadNotify
{
public:
CThreadNotify()
: m_hEventStop(::CreateEvent(NULL, TRUE, FALSE, NULL))
, m_hWndNotify(NULL)
, m_uMsgNotify(WM_NULL)
{
}
virtual ~CThreadNotify()
{
if (m_hEventStop)
{
::CloseHandle(m_hEventStop);
m_hEventStop = NULL;
}
}
void Start(HWND hWnd, UINT uMsg)
{
m_hWndNotify = hWnd;
m_uMsgNotify = uMsg;
HANDLE hThread = ::CreateThread(NULL, 0, _WorkThreadProc, this, 0, NULL);
::CloseHandle(hThread);
}
void Stop()
{
::SetEvent(m_hEventStop);
}
// Need Overide
// Return NeedNotify
void Work(BOOL &bNeedNotify, WPARAM& wParam, LPARAM& lParam)
{
ATLASSERT(FALSE);
}
private:
HANDLE m_hEventStop;
HWND m_hWndNotify;
UINT m_uMsgNotify;
protected:
static DWORD WINAPI _WorkThreadProc(LPVOID pvParam)
{
BOOL bNeedNotify = FALSE;
WPARAM wParam = 0;
LPARAM lParam = 0;
T *pThis = (reinterpret_cast<T *>(pvParam));
while (TRUE)
{
pThis->Work(bNeedNotify, wParam, lParam);
if (bNeedNotify && pThis->m_hWndNotify && ::IsWindow(pThis->m_hWndNotify))
{
::SendMessage(pThis->m_hWndNotify, pThis->m_uMsgNotify, wParam, lParam);
}
DWORD dwRet = ::WaitForSingleObject(pThis->m_hEventStop, t_dwElapse);
if (WAIT_TIMEOUT != dwRet)
break;
}
return 0;
}
};
| [
"Administrator@PC-200201010241"
] | [
[
[
1,
77
]
]
] |
904597d5c19b9030274c4cb16bee0ea70f0766ba | 42a799a12ffd61672ac432036b6fc8a8f3b36891 | /cpp/IGC_Tron/IGC_Tron/ITexture.h | 69e39324b261b318d71c745c72e04996f5632e18 | [] | no_license | timotheehub/igctron | 34c8aa111dbcc914183d5f6f405e7a07b819e12e | e608de209c5f5bd0d315a5f081bf0d1bb67fe097 | refs/heads/master | 2020-02-26T16:18:33.624955 | 2010-04-08T16:09:10 | 2010-04-08T16:09:10 | 71,101,932 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,552 | h | /**************************************************************************/
/* This file is part of IGC Tron */
/* (c) IGC Software 2009 - 2010 */
/* Author : Pierre-Yves GATOUILLAT */
/**************************************************************************/
/* This program is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/**************************************************************************/
#ifndef _TEXTURE
#define _TEXTURE
/***********************************************************************************/
/** INCLUSIONS **/
/***********************************************************************************/
#include "Common.h"
#include "Engine.h"
#include "IRenderer.h"
/***********************************************************************************/
namespace IGC
{
/***********************************************************************************/
class ITexture
{
/***********************************************************************************/
/** CONSTANTES **/
/***********************************************************************************/
public:
static const int FORMAT_L8 = 0x01;
static const int FORMAT_L8A8 = 0x02;
static const int FORMAT_R8G8B8 = 0x03;
static const int FORMAT_R8G8B8A8 = 0x04;
/***********************************************************************************/
/** ATTRIBUTS **/
/***********************************************************************************/
protected:
Engine* engine;
IRenderer* renderer;
byte* data;
int width;
int height;
int format;
bool dirty;
/***********************************************************************************/
/** CONSTRUCTEURS / DESTRUCTEUR **/
/***********************************************************************************/
public:
/*
Instancie la classe sans allouer de mémoire pour la texture.
*/
ITexture( Engine* _engine );
/*
Libère les ressources.
*/
~ITexture();
/***********************************************************************************/
/** ACCESSEURS **/
/***********************************************************************************/
public:
/*
Renvoie un pointeur vers le moteur associé à cet objet.
*/
Engine* getEngine();
/*
Renvoie le renderer associé à cette texture.
*/
IRenderer* getRenderer();
/*
Renvoie la résolution horizontale de cette texture.
*/
int getWidth() { return width; };
/*
Renvoie la résolution verticale de cette texture.
*/
int getHeight() { return height; };
/*
Renvoie le format de cette texture.
*/
int getFormat() { return format; };
/***********************************************************************************/
/** METHODES PRIVEES **/
/***********************************************************************************/
protected:
int getPixelSize();
/***********************************************************************************/
/** METHODES PUBLIQUES **/
/***********************************************************************************/
public:
/*
Génère une nouvelle texture de la résolution spécifiée.
*/
void create( int _width = 256, int _height = 256, int _format = FORMAT_R8G8B8A8 );
/*
Remplit cette texture d'une couleur unie définie par les paramètres.
*/
virtual void fill( float _r = 0.0f, float _g = 0.0f, float _b = 0.0f, float _a = 0.0f );
virtual void fill( float _l = 0.0f, float _a = 0.0f );
/*
Charge un fichier au format Portable Network Graphics (*.png).
*/
void import( const char* _path );
/*
Force la mise à jour en mémoire vidéo.
*/
virtual void update() = 0;
/*
Active cette texture pour le prochain rendu.
*/
virtual void bind() = 0;
/*
Desactive la texture pour le prochain rendu.
*/
virtual void unbind() = 0;
};
}
/***********************************************************************************/
#endif
| [
"raoul12@de5929ad-f5d8-47c6-8969-ac6c484ef978",
"[email protected]"
] | [
[
[
1,
157
],
[
162,
167
]
],
[
[
158,
161
]
]
] |
98597b18cea55376d76fb6bb6ce3b396e1ade9fc | 256259aae3b263991e496f97ea4ae49ade619fda | /zxfloat.cpp | 4e1af35ff7ebb6e75c4ec37b6ffc5210d88005e1 | [] | no_license | majioa/zcl | a14cf2843ec2e1f1f3085ce6ac04fc1d2aebdbc1 | 833eafe1718939ca22f805bcaa200fc4bbf55a58 | refs/heads/master | 2021-01-10T18:40:31.817291 | 2004-07-19T03:39:57 | 2004-07-19T03:39:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,293 | cpp | #include "zxfloat.h"
//extern "C" extedned __fastcall Module$ggg();
//__asm
//{
//EXTRN @@Module$ggg;
//}
__fastcall ZComplexNumber::ZComplexNumber() : ZObject()
{
FReal = 0;
FVirtual = 0;
}
__fastcall ZComplexNumber::ZComplexNumber(extended rp, extended vp) : ZObject()
{
FReal = rp;
FVirtual = vp;
}
ZComplexNumber __fastcall ZComplexNumber::operator +(const ZComplexNumber& rhs) const
{
return ZComplexNumber(rhs.Real + FReal, rhs.Virtual + FVirtual);
}
ZComplexNumber __fastcall ZComplexNumber::operator +(const extended lhs) const
{
return ZComplexNumber(Real + lhs, Virtual);
}
ZComplexNumber __fastcall ZComplexNumber::operator -(const ZComplexNumber& rhs) const
{
return ZComplexNumber(FReal - rhs.Real, FVirtual - rhs.Virtual);
}
ZComplexNumber __fastcall ZComplexNumber::operator -() const
{
return ZComplexNumber(-FReal, -FVirtual);
}
ZComplexNumber __fastcall ZComplexNumber::operator -(const extended rhs) const
{
return ZComplexNumber(FReal - rhs, FVirtual);
}
ZComplexNumber __fastcall ZComplexNumber::operator *(const ZComplexNumber& rhs) const
{
return ZComplexNumber(FReal * rhs.Real - FVirtual * rhs.Virtual, FReal * rhs.Virtual + FVirtual * rhs.Real);
}
ZComplexNumber __fastcall ZComplexNumber::operator *(const extended rhs) const
{
return ZComplexNumber(FReal * rhs, FVirtual * rhs);
}
ZComplexNumber __fastcall ZComplexNumber::operator /(const ZComplexNumber& rhs) const
{
extended z = rhs.Virtual * rhs.Virtual + rhs.Real * rhs.Real;
if(z)
return ZComplexNumber((FReal * rhs.Real + FVirtual * rhs.Virtual)/z, (FVirtual * rhs.Real - FReal * rhs.Virtual)/z);
return ZComplexNumber(Inf,Inf);
}
ZComplexNumber __fastcall ZComplexNumber::operator /(const extended rhs) const
{
if(rhs)
return ZComplexNumber(FReal / rhs, FVirtual / rhs);
return ZComplexNumber(Inf, Inf);
}
ZComplexNumber &__fastcall ZComplexNumber::operator +=(const ZComplexNumber& rhs)
{
FReal += rhs.Real, FVirtual += rhs.Virtual;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator -=(const ZComplexNumber& rhs)
{
FReal -= rhs.Real, FVirtual -= rhs.Virtual;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator *=(const ZComplexNumber& rhs)
{
extended real = FReal * rhs.Real - FVirtual * rhs.Virtual;
FVirtual = FReal * rhs.Virtual + FVirtual * rhs.Real;
FReal = real;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator /=(const ZComplexNumber& rhs)
{
extended z = rhs.Virtual * rhs.Virtual + rhs.Real * rhs.Real, real;
if(z)
{
real = (FReal * rhs.Real + FVirtual * rhs.Virtual)/z;
FVirtual = (FVirtual * rhs.Real - FReal * rhs.Virtual)/z;
FReal = real;
}
else
{
FReal = Inf;
FVirtual = Inf;
}
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator =(const ZComplexNumber& rhs)
{
FReal = rhs.Real;
FVirtual = rhs.Virtual;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator =(const extended rhs)
{
FReal = rhs;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator =(const int rhs)
{
FReal = rhs;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator ^=(const extended rhs)
{
FVirtual = rhs;
return *this;
}
ZComplexNumber &__fastcall ZComplexNumber::operator ^=(const int rhs)
{
FVirtual = rhs;
return *this;
}
bool __fastcall ZComplexNumber::operator ==(const ZComplexNumber& rhs) const
{
return FReal == rhs.Real && FVirtual == rhs.Virtual;
}
bool __fastcall ZComplexNumber::operator !=(const ZComplexNumber& rhs) const
{
return FReal != rhs.Real || FVirtual != rhs.Virtual;
}
bool __fastcall ZComplexNumber::operator >(const ZComplexNumber& rhs) const
{
return FReal > rhs.Real && FVirtual > rhs.Virtual;
}
bool __fastcall ZComplexNumber::operator <(const ZComplexNumber& rhs) const
{
return FReal < rhs.Real && FVirtual < rhs.Virtual;
}
bool __fastcall ZComplexNumber::operator >=(const ZComplexNumber& rhs) const
{
return FReal >= rhs.Real && FVirtual >=rhs.Virtual;
}
bool __fastcall ZComplexNumber::operator <=(const ZComplexNumber& rhs) const
{
return FReal <= rhs.Real && FVirtual <= rhs.Virtual;
}
| [
"[email protected]"
] | [
[
[
1,
151
]
]
] |
9c5dc43f7058f1063fd08d7363beccee5de6baa3 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/neogeo/neo_text.cpp | 889551585b8c67fa1f06b034195e5545b0a59527 | [] | no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,834 | cpp | #include "neogeo.h"
unsigned char* NeoTextROM;
int nNeoTextROMSize = -1;
bool bBIOSTextROMEnabled;
static char* NeoTextTileAttrib = NULL;
static int nBankswitch;
static int nBankLookupAddress[40];
static int nBankLookupShift[40];
static unsigned char* pTile;
static unsigned char* pTileData;
static unsigned int* pTilePalette;
typedef void (*RenderTileFunction)();
static RenderTileFunction RenderTile;
static int nLastBPP = 0;
static int nMinX, nMaxX;
#define BPP 16
#include "neo_text_render.h"
#undef BPP
#define BPP 24
#include "neo_text_render.h"
#undef BPP
#define BPP 32
#include "neo_text_render.h"
#undef BPP
int NeoRenderText()
{
int x, y;
unsigned char* pTextROM;
char* pTileAttrib;
unsigned char* pCurrentRow = pBurnDraw;
unsigned int* pTextPalette = NeoPalette;
unsigned int nTileDown = nBurnPitch << 3;
unsigned int nTileLeft = nBurnBpp << 3;
unsigned short* pTileRow = (unsigned short*)(NeoGraphicsRAM + 0xE000);
#ifndef NO_LAYER_ENABLE_TOGGLE
if (!(nBurnLayer & 2)) {
return 0;
}
#endif
#if USE_BPP_RENDERING == 16
RenderTile = *RenderTile16;
#else
if (nLastBPP != nBurnBpp ) {
nLastBPP = nBurnBpp;
switch (nBurnBpp) {
case 2:
RenderTile = *RenderTile16;
break;
case 3:
RenderTile = *RenderTile24;
break;
case 4:
RenderTile = *RenderTile32;
break;
default:
return 1;
}
}
#endif
if (!bBIOSTextROMEnabled && nBankswitch) {
if (nBankswitch == 1) {
// GAROU, MSLUG3, MSLUG4, SAMSHO5, and SAMSH5SP
int nOffset[32];
int nBank = 0x001000 + (3 << 12);
int z = 0;
y = 0;
while (y < 32) {
if (*((unsigned short*)(NeoGraphicsRAM + 0xEA00 + z)) == 0x0200 && (*((unsigned short*)(NeoGraphicsRAM + 0xEB00 + z)) & 0xFF00) == 0xFF00) {
nBank = ((*((unsigned short*)(NeoGraphicsRAM + 0xEB00 + z)) & 3) ^ 3) << 12;
nBank += 0x001000;
nOffset[y++] = nBank;
}
nOffset[y++] = nBank;
z += 4;
}
for (y = 2, pTileRow += 2; y < 30; y++, pCurrentRow += nTileDown, pTileRow++) {
pTextROM = NeoTextROM + (nOffset[y - 2] << 5);
pTileAttrib = NeoTextTileAttrib + nOffset[y - 2];
for (x = nMinX, pTile = pCurrentRow; x < nMaxX; x++, pTile += nTileLeft) {
unsigned int nTile = pTileRow[x << 5];
int nPalette = nTile & 0xF000;
nTile &= 0x0FFF;
if (pTileAttrib[nTile] == 0) {
pTileData = pTextROM + (nTile << 5);
pTilePalette = &pTextPalette[nPalette >> 8];
RenderTile();
}
}
}
} else {
// KOF2000, MATRIM, SVC, and KOF2003
unsigned short* pBankInfo = (unsigned short*)(NeoGraphicsRAM + 0xEA00) + 1;
pTextROM = NeoTextROM + 0x020000;
pTileAttrib = NeoTextTileAttrib + 0x01000;
for (y = 2, pTileRow += 2; y < 30; y++, pCurrentRow += nTileDown, pTileRow++, pBankInfo++) {
for (x = nMinX, pTile = pCurrentRow; x < nMaxX; x++, pTile += nTileLeft) {
unsigned int nTile = pTileRow[x << 5];
int nPalette = nTile & 0xF000;
nTile &= 0x0FFF;
nTile += (((pBankInfo[nBankLookupAddress[x]] >> nBankLookupShift[x]) & 3) ^ 3) << 12;
if (pTileAttrib[nTile] == 0) {
pTileData = pTextROM + (nTile << 5);
pTilePalette = &pTextPalette[nPalette >> 8];
RenderTile();
}
}
}
}
} else {
if (bBIOSTextROMEnabled) {
pTextROM = NeoTextROM;
pTileAttrib = NeoTextTileAttrib;
} else {
pTextROM = NeoTextROM + 0x020000;
pTileAttrib = NeoTextTileAttrib + 0x1000;
}
for (y = 2, pTileRow += 2; y < 30; y++, pCurrentRow += nTileDown, pTileRow++) {
for (x = nMinX, pTile = pCurrentRow; x < nMaxX; x++, pTile += nTileLeft) {
unsigned int nTile = pTileRow[x << 5];
int nPalette = nTile & 0xF000;
nTile &= 0xFFF;
if (pTileAttrib[nTile] == 0) {
pTileData = pTextROM + (nTile << 5);
pTilePalette = &pTextPalette[nPalette >> 8];
RenderTile();
}
}
}
}
return 0;
}
// kof10th
static inline void NeoUpdateTextAttribOne(const int nOffset)
{
for (int i = nOffset; i < nOffset + 32; i += 4) {
if (*((unsigned int*)(NeoTextROM + i))) {
NeoTextTileAttrib[nOffset >> 5] = 0;
break;
}
}
}
void NeoUpdateTextOne(int nOffset, const unsigned char byteValue)
{
nOffset = (nOffset & ~0x1F) | (((nOffset ^ 0x10) & 0x18) >> 3) | ((nOffset & 0x07) << 2);
if (byteValue) {
NeoTextTileAttrib[nOffset >> 5] = 0;
} else {
if (NeoTextTileAttrib[nOffset >> 5] == 0 && NeoTextROM[nOffset]) {
NeoTextTileAttrib[nOffset >> 5] = 1;
NeoUpdateTextAttribOne(nOffset);
}
}
NeoTextROM[nOffset] = byteValue;
}
void NeoExitText()
{
free(NeoTextTileAttrib);
NeoTextTileAttrib = NULL;
}
int NeoInitText()
{
int nTileNum = (0x020000 + nNeoTextROMSize) >> 5;
free(NeoTextTileAttrib);
NeoTextTileAttrib = (char*)malloc((nTileNum < 0x2000) ? 0x2000 : nTileNum);
if (nNeoScreenWidth == 304) {
nMinX = 1;
nMaxX = 39;
} else {
nMinX = 0;
nMaxX = 40;
}
for (int i = 0; i < nTileNum; i++) {
pTile = NeoTextROM + (i << 5);
bool bTransparent = true;
for (int j = 0; j < 32; j++) {
if (pTile[j]) {
bTransparent = false;
break;
}
}
if (bTransparent) {
NeoTextTileAttrib[i] = 1;
} else {
NeoTextTileAttrib[i] = 0;
}
}
for (int i = nTileNum; i < 0x2000; i++) {
NeoTextTileAttrib[i] = 1;
}
nBankswitch = 0;
if (nNeoTextROMSize > 0x040000) {
if (BurnDrvGetHardwareCode() & HARDWARE_SNK_ALTERNATE_TEXT) {
nBankswitch = 2;
// Precompute lookup-tables
for (int x = nMinX; x < nMaxX; x++) {
nBankLookupAddress[x] = (x / 6) << 5;
nBankLookupShift[x] = (5 - (x % 6)) << 1;
}
} else {
nBankswitch = 1;
}
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
241
]
]
] |
9cd6945f34a99c01a17a5effa9b257daef903cac | 3ecc6321b39e2aedb14cb1834693feea24e0896f | /src/light.cpp | ec3e0a4fc2e2887bf96c3d7cc630a9f8d1cb593b | [] | no_license | weimingtom/forget3d | 8c1d03aa60ffd87910e340816d167c6eb537586c | 27894f5cf519ff597853c24c311d67c7ce0aaebb | refs/heads/master | 2021-01-10T02:14:36.699870 | 2011-06-24T06:21:14 | 2011-06-24T06:21:14 | 43,621,966 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,308 | cpp | /*****************************************************************************
* Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected])
* ALL RIGHTS RESERVED
*
* License I
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITHOUT a fee is granted under following requirements:
* - You make no money using this software.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* Licence II
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITH a fee is granted under following requirements:
* - As soon as you make money using this software, you have to pay a
* licence fee. Until this point of time, you can use this software
* without a fee.
* Please contact Martin Foo ([email protected]) for further details.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS
* BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER,
* INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR
* REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*****************************************************************************/
#include "light.h"
namespace F3D {
/**
* Light class for all games using F3D.
*/
Light::Light() :
m_position(NULL),
m_ambient(NULL),
m_diffuse(NULL),
m_specular(NULL),
m_emission(NULL) {
#ifdef DEBUG
printf("Light constructor...\n");
#endif
}
Light::~Light() {
#ifdef DEBUG
printf("Light destructor...\n");
#endif
}
void Light::setPosition(GLfloat* position) {
m_position = position;
}
void Light::setAmbient(GLfloat* ambient) {
m_ambient = ambient;
}
void Light::setDiffuse(GLfloat* diffuse) {
m_diffuse = diffuse;
}
void Light::setSpecular(GLfloat* specular) {
m_specular = specular;
}
void Light::setEmission(GLfloat* emission) {
m_emission = emission;
}
void Light::initLight() {
glEnable(GL_LIGHT0);
if (m_position != NULL)
glLightfv(GL_LIGHT0, GL_POSITION, m_position);
if (m_ambient != NULL)
glLightfv(GL_LIGHT0, GL_AMBIENT, m_ambient);
if (m_diffuse != NULL)
glLightfv(GL_LIGHT0, GL_DIFFUSE, m_diffuse);
if (m_specular != NULL)
glLightfv(GL_LIGHT0, GL_SPECULAR, m_specular);
if (m_emission != NULL)
glLightfv(GL_LIGHT0, GL_EMISSION, m_emission);
}
}
| [
"i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613"
] | [
[
[
1,
98
]
]
] |
45a89862273d3d000cb416311f24afdb5a6678ec | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/dialog/OpenURLDialog.cpp | 46949aadb77fbda0f3bd54dae4e514a2dd782c04 | [] | no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,492 | cpp | /**
* @file OpenURLDialog.cpp
*/
#include "stdafx.h"
#include "OpenURLDialog.h"
#if defined USE_ATLDBGMEM
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Constructor
COpenURLDlg::COpenURLDlg()
{
}
// Handler
LRESULT COpenURLDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
CenterWindow( GetParent() );
DoDataExchange(FALSE);
m_edit.Attach( GetDlgItem(IDC_EDIT_URL) );
return 0;
}
LRESULT COpenURLDlg::OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/)
{
DoDataExchange(TRUE);
EndDialog(wID);
return 0;
}
void COpenURLDlg::OnRefCmd(UINT /*wNotifyCode*/, int /*wID*/, HWND /*hWndCtl*/)
{
const TCHAR szFilter[] = _T("HTMLファイル(*.htm;*.html)\0*.htm;*.html\0")
_T("Donut Favorite Groupファイル(*.dfg)\0*.dfg\0")
_T("テキストファイル(*.txt)\0*.txt\0")
_T("GIFファイル(*.gif)\0*.gif\0")
_T("JPEGファイル(*.jpg;*.jpeg)\0*.jpg;*.jpeg\0")
_T("AUファイル(*.au)\0*.au\0")
_T("AIFFファイル(*.aif;*.aiff)\0*.aif;*.aiff\0")
_T("XBMファイル(*.xbm)\0*.xbm\0")
_T("すべてのファイル(*.*)\0*.*\0\0");
CFileDialog fileDlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, szFilter);
fileDlg.m_ofn.lpstrTitle = _T("開く");
if (fileDlg.DoModal() == IDOK) {
m_edit.SetWindowText(fileDlg.m_szFileName);
}
}
| [
"[email protected]"
] | [
[
[
1,
63
]
]
] |
bf8a496dc29b8034c1253b680460f6fddca687f8 | 067ff5708784b1fd2595957de78518e87073ccb4 | /Image Viewer/Viewer Application/WindowScroller.cpp | df045efc993b52e326216d37ff2f6fd8e8c6f544 | [] | no_license | wolfmanu/opencvthesis | 637a6a6ead5c839e731faca19ae0dd3e59e33cd3 | c4e806d6369b4ed80ebadce1684e32f147eafce4 | refs/heads/master | 2016-09-05T22:38:07.528951 | 2010-09-10T12:01:49 | 2010-09-10T12:01:49 | 32,142,213 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 75,949 | cpp | /****************************************************************************
WindowScroller.cpp : implementation file
Written by : PJ Arends
[email protected]
Copyright © 2003 PJ Arends
-----------------------------------------------------------------------------
This code is provided as is, with no warranty as to it's suitability or usefulness
in any application in which it may be used.
This code may be used in any way you desire. This file may be redistributed by any
means as long as it is not sold for profit, and providing that this notice and the
author's name are included. Any modifications not made by the original author should
be clearly marked as such to remove any confusion between the original version and
any other versions.
If any bugs are found and fixed, a note to the author explaining the problem and
fix would be nice.
-----------------------------------------------------------------------------
Revision History:
Some code provided by:
Jean-Michel LE FOL - [email protected]
Dieter Hammer - [email protected]
January 10, 2003 - original release
January 20, 2003 - JMLF - added code for scrolling list views
January 23, 2003 - fixed middle button click'n hold bug
February 16, 2003 - added 'mouse button up' handlers
March 1, 2003 - added bUseThumbPos parameter to constructor
as requested by Neville Franks - [email protected]
March 8, 2003 - fixed bug that crashed program if window creation fails
March 10, 2003 - total rewrite of scrolling code, now supports tree views
and list views in all modes
- added GetParentWndType() function
April 30, 2006 - moved code into the pja namespace
- improved drawing code
****************************************************************************/
#include "stdafx.h"
#include <afxcview.h> // for list view and tree view support
#include <math.h> // for abs()
#include "WindowScroller.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Static member pointer used by the hook procedures
pja::CWindowScroller* pja::CWindowScroller::pWindowScroller = NULL;
namespace pja
{
// WindowTypes enumeration. Used to identify the type of window being scrolled.
enum WindowTypes
{
Type_CWnd = 0,
Type_CScrollView,
Type_CTreeView,
Type_CListView_Report,
Type_CListView_List,
Type_CListView_Icon,
// Add more types here
Type_CListBox
};
// Keyboard hook used to kill scroller window if a key is pressed
LRESULT CALLBACK WindowScrollerKeyBoardHookProc(int code, WPARAM wp, LPARAM lp)
{
ASSERT_VALID(CWindowScroller::pWindowScroller);
CallNextHookEx(CWindowScroller::pWindowScroller->m_hKeyboardHook, code, wp, lp);
ReleaseCapture();
return 1;
}
// Mouse hook used to kill scroller if mouse wheel is rotated
LRESULT CALLBACK WindowScrollerMouseHookProc(int code, WPARAM wp, LPARAM lp)
{
ASSERT_VALID(CWindowScroller::pWindowScroller);
LRESULT ret = CallNextHookEx(CWindowScroller::pWindowScroller->m_hMouseHook, code, wp, lp);
if (wp == WM_MOUSEWHEEL)
{
ReleaseCapture();
ret = 1; // eat the WM_MOUSEWHEEL message
}
return ret;
}
};
/////////////////////////////////////////////////////////////////////////////
// CWindowScroller
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller constructor (public member function)
// Constructs, initializes, and runs the window scroller
//
// Parameters :
// pParent [in] : Pointer to the window that has to be scrolled
// Point [in] : The point, in pParent client coordinates, where the scroller
// window is to be centered on
// Pixels [in] : The pixel ratio that is used to calculate the scrolling speed
// Elapse [in] : The delay time between scrolling messages
// Direction [in] : The allowable directions to scroll, either Horizontal, Vertical
// or Both (default)
// bUseThumbPos [in] : Set the flag to be used within the WM_VSCROLL/WM_HSCROLL message
// TRUE for SB_THUMBPOSITION (default)
// FALSE for SB_THUMBTRACK
//
/////////////////////////////////////////////////////////////////////////////
pja::CWindowScroller::CWindowScroller(CWnd *pParent,
CPoint Point,
int Pixels, // = 15
UINT Elapse, // = 30
int Direction, // = Both
BOOL bUseThumbPos) // = TRUE
{
ASSERT_VALID (pParent);
ASSERT (Pixels > 0);
ASSERT (Elapse > 0);
ASSERT (Direction >= Vertical && Direction <= Both);
// Initialize all member variables
Initialize();
m_pParentWnd = pParent;
m_Alignment = Direction;
DWORD dwStyle = m_pParentWnd->GetStyle();
// ensure the parent window allows vertical scrolling
CScrollBar* pBar = m_pParentWnd->GetScrollBarCtrl(SB_VERT);
BOOL bHasBar = ((pBar != NULL) && pBar->IsWindowEnabled()) || (dwStyle & WS_VSCROLL);
if (!bHasBar)
m_Alignment &= ~Vertical;
// ensure the parent window allows horizontal scrolling
pBar = m_pParentWnd->GetScrollBarCtrl(SB_HORZ);
bHasBar = ((pBar != NULL) && pBar->IsWindowEnabled()) || (dwStyle & WS_HSCROLL);
if (!bHasBar)
m_Alignment &= ~Horizontal;
if (!m_Alignment)
{ // scrolling not allowed or not needed, cleanup and get out
TRACE (_T("CWindowScroller::CWindowScroller - No scrolling allowed or needed\n"));
delete this;
}
else
{
// center the window on the given point
m_pParentWnd->ClientToScreen(&Point);
m_CenterPoint = Point;
// create the window
if (CreateEx(NULL,
AfxRegisterWndClass(0, NULL, (HBRUSH)GetStockObject(WHITE_BRUSH), NULL),
NULL,
WS_POPUP | WS_VISIBLE,
m_CenterPoint.x - 15,
m_CenterPoint.y - 15,
32,
32,
*m_pParentWnd,
NULL,
NULL))
{
// we give the parent window the focus to ensure it's caption bar shows the active colour
// also not doing so causes an assertion in debug mode when a key is pressed on the keyboard
m_pParentWnd->SetFocus();
// ensure we get all mouse messages
SetCapture();
// set up the keyboard hook
pWindowScroller = this;
m_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD,
pja::WindowScrollerKeyBoardHookProc,
NULL,
AfxGetApp()->m_nThreadID);
// set up the mouse hook
m_hMouseHook = SetWindowsHookEx(WH_MOUSE,
pja::WindowScrollerMouseHookProc,
NULL,
AfxGetApp()->m_nThreadID);
// create all the necessary cursors and icon
BuildCursors();
// Set the scrolling speed
m_ScrollRatio = Pixels;
// Set the scrolling flag used with WM_VSCROLL/WM_HSCROLL
m_ScrollFlag = bUseThumbPos ? SB_THUMBPOSITION : SB_THUMBTRACK;
// Determine the parent window type
m_ParentWndType = GetParentWndType();
// Set the mouse cursor
SetMyCursor();
// Start the timer
SetTimer (0x1FEB, Elapse, NULL);
}
else // Window creation failed, get out
{
TRACE (_T("CWindowScroller::CWindowScroller - Window creation failed\n"));
}
}
}
BEGIN_MESSAGE_MAP(pja::CWindowScroller, CWnd)
//{{AFX_MSG_MAP(CWindowScroller)
ON_WM_CAPTURECHANGED()
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MBUTTONDOWN()
ON_WM_MBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_PAINT()
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_WM_TIMER()
//}}AFX_MSG_MAP
#ifdef WM_XBUTTONDOWN
ON_MESSAGE(WM_XBUTTONDOWN, OnXButtonDown)
ON_MESSAGE(WM_XBUTTONUP, OnXButtonUp)
#endif // WM_XBUTTONDOWN
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWindowScroller message handlers
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::GetParentWndType (protected member function)
// Because different window types have different scrolling rules, this
// function is used to determine the window type.
//
// Parameters :
// None
//
// Returns :
// The parent window type
//
/////////////////////////////////////////////////////////////////////////////
UINT pja::CWindowScroller::GetParentWndType() const
{
TCHAR szClassName[256] = {0};
::GetClassName(*m_pParentWnd, szClassName, _countof(szClassName));
if (!_tcscmp(szClassName, WC_TREEVIEW))
return Type_CTreeView;
if (!_tcscmp(szClassName, WC_LISTVIEW))
{
if ((m_pParentWnd->GetStyle() & LVS_TYPEMASK) == LVS_REPORT)
return Type_CListView_Report;
if ((m_pParentWnd->GetStyle() & LVS_TYPEMASK) == LVS_LIST)
return Type_CListView_List;
return Type_CListView_Icon;
}
if (m_pParentWnd->IsKindOf(RUNTIME_CLASS(CScrollView)))
return Type_CScrollView;
// Add additional window identifier code here
if (!_tcsicmp(szClassName, _T("ListBox")))
return Type_CListBox;
return Type_CWnd;
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::Initialize (protected member function)
// Initializes all the member variables to zero or NULL
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::Initialize()
{
m_Alignment = 0;
m_bWindowScrolled = FALSE;
m_CenterPoint.x = m_CenterPoint.y = 0;
m_DownCursor = NULL;
m_DownLeftCursor = NULL;
m_DownRightCursor = NULL;
m_hIcon = NULL;
m_hKeyboardHook = NULL;
m_hMouseHook = NULL;
m_HorzScroll = 0;
m_hWnd = NULL;
m_LeftCursor = NULL;
m_NeutralCursor = NULL;
m_ParentWndType = 0;
m_pParentWnd = NULL;
m_RightCursor = NULL;
m_ScrollFlag = 0;
m_ScrollRatio = 0;
m_UpCursor = NULL;
m_UpLeftCursor = NULL;
m_UpRightCursor = NULL;
m_VertScroll = 0;
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnCaptureChanged (protected member function)
// Handles the WM_CAPTURECHANGED message.
// This function gets called when another app that is started via keyboard
// shortcut keys (such as on the MS Internet keyboard) or via the
// scheduled tasks manager grabs the mouse capture.
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnCaptureChanged(CWnd *)
{
DestroyWindow();
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnCreate (protected member function)
// called by the MFC framework when the window is created
// sets the window region to an elliptical region
//
// Parameters :
// lpCreateStruct - not used here, passed on to base class
//
// Returns :
// zero if window creation is to continue
// minus one if the window creation fails and the window is to be destroyed
//
/////////////////////////////////////////////////////////////////////////////
int pja::CWindowScroller::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
/* return CWnd::OnCreate(lpCreateStruct);
*/
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (m_WndRgn.CreateEllipticRgn(0, 0, 32, 32) &&
SetWindowRgn(m_WndRgn, FALSE))
return 0;
return -1;
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnDestroy (protected member function)
// called by the MFC framework when the window is destroyed
// cleans up all the system resources that were used
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnDestroy()
{
CWnd::OnDestroy();
// inform parent window that scroller window is being destroyed
m_pParentWnd->PostMessage(RWM_DESTROYWINDOWSCROLLER, 0, 0);
UnhookWindowsHookEx(m_hKeyboardHook);
UnhookWindowsHookEx(m_hMouseHook);
pWindowScroller = NULL;
KillTimer(0x1FEB);
DestroyIcon(m_hIcon);
DestroyCursor(m_DownCursor);
DestroyCursor(m_DownLeftCursor);
DestroyCursor(m_DownRightCursor);
DestroyCursor(m_LeftCursor);
DestroyCursor(m_NeutralCursor);
DestroyCursor(m_RightCursor);
DestroyCursor(m_UpCursor);
DestroyCursor(m_UpLeftCursor);
DestroyCursor(m_UpRightCursor);
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::On?Button? (protected member functions)
// Call ReleaseCapture() if any mouse button is pressed or released
//
// Parameters :
// None
//
// Returns :
// Nothing
//
// Note : calling ReleaseCapture() causes OnCaptureChanged() to be called.
// OnCaptureChanged() calls DestroyWindow()
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnLButtonDown(UINT, CPoint)
{
ReleaseCapture();
}
void pja::CWindowScroller::OnLButtonUp(UINT, CPoint)
{
if (m_bWindowScrolled)
ReleaseCapture();
}
void pja::CWindowScroller::OnMButtonDown(UINT, CPoint)
{
ReleaseCapture();
}
void pja::CWindowScroller::OnMButtonUp(UINT, CPoint)
{
if (m_bWindowScrolled)
ReleaseCapture();
}
void pja::CWindowScroller::OnRButtonDown(UINT, CPoint)
{
ReleaseCapture();
}
void pja::CWindowScroller::OnRButtonUp(UINT, CPoint)
{
if (m_bWindowScrolled)
ReleaseCapture();
}
LRESULT pja::CWindowScroller::OnXButtonDown(WPARAM, LPARAM)
{
ReleaseCapture();
return TRUE;
}
LRESULT pja::CWindowScroller::OnXButtonUp(WPARAM, LPARAM)
{
if (m_bWindowScrolled)
ReleaseCapture();
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnMouseMove (protected member function)
// handles the WM_MOUSEMOVE message
// calls SetMyCursor() to set the mouse cursor and calculate the scrolling
// direction and speed
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnMouseMove(UINT, CPoint)
{
SetMyCursor();
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnPaint (protected member function)
// handles the WM_PAINT message
// paints the window
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnPaint()
{
CPaintDC dc(this); // device context for painting
// CBrush brush(GetSysColor(COLOR_WINDOW));
// CBrush *pOld = (CBrush *)dc.SelectObject(&brush);
// dc.Ellipse(1, 1, 34, 34);
dc.DrawIcon(0, 0, m_hIcon);
// dc.SelectObject(pOld);
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::OnTimer (protected member function)
// handles the WM_TIMER message
// If the parent window is a ListView, it is sent a LVM_SCROLL message (thanks JMLF)
// If the parent window is a CScrollView, the parent window is scrolled
// If the parent window is any other window, the parent window is sent
// a WM_HSCROLL and/or a WM_VSCROLL message with either a SB_THUMBPOSITION or
// SB_THUMBTRACK flag depending on the value of m_ScrollFlag.
//
// Parameters :
// nIDEvent [in] - The ID of the timer that triggered this message
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::OnTimer(UINT nIDEvent)
{
CPoint pt;
GetCursorPos(&pt);
CRect WindowRect;
AfxGetMainWnd()->GetWindowRect(&WindowRect);
if (nIDEvent == 0x1FEB && WindowRect.PtInRect(pt) && (m_HorzScroll || m_VertScroll))
{
m_bWindowScrolled = TRUE;
CPoint OriginalPoint (m_pParentWnd->GetScrollPos(SB_HORZ), m_pParentWnd->GetScrollPos(SB_VERT));
CPoint NewPoint = OriginalPoint;
NewPoint.x += m_HorzScroll;
NewPoint.y += m_VertScroll;
int xMax = m_pParentWnd->GetScrollLimit(SB_HORZ);
int yMax = m_pParentWnd->GetScrollLimit(SB_VERT);
if (NewPoint.x < 0)
NewPoint.x = 0;
else if (NewPoint.x > xMax)
NewPoint.x = xMax;
if (NewPoint.y < 0)
NewPoint.y = 0;
else if (NewPoint.y > yMax)
NewPoint.y = yMax;
if (NewPoint != OriginalPoint)
{
switch (m_ParentWndType)
{
case Type_CListView_Report:
{
CListView *pView = static_cast<CListView *>(m_pParentWnd);
CListCtrl& list = pView->GetListCtrl();
int item = list.GetTopIndex();
if (item && m_VertScroll < 0)
--item;
CRect rc;
list.GetItemRect(item, rc, LVIR_BOUNDS);
int height = rc.Height();
static int cumulative = 0;
cumulative += NewPoint.y - OriginalPoint.y;
m_pParentWnd->SendMessage(LVM_SCROLL, NewPoint.x - OriginalPoint.x, cumulative);
if (abs(cumulative) >= (height + 1) / 2)
cumulative = 0;
}
break;
case Type_CListView_List:
{
CListView *pView = static_cast<CListView *>(m_pParentWnd);
CListCtrl& list = pView->GetListCtrl();
CRect rc;
list.GetItemRect(0, rc, LVIR_BOUNDS);
int width = rc.Width();
static int cumulative = 0;
cumulative += NewPoint.x - OriginalPoint.x;
int columns = cumulative / width;
m_pParentWnd->SendMessage(LVM_SCROLL, columns, NewPoint.y - OriginalPoint.y);
if (columns)
cumulative = 0;
}
break;
case Type_CListView_Icon:
m_pParentWnd->SendMessage(LVM_SCROLL, NewPoint.x - OriginalPoint.x, NewPoint.y - OriginalPoint.y);
break;
case Type_CTreeView:
if (NewPoint.x != OriginalPoint.x)
{
m_pParentWnd->SetScrollPos(SB_HORZ, NewPoint.x);
m_pParentWnd->SendMessage(WM_HSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.x), NULL);
}
if (NewPoint.y != OriginalPoint.y)
{
CTreeView *pView = static_cast<CTreeView *>(m_pParentWnd);
CTreeCtrl& tree = pView->GetTreeCtrl();
int height = tree.GetItemHeight();
static int cumulative = 0;
cumulative += NewPoint.y - OriginalPoint.y;
if (abs(cumulative) >= height)
{
m_pParentWnd->SetScrollPos(SB_VERT, NewPoint.y);
m_pParentWnd->SendMessage(WM_VSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.y), NULL);
cumulative = 0;
}
}
break;
case Type_CScrollView:
m_pParentWnd->SetScrollPos(SB_HORZ, NewPoint.x);
m_pParentWnd->SetScrollPos(SB_VERT, NewPoint.y);
m_pParentWnd->ScrollWindow(OriginalPoint.x - NewPoint.x, OriginalPoint.y - NewPoint.y);
break;
case Type_CWnd:
if (NewPoint.x != OriginalPoint.x)
{
m_pParentWnd->SetScrollPos(SB_HORZ, NewPoint.x);
m_pParentWnd->SendMessage(WM_HSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.x), NULL);
}
if (NewPoint.y != OriginalPoint.y)
{
m_pParentWnd->SetScrollPos(SB_VERT, NewPoint.y);
m_pParentWnd->SendMessage(WM_VSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.y), NULL);
}
break;
// Add additional cases here
case Type_CListBox:
if (NewPoint.x != OriginalPoint.x)
{
m_pParentWnd->SetScrollPos(SB_HORZ, NewPoint.x);
m_pParentWnd->SendMessage(WM_HSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.x), NULL);
}
if (NewPoint.y != OriginalPoint.y)
{
CListBox *pBox = static_cast<CListBox *>(m_pParentWnd);
int item = pBox->GetTopIndex();
if (item && m_VertScroll < 0)
--item;
int height = pBox->GetItemHeight(item);
static int cumulative = 0;
cumulative += NewPoint.y - OriginalPoint.y;
if (abs(cumulative) >= height)
{
m_pParentWnd->SetScrollPos(SB_VERT, NewPoint.y);
m_pParentWnd->SendMessage(WM_VSCROLL, MAKEWPARAM (m_ScrollFlag, NewPoint.y), NULL);
cumulative = 0;
}
}
break;
default:
TRACE (_T("CWindowScroller::OnTimer - Unknown window type\n"));
break;
} // switch (m_ParentWndType)
} // if (NewPoint != OriginalPoint)
} // if (nIDEvent == 0x1FEB && rc.PtInRect(pt) && (m_HorzScroll || m_VertScroll))
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::PostNcDestroy (protected member function)
// called by the MFC framework after the window has been destroyed
// deletes this instance of the CWindowScroller class
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::PostNcDestroy()
{
delete this;
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::SetMyCursor (protected member function)
// Sets the mouse cursor and calculates the scrolling distance
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
void pja::CWindowScroller::SetMyCursor()
{
m_HorzScroll = 0;
m_VertScroll = 0;
CPoint pt;
GetCursorPos(&pt);
int ydiff = pt.y - m_CenterPoint.y;
int xdiff = pt.x - m_CenterPoint.x;
switch (m_Alignment)
{
case Vertical:
{
if (abs(xdiff) > 16)
m_bWindowScrolled = TRUE;
if (abs(ydiff) < 17)
SetCursor(m_NeutralCursor);
else
{
if (ydiff > 0)
SetCursor(m_DownCursor);
else
SetCursor(m_UpCursor);
m_VertScroll = ydiff / m_ScrollRatio;
if (!m_VertScroll)
m_VertScroll = ydiff > 0 ? 1 : -1;
}
}
break;
case Horizontal:
{
if (abs(ydiff) > 16)
m_bWindowScrolled = TRUE;
if (abs(xdiff) < 17)
SetCursor(m_NeutralCursor);
else
{
if (xdiff > 0)
SetCursor(m_RightCursor);
else
SetCursor(m_LeftCursor);
m_HorzScroll = xdiff / m_ScrollRatio;
if (!m_HorzScroll)
m_HorzScroll = xdiff > 0 ? 1 : -1;
}
}
break;
case Both:
{
if (abs(ydiff) < 17 && abs(xdiff) < 17)
SetCursor(m_NeutralCursor);
else
{
if (abs(ydiff) < 17)
{
if (xdiff > 0)
SetCursor(m_RightCursor);
else
SetCursor(m_LeftCursor);
m_HorzScroll = xdiff / m_ScrollRatio;
if (!m_HorzScroll)
m_HorzScroll = xdiff > 0 ? 1 : -1;
}
else if (abs(xdiff) < 17)
{
if (ydiff > 0)
SetCursor(m_DownCursor);
else
SetCursor(m_UpCursor);
m_VertScroll = ydiff / m_ScrollRatio;
if (!m_VertScroll)
m_VertScroll = ydiff > 0 ? 1 : -1;
}
else
{
if (xdiff > 0)
{
if (ydiff > 0)
SetCursor(m_DownRightCursor);
else
SetCursor(m_UpRightCursor);
}
else
{
if (ydiff > 0)
SetCursor(m_DownLeftCursor);
else
SetCursor(m_UpLeftCursor);
}
m_HorzScroll = xdiff / m_ScrollRatio;
if (!m_HorzScroll)
m_HorzScroll = xdiff > 0 ? 1 : -1;
m_VertScroll = ydiff / m_ScrollRatio;
if (!m_VertScroll)
m_VertScroll = ydiff > 0 ? 1 : -1;
}
}
}
break;
default:
ASSERT (FALSE);
}
}
/////////////////////////////////////////////////////////////////////////////
//
// CWindowScroller::BuildCursors (protected member function)
// creates the icon and cursors that are needed
//
// Parameters :
// None
//
// Returns :
// Nothing
//
/////////////////////////////////////////////////////////////////////////////
#pragma warning (push)
#pragma warning (disable : 4706) // assignment within conditional expression
void pja::CWindowScroller::BuildCursors()
{
LPBYTE pData = NULL;
HINSTANCE hInst = AfxGetInstanceHandle();
BYTE BothIconData[] = {0x28, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00,
0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00,
0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x88,
0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x88, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
0x88, 0x88, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x88, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x88,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x00,
0x00, 0x88, 0x80, 0x00, 0x08, 0x88, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x88, 0x00, 0x08, 0x88, 0x88, 0x00,
0x08, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88,
0x88, 0x00, 0x00, 0x88, 0x80, 0x00, 0x08, 0x88, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x08,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x88, 0x88, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88,
0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0x87, 0xC3, 0xFF, 0xFF, 0x7F,
0xFD, 0xFF, 0xFC, 0xFF, 0xFE, 0x7F, 0xFB, 0xFF, 0xFF, 0xBF,
0xF7, 0xFE, 0xFF, 0xDF, 0xEF, 0xFC, 0x7F, 0xEF, 0xEF, 0xF8,
0x3F, 0xEF, 0xDF, 0xF0, 0x1F, 0xF7, 0xBF, 0xE0, 0x0F, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xBF, 0xFB, 0xFB, 0xBF, 0x3F,
0xF9, 0xFB, 0x7E, 0x3E, 0xF8, 0xFD, 0x7C, 0x3C, 0x78, 0x7D,
0x78, 0x38, 0x38, 0x3D, 0x7C, 0x3C, 0x78, 0x7D, 0x7E, 0x3E,
0xF8, 0xFD, 0xBF, 0x3F, 0xF9, 0xFB, 0xBF, 0xBF, 0xFB, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xE0, 0x0F, 0xFB, 0xDF, 0xF0,
0x1F, 0xF7, 0xEF, 0xF8, 0x3F, 0xEF, 0xEF, 0xFC, 0x7F, 0xEF,
0xF7, 0xFE, 0xFF, 0xDF, 0xFB, 0xFF, 0xFF, 0xBF, 0xFC, 0xFF,
0xFE, 0x7F, 0xFF, 0x7F, 0xFD, 0xFF, 0xFF, 0x87, 0xC3, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF};
BYTE UpDnIconData[] = {0x28, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00,
0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00,
0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x88,
0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x88, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
0x88, 0x88, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x88, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x88, 0x88, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88,
0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0x87, 0xC3, 0xFF, 0xFF, 0x7F,
0xFD, 0xFF, 0xFC, 0xFF, 0xFE, 0x7F, 0xFB, 0xFF, 0xFF, 0xBF,
0xF7, 0xFE, 0xFF, 0xDF, 0xEF, 0xFC, 0x7F, 0xEF, 0xEF, 0xF8,
0x3F, 0xEF, 0xDF, 0xF0, 0x1F, 0xF7, 0xBF, 0xE0, 0x0F, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xFF,
0xFF, 0xFB, 0x7F, 0xFE, 0xFF, 0xFD, 0x7F, 0xFC, 0x7F, 0xFD,
0x7F, 0xF8, 0x3F, 0xFD, 0x7F, 0xFC, 0x7F, 0xFD, 0x7F, 0xFE,
0xFF, 0xFD, 0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xFF, 0xFF, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xE0, 0x0F, 0xFB, 0xDF, 0xF0,
0x1F, 0xF7, 0xEF, 0xF8, 0x3F, 0xEF, 0xEF, 0xFC, 0x7F, 0xEF,
0xF7, 0xFE, 0xFF, 0xDF, 0xFB, 0xFF, 0xFF, 0xBF, 0xFC, 0xFF,
0xFE, 0x7F, 0xFF, 0x7F, 0xFD, 0xFF, 0xFF, 0x87, 0xC3, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF};
BYTE LtRtIconData[] = {0x28, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00,
0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00,
0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x88, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x88,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x00,
0x00, 0x88, 0x80, 0x00, 0x08, 0x88, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x88, 0x00, 0x08, 0x88, 0x88, 0x00,
0x08, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88,
0x88, 0x00, 0x00, 0x88, 0x80, 0x00, 0x08, 0x88, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x08,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0x87, 0xC3, 0xFF, 0xFF, 0x7F,
0xFD, 0xFF, 0xFC, 0xFF, 0xFE, 0x7F, 0xFB, 0xFF, 0xFF, 0xBF,
0xF7, 0xFF, 0xFF, 0xDF, 0xEF, 0xFF, 0xFF, 0xEF, 0xEF, 0xFF,
0xFF, 0xEF, 0xDF, 0xFF, 0xFF, 0xF7, 0xBF, 0xFF, 0xFF, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xBF, 0xFB, 0xFB, 0xBF, 0x3F,
0xF9, 0xFB, 0x7E, 0x3E, 0xF8, 0xFD, 0x7C, 0x3C, 0x78, 0x7D,
0x78, 0x38, 0x38, 0x3D, 0x7C, 0x3C, 0x78, 0x7D, 0x7E, 0x3E,
0xF8, 0xFD, 0xBF, 0x3F, 0xF9, 0xFB, 0xBF, 0xBF, 0xFB, 0xFB,
0xBF, 0xFF, 0xFF, 0xFB, 0xBF, 0xFF, 0xFF, 0xFB, 0xDF, 0xFF,
0xFF, 0xF7, 0xEF, 0xFF, 0xFF, 0xEF, 0xEF, 0xFF, 0xFF, 0xEF,
0xF7, 0xFF, 0xFF, 0xDF, 0xFB, 0xFF, 0xFF, 0xBF, 0xFC, 0xFF,
0xFE, 0x7F, 0xFF, 0x7F, 0xFD, 0xFF, 0xFF, 0x87, 0xC3, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF};
pData = m_Alignment == Vertical ? UpDnIconData : m_Alignment == Horizontal ? LtRtIconData : BothIconData;
VERIFY (m_hIcon = CreateIconFromResource(pData, 744, TRUE, 0x00030000));
BYTE BothCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x10,
0x10, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x40, 0x04, 0x00,
0x00, 0xBF, 0xFA, 0x00, 0x01, 0x40, 0x05, 0x00, 0x02, 0x40,
0x04, 0x80, 0x04, 0x41, 0x04, 0x40, 0x08, 0x42, 0x84, 0x20,
0x10, 0x44, 0x44, 0x10, 0x20, 0x48, 0x24, 0x08, 0x10, 0x44,
0x44, 0x10, 0x08, 0x42, 0x84, 0x20, 0x04, 0x41, 0x04, 0x40,
0x02, 0x40, 0x04, 0x80, 0x01, 0x40, 0x05, 0x00, 0x00, 0xBF,
0xFA, 0x00, 0x00, 0x40, 0x04, 0x00, 0x00, 0x20, 0x08, 0x00,
0x00, 0x10, 0x10, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xE0,
0x0F, 0xFF, 0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0x80, 0x03, 0xFF,
0xFF, 0x40, 0x05, 0xFF, 0xFE, 0x3F, 0xF8, 0xFF, 0xFC, 0x3F,
0xF8, 0x7F, 0xF8, 0x3E, 0xF8, 0x3F, 0xF0, 0x3C, 0x78, 0x1F,
0xE0, 0x38, 0x38, 0x0F, 0xC0, 0x30, 0x18, 0x07, 0xE0, 0x38,
0x38, 0x0F, 0xF0, 0x3C, 0x78, 0x1F, 0xF8, 0x3E, 0xF8, 0x3F,
0xFC, 0x3F, 0xF8, 0x7F, 0xFE, 0x3F, 0xF8, 0xFF, 0xFF, 0x40,
0x05, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xC0, 0x07, 0xFF,
0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
BYTE UpDnCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x10,
0x10, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x40, 0x04, 0x00,
0x00, 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F,
0xF8, 0x00, 0x00, 0x40, 0x04, 0x00, 0x00, 0x20, 0x08, 0x00,
0x00, 0x10, 0x10, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xE0,
0x0F, 0xFF, 0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0x80, 0x03, 0xFF,
0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xC0, 0x07, 0xFF,
0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
BYTE LtRtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x02, 0x00, 0x01, 0x40, 0x05, 0x00, 0x02, 0x40,
0x04, 0x80, 0x04, 0x41, 0x04, 0x40, 0x08, 0x42, 0x84, 0x20,
0x10, 0x44, 0x44, 0x10, 0x20, 0x48, 0x24, 0x08, 0x10, 0x44,
0x44, 0x10, 0x08, 0x42, 0x84, 0x20, 0x04, 0x41, 0x04, 0x40,
0x02, 0x40, 0x04, 0x80, 0x01, 0x40, 0x05, 0x00, 0x00, 0x80,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x7F, 0xFD, 0xFF, 0xFE, 0x3F, 0xF8, 0xFF, 0xFC, 0x3F,
0xF8, 0x7F, 0xF8, 0x3E, 0xF8, 0x3F, 0xF0, 0x3C, 0x78, 0x1F,
0xE0, 0x38, 0x38, 0x0F, 0xC0, 0x30, 0x18, 0x07, 0xE0, 0x38,
0x38, 0x0F, 0xF0, 0x3C, 0x78, 0x1F, 0xF8, 0x3E, 0xF8, 0x3F,
0xFC, 0x3F, 0xF8, 0x7F, 0xFE, 0x3F, 0xF8, 0xFF, 0xFF, 0x7F,
0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
pData = m_Alignment == Vertical ? UpDnCursorData : m_Alignment == Horizontal ? LtRtCursorData : BothCursorData;
VERIFY (m_NeutralCursor = CreateCursor (hInst, 15, 15, 32, 32, pData + 128, pData));
if (m_Alignment & Vertical)
{
BYTE UpCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x10,
0x10, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x40, 0x04, 0x00,
0x00, 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xE0,
0x0F, 0xFF, 0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0x80, 0x03, 0xFF,
0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_UpCursor = CreateCursor(hInst, 15, 15, 32, 32, UpCursorData + 128, UpCursorData));
BYTE DnCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F,
0xF8, 0x00, 0x00, 0x40, 0x04, 0x00, 0x00, 0x20, 0x08, 0x00,
0x00, 0x10, 0x10, 0x00, 0x00, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xC0, 0x07, 0xFF,
0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_DownCursor = CreateCursor(hInst, 15, 15, 32, 32, DnCursorData + 128, DnCursorData));
}
if (m_Alignment & Horizontal)
{
BYTE LtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x02, 0x40,
0x00, 0x00, 0x04, 0x41, 0x00, 0x00, 0x08, 0x42, 0x80, 0x00,
0x10, 0x44, 0x40, 0x00, 0x20, 0x48, 0x20, 0x00, 0x10, 0x44,
0x40, 0x00, 0x08, 0x42, 0x80, 0x00, 0x04, 0x41, 0x00, 0x00,
0x02, 0x40, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x7F, 0xFF, 0xFF, 0xFE, 0x3F, 0xFF, 0xFF, 0xFC, 0x3F,
0xFF, 0xFF, 0xF8, 0x3E, 0xFF, 0xFF, 0xF0, 0x3C, 0x7F, 0xFF,
0xE0, 0x38, 0x3F, 0xFF, 0xC0, 0x30, 0x1F, 0xFF, 0xE0, 0x38,
0x3F, 0xFF, 0xF0, 0x3C, 0x7F, 0xFF, 0xF8, 0x3E, 0xFF, 0xFF,
0xFC, 0x3F, 0xFF, 0xFF, 0xFE, 0x3F, 0xFF, 0xFF, 0xFF, 0x7F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_LeftCursor = CreateCursor(hInst, 15, 15, 32, 32, LtCursorData + 128, LtCursorData));
BYTE RtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
0x04, 0x80, 0x00, 0x01, 0x04, 0x40, 0x00, 0x02, 0x84, 0x20,
0x00, 0x04, 0x44, 0x10, 0x00, 0x08, 0x24, 0x08, 0x00, 0x04,
0x44, 0x10, 0x00, 0x02, 0x84, 0x20, 0x00, 0x01, 0x04, 0x40,
0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFD, 0xFF, 0xFF, 0xFF, 0xF8, 0xFF, 0xFF, 0xFF,
0xF8, 0x7F, 0xFF, 0xFE, 0xF8, 0x3F, 0xFF, 0xFC, 0x78, 0x1F,
0xFF, 0xF8, 0x38, 0x0F, 0xFF, 0xF0, 0x18, 0x07, 0xFF, 0xF8,
0x38, 0x0F, 0xFF, 0xFC, 0x78, 0x1F, 0xFF, 0xFE, 0xF8, 0x3F,
0xFF, 0xFF, 0xF8, 0x7F, 0xFF, 0xFF, 0xF8, 0xFF, 0xFF, 0xFF,
0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_RightCursor = CreateCursor(hInst, 15, 15, 32, 32, RtCursorData + 128, RtCursorData));
}
if (m_Alignment == Both)
{
BYTE UpLtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFE,
0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00,
0x02, 0x04, 0x00, 0x00, 0x02, 0x08, 0x00, 0x00, 0x02, 0x10,
0x00, 0x00, 0x02, 0x21, 0x00, 0x00, 0x02, 0x42, 0x80, 0x00,
0x02, 0x84, 0x40, 0x00, 0x01, 0x08, 0x20, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x01,
0xFF, 0xFF, 0xFC, 0x00, 0xFF, 0xFF, 0xFC, 0x01, 0xFF, 0xFF,
0xFC, 0x03, 0xFF, 0xFF, 0xFC, 0x07, 0xFF, 0xFF, 0xFC, 0x0F,
0xFF, 0xFF, 0xFC, 0x1E, 0xFF, 0xFF, 0xFC, 0x3C, 0x7F, 0xFF,
0xFC, 0x78, 0x3F, 0xFF, 0xFE, 0xF0, 0x1F, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_UpLeftCursor = CreateCursor(hInst, 15, 15, 32, 32, UpLtCursorData + 128, UpLtCursorData));
BYTE UpRtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x80, 0x80,
0x00, 0x00, 0x40, 0x80, 0x00, 0x00, 0x20, 0x80, 0x00, 0x00,
0x10, 0x80, 0x00, 0x01, 0x08, 0x80, 0x00, 0x02, 0x84, 0x80,
0x00, 0x04, 0x42, 0x80, 0x00, 0x08, 0x21, 0x00, 0x00, 0x04,
0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0xFF, 0xFF, 0xFE, 0x00, 0x7F, 0xFF, 0xFF, 0x00, 0x7F,
0xFF, 0xFF, 0x80, 0x7F, 0xFF, 0xFF, 0xC0, 0x7F, 0xFF, 0xFF,
0xE0, 0x7F, 0xFF, 0xFE, 0xF0, 0x7F, 0xFF, 0xFC, 0x78, 0x7F,
0xFF, 0xF8, 0x3C, 0x7F, 0xFF, 0xF0, 0x1E, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_UpRightCursor = CreateCursor(hInst, 15, 15, 32, 32, UpRtCursorData + 128, UpRtCursorData));
BYTE DnRtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x00, 0x08, 0x21, 0x00, 0x00, 0x04,
0x42, 0x80, 0x00, 0x02, 0x84, 0x80, 0x00, 0x01, 0x08, 0x80,
0x00, 0x00, 0x10, 0x80, 0x00, 0x00, 0x20, 0x80, 0x00, 0x00,
0x40, 0x80, 0x00, 0x00, 0x80, 0x80, 0x00, 0x01, 0x00, 0x80,
0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0, 0x1E, 0xFF, 0xFF, 0xF8,
0x3C, 0x7F, 0xFF, 0xFC, 0x78, 0x7F, 0xFF, 0xFE, 0xF0, 0x7F,
0xFF, 0xFF, 0xE0, 0x7F, 0xFF, 0xFF, 0xC0, 0x7F, 0xFF, 0xFF,
0x80, 0x7F, 0xFF, 0xFF, 0x00, 0x7F, 0xFF, 0xFE, 0x00, 0x7F,
0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_DownRightCursor = CreateCursor(hInst, 15, 15, 32, 32, DnRtCursorData + 128, DnRtCursorData));
BYTE DnLtCursorData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00,
0x00, 0x04, 0x40, 0x00, 0x01, 0x08, 0x20, 0x00, 0x02, 0x84,
0x40, 0x00, 0x02, 0x42, 0x80, 0x00, 0x02, 0x21, 0x00, 0x00,
0x02, 0x10, 0x00, 0x00, 0x02, 0x08, 0x00, 0x00, 0x02, 0x04,
0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00,
0x01, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF,
0xFF, 0xF8, 0x3F, 0xFF, 0xFE, 0xF0, 0x1F, 0xFF, 0xFC, 0x78,
0x3F, 0xFF, 0xFC, 0x3C, 0x7F, 0xFF, 0xFC, 0x1E, 0xFF, 0xFF,
0xFC, 0x0F, 0xFF, 0xFF, 0xFC, 0x07, 0xFF, 0xFF, 0xFC, 0x03,
0xFF, 0xFF, 0xFC, 0x01, 0xFF, 0xFF, 0xFC, 0x00, 0xFF, 0xFF,
0xFE, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
VERIFY (m_DownLeftCursor = CreateCursor(hInst, 15, 15, 32, 32, DnLtCursorData + 128, DnLtCursorData));
}
}
#pragma warning (pop)
| [
"thewolfmanu@8d742ff4-5afa-cc76-88a1-f39302f5df42"
] | [
[
[
1,
1424
]
]
] |
931229e9663be8d6accbc9105197a405b161dfcc | 521c910cca3061976a7010c1f395f1e1afb66906 | /CSC205/machine/disk.h | fd3a80c4f748c4058018c210d074265759d66126 | [] | no_license | nsl92/NTUSCE | 31eab19f0337b68a596b19262db55b5ff9a0fffc | b99618df03e9435b4a87775346609c97739e165d | refs/heads/master | 2021-01-19T00:44:34.804409 | 2011-09-11T16:33:36 | 2011-09-11T16:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,008 | h | // disk.h
// Data structures to emulate a physical disk. A physical disk
// can accept (one at a time) requests to read/write a disk sector;
// when the request is satisfied, the CPU gets an interrupt, and
// the next request can be sent to the disk.
//
// Disk contents are preserved across machine crashes, but if
// a file system operation (eg, create a file) is in progress when the
// system shuts down, the file system may be corrupted.
//
// DO NOT CHANGE -- part of the machine emulation
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#ifndef DISK_H
#define DISK_H
#include "copyright.h"
#include "utility.h"
// The following class defines a physical disk I/O device. The disk
// has a single surface, split up into "tracks", and each track split
// up into "sectors" (the same number of sectors on each track, and each
// sector has the same number of bytes of storage).
//
// Addressing is by sector number -- each sector on the disk is given
// a unique number: track * SectorsPerTrack + offset within a track.
//
// As with other I/O devices, the raw physical disk is an asynchronous device --
// requests to read or write portions of the disk return immediately,
// and an interrupt is invoked later to signal that the operation completed.
//
// The physical disk is in fact simulated via operations on a UNIX file.
//
// To make life a little more realistic, the simulated time for
// each operation reflects a "track buffer" -- RAM to store the contents
// of the current track as the disk head passes by. The idea is that the
// disk always transfers to the track buffer, in case that data is requested
// later on. This has the benefit of eliminating the need for
// "skip-sector" scheduling -- a read request which comes in shortly after
// the head has passed the beginning of the sector can be satisfied more
// quickly, because its contents are in the track buffer. Most
// disks these days now come with a track buffer.
//
// The track buffer simulation can be disabled by compiling with -DNOTRACKBUF
#define SectorSize 128 // number of bytes per disk sector
#define SectorsPerTrack 32 // number of sectors per disk track
#define NumTracks 32 // number of tracks per disk
#define NumSectors (SectorsPerTrack * NumTracks)
// total # of sectors per disk
class Disk {
public:
Disk(char* name, VoidFunctionPtr callWhenDone, _int callArg);
// Create a simulated disk.
// Invoke (*callWhenDone)(callArg)
// every time a request completes.
~Disk(); // Deallocate the disk.
void ReadRequest(int sectorNumber, char* data);
// Read/write an single disk sector.
// These routines send a request to
// the disk and return immediately.
// Only one request allowed at a time!
void WriteRequest(int sectorNumber, char* data);
void HandleInterrupt(); // Interrupt handler, invoked when
// disk request finishes.
int ComputeLatency(int newSector, bool writing);
// Return how long a request to
// newSector will take:
// (seek + rotational delay + transfer)
private:
int fileno; // UNIX file number for simulated disk
VoidFunctionPtr handler; // Interrupt handler, to be invoked
// when any disk request finishes
_int handlerArg; // Argument to interrupt handler
bool active; // Is a disk operation in progress?
int lastSector; // The previous disk request
int bufferInit; // When the track buffer started
// being loaded
int TimeToSeek(int newSector, int *rotate); // time to get to the new track
int ModuloDiff(int to, int from); // # sectors between to and from
void UpdateLast(int newSector);
};
#endif // DISK_H
| [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
fd45f471f58aa0562b87521dffdd28ef8bf47209 | c54f5a7cf6de3ed02d2e02cf867470ea48bd9258 | /pyobjc/PyOpenGL-2.0.2.01/src/interface/WGL.EXT._extensions_string.0100.inc | d3ba4782e0febbd95288ba86ec400b60d15a32cd | [] | no_license | orestis/pyobjc | 01ad0e731fbbe0413c2f5ac2f3e91016749146c6 | c30bf50ba29cb562d530e71a9d6c3d8ad75aa230 | refs/heads/master | 2021-01-22T06:54:35.401551 | 2009-09-01T09:24:47 | 2009-09-01T09:24:47 | 16,895 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 54,889 | inc | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.23
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGPYTHON
#ifndef SWIG_TEMPLATE_DISAMBIGUATOR
# if defined(__SUNPRO_CC)
# define SWIG_TEMPLATE_DISAMBIGUATOR template
# else
# define SWIG_TEMPLATE_DISAMBIGUATOR
# endif
#endif
#include <Python.h>
/***********************************************************************
* common.swg
*
* This file contains generic SWIG runtime support for pointer
* type checking as well as a few commonly used macros to control
* external linkage.
*
* Author : David Beazley ([email protected])
*
* Copyright (c) 1999-2000, The University of Chicago
*
* This file may be freely redistributed without license or fee provided
* this copyright message remains intact.
************************************************************************/
#include <string.h>
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if !defined(STATIC_LINKED)
# define SWIGEXPORT(a) __declspec(dllexport) a
# else
# define SWIGEXPORT(a) a
# endif
#else
# define SWIGEXPORT(a) a
#endif
#define SWIGRUNTIME(x) static x
#ifndef SWIGINLINE
#if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
#else
# define SWIGINLINE
#endif
#endif
/* This should only be incremented when either the layout of swig_type_info changes,
or for whatever reason, the runtime changes incompatibly */
#define SWIG_RUNTIME_VERSION "1"
/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
#ifdef SWIG_TYPE_TABLE
#define SWIG_QUOTE_STRING(x) #x
#define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
#define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
#else
#define SWIG_TYPE_TABLE_NAME
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*swig_converter_func)(void *);
typedef struct swig_type_info *(*swig_dycast_func)(void **);
typedef struct swig_type_info {
const char *name;
swig_converter_func converter;
const char *str;
void *clientdata;
swig_dycast_func dcast;
struct swig_type_info *next;
struct swig_type_info *prev;
} swig_type_info;
static swig_type_info *swig_type_list = 0;
static swig_type_info **swig_type_list_handle = &swig_type_list;
/*
Compare two type names skipping the space characters, therefore
"char*" == "char *" and "Class<int>" == "Class<int >", etc.
Return 0 when the two name types are equivalent, as in
strncmp, but skipping ' '.
*/
static int
SWIG_TypeNameComp(const char *f1, const char *l1,
const char *f2, const char *l2) {
for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
while ((*f1 == ' ') && (f1 != l1)) ++f1;
while ((*f2 == ' ') && (f2 != l2)) ++f2;
if (*f1 != *f2) return *f1 - *f2;
}
return (l1 - f1) - (l2 - f2);
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
*/
static int
SWIG_TypeEquiv(const char *nb, const char *tb) {
int equiv = 0;
const char* te = tb + strlen(tb);
const char* ne = nb;
while (!equiv && *ne) {
for (nb = ne; *ne; ++ne) {
if (*ne == '|') break;
}
equiv = SWIG_TypeNameComp(nb, ne, tb, te) == 0;
if (*ne) ++ne;
}
return equiv;
}
/* Register a type mapping with the type-checking */
static swig_type_info *
SWIG_TypeRegister(swig_type_info *ti) {
swig_type_info *tc, *head, *ret, *next;
/* Check to see if this type has already been registered */
tc = *swig_type_list_handle;
while (tc) {
/* check simple type equivalence */
int typeequiv = (strcmp(tc->name, ti->name) == 0);
/* check full type equivalence, resolving typedefs */
if (!typeequiv) {
/* only if tc is not a typedef (no '|' on it) */
if (tc->str && ti->str && !strstr(tc->str,"|")) {
typeequiv = SWIG_TypeEquiv(ti->str,tc->str);
}
}
if (typeequiv) {
/* Already exists in the table. Just add additional types to the list */
if (ti->clientdata) tc->clientdata = ti->clientdata;
head = tc;
next = tc->next;
goto l1;
}
tc = tc->prev;
}
head = ti;
next = 0;
/* Place in list */
ti->prev = *swig_type_list_handle;
*swig_type_list_handle = ti;
/* Build linked lists */
l1:
ret = head;
tc = ti + 1;
/* Patch up the rest of the links */
while (tc->name) {
head->next = tc;
tc->prev = head;
head = tc;
tc++;
}
if (next) next->prev = head;
head->next = next;
return ret;
}
/* Check the typename */
static swig_type_info *
SWIG_TypeCheck(char *c, swig_type_info *ty) {
swig_type_info *s;
if (!ty) return 0; /* Void pointer */
s = ty->next; /* First element always just a name */
do {
if (strcmp(s->name,c) == 0) {
if (s == ty->next) return s;
/* Move s to the top of the linked list */
s->prev->next = s->next;
if (s->next) {
s->next->prev = s->prev;
}
/* Insert s as second element in the list */
s->next = ty->next;
if (ty->next) ty->next->prev = s;
ty->next = s;
s->prev = ty;
return s;
}
s = s->next;
} while (s && (s != ty->next));
return 0;
}
/* Cast a pointer up an inheritance hierarchy */
static SWIGINLINE void *
SWIG_TypeCast(swig_type_info *ty, void *ptr) {
if ((!ty) || (!ty->converter)) return ptr;
return (*ty->converter)(ptr);
}
/* Dynamic pointer casting. Down an inheritance hierarchy */
static swig_type_info *
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
swig_type_info *lastty = ty;
if (!ty || !ty->dcast) return ty;
while (ty && (ty->dcast)) {
ty = (*ty->dcast)(ptr);
if (ty) lastty = ty;
}
return lastty;
}
/* Return the name associated with this type */
static SWIGINLINE const char *
SWIG_TypeName(const swig_type_info *ty) {
return ty->name;
}
/* Return the pretty name associated with this type,
that is an unmangled type name in a form presentable to the user.
*/
static const char *
SWIG_TypePrettyName(const swig_type_info *type) {
/* The "str" field contains the equivalent pretty names of the
type, separated by vertical-bar characters. We choose
to print the last name, as it is often (?) the most
specific. */
if (type->str != NULL) {
const char *last_name = type->str;
const char *s;
for (s = type->str; *s; s++)
if (*s == '|') last_name = s+1;
return last_name;
}
else
return type->name;
}
/* Search for a swig_type_info structure */
static swig_type_info *
SWIG_TypeQuery(const char *name) {
swig_type_info *ty = *swig_type_list_handle;
while (ty) {
if (ty->str && (SWIG_TypeEquiv(ty->str,name))) return ty;
if (ty->name && (strcmp(name,ty->name) == 0)) return ty;
ty = ty->prev;
}
return 0;
}
/* Set the clientdata field for a type */
static void
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
swig_type_info *tc, *equiv;
if (ti->clientdata) return;
/* if (ti->clientdata == clientdata) return; */
ti->clientdata = clientdata;
equiv = ti->next;
while (equiv) {
if (!equiv->converter) {
tc = *swig_type_list_handle;
while (tc) {
if ((strcmp(tc->name, equiv->name) == 0))
SWIG_TypeClientData(tc,clientdata);
tc = tc->prev;
}
}
equiv = equiv->next;
}
}
/* Pack binary data into a string */
static char *
SWIG_PackData(char *c, void *ptr, size_t sz) {
static char hex[17] = "0123456789abcdef";
unsigned char *u = (unsigned char *) ptr;
const unsigned char *eu = u + sz;
register unsigned char uu;
for (; u != eu; ++u) {
uu = *u;
*(c++) = hex[(uu & 0xf0) >> 4];
*(c++) = hex[uu & 0xf];
}
return c;
}
/* Unpack binary data from a string */
static char *
SWIG_UnpackData(char *c, void *ptr, size_t sz) {
register unsigned char uu = 0;
register int d;
unsigned char *u = (unsigned char *) ptr;
const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu = ((d - '0') << 4);
else if ((d >= 'a') && (d <= 'f'))
uu = ((d - ('a'-10)) << 4);
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu |= (d - '0');
else if ((d >= 'a') && (d <= 'f'))
uu |= (d - ('a'-10));
*u = uu;
}
return c;
}
/* This function will propagate the clientdata field of type to
* any new swig_type_info structures that have been added into the list
* of equivalent types. It is like calling
* SWIG_TypeClientData(type, clientdata) a second time.
*/
static void
SWIG_PropagateClientData(swig_type_info *type) {
swig_type_info *equiv = type->next;
swig_type_info *tc;
if (!type->clientdata) return;
while (equiv) {
if (!equiv->converter) {
tc = *swig_type_list_handle;
while (tc) {
if ((strcmp(tc->name, equiv->name) == 0) && !tc->clientdata)
SWIG_TypeClientData(tc, type->clientdata);
tc = tc->prev;
}
}
equiv = equiv->next;
}
}
#ifdef __cplusplus
}
#endif
/* -----------------------------------------------------------------------------
* SWIG API. Portion that goes into the runtime
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#endif
/* -----------------------------------------------------------------------------
* for internal method declarations
* ----------------------------------------------------------------------------- */
#ifndef SWIGINTERN
#define SWIGINTERN static
#endif
#ifndef SWIGINTERNSHORT
#ifdef __cplusplus
#define SWIGINTERNSHORT static inline
#else /* C case */
#define SWIGINTERNSHORT static
#endif /* __cplusplus */
#endif
/* Common SWIG API */
#define SWIG_ConvertPtr(obj, pp, type, flags) SWIG_Python_ConvertPtr(obj, pp, type, flags)
#define SWIG_NewPointerObj(p, type, flags) SWIG_Python_NewPointerObj(p, type, flags)
#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags)
/* Python-specific SWIG API */
#define SWIG_newvarlink() SWIG_Python_newvarlink()
#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr)
#define SWIG_ConvertPacked(obj, ptr, sz, ty, flags) SWIG_Python_ConvertPacked(obj, ptr, sz, ty, flags)
#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type)
#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants)
/*
Exception handling in wrappers
*/
#define SWIG_fail goto fail
#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg)
#define SWIG_append_errmsg(msg) SWIG_Python_AddErrMesg(msg,0)
#define SWIG_preppend_errmsg(msg) SWIG_Python_AddErrMesg(msg,1)
#define SWIG_type_error(type,obj) SWIG_Python_TypeError(type,obj)
#define SWIG_null_ref(type) SWIG_Python_NullRef(type)
/*
Contract support
*/
#define SWIG_contract_assert(expr, msg) \
if (!(expr)) { PyErr_SetString(PyExc_RuntimeError, (char *) msg ); goto fail; } else
/* -----------------------------------------------------------------------------
* Constant declarations
* ----------------------------------------------------------------------------- */
/* Constant Types */
#define SWIG_PY_INT 1
#define SWIG_PY_FLOAT 2
#define SWIG_PY_STRING 3
#define SWIG_PY_POINTER 4
#define SWIG_PY_BINARY 5
/* Constant information structure */
typedef struct swig_const_info {
int type;
char *name;
long lvalue;
double dvalue;
void *pvalue;
swig_type_info **ptype;
} swig_const_info;
/* -----------------------------------------------------------------------------
* Pointer declarations
* ----------------------------------------------------------------------------- */
/*
Use SWIG_NO_COBJECT_TYPES to force the use of strings to represent
C/C++ pointers in the python side. Very useful for debugging, but
not always safe.
*/
#if !defined(SWIG_NO_COBJECT_TYPES) && !defined(SWIG_COBJECT_TYPES)
# define SWIG_COBJECT_TYPES
#endif
/* Flags for pointer conversion */
#define SWIG_POINTER_EXCEPTION 0x1
#define SWIG_POINTER_DISOWN 0x2
/* -----------------------------------------------------------------------------
* Alloc. memory flags
* ----------------------------------------------------------------------------- */
#define SWIG_OLDOBJ 1
#define SWIG_NEWOBJ SWIG_OLDOBJ + 1
#define SWIG_PYSTR SWIG_NEWOBJ + 1
#ifdef __cplusplus
}
#endif
/***********************************************************************
* pyrun.swg
*
* This file contains the runtime support for Python modules
* and includes code for managing global variables and pointer
* type checking.
*
* Author : David Beazley ([email protected])
************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
/* -----------------------------------------------------------------------------
* global variable support code.
* ----------------------------------------------------------------------------- */
typedef struct swig_globalvar {
char *name; /* Name of global variable */
PyObject *(*get_attr)(); /* Return the current value */
int (*set_attr)(PyObject *); /* Set the value */
struct swig_globalvar *next;
} swig_globalvar;
typedef struct swig_varlinkobject {
PyObject_HEAD
swig_globalvar *vars;
} swig_varlinkobject;
static PyObject *
swig_varlink_repr(swig_varlinkobject *v) {
v = v;
return PyString_FromString("<Global variables>");
}
static int
swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) {
swig_globalvar *var;
flags = flags;
fprintf(fp,"Global variables { ");
for (var = v->vars; var; var=var->next) {
fprintf(fp,"%s", var->name);
if (var->next) fprintf(fp,", ");
}
fprintf(fp," }\n");
return 0;
}
static PyObject *
swig_varlink_getattr(swig_varlinkobject *v, char *n) {
swig_globalvar *var = v->vars;
while (var) {
if (strcmp(var->name,n) == 0) {
return (*var->get_attr)();
}
var = var->next;
}
PyErr_SetString(PyExc_NameError,"Unknown C global variable");
return NULL;
}
static int
swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
swig_globalvar *var = v->vars;
while (var) {
if (strcmp(var->name,n) == 0) {
return (*var->set_attr)(p);
}
var = var->next;
}
PyErr_SetString(PyExc_NameError,"Unknown C global variable");
return 1;
}
static PyTypeObject varlinktype = {
PyObject_HEAD_INIT(0)
0, /* Number of items in variable part (ob_size) */
(char *)"swigvarlink", /* Type name (tp_name) */
sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */
0, /* Itemsize (tp_itemsize) */
0, /* Deallocator (tp_dealloc) */
(printfunc) swig_varlink_print, /* Print (tp_print) */
(getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */
(setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */
0, /* tp_compare */
(reprfunc) swig_varlink_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
#if PY_VERSION_HEX >= 0x02020000
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
#endif
#if PY_VERSION_HEX >= 0x02030000
0, /* tp_del */
#endif
#ifdef COUNT_ALLOCS
/* these must be last */
0, /* tp_alloc */
0, /* tp_free */
0, /* tp_maxalloc */
0, /* tp_next */
#endif
};
/* Create a variable linking object for use later */
static PyObject *
SWIG_Python_newvarlink(void) {
swig_varlinkobject *result = 0;
result = PyMem_NEW(swig_varlinkobject,1);
varlinktype.ob_type = &PyType_Type; /* Patch varlinktype into a PyType */
result->ob_type = &varlinktype;
result->vars = 0;
result->ob_refcnt = 0;
Py_XINCREF((PyObject *) result);
return ((PyObject*) result);
}
static void
SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
swig_varlinkobject *v;
swig_globalvar *gv;
v= (swig_varlinkobject *) p;
gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
gv->name = (char *) malloc(strlen(name)+1);
strcpy(gv->name,name);
gv->get_attr = get_attr;
gv->set_attr = set_attr;
gv->next = v->vars;
v->vars = gv;
}
/* -----------------------------------------------------------------------------
* errors manipulation
* ----------------------------------------------------------------------------- */
static void
SWIG_Python_TypeError(const char *type, PyObject *obj)
{
if (type) {
if (!PyCObject_Check(obj)) {
const char *otype = (obj ? obj->ob_type->tp_name : 0);
if (otype) {
PyObject *str = PyObject_Str(obj);
const char *cstr = str ? PyString_AsString(str) : 0;
if (cstr) {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
type, otype, cstr);
} else {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
type, otype);
}
Py_DECREF(str);
return;
}
} else {
const char *otype = (char *) PyCObject_GetDesc(obj);
if (otype) {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PyCObject(%s)' is received",
type, otype);
return;
}
}
PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
} else {
PyErr_Format(PyExc_TypeError, "unexpected type is received");
}
}
static SWIGINLINE void
SWIG_Python_NullRef(const char *type)
{
if (type) {
PyErr_Format(PyExc_TypeError, "null reference of type '%s' was received",type);
} else {
PyErr_Format(PyExc_TypeError, "null reference was received");
}
}
static int
SWIG_Python_AddErrMesg(const char* mesg, int infront)
{
if (PyErr_Occurred()) {
PyObject *type = 0;
PyObject *value = 0;
PyObject *traceback = 0;
PyErr_Fetch(&type, &value, &traceback);
if (value) {
PyObject *old_str = PyObject_Str(value);
Py_XINCREF(type);
PyErr_Clear();
if (infront) {
PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
} else {
PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
}
Py_DECREF(old_str);
}
return 1;
} else {
return 0;
}
}
static int
SWIG_Python_ArgFail(int argnum)
{
if (PyErr_Occurred()) {
/* add information about failing argument */
char mesg[256];
sprintf(mesg, "argument number %d:", argnum);
return SWIG_Python_AddErrMesg(mesg, 1);
} else {
return 0;
}
}
/* -----------------------------------------------------------------------------
* pointers/data manipulation
* ----------------------------------------------------------------------------- */
/* Convert a pointer value */
static int
SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
swig_type_info *tc;
char *c = 0;
static PyObject *SWIG_this = 0;
int newref = 0;
PyObject *pyobj = 0;
void *vptr;
if (!obj) return 0;
if (obj == Py_None) {
*ptr = 0;
return 0;
}
#ifdef SWIG_COBJECT_TYPES
if (!(PyCObject_Check(obj))) {
if (!SWIG_this)
SWIG_this = PyString_FromString("this");
pyobj = obj;
obj = PyObject_GetAttr(obj,SWIG_this);
newref = 1;
if (!obj) goto type_error;
if (!PyCObject_Check(obj)) {
Py_DECREF(obj);
goto type_error;
}
}
vptr = PyCObject_AsVoidPtr(obj);
c = (char *) PyCObject_GetDesc(obj);
if (newref) Py_DECREF(obj);
goto type_check;
#else
if (!(PyString_Check(obj))) {
if (!SWIG_this)
SWIG_this = PyString_FromString("this");
pyobj = obj;
obj = PyObject_GetAttr(obj,SWIG_this);
newref = 1;
if (!obj) goto type_error;
if (!PyString_Check(obj)) {
Py_DECREF(obj);
goto type_error;
}
}
c = PyString_AS_STRING(obj);
/* Pointer values must start with leading underscore */
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
if (newref) { Py_DECREF(obj); }
*ptr = (void *) 0;
return 0;
} else {
if (newref) { Py_DECREF(obj); }
goto type_error;
}
}
c++;
c = SWIG_UnpackData(c,&vptr,sizeof(void *));
if (newref) { Py_DECREF(obj); }
#endif
type_check:
if (ty) {
tc = SWIG_TypeCheck(c,ty);
if (!tc) goto type_error;
*ptr = SWIG_TypeCast(tc,vptr);
}
if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
PyObject_SetAttrString(pyobj,(char*)"thisown",Py_False);
}
return 0;
type_error:
PyErr_Clear();
if (pyobj && !obj) {
obj = pyobj;
if (PyCFunction_Check(obj)) {
/* here we get the method pointer for callbacks */
char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
c = doc ? strstr(doc, "swig_ptr: ") : 0;
if (c) {
c += 10;
if (*c == '_') {
c++;
c = SWIG_UnpackData(c,&vptr,sizeof(void *));
goto type_check;
}
}
}
}
if (flags & SWIG_POINTER_EXCEPTION) {
if (ty) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
} else {
SWIG_Python_TypeError("C/C++ pointer", obj);
}
}
return -1;
}
/* Convert a pointer value, signal an exception on a type mismatch */
static void *
SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
void *result;
if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
PyErr_Clear();
if (flags & SWIG_POINTER_EXCEPTION) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
SWIG_Python_ArgFail(argnum);
}
}
return result;
}
/* Convert a packed value value */
static int
SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty, int flags) {
swig_type_info *tc;
char *c = 0;
if ((!obj) || (!PyString_Check(obj))) goto type_error;
c = PyString_AS_STRING(obj);
/* Pointer values must start with leading underscore */
if (*c != '_') goto type_error;
c++;
c = SWIG_UnpackData(c,ptr,sz);
if (ty) {
tc = SWIG_TypeCheck(c,ty);
if (!tc) goto type_error;
}
return 0;
type_error:
PyErr_Clear();
if (flags & SWIG_POINTER_EXCEPTION) {
if (ty) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
} else {
SWIG_Python_TypeError("C/C++ packed data", obj);
}
}
return -1;
}
/* Create a new pointer string */
static char *
SWIG_Python_PointerStr(char *buff, void *ptr, const char *name, size_t bsz) {
char *r = buff;
if ((2*sizeof(void *) + 2) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,&ptr,sizeof(void *));
if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
strcpy(r,name);
return buff;
}
/* Create a new pointer object */
static PyObject *
SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int own) {
PyObject *robj;
if (!ptr) {
Py_INCREF(Py_None);
return Py_None;
}
#ifdef SWIG_COBJECT_TYPES
robj = PyCObject_FromVoidPtrAndDesc((void *) ptr, (char *) type->name, NULL);
#else
{
char result[1024];
SWIG_Python_PointerStr(result, ptr, type->name, 1024);
robj = PyString_FromString(result);
}
#endif
if (!robj || (robj == Py_None)) return robj;
if (type->clientdata) {
PyObject *inst;
PyObject *args = Py_BuildValue((char*)"(O)", robj);
Py_DECREF(robj);
inst = PyObject_CallObject((PyObject *) type->clientdata, args);
Py_DECREF(args);
if (inst) {
if (own) {
PyObject_SetAttrString(inst,(char*)"thisown",Py_True);
}
robj = inst;
}
}
return robj;
}
static PyObject *
SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
char result[1024];
char *r = result;
if ((2*sz + 2 + strlen(type->name)) > 1024) return 0;
*(r++) = '_';
r = SWIG_PackData(r,ptr,sz);
strcpy(r,type->name);
return PyString_FromString(result);
}
/* -----------------------------------------------------------------------------
* constants/methods manipulation
* ----------------------------------------------------------------------------- */
/* Install Constants */
static void
SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
int i;
PyObject *obj;
for (i = 0; constants[i].type; i++) {
switch(constants[i].type) {
case SWIG_PY_INT:
obj = PyInt_FromLong(constants[i].lvalue);
break;
case SWIG_PY_FLOAT:
obj = PyFloat_FromDouble(constants[i].dvalue);
break;
case SWIG_PY_STRING:
if (constants[i].pvalue) {
obj = PyString_FromString((char *) constants[i].pvalue);
} else {
Py_INCREF(Py_None);
obj = Py_None;
}
break;
case SWIG_PY_POINTER:
obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
break;
case SWIG_PY_BINARY:
obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
break;
default:
obj = 0;
break;
}
if (obj) {
PyDict_SetItemString(d,constants[i].name,obj);
Py_DECREF(obj);
}
}
}
/* Fix SwigMethods to carry the callback ptrs when needed */
static void
SWIG_Python_FixMethods(PyMethodDef *methods,
swig_const_info *const_table,
swig_type_info **types,
swig_type_info **types_initial) {
int i;
for (i = 0; methods[i].ml_name; ++i) {
char *c = methods[i].ml_doc;
if (c && (c = strstr(c, "swig_ptr: "))) {
int j;
swig_const_info *ci = 0;
char *name = c + 10;
for (j = 0; const_table[j].type; j++) {
if (strncmp(const_table[j].name, name,
strlen(const_table[j].name)) == 0) {
ci = &(const_table[j]);
break;
}
}
if (ci) {
size_t shift = (ci->ptype) - types;
swig_type_info *ty = types_initial[shift];
size_t ldoc = (c - methods[i].ml_doc);
size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
char *ndoc = (char*)malloc(ldoc + lptr + 10);
char *buff = ndoc;
void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue: (void *)(ci->lvalue);
strncpy(buff, methods[i].ml_doc, ldoc);
buff += ldoc;
strncpy(buff, "swig_ptr: ", 10);
buff += 10;
SWIG_Python_PointerStr(buff, ptr, ty->name, lptr);
methods[i].ml_doc = ndoc;
}
}
}
}
/* -----------------------------------------------------------------------------
* Lookup type pointer
* ----------------------------------------------------------------------------- */
#if PY_MAJOR_VERSION < 2
/* PyModule_AddObject function was introduced in Python 2.0. The following function
is copied out of Python/modsupport.c in python version 2.3.4 */
static int
PyModule_AddObject(PyObject *m, char *name, PyObject *o)
{
PyObject *dict;
if (!PyModule_Check(m)) {
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs module as first arg");
return -1;
}
if (!o) {
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs non-NULL value");
return -1;
}
dict = PyModule_GetDict(m);
if (dict == NULL) {
/* Internal error -- modules must have a dict! */
PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
PyModule_GetName(m));
return -1;
}
if (PyDict_SetItemString(dict, name, o))
return -1;
Py_DECREF(o);
return 0;
}
#endif
static PyMethodDef swig_empty_runtime_method_table[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
static void
SWIG_Python_LookupTypePointer(swig_type_info ***type_list_handle) {
PyObject *module, *pointer;
void *type_pointer;
/* first check if module already created */
type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
if (type_pointer) {
*type_list_handle = (swig_type_info **) type_pointer;
} else {
PyErr_Clear();
/* create a new module and variable */
module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table);
pointer = PyCObject_FromVoidPtr((void *) (*type_list_handle), NULL);
if (pointer && module) {
PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
}
}
}
#ifdef __cplusplus
}
#endif
/* -------- TYPES TABLE (BEGIN) -------- */
#define SWIGTYPE_p_GLsizei swig_types[0]
#define SWIGTYPE_p_GLshort swig_types[1]
#define SWIGTYPE_p_GLboolean swig_types[2]
#define SWIGTYPE_p_BOOL swig_types[3]
#define SWIGTYPE_size_t swig_types[4]
#define SWIGTYPE_p_GLushort swig_types[5]
#define SWIGTYPE_p_GLenum swig_types[6]
#define SWIGTYPE_p_HGLRC swig_types[7]
#define SWIGTYPE_p_GLvoid swig_types[8]
#define SWIGTYPE_p_HDC swig_types[9]
#define SWIGTYPE_p_UINT swig_types[10]
#define SWIGTYPE_p_DOUBLE swig_types[11]
#define SWIGTYPE_p_COLORREF swig_types[12]
#define SWIGTYPE_p_GLint swig_types[13]
#define SWIGTYPE_p_WORD swig_types[14]
#define SWIGTYPE_p_BYTE swig_types[15]
#define SWIGTYPE_p_char swig_types[16]
#define SWIGTYPE_p_GLclampd swig_types[17]
#define SWIGTYPE_p_GLclampf swig_types[18]
#define SWIGTYPE_p_PROC swig_types[19]
#define SWIGTYPE_p_GLuint swig_types[20]
#define SWIGTYPE_p_HENHMETAFILE swig_types[21]
#define SWIGTYPE_p_DWORD swig_types[22]
#define SWIGTYPE_p_FLOAT swig_types[23]
#define SWIGTYPE_ptrdiff_t swig_types[24]
#define SWIGTYPE_p_GLbyte swig_types[25]
#define SWIGTYPE_p_VOID swig_types[26]
#define SWIGTYPE_p_GLbitfield swig_types[27]
#define SWIGTYPE_p_GLfloat swig_types[28]
#define SWIGTYPE_p_GLubyte swig_types[29]
#define SWIGTYPE_p_GLdouble swig_types[30]
static swig_type_info *swig_types[32];
/* -------- TYPES TABLE (END) -------- */
/*-----------------------------------------------
@(target):= _extensions_string.so
------------------------------------------------*/
#define SWIG_init init_extensions_string
#define SWIG_name "_extensions_string"
SWIGINTERN PyObject *
SWIG_FromCharPtr(const char* cptr)
{
if (cptr) {
size_t size = strlen(cptr);
if (size > INT_MAX) {
return SWIG_NewPointerObj((char*)(cptr),
SWIG_TypeQuery("char *"), 0);
} else {
if (size != 0) {
return PyString_FromStringAndSize(cptr, size);
} else {
return PyString_FromString(cptr);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
/*@C:\\bin\\SWIG-1.3.23\\Lib\\python\\pymacros.swg,66,SWIG_define@*/
#define SWIG_From_int PyInt_FromLong
/*@@*/
/**
*
* WGL.EXT.extensions_string Module for PyOpenGL
*
* Date: May 2001
*
* Authors: Tarn Weisner Burton <[email protected]>
*
***/
GLint PyOpenGL_round(double x) {
if (x >= 0) {
return (GLint) (x+0.5);
} else {
return (GLint) (x-0.5);
}
}
int __PyObject_AsArray_Size(PyObject* x);
#ifdef NUMERIC
#define _PyObject_AsArray_Size(x) ((x == Py_None) ? 0 : ((PyArray_Check(x)) ? PyArray_Size(x) : __PyObject_AsArray_Size(x)))
#else /* NUMERIC */
#define _PyObject_AsArray_Size(x) ((x == Py_None) ? 0 : __PyObject_AsArray_Size(x))
#endif /* NUMERIC */
#define _PyObject_As(NAME, BASE) BASE* _PyObject_As##NAME(PyObject* source, PyObject** temp, int* len);
#define _PyObject_AsArray_Cleanup(target, temp) if (temp) Py_XDECREF(temp); else PyMem_Del(target)
_PyObject_As(FloatArray, float)
_PyObject_As(DoubleArray, double)
_PyObject_As(CharArray, signed char)
_PyObject_As(UnsignedCharArray, unsigned char)
_PyObject_As(ShortArray, short)
_PyObject_As(UnsignedShortArray, unsigned short)
_PyObject_As(IntArray, int)
_PyObject_As(UnsignedIntArray, unsigned int)
void* _PyObject_AsArray(GLenum type, PyObject* source, PyObject** temp, int* len);
#define PyErr_XPrint() if (PyErr_Occurred()) PyErr_Print()
#if HAS_DYNAMIC_EXT
#define DECLARE_EXT(PROC_NAME, RET, ERROR_RET, PROTO, CALL)\
RET PROC_NAME PROTO\
{\
typedef RET (APIENTRY *proc_##PROC_NAME) PROTO;\
proc_##PROC_NAME proc = (proc_##PROC_NAME)GL_GetProcAddress(#PROC_NAME);\
if (proc) return proc CALL;\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
return ERROR_RET;\
}
#define DECLARE_VOID_EXT(PROC_NAME, PROTO, CALL)\
void PROC_NAME PROTO\
{\
typedef void (APIENTRY *proc_##PROC_NAME) PROTO;\
proc_##PROC_NAME proc = (proc_##PROC_NAME)GL_GetProcAddress(#PROC_NAME);\
if (proc) proc CALL;\
else {\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
}\
}
#else
#define DECLARE_EXT(PROC_NAME, RET, ERROR_RET, PROTO, CALL)\
RET PROC_NAME PROTO\
{\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
return ERROR_RET;\
}
#define DECLARE_VOID_EXT(PROC_NAME, PROTO, CALL)\
void PROC_NAME PROTO\
{\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
}
#endif
#define _PyTuple_From(NAME, BASE) PyObject* _PyTuple_From##NAME(int len, BASE* data);
_PyTuple_From(UnsignedCharArray, unsigned char)
_PyTuple_From(CharArray, signed char)
_PyTuple_From(UnsignedShortArray, unsigned short)
_PyTuple_From(ShortArray, short)
_PyTuple_From(UnsignedIntArray, unsigned int)
_PyTuple_From(IntArray, int)
_PyTuple_From(FloatArray, float)
_PyTuple_From(DoubleArray, double)
#define _PyObject_From(NAME, BASE) PyObject* _PyObject_From##NAME(int nd, int* dims, BASE* data, int own);
_PyObject_From(UnsignedCharArray, unsigned char)
_PyObject_From(CharArray, signed char)
_PyObject_From(UnsignedShortArray, unsigned short)
_PyObject_From(ShortArray, short)
_PyObject_From(UnsignedIntArray, unsigned int)
_PyObject_From(IntArray, int)
_PyObject_From(FloatArray, float)
_PyObject_From(DoubleArray, double)
PyObject* _PyObject_FromArray(GLenum type, int nd, int *dims, void* data, int own);
void* SetupPixelRead(int rank, GLenum format, GLenum type, int *dims);
void SetupPixelWrite(int rank);
void* SetupRawPixelRead(GLenum format, GLenum type, int n, const int *dims, int* size);
void* _PyObject_AsPointer(PyObject* x);
/* The following line causes a warning on linux and cygwin
The function is defined in interface_utils.c, which is
linked to each extension module. For some reason, though,
this declaration doesn't get recognised as a declaration
prototype for that function.
*/
void init_util();
typedef void *PTR;
typedef struct
{
void (*_decrement)(void* pointer);
void (*_decrementPointer)(GLenum pname);
int (*_incrementLock)(void *pointer);
int (*_incrementPointerLock)(GLenum pname);
void (*_acquire)(void* pointer);
void (*_acquirePointer)(GLenum pname);
#if HAS_DYNAMIC_EXT
PTR (*GL_GetProcAddress)(const char* name);
#endif
int (*InitExtension)(const char *name, const char** procs);
PyObject *_GLerror;
PyObject *_GLUerror;
} util_API;
static util_API *_util_API = NULL;
#define decrementLock(x) (*_util_API)._decrement(x)
#define decrementPointerLock(x) (*_util_API)._decrementPointer(x)
#define incrementLock(x) (*_util_API)._incrementLock(x)
#define incrementPointerLock(x) (*_util_API)._incrementPointerLock(x)
#define acquire(x) (*_util_API)._acquire(x)
#define acquirePointer(x) (*_util_API)._acquirePointer(x)
#define GLerror (*_util_API)._GLerror
#define GLUerror (*_util_API)._GLUerror
#if HAS_DYNAMIC_EXT
#define GL_GetProcAddress(x) (*_util_API).GL_GetProcAddress(x)
#endif
#define InitExtension(x, y) (*_util_API).InitExtension(x, (const char**)y)
#define PyErr_SetGLerror(code) PyErr_SetObject(GLerror, Py_BuildValue("is", code, gluErrorString(code)));
#define PyErr_SetGLUerror(code) PyErr_SetObject(GLUerror, Py_BuildValue("is", code, gluErrorString(code)));
int _PyObject_Dimension(PyObject* x, int rank);
#define ERROR_MSG_SEP ", "
#define ERROR_MSG_SEP_LEN 2
int GLErrOccurred()
{
if (PyErr_Occurred()) return 1;
if (CurrentContextIsValid())
{
GLenum error, *errors = NULL;
char *msg = NULL;
const char *this_msg;
int count = 0;
error = glGetError();
while (error != GL_NO_ERROR)
{
this_msg = gluErrorString(error);
if (count)
{
msg = realloc(msg, (strlen(msg) + strlen(this_msg) + ERROR_MSG_SEP_LEN + 1)*sizeof(char));
strcat(msg, ERROR_MSG_SEP);
strcat(msg, this_msg);
errors = realloc(errors, (count + 1)*sizeof(GLenum));
}
else
{
msg = malloc((strlen(this_msg) + 1)*sizeof(char));
strcpy(msg, this_msg);
errors = malloc(sizeof(GLenum));
}
errors[count++] = error;
error = glGetError();
}
if (count)
{
PyErr_SetObject(GLerror, Py_BuildValue("Os", _PyTuple_FromIntArray(count, (int*)errors), msg));
free(errors);
free(msg);
return 1;
}
}
return 0;
}
void PyErr_SetGLErrorMessage( int id, char * message ) {
/* set a GLerror with an ID and string message
This tries pretty hard to look just like a regular
error as produced by GLErrOccurred()'s formatter,
save that there's only the single error being reported.
Using id 0 is probably best for any future use where
there isn't a good match for the exception description
in the error-enumeration set.
*/
PyObject * args = NULL;
args = Py_BuildValue( "(i)s", id, message );
if (args) {
PyErr_SetObject( GLerror, args );
Py_XDECREF( args );
} else {
PyErr_SetGLerror(id);
}
}
#if PY_MAJOR_VERSION < 2
#define PyExc_WindowsError PyExc_OSError
#endif
int WGLErrOccurred()
{
DWORD error = GetLastError();
if (error != ERROR_SUCCESS)
{
LPSTR buffer;
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, (LPSTR)&buffer, 0, NULL);
PyErr_SetObject(PyExc_WindowsError, Py_BuildValue("is", error, buffer));
LocalFree(buffer);
return 1;
}
return 0;
}
static char *proc_names[] =
{
#if !EXT_DEFINES_PROTO || !defined(WGL_EXT_extensions_string)
"wglGetExtensionsStringEXT",
#endif
NULL
};
#define wglInitExtensionsStringEXT() InitExtension("WGL_EXT_extensions_string", proc_names)
static char _doc_wglInitExtensionsStringEXT[] = "wglInitExtensionsStringEXT() -> bool";
#if !EXT_DEFINES_PROTO || !defined(WGL_EXT_extensions_string)
DECLARE_EXT(wglGetExtensionsStringEXT, const char*, NULL, (), ())
#endif
PyObject *__info()
{
if (wglInitExtensionsStringEXT())
{
PyObject *info = PyList_New(0);
PyList_Append(info, Py_BuildValue("sss", "wglGetExtensionsStringEXT", wglGetExtensionsStringEXT(), "e"));
return info;
}
Py_INCREF(Py_None);
return Py_None;
}
static char _doc_wglGetExtensionsStringEXT[] = "wglGetExtensionsStringEXT() -> string";
#ifdef __cplusplus
extern "C" {
#endif
static PyObject *_wrap_wglInitExtensionsStringEXT(PyObject *self, PyObject *args) {
PyObject *resultobj;
int result;
if(!PyArg_ParseTuple(args,(char *)":wglInitExtensionsStringEXT")) goto fail;
{
SetLastError(0);
result = (int)wglInitExtensionsStringEXT();
if (WGLErrOccurred()) {
return NULL;
}
}
{
resultobj = SWIG_From_int((int)(result));
}
return resultobj;
fail:
return NULL;
}
static PyObject *_wrap___info(PyObject *self, PyObject *args) {
PyObject *resultobj;
PyObject *result;
if(!PyArg_ParseTuple(args,(char *)":__info")) goto fail;
{
SetLastError(0);
result = (PyObject *)__info();
if (WGLErrOccurred()) {
return NULL;
}
}
{
resultobj= result;
}
return resultobj;
fail:
return NULL;
}
static PyObject *_wrap_wglGetExtensionsStringEXT(PyObject *self, PyObject *args) {
PyObject *resultobj;
char *result;
if(!PyArg_ParseTuple(args,(char *)":wglGetExtensionsStringEXT")) goto fail;
{
SetLastError(0);
result = (char *)wglGetExtensionsStringEXT();
if (WGLErrOccurred()) {
return NULL;
}
}
resultobj = SWIG_FromCharPtr(result);
return resultobj;
fail:
return NULL;
}
static PyMethodDef SwigMethods[] = {
{ (char *)"wglInitExtensionsStringEXT", _wrap_wglInitExtensionsStringEXT, METH_VARARGS, NULL},
{ (char *)"__info", _wrap___info, METH_VARARGS, NULL},
{ (char *)"wglGetExtensionsStringEXT", _wrap_wglGetExtensionsStringEXT, METH_VARARGS, NULL},
{ NULL, NULL, 0, NULL }
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
static swig_type_info _swigt__p_GLsizei[] = {{"_p_GLsizei", 0, "int *|GLsizei *", 0, 0, 0, 0},{"_p_GLint", 0, 0, 0, 0, 0, 0},{"_p_GLsizei", 0, 0, 0, 0, 0, 0},{"_p_BOOL", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLshort[] = {{"_p_GLshort", 0, "short *|GLshort *", 0, 0, 0, 0},{"_p_GLshort", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLboolean[] = {{"_p_GLboolean", 0, "unsigned char *|GLboolean *", 0, 0, 0, 0},{"_p_GLboolean", 0, 0, 0, 0, 0, 0},{"_p_BYTE", 0, 0, 0, 0, 0, 0},{"_p_GLubyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_BOOL[] = {{"_p_BOOL", 0, "int *|BOOL *", 0, 0, 0, 0},{"_p_GLint", 0, 0, 0, 0, 0, 0},{"_p_BOOL", 0, 0, 0, 0, 0, 0},{"_p_GLsizei", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__size_t[] = {{"_size_t", 0, "size_t", 0, 0, 0, 0},{"_size_t", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLushort[] = {{"_p_GLushort", 0, "unsigned short *|GLushort *", 0, 0, 0, 0},{"_p_GLushort", 0, 0, 0, 0, 0, 0},{"_p_WORD", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLenum[] = {{"_p_GLenum", 0, "unsigned int *|GLenum *", 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_HGLRC[] = {{"_p_HGLRC", 0, "long *|HGLRC *", 0, 0, 0, 0},{"_p_HENHMETAFILE", 0, 0, 0, 0, 0, 0},{"_p_HGLRC", 0, 0, 0, 0, 0, 0},{"_p_HDC", 0, 0, 0, 0, 0, 0},{"_p_PROC", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLvoid[] = {{"_p_GLvoid", 0, "void *|GLvoid *", 0, 0, 0, 0},{"_p_VOID", 0, 0, 0, 0, 0, 0},{"_p_GLvoid", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_HDC[] = {{"_p_HDC", 0, "long *|HDC *", 0, 0, 0, 0},{"_p_HENHMETAFILE", 0, 0, 0, 0, 0, 0},{"_p_HGLRC", 0, 0, 0, 0, 0, 0},{"_p_HDC", 0, 0, 0, 0, 0, 0},{"_p_PROC", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_UINT[] = {{"_p_UINT", 0, "unsigned int *|UINT *", 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_DOUBLE[] = {{"_p_DOUBLE", 0, "double *|DOUBLE *", 0, 0, 0, 0},{"_p_GLclampd", 0, 0, 0, 0, 0, 0},{"_p_GLdouble", 0, 0, 0, 0, 0, 0},{"_p_DOUBLE", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_COLORREF[] = {{"_p_COLORREF", 0, "unsigned int *|COLORREF *", 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLint[] = {{"_p_GLint", 0, "int *|GLint *", 0, 0, 0, 0},{"_p_GLint", 0, 0, 0, 0, 0, 0},{"_p_GLsizei", 0, 0, 0, 0, 0, 0},{"_p_BOOL", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_WORD[] = {{"_p_WORD", 0, "unsigned short *|WORD *", 0, 0, 0, 0},{"_p_GLushort", 0, 0, 0, 0, 0, 0},{"_p_WORD", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_BYTE[] = {{"_p_BYTE", 0, "unsigned char *|BYTE *", 0, 0, 0, 0},{"_p_GLboolean", 0, 0, 0, 0, 0, 0},{"_p_BYTE", 0, 0, 0, 0, 0, 0},{"_p_GLubyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_char[] = {{"_p_char", 0, "char *", 0, 0, 0, 0},{"_p_char", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLclampd[] = {{"_p_GLclampd", 0, "double *|GLclampd *", 0, 0, 0, 0},{"_p_GLclampd", 0, 0, 0, 0, 0, 0},{"_p_GLdouble", 0, 0, 0, 0, 0, 0},{"_p_DOUBLE", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLclampf[] = {{"_p_GLclampf", 0, "float *|GLclampf *", 0, 0, 0, 0},{"_p_GLfloat", 0, 0, 0, 0, 0, 0},{"_p_GLclampf", 0, 0, 0, 0, 0, 0},{"_p_FLOAT", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_PROC[] = {{"_p_PROC", 0, "long *|PROC *", 0, 0, 0, 0},{"_p_HENHMETAFILE", 0, 0, 0, 0, 0, 0},{"_p_HGLRC", 0, 0, 0, 0, 0, 0},{"_p_PROC", 0, 0, 0, 0, 0, 0},{"_p_HDC", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLuint[] = {{"_p_GLuint", 0, "unsigned int *|GLuint *", 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_HENHMETAFILE[] = {{"_p_HENHMETAFILE", 0, "long *|HENHMETAFILE *", 0, 0, 0, 0},{"_p_HENHMETAFILE", 0, 0, 0, 0, 0, 0},{"_p_HGLRC", 0, 0, 0, 0, 0, 0},{"_p_HDC", 0, 0, 0, 0, 0, 0},{"_p_PROC", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_DWORD[] = {{"_p_DWORD", 0, "unsigned int *|DWORD *", 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_FLOAT[] = {{"_p_FLOAT", 0, "float *|FLOAT *", 0, 0, 0, 0},{"_p_GLfloat", 0, 0, 0, 0, 0, 0},{"_p_GLclampf", 0, 0, 0, 0, 0, 0},{"_p_FLOAT", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__ptrdiff_t[] = {{"_ptrdiff_t", 0, "ptrdiff_t", 0, 0, 0, 0},{"_ptrdiff_t", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLbyte[] = {{"_p_GLbyte", 0, "signed char *|GLbyte *", 0, 0, 0, 0},{"_p_GLbyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_VOID[] = {{"_p_VOID", 0, "void *|VOID *", 0, 0, 0, 0},{"_p_VOID", 0, 0, 0, 0, 0, 0},{"_p_GLvoid", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLbitfield[] = {{"_p_GLbitfield", 0, "unsigned int *|GLbitfield *", 0, 0, 0, 0},{"_p_DWORD", 0, 0, 0, 0, 0, 0},{"_p_COLORREF", 0, 0, 0, 0, 0, 0},{"_p_UINT", 0, 0, 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLfloat[] = {{"_p_GLfloat", 0, "float *|GLfloat *", 0, 0, 0, 0},{"_p_GLfloat", 0, 0, 0, 0, 0, 0},{"_p_GLclampf", 0, 0, 0, 0, 0, 0},{"_p_FLOAT", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLubyte[] = {{"_p_GLubyte", 0, "unsigned char *|GLubyte *", 0, 0, 0, 0},{"_p_GLboolean", 0, 0, 0, 0, 0, 0},{"_p_BYTE", 0, 0, 0, 0, 0, 0},{"_p_GLubyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLdouble[] = {{"_p_GLdouble", 0, "double *|GLdouble *", 0, 0, 0, 0},{"_p_GLclampd", 0, 0, 0, 0, 0, 0},{"_p_GLdouble", 0, 0, 0, 0, 0, 0},{"_p_DOUBLE", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info *swig_types_initial[] = {
_swigt__p_GLsizei,
_swigt__p_GLshort,
_swigt__p_GLboolean,
_swigt__p_BOOL,
_swigt__size_t,
_swigt__p_GLushort,
_swigt__p_GLenum,
_swigt__p_HGLRC,
_swigt__p_GLvoid,
_swigt__p_HDC,
_swigt__p_UINT,
_swigt__p_DOUBLE,
_swigt__p_COLORREF,
_swigt__p_GLint,
_swigt__p_WORD,
_swigt__p_BYTE,
_swigt__p_char,
_swigt__p_GLclampd,
_swigt__p_GLclampf,
_swigt__p_PROC,
_swigt__p_GLuint,
_swigt__p_HENHMETAFILE,
_swigt__p_DWORD,
_swigt__p_FLOAT,
_swigt__ptrdiff_t,
_swigt__p_GLbyte,
_swigt__p_VOID,
_swigt__p_GLbitfield,
_swigt__p_GLfloat,
_swigt__p_GLubyte,
_swigt__p_GLdouble,
0
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
static swig_const_info swig_const_table[] = {
{ SWIG_PY_POINTER, (char*)"__version__", 0, 0, (void *)"1.38.6.1", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__date__", 0, 0, (void *)"2004/11/14 23:21:33", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__author__", 0, 0, (void *)"Tarn Weisner Burton <[email protected]>", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__doc__", 0, 0, (void *)"http://oss.sgi.com/projects/ogl-sample/registry/EXT/wgl_extensions_string.txt", &SWIGTYPE_p_char},
{0, 0, 0, 0.0, 0, 0}};
#ifdef __cplusplus
}
#endif
#ifdef SWIG_LINK_RUNTIME
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(_MSC_VER) || defined(__GNUC__)
# define SWIGIMPORT(a) extern a
# else
# if defined(__BORLANDC__)
# define SWIGIMPORT(a) a _export
# else
# define SWIGIMPORT(a) a
# endif
# endif
#else
# define SWIGIMPORT(a) a
#endif
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT(void *) SWIG_ReturnGlobalTypeList(void *);
#endif
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT(void) SWIG_init(void) {
static PyObject *SWIG_globals = 0;
static int typeinit = 0;
PyObject *m, *d;
int i;
if (!SWIG_globals) SWIG_globals = SWIG_newvarlink();
/* Fix SwigMethods to carry the callback ptrs when needed */
SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_types_initial);
m = Py_InitModule((char *) SWIG_name, SwigMethods);
d = PyModule_GetDict(m);
if (!typeinit) {
#ifdef SWIG_LINK_RUNTIME
swig_type_list_handle = (swig_type_info **) SWIG_ReturnGlobalTypeList(swig_type_list_handle);
#else
# ifndef SWIG_STATIC_RUNTIME
SWIG_Python_LookupTypePointer(&swig_type_list_handle);
# endif
#endif
for (i = 0; swig_types_initial[i]; i++) {
swig_types[i] = SWIG_TypeRegister(swig_types_initial[i]);
}
typeinit = 1;
}
SWIG_InstallConstants(d,swig_const_table);
PyDict_SetItemString(d,"__version__", SWIG_FromCharPtr("1.38.6.1"));
PyDict_SetItemString(d,"__date__", SWIG_FromCharPtr("2004/11/14 23:21:33"));
{
PyDict_SetItemString(d,"__api_version__", SWIG_From_int((int)(256)));
}
PyDict_SetItemString(d,"__author__", SWIG_FromCharPtr("Tarn Weisner Burton <[email protected]>"));
PyDict_SetItemString(d,"__doc__", SWIG_FromCharPtr("http://oss.sgi.com/projects/ogl-sample/registry/EXT/wgl_extensions_string.txt"));
#ifdef NUMERIC
PyArray_API = NULL;
import_array();
init_util();
PyErr_Clear();
#endif
{
PyObject *util = PyImport_ImportModule("OpenGL.GL._GL__init__");
if (util)
{
PyObject *api_object = PyDict_GetItemString(PyModule_GetDict(util), "_util_API");
if (PyCObject_Check(api_object)) _util_API = (util_API*)PyCObject_AsVoidPtr(api_object);
}
}
}
| [
"ronaldoussoren@f55f28a5-9edb-0310-a011-a803cfcd5d25"
] | [
[
[
1,
1695
]
]
] |
905830070bee7f5d70984ab4ea51e41f983f8d76 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/configsdk/NetworkConfig.cpp | 87c99ac3c2dbd9ca9f775736c661c092bfa9d45b | [] | no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,640 | cpp |
#include "StdAfx.h"
#include "NetworkConfig.h"
#include "json/json.h"
#include "RecordConfig.h"
BOOL Net_NAS_Parse(char* szInBuffer, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned)
{
BOOL bRet = FALSE;
if ( NULL == szInBuffer || NULL == lpOutBuffer || dwOutBufferSize < sizeof(CFG_NAS_INFO) )
{
return bRet;
}
Json::Reader reader;
static Json::Value value;
CFG_NAS_INFO stuNASInfo = {0};
memset(lpOutBuffer, 0, dwOutBufferSize);
int nStringLen = 0;
if(reader.parse(szInBuffer, value, false))
{
if (value["NAS"]["En"].type() != Json::nullValue)
{
stuNASInfo.bEnable = value["NAS"]["En"].asInt();
}
if (value["NAS"]["Version"].type() != Json::nullValue)
{
stuNASInfo.nVersion = value["NAS"]["Version"].asInt();
}
if (value["NAS"]["Protocol"].type() != Json::nullValue)
{
stuNASInfo.nProtocol = value["NAS"]["Protocol"].asInt();
}
if (value["NAS"]["Address"].type() != Json::nullValue)
{
nStringLen = value["NAS"]["Address"].asString().size();
nStringLen = nStringLen>MAX_ADDRESS_LEN?MAX_ADDRESS_LEN:nStringLen;
strncpy(stuNASInfo.szAddress, value["NAS"]["Address"].asString().c_str(), nStringLen);
}
if (value["NAS"]["Port"].type() != Json::nullValue)
{
stuNASInfo.nPort = value["NAS"]["Port"].asInt();
}
if (value["NAS"]["UserName"].type() != Json::nullValue)
{
nStringLen = value["NAS"]["UserName"].asString().size();
nStringLen = nStringLen>MAX_USERNAME_LEN?MAX_USERNAME_LEN:nStringLen;
strncpy(stuNASInfo.szUserName, value["NAS"]["UserName"].asString().c_str(), nStringLen);
}
if (value["NAS"]["Password"].type() != Json::nullValue)
{
nStringLen = value["NAS"]["Password"].asString().size();
nStringLen = nStringLen>MAX_PASSWORD_LEN?MAX_PASSWORD_LEN:nStringLen;
strncpy(stuNASInfo.szPassword, value["NAS"]["Password"].asString().c_str(), nStringLen);
}
if (value["NAS"]["Directory"].type() != Json::nullValue)
{
nStringLen = value["NAS"]["Directory"].asString().size();
nStringLen = nStringLen>MAX_DIRECTORY_LEN?MAX_DIRECTORY_LEN:nStringLen;
strncpy(stuNASInfo.szDirectory, value["NAS"]["Directory"].asString().c_str(), nStringLen);
}
if (value["NAS"]["FileLen"].type() != Json::nullValue)
{
stuNASInfo.nFileLen = value["NAS"]["FileLen"].asInt();
}
if (value["NAS"]["Interval"].type() != Json::nullValue)
{
stuNASInfo.nInterval = value["NAS"]["Interval"].asInt();
}
char szName[64] = {0};
for(int i = 0; i < MAX_VIDEO_CHANNEL_NUM; i++)
{
for(int j = 0; j < WEEK_DAY_NUM; j++)
{
for (int k = 0; k < MAX_NAS_TIME_SECTION; k++)
{
sprintf(szName, "En%d", k);
stuNASInfo.stuChnTime[i].stuTimeSection[j][k].dwRecordMask = value["NAS"]["ChnTime"][i][j][szName].asInt();
sprintf(szName, "Time%d", k);
sscanf((char *)value["NAS"]["ChnTime"][i][j][szName].asString().c_str(),
"%02d:%02d:%02d-%02d:%02d:%02d",
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nBeginHour,
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nBeginMin,
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nBeginSec,
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nHourEnd,
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nEndMin,
&stuNASInfo.stuChnTime[i].stuTimeSection[j][k].nEndSec);
}
}
}
bRet = TRUE;
if (lpBytesReturned)
{
*lpBytesReturned = sizeof(CFG_NAS_INFO);
}
memcpy(lpOutBuffer, &stuNASInfo, sizeof(CFG_NAS_INFO));
}
else
{
bRet = FALSE;
}
return bRet;
}
BOOL Net_NAS_Packet(LPVOID lpInBuffer, DWORD dwInBufferSize, char* szOutBuffer, DWORD dwOutBufferSize)
{
BOOL bRet = FALSE;
if ( NULL == lpInBuffer || NULL == szOutBuffer || dwInBufferSize < sizeof(CFG_NAS_INFO) )
{
return bRet;
}
memset(szOutBuffer, 0, dwOutBufferSize);
Json::Value value;
CFG_NAS_INFO *pNASInfo = NULL;
pNASInfo = (CFG_NAS_INFO *)lpInBuffer;
bRet = TRUE;
value["NAS"]["En"] = pNASInfo->bEnable;
value["NAS"]["Version"] = pNASInfo->nVersion;
value["NAS"]["Protocol"] = pNASInfo->nProtocol;
value["NAS"]["Address"] = pNASInfo->szAddress;
value["NAS"]["Port"] = pNASInfo->nPort;
value["NAS"]["UserName"] = pNASInfo->szUserName;
value["NAS"]["Password"] = pNASInfo->szPassword;
value["NAS"]["Directory"] = pNASInfo->szDirectory;
value["NAS"]["FileLen"] = pNASInfo->nFileLen;
value["NAS"]["Interval"] = pNASInfo->nInterval;
char szName[64] = {0};
for(int i = 0; i < MAX_VIDEO_CHANNEL_NUM; i++)
{
for(int j = 0; j < WEEK_DAY_NUM; j++)
{
for (int k = 0; k < MAX_NAS_TIME_SECTION; k++)
{
sprintf(szName, "En%d", k);
value["NAS"]["ChnTime"][i][j][szName] = (int)pNASInfo->stuChnTime[i].stuTimeSection[j][k].dwRecordMask;
sprintf(szName, "Time%d", k);
char szBuf[128] = {0};
sprintf(szBuf, "%02d:%02d:%02d-%02d:%02d:%02d",
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nBeginHour,
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nBeginMin,
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nBeginSec,
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nHourEnd,
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nEndMin,
pNASInfo->stuChnTime[i].stuTimeSection[j][k].nEndSec);
value["NAS"]["ChnTime"][i][j][szName] = szBuf;
}
}
}
std::string str;
Json::FastWriter writer(str);
writer.write(value);
if (dwOutBufferSize < str.size())
{
bRet = FALSE;
}
else
{
strcpy(szOutBuffer, str.c_str());
}
return bRet;
}
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
193
]
]
] |
3e34adf5858b14023d13f87534fd628959a11fcd | b6bad03a59ec436b60c30fc793bdcf687a21cf31 | /som2416/wince5/sdhc_s3c2450_ch0.cpp | c02bd4f494a7d41a5566e121d3d2958906b6d41e | [] | no_license | blackfa1con/openembed | 9697f99b12df16b1c5135e962890e8a3935be877 | 3029d7d8c181449723bb16d0a73ee87f63860864 | refs/heads/master | 2021-01-10T14:14:39.694809 | 2010-12-16T03:20:27 | 2010-12-16T03:20:27 | 52,422,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,719 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
#include <windows.h>
#include <nkintr.h>
#include <ceddk.h>
#include <s3c2450.h>
#include "SDHC_s3c2450_ch0.h"
#include <cebuscfg.h>
#if (BSP_TYPE == BSP_SMDK2443)
#elif (BSP_TYPE == BSP_SMDK2450)
#define _DBG_ 0
#ifdef _SMDK2450_CH0_EXTCD_
// 08.04.04 by KYS
// New Constructor for card detect of HSMMC ch0 on SMDK2450.
CSDHController::CSDHController() : CSDHCBase() {
m_htCardDetectThread = NULL;
m_hevCardDetectEvent = NULL;
m_dwSDDetectSysIntr = SYSINTR_UNDEFINED;
}
#endif
#endif // !(BSP_TYPE == BSP_SMDK2443)
BOOL
CSDHController::Init(
LPCTSTR pszActiveKey
)
{
#if (BSP_TYPE == BSP_SMDK2443)
S3C2450_CLKPWR_REG *pCLKPWR;
S3C2450_HSMMC_REG *pHSMMC;
S3C2450_IOPORT_REG *pIOPreg;
RETAILMSG(0,(TEXT("CSDHController::Init\n")));
//GPIO Setting
//----- 1. Map the GPIO registers needed to enable the SDI controller -----
pIOPreg = (S3C2450_IOPORT_REG *)VirtualAlloc(0, sizeof(S3C2450_IOPORT_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pIOPreg == NULL)
{
RETAILMSG (1,(TEXT("GPIO registers not allocated\r\n")));
return FALSE;
}
if (!VirtualCopy((PVOID)pIOPreg, (PVOID)(S3C2450_BASE_REG_PA_IOPORT >> 8), sizeof(S3C2450_IOPORT_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("GPIO registers not mapped\r\n")));
return FALSE;
}
pCLKPWR = (S3C2450_CLKPWR_REG *)VirtualAlloc(0, sizeof(S3C2450_CLKPWR_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pCLKPWR == NULL)
{
RETAILMSG (1,(TEXT("Clock & Power Management Special Register not allocated\n\r")));
return FALSE;
}
if (!VirtualCopy((PVOID)pCLKPWR, (PVOID)(S3C2450_BASE_REG_PA_CLOCK_POWER >> 8), sizeof(S3C2450_CLKPWR_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("Clock & Power Management Special Register not mapped\n\r")));
return FALSE;
}
pHSMMC = (S3C2450_HSMMC_REG *)VirtualAlloc(0, sizeof(S3C2450_HSMMC_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pHSMMC == NULL)
{
RETAILMSG (1,(TEXT("HSMMC Special Register not allocated\n\r")));
return FALSE;
}
if (!VirtualCopy((PVOID)pHSMMC, (PVOID)(S3C2450_BASE_REG_PA_HSMMC >> 8), sizeof(S3C2450_HSMMC_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("HSMMC Special Register not mapped\n\r")));
return FALSE;
}
// pIOPreg->GPFCON &= ~(0x3<<14);
// pIOPreg->GPFCON |= (0x1<<14);
pIOPreg->GPLCON &= ~(0xFFFFF);
pIOPreg->GPLCON |= (0xAAAAA);
// pIOPreg->GPLUDP &= ~(0xFFFFF);
// pIOPreg->GPLUDP |= (0xAAAAA);
pIOPreg->GPJCON &= ~(0x3F << 26);
pIOPreg->GPJCON |= (0x2A << 26);
// pIOPreg->GPJUDP &= ~(0x3F << 26);
// pIOPreg->GPJUDP |= (0x2A << 26);
pHSMMC->CONTROL2 = (pHSMMC->CONTROL2 & ~(0xffffffff)) | (0x1<<15)|(0x1<<14)|(0x1<<8)|(0x2/*EPLL*/<<4);
pHSMMC->CONTROL3 = (0<<31) | (1<<23) | (0<<15) | (1<<7);
RETAILMSG(0,(TEXT("pHSMMC->CONTROL2 = 0x%X\n"),pHSMMC->CONTROL2));
pCLKPWR->HCLKCON |= (0x1<<16);
pCLKPWR->SCLKCON |= (0x1<<13);
pCLKPWR->SCLKCON |= (0x1<<12);
// pCLKPWR->CLKDIV1 |= (0x3<<6);
VirtualFree((PVOID) pIOPreg, 0, MEM_RELEASE);
VirtualFree((PVOID) pCLKPWR, 0, MEM_RELEASE);
VirtualFree((PVOID) pHSMMC, 0, MEM_RELEASE);
#elif (BSP_TYPE == BSP_SMDK2450)
RETAILMSG(1, (TEXT("[HSMMC0] Initializing the HSMMC Host Controller\n")));
// 08.03.13 by KYS
// HSMMC Ch1 initialization
if (!InitCh()) return FALSE;
#endif // !(BSP_TYPE == BSP_SMDK2443)
return CSDHCBase::Init(pszActiveKey);
}
void
CSDHController::PowerUp()
{
#if (BSP_TYPE == BSP_SMDK2443)
S3C2450_CLKPWR_REG *pCLKPWR;
S3C2450_HSMMC_REG *pHSMMC;
S3C2450_IOPORT_REG *pIOPreg;
S3C2450_INTR_REG *pINTreg;
//GPIO Setting
//----- 1. Map the GPIO registers needed to enable the SDI controller -----
pIOPreg = (S3C2450_IOPORT_REG *)VirtualAlloc(0, sizeof(S3C2450_IOPORT_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pIOPreg == NULL)
{
RETAILMSG (1,(TEXT("GPIO registers not allocated\r\n")));
return;
}
if (!VirtualCopy((PVOID)pIOPreg, (PVOID)(S3C2450_BASE_REG_PA_IOPORT >> 8), sizeof(S3C2450_IOPORT_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("GPIO registers not mapped\r\n")));
return;
}
pCLKPWR = (S3C2450_CLKPWR_REG *)VirtualAlloc(0, sizeof(S3C2450_CLKPWR_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pCLKPWR == NULL)
{
RETAILMSG (1,(TEXT("Clock & Power Management Special Register not allocated\n\r")));
return;
}
if (!VirtualCopy((PVOID)pCLKPWR, (PVOID)(S3C2450_BASE_REG_PA_CLOCK_POWER >> 8), sizeof(S3C2450_CLKPWR_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("Clock & Power Management Special Register not mapped\n\r")));
return;
}
pHSMMC = (S3C2450_HSMMC_REG *)VirtualAlloc(0, sizeof(S3C2450_HSMMC_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pHSMMC == NULL)
{
RETAILMSG (1,(TEXT("HSMMC Special Register not allocated\n\r")));
return;
}
if (!VirtualCopy((PVOID)pHSMMC, (PVOID)(S3C2450_BASE_REG_PA_HSMMC >> 8), sizeof(S3C2450_HSMMC_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("HSMMC Special Register not mapped\n\r")));
return;
}
pINTreg = (S3C2450_INTR_REG *)VirtualAlloc(0, sizeof(S3C2450_INTR_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pINTreg == NULL)
{
RETAILMSG (1,(TEXT("HSMMC Special Register not allocated\n\r")));
return;
}
if (!VirtualCopy((PVOID)pINTreg, (PVOID)(S3C2450_BASE_REG_PA_INTR >> 8), sizeof(S3C2450_INTR_REG), PAGE_PHYSICAL | PAGE_READWRITE | PAGE_NOCACHE)) {
RETAILMSG (1,(TEXT("HSMMC Special Register not mapped\n\r")));
return;
}
// pIOPreg->GPFCON &= ~(0x3<<14);
// pIOPreg->GPFCON |= (0x1<<14);
pIOPreg->GPLCON &= ~(0xFFFFF);
pIOPreg->GPLCON |= (0xAAAAA);
// pIOPreg->GPLUDP &= ~(0xFFFFF);
// pIOPreg->GPLUDP |= (0x55555);
pIOPreg->GPJCON &= ~(0x3F << 26);
pIOPreg->GPJCON |= (0x2A << 26);
// pIOPreg->GPJUDP &= ~(0x3F << 26);
// pIOPreg->GPJUDP |= (0x15 << 26);
pHSMMC->CONTROL2 = (pHSMMC->CONTROL2 & ~(0xffffffff)) | (0x1<<15)|(0x1<<14)|(0x1<<8)|(0x2/*EPLL*/<<4);
pHSMMC->CONTROL3 = (0<<31) | (1<<23) | (0<<15) | (1<<7);
pCLKPWR->HCLKCON |= (0x1<<16);
pCLKPWR->SCLKCON |= (0x1<<13);
pCLKPWR->SCLKCON |= (0x1<<12);
RETAILMSG(0,(TEXT("HSMMC!!!!!!!!!!! pINTreg->INTMSK = 0x%08X\n"),pINTreg->INTMSK));
RETAILMSG(0,(TEXT("HSMMC!!!!!!!!!!! pHSMMC->NORINTSTSEN = 0x%08X\n"),pHSMMC->NORINTSTSEN));
VirtualFree((PVOID) pINTreg, 0, MEM_RELEASE);
VirtualFree((PVOID) pIOPreg, 0, MEM_RELEASE);
VirtualFree((PVOID) pCLKPWR, 0, MEM_RELEASE);
VirtualFree((PVOID) pHSMMC, 0, MEM_RELEASE);
#elif (BSP_TYPE == BSP_SMDK2450)
RETAILMSG(1, (TEXT("[HSMMC0] Power Up the HSMMC Host Controller\n")));
// 08.03.13 by KYS
// HSMMC Ch1 initialization for "WakeUp"
if (!InitCh()) return;
#endif // !(BSP_TYPE == BSP_SMDK2443)
CSDHCBase::PowerUp();
}
extern "C"
PCSDHCBase
CreateHSMMCHCObject(
)
{
return new CSDHController;
}
VOID
CSDHController::DestroyHSMMCHCObject(
PCSDHCBase pSDHC
)
{
DEBUGCHK(pSDHC);
delete pSDHC;
}
#if (BSP_TYPE == BSP_SMDK2443)
#elif (BSP_TYPE == BSP_SMDK2450)
BOOL CSDHController::InitClkPwr() {
volatile S3C2450_CLKPWR_REG *pCLKPWR = NULL;
pCLKPWR = (volatile S3C2450_CLKPWR_REG *)VirtualAlloc(0, sizeof(S3C2450_CLKPWR_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pCLKPWR == NULL) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] Clock & Power Management Special Register is *NOT* allocated.\n")));
return FALSE;
}
if (!VirtualCopy((PVOID)pCLKPWR, (PVOID)(S3C2450_BASE_REG_PA_CLOCK_POWER >> 8),
sizeof(S3C2450_CLKPWR_REG), PAGE_PHYSICAL|PAGE_READWRITE|PAGE_NOCACHE)) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] Clock & Power Management Special Register is *NOT* mapped.\n")));
return FALSE;
}
RETAILMSG(_DBG_, (TEXT("[HSMMC0] Setting registers for the EPLL (for SDCLK) : SYSCon.\n")));
pCLKPWR->CLKSRC |= (0x0<<16); // HSMMC0 clock: 0 = EPLL, 1 = USB 48MHz
pCLKPWR->HCLKCON |= (0x1<<15); // Enable HCLK into the HSMMC0
pCLKPWR->SCLKCON |= (0x0<<13); // Disable HSMMC_EXT clock for HSMMC 0,1 (EXTCLK)
pCLKPWR->SCLKCON |= (0x1<<6); // Enable HSMMC_0 clock for (EPLL/USB48M)
VirtualFree((PVOID) pCLKPWR, 0, MEM_RELEASE);
return TRUE;
}
BOOL CSDHController::InitGPIO() {
volatile S3C2450_IOPORT_REG *pIOPreg = NULL;
pIOPreg = (volatile S3C2450_IOPORT_REG *)VirtualAlloc(0, sizeof(S3C2450_IOPORT_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pIOPreg == NULL) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] GPIO registers is *NOT* allocated.\n")));
return FALSE;
}
if (!VirtualCopy((PVOID)pIOPreg, (PVOID)(S3C2450_BASE_REG_PA_IOPORT >> 8),
sizeof(S3C2450_IOPORT_REG), PAGE_PHYSICAL|PAGE_READWRITE|PAGE_NOCACHE)) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] GPIO registers is *NOT* mapped.\n")));
return FALSE;
}
RETAILMSG(_DBG_, (TEXT("[HSMMC0] Setting registers for the GPIO.\n")));
pIOPreg->GPECON &= ~(0xFFF<<10);
pIOPreg->GPECON |= (0xAAA<<10); // SD0_DAT[3:0], SD0_CMD, SD0_CLK
pIOPreg->GPEUDP &= ~(0xFFF<<10); // pull-up/down disabled
#ifdef _SMDK2450_CH0_EXTCD_
// 08.04.04 by KYS
// Setting for card detect pin of HSMMC ch0 on SMDK2450.
pIOPreg->GPFCON = ( pIOPreg->GPFCON & ~(0x3<<2) ) | (0x2<<2); // SD_CD0 by EINT1(GPF1)
pIOPreg->GPFUDP = ( pIOPreg->GPFUDP & ~(0x3<<2) ) | (0x0<<2); // pull-up/down disabled
pIOPreg->EXTINT0 = ( pIOPreg->EXTINT0 & ~(0xF<<4) ) | (0x6<<4); // 4b'0110 : Filter Enable, Both edge triggered
#endif
#ifdef _SMDK2450_CH0_WP_
//
// Here for the Setting code on WriteProtection!!
// Refer to InitGPIO() in HSMMC_ch1\HSMMC_ch1\sdhc_s3c2450_ch1.cpp file
//
#endif
VirtualFree((PVOID) pIOPreg, 0, MEM_RELEASE);
return TRUE;
}
BOOL CSDHController::InitHSMMC() {
volatile S3C2450_HSMMC_REG *pHSMMC = NULL;
pHSMMC = (volatile S3C2450_HSMMC_REG *)VirtualAlloc(0, sizeof(S3C2450_HSMMC_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pHSMMC == NULL)
{
RETAILMSG(_DBG_,(TEXT("[HSMMC0] HSMMC Special Register is *NOT* allocated.\n")));
return FALSE;
}
if (!VirtualCopy((PVOID)pHSMMC, (PVOID)(S3C2450_BASE_REG_PA_HSMMC0 >> 8),
sizeof(S3C2450_HSMMC_REG), PAGE_PHYSICAL|PAGE_READWRITE|PAGE_NOCACHE)) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] HSMMC Special Register is *NOT* mapped.\n")));
return FALSE;
}
RETAILMSG(_DBG_, (TEXT("[HSMMC0] Setting registers for the EPLL : HSMMCCon.\n")));
pHSMMC->CONTROL2 = (pHSMMC->CONTROL2 & ~(0xffffffff)) | // clear all
(0x1<<15) | // enable Feedback clock for Tx Data/Command Clock
(0x1<<14) | // enable Feedback clock for Rx Data/Command Clock
(0x3<<9) | // Debounce Filter Count 0x3=64 iSDCLK
(0x1<<8) | // SDCLK Hold Enable
(0x2<<4); // Base Clock Source = EPLL (from SYSCON block)
pHSMMC->CONTROL3 = (0<<31) | (1<<23) | (0<<15) | (1<<7); // controlling the Feedback Clock
VirtualFree((PVOID) pHSMMC, 0, MEM_RELEASE);
return TRUE;
}
BOOL CSDHController::InitCh() {
if (!InitClkPwr()) return FALSE;
if (!InitGPIO()) return FALSE;
if (!InitHSMMC()) return FALSE;
return TRUE;
}
#ifdef _SMDK2450_CH0_EXTCD_
// 08.04.04 by KYS
// New function to Card detect thread of HSMMC ch0 on SMDK2450.
DWORD CSDHController::CardDetectThread() {
BOOL bSlotStateChanged = FALSE;
DWORD dwWaitResult = WAIT_TIMEOUT;
PCSDHCSlotBase pSlotZero = GetSlot(0);
CeSetThreadPriority(GetCurrentThread(), 100);
while(1) {
// Wait for the next insertion/removal interrupt
dwWaitResult = WaitForSingleObject(m_hevCardDetectEvent, INFINITE);
Lock();
pSlotZero->HandleInterrupt(SDSLOT_INT_CARD_DETECTED);
Unlock();
InterruptDone(m_dwSDDetectSysIntr);
EnableCardDetectInterrupt();
}
return TRUE;
}
// 08.04.04 by KYS
// New function to request a SYSINTR for Card detect interrupt of HSMMC ch0 on SMDK2450.
BOOL CSDHController::InitializeHardware() {
m_dwSDDetectIrq = SD_CD0_IRQ;
// convert the SDI hardware IRQ into a logical SYSINTR value
if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &m_dwSDDetectIrq, sizeof(DWORD), &m_dwSDDetectSysIntr, sizeof(DWORD), NULL)) {
// invalid SDDetect SYSINTR value!
RETAILMSG(1, (TEXT("[HSMMC0] invalid SD detect SYSINTR value!\n")));
m_dwSDDetectSysIntr = SYSINTR_UNDEFINED;
return FALSE;
}
return CSDHCBase::InitializeHardware();
}
// 08.04.04 by KYS
// New Start function for Card detect of HSMMC ch0 on SMDK2450.
SD_API_STATUS CSDHController::Start() {
SD_API_STATUS status = SD_API_STATUS_INSUFFICIENT_RESOURCES;
m_fDriverShutdown = FALSE;
// allocate the interrupt event
m_hevInterrupt = CreateEvent(NULL, FALSE, FALSE,NULL);
if (NULL == m_hevInterrupt) {
goto EXIT;
}
// initialize the interrupt event
if (!InterruptInitialize (m_dwSysIntr, m_hevInterrupt, NULL, 0)) {
goto EXIT;
}
m_fInterruptInitialized = TRUE;
// create the interrupt thread for controller interrupts
m_htIST = CreateThread(NULL, 0, ISTStub, this, 0, NULL);
if (NULL == m_htIST) {
goto EXIT;
}
// allocate the card detect event
m_hevCardDetectEvent = CreateEvent(NULL, FALSE, FALSE,NULL);
if (NULL == m_hevCardDetectEvent) {
goto EXIT;
}
// initialize the interrupt event
if (!InterruptInitialize (m_dwSDDetectSysIntr, m_hevCardDetectEvent, NULL, 0)) {
goto EXIT;
}
// create the card detect interrupt thread
m_htCardDetectThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)SD_CardDetectThread, this, 0, NULL);
if (NULL == m_htCardDetectThread) {
goto EXIT;
}
for (DWORD dwSlot = 0; dwSlot < m_cSlots; ++dwSlot) {
PCSDHCSlotBase pSlot = GetSlot(dwSlot);
status = pSlot->Start();
if (!SD_API_SUCCESS(status)) {
goto EXIT;
}
}
// wake up the interrupt thread to check the slot
::SetInterruptEvent(m_dwSDDetectSysIntr);
status = SD_API_STATUS_SUCCESS;
EXIT:
if (!SD_API_SUCCESS(status)) {
// Clean up
Stop();
}
return status;
}
// 08.04.04 by KYS
// New function for enabling the Card detect interrupt of HSMMC ch0 on SMDK2450.
BOOL CSDHController::EnableCardDetectInterrupt() {
volatile S3C2450_INTR_REG *pINTRreg = NULL;
pINTRreg = (volatile S3C2450_INTR_REG *)VirtualAlloc(0, sizeof(S3C2450_INTR_REG), MEM_RESERVE, PAGE_NOACCESS);
if (pINTRreg == NULL) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] INTR registers is *NOT* allocated.\n")));
return FALSE;
}
if (!VirtualCopy((PVOID)pINTRreg, (PVOID)(S3C2450_BASE_REG_PA_INTR >> 8),
sizeof(S3C2450_INTR_REG), PAGE_PHYSICAL|PAGE_READWRITE|PAGE_NOCACHE)) {
RETAILMSG(_DBG_,(TEXT("[HSMMC0] INTR registers is *NOT* mapped.\n")));
return FALSE;
}
//pINTRreg->SRCPND1 = ( pINTRreg->SRCPND1 | (0x1<<1)); //clear EINT1SRC pending bit
pINTRreg->INTPND1 = ( pINTRreg->INTPND1 | (0x1<<1)); //clear EINT1 pending bit
pINTRreg->INTMSK1 = ( pINTRreg->INTMSK1 & ~(0x1<<1)); //enable EINT19
VirtualFree((PVOID)pINTRreg, 0, MEM_RELEASE);
return TRUE;
}
#endif
#endif // !(BSP_TYPE == BSP_SMDK2443)
| [
"[email protected]"
] | [
[
[
1,
468
]
]
] |
e02b88a7b4c847ed2759a9a5e006cdfef222f17e | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /mancala.h | 1d9442af5d4841b2e1d2f940b86eee6882e2e2c1 | [] | no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,911 | h | class Board
{
static const int NUMSTONES = 4; // number of stones each bowl begins with
static const int NUMBOWLS = 6; // number of bowls for each player
// (count does not include the mancala)
public:
Board();
// post: All bowls for each player have been initialized to NUMSTONES.
// The mancala for each player has been initialized to 0.
void setFirstPlayer(const char color, const bool compPlayer);
// pre: color = 'R' or 'B'.
// post: The current player is set to the value passed in to the variable
// color. (This function should only be called once per round --
// prior to the first move.)
char checkForWin();
// post: Returns 'R' if the Red player has won
// Returns 'B' if the Blue player has won
// Returns 'N' if neither player has won
bool move(const int bowlNum, const int direction);
// pre: bowlNum = the starting bowl the current player will move from
// (specified by an int between [0,NUMBOWLS-1]).
// direction = -1 (for clockwise) or 1 (for counter clockwise)
// post: The human player's move is executed, and the current player is
// updated/switched. If the player's move wins him/herself another
// turn, the function returns true. Otherwise, the function returns
// false.
bool computerMove();
// pre: currPlayer = The computer player's color.
// post: The computer player executes a move according to its strategy
// (described below). The current player is updated/switched. If the
// the computer's move wins itself another turn, the function returns
// true. Otherwise, the function returns false.
void display();
// post: The current mancala board status has been printed to the screen.
friend std::ostream& operator << (std::ostream& outs, const Board& obj);
// post: The board contained in obj has been printed to the ostream
// (in whatever format you choose).
friend std::istream& operator >> (std::istream& ins, Board& obj);
// post: board is read from istream and stored in object obj.
private:
int theBoard[2][NUMBOWLS+1]; // Each row is one player's side of the
// board. Indices [0,NUMBOWLS-1] represent
// a player's bowls. NUMBOWLS represents
// a player's mancala.
char currPlayer; // The color of the current player
void switchPlayers();
// pre: It is the end of one player's turn
// post: currPlayer is updated to indicate it is a different player's turn
void addToMancala();
// pre: The current player just ended his turn by placing a stone
// in one of his empty bowls.
// post: The newly placed stone, plus all of the stones from the
// opponent's corresponding bowl, are added to the current player's
// mancala.
};
class Mancala
{
public:
Mancala();
// pre: Random Number Generator (RNG) has been seeded.
// post: The player to move first (Red or Blue) has been chosen.
bool LoadGame();
// post: User is asked for a file to open that stores a previously saved
// game. If the file exists and is in the correct format, the game is
// loaded and True is returned. Else the function returns false.
void SaveGame();
// post: The user is prompted for a filename, and the current game is
// saved to the file.
char Play();
// post: This function allows two people to play a round of Mancala. If
// the Red player wins, 'R' is returned. If the Blue player wins, 'B'
// is returned. If there is a tie, 'T' is returned.
private:
Board gameBoard; // the Mancala board containing all the stones
char currPlayer; // the color of the player whose turn it is
};
| [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
1d0de3cc06c7027628d605c15f33a7d11f727f0e | 93eac58e092f4e2a34034b8f14dcf847496d8a94 | /ncl30-cpp/ncl30-generator/src/AttributeAssessmentGenerator.cpp | 9aa7ee8c752c3cd568ba719920f44eacecabea1d | [] | no_license | lince/ginga-srpp | f8154049c7e287573f10c472944315c1c7e9f378 | 5dce1f7cded43ef8486d2d1a71ab7878c8f120b4 | refs/heads/master | 2020-05-27T07:54:24.324156 | 2011-10-17T13:59:11 | 2011-10-17T13:59:11 | 2,576,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,938 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
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 version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file AtributeAssessmentGenerator.cpp
* @author Caio Viel
* @date 29-01-10
*/
#include "../include/generables/AttributeAssessmentGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generator {
string AtributeAssessmentGenerator::generateCode() {
string ret = "<attributeAssessment ";
ret += "role=\"" + this->getLabel() + "\" ";
ret += "eventType=\"" + EventUtil::getTypeName(this->getEventType()) + "\" ";
if (this->getKey() != "") {
ret += "key=\"" + this->getKey(); + "\" ";
}
ret += "attriuteType=\"" + EventUtil::getAttributeTypeName(this->getAttributeType());
if (this->getOffset() != "") {
ret += "offset=\"" + this->getOffset() + "\" ";
}
ret += "/>";
return ret;
}
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
82
]
]
] |
488810138e75f04c0cc4bc8f2fa445b1b1208074 | 8b3186e126ac2d19675dc19dd473785de97068d2 | /bmt_prod/util/material.h | c51a7238213620cf1f2ced3f9d0c60a5f1a344c2 | [] | no_license | leavittx/revenge | e1fd7d6cd1f4a1fb1f7a98de5d16817a0c93da47 | 3389148f82e6434f0619df47c076c60c8647ed86 | refs/heads/master | 2021-01-01T17:28:26.539974 | 2011-08-25T20:25:14 | 2011-08-25T20:25:14 | 618,159 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | h | #pragma once
#include "../globals.h"
class Material
{
public:
Material();
~Material();
void setDiffuse(float r, float g, float b, float a);
void setDiffuse(const Color3 &olor, float a = 1.0f);
void setAmbient(float r, float g, float b, float a);
void setAmbient(const Color3 &olor, float a = 1.0f);
void setSpecular(float r, float g, float b, float a);
void setSpecular(const Color3 &olor, float a = 1.0f);
void setEmission(float r, float g, float b, float a);
void setEmission(const Color3 &olor, float a = 1.0f);
void setShininess(float shininess);
void use(bool diffuse = true, bool ambient = true, bool specular = true, bool emission = true, bool shininess = true);
void setDefaults();
private:
//components for the material
float m_diffuse[4];
float m_ambient[4];
float m_specular[4];
float m_emission[4];
float m_shininess;
};
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
b9eb76bc767d42dcc7eb1ea1aa27976db594ef81 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /tags/pyplusplus_dev_0.9.5/docs/troubleshooting_guide/smart_ptrs/classes.hpp | c1eb9c966e779c0f30cfc43afc08e161c96116d9 | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,882 | hpp | #ifndef classes_11_11_2006
#define classes_11_11_2006
#include "smart_ptr.h"
struct base_i{
public:
virtual ~base_i() {}
virtual int get_value() const = 0;
};
struct derived_t : base_i{
derived_t(){}
virtual int get_value() const{ return 0xD; }
};
// Some smart pointer classes does not have reach interface as boost ones.
// In order to provide same level of convenience, users are forced to create
// classes, which derive from smart pointer class.
struct derived_ptr_t : public smart_pointers::smart_ptr_t< derived_t >{
derived_ptr_t()
: smart_pointers::smart_ptr_t< derived_t >()
{}
explicit derived_ptr_t(derived_t* rep)
: smart_pointers::smart_ptr_t<derived_t>(rep)
{}
derived_ptr_t(const derived_ptr_t& r)
: smart_pointers::smart_ptr_t<derived_t>(r) {}
derived_ptr_t( const smart_pointers::smart_ptr_t< base_i >& r)
: smart_pointers::smart_ptr_t<derived_t>()
{
m_managed = static_cast<derived_t*>(r.get());
m_use_count = r.use_count_ptr();
if (m_use_count)
{
++(*m_use_count);
}
}
derived_ptr_t& operator=(const smart_pointers::smart_ptr_t< base_i >& r)
{
if (m_managed == static_cast<derived_t*>(r.get()))
return *this;
release();
m_managed = static_cast<derived_t*>(r.get());
m_use_count = r.use_count_ptr();
if (m_use_count)
{
++(*m_use_count);
}
return *this;
}
};
// Few functions that will be used to test custom smart pointer functionality
// from Python.
derived_ptr_t create_derived(){
return derived_ptr_t( new derived_t() );
}
smart_pointers::smart_ptr_t< base_i > create_base(){
return smart_pointers::smart_ptr_t< base_i >( new derived_t() );
}
// Next function could be exposed, but it could not be called from Python, when
// the argument is the instance of a derived class.
//
// This is the explanation David Abrahams gave:
// Naturally; there is no instance of smart_pointers::smart_ptr_t<base_i> anywhere in the
// Python object for the reference to bind to. The rules are the same as in C++:
//
// int f(smart_pointers::smart_ptr_t<base>& x);
// smart_pointers::smart_ptr_t<derived> y;
// int z = f(y); // fails to compile
inline int
ref_get_value( smart_pointers::smart_ptr_t< base_i >& a ){
return a->get_value();
}
inline int
val_get_value( smart_pointers::smart_ptr_t< base_i > a ){
return a->get_value();
}
inline int
const_ref_get_value( const smart_pointers::smart_ptr_t< base_i >& a ){
return a->get_value();
}
struct numeric_t{
numeric_t()
: value(0)
{}
int value;
};
smart_pointers::smart_ptr_t< numeric_t > create_numeric( int value ){
smart_pointers::smart_ptr_t< numeric_t > num( new numeric_t() );
num->value = value;
return num;
}
int get_numeric_value( smart_pointers::smart_ptr_t< numeric_t > n ){
if( n.get() ){
return n->value;
}
else{
return 0;
}
}
namespace shared_data{
// Boost.Python has small problem with user defined smart pointers and public
// member variables, exposed using def_readonly, def_readwrite functionality
// Read carefully "make_getter" documentation.
// http://boost.org/libs/python/doc/v2/data_members.html#make_getter-spec
// bindings.cpp contains solution to the problem.
struct buffer_t{
buffer_t() : size(0) {}
int size;
};
struct buffer_holder_t{
buffer_holder_t()
: data( new buffer_t() )
{}
smart_pointers::smart_ptr_t< buffer_t > get_data(){ return data; }
smart_pointers::smart_ptr_t< buffer_t > data;
};
}
#endif//classes_11_11_2006
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
149
]
]
] |
522ad9d6490761251b31dd19fcbb6655a84d8a13 | eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5 | /WinEditionWithJRE/browser-lcc/jscc/src/v8/v8/src/.svn/text-base/mksnapshot.cc.svn-base | 4cf088f39332edfe7ea732f6e466c6d524d867e2 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"Artistic-1.0",
"LicenseRef-scancode-public-domain",
"Artistic-2.0"
] | permissive | baxtree/OKBuzzer | c46c7f271a26be13adcf874d77a7a6762a8dc6be | a16e2baad145f5c65052cdc7c767e78cdfee1181 | refs/heads/master | 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,870 | // Copyright 2006-2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef COMPRESS_STARTUP_DATA_BZ2
#include <bzlib.h>
#endif
#include <signal.h>
#include <string>
#include <map>
#include "v8.h"
#include "bootstrapper.h"
#include "natives.h"
#include "platform.h"
#include "serialize.h"
#include "list.h"
// use explicit namespace to avoid clashing with types in namespace v8
namespace i = v8::internal;
using namespace v8;
static const unsigned int kMaxCounters = 256;
// A single counter in a counter collection.
class Counter {
public:
static const int kMaxNameSize = 64;
int32_t* Bind(const char* name) {
int i;
for (i = 0; i < kMaxNameSize - 1 && name[i]; i++) {
name_[i] = name[i];
}
name_[i] = '\0';
return &counter_;
}
private:
int32_t counter_;
uint8_t name_[kMaxNameSize];
};
// A set of counters and associated information. An instance of this
// class is stored directly in the memory-mapped counters file if
// the --save-counters options is used
class CounterCollection {
public:
CounterCollection() {
magic_number_ = 0xDEADFACE;
max_counters_ = kMaxCounters;
max_name_size_ = Counter::kMaxNameSize;
counters_in_use_ = 0;
}
Counter* GetNextCounter() {
if (counters_in_use_ == kMaxCounters) return NULL;
return &counters_[counters_in_use_++];
}
private:
uint32_t magic_number_;
uint32_t max_counters_;
uint32_t max_name_size_;
uint32_t counters_in_use_;
Counter counters_[kMaxCounters];
};
// We statically allocate a set of local counters to be used if we
// don't want to store the stats in a memory-mapped file
static CounterCollection local_counters;
typedef std::map<std::string, int*> CounterMap;
typedef std::map<std::string, int*>::iterator CounterMapIterator;
static CounterMap counter_table_;
class Compressor {
public:
virtual ~Compressor() {}
virtual bool Compress(i::Vector<char> input) = 0;
virtual i::Vector<char>* output() = 0;
};
class PartialSnapshotSink : public i::SnapshotByteSink {
public:
PartialSnapshotSink() : data_(), raw_size_(-1) { }
virtual ~PartialSnapshotSink() { data_.Free(); }
virtual void Put(int byte, const char* description) {
data_.Add(byte);
}
virtual int Position() { return data_.length(); }
void Print(FILE* fp) {
int length = Position();
for (int j = 0; j < length; j++) {
if ((j & 0x1f) == 0x1f) {
fprintf(fp, "\n");
}
if (j != 0) {
fprintf(fp, ",");
}
fprintf(fp, "%d", at(j));
}
}
char at(int i) { return data_[i]; }
bool Compress(Compressor* compressor) {
ASSERT_EQ(-1, raw_size_);
raw_size_ = data_.length();
if (!compressor->Compress(data_.ToVector())) return false;
data_.Clear();
data_.AddAll(*compressor->output());
return true;
}
int raw_size() { return raw_size_; }
private:
i::List<char> data_;
int raw_size_;
};
class CppByteSink : public PartialSnapshotSink {
public:
explicit CppByteSink(const char* snapshot_file) {
fp_ = i::OS::FOpen(snapshot_file, "wb");
if (fp_ == NULL) {
i::PrintF("Unable to write to snapshot file \"%s\"\n", snapshot_file);
exit(1);
}
fprintf(fp_, "// Autogenerated snapshot file. Do not edit.\n\n");
fprintf(fp_, "#include \"v8.h\"\n");
fprintf(fp_, "#include \"platform.h\"\n\n");
fprintf(fp_, "#include \"snapshot.h\"\n\n");
fprintf(fp_, "namespace v8 {\nnamespace internal {\n\n");
fprintf(fp_, "const byte Snapshot::data_[] = {");
}
virtual ~CppByteSink() {
fprintf(fp_, "const int Snapshot::size_ = %d;\n", Position());
#ifdef COMPRESS_STARTUP_DATA_BZ2
fprintf(fp_, "const byte* Snapshot::raw_data_ = NULL;\n");
fprintf(fp_,
"const int Snapshot::raw_size_ = %d;\n\n",
raw_size());
#else
fprintf(fp_,
"const byte* Snapshot::raw_data_ = Snapshot::data_;\n");
fprintf(fp_,
"const int Snapshot::raw_size_ = Snapshot::size_;\n\n");
#endif
fprintf(fp_, "} } // namespace v8::internal\n");
fclose(fp_);
}
void WriteSpaceUsed(
int new_space_used,
int pointer_space_used,
int data_space_used,
int code_space_used,
int map_space_used,
int cell_space_used,
int large_space_used) {
fprintf(fp_, "const int Snapshot::new_space_used_ = %d;\n", new_space_used);
fprintf(fp_,
"const int Snapshot::pointer_space_used_ = %d;\n",
pointer_space_used);
fprintf(fp_,
"const int Snapshot::data_space_used_ = %d;\n",
data_space_used);
fprintf(fp_,
"const int Snapshot::code_space_used_ = %d;\n",
code_space_used);
fprintf(fp_, "const int Snapshot::map_space_used_ = %d;\n", map_space_used);
fprintf(fp_,
"const int Snapshot::cell_space_used_ = %d;\n",
cell_space_used);
fprintf(fp_,
"const int Snapshot::large_space_used_ = %d;\n",
large_space_used);
}
void WritePartialSnapshot() {
int length = partial_sink_.Position();
fprintf(fp_, "};\n\n");
fprintf(fp_, "const int Snapshot::context_size_ = %d;\n", length);
#ifdef COMPRESS_STARTUP_DATA_BZ2
fprintf(fp_,
"const int Snapshot::context_raw_size_ = %d;\n",
partial_sink_.raw_size());
#else
fprintf(fp_,
"const int Snapshot::context_raw_size_ = "
"Snapshot::context_size_;\n");
#endif
fprintf(fp_, "const byte Snapshot::context_data_[] = {\n");
partial_sink_.Print(fp_);
fprintf(fp_, "};\n\n");
#ifdef COMPRESS_STARTUP_DATA_BZ2
fprintf(fp_, "const byte* Snapshot::context_raw_data_ = NULL;\n");
#else
fprintf(fp_, "const byte* Snapshot::context_raw_data_ ="
" Snapshot::context_data_;\n");
#endif
}
void WriteSnapshot() {
Print(fp_);
}
PartialSnapshotSink* partial_sink() { return &partial_sink_; }
private:
FILE* fp_;
PartialSnapshotSink partial_sink_;
};
#ifdef COMPRESS_STARTUP_DATA_BZ2
class BZip2Compressor : public Compressor {
public:
BZip2Compressor() : output_(NULL) {}
virtual ~BZip2Compressor() {
delete output_;
}
virtual bool Compress(i::Vector<char> input) {
delete output_;
output_ = new i::ScopedVector<char>((input.length() * 101) / 100 + 1000);
unsigned int output_length_ = output_->length();
int result = BZ2_bzBuffToBuffCompress(output_->start(), &output_length_,
input.start(), input.length(),
9, 1, 0);
if (result == BZ_OK) {
output_->Truncate(output_length_);
return true;
} else {
fprintf(stderr, "bzlib error code: %d\n", result);
return false;
}
}
virtual i::Vector<char>* output() { return output_; }
private:
i::ScopedVector<char>* output_;
};
#endif
int main(int argc, char** argv) {
#ifdef ENABLE_LOGGING_AND_PROFILING
// By default, log code create information in the snapshot.
i::FLAG_log_code = true;
#endif
// Print the usage if an error occurs when parsing the command line
// flags or if the help flag is set.
int result = i::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (result > 0 || argc != 2 || i::FLAG_help) {
::printf("Usage: %s [flag] ... outfile\n", argv[0]);
i::FlagList::PrintHelp();
return !i::FLAG_help;
}
i::Serializer::Enable();
Persistent<Context> context = v8::Context::New();
ASSERT(!context.IsEmpty());
// Make sure all builtin scripts are cached.
{ HandleScope scope;
for (int i = 0; i < i::Natives::GetBuiltinsCount(); i++) {
i::Isolate::Current()->bootstrapper()->NativesSourceLookup(i);
}
}
// If we don't do this then we end up with a stray root pointing at the
// context even after we have disposed of the context.
HEAP->CollectAllGarbage(true);
i::Object* raw_context = *(v8::Utils::OpenHandle(*context));
context.Dispose();
CppByteSink sink(argv[1]);
// This results in a somewhat smaller snapshot, probably because it gets rid
// of some things that are cached between garbage collections.
i::StartupSerializer ser(&sink);
ser.SerializeStrongReferences();
i::PartialSerializer partial_ser(&ser, sink.partial_sink());
partial_ser.Serialize(&raw_context);
ser.SerializeWeakReferences();
#ifdef COMPRESS_STARTUP_DATA_BZ2
BZip2Compressor compressor;
if (!sink.Compress(&compressor))
return 1;
if (!sink.partial_sink()->Compress(&compressor))
return 1;
#endif
sink.WriteSnapshot();
sink.WritePartialSnapshot();
sink.WriteSpaceUsed(
partial_ser.CurrentAllocationAddress(i::NEW_SPACE),
partial_ser.CurrentAllocationAddress(i::OLD_POINTER_SPACE),
partial_ser.CurrentAllocationAddress(i::OLD_DATA_SPACE),
partial_ser.CurrentAllocationAddress(i::CODE_SPACE),
partial_ser.CurrentAllocationAddress(i::MAP_SPACE),
partial_ser.CurrentAllocationAddress(i::CELL_SPACE),
partial_ser.CurrentAllocationAddress(i::LO_SPACE));
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
328
]
]
] |
|
12a14acfeb9716a65ba6050f06e4dc631a82ea2c | a0155e192c9dc2029b231829e3db9ba90861f956 | /Libs/mwnlm/Libraries/MSL C++/Include/deque.h | 7f4812d133b0c18904ed80e6c3415e0e28151080 | [] | no_license | zeha/mailfilter | d2de4aaa79bed2073cec76c93768a42068cfab17 | 898dd4d4cba226edec566f4b15c6bb97e79f8001 | refs/heads/master | 2021-01-22T02:03:31.470739 | 2010-08-12T23:51:35 | 2010-08-12T23:51:35 | 81,022,257 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 742 | h | /* Metrowerks Standard Library
* Copyright © 1995-2002 Metrowerks Corporation. All rights reserved.
*
* $Date: 2002/07/01 21:13:32 $
* $Revision: 1.3 $
*/
// deque.h // hh 971206 Changed filename from deque to deque.h
#ifndef _DEQUE_H // hh 971206 Made include guards standard
#define _DEQUE_H
#include <deque>
#ifndef _MSL_NO_CPP_NAMESPACE // hh 971206 Backward compatibility added with "using"
using std::deque;
#endif
#endif // _DEQUE_H
// hh 971206 Changed filename from deque to deque.h
// hh 971206 Made include guards standard
// hh 971206 Backward compatibility added with "using"
// hh 990120 changed name of MSIPL flags
// hh 991112 modified using policy
| [
"[email protected]"
] | [
[
[
1,
25
]
]
] |
e48f4d43b7f6b5362e4bca4efeeea84d3ec00459 | bbcd9d87dfc5b475763174dc00ba6fef76aca82d | /wiNstaller/ziparchive/include/ZipFileHeader.h | 33d6eedc543483d1de5fe09d5d2c256ebbd4ea5a | [] | no_license | wwxxyx/winstaller | 8cec98422fb18de2e65846e0562d3038a34ac14b | 722bda5b6687d50caa377ceedca7a222d5b04763 | refs/heads/master | 2020-05-24T07:50:29.060316 | 2007-09-13T05:43:05 | 2007-09-13T05:43:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,968 | h | ////////////////////////////////////////////////////////////////////////////////
// This source file is part of the ZipArchive library source distribution and
// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz
//
// 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.
//
// For the licensing details refer to the License.txt file.
//
// Web Site: http://www.artpol-software.com
////////////////////////////////////////////////////////////////////////////////
/**
* \file ZipFileHeader.h
* Includes the CZipFileHeader class.
*
*/
#if !defined(ZIPARCHIVE_ZIPFILEHEADER_DOT_H)
#define ZIPARCHIVE_ZIPFILEHEADER_DOT_H
#if _MSC_VER > 1000
#pragma once
#endif
#include "ZipExport.h"
#include "ZipStorage.h"
#include "ZipAutoBuffer.h"
#include "sys/types.h"
#include "ZipCompatibility.h"
#include "ZipCollections.h"
#include "ZipExtraField.h"
#include "ZipStringStoreSettings.h"
#include "ZipCryptograph.h"
class CZipCentralDir;
/**
Represents a single file stored in a zip archive.
*/
class ZIP_API CZipFileHeader
{
friend class CZipCentralDir;
friend class CZipArchive;
public:
CZipFileHeader();
CZipFileHeader(const CZipFileHeader& header)
{
*this = header;
}
CZipFileHeader& operator=(const CZipFileHeader& header);
virtual ~CZipFileHeader();
/**
Predicts the filename size after conversion using the current filename code page.
\return
The number of characters not including a terminating \c NULL character.
*/
int PredictFileNameSize() const
{
if (m_pszFileNameBuffer.IsAllocated())
return m_pszFileNameBuffer.GetSize();
CZipAutoBuffer buffer;
ConvertFileName(buffer);
return buffer.GetSize();
}
/**
Gets the comment size.
\return
The number of characters in the comment not including a terminating \c NULL character.
*/
WORD GetCommentSize() const {return (WORD)m_pszComment.GetSize();}
/**
Gets the filename. If necessary, performs the conversion using the current filename code page.
Caches the result of conversion for faster access the next time.
\param bClearBuffer
If \c true, releases the internal buffer after performing the filename conversion.
If \c false, the internal buffer is not released and both representations of the
filename are kept in memory (converted and not converted). This takes more memory, but the
conversion does not take place again when the central directory is written back to the archive.
\return
The converted filename.
\see
<a href="kb">0610051525</a>
\see
GetStringStoreSettings
\see
CZipStringStoreSettings::m_uNameCodePage
*/
CZipString& GetFileName(bool bClearBuffer = true);
/**
Sets the filename.
\param lpszFileName
The filename to set.
*/
void SetFileName(LPCTSTR lpszFileName);
/**
Gets the file comment.
\return
The file comment.
*/
CZipString GetComment() const;
/**
Sets the file comment.
\param lpszComment
The file comment.
*/
void SetComment(LPCTSTR lpszComment);
/**
Gets a value indicating whether the data descriptor is present or not.
\return
\c true, if the data descriptor is present; \c false otherwise.
*/
bool IsDataDescriptor()const { return (m_uFlag & (WORD) 8) != 0;}
/**
Gets the data descriptor size as it is required for the current file.
Takes into account various factors, such as the archive segmentation type,
encryption and the need for the Zip64 format.
\param pStorage
The storage to test for segmentation type.
\return
The required data descriptor size in bytes.
*/
WORD GetDataDescriptorSize(const CZipStorage* pStorage) const
{
return GetDataDescriptorSize(NeedsSignatureInDataDescriptor(pStorage));
}
/**
Gets the data descriptor size as it is required for the current file.
Takes into account various factors, such as the need for the data descriptor signature
or for the Zip64 format.
\param bConsiderSignature
\c true, if the data descriptor signature is needed; \c false otherwise.
\return
The required data descriptor size in bytes.
*/
WORD GetDataDescriptorSize(bool bConsiderSignature = false) const;
/**
Gets the size of the compressed data.
\param bUseLocal
If \c true, uses #m_uLocalComprSize; otherwise uses #m_uComprSize;
\param bReal
If \c true, the returned value does not include the encrypted information size, only the data size.
If \c false, the encrypted information size is added (you should not use this value
when the file exists in the archive).
\returns
The compressed data size in bytes.
\see
GetEncryptedInfoSize
*/
ZIP_SIZE_TYPE GetDataSize(bool bUseLocal = false, bool bReal = true) const
{
ZIP_SIZE_TYPE uSize = bUseLocal ? m_uLocalComprSize : m_uComprSize;
DWORD uEncrSize = GetEncryptedInfoSize();
return bReal ? (uSize - uEncrSize) : (uSize + uEncrSize);
}
/**
Gets the encrypted information size. The returned value depends on the used encryption method.
\return
The encrypted information size in bytes.
*/
DWORD GetEncryptedInfoSize() const
{
return CZipCryptograph::GetEncryptedInfoSize(m_uEncryptionMethod);
}
/**
Gets the total size of the structure in the central directory.
\return
The total size in bytes.
*/
DWORD GetSize()const;
/**
Gets the local header size. Before calling this method, the local information must be up-to-date
(see <a href="kb">0610242128|local</a> for more information).
\param bReal
If \c true, uses the real local filename size.
If \c false, predicts the filename size.
\return
The local header size in bytes.
*/
DWORD GetLocalSize(bool bReal) const;
/**
Gets a value indicating if the compression is efficient.
\return
\c true if the compression is efficient; \c false if the file should be
stored without the compression instead.
*/
bool CompressionEfficient()
{
ZIP_SIZE_TYPE uBefore = m_uUncomprSize;
// ignore the length of encryption info
ZIP_SIZE_TYPE uAfter = GetDataSize(false, true);
return uAfter <= uBefore;
}
/**
Gets the compression ratio.
\return
The compression ratio of the file.
*/
float GetCompressionRatio()
{
#if _MSC_VER >= 1300 || !defined(_ZIP64)
return m_uUncomprSize ? ((float)m_uComprSize * 100 ) / m_uUncomprSize: 0;
#else
return m_uUncomprSize ? ((float)(__int64)(m_uComprSize) / (float)(__int64)m_uUncomprSize) * 100: 0;
#endif
}
/**
Sets the file modification date.
\param ttime
The date to set. If this value is incorrect, the date defaults to January 1, 1980.
\see
GetTime
*/
void SetTime(const time_t& ttime);
/**
Gets the file modification time.
\return
The modification time.
\see
SetTime
*/
time_t GetTime()const;
/**
Gets the file system compatibility.
External software can use this information e.g. to determine end-of-line
format for text files etc.
The ZipArchive Library uses it to perform a proper file attributes conversion.
\return
The file system compatibility. Can be one of the ZipCompatibility::ZipPlatforms values.
\see
CZipArchive::GetSystemComatibility
\see
ZipPlatform::GetSystemID
*/
int GetSystemCompatibility()const
{
return (m_uVersionMadeBy & 0xFF00) >> 8;
}
/**
Gets the file attributes.
\return
The file attributes, converted if necessary to be compatible with the current system.
\note
- Throws an exception, if the archive system or the current system
is not supported by the ZipArchive Library.
- <strong>Linux version</strong>: after obtaining the attributes,
you need to shift them right by 16 bits.
\see
GetOriginalAttributes
*/
DWORD GetSystemAttr();
/**
Gets the original file attributes.
\return
The original file attributes as they are stored in the archive.
No conversion is performed.
\see
GetSystemAttr
*/
DWORD GetOriginalAttributes() const {return m_uExternalAttr;}
/**
Gets a value indicating whether the file represents a directory or not.
This method checks the file attributes. If the attributes value is zero,
the method checks for the presence of a path
separator at the end of the filename. If the path separator is present,
the file is assumed to be a directory.
\return
\c true, if the file represents a directory; \c false otherwise.
*/
bool IsDirectory();
/**
Gets the string store settings for the file.
\returns
The string store settings.
\see
<a href="kb">0610051525</a>
\see
CZipArchive::GetStringStoreSettings
*/
CZipStringStoreSettings GetStringStoreSettings()
{
return m_stringSettings;
}
/**
Gets a value indicating if the file is encrypted or not.
If the file is encrypted, you need to set the password with the
CZipArchive::SetPassword method before decompressing the file.
\return
\c true if the file is encrypted; \c false otherwise.
\see
CZipArchive::SetPassword
*/
bool IsEncrypted()const { return m_uEncryptionMethod != CZipCryptograph::encNone;}
/**
Gets the encryption method of the file.
\return
The file encryption method. Can be one of the CZipCryptograph::EncryptionMethod values.
*/
int GetEncryptionMethod() const {return m_uEncryptionMethod;}
/**
Gets a value indicating if the file is encrypted using WinZip AES encryption method or not.
\return
\c true, if the file is encrypted using WinZip AES encryption method; \c false otherwise.
*/
bool IsWinZipAesEncryption() const
{
return CZipCryptograph::IsWinZipAesEncryption(m_uEncryptionMethod);
}
/**
Gets an approximate file compression level.
\return
The compression level. May not be the real value used when compressing the file.
*/
int GetCompressionLevel() const;
/**
Returns the value indicating whether the current CZipFileHeader object has the time set or not.
\return
\c true, if the time is set; \c false otherwise.
*/
bool HasTime()
{
return m_uModTime != 0 || m_uModDate != 0;
}
static char m_gszSignature[]; ///< The central file header signature.
static char m_gszLocalSignature[]; ///< The local file header signature.
WORD m_uVersionMadeBy; ///< The "made by" version and the system compatibility.
WORD m_uVersionNeeded; ///< The version needed to extract the file.
WORD m_uFlag; ///< A general purpose bit flag.
WORD m_uMethod; ///< The compression method. Can be one of the CZipCompressor::CompressionMethod values.
WORD m_uModTime; ///< The file last modification time.
WORD m_uModDate; ///< The file last modification date.
DWORD m_uCrc32; ///< The crc-32 value.
ZIP_SIZE_TYPE m_uComprSize; ///< The compressed size.
ZIP_SIZE_TYPE m_uUncomprSize; ///< The uncompressed size.
ZIP_PART_TYPE m_uDiskStart; ///< The disk number at which the compressed file starts.
WORD m_uInternalAttr; ///< Internal file attributes.
ZIP_SIZE_TYPE m_uLocalComprSize; ///< The compressed size written in the local header.
ZIP_SIZE_TYPE m_uLocalUncomprSize; ///< The uncompressed size written in the local header.
ZIP_SIZE_TYPE m_uOffset; ///< Relative offset of the local header with respect to #m_uDiskStart.
CZipExtraField m_aLocalExtraData; ///< The local extra field. Do not modify after you have started compressing the file.
CZipExtraField m_aCentralExtraData; ///< The central extra field.
protected:
DWORD m_uExternalAttr; ///< External file attributes.
WORD m_uLocalFileNameSize; ///< The local filename length.
BYTE m_uEncryptionMethod; ///< The file encryption method. Can be one of the CZipCryptograph::EncryptionMethod values.
bool m_bIgnoreCrc32; ///< A value indicating whether to ignore Crc32 checking or not.
/**
Sets the file system compatibility.
\param iSystemID
The file system compatibility. Can be one of the ZipCompatibility::ZipPlatforms values.
\see
GetSystemCompatibility
*/
void SetSystemCompatibility(int iSystemID)
{
m_uVersionMadeBy &= 0x00FF;
m_uVersionMadeBy |= (WORD)(iSystemID << 8);
}
/**
Sets the file attributes.
To set the attributes of this structure use the CZipArchive::SetFileHeaderAttr method.
\param uAttr
The attributes to set.
\note
Throws exceptions, if the archive system or the current system
is not supported by the ZipArchive Library.
\see
CZipArchive::SetFileHeaderAttr
\see
GetSystemAttr
*/
void SetSystemAttr(DWORD uAttr);
/**
Prepares the filename for writing to the archive.
*/
void PrepareFileName()
{
if (m_pszFileNameBuffer.IsAllocated() || m_pszFileName == NULL)
return;
ConvertFileName(m_pszFileNameBuffer);
}
/**
Validates an existing data descriptor after file decompression.
\param pStorage
The storage to read the data descriptor from.
\return
\c true, if the data descriptor is valid; \c false otherwise.
*/
bool CheckDataDescriptor(CZipStorage* pStorage) const;
/**
Prepares the data for writing when adding a new file. When Zip64 extensions are required for this file,
this method adds Zip64 extra data to #m_aLocalExtraData.
\param iLevel
The compression level.
\param bSegm
Set to \c true, if the archive is segmented; \c false otherwise.
*/
void PrepareData(int iLevel, bool bSegm);
/**
Writes the local file header to the \a pStorage.
The filename and extra field are the same as those that will be stored in the central directory.
\param pStorage
The storage to write the local file header to.
\note
Throws exceptions.
*/
void WriteLocal(CZipStorage *pStorage);
/**
Reads the local file header from an archive and validates the read data.
\param centralDir
The current central directory.
\return
\c true, if read data is consistent; \c false otherwise.
\note
Throws exceptions.
\see
CZipArchive::SetIgnoredConsistencyChecks
*/
bool ReadLocal(CZipCentralDir& centralDir);
/**
Writes the central file header to \a pStorage.
\param pStorage
The storage to write the central file header to.
\return
The size of the file header.
\note
Throws exceptions.
*/
DWORD Write(CZipStorage *pStorage);
/**
Reads the central file header from \a pStorage and validates the read data.
\param centralDir
The current central directory.
\param bReadSignature
\c true, if the the central header signature should be read; \c false otherwise.
\return
\c true, if the read data is consistent; \c false otherwise.
\note
Throws exceptions.
*/
bool Read(CZipCentralDir& centralDir, bool bReadSignature);
/**
Validates the member fields lengths.
The tested fields are: filename, extra fields and comment.
\return
\c false, if any of the lengths exceeds the allowed value.
*/
bool CheckLengths(bool local) const
{
if (m_pszComment.GetSize() > USHRT_MAX || m_pszFileNameBuffer.GetSize() > USHRT_MAX)
return false;
else if (local)
return m_aLocalExtraData.Validate();
else
return m_aCentralExtraData.Validate();
}
/**
Writes the Crc32 to \a pBuf.
\param pBuf
The buffer to write the Crc32 to. Must have be of at least 4 bytes size.
*/
void WriteCrc32(char* pBuf) const;
/**
Gets a value indicating whether the file needs the data descriptor.
The data descriptor is needed when a file is encrypted or the Zip64 format needs to be used.
\return
\c true, if the data descriptor is needed; \c false otherwise.
*/
bool NeedsDataDescriptor() const;
/**
Writes the data descriptor.
\param pDest
The buffer to receive the data.
\param bLocal
Set to \c true, if the local sizes are used; \c false otherwise.
*/
void WriteSmallDataDescriptor(char* pDest, bool bLocal = true);
/**
Writes the data descriptor taking into account the Zip64 format.
\param pStorage
The storage to write the data descriptor to.
*/
void WriteDataDescriptor(CZipStorage* pStorage);
bool NeedsSignatureInDataDescriptor(const CZipStorage* pStorage) const
{
return pStorage->IsSegmented() != 0 || IsEncrypted();
}
/**
Updates the local header in the archive after is has already been written.
\param pStorage
The storage to update the data descriptor in.
*/
void UpdateLocalHeader(CZipStorage* pStorage);
/**
Verifies the central header signature.
\param buf
The buffer that contains the signature to verify.
\return
\c true, if the signature is valid; \c false otherwise.
*/
static bool VerifySignature(CZipAutoBuffer& buf)
{
return memcmp(buf, m_gszSignature, 4) == 0;
}
/**
Updates the general purpose bit flag.
\param bSegm
\c true, if the current archive is a segmented archive; \c false otherwise.
*/
void UpdateFlag(bool bSegm)
{
if (bSegm || m_uEncryptionMethod == CZipCryptograph::encStandard)
m_uFlag |= 8; // data descriptor present
if (IsEncrypted())
m_uFlag |= 1; // encrypted file
}
private:
/**
Sets the "made by" version.
\param uVersion
The version to set.
*/
void SetVersion(WORD uVersion)
{
if ((m_uVersionMadeBy & 0x00FF) != (uVersion & 0x00FF))
{
m_uVersionMadeBy &= 0xFF00;
m_uVersionMadeBy |= (WORD)(uVersion & 0x00FF);
}
}
void ConvertFileName(CZipAutoBuffer& buffer) const;
void ConvertFileName(CZipString& szFileName) const;
void ClearFileName()
{
if (m_stringSettings.m_bStoreNameInExtraData)
// we are keeping m_pszFileName, clear the buffer, we need the original, when writing extra header and when accessing the filename
m_pszFileNameBuffer.Release();
else if (m_pszFileName != NULL)
{
delete m_pszFileName;
m_pszFileName = NULL;
}
}
void GetCrcAndSizes(char* pBuffer)const;
bool NeedsZip64() const
{
return m_uComprSize >= UINT_MAX || m_uUncomprSize >= UINT_MAX || m_uDiskStart >= USHRT_MAX || m_uOffset >= UINT_MAX;
}
void OnNewFileClose(CZipStorage* pStorage)
{
UpdateLocalHeader(pStorage);
WriteDataDescriptor(pStorage);
pStorage->Flush();
}
CZipAutoBuffer m_pszFileNameBuffer;
CZipString* m_pszFileName;
CZipStringStoreSettings m_stringSettings;
CZipAutoBuffer m_pszComment;
};
#endif // !defined(ZIPARCHIVE_ZIPFILEHEADER_DOT_H)
| [
"[email protected]"
] | [
[
[
1,
708
]
]
] |
b34b50fd0061897195417feeb80cf6c467769650 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Kenwalt/KW_SMDK1/SMDK_Precip.cpp | 30949aa12ce088b47af6e9050e6d5b86965d9820 | [] | 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 | 23,231 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "smdk_precip.h"
//====================================================================================
//#pragma optimize("", off)
static MInitialiseTest InitTest("SMDK_Precip");
static MAqSpeciePtr spAlumina (InitTest, "Al2O3(l)", false);
static MSpeciePtr spWater (InitTest, "H2O(l)", false);
static MAqSpeciePtr spTHA (InitTest, "Al2O3.3H2O(s)", false);
static MAqSpeciePtr spCausticSoda (InitTest, "NaOH(l)", false);
static MSpeciePtr spOccSoda (InitTest, "Na2O(s)", false);
static MAqSpeciePtr spSodiumCarbonate (InitTest, "Na2CO3(l)", false);
//static MAqSpeciePtr spSodiumOxalate (InitTest, "Na2C2O4(l)", false);
enum GrowthRateMethods { GRM_White, GRM_Cresswell, GRM_WhiteBateman };
enum SodaPrecipMethods { SPM_Sang, SPM_Ohkawa };
enum ThermalHeatLossMethods { THL_None, THL_TempDrop, THL_FixedHeatFlow, THL_HeatFlowFrac };
enum ReactionHeatMethods { RHM_Calc, RHM_Override1 };
//====================================================================================
const long idFeed = 0;
const long idProd = 1;
static MInOutDefStruct s_IODefs[]=
{
// Desc; Name; PortId; Rqd; Max; CnId, FracHgt; Options;
{ "Feed", "Feed", idFeed, 1, 10, 0, 1.0f, MIO_In |MIO_Material },
{ "Product", "Prod", idProd, 1, 1, 0, 1.0f, MIO_Out|MIO_Material },
{ NULL },
};
static double Drw_CPrecipitator[] =
{
MDrw_Poly, -5,10, -5,-10, 5,-10, 5,10,
MDrw_End
};
//---------------------------------------------------------------------------
DEFINE_TRANSFER_UNIT(CPrecipitator, "Precipitator", DLL_GroupName)
void CPrecipitator_UnitDef::GetOptions()
{
SetDefaultTag("PC", true);
SetDrawing("Tank", Drw_CPrecipitator);
SetTreeDescription("Demo:Precipitator");
SetDescription("TODO: A description");
SetModelSolveMode(MSolveMode_Probal);
SetModelGroup(MGroup_Alumina);
SetModelLicense(MLicense_HeatExchange|MLicense_Alumina);
};
//---------------------------------------------------------------------------
CPrecipitator::CPrecipitator(MUnitDefBase * pUnitDef, TaggedObject * pNd) : MBaseMethod(pUnitDef, pNd)
{
//default values...
bOnLine = 1;
dTempDropRqd = 0.5;
dThermalLossRqd = 1500.0;
dThermalLossFrac = 0.0002;
iGrowthRateMethod = GRM_Cresswell;
iSodaPrecipMethod = SPM_Ohkawa;
iThermalLossMethod = THL_TempDrop;
iRctHeatMethod = RHM_Calc;
dHOR_a = 400.0;
dHOR_b = 1.0;
ER_White = 7200.0;
ER_Cresswell = 7600.0;
ER_WhBateman = 8500.0;
K_White = 1.96e10;
K_Cresswell = 15.0;
K_WhBateman = 7.4e12;
gF_White = 1.0;
gF_Cresswell = 1.0;
gF_WhBateman = 1.0;
Tref = 343.25;
KSoda_Sang = 0.000474;
KSoda_Ohkawa = 0.00127;
m_AOutEst = dNAN;
m_TOutEst = dNAN;
m_xPrev = dNAN;
m_XSodaPrev = dNAN;
dTankVol = 1000.0;
dSolPrecip = 0.0;
dOccSoda = 0.0;
dGrowthRate = 0.0;
dGrowthRateFactor = 0.0;
dYield = 0.0;
dTin = C2K(25.0);
dTout = C2K(25.0);
dDiamin = 0.0;
dDiamout = 0.0;
dSALin = 0.0;
dSALout = 0.0;
dQvin = 0.0;
dQvout = 0.0;
dACin = 0.0;
dACout = 0.0;
dASat = 0.0;
dResidenceTime = 0.0;
dThermalLoss = 0.0;
dThermTempDrop = 0.0;
dReactionHeat = 0.0;
}
//---------------------------------------------------------------------------
CPrecipitator::~CPrecipitator()
{
}
//---------------------------------------------------------------------------
void CPrecipitator::Init()
{
SetIODefinition(s_IODefs);
}
//---------------------------------------------------------------------------
const long OM_Simple = 0;
const long OM_Condensing = 1;
void CPrecipitator::BuildDataFields()
{
static MDDValueLst DDB1[]={
{GRM_White, "White"},
{GRM_Cresswell,"Cresswell"},
{GRM_WhiteBateman,"WhiteBateman"},
{0}};
static MDDValueLst DDB2[]={
{SPM_Sang, "Sang"},
{SPM_Ohkawa,"Ohkawa"},
{0}};
static MDDValueLst DDB3[]={
{THL_None, "None" },
{THL_TempDrop, "TempDrop"},
{THL_FixedHeatFlow, "FixedLoss"},
{THL_HeatFlowFrac, "LossFraction"},
{0}};
static MDDValueLst DDB4[]={
{RHM_Calc, "Calculated" },
{RHM_Override1, "Override1"},
{0}};
DD.Text ("");
DD.CheckBox("On", "", &bOnLine, MF_PARAMETER|MF_SET_ON_CHANGE);
DD.Text("");
DD.Text ("Requirements");
DD.Double("TankVol", "", &dTankVol ,MF_PARAMETER, MC_Vol("m^3"));
DD.Long ("GrowthMethod", "", (long*)&iGrowthRateMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB1);
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_Cresswell);
DD.Double("ER_Cresswell", "", &ER_Cresswell ,MF_PARAMETER, MC_T("K"));
DD.Double("Tref", "", &Tref ,MF_PARAMETER|MF_INIT_HIDDEN, MC_T("K"));
DD.Double("K_Cresswell", "", &K_Cresswell ,MF_PARAMETER, MC_);
DD.Double("gF_Cresswell", "", &gF_Cresswell ,MF_PARAMETER, MC_);
DD.Show(iGrowthRateMethod==GRM_WhiteBateman);
DD.Double("ER_WhiteBateman", "", &ER_WhBateman ,MF_PARAMETER, MC_T("K"));
DD.Double("K_WhiteBateman", "", &K_WhBateman ,MF_PARAMETER, MC_);
DD.Double("gF_WhiteBateman", "", &gF_WhBateman ,MF_PARAMETER, MC_);
DD.Show();
DD.Long ("SodaPrecipMethod", "", &iSodaPrecipMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB2);
DD.Show(iSodaPrecipMethod==SPM_Sang);
DD.Double("Ksoda_Sang", "", &KSoda_Sang ,MF_PARAMETER, MC_);
DD.Show(iSodaPrecipMethod==SPM_Ohkawa);
DD.Double("Ksoda_Ohkawa", "", &KSoda_Ohkawa ,MF_PARAMETER, MC_);
DD.Show();
DD.Long ("ReactionHeatMethod", "",&iRctHeatMethod ,MF_PARAMETER|MF_SET_ON_CHANGE, DDB4);
DD.Show(iRctHeatMethod==RHM_Override1);
DD.Double("HOR_a", "", &dHOR_a ,MF_PARAMETER, MC_);
DD.Double("HOR_b", "", &dHOR_b ,MF_PARAMETER, MC_);
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_HeatFlowFrac);
DD.Double("ThermalLossFrac", "", &dThermalLossFrac ,MF_PARAMETER, MC_Frac("%"));
DD.Show();
DD.Text ("");
DD.Text ("Results Tank");
DD.Double("ResidenceTime", "", &dResidenceTime ,MF_RESULT, MC_Time("h"));
DD.Double("Yield", "", &dYield ,MF_RESULT, MC_Conc("kg/m^3"));
DD.Double("THAPrecip", "", &dSolPrecip ,MF_RESULT, MC_Qm("kg/s"));
DD.Double("OccludedSoda", "", &dOccSoda ,MF_RESULT, MC_Qm("kg/s"));
DD.Text ("Results");
DD.Show();
DD.Double("ASat", "", &dASat ,MF_RESULT, MC_Conc("g/L"));
DD.Double("GrowthRateFactor", "", &dGrowthRateFactor,MF_RESULT, MC_Ldt("m/s"));
DD.Double("GrowthRate", "", &dGrowthRate ,MF_RESULT, MC_);
DD.Show();
DD.Double("ACin", "", &dACin ,MF_RESULT, MC_);
DD.Double("ACout", "", &dACout ,MF_RESULT, MC_);
DD.Double("TempIn", "", &dTin ,MF_RESULT, MC_T("C"));
DD.Double("TempOut", "", &dTout ,MF_RESULT, MC_T("C"));
DD.Double("ReactionHeat", "", &dReactionHeat ,MF_RESULT|MF_INIT_HIDDEN, MC_Pwr("kW"));
DD.Double("ThermalLoss", "", &dThermalLoss ,MF_RESULT, MC_Pwr("kW"));
DD.Double("ThermalTempDrop", "", &dThermTempDrop ,MF_RESULT, MC_dT("C"));
DD.Double("PartDiamIn", "", &dDiamin ,MF_RESULT, MC_L("um"));
DD.Double("PartDiamOut", "", &dDiamout ,MF_RESULT, MC_L("um"));
DD.Double("SeedSurfAreaLIn", "", &dSALin ,MF_RESULT|MF_INIT_HIDDEN, MC_SurfAreaL("m^2/L"));
DD.Double("SeedSurfAreaLOut", "", &dSALout ,MF_RESULT|MF_INIT_HIDDEN, MC_SurfAreaL("m^2/L"));
DD.Double("Vol_FlowIn", "", &dQvin ,MF_RESULT, MC_Qv("L/s"));
DD.Double("Vol_FlowOut", "", &dQvout ,MF_RESULT, MC_Qv("L/s"));
DD.Double("AOutEst", "", &m_AOutEst ,MF_PARAMETER|MF_NO_VIEW, MC_);
DD.Text("");
}
//---------------------------------------------------------------------------
bool CPrecipitator::ValidateDataFields()
{//ensure parameters are within expected ranges
Tref = Range(C2K(20.0), Tref, C2K(110.0));
return true;
}
//---------------------------------------------------------------------------
void CPrecipitator::AdjustMasses(MVector & Prod, double & x, double SodaFac)
{
MVDouble AluminaMass(Prod, spAlumina); // Al2O3
MVDouble WaterMass (Prod, spWater); // H2O
MVDouble THAMass (Prod, spTHA); // Al2O3.3H2O
MVDouble CausticMass (Prod, spCausticSoda); // NaOH
MVDouble Na2OMass (Prod, spOccSoda); // Na2O
const double MW_H2O = spWater.MW; //18.0152800
const double MW_Na2O = spOccSoda.MW; //61.9789360
const double MW_NaOH = spCausticSoda.MW; //39.9971080
const double MW_Al2O3 = spAlumina.MW; //101.961278
const double MW_Al2O3_3H2O= spTHA.MW; //156.007118
const double FacAl = MW_Al2O3/MW_Al2O3_3H2O; //Alpha = 0.6538; // Ratio of molecular weights (Al2O3/Al2O3.3H2O)
double XSoda = x/100.0*SodaFac;
if (fabs(XSoda)>1.0e-9)
{
//check for limit problem (specie availability)...
if (Na2OMass + XSoda<1e-9)
{ //set to limit
XSoda = 1e-9 - Na2OMass;
x = XSoda*100.0/SodaFac;
}
if (CausticMass - (MW_NaOH*2)/MW_Na2O*XSoda<1e-12)
{ //set to limit
XSoda = (CausticMass - 1e-12)*MW_Na2O/(MW_NaOH*2);
if (Na2OMass + XSoda<1e-9)
XSoda = 1e-9 - Na2OMass;
x = XSoda*100.0/SodaFac;
}
}
//adjust masses...
AluminaMass = AluminaMass - FacAl*x;
THAMass = THAMass + x;
WaterMass = WaterMass - (1.0-FacAl)*x + MW_H2O/MW_Na2O*XSoda;
CausticMass = CausticMass - (MW_NaOH*2)/MW_Na2O*XSoda;
Na2OMass = Na2OMass + XSoda;
}
//---------------------------------------------------------------------------
double CPrecipitator::PerformAluminaSolubility(MVector & Prod, double TRqd, double ARqd, double SSat, double Cin, bool & ConvergeErr)
{
// 2 AlO2 + 4 H2O <==> Al2O3.3H2O + 2 OH
//or Na2O + Al2O3 + 4 H2O <==> Al2O3.3H2O + 2 NaOH
// x is the Fraction of Alumina which precipitates as the hydrate
// ie x is deposition rate of new THA crystal
bool AdjustT=!Valid(TRqd);
double T = AdjustT ? Prod.T : TRqd;
MIBayer & ProdB=*Prod.FindIF<MIBayer>();
double A = ProdB.AluminaConc(T);
const double AluminaMass = Prod.MassVector[spAlumina]; // Al2O3
const double MW_Al2O3 = spAlumina.MW; //101.961278
const double MW_Al2O3_3H2O= spTHA.MW; //156.007118
const double FacAl = MW_Al2O3/MW_Al2O3_3H2O; //Alpha = 0.6538; // Ratio of molecular weights (Al2O3/Al2O3.3H2O)
const double ESoda = 2535.0; //constant 2535K
const double KSodaFac = (iSodaPrecipMethod==SPM_Sang ? KSoda_Sang : KSoda_Ohkawa);
for (int Iter=100; Iter; Iter--)
{
double x = AluminaMass*(1.0-ARqd/GTZ(A))/FacAl;
//Soda Precipitation...
double SodaFac;
if (Valid(Cin))
{//Sang
const double xx = SSat*Cin;
SodaFac = KSodaFac*xx*xx;
}
else
{//Ohkawa, Tsuneizumi and Hirao
SodaFac = KSodaFac*exp(ESoda/T)*SSat*SSat;
}
AdjustMasses(Prod, x, SodaFac);
if (iRctHeatMethod==RHM_Override1)
{
Prod.MarkStateChanged(); //this forces recalculation of temperature / enthalpy based on new stream makeup
Prod.SetTP(T, Prod.P);
}
else
{
Prod.MarkStateChanged(); //this forces recalculation of temperature / enthalpy based on new stream makeup
if (AdjustT)
T=Prod.T;
}
A = ProdB.AluminaConc(T);
if (fabs(A-ARqd)<1.0e-12)
break;
if (fabs(x)<1e-22)
{//problem!!!
Iter=0;
break;
}
}
ConvergeErr = (Iter==0);
return ProdB.AluminaConc(T);
}
//---------------------------------------------------------------------------
void CPrecipitator::DoPrecip(MVector & Prod)
{
MIBayer & ProdB=*Prod.FindIF<MIBayer>();
//MIPSD & ProdSz = *Prod.FindIF<MIPSD>();
MISSA & ProdSSA = *Prod.FindIF<MISSA>();
//Log.SetCondition(IsNothing(ProdSz), 2, MMsg_Error, "Bad Feed Stream - No Size Distribution");
Log.SetCondition(IsNothing(ProdSSA), 3, MMsg_Error, "Bad Feed Stream - No SSA Data");
double LiqIn = Prod.Mass(MP_Liq); // kg/s
double SolIn = Prod.Mass(MP_Sol); // kg/s
double THAIn = Prod.MassVector[spTHA]; // kg/s
double OcNaIn = Prod.MassVector[spOccSoda]; // kg/s
double Al2O3In = Prod.MassVector[spAlumina]; // kg/s
double T = Prod.T; // temperature (K)
double P = Prod.P;
double Hfin = Prod.totHf(MP_All, T, P);
double CpIn = Prod.totCp(MP_All, T, P);
double Qvin = Prod.Volume(MP_Liq)*3600.0; // Liquor volumetric flow rate @ T (m3/h)
double Qvin25 = Prod.Volume(MP_Liq, C2K(25.0), P)*3600.0; // m3/h
double Ain = ProdB.AluminaConc(T); //Al2O3
double Cin = ProdB.CausticConc(T);
double Sin = ProdB.SodaConc(T);
double ASat = ProdB.AluminaConcSat(T); // Equilibrium Al2O3 liquor concentration @ T
double Rhos = ProdB.THADens(T);
double SSat = (Ain-ASat)/GTZ(Cin);
double NoPerSec= IsNothing(ProdSSA) ? 0.0 : ProdSSA.PartNumPerSec();
dTin = T;
dACin = ProdB.AtoC();
dQvin = Prod.Volume();
if (!IsNothing(ProdSSA))
{
dSALin = ProdSSA.SpecificSurfaceAreaVol(); // m^2/L
dDiamin = ProdSSA.PartDiamFromSAM();
}
if (!IsNothing(ProdSSA) && SSat > 1.0e-6)
{
const double MW_H2O = spWater.MW; //18.0152800
const double MW_Na2O = spOccSoda.MW; //61.9789360
const double MW_Al2O3 = spAlumina.MW; //101.961278
const double MW_Al2O3_3H2O= spTHA.MW; //156.007118
const double MW_NaOH = spCausticSoda.MW; //39.9971080
//const double MW_Na2C2O4 = spSodiumOxalate.MW; //133.999136
const double MW_Na2CO3 = spSodiumCarbonate.MW; //105.989
const double FacAl = MW_Al2O3/MW_Al2O3_3H2O; //Alpha = 0.6538; // Ratio of molecular weights (Al2O3/Al2O3.3H2O)
const double AluminaMass_in = Prod.MassVector[spAlumina]; // kg/s Al2O3
const double Na2OMass_in = Prod.MassVector[spOccSoda]; // kg/s Na2O
//The growth and SodaFactor equations are using C, etc as Na2CO3 equivilant,
//shouldn't they be as Na2O equivilant!!!
const double Alpha = FacAl; //102./156.;
double Cin_ = (iSodaPrecipMethod==SPM_Sang ? Cin*MW_Na2O/MW_Na2CO3 : dNAN);
SSat = (Ain-ASat)/GTZ(Cin*MW_Na2O/MW_Na2CO3); //Na2O equiv
bool bUsePrevAsEstimate = false;
if (bUsePrevAsEstimate)
{//THIS FAILS!!!
if (!Valid(m_TOutEst))
m_TOutEst = T;
if (Valid(m_xPrev) && Valid(m_XSodaPrev))
AdjustMasses(Prod, m_xPrev, m_XSodaPrev); //based on previous solution
if (!Valid(m_AOutEst) || m_AOutEst<1e-6)
m_AOutEst = 0.98*Ain;
}
else
{
m_TOutEst = T;
m_AOutEst = ((ASat+Ain)/2.0)*1.01;
}
bool ConvergeErr;
m_AOutEst = PerformAluminaSolubility(Prod, m_TOutEst, m_AOutEst, SSat, Cin_, ConvergeErr);
if (NoPerSec>0.0)
{
ProdSSA.SetSAMFromFlow(ProdB.THAMassFlow(), NoPerSec);
}
//----------------------------------------
double V = dTankVol*1000.0; // Liters
double Qvout25, Cout, AoutPrev, Afact;
int ZeroCnt=0;
for (int Iter=100; Iter; Iter--)
{
T = Prod.T; // K
Cout = ProdB.SodaConc(T)*MW_Na2O/MW_Na2CO3; //Na2O equiv
AoutPrev = m_AOutEst;
Qvout25 = (Alpha*Rhos-Ain)/(Alpha*Rhos-m_AOutEst)*Qvin25;
Afact = Sqr((m_AOutEst-ASat)/GTZ(Cout));
if (iGrowthRateMethod==GRM_White)
{
double x = Exps(-ER_White/T);
dGrowthRateFactor = gF_White*K_White*x;
}
else if (iGrowthRateMethod==GRM_Cresswell)
{
double C25 = ProdB.CausticConc(C2K(25.0)); // Caustic concentration @ 25C (gNa2CO3/l)
double m_C25 = C25*MW_Na2O/MW_Na2CO3; // Caustic concentration @ 25C (gNa2O/l)
double x = Exps(-ER_Cresswell*((1.0/T)-(1.0/Tref)));
dGrowthRateFactor = gF_Cresswell*K_Cresswell*x/sqrt(m_C25/100.0);
}
else if (iGrowthRateMethod==GRM_WhiteBateman)
{
double C25 = ProdB.CausticConc(C2K(25.0)); // Caustic concentration @ 25C (gNa2CO3/l)
double m_C25 = C25*MW_Na2O/MW_Na2CO3; // Caustic concentration @ 25C (gNa2O/l)
double x = Exps(-ER_WhBateman/T);
dGrowthRateFactor = gF_WhBateman*K_WhBateman*x/sqrt(m_C25);
}
dGrowthRate = dGrowthRateFactor*Afact;
m_AOutEst = (Qvin25*Ain - dGrowthRate*dSALin/1000.0*V)/GTZ(Qvout25);
m_AOutEst = GTZ(0.5*(m_AOutEst+AoutPrev));
//Should SSat be recalulated as (Aout-ASat)/GTZ(Cout) ? (or does Afact effectively do this?)
m_AOutEst = PerformAluminaSolubility(Prod, T, m_AOutEst, SSat, Cin_, ConvergeErr);
if (NoPerSec>0.0)
{
ProdSSA.SetSAMFromFlow(ProdB.THAMassFlow(), NoPerSec);
}
if (iRctHeatMethod==RHM_Override1)
{
//NB: msCp * MassFlow = totCp
double Cp = Prod.totCp(MP_All, T, P);
double THAOut = Prod.MassVector[spTHA];
double SolPrecip = THAOut - THAIn; //kg/s
double CalcHOR = dHOR_a + (dHOR_b * K2C(T)); //kJ/kg
double enthIn = CpIn * K2C(dTin);
double NewT = (SolPrecip*CalcHOR + enthIn) / Cp;
Prod.SetTP(C2K(NewT), P);
}
if (fabs(m_AOutEst-AoutPrev)<1.0e-9*Ain)
{
m_TOutEst = T;
const double AluminaMass_out = Prod.MassVector[spAlumina]; // Al2O3
m_xPrev = (AluminaMass_in - AluminaMass_out)/FacAl;
const double Na2OMass_out = Prod.MassVector[spOccSoda]; // Na2O
m_XSodaPrev = (Na2OMass_out - Na2OMass_in);
break;//found a solution!
}
if (m_AOutEst<1e-6)
ZeroCnt++;
if (ZeroCnt>3)
Iter = 1; //problem...
}
Log.SetCondition(Iter==0, 4, MMsg_Warning, "A at outlet not converging");
Log.SetCondition(m_AOutEst<1.0e-6, 5, MMsg_Warning, "A at outlet is zero");
Log.SetCondition(ConvergeErr, 6, MMsg_Warning, "Cannot converge PrecipTHA Alumina Conc");
}
//----------------------------------------
//calculate reaction heat...
//double H0 = Bm.totHf(MP_All, dTin, P);
double H0 = Prod.totHf(MP_All, T, P);
dReactionHeat = Hfin - H0;
// apply Thermal Losses after precipitation...
double T1;
double H1 = Prod.totHf(MP_All, Prod.T, P);
switch (iThermalLossMethod)
{
case THL_None:
dThermalLoss = 0.0;
dThermTempDrop = 0.0;
break;
case THL_TempDrop:
Prod.SetTP(Prod.T-dTempDropRqd, P);
dThermalLoss = H1 - Prod.totHf(MP_All, Prod.T, P);
dThermTempDrop = dTempDropRqd;
break;
case THL_FixedHeatFlow:
T1 = Prod.T;
Prod.Set_totHf(H1-dThermalLossRqd);
dThermalLoss = dThermalLossRqd;
dThermTempDrop = T1-Prod.T;
break;
case THL_HeatFlowFrac:
T1 = Prod.T;
dThermalLoss = -Hfin*dThermalLossFrac;
Prod.Set_totHf(H1-dThermalLoss);
dThermTempDrop = T1-Prod.T;
break;
}
//results...
dResidenceTime = dTankVol/GTZ(Prod.Volume(MP_SL)); // Hours
dTout = Prod.T;
dSALout = (IsNothing(ProdSSA) ? 0.0 : ProdSSA.SpecificSurfaceAreaVol());
dDiamout = (IsNothing(ProdSSA) ? 0.0 : ProdSSA.PartDiamFromSAM());
dACout = ProdB.AtoC();
double Cout = ProdB.CausticConc(Prod.T);
dYield = Cout*(dACin-dACout);
dASat = ProdB.AluminaConcSat(Prod.T);
dQvout = Prod.Volume();
double SolOut = Prod.Mass(MP_Sol);
double THAOut = Prod.MassVector[spTHA];
double OcNaOut = Prod.MassVector[spOccSoda];
dSolPrecip = THAOut - THAIn;
dOccSoda = OcNaOut - OcNaIn;
}
//---------------------------------------------------------------------------
void CPrecipitator::EvalProducts()
{
try
{
MStreamI Feed;
FlwIOs.AddMixtureIn_Id(Feed, idFeed);
MStream & Prod = FlwIOs[FlwIOs.First[idProd]].Stream; //get reference to the actual output stream
Prod = Feed;
dThermalLoss = 0.0;
dYield = 0.0;
dSALin = 0.0;
dDiamin = 0.0;
MIBayer & ProdB=*Prod.FindIF<MIBayer>();
bool IsOff = true;
if (bOnLine)
{
Log.SetCondition(IsNothing(ProdB), 1, MMsg_Warning, "Bad Feed Stream - Not Bayer Model"); //expect stream to have bayer properties
if (!IsNothing(ProdB))
{
IsOff = false;
DoPrecip(Prod);
}
}
if (IsOff)
{
//results...
dTin = Prod.T;
dTout = dTin;
dQvin = Prod.Volume();
dQvout = dQvin;
dACin = (IsNothing(ProdB) ? 0.0 : ProdB.AtoC());
dACout = dACin;
dGrowthRateFactor = 0.0;
dGrowthRate = 0.0;
dThermalLoss = 0.0;
dThermTempDrop = 0.0;
dReactionHeat = 0.0;
dResidenceTime = 0.0;
dSALout = 0.0;
dDiamout = 0.0;
dYield = 0.0;
dASat = 0.0;
dSolPrecip = 0.0;
dOccSoda = 0.0;
}
}
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 CPrecipitator::ClosureInfo(MClosureInfo & CI)
{//ensure heat balance
if (CI.DoFlows())
{
CI.AddPowerIn(0, -dThermalLoss);
}
}
//====================================================================================
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
14,
14
],
[
17,
17
],
[
20,
235
],
[
241,
289
],
[
291,
292
],
[
294,
349
],
[
353,
552
],
[
554,
562
],
[
564,
626
]
],
[
[
13,
13
],
[
15,
16
],
[
18,
19
],
[
236,
240
],
[
290,
290
],
[
293,
293
],
[
350,
352
],
[
553,
553
],
[
563,
563
]
]
] |
0f6fa55838e744b02dbe17d60629ec9ba2fb9307 | 99d3989754840d95b316a36759097646916a15ea | /tags/2011_09_07_to_baoxin_gpd_0.1/ferrylibs/src/ferry/imutil/io/AVIWriter.h | 55598f93210ca24d615c349b023d12e654edc0ea | [] | no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | h | #pragma once
#include <iostream>
#include <cv.h>
#include <highgui.h>
using namespace std;
namespace ferry { namespace imutil { namespace io {
class AVIWriter
{
public:
AVIWriter(const char* path, int width, int height) {
//this->path = path;
pvw = cvCreateVideoWriter(path, -1, 30, cvSize(width, height));
if (!pvw) {
cout<<"can't create video writer!"<<endl;
return;
}
}
~AVIWriter(void) {
cvReleaseVideoWriter(&pvw);
}
public:
void writeFrame(IplImage* frame) {
if (pvw) {
cvWriteFrame(pvw, frame);
}
}
private:
//const char* path;
CvVideoWriter* pvw;
};
} } } | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
] | [
[
[
1,
42
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.