blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0af20eef1229689c9ea1e17f15115dcbeb680c9f | 280e6fff54711b88fa370e38c6e201aedcfedfc9 | /3rdparty/json/src/jsonreader.cpp | 75c4721b0af202355f83b44a02567b1180acd5d2 | []
| no_license | plus7/Highwind | 7cf48022f0b511202b1f6dd42623c07bd1291ac6 | 4cfe2874c2ab5697963946401bf1d2a769f19832 | refs/heads/master | 2016-09-02T09:13:35.628726 | 2009-10-13T16:41:19 | 2009-10-13T16:41:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,364 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: jsonreader.cpp
// Purpose: the wxJSONReader class: a JSON text parser
// Author: Luciano Cattani
// Created: 2007/10/14
// RCS-ID: $Id: jsonreader.cpp,v 1.12 2008/03/12 10:48:19 luccat Exp $
// Copyright: (c) 2007 Luciano Cattani
// Licence: wxWidgets licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "jsonreader.cpp"
#endif
#include <wx/jsonreader.h>
#include <wx/sstream.h>
#include <wx/debug.h>
#include <wx/log.h>
/*! \class wxJSONReader
\brief The JSON parser
The class is a JSON parser which reads a JSON formatted text and stores
values in the \c wxJSONValue structure.
The ctor accepts two parameters: the \e style flag, which controls how
much error-tolerant should the parser be and an integer which is
the maximum number of errors and warnings that have to be reported.
If the JSON text document does not contain an open/close JSON character the
function returns an \b invalid value object; in other words, the
wxJSONValue::IsValid() function returns FALSE.
This is the case of a document that is empty or contains only
whitespaces or comments.
If the document contains a starting object/array character immediatly
followed by a closing object/array character
(i.e.: \c {} ) then the function returns an \b empty array or object
JSON value.
This is a valid JSON object of type wxJSONTYPE_OBJECT or wxJSONTYPE_ARRAY
whose wxJSONValue::Size() function returns ZERO.
\par JSON text
The wxJSON parser just skips all characters read from the
input JSON text until the start-object '{' or start-array '[' characters
are encontered (see the GetStart() function).
This means that the JSON input text may contain everything
before the first start-object/array character except these two chars themselves
unless they are included in a C/C++ comment.
Comment lines that apear before the first start array/object character,
are non ignored if the parser is constructed with the wxJSONREADER_STORE_COMMENT
flag: they are added to the comment's array of the root JSON value.
Note that the parsing process stops when the internal DoRead() function
returns. Because that function is recursive, the top-level close-object
'}' or close-array ']' character cause the top-level DoRead() function
to return thus stopping the parsing process regardless the EOF condition.
This means that the JSON input text may contain everything \b after
the top-level close-object/array character.
Here are some examples:
Returns a wxJSONTYPE_INVALID value (invalid JSON value)
\code
// this text does not contain an open array/object character
\endcode
Returns a wxJSONTYPE_OBJECT value of Size() = 0
\code
{
}
\endcode
Returns a wxJSONTYPE_ARRAY value of Size() = 0
\code
[
]
\endcode
Text before and after the top-level open/close characters is ignored.
\code
This non-JSON text does not cause the parser to report errors or warnings
{
}
This non-JSON text does not cause the parser to report errors or warnings
\endcode
\par Extensions
The wxJSON parser recognizes all JSON text plus some extensions
that are not part of the JSON syntax but that many other JSON
implementations do recognize.
If the input text contains the following non-JSON text, the parser
reports the situation as \e warnings and not as \e errors unless
the parser object was constructed with the wxJSONREADER_STRICT
flag. In the latter case the wxJSON parser is not tolerant.
\li C/C++ comments: the parser recognizes C and C++ comments.
Comments can optionally be stored in the value they refer
to and can also be written back to the JSON text document.
To know more about comment storage see \ref wxjson_comments
\li case tolerance: JSON syntax states that the literals \c null,
\c true and \c false must be lowercase; the wxJSON parser
also recognizes mixed case literals such as, for example,
\b Null or \b FaLSe. A \e warning is emitted.
\li wrong or missing closing character: wxJSON parser is tolerant
about the object / array closing character. When an open-array
character '[' is encontered, the parser expects the
corresponding close-array character ']'. If the character
encontered is a close-object char '}' a warning is reported.
A warning is also reported if the character is missing when
the end-of-file is reached.
\li multi-line strings: this feature allows a JSON string type to be
splitted in two or more lines as in the standard C/C++
languages. The drawback is that this feature is error-prone
and you have to use it with care.
For more info about this topic read \ref json_multiline_string
Note that you can control how much error-tolerant should the parser be
and also you can specify how many and what extensions are recognized.
See the constructor's parameters for more details.
\par Unicode vs ANSI
The parser can read JSON text from two very different kind of objects:
\li a string object (\b wxString)
\li a stream object (\b wxInputStream)
When the input is from a string object, the character represented in the
string is platform- and mode- dependant; in other words, characters are
represented differently: in ANSI builds they depend on the charset in use
and in Unicode builds they depend on the platform (UCS-2 on win32, UCS-4
on GNU/Linux).
When the input is from a stream object, the only recognized encoding format
is UTF-8 for both ANSI and Unicode builds.
\par Example:
\code
wxJSONValue value;
wxJSONReader reader;
// open a text file that contains the UTF-8 encoded JSON text
wxFFileInputStream jsonText( _T("filename.utf8"), _T("r"));
// read the file
int numErrors = reader.Parse( jsonText, &value );
if ( numErrors > 0 ) {
::MessageBox( _T("Error reading the input file"));
}
\endcode
To know more about ANSI and Unicode mode read \ref wxjson_tutorial_unicode.
*/
// if you have the debug build of wxWidgets and wxJSON you can see
// trace messages by setting the:
// WXTRACE=traceReader StoreComment
// environment variable
static const wxChar* traceMask = _T("traceReader");
static const wxChar* storeTraceMask = _T("StoreComment");
//! Ctor
/*!
Construct a JSON parser object with the given parameters.
JSON parser objects should always be constructed on the stack but
it does not hurt to have a global JSON parser.
\param flags this paramter controls how much error-tolerant should the
parser be
\param maxErrors the maximum number of errors (and warnings, too) that are
reported by the parser. When the number of errors reaches this limit,
the parser stops to read the JSON input text and no other error is
reported.
The \c flag parameter is the combination of ZERO or more of the
following constants OR'ed toghether:
\li wxJSONREADER_ALLOW_COMMENTS: C/C++ comments are recognized by the
parser; a warning is reported by the parser
\li wxJSONREADER_STORE_COMMENTS: C/C++ comments, if recognized, are
stored in the value they refer to and can be rewritten back to
the JSON text
\li wxJSONREADER_CASE: the parser recognizes mixed-case literal strings
\li wxJSONREADER_MISSING: the parser allows missing or wrong close-object
and close-array characters
\li wxJSONREADER_MULTISTRING: strings may be splitted in two or more
lines
\li wxJSONREADER_COMMENTS_AFTER: if STORE_COMMENTS if defined, the parser
assumes that comment lines apear \b before the value they
refer to unless this constant is specified. In the latter case,
comments apear \b after the value they refer to.
You can also use the following shortcuts to specify some predefined
flag's combinations:
\li wxJSONREADER_STRICT: all wxJSON extensions are reported as errors, this
is the same as specifying a ZERO value as \c flags.
\li wxJSONREADER_TOLERANT: this is the same as ALLOW_COMMENTS | CASE |
MISSING | MULTISTRING; all wxJSON extensions are turned on but comments
are not stored in the value objects.
\par Example:
The following code fragment construct a JSON parser, turns on all
wxJSON extensions and also stores C/C++ comments in the value object
they refer to. The parser assumes that the comments apear before the
value:
\code
wxJSONReader reader( wxJSONREADER_TOLERANT | wxJSONREADER_STORE_COMMENTS );
wxJSONValue root;
int numErrors = reader.Parse( jsonText, &root );
\endcode
*/
wxJSONReader::wxJSONReader( int flags, int maxErrors )
{
m_flags = flags;
m_maxErrors = maxErrors;
m_inType = -1;
m_inObject = 0;
}
//! Dtor - does nothing
wxJSONReader::~wxJSONReader()
{
}
//! Parse the JSON document.
/*!
The two overloaded versions of the \c Parse() function read a
JSON text stored in a wxString object or in a wxInputStream
object.
If \c val is a NULL pointer, the function does not store the
values: it can be used as a JSON checker in order to check the
syntax of the document.
Returns the number of \b errors found in the document.
If the returned value is ZERO and the parser was constructed
with the \c wxJSONREADER_STRICT flag, then the parsed document
is \e well-formed and it only contains valid JSON text.
If the \c wxJSONREADER_TOLERANT flag was used in the parser's
constructor, then a return value of ZERO
does not mean that the document is \e well-formed because it may
contain comments and other extensions that are not fatal for the
wxJSON parser but other parsers may fail to recognize.
You can use the \c GetWarningCount() function to know how many
wxJSON extensions are present in the JSON input text.
Note that the JSON value object \c val is not cleared by this
function unless its type is of the wrong type.
In other words, if \c val is of type wxJSONTYPE_ARRAY and it already
contains 10 elements and the input document starts with a
'[' (open-array char) then the elements read from the document are
\b appended to the existing ones.
On the other hand, if the text document starts with a '{' (open-object) char
then this function must change the type of the \c val object to
\c wxJSONTYPE_OBJECT and the old content of 10 array elements will be lost.
When reading from a \b wxInputStream the JSON text must be encoded
in UTF-8 format for both Unicode and ANSI builds.
When reading from a \b wxString object, the input text is encoded
in different formats depending on the platform and the build
mode: in Unicode builds, strings are encoded in UCS-2 format on
Windows and in UCS-4 format on GNU/Linux; in ANSI builds, strings
contain one-byte locale dependent characters.
*/
int
wxJSONReader:: Parse( const wxString& doc, wxJSONValue* val )
{
m_inType = 0; // a string
m_inObject = (void*) &doc;
m_charPos = 0;
m_conv = 0;
int numErr = Parse( val );
return numErr;
}
//! \overload Parse( const wxString&, wxJSONValue* )
int
wxJSONReader::Parse( wxInputStream& is, wxJSONValue* val )
{
wxMBConvUTF8 conv;
m_conv = &conv;
m_inObject = &is;
m_inType = 1;
return Parse( val );
}
//! The general parsing function (internal use)
/*!
This protected function is called by the public overloaded Parse()
functions after setting up the internal data members.
*/
int
wxJSONReader::Parse( wxJSONValue* val )
{
// construct a temporary wxJSONValue that will be passed
// to DoRead() if val == 0 - note that it will be deleted on exit
wxJSONValue* temp = 0;
m_level = 0;
m_lineNo = 1;
m_colNo = 1;
m_peekChar = -1;
m_errors.clear();
m_warnings.clear();
// check the internal data members
wxJSON_ASSERT( m_inObject != 0 );
wxJSON_ASSERT( m_inType >= 0 );
if ( val != 0 ) {
temp = val;
}
else {
temp = new wxJSONValue();
}
// set the wxJSONValue object's pointers for comment storage
m_next = temp;
m_next->SetLineNo( -1 );
m_lastStored = 0;
m_current = 0;
int ch = GetStart();
switch ( ch ) {
case '{' :
temp->SetType( wxJSONTYPE_OBJECT );
break;
case '[' :
temp->SetType( wxJSONTYPE_ARRAY );
break;
default :
AddError( _T("Cannot find a start object/array character" ));
return m_errors.size();
break;
}
// returning from DoRead() could be for EOF or for
// the closing array-object character
// if -1 is returned, it is as an error because the lack
// of close-object/array characters
// note that the missing close-chars error messages are
// added by the DoRead() function
ch = DoRead( *temp );
if ( val == 0 ) {
delete temp;
}
return m_errors.size();
}
//! Returns the start of the document
/*!
This is the first function called by the Parse() function and it searches
the input stream for the starting character of a JSON text and returns it.
JSON text start with '{' or '['.
If the two starting characters are inside a C/C++ comment, they
are ignored.
Returns the JSON-text start character or -1 on EOF.
*/
int
wxJSONReader::GetStart()
{
int ch = 0;
do {
switch ( ch ) {
case 0 :
ch = ReadChar();
break;
case '{' :
return ch;
break;
case '[' :
return ch;
break;
case '/' :
ch = SkipComment();
StoreComment( 0 );
break;
default :
ch = ReadChar();
break;
}
} while ( ch >= 0 );
return ch;
}
//! Return a reference to the error message's array.
const wxArrayString&
wxJSONReader::GetErrors() const
{
return m_errors;
}
//! Return a reference to the warning message's array.
const wxArrayString&
wxJSONReader::GetWarnings() const
{
return m_warnings;
}
//! Return the size of the error message's array.
int
wxJSONReader::GetErrorCount() const
{
return m_errors.size();
}
//! Return the size of the warning message's array.
int
wxJSONReader::GetWarningCount() const
{
return m_warnings.size();
}
//! Read a character from the input JSON document.
/*!
The function returns a single character from the input JSON document
as an integer so that all 2^31 unicode characters can be represented
as a positive integer value.
In case of errors or EOF, the function returns -1.
The function also updates the \c m_lineNo and \c m_colNo data
members and converts all CR+LF sequence in LF.
Note that this function calls GetChar() in order to retrieve the
next character in the JSON input text.
*/
int
wxJSONReader::ReadChar()
{
int ch = GetChar();
// the function also converts CR in LF. only LF is returned
// in the case of CR+LF
// returns -1 on EOF
if ( ch == -1 ) {
return ch;
}
int nextChar;
if ( ch == '\r' ) {
m_colNo = 1;
nextChar = PeekChar();
if ( nextChar == -1 ) {
return -1;
}
else if ( nextChar == '\n' ) {
ch = GetChar();
}
}
if ( ch == '\n' ) {
++m_lineNo;
m_colNo = 1;
}
else {
++m_colNo;
}
return ch;
}
//! Return a character from the input JSON document.
/*!
The function is called by ReadChar() and returns a single character
from the input JSON document
as an integer so that all 2^31 unicode characters can be represented
as a positive integer value.
In case of errors or EOF, the function returns -1.
Note that this function behaves differently depending on the build
mode (ANSI or Unicode) and the type of the object containing the
JSON document.
\par wxString input
If the input JSON text is stored in a \b wxString object, there is
no difference between ANSI and Unicode builds: the function just returns
the next character in the string and updates the \c m_charPos data
member that points the next character in the string.
In Unicode mode, the function returns wide characters and in ANSI
builds it returns only chars.
\par wxInputStream input
Stream input is always encoded in UTF-8 format in both ANSI ans
Unicode builds.
In order to return a single character, the function calls the
NumBytes() function which returns the number of bytes that
have to be read from the stream in order to get one character.
The bytes read are then converted to a wide character and
returned.
Note that wide chars are also returned in ANSI mode but they
are processed differently by the parser: before storing the
wide character in the JSON value, it is converted to the
locale dependent character if one exists; if not, the \e unicode
\e escape \e sequence is stored in the JSON value.
*/
int
wxJSONReader::GetChar()
{
int ch;
if ( m_peekChar >= 0 ) {
ch = m_peekChar;
m_peekChar = -1;
return ch;
}
if ( m_inType == 0 ) { // input is a string
wxString* s = (wxString*) m_inObject;
size_t strLen = s->length();
if ( m_charPos >= (int) strLen ) {
return -1; // EOF
}
else {
ch = s->GetChar( m_charPos );
++m_charPos;
}
}
else {
// input is a stream: it must be UTF-8
wxInputStream* is = (wxInputStream*) m_inObject;
wxJSON_ASSERT( is != 0 );
// must know the number fo bytes to read
char buffer[10];
buffer[0] = is->GetC();
// check the EOF condition; note that in wxWidgets 2.6.x and below
// some streams returns EOF after the last char was read and
// we should use LastRead() to know the EOF condition
// wxJSON depends on 2.8.4 and above so there should be no problem
if ( is->Eof() ) {
return -1;
}
// if ( LastRead() <= 0 ) {
// return -1;
// }
int numBytes = NumBytes( buffer[0] );
wxJSON_ASSERT( numBytes < 10 );
if ( numBytes > 1 ) {
is->Read( buffer + 1, numBytes - 1);
}
// check that we read at least 'numBytes' bytes
int lastRead = is->LastRead();
if ( lastRead < ( numBytes -1 )) {
AddError( _T("Cannot read the number of needed UTF-8 encoded bytes"));
ch = -1;
return ch;
}
// we convert the UTF-8 char to a wide char; if the conversion
// fails, returns -1
wchar_t dst[5];
wxJSON_ASSERT( m_conv != 0 );
size_t outLength = m_conv->ToWChar( dst, 10, buffer, numBytes );
if ( outLength == wxCONV_FAILED ) {
AddError( _T("Cannot convert multibyte sequence to wide character"));
ch = -1;
return ch;
}
else {
wxJSON_ASSERT( outLength == 2 ); // seems that a NULL char is appended
ch = dst[0];
}
// we are only interested in the dst[0] wide-chracter; it could be
// possible that 'outLenght' is 2 because a trailing NULL wchar is
// appended but it is ignored
// if the character read is a NULL char, it is returned as a NULL
// char thus causing the JSON reader to read the next char.
}
// for tracing purposes we do not print control characters
char chPrint = '.';
if ( ch >= 20 ) {
chPrint = ch;
}
::wxLogTrace( _T("traceChar"), _T("(%s) ch=%x char=%c"), __PRETTY_FUNCTION__, ch, chPrint );
return ch;
}
//! Peek a character from the input JSON document
/*!
This function is much like GetChar() but it does not update
the stream or string input position.
*/
int
wxJSONReader::PeekChar()
{
int ch;
if ( m_peekChar >= 0 ) {
ch = m_peekChar;
}
else {
ch = GetChar();
m_peekChar = ch;
}
return ch;
}
//! Reads the JSON text document (internal use)
/*!
This is a recursive function that is called by \c Parse()
and by the \c DoRead() function itself when a new object /
array is encontered.
The function returns when a EOF condition is encontered or
when the final close-object / close-array char is encontered.
The function also increments the \c m_level
data member when it is entered and decrements it on return.
The function is the heart of the wxJSON parser class but it is
also very easy to understand because JSON syntax is very
easy.
Returns the last close-object/array character read or -1 on EOF.
*/
int
wxJSONReader::DoRead( wxJSONValue& parent )
{
++m_level;
// the value that has to be read (can be a complex structure)
// it can also be a 'name' (key) string
wxJSONValue value( wxJSONTYPE_INVALID );
m_next = &value;
m_current = &parent;
m_current->SetLineNo( m_lineNo );
m_lastStored = 0;
// the 'key' string is stored from 'value' when a ':' is encontered
wxString key;
// the character read: -1=EOF, 0=to be read
int ch=0;
do { // we read until ch < 0
switch ( ch ) {
case 0 :
ch = ReadChar();
break;
case ' ' :
case '\t' :
case '\n' :
case '\r' :
ch = SkipWhiteSpace();
break;
case -1 : // the EOF
break;
case '/' :
ch = SkipComment();
StoreComment( &parent );
break;
case '{' :
if ( parent.IsObject() ) {
if ( key.empty() ) {
AddError( _T("\'{\' is not allowed here (\'name\' is missing") );
}
if ( value.IsValid() ) {
AddError( _T("\'{\' cannot follow a \'value\'") );
}
}
else if ( parent.IsArray() ) {
if ( value.IsValid() ) {
AddError( _T("\'{\' cannot follow a \'value\' in JSON array") );
}
}
else {
wxJSON_ASSERT( 0 ); // always fails
}
// althrough there were errors, we go into the subobject
value.SetType( wxJSONTYPE_OBJECT );
ch = DoRead( value );
break;
case '}' :
if ( !parent.IsObject() ) {
AddWarning( wxJSONREADER_MISSING,
_T("Trying to close an array using the \'}\' (close-object) char" ));
}
StoreValue( ch, key, value, parent );
m_current = &parent;
m_next = 0;
m_current->SetLineNo( m_lineNo );
ch = ReadChar();
return ch;
break;
case '[' :
if ( parent.IsObject() ) {
if ( key.empty() ) {
AddError( _T("\'[\' is not allowed here (\'name\' is missing") );
}
if ( value.IsValid() ) {
AddError( _T("\'[\' cannot follow a \'value\' text") );
}
}
else if ( parent.IsArray()) {
if ( value.IsValid() ) {
AddError( _T("\'[\' cannot follow a \'value\'") );
}
}
else {
wxJSON_ASSERT( 0 ); // always fails
}
// althrough there were errors, we go into the subobject
value.SetType( wxJSONTYPE_ARRAY );
ch = DoRead( value );
break;
case ']' :
if ( !parent.IsArray() ) {
AddWarning( wxJSONREADER_MISSING,
_T("Trying to close an object using the \']\' (close-array) char" ));
}
StoreValue( ch, key, value, parent );
m_current = &parent;
m_next = 0;
m_current->SetLineNo( m_lineNo );
return 0; // returning ZERO for reading the next char
break;
case ',' :
StoreValue( ch, key, value, parent );
key.clear();
ch = ReadChar();
break;
case '\"' :
ch = ReadString( value ); // store the string in 'value'
m_current = &value;
m_next = 0;
break;
case ':' : // key / value separator
m_current = &value;
m_current->SetLineNo( m_lineNo );
m_next = 0;
if ( !parent.IsObject() ) {
AddError( _T( "\':\' cannot be used in array's values" ));
}
else if ( !value.IsString() ) {
AddError( _T( "\':\' follows a value which is not of type \'string\'" ));
}
else if ( !key.empty() ) {
AddError( _T( "\':\' not allowed where a \'name\' string was already available" ));
}
else {
key = value.AsString();
value.SetType( wxJSONTYPE_INVALID );
}
ch = ReadChar();
break;
// no special chars, is it a value?
default :
// errors are checked in the 'ReadValue()' function.
m_current = &value;
m_current->SetLineNo( m_lineNo );
m_next = 0;
ch = ReadValue( ch, value );
break;
}
} while ( ch >= 0 );
if ( parent.IsArray() ) {
AddWarning( wxJSONREADER_MISSING, _T("\']\' missing at end of file"));
}
else if ( parent.IsObject() ) {
AddWarning( wxJSONREADER_MISSING, _T("\'}\' missing at end of file"));
}
else {
wxJSON_ASSERT( 0 );
}
// we store the value, as there is a missing close-object/array char
StoreValue( ch, key, value, parent );
--m_level;
return ch;
}
//! Store a value in the parent object.
/*!
The function is called by \c DoRead() when a the comma
or a close-object/array character is encontered and stores the current
value read by the parser in the parent object.
The function checks that \c value is not invalid and that \c key is
not an empty string if \c parent is an object.
\param ch the character read: a comma or close objecty/array char
\param key the \b key string: may be empty if parent ss an array
\param value the current JSON value to be stored in \c parent
\param parent the JSON value that holds \c value.
*/
void
wxJSONReader::StoreValue( int ch, const wxString& key, wxJSONValue& value, wxJSONValue& parent )
{
// if 'ch' == } or ] than value AND key may be empty when a open object/array
// is immediatly followed by a close object/array
//
// if 'ch' == , (comma) value AND key (for TypeMap) cannot be empty
//
::wxLogTrace( traceMask, _T("(%s) ch=%d char=%c"), __PRETTY_FUNCTION__, ch, (char) ch);
::wxLogTrace( traceMask, _T("(%s) value=%s"), __PRETTY_FUNCTION__, value.AsString().c_str());
m_current = 0;
m_next = &value;
m_lastStored = 0;
m_next->SetLineNo( -1 );
if ( !value.IsValid() && key.empty() ) {
// OK, if the char read is a close-object or close-array
if ( ch == '}' || ch == ']' ) {
m_lastStored = 0;
::wxLogTrace( traceMask, _T("(%s) key and value are empty, returning"),
__PRETTY_FUNCTION__);
}
else {
AddError( _T("key or value is missing for JSON value"));
}
}
else {
// key or value are not empty
if ( parent.IsObject() ) {
if ( !value.IsValid() ) {
AddError( _T("cannot store the value: \'value\' is missing for JSON object type"));
}
else if ( key.empty() ) {
AddError( _T("cannot store the value: \'key\' is missing for JSON object type"));
}
else {
::wxLogTrace( traceMask, _T("(%s) adding value to key:%s"),
__PRETTY_FUNCTION__, key.c_str());
parent[key] = value;
m_lastStored = &(parent[key]);
m_lastStored->SetLineNo( m_lineNo );
}
}
else if ( parent.IsArray() ) {
if ( !value.IsValid() ) {
AddError( _T("cannot store the item: \'value\' is missing for JSON array type"));
}
if ( !key.empty() ) {
AddError( _T("cannot store the item: \'key\' (\'%s\') is not permitted in JSON array type"), key);
}
::wxLogTrace( traceMask, _T("(%s) appending value to parent array"), __PRETTY_FUNCTION__ );
parent.Append( value );
const wxJSONInternalArray* arr = parent.AsArray();
wxJSON_ASSERT( arr );
m_lastStored = &(arr->Last());
m_lastStored->SetLineNo( m_lineNo );
}
else {
wxJSON_ASSERT( 0 ); // should never happen
}
}
value.SetType( wxJSONTYPE_INVALID );
value.ClearComments();
}
//! Add a error message to the error's array
/*!
The overloaded versions of this function add an error message to the
error's array stored in \c m_errors.
The error message is formatted as follows:
\code
Error: line xxx, col xxx - <error_description>
\endcode
The \c msg parameter is the description of the error; line's and column's
number are automatically added by the functions.
The \c fmt parameter is a format string that has the same syntax as the \b printf
function.
Note that it is the user's responsability to provide a format string suitable
with the arguments: another string or a character.
*/
void
wxJSONReader::AddError( const wxString& msg )
{
wxString err;
err.Printf( _T("Error: line %d, col %d - %s"), m_lineNo, m_colNo, msg.c_str() );
::wxLogTrace( traceMask, _T("(%s) %s"), __PRETTY_FUNCTION__, err.c_str());
if ( (int) m_errors.size() < m_maxErrors ) {
m_errors.Add( err );
}
else if ( (int) m_errors.size() == m_maxErrors ) {
m_errors.Add( _T("Error: too many error messages - ignoring further errors"));
}
// else if ( m_errors > m_maxErrors ) do nothing, thus ignore the error message
}
//! \overload AddError( const wxString& )
void
wxJSONReader::AddError( const wxString& fmt, const wxString& str )
{
wxString s;
s.Printf( fmt.c_str(), str.c_str() );
AddError( s );
}
//! \overload AddError( const wxString& )
void
wxJSONReader::AddError( const wxString& fmt, wxChar c )
{
wxString s;
s.Printf( fmt.c_str(), c );
AddError( s );
}
//! Add a warning message to the warning's array
/*!
The warning description is as follows:
\code
Warning: line xxx, col xxx - <warning_description>
\endcode
Warning messages are generated by the parser when the JSON
text that has been read is not well-formed but the
error is not fatal and the parser recognizes the text
as an extension to the JSON standard (see the parser's ctor
for more info about wxJSON extensions).
Note that the parser has to be constructed with a flag that
indicates if each individual wxJSON extension is on.
If the warning message is related to an extension that is not
enabled in the parser's \c m_flag data member, this function
calls AddError() and the warning message becomes an error
message.
The \c type parameter is one of the same constants that
specify the parser's extensions.
*/
void
wxJSONReader::AddWarning( int type, const wxString& msg )
{
// if 'type' AND 'm_flags' == 1 than the extension is
// ON. Otherwise it is OFF anf the function calls AddError()
if ( ( type & m_flags ) == 0 ) {
AddError( msg );
return;
}
wxString err;
err.Printf( _T( "Warning: line %d, col %d - %s"), m_lineNo, m_colNo, msg.c_str() );
::wxLogTrace( traceMask, _T("(%s) %s"), __PRETTY_FUNCTION__, err.c_str());
if ( (int) m_warnings.size() < m_maxErrors ) {
m_warnings.Add( err );
}
else if ( (int) m_warnings.size() == m_maxErrors ) {
m_warnings.Add( _T("Error: too many warning messages - ignoring further warnings"));
}
// else do nothing, thus ignore the warning message
}
//! Skip all whitespaces.
/*!
The function reads characters from the input text
and returns the first non-whitespace character read or -1
if EOF.
Note that the function does not rely on the \b isspace function
of the C library but checks the space constants: space, TAB and
LF.
*/
int
wxJSONReader::SkipWhiteSpace()
{
int ch;
do {
ch = ReadChar();
if ( ch < 0 ) {
break;
}
}
while ( ch == ' ' || ch == '\n' || ch == '\t' );
::wxLogTrace( traceMask, _T("(%s) end whitespaces line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
return ch;
}
//! Skip a comment
/*!
The function is called by DoRead() when a '/' (slash) character
is read from the input stream assuming that a C/C++ comment is starting.
Returns the first character that follows the comment or
-1 on EOF.
The function also adds a warning message because comments are not
valid JSON text.
The function also stores the comment, if any, in the \c m_comment data
member: it can be used by the DoRead() function if comments have to be
stored in the value they refer to.
*/
int
wxJSONReader::SkipComment()
{
static const wxChar* warn =
_T("Comments may be tolerated in JSON text but they are not part of JSON syntax");
// if it is a comment, then a warning is added to the array
// otherwise it is an error: values cannot start with a '/'
int ch = ReadChar();
if ( ch < 0 ) {
return -1;
}
::wxLogTrace( storeTraceMask, _T("(%s) start comment line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
if ( ch == '/' ) { // C++ comment, read until end-of-line
AddWarning( wxJSONREADER_ALLOW_COMMENTS, warn );
m_commentLine = m_lineNo;
m_comment.append( _T("//") );
while ( ch != '\n' && ch >= 0 ) {
ch = ReadChar();
m_comment.append( 1, (wchar_t)ch );
}
// now ch contains the '\n' character;
}
else if ( ch == '*' ) { // C-style comment
AddWarning(wxJSONREADER_ALLOW_COMMENTS, warn );
m_commentLine = m_lineNo;
m_comment.append( _T("/*") );
while ( ch >= 0 ) {
ch = ReadChar();
m_comment.append( 1, (wchar_t)ch );
if ( ch == '*' && PeekChar() == '/' ) {
m_comment.append( 1, '/' );
break;
}
}
// now ch contains '*' followed by '/'; we read two characters
ch = ReadChar();
ch = ReadChar();
}
else { // it is not a comment, return the character next the first '/'
AddError( _T( "Strange '/' (did you want to insert a comment?)"));
// we read until end-of-line OR end of C-style comment OR EOF
// because a '/' should be a start comment
while ( ch >= 0 ) {
ch = ReadChar();
if ( ch == '*' && PeekChar() == '/' ) {
break;
}
if ( ch == '\n' ) {
break;
}
}
ch = ReadChar();
}
::wxLogTrace( traceMask, _T("(%s) end comment line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
::wxLogTrace( storeTraceMask, _T("(%s) end comment line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
::wxLogTrace( storeTraceMask, _T("(%s) comment=%s"),
__PRETTY_FUNCTION__, m_comment.c_str());
return ch;
}
//! Read a string value
/*!
The function reads a string value from input stream and it is
called by the \c DoRead() function when it enconters the
double quote characters.
The function read all characters up to the next double quotes
unless it is escaped.
Also, the function recognizes the escaped characters defined
in the JSON syntax.
The string is also stored in the provided wxJSONValue argument
provided that it is empty or it contains a string value.
This is because the parser class recognizes multi-line strings
like the following one:
\code
[
"This is a very long string value which is splitted into more"
"than one line because it is more human readable"
]
\endcode
Because of the lack of the value separator (,) the parser
assumes that the string was split into several double-quoted
strings.
If the value does not contain a string then an error is
reported.
Splitted strings cause the parser to report a warning.
*/
int
wxJSONReader::ReadString( wxJSONValue& val )
{
long int hex;
// the char read is the opening qoutes (")
wxString s;
int ch = ReadChar();
while ( ch > 0 && ch != '\"' ) {
if ( ch == '\\' ) { // an escape sequence
ch = ReadChar();
switch ( ch ) {
case -1 :
break;
case 't' :
s.append( 1, '\t' );
break;
case 'n' :
s.append( 1, '\n' );
break;
case 'b' :
s.append( 1, '\b' );
break;
case 'r' :
s.append( 1, '\r' );
break;
case '\"' :
s.append( 1, '\"' );
break;
case '\\' :
s.append( 1, '\\' );
break;
case '/' :
s.append( 1, '/' );
break;
case 'f' :
s.append( 1, '\f' );
break;
case 'u' :
ch = ReadUnicode( hex );
if ( hex < 0 ) {
AddError( _T( "unicode sequence must contain 4 hex digits"));
}
else {
// append the unicode escaped character to the string 's'
AppendUnicodeSequence( s, hex );
}
// many thanks to Bryan Ashby who discovered this bug
continue;
// break;
default :
AddError( _T( "Unknow escaped character \'\\%c\'"), ch );
}
}
else {
// we have read a non-escaped character so we have to append it to
// the string. note that in ANSI builds we have to convert the char
// to a locale dependent charset; if the char cannot be converted,
// store its unicode escape sequence
#if defined( wxJSON_USE_UNICODE )
s.Append( (wxChar) ch, 1 );
#else
wchar_t wchar = ch;
char buffer[5];
size_t len = wxConvLibc.FromWChar( buffer, 5, &wchar, 1 );
if ( len != wxCONV_FAILED ) {
s.Append( buffer[0], 1 );
}
else {
::wxSnprintf( buffer, 10, _T("\\u%04X" ), ch );
s.Append( buffer );
}
#endif
}
ch = ReadChar(); // read the next char until closing quotes
}
::wxLogTrace( traceMask, _T("(%s) line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
::wxLogTrace( traceMask, _T("(%s) string read=%s"),
__PRETTY_FUNCTION__, s.c_str() );
::wxLogTrace( traceMask, _T("(%s) value=%s"),
__PRETTY_FUNCTION__, val.AsString().c_str() );
// now assign the string to the JSON-value 'value'
// must check that:
// 'value' is empty
// 'value' is a string; concatenate it but emit warning
if ( !val.IsValid() ) {
::wxLogTrace( traceMask, _T("(%s) assigning the string to value"), __PRETTY_FUNCTION__ );
val = s ;
}
else if ( val.IsString() ) {
AddWarning( wxJSONREADER_MULTISTRING,
_T("Multiline strings are not allowed by JSON syntax") );
::wxLogTrace( traceMask, _T("(%s) concatenate the string to value"), __PRETTY_FUNCTION__ );
val.Cat( s );
}
else {
AddError( _T( "String value \'%s\' cannot follow another value"), s );
}
// store the input text's line number when the string was stored in 'val'
val.SetLineNo( m_lineNo );
// read the next char after the closing quotes and returns it
if ( ch > 0 ) {
ch = ReadChar();
}
return ch;
}
//! Reads a token string
/*!
This function is called by the ReadValue() when the
first character encontered is not a special char
and it is not a string.
It stores the token in the provided string argument
and returns the next character read which is a
whitespace or a special JSON character.
A token cannot include \e unicode \e escaped \e sequences
so this function does not try to interpret such sequences.
*/
int
wxJSONReader::ReadToken( int ch, wxString& s )
{
int nextCh = ch;
while ( nextCh >= 0 ) {
switch ( nextCh ) {
case ' ' :
case ',' :
case ':' :
case '[' :
case ']' :
case '{' :
case '}' :
case '\t' :
case '\n' :
case '\r' :
case '\b' :
::wxLogTrace( traceMask, _T("(%s) line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
::wxLogTrace( traceMask, _T("(%s) token read=%s"),
__PRETTY_FUNCTION__, s.c_str() );
return nextCh;
break;
default :
#if defined( wxJSON_USE_UNICODE )
s.Append( (wxChar) nextCh, 1 );
#else
// In ANSI builds we have to convert the char
// to a locale dependent charset; if the char cannot be converted,
// store its unicode escape sequence
wchar_t wchar = nextCh;
char buffer[10];
size_t len = wxConvLibc.FromWChar( buffer, 10, &wchar, 1 );
if ( len != wxCONV_FAILED ) {
s.Append( buffer[0], 1 );
}
else {
::wxSnprintf( buffer, 10, _T("\\u%04x" ), ch );
s.Append( buffer );
}
#endif
break;
}
// read the next character
nextCh = ReadChar();
}
::wxLogTrace( traceMask, _T("(%s) EOF on line=%d col=%d"),
__PRETTY_FUNCTION__, m_lineNo, m_colNo );
::wxLogTrace( traceMask, _T("(%s) EOF - token read=%s"),
__PRETTY_FUNCTION__, s.c_str() );
return nextCh;
}
//! Read a value from input stream
/*!
The function is called by DoRead() when it enconters a char that is
not a special char nor a double-quote.
It assumes that the string is a numeric value or a 'null' or a
boolean value and stores it in the wxJSONValue object \c val.
The function also checks that \c val is of type wxJSONTYPE_INVALID otherwise
an error is reported becasue a value cannot follow another value:
maybe a (,) or (:) is missing.
Returns the next character or -1 on EOF.
*/
int
wxJSONReader::ReadValue( int ch, wxJSONValue& val )
{
wxString s;
int nextCh = ReadToken( ch, s );
::wxLogTrace( traceMask, _T("(%s) value=%s"),
__PRETTY_FUNCTION__, val.AsString().c_str() );
if ( val.IsValid() ) {
AddError( _T( "Value \'%s\' cannot follow a value: \',\' or \':\' missing?"), s );
return nextCh;
}
// variables used in the switch statement
bool r; double d;
// on 64-bits platforms, integers are stored in a wx(U)Int64 data type
#if defined( wxJSON_64BIT_INT )
wxInt64 i64;
wxUint64 ui64;
#else
unsigned long int ul; long int l;
#endif
// try to convert to a number if the token starts with a digit
// or a sign character
switch ( ch ) {
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
// first try a signed integer, then a unsigned integer, then a double
#if defined( wxJSON_64BIT_INT)
r = Strtoll( s, &i64 );
::wxLogTrace( traceMask, _T("(%s) convert to wxInt64 result=%d"),
__PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = i64;
return nextCh;
}
#else
r = s.ToLong( &l );
::wxLogTrace( traceMask, _T("(%s) convert to int result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = (int) l;
return nextCh;
}
#endif
// try a unsigned integer
#if defined( wxJSON_64BIT_INT)
r = Strtoull( s, &ui64 );
::wxLogTrace( traceMask, _T("(%s) convert to wxUint64 result=%d"),
__PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = ui64;
return nextCh;
}
#else
r = s.ToULong( &ul );
::wxLogTrace( traceMask, _T("(%s) convert to int result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = (unsigned int) ul;
return nextCh;
}
#endif
// number is very large or it is in exponential notation, try double
r = s.ToDouble( &d );
::wxLogTrace( traceMask, _T("(%s) convert to double result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = d;
return nextCh;
}
else { // the value is not syntactically correct
AddError( _T( "Value \'%s\' is incorrect (did you forget quotes?)"), s );
return nextCh;
}
break;
case '+' :
// the plus sign forces a unsigned integer
#if defined( wxJSON_64BIT_INT)
r = Strtoull( s, &ui64 );
::wxLogTrace( traceMask, _T("(%s) convert to wxUint64 result=%d"),
__PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = ui64;
return nextCh;
}
#else
r = s.ToULong( &ul );
::wxLogTrace( traceMask, _T("(%s) convert to int result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = (unsigned int) ul;
return nextCh;
}
#endif
// number is very large or it is in exponential notation, try double
r = s.ToDouble( &d );
::wxLogTrace( traceMask, _T("(%s) convert to double result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = d;
return nextCh;
}
else { // the value is not syntactically correct
AddError( _T( "Value \'%s\' is incorrect (did you forget quotes?)"), s );
return nextCh;
}
break;
case '-' :
// try a signed integer, then a double
#if defined( wxJSON_64BIT_INT)
r = Strtoll( s, &i64 );
::wxLogTrace( traceMask, _T("(%s) convert to wxInt64 result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = i64;
return nextCh;
}
#else
r = s.ToLong( &l );
::wxLogTrace( traceMask, _T("(%s) convert to int result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = (int) l;
return nextCh;
}
#endif
// number is very large or it is in exponential notation, try double
r = s.ToDouble( &d );
::wxLogTrace( traceMask, _T("(%s) convert to double result=%d"), __PRETTY_FUNCTION__, r );
if ( r ) {
// store the value
val = d;
return nextCh;
}
else { // the value is not syntactically correct
AddError( _T( "Value \'%s\' is incorrect (did you forget quotes?)"), s );
return nextCh;
}
break;
// if it is not a number than try the literals
// JSON syntax states that constant must be lowercase
// but this parser tolerate mixed-case literals but
// reports a warning.
default:
if ( s == _T("null") ) {
val.SetType( wxJSONTYPE_NULL );
::wxLogTrace( traceMask, _T("(%s) value = NULL"), __PRETTY_FUNCTION__ );
return nextCh;
}
else if ( s.CmpNoCase( _T( "null" )) == 0 ) {
::wxLogTrace( traceMask, _T("(%s) value = NULL"), __PRETTY_FUNCTION__ );
AddWarning( wxJSONREADER_CASE, _T( "the \'null\' literal must be lowercase" ));
val.SetType( wxJSONTYPE_NULL );
return nextCh;
}
else if ( s == _T("true") ) {
::wxLogTrace( traceMask, _T("(%s) value = TRUE"), __PRETTY_FUNCTION__ );
val = true;
return nextCh;
}
else if ( s.CmpNoCase( _T( "true" )) == 0 ) {
::wxLogTrace( traceMask, _T("(%s) value = TRUE"), __PRETTY_FUNCTION__ );
AddWarning( wxJSONREADER_CASE, _T( "the \'true\' literal must be lowercase" ));
val = true;
return nextCh;
}
else if ( s == _T("false") ) {
::wxLogTrace( traceMask, _T("(%s) value = FALSE"), __PRETTY_FUNCTION__ );
val = false;
return nextCh;
}
else if ( s.CmpNoCase( _T( "false" )) == 0 ) {
::wxLogTrace( traceMask, _T("(%s) value = FALSE"), __PRETTY_FUNCTION__ );
AddWarning( wxJSONREADER_CASE, _T( "the \'false\' literal must be lowercase" ));
val = false;
return nextCh;
}
else {
AddError( _T( "Unrecognized literal \'%s\' (did you forget quotes?)"), s );
return nextCh;
}
}
return nextCh;
}
//! Read a 4-hex-digit unicode character.
/*!
The function is called by ReadString() when the \b \\u sequence is
encontered; the sequence introduces a unicode character.
The function reads four chars from the input text by calling ReadChar()
four times: if -1( EOF) is encontered before reading four chars, -1 is
also returned and no conversion takes place.
The function tries to convert the 4-hex-digit sequence in an integer which
is returned in the \ hex parameter.
If the string cannot be converted, the function stores -1 in \c hex
and reports an error.
Returns the character after the hex sequence or -1 if EOF or if the
four characters cannot be converted to a hex number.
*/
int
wxJSONReader::ReadUnicode( long int& hex )
{
wxString s; int ch;
for ( int i = 0; i < 4; i++ ) {
ch = ReadChar();
if ( ch < 0 ) {
return ch;
}
s.append( 1, (wxChar) ch );
}
bool r = s.ToLong( &hex, 16 );
if ( !r ) {
hex = -1;
}
::wxLogTrace( traceMask, _T("(%s) unicode sequence=%s code=%d"),
__PRETTY_FUNCTION__, s.c_str(), (int) hex );
ch = ReadChar();
return ch;
}
//! Store the comment string in the value it refers to.
/*!
The function searches a suitable value object for storing the
comment line that was read by the parser and temporarly
stored in \c m_comment.
The function searches the three values pointed to by:
\li \c m_next
\li \c m_current
\li \c m_lastStored
The value that the comment refers to is:
\li if the comment is on the same line as one of the values, the comment
refer to that value and it is stored as \b inline.
\li otherwise, if the comment flag is wxJSONREADER_COMMENTS_BEFORE, the comment lines
are stored in the value pointed to by \c m_next
\li otherwise, if the comment flag is wxJSONREADER_COMMENTS_AFTER, the comment lines
are stored in the value pointed to by \c m_current or m_latStored
Note that the comment line is only stored if the wxJSONREADER_STORE_COMMENTS
flag was used when the parser object was constructed; otherwise, the
function does nothing and immediatly returns.
Also note that if the comment line has to be stored but the
function cannot find a suitable value to add the comment line to,
an error is reported (note: not a warning but an error).
*/
void
wxJSONReader::StoreComment( const wxJSONValue* parent )
{
::wxLogTrace( storeTraceMask, _T("(%s) m_comment=%s"), __PRETTY_FUNCTION__, m_comment.c_str());
::wxLogTrace( storeTraceMask, _T("(%s) m_flags=%d m_commentLine=%d"),
__PRETTY_FUNCTION__, m_flags, m_commentLine );
::wxLogTrace( storeTraceMask, _T("(%s) m_current=%p"), __PRETTY_FUNCTION__, m_current );
::wxLogTrace( storeTraceMask, _T("(%s) m_next=%p"), __PRETTY_FUNCTION__, m_next );
::wxLogTrace( storeTraceMask, _T("(%s) m_lastStored=%p"), __PRETTY_FUNCTION__, m_lastStored );
// first check if the 'store comment' bit is on
if ( (m_flags & wxJSONREADER_STORE_COMMENTS) == 0 ) {
m_comment.clear();
return;
}
// check if the comment is on the same line of one of the
// 'current', 'next' or 'lastStored' value
if ( m_current != 0 ) {
::wxLogTrace( storeTraceMask, _T("(%s) m_current->lineNo=%d"),
__PRETTY_FUNCTION__, m_current->GetLineNo() );
if ( m_current->GetLineNo() == m_commentLine ) {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to \'m_current\' INLINE"),
__PRETTY_FUNCTION__ );
m_current->AddComment( m_comment, wxJSONVALUE_COMMENT_INLINE );
m_comment.clear();
return;
}
}
if ( m_next != 0 ) {
::wxLogTrace( storeTraceMask, _T("(%s) m_next->lineNo=%d"),
__PRETTY_FUNCTION__, m_next->GetLineNo() );
if ( m_next->GetLineNo() == m_commentLine ) {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to \'m_next\' INLINE"),
__PRETTY_FUNCTION__ );
m_next->AddComment( m_comment, wxJSONVALUE_COMMENT_INLINE );
m_comment.clear();
return;
}
}
if ( m_lastStored != 0 ) {
::wxLogTrace( storeTraceMask, _T("(%s) m_lastStored->lineNo=%d"),
__PRETTY_FUNCTION__, m_lastStored->GetLineNo() );
if ( m_lastStored->GetLineNo() == m_commentLine ) {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to \'m_lastStored\' INLINE"),
__PRETTY_FUNCTION__ );
m_lastStored->AddComment( m_comment, wxJSONVALUE_COMMENT_INLINE );
m_comment.clear();
return;
}
}
// if comment is BEFORE, store the comment in the 'm_next'
// or 'm_current' value
// if comment is AFTER, store the comment in the 'm_lastStored'
// or 'm_current' value
if ( m_flags & wxJSONREADER_COMMENTS_AFTER ) { // comment AFTER
if ( m_current ) {
if ( m_current == parent || !m_current->IsValid()) {
AddError( _T("Cannot find a value for storing the comment (flag AFTER)"));
}
else {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to m_current (AFTER)"),
__PRETTY_FUNCTION__ );
m_current->AddComment( m_comment, wxJSONVALUE_COMMENT_AFTER );
}
}
else if ( m_lastStored ) {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to m_lastStored (AFTER)"),
__PRETTY_FUNCTION__ );
m_lastStored->AddComment( m_comment, wxJSONVALUE_COMMENT_AFTER );
}
else {
::wxLogTrace( storeTraceMask, _T("(%s) cannot find a value for storing the AFTER comment"),
__PRETTY_FUNCTION__ );
AddError(_T("Cannot find a value for storing the comment (flag AFTER)"));
}
}
else { // comment BEFORE can only be added to the 'next' value
if ( m_next ) {
::wxLogTrace( storeTraceMask, _T("(%s) comment added to m_next (BEFORE)"),
__PRETTY_FUNCTION__ );
m_next->AddComment( m_comment, wxJSONVALUE_COMMENT_BEFORE );
}
else {
// cannot find a value for storing the comment
AddError(_T("Cannot find a value for storing the comment (flag BEFORE)"));
}
}
m_comment.clear();
}
//! Return the number of bytes that make a character in stream input
/*!
This function is used by the GetChar() function when the JSON input
is from a stream object and returns the number of bytes that has to
be read from the stream in order to get a single wide character.
Because the encoding format of a JSON text in streams is UTF-8 and
no other formats are supported by now, the function just calls
UTF8NumBytes() function.
In order to implement new input formats from stream input, you have
to implement this function in order to return the correct number of
bytes and to set the appropriate value in the \c m_conv data member
which has to point to the conversion object.
For example, to implement UCS-4 Little Endian encoding:
\li this function must return 4
\li the \c m_conv data member must be set to point to an instance
of the wxMBConv("UCS4-LE") object
*/
int
wxJSONReader::NumBytes( char ch )
{
int n = UTF8NumBytes( ch );
return n;
}
//! Compute the number of bytes that makes a UTF-8 encoded wide character.
/*!
The function counts the number of '1' bit in the character \c ch and
returns it.
The UTF-8 encoding specifies the number of bytes needed by a wide character
by coding it in the first byte. See below.
Note that if the character does not contain a valid UTF-8 encoding
the function returns -1.
\code
UCS-4 range (hex.) UTF-8 octet sequence (binary)
------------------- -----------------------------
0000 0000-0000 007F 0xxxxxxx
0000 0080-0000 07FF 110xxxxx 10xxxxxx
0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx
\endcode
*/
int
wxJSONReader::UTF8NumBytes( char ch )
{
int num = 0; // the counter of '1' bits
for ( int i = 0; i < 8; i++ ) {
if ( (ch & 0x80) == 0 ) {
break;
}
++num;
ch = ch << 1;
}
// note that if the char contains more than six '1' bits it is not
// a valid UTF-8 encoded character
if ( num > 6 ) {
num = -1;
}
else if ( num == 0 ) {
num = 1;
}
return num;
}
//! The function appends the wide character to the string value
/*!
This function is called by \c ReadString() when a \e unicode \e escaped
\e sequence is read from the input text as for example (the greek letter
alpha):
\code
\u03B1
\endcode
In unicode mode, the function just appends the wide character code
stored in \c hex to the string \c s.
In ANSI mode, the function converts the wide character code to the
corresponding character if it is convertible using the locale dependent
character set.
If the wide char cannot be converted, the function appends the
\e unicode \e escape \e sequence to the string \c s.
Returns ZERO if the character was not converted to a unicode escape
sequence.
*/
int
wxJSONReader::AppendUnicodeSequence( wxString& s, int hex )
{
int r = 0;
#if defined( wxJSON_USE_UNICODE )
s.append( 1, (wxChar) hex );
#else
wchar_t ch = hex;
char buffer[10];
size_t len = wxConvLibc.FromWChar( buffer, 10, &ch, 1 );
if ( len != wxCONV_FAILED ) {
s.append( 1, buffer[0] );
}
else {
::wxSnprintf( buffer, 10, _T("\\u%04X"), hex );
s.append( buffer );
r = 1;
}
#endif
return r;
}
#if defined( wxJSON_64BIT_INT )
//! Converts a decimal string to a 64-bit signed integer
/*
This function implements a simple variant
of the \b strtoll C-library function.
I needed this implementation because the wxString::To(U)LongLong
function does not work on my system:
\li GNU/Linux Fedora Core 6
\li GCC version 4.1.1
\li libc.so.6
The wxWidgets library (actually I have installed version 2.8.7)
relies on \b strtoll in order to do the conversion from a string
to a long long integer but, in fact, it does not work because
the 'wxHAS_STRTOLL' macro is not defined on my system.
The problem only affects the Unicode builds while it seems
that the wxString::To(U)LongLong function works in ANSI builds.
To know more about see the \c Test58() function in the \c samples/test13.cpp
source file.
Note that this implementation is not a complete substitute of the
strtoll function because it only converts decimal strings (only base
10 is implemented).
*/
bool
wxJSONReader::Strtoll( const wxString& str, wxInt64* i64 )
{
wxChar sign = ' ';
wxUint64 ui64;
bool r = DoStrto_ll( str, &ui64, &sign );
// check overflow for signed long long
switch ( sign ) {
case '-' :
if ( ui64 > (wxUint64) LLONG_MAX + 1 ) {
r = false;
}
else {
*i64 = (wxInt64) (ui64 * -1);
}
break;
// case '+' :
default :
if ( ui64 > LLONG_MAX ) {
r = false;
}
else {
*i64 = (wxInt64) ui64;
}
break;
}
return r;
}
//! Converts a decimal string to a 64-bit unsigned integer.
bool
wxJSONReader::Strtoull( const wxString& str, wxUint64* ui64 )
{
wxChar sign = ' ';
bool r = DoStrto_ll( str, ui64, &sign );
if ( sign == '-' ) {
r = false;
}
return r;
}
//! Perform the actual conversion from a string to a 64-bit integer
/*!
This function is called internally by the Strtoll and Strtoull functions
and it does the actual conversion.
The function is also able to check numeric overflow.
*/
bool
wxJSONReader::DoStrto_ll( const wxString& str, wxUint64* ui64, wxChar* sign )
{
// the conversion is done by multiplying the individual digits
// in reverse order to the corresponding power of 10
//
// 10's power: 987654321.9876543210
//
// LLONG_MAX: 9223372036854775807
// LLONG_MIN: -9223372036854775808
// ULLONG_MAX: 18446744073709551615
//
// the function does not take into account the sign: only a
// unsigned long long int is returned
int maxDigits = 20; // 20 + 1 (for the sign)
wxUint64 power10[] = {
wxULL(1),
wxULL(10),
wxULL(100),
wxULL(1000),
wxULL(10000),
wxULL(100000),
wxULL(1000000),
wxULL(10000000),
wxULL(100000000),
wxULL(1000000000),
wxULL(10000000000),
wxULL(100000000000),
wxULL(1000000000000),
wxULL(10000000000000),
wxULL(100000000000000),
wxULL(1000000000000000),
wxULL(10000000000000000),
wxULL(100000000000000000),
wxULL(1000000000000000000),
wxULL(10000000000000000000)
};
wxUint64 temp1 = wxULL(0); // the temporary converted integer
int strLen = str.length();
if ( strLen == 0 ) {
// an empty string is converted to a ZERO value: the function succeeds
*ui64 = wxLL(0);
return true;
}
int index = 0;
wxChar ch = str[0];
if ( ch == '+' || ch == '-' ) {
*sign = ch;
++index;
++maxDigits;
}
if ( strLen > maxDigits ) {
return false;
}
// check the overflow: check the string length and the individual digits
// of the string; the overflow is checked for unsigned long long
if ( strLen == maxDigits ) {
wxString uLongMax( _T("18446744073709551615"));
int j = 0;
for ( int i = index; i < strLen - 1; i++ ) {
ch = str[i];
if ( ch < '0' || ch > '9' ) {
return false;
}
if ( ch > uLongMax[j] ) {
return false;
}
if ( ch < uLongMax[j] ) {
break;
}
++j;
}
}
// get the digits in the reverse order and multiply them by the
// corresponding power of 10
int exponent = 0;
for ( int i = strLen - 1; i >= index; i-- ) {
wxChar ch = str[i];
if ( ch < '0' || ch > '9' ) {
return false;
}
ch = ch - '0';
// compute the new temporary value
temp1 += ch * power10[exponent];
++exponent;
}
*ui64 = temp1;
return true;
}
#endif // defined( wxJSON_64BIT_INT )
/*
{
}
*/
| [
"Master@IBM-A89814EDA00.(none)"
]
| [
[
[
1,
1964
]
]
]
|
9a1413553eb38de78d034b2e2b789ff44e230db9 | 738cf147e038d90ffb912ed4995dc400bc7f2f8a | /Vision/Ass1/Postboxes/postboxes.cpp | 3535b0d9c58eee326ce83c0892b865af28ca0d60 | []
| no_license | Newky/4thYear | c50b87d7893280226012c7e2b0ae839d3a87feaf | 81733220ccfbe2372630ce50bd07e26d36ae9a88 | refs/heads/master | 2020-06-02T22:28:26.529074 | 2011-12-20T11:24:45 | 2011-12-20T11:24:45 | 2,483,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,309 | cpp | #ifdef _CH_
#pragma package <opencv>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "cv.h"
#include "highgui.h"
#include "../utilities.h"
#define VARIATION_ALLOWED_IN_PIXEL_VALUES 31
#define ALLOWED_MOTION_FOR_MOTION_FREE_IMAGE 1.0
#define NUMBER_OF_POSTBOXES 6
#define MINIMUM_GRADIENT_VALUE 5
int PostboxLocations[NUMBER_OF_POSTBOXES][5] = {
{ 6, 73, 95, 5, 92 }, { 6, 73, 95, 105, 192 },
{ 105, 158, 193, 5, 92 }, { 105, 158, 193, 105, 192 },
{ 204, 245, 292, 5, 92 }, { 204, 245, 292, 105, 192 } };
/* Thresholds set up individually for each postbox.
* Getting these thresholds, I had to generate
* graphs based on the number of lines usual in each postbox
* The values vary because of lighting, and different things.*/
int thresholds[NUMBER_OF_POSTBOXES] ={15,11,9,13,14,12};
/* A global pointer to the previous frame
* and the previous output frame.
*/
IplImage * prev_frame;
IplImage * prev_output_frame;
#define POSTBOX_TOP_ROW 0
#define POSTBOX_TOP_BASE_ROW 1
#define POSTBOX_BOTTOM_ROW 2
#define POSTBOX_LEFT_COLUMN 3
#define POSTBOX_RIGHT_COLUMN 4
void indicate_post_in_box( IplImage* image, int postbox )
{
write_text_on_image(image,(PostboxLocations[postbox][POSTBOX_TOP_ROW]+PostboxLocations[postbox][POSTBOX_BOTTOM_ROW])/2,PostboxLocations[postbox][POSTBOX_LEFT_COLUMN]+2, "Post in");
write_text_on_image(image,(PostboxLocations[postbox][POSTBOX_TOP_ROW]+PostboxLocations[postbox][POSTBOX_BOTTOM_ROW])/2+19,PostboxLocations[postbox][POSTBOX_LEFT_COLUMN]+2, "this box");
}
/* Using a 3 X 3 Mask
* Generate a first derivate of the input image
* for the pixel pointed to by f(row, col)
*/
int first_derivative_with_mask(IplImage* input_image, int row, int col, int mask[3][3]) {
int width_step=input_image->widthStep;
int pixel_step=input_image->widthStep/input_image->width;
int i=0;
int fd = 0;
for(;i<3;i++) {
int j=0;
for(;j<3;j++) {
if(!((row - (i - 2) < 0) && (row + (i - 2) >= input_image->height))){
if(!((col - (j - 2) < 0) && (col + (j - 2) >= input_image->width))){
int mod_row = row + (i - 2);
int mod_col = col + (j - 2);
unsigned char* curr_point = (unsigned char *) GETPIXELPTRMACRO(input_image, mod_col, mod_row, width_step, pixel_step);
fd += (curr_point[0] * mask[i][j]);
}
}
}
}
return fd;
};
/* This uses sobels technique on a single pixel
* in input image,f(row, col).
* It also stores the first derivative of the pixel
* in the fd_image which stores the first derivatives
* for the image.
*/
void sobel(IplImage* input_image,IplImage*output_image,IplImage*fd_image, int row, int col){
int width_step=fd_image->widthStep;
int pixel_step=fd_image->widthStep/fd_image->width;
int width_step2=output_image->widthStep;
int pixel_step2=output_image->widthStep/output_image->width;
int mask[3][3] = {{1, 0, -1}, {2, 0, -2}, {1, 0, -1}};
int fd = abs(first_derivative_with_mask(input_image, row, col, mask));
unsigned char fd_[] = {fd};
PUTPIXELMACRO(fd_image, col, row,fd_,width_step, pixel_step, fd_image->nChannels);
/*Because I'm only calculating the first derivated partial for the vertical mask
* I had to trick around with the MINIMUM GRADIENT VALUE */
if(fd> MINIMUM_GRADIENT_VALUE + 40 ){
unsigned char red[] = {0,0,255,0};
PUTPIXELMACRO(output_image, col, row, red,width_step2, pixel_step2, output_image->nChannels);
}else{
unsigned char black[] = {0,0,0,0};
PUTPIXELMACRO(output_image, col, row, black,width_step2, pixel_step2, output_image->nChannels);
}
}
/* Given an output image, which already has edges denoted by 255
* in the red channel. and a first derivate image which contains the
* first derivative value for each pixel. Then for a certain row, col
* Do non maxima suppression as follows:
* We assume the orientation of the edges are 90 vertical angles.
* Meaning the orthogonal pairs are the pixels either side of it.
* the non maxima formula works as follows.
*
* Foreach i, j in image:
* if gradient(f(i, j)) < gradient(f(i, j-1)) || gradient(f(i, j+1)):
* f(i, j) = 0
*
* Through this method the thickness of the edges will be reduced.
*/
void non_maxima(IplImage * output_image, IplImage * fd_image, int row, int col) {
int width_step=fd_image->widthStep;
int pixel_step=fd_image->widthStep/fd_image->width;
int width_step2=output_image->widthStep;
int pixel_step2=output_image->widthStep/output_image->width;
unsigned char black[] = {0,0,0,0};
unsigned char* curr_point = (unsigned char *) GETPIXELPTRMACRO(output_image, col, row, width_step2, pixel_step2);
if(curr_point[RED_CH] == 255) {
unsigned char* fd_point = (unsigned char *) GETPIXELPTRMACRO(fd_image, col, row, width_step, pixel_step);
//Examine the orthogonal pair of this pixel. i.e one to the left and one to the right.
// Because orientation is upwards.
if(col -1 > 0) {
unsigned char* to_the_left = (unsigned char *) GETPIXELPTRMACRO(fd_image, col-1, row, width_step, pixel_step);
if(fd_point[0] <= to_the_left[0]){
PUTPIXELMACRO(output_image, col, row, black,width_step2, pixel_step2, output_image->nChannels);
return;
}
}
if(col + 1 < fd_image->width) {
unsigned char* to_the_right = (unsigned char *) GETPIXELPTRMACRO(fd_image, col+1, row, width_step, pixel_step);
if(fd_point[0] <= to_the_right[0]){
PUTPIXELMACRO(output_image, col, row, black,width_step2, pixel_step2, output_image->nChannels);
return;
}
}
}
}
/* This is the function which determines where the edges are in
* the postboxes which can be used to detect post.
*/
void compute_vertical_edge_image(IplImage* input_image, IplImage* output_image)
{
// Firstly we create a grayscale interpretation of the image
IplImage *gray_input= cvCreateImage( cvGetSize(input_image), 8, 1 );
cvConvertImage(input_image, gray_input);
// Image (store) for the partial first derivate (vertical) of the image
IplImage *fd_image= cvCreateImage( cvGetSize(input_image), 8, 1 );
// Smooth the grayscale image, (This is to get rid of noise which might affect the
// image.
cvSmooth(gray_input, gray_input, CV_GAUSSIAN, 3, 3, 0);
// Get the width step and pixel step of the inputs. and number of channels.
int width_step=gray_input->widthStep;
int pixel_step=gray_input->widthStep/gray_input->width;
int number_channels=gray_input->nChannels;
/*For each f(i, j) in image
*Do the sobel function on it, giving it the grayscale image
* and a row and column and it will give out an
* output image and a first derivative image.*/
int row=0,col=0;
for(;row < gray_input->height; row ++) {
for(col = 0;col < gray_input->width; col ++ ) {
sobel(gray_input, output_image,fd_image, row, col);
}
}
/* We then need to loop through the image again,
* to do non-maxima suppression on the image.
* The output image is used as both an input and an
* output here.
*/
for(row=0;row < gray_input->height; row ++) {
for(col = 0;col < gray_input->width; col ++ ) {
non_maxima(output_image, fd_image, row, col);
}
}
};
/* This function determines whether or not there is movement in
* the video based on the number of pixels which have changed
* beyond a certain threshold constant.
*/
bool motion_free_frame(IplImage* current_frame, IplImage* previous_frame)
{
int width_step=current_frame->widthStep;
int pixel_step=current_frame->widthStep/current_frame->width;
int number_channels=current_frame->nChannels;
int row=0,col=0;
int changed = 0;
for(;row < current_frame->height; row ++) {
for(col = 0;col < current_frame->width; col ++ ) {
unsigned char* curr_point = (unsigned char *) GETPIXELPTRMACRO(current_frame,col, row,width_step, pixel_step);
unsigned char* prev_point = (unsigned char *) GETPIXELPTRMACRO(previous_frame,col, row,width_step, pixel_step);
int i=0, sum1 =0, sum2=0;
for(;i<number_channels;i++){
sum1 += curr_point[i];
sum2 += prev_point[i];
}
changed += (abs(sum1 -sum2) > (VARIATION_ALLOWED_IN_PIXEL_VALUES*3));
}
}
int percentage = (((double) changed)/((double) current_frame->height * current_frame->width)) * 100;
return (percentage < ALLOWED_MOTION_FOR_MOTION_FREE_IMAGE);
}
/* This function is fed a red edge point
* and draws its way upward looking for other redpoints
* so it can make a chain.
* it returns the number of pixels in the
* vertical chain.
*/
int pixel_count(IplImage*input_image, int col,int row) {
int width_step=input_image->widthStep;;
int pixel_step=input_image->widthStep/input_image->width;
int pixel_no = 0;
row--;
while(row != -1 && col != -1) {
pixel_no += 1;
unsigned char* curr_point = (unsigned char *) GETPIXELPTRMACRO(input_image, col, row, width_step, pixel_step);
unsigned char* prev_point= (unsigned char *) GETPIXELPTRMACRO(input_image, col-1, row, width_step, pixel_step);
unsigned char* next_point = (unsigned char *) GETPIXELPTRMACRO(input_image, col+1, row, width_step, pixel_step);
unsigned char red[] = {0,0,255,0};
if(curr_point[RED_CH] != 255 && prev_point[RED_CH] != 255 && next_point[RED_CH] != 255){
break;
}else if(next_point[RED_CH] == 255){
PUTPIXELMACRO(input_image, col+1, row, red,width_step, pixel_step, input_image->nChannels);
col = col + 1;
}else if(prev_point[RED_CH] == 255){
PUTPIXELMACRO(input_image, col-1, row, red,width_step, pixel_step, input_image->nChannels);
col = col - 1;
}else{
PUTPIXELMACRO(input_image, col, row, red,width_step, pixel_step, input_image->nChannels);
}
row --;
};
return pixel_no;
};
/* if no motion is detected in the
* frame then we can compute the vertical edges otherwise. do nothing.
* I changed labelled_output_image to a pointer to a pointer so I could clone within the function
*/
void check_postboxes(IplImage* input_image, IplImage** labelled_output_image, IplImage* vertical_edge_image )
{
if(motion_free_frame(input_image, prev_frame)){
compute_vertical_edge_image(input_image, vertical_edge_image);
int width_step=vertical_edge_image->widthStep;
int pixel_step=vertical_edge_image->widthStep/vertical_edge_image->width;
for(int pb=0;pb<6;pb++){
int *postbox = PostboxLocations[pb];
int row=postbox[POSTBOX_BOTTOM_ROW],col=postbox[POSTBOX_LEFT_COLUMN], redcount=0;
for(col=postbox[POSTBOX_LEFT_COLUMN];col < postbox[POSTBOX_RIGHT_COLUMN]; col++) {
unsigned char* curr_point = (unsigned char *) GETPIXELPTRMACRO(vertical_edge_image,col,row,width_step, pixel_step);
if(curr_point[RED_CH] == 255) {
int pixel_no= pixel_count(vertical_edge_image, col, row);
if(pixel_no > 5)
redcount += 1;
}
}
if(redcount < thresholds[pb] - 5)
indicate_post_in_box(*labelled_output_image, pb);
}
}else {
*labelled_output_image = cvCloneImage( prev_output_frame );
}
};
int main( int argc, char** argv )
{
IplImage *current_frame=NULL;
CvSize size;
size.height = 300; size.width = 200;
IplImage *corrected_frame = cvCreateImage( size, IPL_DEPTH_8U, 3 );
IplImage *labelled_image=NULL;
IplImage *vertical_edge_image=NULL;
int user_clicked_key=0;
// Load the video (AVI) file
CvCapture *capture = cvCaptureFromAVI( "./Postboxes.avi" );
// Ensure AVI opened properly
if( !capture )
return 1;
// Get Frames Per Second in order to playback the video at the correct speed
int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS );
// Explain the User Interface
printf( "Hot keys: \n"
"\tESC - quit the program\n"
"\tSPACE - pause/resume the video\n");
//What?
CvPoint2D32f from_points[4] = { {3, 6}, {221, 11}, {206, 368}, {18, 373} };
CvPoint2D32f to_points[4] = { {0, 0}, {200, 0}, {200, 300}, {0, 300} };
//Multi Channel Matrix
CvMat* warp_matrix = cvCreateMat( 3,3,CV_32FC1 );
cvGetPerspectiveTransform( from_points, to_points, warp_matrix );
// Create display windows for images
cvNamedWindow( "Input video", 0 );
cvMoveWindow("Input video", 0, 0);
cvNamedWindow( "Vertical edges", 0 );
cvMoveWindow( "Vertical edges", 360, 0);
cvNamedWindow( "Results", 0 );
cvMoveWindow( "Results", 720, 0);
// Setup mouse callback on the original image so that the user can see image values as they move the
// cursor over the image.
cvSetMouseCallback( "Input video", on_mouse_show_values, 0 );
window_name_for_on_mouse_show_values="Input video";
while( user_clicked_key != ESC ) {
// Get current video frame
prev_frame = cvCloneImage(corrected_frame);
if(labelled_image != NULL)
prev_output_frame = cvCloneImage(labelled_image);
current_frame = cvQueryFrame( capture );
image_for_on_mouse_show_values=current_frame; // Assign image for mouse callback
if( !current_frame ) // No new frame available
break;
cvWarpPerspective( current_frame, corrected_frame, warp_matrix );
if (labelled_image == NULL)
{ // The first time around the loop create the image for processing
prev_frame = cvCloneImage(corrected_frame);
prev_output_frame = cvCloneImage(corrected_frame);
labelled_image = cvCloneImage( corrected_frame );
vertical_edge_image = cvCloneImage( corrected_frame );
}
labelled_image = cvCloneImage( corrected_frame );
check_postboxes( corrected_frame, &(labelled_image), vertical_edge_image );
//IplImage *gframe= cvCreateImage( cvGetSize(corrected_frame),8, 1 );
//IplImage *outputframe= cvCreateImage( cvGetSize(corrected_frame),8, 3 );
//cvConvertImage(corrected_frame, gframe);
//compute_vertical_edge_image(gframe, outputframe);
// Display the current frame and results of processing
cvShowImage( "Input video", current_frame);
cvShowImage( "Vertical edges",vertical_edge_image);
cvShowImage( "Results",labelled_image);
// Wait for the delay between frames
user_clicked_key = (char) cvWaitKey( 1000 / fps );
if (user_clicked_key == ' ')
{
user_clicked_key = cvWaitKey(0);
}
}
/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "video" );
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
354
]
]
]
|
934946b289728b5f81371bd5ce2cc8c6659498c2 | 6fbf3695707248bfb00e3f8c4a0f9adf5d8a3d4c | /java/testjava/vs_regex_tests/vs_regex_tests.cpp | b1d6329365569523474f76cb07a2f78bfb7555ab | []
| no_license | ochafik/cppjvm | c554a2f224178bc3280f03919aff9287bd912024 | e1feb48eee3396d3a5ecb539de467c0a8643cba0 | refs/heads/master | 2020-12-25T16:02:38.582622 | 2011-11-17T00:11:35 | 2011-11-17T00:11:35 | 2,790,123 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp | // vs_regex_tests.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"danielearwicker@ubuntu.(none)"
]
| [
[
[
1,
11
]
]
]
|
37c78267c28603690f47f914c944cddcae7e0695 | 00e841811d72cc6b6990b8c0bd38365a1290e976 | /v1.1/source/system/fifo/fifo.h | 64a7a648650df048de63a2ef9d31e252f127ddc7 | []
| no_license | kurochan/OASIS | 625aaa829fe32a95eaf7f44e82466b6698ddbfa8 | 17c0ecd6b00cbfc34d6e0217b28b81330c1cba21 | refs/heads/master | 2021-01-01T05:34:25.877020 | 2011-01-30T15:33:00 | 2011-01-30T15:33:00 | 1,313,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | h | //=========================================
// OASIS Kernel header code
// Copyright (C) 2010 soS.A
//=========================================
/* FIFOバッファ */
class FIFO {
// INPUTCTLクラスに継承されるから
protected:
// *buf : 記憶バッファ
// p : 書き込み位置
// q : 読み込み位置
// size : バッファサイズ
// free_s_size : バッファ空き容量のサイズ
public:
UINT *buf, p, q, size, free_s_size;
FIFO(const UINT datasize);
~FIFO(void);
void put(const UINT data); // データ追加
UINT get(void); // データ取得
UINT status(void) const; // データ量取得
};
/* どのくらいデータが溜まっているかを報告する */
inline UINT FIFO::status(void) const{
return size - free_s_size;
}
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
1a59707dd553ae9b5064803033e60b955e2fa4a4 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/samp/samp_api.cpp | 95309e690701370b2a1b61ec5a7438d64528aed5 | []
| no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 66,153 | cpp | #include "config.hpp"
#include "samp_api.hpp"
#include <functional>
#include <boost/foreach.hpp>
#include "pawn/pawn_marshaling.hpp"
#include "samp_events.hpp"
#include "core/application.hpp"
#if defined(_DEBUG) && defined(_MSC_VER)
#include <Windows.h>
#endif // if defined(_DEBUG) && defined(
namespace samp {
namespace {
//Данные для маршалинга аргументов в павн
pawn::marh_collection_t marhs; // Должен быть до объявлений marh_t
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_objects.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pawn::marh_t<int, float, float, float, float, float, float, float> create_object_t("CreateObject", marhs);
pawn::marh_t<int, float, float, float> set_object_pos_t("SetObjectPos", marhs);
pawn::marh_t<int, float&, float&, float&> get_object_pos_t("GetObjectPos", marhs);
pawn::marh_t<int, float, float, float> set_object_rot_t("SetObjectRot", marhs);
pawn::marh_t<int, float&, float&, float&> get_object_rot_t("GetObjectRot", marhs);
pawn::marh_t<int> is_valid_object_t("IsValidObject", marhs);
pawn::marh_t<int> destroy_object_t("DestroyObject", marhs);
pawn::marh_t<int, float, float, float, float> move_object_t("MoveObject", marhs);
pawn::marh_t<int> stop_object_t("StopObject", marhs);
pawn::marh_t<int, int, float, float, float, float, float, float, float> create_player_object_t("CreatePlayerObject", marhs);
pawn::marh_t<int, int, float, float, float> set_player_object_pos_t("SetPlayerObjectPos", marhs);
pawn::marh_t<int, int, float&, float&, float&> get_player_object_pos_t("GetPlayerObjectPos", marhs);
pawn::marh_t<int, int, float, float, float> set_player_object_rot_t("SetPlayerObjectRot", marhs);
pawn::marh_t<int, int, float&, float&, float&> get_player_object_rot_t("GetPlayerObjectRot", marhs);
pawn::marh_t<int, int> is_valid_player_object_t("IsValidPlayerObject", marhs);
pawn::marh_t<int, int> destroy_player_object_t("DestroyPlayerObject", marhs);
pawn::marh_t<int, int, float, float, float, float> move_player_object_t("MovePlayerObject", marhs);
pawn::marh_t<int, int> stop_player_object_t("StopPlayerObject", marhs);
pawn::marh_t<int, int, float, float, float, float, float, float> attach_object_to_player_t("AttachObjectToPlayer", marhs);
pawn::marh_t<int, int, int, float, float, float, float, float, float> attach_player_object_to_player_t("AttachPlayerObjectToPlayer", marhs);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_players.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Player
pawn::marh_t<int, int, int, float, float, float, float, int, int, int, int, int, int> set_spawn_info_t("SetSpawnInfo", marhs);
pawn::marh_t<int> spawn_player_t("SpawnPlayer", marhs);
// Player info
pawn::marh_t<int, float, float, float> set_player_pos_t("SetPlayerPos", marhs);
pawn::marh_t<int, float, float, float> set_player_pos_findz_t("SetPlayerPosFindZ", marhs);
pawn::marh_t<int, float&, float&, float&> get_player_pos_t("GetPlayerPos", marhs);
pawn::marh_t<int, float> set_player_facing_angle_t("SetPlayerFacingAngle", marhs);
pawn::marh_t<int, float&> get_player_facing_angle_t("GetPlayerFacingAngle", marhs);
pawn::marh_t<int, float, float, float, float> is_player_in_range_of_point_t("IsPlayerInRangeOfPoint", marhs);
pawn::marh_t<int, int> is_player_streamed_in_t("IsPlayerStreamedIn", marhs);
pawn::marh_t<int, int> set_player_interior_t("SetPlayerInterior", marhs);
pawn::marh_t<int> get_player_interior_t("GetPlayerInterior", marhs);
pawn::marh_t<int, float> set_player_health_t("SetPlayerHealth", marhs);
pawn::marh_t<int, float&> get_player_health_t("GetPlayerHealth", marhs);
pawn::marh_t<int, float> set_player_armour_t("SetPlayerArmour", marhs);
pawn::marh_t<int, float&> get_player_armour_t("GetPlayerArmour", marhs);
pawn::marh_t<int, int, int> set_player_ammo_t("SetPlayerAmmo", marhs);
pawn::marh_t<int> get_player_ammo_t("GetPlayerAmmo", marhs);
pawn::marh_t<int> get_player_weapon_state_t("GetPlayerWeaponState", marhs);
pawn::marh_t<int, int> set_player_team_t("SetPlayerTeam", marhs);
pawn::marh_t<int> get_player_team_t("GetPlayerTeam", marhs);
pawn::marh_t<int, int> set_player_score_t("SetPlayerScore", marhs);
pawn::marh_t<int> get_player_score_t("GetPlayerScore", marhs);
pawn::marh_t<int> get_player_drunk_level_t("GetPlayerDrunkLevel", marhs);
pawn::marh_t<int, int> set_player_drunk_level_t("SetPlayerDrunkLevel", marhs);
pawn::marh_t<int, unsigned> set_player_color_t("SetPlayerColor", marhs);
pawn::marh_t<int> get_player_color_t("GetPlayerColor", marhs);
pawn::marh_t<int, int> set_player_skin_t("SetPlayerSkin", marhs);
pawn::marh_t<int> get_player_skin_t("GetPlayerSkin", marhs);
pawn::marh_t<int, int, int> give_player_weapon_t("GivePlayerWeapon", marhs);
pawn::marh_t<int> reset_player_weapons_t("ResetPlayerWeapons", marhs);
pawn::marh_t<int, int> set_player_armed_weapon_t("SetPlayerArmedWeapon", marhs);
pawn::marh_t<int, int, int&, int&> get_player_weapon_data_t("GetPlayerWeaponData", marhs);
pawn::marh_t<int, int> give_player_money_t("GivePlayerMoney", marhs);
pawn::marh_t<int> reset_player_money_t("ResetPlayerMoney", marhs);
pawn::marh_t<int, std::string const&> set_player_name_t("SetPlayerName", marhs);
pawn::marh_t<int> get_player_money_t("GetPlayerMoney", marhs);
pawn::marh_t<int> get_player_state_t("GetPlayerState", marhs);
pawn::marh_t<int, std::string&, pawn::string_len> get_player_ip_t("GetPlayerIp", marhs);
pawn::marh_t<int> get_player_ping_t("GetPlayerPing", marhs);
pawn::marh_t<int> get_player_weapon_t("GetPlayerWeapon", marhs);
pawn::marh_t<int, int&, int&, int&> get_player_keys_t("GetPlayerKeys", marhs);
pawn::marh_t<int, std::string&, pawn::string_len> get_player_name_t("GetPlayerName", marhs);
pawn::marh_t<int, int, int> set_player_time_t("SetPlayerTime", marhs);
pawn::marh_t<int, int&, int&> get_player_time_t("GetPlayerTime", marhs);
pawn::marh_t<int, int> toggle_player_clock_t("TogglePlayerClock", marhs);
pawn::marh_t<int, int> set_player_weather_t("SetPlayerWeather", marhs);
pawn::marh_t<int> force_class_selection_t("ForceClassSelection", marhs);
pawn::marh_t<int, int> set_player_wanted_level_t("SetPlayerWantedLevel", marhs);
pawn::marh_t<int> get_player_wanted_level_t("GetPlayerWantedLevel", marhs);
pawn::marh_t<int, int> set_player_fighting_style_t("SetPlayerFightingStyle", marhs);
pawn::marh_t<int> get_player_fighting_style_t("GetPlayerFightingStyle", marhs);
pawn::marh_t<int, float, float, float> set_player_velocity_t("SetPlayerVelocity", marhs);
pawn::marh_t<int, float&, float&, float&> get_player_velocity_t("GetPlayerVelocity", marhs);
pawn::marh_t<int, int, int> play_crime_report_for_player_t("PlayCrimeReportForPlayer", marhs);
pawn::marh_t<int, std::string const&> set_player_shop_name_t("SetPlayerShopName", marhs);
pawn::marh_t<int, int, int> set_player_skill_level_t("SetPlayerSkillLevel", marhs);
pawn::marh_t<int> get_player_surfing_vehicle_id_t("GetPlayerSurfingVehicleID", marhs);
pawn::marh_t<int, int, int, float, float, float, float, float, float> set_player_holding_object_t("SetPlayerHoldingObject", marhs);
pawn::marh_t<int> stop_player_holding_object_t("StopPlayerHoldingObject", marhs);
pawn::marh_t<int> is_player_holding_object_t("IsPlayerHoldingObject", marhs);
pawn::marh_t<int, std::string const&, unsigned int, float, int> set_player_chat_bubble_t("SetPlayerChatBubble", marhs);
// Player controls
pawn::marh_t<int, int, int> put_player_in_vehicle_t("PutPlayerInVehicle", marhs);
pawn::marh_t<int> get_player_vehicle_id_t("GetPlayerVehicleID", marhs);
pawn::marh_t<int> get_player_vehicle_seat_t("GetPlayerVehicleSeat", marhs);
pawn::marh_t<int> remove_player_from_vehicle_t("RemovePlayerFromVehicle", marhs);
pawn::marh_t<int, bool> toggle_player_controllable_t("TogglePlayerControllable", marhs);
pawn::marh_t<int, int, float, float, float> player_play_sound_t("PlayerPlaySound", marhs);
pawn::marh_t<int, std::string const&, std::string const&, float, int, int, int, int, int, int> apply_animation_t("ApplyAnimation", marhs);
pawn::marh_t<int, int> clear_animations_t("ClearAnimations", marhs);
pawn::marh_t<int> get_player_animation_index_t("GetPlayerAnimationIndex", marhs);
pawn::marh_t<int, std::string&, pawn::string_len, std::string&, pawn::string_len> get_animation_name_t("GetAnimationName", marhs);
pawn::marh_t<int> get_player_special_action_t("GetPlayerSpecialAction", marhs);
pawn::marh_t<int, int> set_player_special_action_t("SetPlayerSpecialAction", marhs);
// Player world/map related
pawn::marh_t<int, float, float, float, float> set_player_checkpoint_t("SetPlayerCheckpoint", marhs);
pawn::marh_t<int> disable_player_checkpoint_t("DisablePlayerCheckpoint", marhs);
pawn::marh_t<int, int, float, float, float, float, float, float, float> set_player_race_checkpoint_t("SetPlayerRaceCheckpoint", marhs);
pawn::marh_t<int> disable_player_race_checkpoint_t("DisablePlayerRaceCheckpoint", marhs);
pawn::marh_t<int, float, float, float, float> set_player_world_bounds_t("SetPlayerWorldBounds", marhs);
pawn::marh_t<int, int, unsigned> set_player_marker_for_player_t("SetPlayerMarkerForPlayer", marhs);
pawn::marh_t<int, int, bool> show_player_name_tag_for_player_t("ShowPlayerNameTagForPlayer", marhs);
pawn::marh_t<int, int, float, float, float, int, unsigned> set_player_mapicon_t("SetPlayerMapIcon", marhs);
pawn::marh_t<int, int> remove_player_mapicon_t("RemovePlayerMapIcon", marhs);
pawn::marh_t<int, bool> allow_player_teleport_t("AllowPlayerTeleport", marhs);
// Player camera
pawn::marh_t<int, float, float, float> set_player_camera_pos_t("SetPlayerCameraPos", marhs);
pawn::marh_t<int, float, float, float> set_player_camera_look_at_t("SetPlayerCameraLookAt", marhs);
pawn::marh_t<int> set_camera_behind_player_t("SetCameraBehindPlayer", marhs);
pawn::marh_t<int, float&, float&, float&> get_player_camera_pos_t("GetPlayerCameraPos", marhs);
pawn::marh_t<int, float&, float&, float&> get_player_camera_front_vector_t("GetPlayerCameraFrontVector", marhs);
// Player conditionals
pawn::marh_t<int> is_player_called_t("IsPlayerConnected", marhs);
pawn::marh_t<int, int> is_player_in_vehicle_t("IsPlayerInVehicle", marhs);
pawn::marh_t<int> is_player_in_any_vehicle_t("IsPlayerInAnyVehicle", marhs);
pawn::marh_t<int> is_player_in_checkpoint_t("IsPlayerInCheckpoint", marhs);
pawn::marh_t<int> is_player_in_race_checkpoint_t("IsPlayerInRaceCheckpoint", marhs);
// Virtual Worlds
pawn::marh_t<int, int> set_player_virtual_world_t("SetPlayerVirtualWorld", marhs);
pawn::marh_t<int> get_player_virtual_world_t("GetPlayerVirtualWorld", marhs);
// Insane Stunts
pawn::marh_t<int, bool> enable_stunt_bonus_for_player_t("EnableStuntBonusForPlayer", marhs);
pawn::marh_t<bool> enable_stunt_bonus_for_all_t("EnableStuntBonusForAll", marhs);
// Spectating
pawn::marh_t<int, bool> toggle_player_spectating_t("TogglePlayerSpectating", marhs);
pawn::marh_t<int, int, int> player_spectate_player_t("PlayerSpectatePlayer", marhs);
pawn::marh_t<int, int, int> player_spectate_vehicle_t("PlayerSpectateVehicle", marhs);
// Recording for NPC playback
pawn::marh_t<int, int, std::string const&> start_recording_player_data_t("StartRecordingPlayerData", marhs);
pawn::marh_t<int> stop_recording_player_data_t("StopRecordingPlayerData", marhs);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_samp.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Util
pawn::marh_t<int, unsigned, std::string const&> send_client_message_t("SendClientMessage", marhs);
pawn::marh_t<int, int, std::string const&> send_player_message_to_player_t("SendPlayerMessageToPlayer", marhs);
pawn::marh_t<int, int, int> send_death_message_t("SendDeathMessage", marhs);
pawn::marh_t<int, std::string const&, int, int> game_text_for_player_t("GameTextForPlayer", marhs);
pawn::marh_t<> get_max_players_t("GetMaxPlayers", marhs);
// Game
pawn::marh_t<std::string const&> set_game_mode_text_t("SetGameModeText", marhs);
pawn::marh_t<int> set_team_count_t("SetTeamCount", marhs);
pawn::marh_t<int, float, float, float, float, int, int, int, int, int, int> add_player_class_t("AddPlayerClass", marhs);
pawn::marh_t<int, int, float, float, float, float, int, int, int, int, int, int> add_player_class_ex_t("AddPlayerClassEx", marhs);
pawn::marh_t<int, float, float, float, float, int, int> add_static_vehicle_t("AddStaticVehicle", marhs);
pawn::marh_t<int, float, float, float, float, int, int, int> add_static_vehicle_ex_t("AddStaticVehicleEx", marhs);
pawn::marh_t<int, int, float, float, float, int> add_static_pickup_t("AddStaticPickup", marhs);
pawn::marh_t<int, int, float, float, float, int> create_pickup_t("CreatePickup", marhs);
pawn::marh_t<int> destroy_pickup_t("DestroyPickup", marhs);
pawn::marh_t<bool> show_name_tags_t("ShowNameTags", marhs);
pawn::marh_t<int> show_player_markers_t("ShowPlayerMarkers", marhs);
pawn::marh_t<> gamemode_exit_t("GameModeExit", marhs);
pawn::marh_t<int> set_world_time_t("SetWorldTime", marhs);
pawn::marh_t<int, std::string&, pawn::string_len> get_weapon_name_t("GetWeaponName", marhs);
pawn::marh_t<bool> enable_tire_popping_t("EnableTirePopping", marhs);
pawn::marh_t<bool> allow_interior_weapons_t("AllowInteriorWeapons", marhs);
pawn::marh_t<int> set_weather_t("SetWeather", marhs);
pawn::marh_t<float> set_gravity_t("SetGravity", marhs);
pawn::marh_t<bool> allow_admin_teleport_t("AllowAdminTeleport", marhs);
pawn::marh_t<int> set_death_drop_amount_t("SetDeathDropAmount", marhs);
pawn::marh_t<float, float, float, int, float> create_explosion_t("CreateExplosion", marhs);
pawn::marh_t<bool> enable_zone_names_t("EnableZoneNames", marhs);
pawn::marh_t<> use_player_ped_anims_t("UsePlayerPedAnims", marhs);
pawn::marh_t<> disable_interior_enter_exits_t("DisableInteriorEnterExits", marhs);
pawn::marh_t<float> set_name_tag_draw_distance_t("SetNameTagDrawDistance", marhs);
pawn::marh_t<> disable_name_tag_los_t("DisableNameTagLOS", marhs);
pawn::marh_t<float> limit_global_chat_radius_t("LimitGlobalChatRadius", marhs);
pawn::marh_t<float> limit_player_marker_radius_t("LimitPlayerMarkerRadius", marhs);
// Npc
pawn::marh_t<std::string const&, std::string const&> call_npc_t("ConnectNPC", marhs);
pawn::marh_t<int> is_player_npc_t("IsPlayerNPC", marhs);
// Admin
pawn::marh_t<int> is_player_admin_t("IsPlayerAdmin", marhs);
pawn::marh_t<int> kick_t("Kick", marhs);
pawn::marh_t<int> ban_t("Ban", marhs);
pawn::marh_t<int, std::string const&> ban_ex_t("BanEx", marhs);
pawn::marh_t<std::string const&> send_rcon_command_t("SendRconCommand", marhs);
pawn::marh_t<std::string const&, std::string&, pawn::string_len> get_server_var_as_string_t("GetServerVarAsString", marhs);
pawn::marh_t<std::string const&> get_server_var_as_int_t("GetServerVarAsInt", marhs);
pawn::marh_t<std::string const&> get_server_var_as_bool_t("GetServerVarAsBool", marhs);
// Menu
pawn::marh_t<std::string const&, int, float, float, float, float> create_menu_t("CreateMenu", marhs);
pawn::marh_t<int> destroy_menu_t("DestroyMenu", marhs);
pawn::marh_t<int, int, std::string const&> add_menu_item_t("AddMenuItem", marhs);
pawn::marh_t<int, int, std::string const&> set_menu_column_header_t("SetMenuColumnHeader", marhs);
pawn::marh_t<int, int> show_menu_for_player_t("ShowMenuForPlayer", marhs);
pawn::marh_t<int, int> hide_menu_for_player_t("HideMenuForPlayer", marhs);
pawn::marh_t<int> is_valid_menu_t("IsValidMenu", marhs);
pawn::marh_t<int> disable_menu_t("DisableMenu", marhs);
pawn::marh_t<int, int> disable_menu_row_t("DisableMenuRow", marhs);
pawn::marh_t<int> get_player_menu_t("GetPlayerMenu", marhs);
// Text Draw
pawn::marh_t<float, float, std::string const&> textdraw_create_t("TextDrawCreate", marhs);
pawn::marh_t<int> textdraw_destroy_t("TextDrawDestroy", marhs);
pawn::marh_t<int, float, float> textdraw_letter_size_t("TextDrawLetterSize", marhs);
pawn::marh_t<int, float, float> textdraw_text_size_t("TextDrawTextSize", marhs);
pawn::marh_t<int, int> textdraw_alignment_t("TextDrawAlignment", marhs);
pawn::marh_t<int, unsigned> textdraw_color_t("TextDrawColor", marhs);
pawn::marh_t<int, int> textdraw_use_box_t("TextDrawUseBox", marhs);
pawn::marh_t<int, unsigned> textdraw_box_color_t("TextDrawBoxColor", marhs);
pawn::marh_t<int, int> textdraw_set_shadow_t("TextDrawSetShadow", marhs);
pawn::marh_t<int, int> textdraw_set_outline_t("TextDrawSetOutline", marhs);
pawn::marh_t<int, unsigned> textdraw_background_color_t("TextDrawBackgroundColor", marhs);
pawn::marh_t<int, int> textdraw_font_t("TextDrawFont", marhs);
pawn::marh_t<int, bool> textdraw_set_proportional_t("TextDrawSetProportional", marhs);
pawn::marh_t<int, int> textdraw_show_for_player_t("TextDrawShowForPlayer", marhs);
pawn::marh_t<int, int> textdraw_hide_for_player_t("TextDrawHideForPlayer", marhs);
pawn::marh_t<int, std::string const&> textdraw_set_string_t("TextDrawSetString", marhs);
// Gang Zones
pawn::marh_t<float, float, float, float> gangzone_create_t("GangZoneCreate", marhs);
pawn::marh_t<int> gangzone_destroy_t("GangZoneDestroy", marhs);
pawn::marh_t<int, int, unsigned> gangzone_show_for_player_t("GangZoneShowForPlayer", marhs);
pawn::marh_t<int, int> gangzone_hide_for_player_t("GangZoneHideForPlayer", marhs);
pawn::marh_t<int, int, int> gangzone_flash_for_player_t("GangZoneFlashForPlayer", marhs);
pawn::marh_t<int, int> gangzone_stop_flash_for_player_t("GangZoneStopFlashForPlayer", marhs);
// Global 3D Text Labels
pawn::marh_t<std::string const&, unsigned int, float, float, float, float, int, bool> create_3dtextlabel_t("Create3DTextLabel", marhs);
pawn::marh_t<int> delete_3dtextlabel_t("Delete3DTextLabel", marhs);
pawn::marh_t<int, int, float, float, float> attach_3dtextlabel_to_player_t("Attach3DTextLabelToPlayer", marhs);
pawn::marh_t<int, int, float, float, float> attach_3dtextlabel_to_vehicle_t("Attach3DTextLabelToVehicle", marhs);
pawn::marh_t<int, unsigned int, std::string const&> update_3dtextlabel_text_t("Update3DTextLabelText", marhs);
// Per-player 3D Text Labels
pawn::marh_t<int, std::string const&, unsigned int, float, float, float, float, int, int, bool> create_player3dtextlabel_t("CreatePlayer3DTextLabel", marhs);
pawn::marh_t<int, int> delete_player3dtextlabel_t("DeletePlayer3DTextLabel", marhs);
pawn::marh_t<int, int, unsigned int, std::string const&> update_player3dtextlabel_text_t("UpdatePlayer3DTextLabelText", marhs);
// Player GUI Dialog
pawn::marh_t<int, int, int, std::string const&, std::string const&, std::string const&, std::string const&> show_player_dialog_t("ShowPlayerDialog", marhs); // ShowPlayerDialog(playerid, dialogid, style, caption[], info[], button1[], button2[]);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_vehicles.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Vehicle
pawn::marh_t<int, float, float, float, float, int, int, int> create_vehicle_t("CreateVehicle", marhs);
pawn::marh_t<int> destroy_vehicle_t("DestroyVehicle", marhs);
pawn::marh_t<int, int> is_vehicle_streamed_in_t("IsVehicleStreamedIn", marhs);
pawn::marh_t<int, float&, float&, float&> get_vehicle_pos_t("GetVehiclePos", marhs);
pawn::marh_t<int, float, float, float> set_vehicle_pos_t("SetVehiclePos", marhs);
pawn::marh_t<int, float&> get_vehicle_zangle_t("GetVehicleZAngle", marhs);
pawn::marh_t<int, float&, float&, float&, float&> get_vehicle_rotation_quat_t("GetVehicleRotationQuat", marhs);
pawn::marh_t<int, float> set_vehicle_zangle_t("SetVehicleZAngle", marhs);
pawn::marh_t<int, int, bool, bool> set_vehicle_params_for_player_t("SetVehicleParamsForPlayer", marhs);
pawn::marh_t<int> set_vehicle_to_respawn_t("SetVehicleToRespawn", marhs);
pawn::marh_t<int, int> link_vehicle_to_interior_t("LinkVehicleToInterior", marhs);
pawn::marh_t<int, int> add_vehicle_component_t("AddVehicleComponent", marhs);
pawn::marh_t<int, int> remove_vehicle_component_t("RemoveVehicleComponent", marhs);
pawn::marh_t<int, int, int> change_vehicle_color_t("ChangeVehicleColor", marhs);
pawn::marh_t<int, int> change_vehicle_paintjob_t("ChangeVehiclePaintjob", marhs);
pawn::marh_t<int, float> set_vehicle_health_t("SetVehicleHealth", marhs);
pawn::marh_t<int, float&> get_vehicle_health_t("GetVehicleHealth", marhs);
pawn::marh_t<int, int> attach_trailer_to_vehicle_t("AttachTrailerToVehicle", marhs);
pawn::marh_t<int> detach_trailer_from_vehicle_t("DetachTrailerFromVehicle", marhs);
pawn::marh_t<int> is_trailer_attached_to_vehicle_t("IsTrailerAttachedToVehicle", marhs);
pawn::marh_t<int> get_vehicle_trailer_t("GetVehicleTrailer", marhs);
pawn::marh_t<int, std::string const&> set_vehicle_number_plate_t("SetVehicleNumberPlate", marhs);
pawn::marh_t<int> get_vehicle_model_t("GetVehicleModel", marhs);
pawn::marh_t<int, int> get_vehicle_component_in_slot_t("GetVehicleComponentInSlot", marhs);
pawn::marh_t<int> get_vehicle_component_type_t("GetVehicleComponentType", marhs);
pawn::marh_t<int> repair_vehicle_t("RepairVehicle", marhs);
pawn::marh_t<int, float&, float&, float&> get_vehicle_velocity_t("GetVehicleVelocity", marhs);
pawn::marh_t<int, float, float, float> set_vehicle_velocity_t("SetVehicleVelocity", marhs);
pawn::marh_t<int, float, float, float> set_vehicle_angular_velocity_t("SetVehicleAngularVelocity", marhs);
pawn::marh_t<int, int&, int&, int&, int&> get_vehicle_damage_status_t("GetVehicleDamageStatus", marhs);
pawn::marh_t<int, int, int, int, int> update_vehicle_damage_status_t("UpdateVehicleDamageStatus", marhs);
// Virtual Worlds
pawn::marh_t<int, int> set_vehicle_virtual_world_t("SetVehicleVirtualWorld", marhs);
pawn::marh_t<int> get_vehicle_virtual_world_t("GetVehicleVirtualWorld", marhs);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Недокументированные возможности
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pawn::marh_t<int, std::string&, pawn::string_len> gpci_t("gpci", marhs);
} // namespace {
REGISTER_IN_APPLICATION(api);
api::ptr api::instance() {
return application::instance()->get_item<api>();
}
api::api()
:ver(server_ver_unknown)
{
}
api::~api() {
}
//Инициализация мода - инициализирем методы маршалинга
void api::on_pre_pre_gamemode_init(AMX* amx, server_ver ver) {
this->ver = ver;
BOOST_FOREACH(pawn::marh_amx_t* for_init, marhs.marhs) {
bool rezult = for_init->init(amx);
# if defined(_DEBUG)
if (!rezult) {
dump_marhs();
}
# endif // if defined(_DEBUG)
assert(rezult && "Не удалось инициализировать натив. Возможно его нужно прописать в sys_all_call() в игровом режиме");
}
}
void api::on_post_post_gamemode_exit(AMX* amx) {
marhs.fini();
}
//Методы сампа
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_objects.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int api::create_object(int model_id, float x, float y, float z, float rx, float ry, float rz, float draw_distance) {
return create_object_t.call(model_id, x, y, z, rx, ry, rz, draw_distance);
}
void api::set_object_pos(int object_id, float x, float y, float z) {
set_object_pos_t.call(object_id, x, y, z);
}
void api::get_object_pos(int object_id, float& x, float& y, float& z) {
get_object_pos_t.call(object_id, x, y, z);
}
void api::set_object_rot(int object_id, float rx, float ry, float rz) {
set_object_rot_t.call(object_id, rx, ry, rz);
}
void api::get_object_rot(int object_id, float& rx, float& ry, float& rz) {
get_object_rot_t.call(object_id, rx, ry, rz);
}
bool api::is_valid_object(int object_id) {
return 0 != is_valid_object_t.call(object_id);
}
void api::destroy_object(int object_id) {
destroy_object_t.call(object_id);
}
void api::move_object(int object_id, float x, float y, float z, float speed) {
move_object_t.call(object_id, x, y, z, speed);
}
void api::stop_object(int object_id) {
stop_object_t.call(object_id);
}
int api::create_player_object(int player_id, int model_id, float x, float y, float z, float rx, float ry, float rz, float draw_distance) {
return create_player_object_t.call(player_id, model_id, x, y, z, rx, ry, rz, draw_distance);
}
void api::set_player_object_pos(int player_id, int object_id, float x, float y, float z) {
set_player_object_pos_t.call(player_id, object_id, x, y, z);
}
void api::get_player_object_pos(int player_id, int object_id, float& x, float& y, float& z) {
get_player_object_pos_t.call(player_id, object_id, x, y, z);
}
void api::set_player_object_rot(int player_id, int object_id, float rx, float ry, float rz) {
set_player_object_rot_t.call(player_id, object_id, rx, ry, rz);
}
void api::get_player_object_rot(int player_id, int object_id, float& rx, float& ry, float& rz) {
get_player_object_rot_t.call(player_id, object_id, rx, ry, rz);
}
bool api::is_valid_player_object(int player_id, int object_id) {
return 0 != is_valid_player_object_t.call(player_id, object_id);
}
void api::destroy_player_object(int player_id, int object_id) {
destroy_player_object_t.call(player_id, object_id);
}
void api::move_player_object(int player_id, int object_id, float x, float y, float z, float speed) {
move_player_object_t.call(player_id, object_id, x, y, z, speed);
}
void api::stop_player_object(int player_id, int object_id) {
stop_player_object_t.call(player_id, object_id);
}
void api::attach_object_to_player(int object_id, int player_id, float offset_x, float offset_y, float offset_z, float offset_rx, float offset_ry, float offset_rz) {
attach_object_to_player_t.call(object_id, player_id, offset_x, offset_y, offset_z, offset_rx, offset_ry, offset_rz);
}
void api::attach_player_object_to_player(int object_player_id, int object_id, int attach_player_id, float offset_x, float offset_y, float offset_z, float offset_rx, float offset_ry, float offset_rz) {
attach_player_object_to_player_t.call(object_player_id, object_id, attach_player_id, offset_x, offset_y, offset_z, offset_rx, offset_ry, offset_rz);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_players.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Player
void api::set_spawn_info(int player_id, int team_id, int skin_id, float x, float y, float z, float rz, int weapon_id1, int weapon_ammo1, int weapon_id2, int weapon_ammo2, int weapon_id3, int weapon_ammo3) {
set_spawn_info_t.call(player_id, team_id, skin_id, x, y, z, rz, weapon_id1, weapon_ammo1, weapon_id2, weapon_ammo2, weapon_id3, weapon_ammo3);
}
void api::spawn_player(int player_id) {
spawn_player_t.call(player_id);
}
// Player info
void api::set_player_pos(int player_id, float x, float y, float z) {
set_player_pos_t.call(player_id, x, y, z);
}
void api::set_player_pos_findz(int player_id, float x, float y, float z) {
set_player_pos_findz_t.call(player_id, x, y, z);
}
void api::get_player_pos(int player_id, float& x, float& y, float& z) {
get_player_pos_t.call(player_id, x, y, z);
}
void api::set_player_facing_angle(int player_id, float rz) {
set_player_facing_angle_t.call(player_id, rz);
}
float api::get_player_facing_angle(int player_id) {
float rz;
get_player_facing_angle_t.call(player_id, rz);
return rz;
}
bool api::is_player_in_range_of_point(int player_id, float range, float x, float y, float z) {
return 0 != is_player_in_range_of_point_t.call(player_id, range, x, y, z);
}
bool api::is_player_streamed_in(int player_id, int for_player_id) {
return 0 != is_player_streamed_in_t.call(player_id, for_player_id);
}
void api::set_player_interior(int player_id, int interior_id) {
set_player_interior_t.call(player_id, interior_id);
}
int api::get_player_interior(int player_id) {
return get_player_interior_t.call(player_id);
}
void api::set_player_health(int player_id, float health) {
set_player_health_t.call(player_id, health);
}
float api::get_player_health(int player_id) {
float rezult;
get_player_health_t.call(player_id, rezult);
return rezult;
}
void api::set_player_armour(int player_id, float armour) {
set_player_armour_t.call(player_id, armour);
}
float api::get_player_armour(int player_id) {
float rezult;
get_player_armour_t.call(player_id, rezult);
return rezult;
}
void api::set_player_ammo(int player_id, int weapon_slot, int ammo) {
set_player_ammo_t.call(player_id, weapon_slot, ammo);
}
int api::get_player_ammo(int player_id) {
return get_player_ammo_t.call(player_id);
}
api::weapon_state api::get_player_weapon_state(int player_id) {
return static_cast<weapon_state>(get_player_weapon_state_t.call(player_id));
}
void api::set_player_team(int player_id, int team_id) {
set_player_team_t.call(player_id, team_id);
}
int api::get_player_team(int player_id) {
return get_player_team_t.call(player_id);
}
void api::set_player_score(int player_id, int score) {
set_player_score_t.call(player_id, score);
}
int api::get_player_score(int player_id) {
return get_player_score_t.call(player_id);
}
int api::get_player_drunk_level(int player_id) {
return get_player_drunk_level_t.call(player_id);
}
void api::set_player_drunk_level(int player_id, int level) {
set_player_drunk_level_t.call(player_id, level);
}
void api::set_player_color(int player_id, unsigned color) {
set_player_color_t.call(player_id, color);
}
unsigned api::get_player_color(int player_id) {
return get_player_color_t.call(player_id);
}
void api::set_player_skin(int player_id, int skin_id) {
set_player_skin_t.call(player_id, skin_id);
}
int api::get_player_skin(int player_id) {
return get_player_skin_t.call(player_id);
}
void api::give_player_weapon(int player_id, int weapon_id, int weapon_ammo) {
give_player_weapon_t.call(player_id, weapon_id, weapon_ammo);
}
void api::reset_player_weapons(int player_id) {
reset_player_weapons_t.call(player_id);
}
void api::set_player_armed_weapon(int player_id, int weapon_id) {
set_player_armed_weapon_t.call(player_id, weapon_id);
}
void api::get_player_weapon_data(int player_id, int slot, int& weapon_id, int& weapon_ammo) {
get_player_weapon_data_t.call(player_id, slot, weapon_id, weapon_ammo);
}
void api::give_player_money(int player_id, int money) {
give_player_money_t.call(player_id, money);
}
void api::reset_player_money(int player_id) {
reset_player_money_t.call(player_id);
}
int api::set_player_name(int player_id, std::string const& name) {
return set_player_name_t.call(player_id, name);
}
int api::get_player_money(int player_id) {
return get_player_money_t.call(player_id);
}
api::player_state api::get_player_state(int player_id) {
return static_cast<player_state>(get_player_state_t.call(player_id));
}
std::string api::get_player_ip(int player_id) {
std::string rezult;
get_player_ip_t.call(player_id, rezult, pawn::string_len::val);
return rezult;
}
int api::get_player_ping(int player_id) {
return get_player_ping_t.call(player_id);
}
int api::get_player_weapon(int player_id) {
return get_player_weapon_t.call(player_id);
}
void api::get_player_keys(int player_id, int& keys, int& updown, int& leftright) {
get_player_keys_t.call(player_id, keys, updown, leftright);
}
std::string api::get_player_name(int player_id) {
std::string rezult;
get_player_name_t.call(player_id, rezult, pawn::string_len::val);
return rezult;
}
void api::set_player_time(int player_id, int hour, int minute) {
set_player_time_t.call(player_id, hour, minute);
}
void api::get_player_time(int player_id, int& hour, int& minute) {
get_player_time_t.call(player_id, hour, minute);
}
void api::toggle_player_clock(int player_id, int toggle) {
toggle_player_clock_t.call(player_id, toggle);
}
void api::set_player_weather(int player_id, int weather) {
set_player_weather_t.call(player_id, weather);
}
void api::force_class_selection(int player_id) {
force_class_selection_t.call(player_id);
}
void api::set_player_wanted_level(int player_id, int level) {
set_player_wanted_level_t.call(player_id, level);
}
int api::get_player_wanted_level(int player_id) {
return get_player_wanted_level_t.call(player_id);
}
void api::set_player_fighting_style(int player_id, fight_style style) {
set_player_fighting_style_t.call(player_id, style);
}
api::fight_style api::get_player_fighting_style(int player_id) {
return static_cast<fight_style>(get_player_fighting_style_t.call(player_id));
}
void api::set_player_velocity(int player_id, float x, float y, float z) {
set_player_velocity_t.call(player_id, x, y, z);
}
void api::get_player_velocity(int player_id, float& x, float& y, float& z) {
get_player_velocity_t.call(player_id, x, y, z);
}
void api::play_crime_report_for_player(int player_id, int suspect_id, int crime_id) {
play_crime_report_for_player_t.call(player_id, suspect_id, crime_id);
}
void api::set_player_shop_name(int player_id, std::string const& shop_name) {
set_player_shop_name_t.call(player_id, shop_name);
}
void api::set_player_skill_level(int player_id, weapon_skill skill, int level) {
set_player_skill_level_t.call(player_id, skill, level);
}
int api::get_player_surfing_vehicle_id(int player_id) {
return get_player_surfing_vehicle_id_t.call(player_id);
}
void api::set_player_holding_object(int player_id, int model_id, bones bone_id, float offset_x, float offset_y, float offset_z, float rx, float ry, float rz) {
set_player_holding_object_t.call(player_id, model_id, bone_id, offset_x, offset_y, offset_z, rx, ry, rz);
}
void api::stop_player_holding_object(int player_id) {
stop_player_holding_object_t.call(player_id);
}
bool api::is_player_holding_object(int player_id) {
return 0 != is_player_holding_object_t.call(player_id);
}
void api::set_player_chat_bubble(int player_id, std::string const& text, unsigned int color, float draw_distance, int expire_time) {
set_player_chat_bubble_t.call(player_id, text, color, draw_distance, expire_time);
}
// Player controls
void api::put_player_in_vehicle(int player_id, int vehicle_id, int seat_id) {
put_player_in_vehicle_t.call(player_id, vehicle_id, seat_id);
}
int api::get_player_vehicle_id(int player_id) {
return get_player_vehicle_id_t.call(player_id);
}
int api::get_player_vehicle_seat(int player_id) {
return get_player_vehicle_seat_t.call(player_id);
}
void api::remove_player_from_vehicle(int player_id) {
remove_player_from_vehicle_t.call(player_id);
}
void api::toggle_player_controllable(int player_id, bool is_unfreeze) {
toggle_player_controllable_t.call(player_id, is_unfreeze);
}
void api::player_play_sound(int player_id, int sound_id, float x, float y, float z) {
player_play_sound_t.call(player_id, sound_id, x, y, z);
}
void api::apply_animation(int player_id, std::string const& anim_lib, std::string const& anim_name, float delta, int loop, int lock_x, int lock_y, int freeze, int time, int forcesync) {
apply_animation_t.call(player_id, anim_lib, anim_name, delta, loop, lock_x, lock_y, freeze, time, forcesync);
}
void api::clear_animations(int player_id, int forcesync) {
clear_animations_t.call(player_id, forcesync);
}
int api::get_player_animation_index(int player_id) {
return get_player_animation_index_t.call(player_id);
}
void api::get_animation_name(int index, std::string& anim_lib, std::string& anim_name) {
get_animation_name_t.call(index, anim_lib, pawn::string_len::val, anim_name, pawn::string_len::val);
}
api::special_action api::get_player_special_action(int player_id) {
return static_cast<special_action>(get_player_special_action_t.call(player_id));
}
void api::set_player_special_action(int player_id, special_action action_id) {
set_player_special_action_t.call(player_id, action_id);
}
// Player world/map related
void api::set_player_checkpoint(int player_id, float x, float y, float z, float size) {
set_player_checkpoint_t.call(player_id, x, y, z, size);
}
void api::disable_player_checkpoint(int player_id) {
disable_player_checkpoint_t.call(player_id);
}
void api::set_player_race_checkpoint(int player_id, int type_id, float x, float y, float z, float next_x, float next_y, float next_z, float size) {
set_player_race_checkpoint_t.call(player_id, type_id, x, y, z, next_x, next_y, next_z, size);
}
void api::disable_player_race_checkpoint(int player_id) {
disable_player_race_checkpoint_t.call(player_id);
}
void api::set_player_world_bounds(int player_id, float x_max, float x_min, float y_max, float y_min) {
set_player_world_bounds_t.call(player_id, x_max, x_min, y_max, y_min);
}
void api::set_player_marker_for_player(int player_id, int show_player_id, unsigned color) {
set_player_marker_for_player_t.call(player_id, show_player_id, color);
}
void api::show_player_name_tag_for_player(int player_id, int show_player_id, bool show) {
show_player_name_tag_for_player_t.call(player_id, show_player_id, show);
}
void api::set_player_mapicon(int player_id, int icon_id, float x, float y, float z, int markertype, unsigned color) {
set_player_mapicon_t.call(player_id, icon_id, x, y, z, markertype, color);
}
void api::remove_player_mapicon(int player_id, int icon_id) {
remove_player_mapicon_t.call(player_id, icon_id);
}
void api::allow_player_teleport(int player_id, bool allow) {
allow_player_teleport_t.call(player_id, allow);
}
// Player camera
void api::set_player_camera_pos(int player_id, float x, float y, float z) {
set_player_camera_pos_t.call(player_id, x, y, z);
}
void api::set_player_camera_look_at(int player_id, float x, float y, float z) {
set_player_camera_look_at_t.call(player_id, x, y, z);
}
void api::set_camera_behind_player(int player_id) {
set_camera_behind_player_t.call(player_id);
}
void api::get_player_camera_pos(int player_id, float& x, float& y, float& z) {
get_player_camera_pos_t.call(player_id, x, y, z);
}
void api::get_player_camera_front_vector(int player_id, float& x, float& y, float& z) {
get_player_camera_front_vector_t.call(player_id, x, y, z);
}
// Player conditionals
bool api::is_player_connected(int player_id) {
return 0 != is_player_called_t.call(player_id);
}
bool api::is_player_in_vehicle(int player_id, int vehicle_id) {
return 0 != is_player_in_vehicle_t.call(player_id, vehicle_id);
}
bool api::is_player_in_any_vehicle(int player_id) {
return 0 != is_player_in_any_vehicle_t.call(player_id);
}
bool api::is_player_in_checkpoint(int player_id) {
return 0 != is_player_in_checkpoint_t.call(player_id);
}
bool api::is_player_in_race_checkpoint(int player_id) {
return 0 != is_player_in_race_checkpoint_t.call(player_id);
}
// Virtual Worlds
void api::set_player_virtual_world(int player_id, int world_id) {
set_player_virtual_world_t.call(player_id, world_id);
}
int api::get_player_virtual_world(int player_id) {
return get_player_virtual_world_t.call(player_id);
}
// Insane Stunts
void api::enable_stunt_bonus_for_player(int player_id, bool enable) {
enable_stunt_bonus_for_player_t.call(player_id, enable);
}
void api::enable_stunt_bonus_for_all(bool enable) {
enable_stunt_bonus_for_all_t.call(enable);
}
// Spectating
void api::toggle_player_spectating(int player_id, bool toggle) {
toggle_player_spectating_t.call(player_id, toggle);
}
void api::player_spectate_player(int player_id, int target_player_id, spectate_mode mode) {
player_spectate_player_t.call(player_id, target_player_id, mode);
}
void api::player_spectate_vehicle(int player_id, int target_vehicle_id, spectate_mode mode) {
player_spectate_vehicle_t.call(player_id, target_vehicle_id, mode);
}
// Recording for NPC playback
void api::start_recording_player_data(int player_id, player_recording_type record_type, std::string const& record_name) {
start_recording_player_data_t.call(player_id, record_type, record_name);
}
void api::stop_recording_player_data(int player_id) {
stop_recording_player_data_t.call(player_id);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_samp.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Util
void api::send_client_message(int player_id, unsigned color, std::string const& message) {
send_client_message_t.call(player_id, color, message);
}
void api::send_player_message_to_player(int player_id, int sender_id, std::string const& message) {
send_player_message_to_player_t.call(player_id, sender_id, message);
}
void api::send_death_message(int killer_id, int killed_id, int weapon_id) {
send_death_message_t.call(killer_id, killed_id, weapon_id);
}
void api::game_text_for_player(int player_id, std::string const& string, int time, int style) {
game_text_for_player_t.call(player_id, string, time, style);
}
int api::get_max_players() {
return get_max_players_t.call();
}
// Game
void api::set_game_mode_text(std::string const& text) {
set_game_mode_text_t.call(text);
}
void api::set_team_count(int count) {
set_team_count_t.call(count);
}
int api::add_player_class(int skin_id, float x, float y, float z, float rz, int weapon_id1, int weapon_ammo1, int weapon_id2, int weapon_ammo2, int weapon_id3, int weapon_ammo3) {
return add_player_class_t.call(skin_id, x, y, z, rz, weapon_id1, weapon_ammo1, weapon_id2, weapon_ammo2, weapon_id3, weapon_ammo3);
}
int api::add_player_class_ex(int team_id, int skin_id, float x, float y, float z, float rz, int weapon_id1, int weapon_ammo1, int weapon_id2, int weapon_ammo2, int weapon_id3, int weapon_ammo3) {
return add_player_class_ex_t.call(team_id, skin_id, x, y, z, rz, weapon_id1, weapon_ammo1, weapon_id2, weapon_ammo2, weapon_id3, weapon_ammo3);
}
void api::add_static_vehicle(int model_id, float x, float y, float z, float rz, int color_id1, int color_id2) {
add_static_vehicle_t.call(model_id, x, y, z, rz, color_id1, color_id2);
}
int api::add_static_vehicle_ex(int model_id, float x, float y, float z, float rz, int color_id1, int color_id2, int respawn_delay) {
return add_static_vehicle_ex_t.call(model_id, x, y, z, rz, color_id1, color_id2, respawn_delay);
}
void api::add_static_pickup(int model_id, int type, float x, float y, float z, int virtual_world) {
add_static_pickup_t.call(model_id, type, x, y, z, virtual_world);
}
int api::create_pickup(int model_id, int type, float x, float y, float z, int virtual_world) {
return create_pickup_t.call(model_id, type, x, y, z, virtual_world);
}
void api::destroy_pickup(int pickup_id) {
destroy_pickup_t.call(pickup_id);
}
void api::show_name_tags(bool is_show) {
show_name_tags_t.call(is_show);
}
void api::show_player_markers(player_markers_mode mode) {
show_player_markers_t.call(mode);
}
void api::gamemode_exit() {
gamemode_exit_t.call();
}
void api::set_world_time(int hour) {
set_world_time_t.call(hour);
}
std::string api::get_weapon_name(int weapon_id) {
std::string rezult;
get_weapon_name_t.call(weapon_id, rezult, pawn::string_len::val);
return rezult;
}
void api::enable_tire_popping(bool is_enable) {
enable_tire_popping_t.call(is_enable);
}
void api::allow_interior_weapons(bool is_allow) {
allow_interior_weapons_t.call(is_allow);
}
void api::set_weather(int weather_id) {
set_weather_t.call(weather_id);
}
void api::set_gravity(float gravity) {
set_gravity_t.call(gravity);
}
void api::allow_admin_teleport(bool is_allow) {
allow_admin_teleport_t.call(is_allow);
}
void api::set_death_drop_amount(int amount) {
set_death_drop_amount_t.call(amount);
}
void api::create_explosion(float x, float y, float z, int type, float radius) {
create_explosion_t.call(x, y, z, type, radius);
}
void api::enable_zone_names(bool is_enable) {
enable_zone_names_t.call(is_enable);
}
void api::use_player_ped_anims() {
use_player_ped_anims_t.call();
}
void api::disable_interior_enter_exits() {
disable_interior_enter_exits_t.call();
}
void api::set_name_tag_draw_distance(float distance) {
set_name_tag_draw_distance_t.call(distance);
}
void api::disable_name_tag_los() {
disable_name_tag_los_t.call();
}
void api::limit_global_chat_radius(float chat_radius) {
limit_global_chat_radius_t.call(chat_radius);
}
void api::limit_player_marker_radius(float marker_radius) {
limit_player_marker_radius_t.call(marker_radius);
}
// Npc
void api::connect_npc(std::string const& name, std::string const& script) {
call_npc_t.call(name, script);
}
bool api::is_player_npc(int player_id) {
return 0 != is_player_npc_t.call(player_id);
}
// Admin
bool api::is_player_admin(int player_id) {
return 0 != is_player_admin_t.call(player_id);
}
void api::kick(int player_id) {
kick_t.call(player_id);
}
void api::ban(int player_id) {
ban_t.call(player_id);
}
void api::ban_ex(int player_id, std::string const& reason) {
ban_ex_t.call(player_id, reason);
}
void api::send_rcon_command(std::string const& command) {
send_rcon_command_t.call(command);
}
std::string api::get_server_var_as_string(std::string const& var_name) {
std::string rezult;
get_server_var_as_string_t.call(var_name, rezult, pawn::string_len::val);
return rezult;
}
int api::get_server_var_as_int(std::string const& var_name) {
return get_server_var_as_int_t.call(var_name);
}
bool api::get_server_var_as_bool(std::string const& var_name) {
return 0 != get_server_var_as_bool_t.call(var_name);
}
// Menu
int api::create_menu(std::string const& title, int columns, float x, float y, float col1width, float col2width) {
return create_menu_t.call(title, columns, x, y, col1width, col2width);
}
void api::destroy_menu(int menu_id) {
destroy_menu_t.call(menu_id);
}
void api::add_menu_item(int menu_id, int column, std::string const& text) {
add_menu_item_t.call(menu_id, column, text);
}
void api::set_menu_column_header(int menu_id, int column, std::string const& header) {
set_menu_column_header_t.call(menu_id, column, header);
}
void api::show_menu_for_player(int menu_id, int player_id) {
show_menu_for_player_t.call(menu_id, player_id);
}
void api::hide_menu_for_player(int menu_id, int player_id) {
hide_menu_for_player_t.call(menu_id, player_id);
}
bool api::is_valid_menu(int menu_id) {
return 0 != is_valid_menu_t.call(menu_id);
}
void api::disable_menu(int menu_id) {
disable_menu_t.call(menu_id);
}
void api::disable_menu_row(int menu_id, int row) {
disable_menu_row_t.call(menu_id, row);
}
int api::get_player_menu(int player_id) {
return get_player_menu_t.call(player_id);
}
// Text Draw
int api::textdraw_create(float x, float y, std::string const& text) {
return textdraw_create_t.call(x, y, text);
}
void api::textdraw_destroy(int text_id) {
textdraw_destroy_t.call(text_id);
}
void api::textdraw_letter_size(int text_id, float x, float y) {
textdraw_letter_size_t.call(text_id, x, y);
}
void api::textdraw_text_size(int text_id, float x, float y) {
textdraw_text_size_t.call(text_id, x, y);
}
void api::textdraw_alignment(int text_id, int alignment) {
textdraw_alignment_t.call(text_id, alignment);
}
void api::textdraw_color(int text_id, unsigned color) {
textdraw_color_t.call(text_id, color);
}
void api::textdraw_use_box(int text_id, int use) {
textdraw_use_box_t.call(text_id, use);
}
void api::textdraw_box_color(int text_id, unsigned color) {
textdraw_box_color_t.call(text_id, color);
}
void api::textdraw_set_shadow(int text_id, int size) {
textdraw_set_shadow_t.call(text_id, size);
}
void api::textdraw_set_outline(int text_id, int size) {
textdraw_set_outline_t.call(text_id, size);
}
void api::textdraw_background_color(int text_id, unsigned color) {
textdraw_background_color_t.call(text_id, color);
}
void api::textdraw_font(int text_id, int font) {
textdraw_font_t.call(text_id, font);
}
void api::textdraw_set_proportional(int text_id, bool set) {
textdraw_set_proportional_t.call(text_id, set);
}
void api::textdraw_show_for_player(int player_id, int text_id) {
textdraw_show_for_player_t.call(player_id, text_id);
}
void api::textdraw_hide_for_player(int player_id, int text_id) {
textdraw_hide_for_player_t.call(player_id, text_id);
}
void api::textdraw_set_string(int text_id, std::string const& text) {
textdraw_set_string_t.call(text_id, text);
}
// Gang Zones
int api::gangzone_create(float minx, float miny, float maxx, float maxy) {
return gangzone_create_t.call(minx, miny, maxx, maxy);
}
void api::gangzone_destroy(int zone_id) {
gangzone_destroy_t.call(zone_id);
}
void api::gangzone_show_for_player(int player_id, int zone_id, unsigned int color) {
gangzone_show_for_player_t.call(player_id, zone_id, color);
}
void api::gangzone_hide_for_player(int player_id, int zone_id) {
gangzone_hide_for_player_t.call(player_id, zone_id);
}
void api::gangzone_flash_for_player(int player_id, int zone_id, unsigned int flashcolor) {
gangzone_flash_for_player_t.call(player_id, zone_id, flashcolor);
}
void api::gangzone_stop_flash_for_player(int player_id, int zone_id) {
gangzone_stop_flash_for_player_t.call(player_id, zone_id);
}
// Global 3D Text Labels
int api::create_3dtextlabel(std::string const& text, unsigned int color, float x, float y, float z, float draw_distance, int world, bool is_test_los) {
return create_3dtextlabel_t.call(text, color, x, y, z, draw_distance, world, is_test_los);
}
void api::delete_3dtextlabel(int text3d_id) {
delete_3dtextlabel_t.call(text3d_id);
}
void api::attach_3dtextlabel_to_player(int text3d_id, int player_id, float offset_x, float offset_y, float offset_z) {
attach_3dtextlabel_to_player_t.call(text3d_id, player_id, offset_x, offset_y, offset_z);
}
void api::attach_3dtextlabel_to_vehicle(int text3d_id, int vehicle_id, float offset_x, float offset_y, float offset_z) {
attach_3dtextlabel_to_vehicle_t.call(text3d_id, vehicle_id, offset_x, offset_y, offset_z);
}
void api::update_3dtextlabel_text(int text3d_id, unsigned int color, std::string const& text) {
update_3dtextlabel_text_t.call(text3d_id, color, text);
}
// Per-player 3D Text Labels
int api::create_player3dtextlabel(int player_id, std::string const& text, unsigned int color, float x, float y, float z, float draw_distance, int attached_player_id, int attached_vehicle_id, bool is_test_los) {
return create_player3dtextlabel_t.call(player_id, text, color, x, y, z, draw_distance, attached_player_id, attached_vehicle_id, is_test_los);
}
void api::delete_player3dtextlabel(int player_id, int playertext3d_id) {
delete_player3dtextlabel_t.call(player_id, playertext3d_id);
}
void api::update_player3dtextlabel_text(int player_id, int playertext3d_id, unsigned int color, std::string const& text) {
update_player3dtextlabel_text_t.call(player_id, playertext3d_id, color, text);
}
// Player GUI Dialog
void api::show_player_dialog(int player_id, int dialog_id, dialog_style style, std::string const& caption, std::string const& info, std::string const& button_ok, std::string const& button_cancel) {
show_player_dialog_t.call(player_id, dialog_id, style, caption, info, button_ok, button_cancel);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a_vehicles.inc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Vehicle
int api::create_vehicle(int vehicle_model, float x, float y, float z, float rz, int color_id1, int color_id2, int respawn_delay) {
return create_vehicle_t.call(vehicle_model, x, y, z, rz, color_id1, color_id2, respawn_delay);
}
void api::destroy_vehicle(int vehicle_id) {
destroy_vehicle_t.call(vehicle_id);
}
bool api::is_vehicle_streamed_in(int vehicle_id, int for_player_id) {
return 0 != is_vehicle_streamed_in_t.call(vehicle_id, for_player_id);
}
void api::get_vehicle_pos(int vehicle_id, float& x, float& y, float& z) {
get_vehicle_pos_t.call(vehicle_id, x, y, z);
}
void api::set_vehicle_pos(int vehicle_id, float x, float y, float z) {
set_vehicle_pos_t.call(vehicle_id, x, y, z);
}
float api::get_vehicle_zangle(int vehicle_id) {
float rz;
get_vehicle_zangle_t.call(vehicle_id, rz);
return rz;
}
void api::get_vehicle_rotation_quat(int vehicle_id, float& w, float& x, float& y, float& z) {
get_vehicle_rotation_quat_t.call(vehicle_id, w, x, y, x);
}
void api::set_vehicle_zangle(int vehicle_id, float rz) {
set_vehicle_zangle_t.call(vehicle_id, rz);
}
void api::set_vehicle_params_for_player(int vehicle_id, int player_id, bool objective, bool doorslocked) {
set_vehicle_params_for_player_t.call(vehicle_id, player_id, objective, doorslocked);
}
void api::set_vehicle_to_respawn(int vehicle_id) {
set_vehicle_to_respawn_t.call(vehicle_id);
}
void api::link_vehicle_to_interior(int vehicle_id, int interior_id) {
link_vehicle_to_interior_t.call(vehicle_id, interior_id);
}
void api::add_vehicle_component(int vehicle_id, int component_id) {
add_vehicle_component_t.call(vehicle_id, component_id);
}
void api::remove_vehicle_component(int vehicle_id, int component_id) {
remove_vehicle_component_t.call(vehicle_id, component_id);
}
void api::change_vehicle_color(int vehicle_id, int color_id1, int color_id2) {
change_vehicle_color_t.call(vehicle_id, color_id1, color_id2);
}
void api::change_vehicle_paintjob(int vehicle_id, int paintjob_id) {
change_vehicle_paintjob_t.call(vehicle_id, paintjob_id);
}
void api::set_vehicle_health(int vehicle_id, float health) {
set_vehicle_health_t.call(vehicle_id, health);
}
float api::get_vehicle_health(int vehicle_id) {
float health;
get_vehicle_health_t.call(vehicle_id, health);
return health;
}
void api::attach_trailer_to_vehicle(int trailer_id, int vehicle_id) {
attach_trailer_to_vehicle_t.call(trailer_id, vehicle_id);
}
void api::detach_trailer_from_vehicle(int vehicle_id) {
detach_trailer_from_vehicle_t.call(vehicle_id);
}
bool api::is_trailer_attached_to_vehicle(int vehicle_id) {
return 0 != is_trailer_attached_to_vehicle_t.call(vehicle_id);
}
int api::get_vehicle_trailer(int vehicle_id) {
return get_vehicle_trailer_t.call(vehicle_id);
}
void api::set_vehicle_number_plate(int vehicle_id, std::string const& numberplate) {
set_vehicle_number_plate_t.call(vehicle_id, numberplate);
}
int api::get_vehicle_model(int vehicle_id) {
return get_vehicle_model_t.call(vehicle_id);
}
int api::get_vehicle_component_in_slot(int vehicle_id, carmod_type slot) {
return get_vehicle_component_in_slot_t.call(vehicle_id, slot);
}
api::carmod_type api::get_vehicle_component_type(int component_id) {
return static_cast<carmod_type>(get_vehicle_component_type_t.call(component_id));
}
void api::repair_vehicle(int vehicle_id) {
repair_vehicle_t.call(vehicle_id);
}
void api::get_vehicle_velocity(int vehicle_id, float& x, float& y, float& z) {
get_vehicle_velocity_t.call(vehicle_id, x, y, z);
}
void api::set_vehicle_velocity(int vehicle_id, float x, float y, float z) {
set_vehicle_velocity_t.call(vehicle_id, x, y, z);
}
void api::set_vehicle_angular_velocity(int vehicle_id, float x, float y, float z) {
set_vehicle_angular_velocity_t.call(vehicle_id, x, y, z);
}
void api::get_vehicle_damage_status(int vehicle_id, int& panels, int& doors, int& lights, int& tires) {
get_vehicle_damage_status_t.call(vehicle_id, panels, doors, lights, tires);
}
void api::update_vehicle_damage_status(int vehicle_id, int panels, int doors, int lights, int tires) {
update_vehicle_damage_status_t.call(vehicle_id, panels, doors, lights, tires);
}
// Virtual Worlds
void api::set_vehicle_virtual_world(int vehicle_id, int world_id) {
set_vehicle_virtual_world_t.call(vehicle_id, world_id);
}
int api::get_vehicle_virtual_world(int vehicle_id) {
return get_vehicle_virtual_world_t.call(vehicle_id);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Недокументированные возможности
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string api::get_serial(int player_id) {
std::string rezult;
gpci_t.call(player_id, rezult, pawn::string_len::val);
return rezult;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Другое
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
samp::server_ver api::get_ver() const {
return ver;
}
bool api::is_has_022_features() const {
return server_ver_022 == ver || server_ver_02X == ver;
}
bool api::is_has_030_features() const {
return server_ver_03a == ver || server_ver_03b == ver;
}
int api::get_invalid_player_id() const {
if (is_has_030_features()) {
return INVALID_PLAYER_ID_030;
}
return INVALID_PLAYER_ID_02X;
}
void api::dump_marhs() const {
# if defined(_DEBUG) && defined(_MSC_VER)
// В режиме отладки печатаем в окно отладчика список нативов для вставки в sys_all_call()
std::vector<std::string> pawn_calls = marhs.get_pawn_calls();
::OutputDebugStringA("Data to insert to gamemode:\n");
::OutputDebugStringA("public sys_all_call() {\n");
::OutputDebugStringA(" new vi;\n");
::OutputDebugStringA(" new vs[16];\n");
::OutputDebugStringA(" new Float:vf;\n");
::OutputDebugStringA("\n");
BOOST_FOREACH(std::string const& pawn_call, pawn_calls) {
::OutputDebugStringA((pawn_call + "\n").c_str());
}
::OutputDebugStringA("}\n");
# endif // if defined(_DEBUG) && defined(_MSC_VER)
}
} // namespace samp {
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
]
| [
[
[
1,
1195
]
]
]
|
73b2104eb90c83b8d9a6c57ccdb269ef4b13931f | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D11/D3D11UnorderedAccessView.h | a86f419d3045dd459223623d646c1d0acd98847c | []
| 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 | 1,343 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "D3D11View.h"
using namespace System;
using namespace Microsoft::WindowsAPICodePack::DirectX;
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D11 {
/// <summary>
/// A view interface specifies the parts of a resource the pipeline can access during rendering.
/// <para>(Also see DirectX SDK: ID3D11UnorderedAccessView)</para>
/// </summary>
public ref class UnorderedAccessView :
public Microsoft::WindowsAPICodePack::DirectX::Direct3D11::View
{
public:
/// <summary>
/// Get a description of the resource.
/// <para>(Also see DirectX SDK: ID3D11UnorderedAccessView::GetDesc)</para>
/// </summary>
/// <returns>A resource description (see <see cref="UnorderedAccessViewDescription"/>)<seealso cref="UnorderedAccessViewDescription"/>.</returns>
property UnorderedAccessViewDescription Description
{
UnorderedAccessViewDescription get();
}
internal:
UnorderedAccessView() : View()
{ }
UnorderedAccessView(ID3D11UnorderedAccessView* pNativeID3D11UnorderedAccessView) : View(pNativeID3D11UnorderedAccessView)
{ }
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
]
| [
[
[
1,
37
]
]
]
|
ba4daba50a9e14805e14cf8bd0ff58193d8afbb7 | 59112a8527fc59e65ac099b00fd1977d2393fdd7 | /WaveCreatorDlg.cpp | 30008cf2ea607f14b2b82c730c182f2b827ecc23 | []
| no_license | viniciusjarina/wave_creator | 4aa3714ee5894b2f47ecb36c236d8e57fcfd86a9 | 05002aa81918da90e248992a06557d1d86216e69 | refs/heads/master | 2020-06-03T01:45:10.300399 | 2010-09-05T02:23:33 | 2010-09-05T02:23:33 | 3,187,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,894 | cpp | // WaveCreatorDlg.cpp : implementation file
//
#include "stdafx.h"
#include "WaveCreator.h"
#include "WaveCreatorDlg.h"
#include "Path.h"
#include "dlgOptions.h"
#include "Wave.h"
#include <math.h>
#include "afxwin.h"
#include <Shlwapi.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
public:
CHyperLink m_link;
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_LINK, m_link);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CWaveCreatorDlg dialog
CWaveCreatorDlg::CWaveCreatorDlg(CWnd* pParent /*=NULL*/)
: CDialog(CWaveCreatorDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_nCurrentSecond = 0;
m_nBps = AfxGetApp()->GetProfileInt(_T("Settings"), _T("Bps"), 16);
m_nSampleRate = AfxGetApp()->GetProfileInt(_T("Settings"), _T("SampleRate"), 8000);
m_pBuffer = new double[m_nSampleRate];
m_arrCreators[0] = &m_paneFixWave;
m_arrCreators[1] = &m_paneCSVFile;
}
void CWaveCreatorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CB_KIND, m_combo);
DDX_Control(pDX, IDC_CTRL_WAVE, m_ctrlWave);
}
BEGIN_MESSAGE_MAP(CWaveCreatorDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDOK, &CWaveCreatorDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON2, &CWaveCreatorDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_SAVE_AS, &CWaveCreatorDlg::OnBnClickedSaveAs)
ON_CBN_SELCHANGE(IDC_CB_KIND, &CWaveCreatorDlg::OnCbnSelchangeCbKind)
ON_BN_CLICKED(IDC_BUTTON3, &CWaveCreatorDlg::OnBnClickedButton3)
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_SAVE_AS2, &CWaveCreatorDlg::OnBnClickedSaveAs2)
ON_BN_CLICKED(IDC_BUTTON5, &CWaveCreatorDlg::OnBnClickedButton5)
ON_BN_CLICKED(IDC_BUTTON4, &CWaveCreatorDlg::OnBnClickedButton4)
END_MESSAGE_MAP()
// CWaveCreatorDlg message handlers
BOOL CWaveCreatorDlg::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);
}
}
m_paneFixWave.CRHCreateGenericChildDialog(this, IDC_STATIC_PLACE, 0, NULL);
m_paneCSVFile.CRHCreateGenericChildDialog(this, IDC_STATIC_PLACE, 0, NULL);
int nLastPos = AfxGetApp()->GetProfileInt(_T("Settings"), _T("LastKind"), 0);
m_combo.SetCurSel(nLastPos);
UpdatePanes();
UpdateWaveCtrl();
// 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 CWaveCreatorDlg::UpdatePanes()
{
int nSelected = m_combo.GetCurSel();
m_paneCSVFile.ShowWindow(SW_HIDE);
m_paneFixWave.ShowWindow(SW_HIDE);
switch(nSelected)
{
case 0:
m_paneFixWave.ShowWindow(SW_SHOW);
break;
case 1:
m_paneCSVFile.ShowWindow(SW_SHOW);
break;
}
}
void CWaveCreatorDlg::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 CWaveCreatorDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CWaveCreatorDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CWaveCreatorDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
}
void CWaveCreatorDlg::OnBnClickedButton2()
{
CdlgOptions dlg(this);
dlg.m_nSampleRate = m_nSampleRate;
dlg.m_nBps = m_nBps;
if(dlg.DoModal() == IDOK)
{
m_nSampleRate = dlg.m_nSampleRate;
m_nBps = dlg.m_nBps;
UpdateWaveCtrl();
}
}
CString CWaveCreatorDlg::BrowseSaveWaveFile(const CString & strInitialFile)
{
CString strFile;
CString strTempFileName;
CPath strTempDir;
CString folder;
strFile.Empty();
OPENFILENAME ofn;
ZeroMemory(&ofn,sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hInstance = AfxGetInstanceHandle();
CString strFilter(MAKEINTRESOURCE(IDS_FILE_OPEN_WAV));
ofn.Flags = OFN_ENABLESIZING |OFN_EXPLORER | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
ofn.hwndOwner = AfxGetMainWnd()->m_hWnd;
LPTSTR pch = strFilter.GetBuffer(0); // modify the buffer in place
// MFC delimits with '|' not '\0'
while ((pch = _tcschr(pch, '|')) != NULL)
*pch++ = '\0';
ofn.lpstrFilter = strFilter;
ofn.nFilterIndex = 1;
if(!strInitialFile.IsEmpty())
{
strTempDir = strInitialFile;
folder = strTempDir.GetFolder();
if(!folder.IsEmpty())
{
ofn.lpstrInitialDir = folder;
}
strTempFileName = strInitialFile;
}
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFile = strTempFileName.GetBufferSetLength(MAX_PATH);
if(::GetSaveFileName(&ofn))
{
strTempFileName.ReleaseBuffer();
strFile = strTempFileName;
}
return strFile;
}
CString CWaveCreatorDlg::BrowseSaveCSVFile(const CString & strInitialFile)
{
CString strFile;
CString strTempFileName;
CPath strTempDir;
CString folder;
strFile.Empty();
OPENFILENAME ofn;
ZeroMemory(&ofn,sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hInstance = AfxGetInstanceHandle();
CString strFilter(MAKEINTRESOURCE(IDS_FILE_OPEN_CSV));
ofn.Flags = OFN_ENABLESIZING |OFN_EXPLORER | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
ofn.hwndOwner = AfxGetMainWnd()->m_hWnd;
LPTSTR pch = strFilter.GetBuffer(0); // modify the buffer in place
// MFC delimits with '|' not '\0'
while ((pch = _tcschr(pch, '|')) != NULL)
*pch++ = '\0';
ofn.lpstrFilter = strFilter;
ofn.nFilterIndex = 1;
if(!strInitialFile.IsEmpty())
{
strTempDir = strInitialFile;
folder = strTempDir.GetFolder();
if(!folder.IsEmpty())
{
ofn.lpstrInitialDir = folder;
}
strTempFileName = strInitialFile;
}
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFile = strTempFileName.GetBufferSetLength(MAX_PATH);
if(::GetSaveFileName(&ofn))
{
strTempFileName.ReleaseBuffer();
strFile = strTempFileName;
}
return strFile;
}
void CWaveCreatorDlg::OnBnClickedSaveAs()
{
CString strNewPath;
CString strLastName = AfxGetApp()->GetProfileString(_T("Settings"), _T("LastWaveFile"), _T(""));
if(strLastName.IsEmpty())
{
strLastName.LoadString(IDS_DEFAULT_NAME);
}
CPath strPath = BrowseSaveWaveFile(strLastName);
if(strPath.IsEmpty())
return;
if(strPath.GetExtension().IsEmpty())
{
strPath.ChangeExtension(_T("wav"));
}
CWave wav;
WAVEFORMATEX wf;
INT ErrorCode;
ZeroMemory(&wf, sizeof(wf));
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.nChannels = 1;
wf.wBitsPerSample = m_nBps;
wf.nSamplesPerSec = m_nSampleRate;
wf.nBlockAlign = wf.nChannels *(wf.wBitsPerSample/8);
wf.nAvgBytesPerSec = wf.nSamplesPerSec *wf.nBlockAlign;
wf.cbSize = 0;
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
ErrorCode = wav.OutOpen( &strPath,&wf, m_nSampleRate, m_nSampleRate*nSeconds);
for(int j = 0; j < nSeconds; j++)
{
pCreator->GetSample(j ,m_pBuffer, m_nSampleRate, m_nBps);
ErrorCode = wav.OutWrite( m_pBuffer, m_nSampleRate ) != m_nSampleRate;
}
wav.OutClose();
}
CWaveCreatorDlg::~CWaveCreatorDlg()
{
AfxGetApp()->WriteProfileInt(_T("Settings"), _T("Bps"), m_nBps);
AfxGetApp()->WriteProfileInt(_T("Settings"), _T("SampleRate"), m_nSampleRate);
if(m_pBuffer)
{
delete [] m_pBuffer;
m_pBuffer = NULL;
}
}
void CWaveCreatorDlg::OnCbnSelchangeCbKind()
{
UpdatePanes();
UpdateWaveCtrl();
}
void CWaveCreatorDlg::OnBnClickedButton3()
{
CPath tempPath(tempFileCreate);
CWave wav;
WAVEFORMATEX wf;
INT ErrorCode;
ZeroMemory(&wf, sizeof(wf));
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.nChannels = 1;
wf.wBitsPerSample = m_nBps;
wf.nSamplesPerSec = m_nSampleRate;
wf.nBlockAlign = wf.nChannels *(wf.wBitsPerSample/8);
wf.nAvgBytesPerSec = wf.nSamplesPerSec *wf.nBlockAlign;
wf.cbSize = 0;
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
ErrorCode = wav.OutOpen( &tempPath,&wf, m_nSampleRate, m_nSampleRate*nSeconds);
for(int j = 0; j < nSeconds; j++)
{
pCreator->GetSample(j ,m_pBuffer, m_nSampleRate, m_nBps);
ErrorCode = wav.OutWrite( m_pBuffer, m_nSampleRate ) != m_nSampleRate;
}
wav.OutClose();
::PlaySound(tempPath, NULL,SND_FILENAME| SND_SYNC);
tempPath.DeleteFile();
}
void CWaveCreatorDlg::UpdateWaveCtrl()
{
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
UpdateButtons();
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nTotalSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
if(nTotalSeconds == 0)
{
m_ctrlWave.Empty();
return;
}
pCreator->GetSample(0 ,m_pBuffer, m_nSampleRate, m_nBps);
m_ctrlWave.SetBuffer(m_pBuffer, m_nSampleRate, m_nBps);
}
void CWaveCreatorDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
}
void CWaveCreatorDlg::OnBnClickedSaveAs2()
{
CString strNewPath;
CString strLastName = AfxGetApp()->GetProfileString(_T("Settings"), _T("LastCSVFile"), _T(""));
if(strLastName.IsEmpty())
{
strLastName.LoadString(IDS_DEFAULT_CSV);
}
CPath strPath = BrowseSaveCSVFile(strLastName);
if(strPath.IsEmpty())
return;
if(strPath.GetExtension().IsEmpty())
{
strPath.ChangeExtension(_T("csv"));
}
CStdioFile fileOut;
if(!fileOut.Open(strPath, CFile::modeCreate | CFile::modeWrite))
return;
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
for(int j = 0; j < nSeconds; j++)
{
for(int k = 0; k < m_nSampleRate; k++)
{
double & dVal = m_pBuffer[k];
CString strVal;
strVal.Format(_T("%g,"), dVal);
fileOut.WriteString(strVal);
}
}
}
void CWaveCreatorDlg::OnBnClickedButton5()
{
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
if(nSeconds == m_nCurrentSecond + 1)
return;
m_nCurrentSecond++;
UpdateButtons();
}
void CWaveCreatorDlg::UpdateButtons()
{
int nSel = m_combo.GetCurSel();
if(nSel == LB_ERR)
return;
CWaveCreatorAbstract * pCreator = m_arrCreators[nSel];
int nSeconds = pCreator->GetTotalSeconds(m_nSampleRate);
if(nSeconds == 0)
{
m_nCurrentSecond = 0;
}
SetDlgItemInt(IDC_STATIC_START, m_nCurrentSecond);
SetDlgItemInt(IDC_STATIC_END, m_nCurrentSecond + 1);
GetDlgItem(IDC_BUTTON5)->EnableWindow(nSeconds && nSeconds != m_nCurrentSecond + 1);
GetDlgItem(IDC_BUTTON4)->EnableWindow(nSeconds && m_nCurrentSecond);
}
void CWaveCreatorDlg::OnBnClickedButton4()
{
if(!m_nCurrentSecond)
return;
m_nCurrentSecond--;
UpdateWaveCtrl();
}
| [
"[email protected]"
]
| [
[
[
1,
590
]
]
]
|
a3ff1bb6f9aa6be33c20d7f1447fb760f5b01522 | 14447604061a3ded605cd609b44fec3979d9b1cc | /Cacoon/MainFrm.cpp | b7e3660bfbdb235a980ae9dc7c2e08976c651ab2 | []
| no_license | sinsoku/cacoon | 459e441aacf4dc01311a6b5cd7eae2425fbf4c3f | 36e81b689b53505c2d8117ff60ce8e4012d6eae6 | refs/heads/master | 2020-05-30T23:34:08.361671 | 2010-12-03T17:44:20 | 2010-12-03T17:44:20 | 809,470 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 13,094 | cpp |
// MainFrm.cpp : MainFrame クラスの実装
//
#include "stdafx.h"
#include "Cacoon.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define WM_USER_NTFYICON (WM_USER+100) // 100に特に意味はない。
// MainFrame
IMPLEMENT_DYNCREATE(MainFrame, CFrameWndEx)
const int iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;
BEGIN_MESSAGE_MAP(MainFrame, CFrameWndEx)
ON_WM_CREATE()
ON_COMMAND(ID_VIEW_CUSTOMIZE, &MainFrame::OnViewCustomize)
ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &MainFrame::OnToolbarCreateNew)
ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &MainFrame::OnApplicationLook)
ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &MainFrame::OnUpdateApplicationLook)
ON_WM_WINDOWPOSCHANGING()
ON_COMMAND(ID_MENUITEM_1, OnCommandMenu_1)
ON_COMMAND(ID_MENUITEM_2, OnCommandMenu_2)
ON_COMMAND(ID_MENUITEM_3, OnCommandMenu_3)
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // ステータス ライン インジケーター
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// MainFrame コンストラクション/デストラクション
MainFrame::MainFrame()
{
// TODO: メンバー初期化コードをここに追加してください。
theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2008);
}
MainFrame::~MainFrame()
{
}
int MainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWndEx::OnCreate(lpCreateStruct) == -1)
return -1;
m_stNtfyIcon.cbSize = NOTIFYICONDATA_V2_SIZE; //構造体のサイズです。
m_stNtfyIcon.uID = 0; //アイコンの識別ナンバーです。
m_stNtfyIcon.hWnd = m_hWnd; //メッセージを送らせるウィンドウのハンドルです。
m_stNtfyIcon.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO; //各種設定です。
m_stNtfyIcon.hIcon = AfxGetApp()->LoadIconW( IDR_MAINFRAME ); //アプリケーションのアイコンです。
m_stNtfyIcon.uCallbackMessage = WM_USER_NTFYICON; //送ってもらうメッセージです。
lstrcpy( m_stNtfyIcon.szTip, _T( "Cacoon" ) ); //チップの文字列です。
::Shell_NotifyIconW( NIM_ADD, &m_stNtfyIcon ); //タスクトレイに表示します。
m_stNtfyIcon.dwInfoFlags = NIIF_INFO;
// ポップアップメニューの構築
m_TaskTrayMenu.CreatePopupMenu();
// ポップアップメニューのイベント設定
m_TaskTrayMenu.EnableMenuItem( ID_MENUITEM_1, MF_ENABLED );
m_TaskTrayMenu.EnableMenuItem( ID_MENUITEM_2, MF_ENABLED );
m_TaskTrayMenu.EnableMenuItem( ID_MENUITEM_3, MF_ENABLED );
// ポップアップメニューのメニュー項目
m_TaskTrayMenu.AppendMenuW( MF_STRING, ID_MENUITEM_1, L"設定");
m_TaskTrayMenu.AppendMenuW( MF_SEPARATOR, 0);
m_TaskTrayMenu.AppendMenuW( MF_STRING, ID_MENUITEM_2, L"バージョン情報");
m_TaskTrayMenu.AppendMenuW( MF_STRING, ID_MENUITEM_3, L"終了");
BOOL bNameValid;
// 固定値に基づいてビジュアル マネージャーと visual スタイルを設定します
OnApplicationLook(theApp.m_nAppLook);
if (!m_wndMenuBar.Create(this))
{
TRACE0("メニュー バーを作成できませんでした\n");
return -1; // 作成できませんでした。
}
m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY);
// アクティブになったときメニュー バーにフォーカスを移動しない
CMFCPopupMenu::SetForceMenuFocus(FALSE);
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME))
{
TRACE0("ツール バーの作成に失敗しました。\n");
return -1; // 作成できませんでした。
}
CString strToolBarName;
bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD);
ASSERT(bNameValid);
m_wndToolBar.SetWindowText(strToolBarName);
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
// ユーザー定義のツール バーの操作を許可します:
InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId);
if (!m_wndStatusBar.Create(this))
{
TRACE0("ステータス バーの作成に失敗しました。\n");
return -1; // 作成できない場合
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: ツール バーおよびメニュー バーをドッキング可能にしない場合は、この 5 つの行を削除します
m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY);
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndMenuBar);
DockPane(&m_wndToolBar);
// Visual Studio 2005 スタイルのドッキング ウィンドウ動作を有効にします
CDockingManager::SetDockingMode(DT_SMART);
// Visual Studio 2005 スタイルのドッキング ウィンドウの自動非表示動作を有効にします
EnableAutoHidePanes(CBRS_ALIGN_ANY);
// ツール バーとドッキング ウィンドウ メニューの配置変更を有効にします
EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR);
// ツール バーのクイック (Alt キーを押しながらドラッグ) カスタマイズを有効にします
CMFCToolBar::EnableQuickCustomization();
if (CMFCToolBar::GetUserImages() == NULL)
{
// ユーザー定義のツール バー イメージを読み込みます
if (m_UserImages.Load(_T(".\\UserImages.bmp")))
{
CMFCToolBar::SetUserImages(&m_UserImages);
}
}
// メニューのパーソナル化 (最近使用されたコマンド) を有効にします
// TODO: ユーザー固有の基本コマンドを定義し、各メニューをクリックしたときに基本コマンドが 1 つ以上表示されるようにします。
CList<UINT, UINT> lstBasicCommands;
lstBasicCommands.AddTail(ID_FILE_NEW);
lstBasicCommands.AddTail(ID_FILE_OPEN);
lstBasicCommands.AddTail(ID_FILE_SAVE);
lstBasicCommands.AddTail(ID_FILE_PRINT);
lstBasicCommands.AddTail(ID_APP_EXIT);
lstBasicCommands.AddTail(ID_EDIT_CUT);
lstBasicCommands.AddTail(ID_EDIT_PASTE);
lstBasicCommands.AddTail(ID_EDIT_UNDO);
lstBasicCommands.AddTail(ID_APP_ABOUT);
lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR);
lstBasicCommands.AddTail(ID_VIEW_TOOLBAR);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_WINDOWS_7);
CMFCToolBar::SetBasicCommands(lstBasicCommands);
return 0;
}
BOOL MainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWndEx::PreCreateWindow(cs) )
return FALSE;
// TODO: この位置で CREATESTRUCT cs を修正して Window クラスまたはスタイルを
// 修正してください。
return TRUE;
}
// MainFrame 診断
#ifdef _DEBUG
void MainFrame::AssertValid() const
{
CFrameWndEx::AssertValid();
}
void MainFrame::Dump(CDumpContext& dc) const
{
CFrameWndEx::Dump(dc);
}
#endif //_DEBUG
// MainFrame メッセージ ハンドラー
void MainFrame::OnViewCustomize()
{
CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* メニューをスキャンします*/);
pDlgCust->EnableUserDefinedToolbars();
pDlgCust->Create();
}
LRESULT MainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp)
{
LRESULT lres = CFrameWndEx::OnToolbarCreateNew(wp,lp);
if (lres == 0)
{
return 0;
}
CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres;
ASSERT_VALID(pUserToolbar);
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
return lres;
}
void MainFrame::OnApplicationLook(UINT id)
{
CWaitCursor wait;
theApp.m_nAppLook = id;
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_WIN_2000:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager));
break;
case ID_VIEW_APPLOOK_OFF_XP:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP));
break;
case ID_VIEW_APPLOOK_WIN_XP:
CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
break;
case ID_VIEW_APPLOOK_OFF_2003:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_VS_2005:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_VS_2008:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_WINDOWS_7:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows7));
CDockingManager::SetDockingMode(DT_SMART);
break;
default:
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_OFF_2007_BLUE:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue);
break;
case ID_VIEW_APPLOOK_OFF_2007_BLACK:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
break;
case ID_VIEW_APPLOOK_OFF_2007_SILVER:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
break;
case ID_VIEW_APPLOOK_OFF_2007_AQUA:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua);
break;
}
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
CDockingManager::SetDockingMode(DT_SMART);
}
RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);
theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook);
}
void MainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI)
{
pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID);
}
BOOL MainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext)
{
// 基本クラスが実際の動作を行います。
if (!CFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext))
{
return FALSE;
}
// すべてのユーザー定義ツール バーのボタンのカスタマイズを有効にします
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
for (int i = 0; i < iMaxUserToolbars; i ++)
{
CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i);
if (pUserToolbar != NULL)
{
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
}
}
return TRUE;
}
void MainFrame::OnDestroy(void)
{
::Shell_NotifyIconW( NIM_DELETE, &m_stNtfyIcon ); // タスクトレイのアイコンを削除
CFrameWndEx::OnDestroy();
}
LRESULT MainFrame::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
switch( message )
{
case WM_USER_NTFYICON: //アイコンからのメッセージ。
POINT point;
::GetCursorPos(&point);
if( lParam == WM_LBUTTONDOWN ) {
// 左クリックの処理
m_stNtfyIcon.dwInfoFlags = NIIF_INFO ;
::lstrcpy( m_stNtfyIcon.szInfoTitle , L"Cacoon") ;
::lstrcpy( m_stNtfyIcon.szInfo , L"DiagramTitle\n2010/10/25 00:00:00 UserName") ;
m_stNtfyIcon.uTimeout = 10 ;
::Shell_NotifyIcon( NIM_MODIFY , &m_stNtfyIcon ) ;
;
} else if( lParam == WM_RBUTTONDOWN ) {
// 右クリックの処理
SetForegroundWindow();
m_TaskTrayMenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
PostMessage(WM_NULL);
break;
}
}
return CFrameWndEx::WindowProc(message, wParam, lParam);
}
void MainFrame::OnWindowPosChanging(WINDOWPOS * lpwndpos)
{
lpwndpos->flags &= ~SWP_SHOWWINDOW;
}
void MainFrame::OnCommandMenu_1() {
::MessageBox( NULL, L"設定が押されました", L"設定", MB_OK );
}
void MainFrame::OnCommandMenu_2() {
::MessageBox( NULL, L"バージョン情報が押されました", L"バージョン情報", MB_OK );
}
void MainFrame::OnCommandMenu_3() {
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
| [
"[email protected]"
]
| [
[
[
1,
392
]
]
]
|
7953e3cbfe8a62c22b169fc9657666a933e73847 | a705a17ff1b502ec269b9f5e3dc3f873bd2d3b9c | /src/bg.cpp | 023a90fbb7a36acc31670cea04f25433abdd7a20 | []
| no_license | cantidio/ChicolinusQuest | 82431a36516d17271685716590fe7aaba18226a0 | 9b77adabed9325bba23c4d99a3815e7f47456a4d | refs/heads/master | 2021-01-25T07:27:54.263356 | 2011-08-09T11:17:53 | 2011-08-09T11:17:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,531 | cpp | #include "bg.hpp"
#include "game.hpp"
/*
-lallegro
-lallegro_color
-lallegro_image
-lallegro_primitives
-lallegro_memfile
-lallegro_audio
-lallegro_acodec
*/
using namespace Gorgon::Script;
BG::BG(const std::string& pScript)
{
Lua lua(pScript);
//register some help functions
lua.executeString("function _getLayerNumber() return #layers end");
lua.executeString("function _getLayerImage(i) return layers[i + 1].img end");
lua.executeString("function _getLayerVelocityX(i) return layers[i + 1].vel.x end");
lua.executeString("function _getLayerVelocityY(i) return layers[i + 1].vel.y end");
lua.executeString("function _getPlayerXPosition() return playerPosition[1] end");
lua.executeString("function _getPlayerYPosition() return playerPosition[2] end");
mName = lua.getNumericVar("BG_name");
mWidth = lua.getNumericVar("BG_width");
mHeight = lua.getNumericVar("BG_height");
mPosition.x = lua.function("_getXPosition" , LuaParam(""), 1).getNumericValue();
mPosition.y = lua.function("_getYPosition" , LuaParam(""), 1).getNumericValue();
Point playerPosition;
mPlayerLayer = lua.getNumericVar("playerLayer");
playerPosition.x = lua.function("_getPlayerXPosition", LuaParam(""), 1).getNumericValue();
playerPosition.y = lua.function("_getPlayerYPosition", LuaParam(""), 1).getNumericValue();
const int layerNum = lua.function("_getLayerNumber" , LuaParam(""), 1).getNumericValue();
mCameraTarget = NULL;
mMusic = audiere::OpenSound( Game::getAudioDevice(), lua.getStringVar("music").c_str(), false );
if (mMusic == NULL)
{
printf( "BG music:\"%s\" couldn't be loaded!\n", lua.getStringVar("music").c_str() );
}
for(register int i = 0 ; i < layerNum; ++i)
{
mLayers.push_back
(
new BGLayer
(
lua.function("_getLayerImage", LuaParam("i",i), 1).getStringValue(),
Point
(
lua.function("_getLayerVelocityX", LuaParam("i",i), 1).getNumericValue(),
lua.function("_getLayerVelocityY", LuaParam("i",i), 1).getNumericValue()
)
)
);
}
}
BG::~BG()
{
for(unsigned int i = 0 ; i < mLayers.size(); ++i)
{
delete mLayers[i];
}
mLayers.clear();
}
void BG::draw() const
{
for(unsigned int i = 0 ; i < mLayers.size(); ++i)
{
mLayers[i]->draw(mPosition);;
}
}
void BG::logic()
{
if( mMusic != NULL && !mMusic->isPlaying() && mMusic->getLength() != mMusic->getPosition())
{
printf("play the mothafucka\n");
mMusic->play();
}
if( mCameraTarget != NULL )
{
Point cameraPos = mPosition;
Point targetPos = mCameraTarget->getPosition();
const int width = 320;
const int height = 240;
if( targetPos.x >= ( width / 2 ) )
{
if( targetPos.x <= ( 99999999 - width / 2 ) )
{
cameraPos.x = 1 * ( targetPos.x - width / 2 );
}
else if( targetPos.x >= (99999999 - width/2) )
{
cameraPos.x = 1 * (99999999 - width);
}
}
else
{
cameraPos.x = 0;
}
mPosition.x = cameraPos.x;
/*if targetPos.y >= (window_height/2) then
if targetPos.y <= (self.mHeight - window_height/2) then
cameraPos.y = -1 * (targetPos.y - window_height/2 )
elseif targetPos.y >= (self.mHeight - window_height/2) then
cameraPos.y = -1 * (self.mHeight - window_height)
end
elseif targetPos.y <= (window_height/2) then
cameraPos.y = 0
end*/
}
for(unsigned int i = 0 ; i < mLayers.size(); ++i)
{
mLayers[i]->logic();
}
}
BGLayer* BG::getLayer(const unsigned int& pLayer)
{
return mLayers[pLayer];
}
void BG::setCameraTarget(Object* pObject)
{
mCameraTarget = pObject;
}
| [
"[email protected]"
]
| [
[
[
1,
137
]
]
]
|
f7e5d2d75486a3ad5f281d74ce1da848e0b3450d | 9f2d447c69e3e86ea8fd8f26842f8402ee456fb7 | /shooting2011/shooting2011/aimedRandom.cpp | 1d21b5dcbfc6a3edc3bb05c9a4b19ead3e78baa6 | []
| no_license | nakao5924/projectShooting2011 | f086e7efba757954e785179af76503a73e59d6aa | cad0949632cff782f37fe953c149f2b53abd706d | refs/heads/master | 2021-01-01T18:41:44.855790 | 2011-11-07T11:33:44 | 2011-11-07T11:33:44 | 2,490,410 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | #include "main.h"
#include "movePattern.h"
#include "firePattern.h"
#include "enemyBullet.h"
#include "enemy.h"
#include "shootingAccessor.h"
#include "graphicPattern.h"
FirePatternAimedRandom::FirePatternAimedRandom(int _interval,int _n,double _v,int _graphicID){
interval = _interval;
n = _n;
v = _v;
graphicID=_graphicID;
}
bool FirePatternAimedRandom::isFire(){
bool ret = (!curFrame);
curFrame=(curFrame+1)%interval;
return ret;
}
void FirePatternAimedRandom::action(MovingObject *owner){
if(isFire() && owner->getStatus()==VALID){
deque<pair<double,double> > pos = ShootingAccessor::getHeroPos();
Rect r = owner->getHitRect();
int ind = rand()%(pos.size());
double dx = pos[ind].first - r.x;
double dy = pos[ind].second - r.y;
double theta = atan2(dy,dx);
ShootingAccessor::addEnemyBullet(new EnemyBullet(r.x,r.y,new MovePatternStraight(v*cos(theta),v*sin(theta)),new FirePatternNone(),new GraphicPattern(graphicID)));
}
}
FirePatternAimedRandom::~FirePatternAimedRandom(){
} | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
32
]
],
[
[
33,
33
]
]
]
|
cbd275d8b4eb340572828356cb8d4f076e4c12ba | f9fd733174ef8a8bd07ff9be849431dfc46e541f | /NumberLib/NumbersLib/utils.h | 23dff634c6e3eb6d3501322f5d915acfcaacb8c6 | []
| no_license | Jargyle214/specialnumbers | 8b33369c2bfb75b324cb70539c5daee19f7bce84 | 107b4c3022e5febed38136fa09023f66931df77e | refs/heads/master | 2021-01-10T16:33:58.894648 | 2008-09-21T18:56:04 | 2008-09-21T18:56:04 | 55,395,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,768 | h | #ifndef _UTILS_H_
#define _UTILS_H_
#include "math.h"
namespace luma
{
namespace numbers
{
template <class T>
inline T min(const T& v1, const T& v2);
template <class T>
inline T max(const T& v1, const T& v2);
/**
Returns the given value clamped between the given minimum and maximum.
@param T
Any type that is supported by the standard min and max functions.
@param value
The value to clamp.
@param minValue
The minimum value of the output.
@param maxValue
The maximum vakue of the output.
@return
A value clamped between minValue and maxValue.
@note The range of this function includes the maxValue.
*/
template <class T>
inline T clamp(const T& value, const T& minValue, const T& maxValue);
/**
Returns the modulus of a number in a specified range, that is
(min + value mod (max - min)).
For example,
@code
for (int i = 0; i < 10; i++)
{
int r = mod(i, 2, 5);
cout << i << " ";
}
@endcode
prints 3 4 2 3 4 2 3 4 2 3
@note The range of this function excludes the maxValue.
*/
template <class T>
inline T mod(const T& value, const T& minValue, const T& maxValue);
/**
Returns a number reflected between the bounds.
For example,
@code
for (int i = 0; i < 10; i++)
{
int r = reflect(i, 0, 3);
cout << i << " ";
}
@endcode
prints 0 1 2 3 2 1 0 1 2 3
@note The range of this function includes the maxValue.
*/
template <class T>
inline T reflect(const T& value, const T& minValue, const T& maxValue);
/**
Linearly interpolates a value between a given range.
If the value is below the inputMin, the outputMin is returned.
If the value is above the inputMax, the outputMax is returned.
Otherwise, the returned value is
outputMin + ((value - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin).
@author Luke Lamothe ([email protected])
*/
template <class T>
inline T lerp(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax);
/**
This function is a smooth aproximation for lerp.
*/
template <class T>
inline T sigmoid(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax);
/**
If the value is below the inputMin, the outputMin is returned.
Otherwise, the returned value is
outputMin + ((value - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin).
*/
template <class T>
inline T ramp(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax);
/**
Otherwise, the returned value is
outputMin + ((value - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin).
*/
template <class T>
inline T line(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax);
/**
Returns the one of two outputs, depending on whether the input value exceeds a given threshold.
*/
template <class T>
inline T step(const T& input, const T& inputThreshold, const T& outputMin, const T& outputMax);
/**
Returns the fractional part of a float or double. Guarenteed always to lie
between 0 and 1, even if the input is negative.
@note: the following identity hold (within floating point threshold):
@code
x == frac(c) + floor(x)
@endcode
@see floor()
*/
template <class T>
inline T frac(T x);
/**
Returns the largest integer smaller than the argument given.
@see frac()
*/
template <class T>
inline T floor(T x);
/**
Returns the value furthest from the center. For example,
@code
extreme(-1, 5, 0) == 5
extreme(1, -5, 0) == -5
@endcode
This is useful, for example when deciding on which of two (polar opposite)
inputs to use to make a decision.
*/
template <class T>
inline T extreme(T v1, T v2, T center);
/**
Integrates a sequence of numbers. Same as accumulating the sequence in place.
For example, the array {0, 1, 2, 3} will be set to {0, 1, 3, 6}.
*/
template <unsigned int n, class T>
void integrate(T samples[]);
//---------------------------------------------------------------------------------------
// Function definitions
//
template <class T>
inline T min(const T& v1, const T& v2)
{
return v1 < v2 ? v1 : v2;
}
template <class T>
inline T max(const T& v1, const T& v2)
{
return v1 > v2 ? v1 : v2;
}
template <class T>
inline T clamp(const T& value, const T& minValue, const T& maxValue)
{
return min(maxValue, max(minValue, value));
}
template <class T>
inline T mod(const T& value, const T& minValue, const T& maxValue)
{
T tmpValue = value - minValue;
T range = maxValue - minValue;
int quotient = (int)(tmpValue / range);
T remainder = tmpValue - quotient * range;
if (remainder < 0)
{
remainder += range;
}
return minValue + remainder;
}
template <class T>
inline T reflect(const T& value, const T& minValue, const T& maxValue)
{
T cycleMax = 2 * maxValue - minValue;
T c = mod(value, minValue, cycleMax);
return c <= maxValue ? c: 2 * maxValue - c;
}
template <class T>
inline T lerp(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax)
{
if(value >= inputMax)
{
return outputMax;
}
return ramp(value, inputMin, inputMax, outputMin, outputMax);
}
template <class T>
inline T sigmoid(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax)
{
T w = exp((-2 * value + (inputMax + inputMin))/ (inputMax - inputMin));
return (outputMax - outputMin) / (1 + w) + outputMin;
}
template <class T>
inline T ramp(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax)
{
if(value <= inputMin)
{
return outputMin;
}
return line(value, inputMin, inputMax, outputMin, outputMax);
}
template <class T>
inline T line(const T& value, const T& inputMin, const T& inputMax, const T& outputMin, const T& outputMax)
{
return outputMin + ((value - inputMin) * (outputMax - outputMin) / (inputMax - inputMin));
}
template <class T>
inline T frac(T x)
{
return x >= (T) 0 ? x - (int) x : x + 1 - (int) x;
}
template <class T>
inline T floor(T x)
{
return x >= (T) 0 ? (int) x : (int) x - 1;
}
template <class T>
inline T extreme(T v1, T v2, T center = 0)
{
return abs(v1 - center) > abs(v2 - center) ? v1 : v2;
}
template <class T>
inline T step(const T& input, const T& inputThreshold, const T& outputMin, const T& outputMax)
{
return input < inputThreshold ? outputMin : outputMax;
}
/**
*/
template <unsigned int n, class T>
void integrate(T samples[])
{
for(int i = 1; i < n; i++)
{
samples[i] += samples[i - 1];
}
}
}} //namespace
#endif //_UTILS_H_
| [
"herman.tulleken@efac63d9-b148-0410-ace2-6f69ea89f809"
]
| [
[
[
1,
285
]
]
]
|
4cf2388f02f13b995f631e3e2473a0755ace4d60 | 09756520fa2cb26daf7842a5bad914f9b29d5a74 | /sqrattest/Vector.h | 09cdb8baa737c53d32f102c600bcc189b6535eb0 | []
| no_license | splhack/sqrat | b60263e27f49ae4c5b591200a33f1a12a72b99a9 | 982ba7f1649a2aa9d709076d3c21433aed65c658 | refs/heads/master | 2021-01-18T01:59:39.951195 | 2011-07-16T16:00:59 | 2011-07-16T16:00:59 | 2,058,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,684 | h | //
// Copyright (c) 2009 Brandon Jones
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
#if !defined(SQRAT_TEST_VECTOR_H)
#define SQRAT_TEST_VECTOR_H
#include <sqrat.h>
namespace Sqrat {
// A simple Vector class used to demonstrate binding
class Vec2 {
public:
float x, y;
Vec2( void );
Vec2( const Vec2 &v );
Vec2( const float vx, const float vy );
bool operator ==( const Vec2 &v ) const;
Vec2 operator -( void ) const;
Vec2 operator +( const Vec2& v ) const;
Vec2 operator -( const Vec2& v ) const;
Vec2 operator *( const float f ) const;
Vec2 operator /( const float f ) const;
Vec2& operator =( const Vec2& v );
float Length( void ) const;
float Distance( const Vec2 &v ) const;
Vec2& Normalize( void );
float Dot( const Vec2 &v ) const;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
565cb6439e9a195caff469449c3669fe49e9cdd0 | b9b99474453d2a30451e51ba86381f306cf372e9 | /include/gliese/Game.h | 1c5e498b551a3361e74198a72cf9832fdbf2d86b | []
| no_license | lagenar/pacman | d34c6edfde524ad8514714cc4905c4854f6c8e70 | 2845b0d0247450ea5fc10b24ccc185c75f07f4a2 | refs/heads/master | 2021-01-21T13:49:33.019555 | 2009-12-02T00:27:10 | 2009-12-02T00:27:10 | 369,156 | 3 | 1 | null | 2020-10-20T14:20:59 | 2009-11-11T17:21:07 | C | UTF-8 | C++ | false | false | 5,770 | h | #ifndef GAME_H_
#define GAME_H_
#include "ApplicationState.h"
#include "LogicObject.h"
#include "Rule.h"
#include "Observer.h"
#include "PriorityComponentManager.h"
#include "GameSpace.h"
#include "iostream"
#include "list"
#include "map"
class Application;
class GameOverRule;
class GameSimulator;
class GameState;
class ScenarioBuilder;
/**
* La clase Game representa los estados de la aplicación correspondientes
* a la ejecución del ciclo del juego exclusivamente.
* La característica principal de este tipo de estado es que lleva a cabo el
* denominado "ciclo del juego" (o game loop). En el mismo, se actualizan
* periódicamente los objetos lógicos que realizarán sus acciones, y los
* procesos que contienen los algoritmos con las reglas del juego, el control
* de los jugadores, etc.
*
*/
class Game : public ApplicationState, public Observer
{
friend std::ostream & operator << (std::ostream & output, const Game & game);
friend class GameSimulator;
public:
Game(const Game * otherGame, bool simulated = false);
Game(Application * application, ScenarioBuilder * builder, bool simulated = false);
virtual ~Game();
const ComponentManager & getObjectManager() const;
ComponentManager & getObjectManager();
const ComponentManager & getStaticObjectManager() const;
ComponentManager & getStaticObjectManager();
const PriorityComponentManager & getRuleManager() const;
PriorityComponentManager & getRuleManager();
void setGameOverRule(GameOverRule * rule);
const GameOverRule & getGameOverRule() const;
GameOverRule & getGameOverRule();
void addObject(LogicObject * obj, bool isStatic = true);
void addRule(Rule * obj);
/**
* Devuelve los objetos que cumplan con el filtro por tipo indicado.
* @param type tipo de los objetos
* @param objects objetos constantes cuya posición se encuentra dentro del area indicada.
*/
void getObjects(const LogicObject::Type & type, std::list<const LogicObject *> & objects) const;
/**
* Devuelve los objetos que cumplan con el filtro por tipo indicado.
* @param type tipo de los objetos
* @param objects objetos cuya posición se encuentra dentro del area indicada.
*/
void getObjects(const LogicObject::Type & type, std::list<LogicObject *> & objects);
/**
* Devuelve el objeto correspondiente al tipo del objeto lógico indicado.
* @param type tipo del objeto lógico.
* @return referencia constante al objeto lógico si el mismo forma parte de
* los objetos administrados por el juego, o NULL en caso contrario.
*/
const LogicObject * getObject(const LogicObject::Type & type) const;
/**
* Devuelve el objeto correspondiente al tipo del objeto lógico indicado.
* @param type tipo del objeto lógico.
* @return referencia al objeto lógico si el mismo forma parte de
* los objetos administrados por el juego, o NULL en caso contrario.
*/
LogicObject * getObject(const LogicObject::Type & type);
/**
* Verifica si el juego hay sido configurado con una referencia al espacio del juego.
*
* @return true si el juego tiene una referencia al espacio del juego,
* false en caso contrario.
* @see setGameSpace
*/
bool hasGameSpace() const;
/**
* Configura el juego con una referencia al espacio del juego.
* De esta forma el juego puede brindar soporte para el acceso y utilización
* del espacio del juego.
*
* @param gameSpace referencia al espacio del juego
*/
void setGameSpace(GameSpace * gameSpace);
/**
* Devuelve una referencia al espacio del juego.
*
* @return referencia constante al espacio del juego
* @see hasGameSpace
*/
const GameSpace & getGameSpace() const;
/**
* Devuelve una referencia al espacio del juego.
*
* @return referencia al espacio del juego
* @see hasGameSpace
*/
GameSpace & getGameSpace();
/**
* Devuelve una estructura que contiene las variables
* del juego.
* @return referencia constante a las variables del juego.
*/
const Variables & getVariables() const;
/**
* Devuelve una estructura que contiene las variables
* del juego.
* @return referencia a las variables del juego.
*/
Variables & getVariables();
/**
* Verifica si el juego se está usando para la simulación.
* Si el juego es simulado no se realiza ninguna operación relacionada con
* la visualización de las animaciones o con el manejo de los eventos de entrada.
*
* @return true si el juego es simulado, false en caso contrario.
*/
bool isSimulated() const;
void setCycles(unsigned int cycles);
const unsigned int getCycles() const;
virtual Game * newInstance(bool simulated = false) const = 0;
void setNextState(ApplicationState * nextState);
virtual GameState * getState();
virtual void gameSetup(GameSimulator * gameSimulator = 0) = 0;
protected:
virtual void update(unsigned int time);
virtual void onGameOver();
virtual void onProcessChange(const Observable * observable, const Observable::NotifyPoint & notifyPoint);
private:
void setup();
protected:
GameOverRule * gameOverRule;
ScenarioBuilder * scenarioBuilder;
ComponentManager updatableObjects;
ComponentManager nonUpdatableObjects;
PriorityComponentManager rules;
Variables variables;
bool simulated;
GameSpace * gameSpace;
ApplicationState * nextState;
unsigned int cycles;
};
std::ostream & operator << (std::ostream & output, const Game & game);
#endif /*GAME_H_*/
| [
"[email protected]"
]
| [
[
[
1,
188
]
]
]
|
094c5a15eb316e1fdf395c1d85f73e871ccf8583 | f6c641b102ebbffb48e93dd554a0b7eb7e639be7 | /Source/Base/Base Graphics Library/TextureData1D.hpp | 1190666d83b024786356c8d74315f5a7288d0045 | []
| no_license | ZAsprose/rtrt-on-gpu | e3ca4921a3429cbc72e0cee8afd946200b83573d | 4949e373c273f963467658ca25d39244da7fb4e6 | refs/heads/master | 2021-01-10T14:42:45.293509 | 2010-08-25T18:37:19 | 2010-08-25T18:37:19 | 53,016,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,989 | hpp | /*
-----------------------------------------------------------------------------
| B A S E G R A P H I C S L I B R A R Y |
-----------------------------------------------------------------------------
Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com )
This library 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 library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TEXTURE_DATA_1D_
#define _TEXTURE_DATA_1D_
#include <OpenGL.h>
namespace graphics
{
class TextureData1D
{
public:
/************************************************************************/
/* CONSTRUCTOR AND DESTRUCTOR */
/************************************************************************/
/* If data are created and used only on GPU set last argument to TRUE */
TextureData1D ( GLsizei width,
GLuint components = 4,
bool empty = false );
~TextureData1D ( void );
/************************************************************************/
/* OVERLOADED OPERATORS */
/************************************************************************/
operator GLfloat * ( void );
operator const GLfloat * ( void ) const;
/************************************************************************/
/* PUBLIC METHODS */
/************************************************************************/
/* For accessing to texture data as a 1D array of tuples */
template < class TUPLE >
TUPLE & Pixel ( GLuint x );
//------------------------------------------------------------------------
GLenum Type ( void ) const;
//------------------------------------------------------------------------
GLsizei Width ( void ) const;
//------------------------------------------------------------------------
GLenum PixelFormat ( void ) const;
GLint InternalFormat ( void ) const;
//------------------------------------------------------------------------
/* Possible targets: GL_TEXTURE_1D */
void Upload ( GLenum target = GL_TEXTURE_1D );
private:
/************************************************************************/
/* PRIVATE FIELDS */
/************************************************************************/
GLfloat * fPixels;
//------------------------------------------------------------------------
GLsizei fWidth;
//------------------------------------------------------------------------
GLuint fComponents;
};
/********************************************************************************/
template < class TUPLE >
TUPLE & TextureData1D :: Pixel ( GLuint x )
{
return ( TUPLE & ) *( fPixels + x * fComponents );
}
}
#endif | [
"[email protected]"
]
| [
[
[
1,
107
]
]
]
|
4a960f51c08b3d138d462ee7af89f34f42e22445 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/email.hpp | 7c024922952d152b27e6097aa2258db96bae96b2 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,735 | hpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
/**
* @file
* @brief Generated from email.xsd.
*/
#ifndef AOSLCPP_AOSL__EMAIL_HPP
#define AOSLCPP_AOSL__EMAIL_HPP
// Begin prologue.
//
#include <aoslcpp/common.hpp>
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include "aosl/email_forward.hpp"
#include <memory> // std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include <xsd/cxx/tree/containers-wildcard.hxx>
#ifndef XSD_DONT_INCLUDE_INLINE
#define XSD_DONT_INCLUDE_INLINE
#undef XSD_DONT_INCLUDE_INLINE
#else
#endif // XSD_DONT_INCLUDE_INLINE
/**
* @brief C++ namespace for the %artofsequence.org/aosl/1.0
* schema namespace.
*/
namespace aosl
{
/**
* @brief Class corresponding to the %email schema type.
*
* Valid email adress.
*
* @nosubgrouping
*/
class Email: public ::xml_schema::String
{
public:
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from initializers for required
* elements and attributes.
*/
Email ();
/**
* @brief Create an instance from a C string and initializers
* for required elements and attributes.
*/
Email (const char*);
/**
* @brief Create an instance from a string andinitializers
* for required elements and attributes.
*/
Email (const ::std::string&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
Email (const ::xml_schema::String&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Email (const ::xercesc::DOMElement& e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a DOM attribute.
*
* @param a A DOM attribute to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Email (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a string fragment.
*
* @param s A string fragment to extract the data from.
* @param e A pointer to DOM element containing the string fragment.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Email (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
Email (const Email& x,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual Email*
_clone (::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~Email ();
};
}
#ifndef XSD_DONT_INCLUDE_INLINE
#endif // XSD_DONT_INCLUDE_INLINE
#include <iosfwd>
namespace aosl
{
::std::ostream&
operator<< (::std::ostream&, const Email&);
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace aosl
{
}
#include <iosfwd>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
namespace aosl
{
void
operator<< (::xercesc::DOMElement&, const Email&);
void
operator<< (::xercesc::DOMAttr&, const Email&);
void
operator<< (::xml_schema::ListStream&,
const Email&);
}
#ifndef XSD_DONT_INCLUDE_INLINE
#include "aosl/email.inl"
#endif // XSD_DONT_INCLUDE_INLINE
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__EMAIL_HPP
| [
"klaim@localhost"
]
| [
[
[
1,
234
]
]
]
|
227a67569a3f6134ea053e19dcb5f59c4e68304e | 1fe913f8627e94f337ce120c23423a614367dbf5 | /03_VarArgsPratice/C test/20091215/2p.cpp | e42a12a82e738ba44f4f79f0deda2e10caf7d745 | []
| no_license | jayska/Programming | 9abbbf70a85a1c90496fbf5da0b0461675da9f8c | a744da5ed9b7f266f130d2ea350cc376a74aa49f | refs/heads/master | 2021-01-20T11:24:56.280316 | 2010-01-02T03:45:04 | 2010-01-02T03:45:04 | null | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 725 | cpp | #include <stdio.h>
int main()
{
long int NumA = 2L;
float NumB = 2.0;
int NumC = 2;
float NumD = 2.0F;
printf("給定型態\n");
printf("sizeof long int NumA(%d) = %d\n", NumA, sizeof(NumA));
printf("sizeof float NumB(%f) = %d\n", NumB, sizeof(NumB));
printf("sizeof int NumC(%d) = %d\n", NumC, sizeof(NumC));
printf("sizeof float NumD(%f) = %d\n", NumD, sizeof(NumD));
printf("*******************************************\n");
printf("直接帶數字\n");
printf("sizeof NumA(%d) = %d\n", 2L, sizeof(2L));
printf("sizeof NumB(%f) = %d\n", 2.0, sizeof(2.0));
printf("sizeof NumC(%d) = %d\n", 2, sizeof(2));
printf("sizeof NumD(%f) = %d\n", 2.0F, sizeof(2.0F));
getchar();
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
24
]
]
]
|
42a24b28ef4410633508d7355eca4e318a3170f4 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/ModelsC/QALPrcp1/PSD/LSoda.h | b381dd63971086c4cfe2576c149d4354460888ce | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,757 | h |
#pragma once
#include "linpack.h"
class CLSoda : public CLinPack
{
protected:
union
{
struct
{
double rowns[209], ccmax, el0, h, hmin, hmxi, hu, rc, tn, uround;
long illin, init, lyh, lewt, lacor, lsavf, lwm, liwm, mxstep, mxhnil, nhnil, ntrep, nslast, nyh, iowns[6],
icf, ierpj, iersl, jcur, jstart, kflag, l, meth, miter, maxord, maxcor, msbp, mxncf, n, nq, nst, nfe, nje, nqu;
} _1;
struct
{
double rowns[209], ccmax, el0, h, hmin, hmxi, hu, rc, tn, uround;
long iownd[14], iowns[6], icf, ierpj, iersl, jcur, jstart, kflag, l, meth, miter, maxord, maxcor, msbp,
mxncf, n, nq, nst, nfe, nje, nqu;
} _2;
struct
{
double conit, crate, el[13], elco[156] /* was [13][12] */, hold, rmax, tesco[36] /* was [3][12] */, ccmax, el0,
h, hmin, hmxi, hu, rc, tn, uround;
long iownd[14], ialth, ipup, lmax, meo, nqnyh, nslp, icf, ierpj, iersl, jcur, jstart, kflag, l, meth, miter,
maxord, maxcor, msbp, mxncf, n, nq, nst, nfe, nje, nqu;
} _3;
} ls0001_;
union
{
struct
{
double tsw, rowns2[20], pdnorm;
long insufr, insufi, ixpr, iowns2[2], jtyp, mused, mxordn, mxords;
} _1;
struct
{
double rownd2, rowns2[20], pdnorm;
long iownd2[3], iowns2[2], jtyp, mused, mxordn, mxords;
} _2;
struct
{
double rownd2, pdest, pdlast, ratio, cm1[12], cm2[5], pdnorm;
long iownd2[3], icount, irflag, jtyp, mused, mxordn, mxords;
} _3;
} lsa001_;
struct
{
long mesflg;//, lunit;
} eh0001_;
public:
int LSoda(/*S_fp f,*/ long *neq, double *y, double *t, double *tout, long *itol, double *rtol, double *atol, long *itask, long *istate, long *iopt, double *rwork, long *lrw, long *iwork, long *liw, /*U_fp jac,*/ long *jt);
double bnorm_(long *n, double *a, long *nra, long *ml, long *mu, double *w);
int cfode_(long *meth, double *elco, double *tesco);
int ewset_(long *n, long *itol, double *rtol, double *atol, double *ycur, double *ewt);
double fnorm_(long *n, double *a, double *w);
int intdy_(double *t, long *k, double *yh, long *nyh, double *dky, long *iflag);
//int prja_(long *neq, double *y, double *yh, long *nyh, double *ewt, double *ftem, double *savf, double *wm, long *iwm, S_fp f, S_fp jac);
int stoda_(long *neq, double *y, double *yh, long *nyh, double *yh1, double *ewt, double *savf, double *acor, double *wm, long *iwm /*,S_fp f, U_fp jac, S_fp pjac, S_fp slvs*/);
double vmnorm_(long *n, double *v, double *w);
int xerrwv_(char *msg, long *nmes, long *nerr, long *level, long *ni, long *i1, long *i2, long *nr, double *r1, double *r2, long L);
/* comlen ls0001_ 1900 */
/* comlen lsa001_ 212 */
/* comlen eh0001_ 8 */
/*:ref: d1mach_ 7 1 4 */
/*:ref: stoda_ 14 14 4 7 7 4 7 7 7 7 7 4 214 200 214 214 */
/*:ref: dgefa_ 14 5 7 4 4 4 4 */
/*:ref: dgbfa_ 14 7 7 4 4 4 4 4 4 */
/*:ref: dgesl_ 14 6 7 4 4 4 7 4 */
/*:ref: dgbsl_ 14 8 7 4 4 4 4 4 7 4 */
/* Rerunning f2c -P may change prototypes or declarations. */
virtual int LSFun(long *neq, double *t, double *y, double *yp)=0;
virtual int LSJac(long *neq, double *t, double *y, long *ml, long *mu, double *pd, long *nrowpd)=0;
virtual int LSPJac(long *neq, double *y, double *yh, long *nyh, double *ewt,
double *ftem, double *savf, double *wm, long *iwm);
int CLSoda::LSSolSy(double *wm, long *iwm, double *x, double *tem);
};
| [
"[email protected]"
]
| [
[
[
1,
87
]
]
]
|
5e3ee70386f5e9f6f43b1b5439761d41059e66e4 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/C++/生物进化/stdafx.cpp | 965ec3b6c8d05f84ecfc1aad80585c0ac1003de7 | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 173 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// 生物进化.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
7
]
]
]
|
dc8004b7f9725d22724de4e67cc4557da9454097 | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/CodeJam/practice/ForceTest.cpp | 1c6723f61fe6d536944fbad81627f12af01a5ba6 | []
| no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,074 | cpp | // BEGIN CUT HERE
// PROBLEM STATEMENT
// Your company produces components used in construction.
// From time to time, it is necessary to run a series of
// tests on several of the components, to determine their
// breaking force. The goal of the testing is to determine
// the point at which the unit breaks, up to a given
// threshold. (Only integer forces are applied.)
//
// You have a set of components to be used for testing. You
// are to find an optimal testing plan, minimizing the number
// of tests that will have to be performed (in the worst
// case). In the process of testing, you may destroy some or
// all of the test components, provided that in the end, the
// breaking force is known.
//
// Unfortunately, no manufacturing process is perfect, so it
// is possible that one of your test components is
// defective. A defective component is defined as one that
// breaks under a lesser force than a typically produced
// component.
//
// You are given int maxForce, the highest force at which you
// need to test the components. (They may have a higher
// breaking force than this, but you are not concerned with
// testing any higher force.) You are also given int
// testUnits, the number of units that are available for
// testing. You are to return the fewest number of tests
// necessary to conclusively determine the breaking force of
// a non-defective component.
//
//
// DEFINITION
// Class:ForceTest
// Method:fewestTests
// Parameters:int, int
// Returns:int
// Method signature:int fewestTests(int maxForce, int
// testUnits)
//
//
// NOTES
// -Assume that the (non-defective) component has a fixed
// breaking point. That is, if it breaks when tested at a
// given force, it will break whenever tested with a greater
// force. Likewise, if it passes testing for a given force,
// it will pass for any lower force.
// -The testing strategy may destroy all of the components
// that were made available for testing, as long as it finds
// the exact breaking force of the non-defective component.
// -All of the test components, except for possibly a single
// defective one, are identical, and will break under the
// same force.
// -It is not necessarily the case that one of the test
// components is defective, however, there will never be more
// than one defective component.
// -A defective component will always break under a lower
// force than a normal component.
//
//
// CONSTRAINTS
// -maxForce will be between 1 and 100, inclusive.
// -testUnits will be between 2 and 20, inclusive.
//
//
// EXAMPLES
//
// 0)
// 1
// 2
//
// Returns: 2
//
// We have to do a maximum of two tests. If the first test
// should fail, we need to test the second unit to determine
// if the first was defective.
//
// 1)
// 2
// 2
//
// Returns: 3
//
// Here, we have to start by testing a force of 1. If the
// unit breaks, we have to retest with a force of 1 to
// determine if the first was a defect. Then, if the second
// test passes, we need a third test to determine if the good
// unit can withstand a force of 2.
//
// Notice that if we had tested the first component with a
// force of 2, and it had failed, we would have only had a
// single unit left, and would not have been able to
// determine if a defective unit was present.
//
//
// 2)
// 10
// 4
//
// Returns: 6
//
// 3)
// 100
// 2
//
// Returns: 101
//
#line 109 "ForceTest.cpp"
// END CUT HERE
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <cmath>
#include <valarray>
#include <numeric>
#include <functional>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector< VI > VVI;
typedef vector<char> VC;
typedef vector<string> VS;
typedef map<int,int> MII;
typedef map<string,int> MSI;
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<int(b);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
#define FOUND(v,p) (find(ALL(v),p)!=v.end())
#define SUM(v) accumulate(ALL(v),0)
#define SE(i) (i)->second
#define DV(v) REP(i,SZ(v)) cout << v[i] << " "; cout << endl
typedef stringstream SS;
typedef istringstream ISS;
typedef ostringstream OSS;
template<class U,class T> T cast(U x){T y; OSS a; a<<x; ISS b(a.str());b>>y;return y;}
class ForceTest
{
public:
int fewestTests(int maxForce, int testUnits)
{
int re;
return re;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 1; int Arg1 = 2; int Arg2 = 2; verify_case(0, Arg2, fewestTests(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 3; verify_case(1, Arg2, fewestTests(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 10; int Arg1 = 4; int Arg2 = 6; verify_case(2, Arg2, fewestTests(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 100; int Arg1 = 2; int Arg2 = 101; verify_case(3, Arg2, fewestTests(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ForceTest ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
]
| [
[
[
1,
179
]
]
]
|
18e03f25af5c82709f2b6fea561cd1db52df65a9 | bf4f0fc16bd1218720c3f25143e6e34d6aed1d4e | /Symbols.cpp | be8901f421fa4064cdaf648e24516f8b6276a9dd | []
| no_license | shergin/downright | 4b0f161700673d7eb49459e4fde2b7d095eb91bb | 6cc40cd35878e58f4ae8bae8d5e58256e6df4ce8 | refs/heads/master | 2020-07-03T13:34:20.697914 | 2009-09-29T19:15:07 | 2009-09-29T19:15:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | cpp | #include "StdAfx.h"
#include "symbols.h"
CSymbols::CSymbols(void)
{
m_nSymbol=0;
}
CSymbols::~CSymbols(void)
{
}
CSymbols& CSymbols::operator = (const CSymbols &obj)
{
m_nSymbol=obj.m_nSymbol;
// implementation m_Symbols=obj.m_Symbols;
m_Symbol.RemoveAll();
m_Symbol.SetSize(m_nSymbol);
for(int i=0;i<m_nSymbol;i++)
{
m_Symbol.SetAtGrow(i,const_cast<CSymbol&>(obj.m_Symbol[i]));
}
// end of implementation
return *this;
}
void CSymbols::operator = (const CString &s)
{
m_nSymbol=0;
m_Symbol.RemoveAll();
m_Symbol.SetSize(1,3);
CSymbol symbol;
CString str;
TCHAR ch=0;
for(int i=0;i<s.GetLength();i++)
{
ch=s.GetAt(i);
if((ch=='|')||(i+1==s.GetLength()))
{
if(i+1==s.GetLength())str+=ch;
symbol=str;
m_Symbol.SetAtGrow(m_nSymbol,symbol);
m_nSymbol++;
str.Empty();
}
else
str+=ch;
}
}
CSymbols::operator CString()
{
CString result;
for(int i=0;i<m_nSymbol;i++)
{
result+=(CString)m_Symbol[i];
if(i+1!=m_nSymbol)result+="|";
}
return result;
} | [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
07cf06364bbdbf113fd87d2d50cd6c659eddb3ff | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /branches/bokeoa-scons/pcbnew/editpads.cpp | 8eebab6cc5bab46fa61059a7b46798a85528866f | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,103 | cpp | /******************************************************/
/* editpads.cpp: Pad editing functions and dialog box */
/******************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "trigo.h"
#include "drag.h"
#include "protos.h"
/* Routines Locales */
/* Variables locales */
static wxString Current_PadNetName;
#define NBSHAPES 4
int CodeShape[NBSHAPES] = /* forme des pads */
{
CIRCLE, OVALE, RECT, TRAPEZE
};
#define NBTYPES 5
int CodeType[NBTYPES] =
{ STANDARD, SMD, CONN, P_HOLE, MECA
};
static long Std_Pad_Layers[NBTYPES] =
{
ALL_CU_LAYERS|SILKSCREEN_LAYER_CMP|SOLDERMASK_LAYER_CU|SOLDERMASK_LAYER_CMP,
CMP_LAYER|SOLDERPASTE_LAYER_CMP|SOLDERMASK_LAYER_CMP,
CMP_LAYER|SOLDERMASK_LAYER_CMP,
ALL_CU_LAYERS|SILKSCREEN_LAYER_CU|SILKSCREEN_LAYER_CMP|
SOLDERMASK_LAYER_CU|SOLDERMASK_LAYER_CMP,
ALL_CU_LAYERS|SILKSCREEN_LAYER_CU|SILKSCREEN_LAYER_CMP|
SOLDERMASK_LAYER_CU|SOLDERMASK_LAYER_CMP
};
/************************************/
/* class WinEDA_PadPropertiesFrame */
/************************************/
#include "dialog_pad_edit.cpp"
/*************************************************************/
void WinEDA_BasePcbFrame::InstallPadOptionsFrame(D_PAD * Pad,
wxDC * DC, const wxPoint & pos)
/*************************************************************/
{
DrawPanel->m_IgnoreMouseEvents = TRUE;
WinEDA_PadPropertiesFrame * frame = new WinEDA_PadPropertiesFrame(this,
Pad, DC);
frame->ShowModal(); frame->Destroy();
DrawPanel->m_IgnoreMouseEvents = FALSE;
}
/********************************************************/
void WinEDA_PadPropertiesFrame::SetOthersControls(void)
/********************************************************/
{
int tmp;
m_PadNumCtrl->SetValue(g_Current_PadName);
m_PadNetNameCtrl->SetValue(Current_PadNetName);
m_PadSizeCtrl = new WinEDA_SizeCtrl(this, _("Pad Size"),
CurrentPad ? CurrentPad->m_Size : g_Pad_Master.m_Size,
g_UnitMetric, m_PadSizeBoxSizer, m_Parent->m_InternalUnits);
m_PadDeltaSizeCtrl = new WinEDA_SizeCtrl(this, _("Delta"),
CurrentPad ? CurrentPad->m_DeltaSize : g_Pad_Master.m_DeltaSize,
g_UnitMetric, m_PadDeltaBoxSizer, m_Parent->m_InternalUnits);
m_PadDrillCtrl = new WinEDA_ValueCtrl(this, _("Pad Drill"),
CurrentPad ? CurrentPad->m_Drill : g_Pad_Master.m_Drill,
g_UnitMetric, m_PadDeltaBoxSizer, m_Parent->m_InternalUnits );
m_PadOffsetCtrl = new WinEDA_SizeCtrl(this, _("Offset"),
CurrentPad ? CurrentPad->m_Offset : g_Pad_Master.m_Offset,
g_UnitMetric, m_PadOffsetBoxSizer, m_Parent->m_InternalUnits);
if ( CurrentPad )
{
tmp = CurrentPad->m_Orient - m_Module->m_Orient;
}
else tmp = g_Pad_Master.m_Orient;
m_PadOrientCtrl = new WinEDA_ValueCtrl(this, _("Pad Orient (0.1 deg)"),
tmp, 2, m_LeftBoxSizer, 1);
// Pad Orient
switch ( tmp )
{
case 0:
m_PadOrient->SetSelection(0);
m_PadOrientCtrl->Enable(FALSE);
break;
case -2700:
case 900:
m_PadOrient->SetSelection(1);
m_PadOrientCtrl->Enable(FALSE);
break;
case -900:
case 2700:
m_PadOrient->SetSelection(2);
m_PadOrientCtrl->Enable(FALSE);
break;
case 1800:
case -1800:
m_PadOrient->SetSelection(3);
m_PadOrientCtrl->Enable(FALSE);
break;
default:
m_PadOrient->SetSelection(4);
break;
}
tmp = CurrentPad ? CurrentPad->m_PadShape : g_Pad_Master.m_PadShape;
switch ( tmp )
{
case CIRCLE:
m_PadShape->SetSelection(0);
break;
case OVALE:
m_PadShape->SetSelection(1);
break;
case RECT:
m_PadShape->SetSelection(2);
break;
case TRAPEZE:
m_PadShape->SetSelection(3);
break;
case SPECIAL_PAD:
m_PadShape->SetSelection(4);
break;
}
// Selection du type
tmp = CurrentPad ? CurrentPad->m_Attribut : g_Pad_Master.m_Attribut;
m_PadType->SetSelection( 0 );
for ( int ii = 0; ii < NBTYPES; ii++ )
{
if ( CodeType[ii] == tmp )
{
m_PadType->SetSelection( ii ); break ;
}
}
// Selection des couches cuivre :
if ( CurrentPad ) SetPadLayersList(CurrentPad->m_Masque_Layer);
else PadTypeSelected();
}
/*******************************************************************/
void WinEDA_PadPropertiesFrame::PadOrientEvent(wxCommandEvent& event)
/********************************************************************/
{
switch ( m_PadOrient->GetSelection() )
{
case 0:
m_PadOrientCtrl->SetValue(0);
m_PadOrientCtrl->Enable(FALSE);
break;
case 1:
m_PadOrientCtrl->SetValue(900);
m_PadOrientCtrl->Enable(FALSE);
break;
case 2:
m_PadOrientCtrl->SetValue(2700);
m_PadOrientCtrl->Enable(FALSE);
break;
case 3:
m_PadOrientCtrl->SetValue(1800);
m_PadOrientCtrl->Enable(FALSE);
break;
default:
m_PadOrientCtrl->Enable(TRUE);
break;
}
}
/**************************************************************************/
void WinEDA_PadPropertiesFrame::PadTypeSelectedEvent(wxCommandEvent& event)
/**************************************************************************/
/* calcule un layer_mask type selon la selection du type du pad
*/
{
PadTypeSelected();
}
void WinEDA_PadPropertiesFrame::PadTypeSelected(void)
{
long layer_mask;
int ii;
ii = m_PadType->GetSelection();
if ( (ii < 0) || ( ii >= NBTYPES) ) ii = 0;
layer_mask = Std_Pad_Layers[ii];
SetPadLayersList(layer_mask);
}
/****************************************************************/
void WinEDA_PadPropertiesFrame::SetPadLayersList(long layer_mask)
/****************************************************************/
/* Met a jour l'etat des CheckBoxes de la liste des layers actives,
données bit a bit dans layer_mask
*/
{
if( layer_mask & CUIVRE_LAYER ) m_PadLayerCu->SetValue(TRUE);
else m_PadLayerCu->SetValue(FALSE);
if( layer_mask & CMP_LAYER ) m_PadLayerCmp->SetValue(TRUE);
else m_PadLayerCmp->SetValue(FALSE);
if( layer_mask & ADHESIVE_LAYER_CMP ) m_PadLayerAdhCmp->SetValue(TRUE);
else m_PadLayerAdhCmp->SetValue(FALSE);
if( layer_mask & ADHESIVE_LAYER_CU ) m_PadLayerAdhCu->SetValue(TRUE);
else m_PadLayerAdhCu->SetValue(FALSE);
if( layer_mask & SOLDERPASTE_LAYER_CMP ) m_PadLayerPateCmp->SetValue(TRUE);
else m_PadLayerPateCmp->SetValue(FALSE);
if( layer_mask & SOLDERPASTE_LAYER_CU ) m_PadLayerPateCu->SetValue(TRUE);
else m_PadLayerPateCu->SetValue(FALSE);
if( layer_mask & SILKSCREEN_LAYER_CMP ) m_PadLayerSilkCmp->SetValue(TRUE);
else m_PadLayerSilkCmp->SetValue(FALSE);
if( layer_mask & SILKSCREEN_LAYER_CU ) m_PadLayerSilkCu->SetValue(TRUE);
else m_PadLayerSilkCu->SetValue(FALSE);
if( layer_mask & SOLDERMASK_LAYER_CMP ) m_PadLayerMaskCmp->SetValue(TRUE);
else m_PadLayerMaskCmp->SetValue(FALSE);
if( layer_mask & SOLDERMASK_LAYER_CU ) m_PadLayerMaskCu->SetValue(TRUE);
else m_PadLayerMaskCu->SetValue(FALSE);
if( layer_mask & ECO1_LAYER ) m_PadLayerECO1->SetValue(TRUE);
else m_PadLayerECO1->SetValue(FALSE);
if( layer_mask & ECO2_LAYER ) m_PadLayerECO2->SetValue(TRUE);
else m_PadLayerECO2->SetValue(FALSE);
if( layer_mask & DRAW_LAYER ) m_PadLayerDraft->SetValue(TRUE);
else m_PadLayerDraft->SetValue(FALSE);
}
/*************************************************************************/
void WinEDA_PadPropertiesFrame::PadPropertiesAccept(wxCommandEvent& event)
/*************************************************************************/
/* Met a jour les differents parametres pour le composant en cours d'édition
*/
{
long PadLayerMask;
g_Pad_Master.m_Attribut = CodeType[m_PadType->GetSelection()];
g_Pad_Master.m_PadShape = CodeShape[m_PadShape->GetSelection()];
g_Pad_Master.m_Size = m_PadSizeCtrl->GetValue();
g_Pad_Master.m_DeltaSize = m_PadDeltaSizeCtrl->GetValue();
g_Pad_Master.m_Offset = m_PadOffsetCtrl->GetValue();
g_Pad_Master.m_Drill = m_PadDrillCtrl->GetValue();
g_Pad_Master.m_Orient = m_PadOrientCtrl->GetValue();
g_Current_PadName = m_PadNumCtrl->GetValue().Left(4);
Current_PadNetName = m_PadNetNameCtrl->GetValue();
PadLayerMask = 0;
if( m_PadLayerCu->GetValue() ) PadLayerMask |= CUIVRE_LAYER;
if( m_PadLayerCmp->GetValue() ) PadLayerMask |= CMP_LAYER;
if ( (PadLayerMask & (CUIVRE_LAYER|CMP_LAYER)) == (CUIVRE_LAYER|CMP_LAYER) )
PadLayerMask |= ALL_CU_LAYERS;
if( m_PadLayerAdhCmp->GetValue() ) PadLayerMask |= ADHESIVE_LAYER_CMP;
if( m_PadLayerAdhCu->GetValue() ) PadLayerMask |= ADHESIVE_LAYER_CU;
if( m_PadLayerPateCmp->GetValue() ) PadLayerMask |= SOLDERPASTE_LAYER_CMP;
if( m_PadLayerPateCu->GetValue() ) PadLayerMask |= SOLDERPASTE_LAYER_CU;
if( m_PadLayerSilkCmp->GetValue() ) PadLayerMask |= SILKSCREEN_LAYER_CMP;
if( m_PadLayerSilkCu->GetValue() ) PadLayerMask |= SILKSCREEN_LAYER_CU;
if( m_PadLayerMaskCmp->GetValue() ) PadLayerMask |= SOLDERMASK_LAYER_CMP;
if( m_PadLayerMaskCu->GetValue() ) PadLayerMask |= SOLDERMASK_LAYER_CU;
if( m_PadLayerECO1->GetValue() ) PadLayerMask |= ECO1_LAYER;
if( m_PadLayerECO2->GetValue() ) PadLayerMask |= ECO2_LAYER;
if( m_PadLayerDraft->GetValue() ) PadLayerMask |= DRAW_LAYER;
g_Pad_Master.m_Masque_Layer = PadLayerMask;
if ( CurrentPad ) // Set Pad Name & Num
{
m_Parent->SaveCopyInUndoList();
MODULE * Module;
Module = (MODULE*) CurrentPad->m_Parent;
Module->m_LastEdit_Time = time(NULL);
if ( m_DC ) CurrentPad->Draw(m_Parent->DrawPanel, m_DC, wxPoint(0,0), GR_XOR);
CurrentPad->m_PadShape = g_Pad_Master.m_PadShape;
CurrentPad->m_Attribut = g_Pad_Master.m_Attribut;
CurrentPad->m_Size = g_Pad_Master.m_Size;
CurrentPad->m_DeltaSize = g_Pad_Master.m_DeltaSize;
CurrentPad->m_Drill = g_Pad_Master.m_Drill;
CurrentPad->m_Offset = g_Pad_Master.m_Offset;
CurrentPad->m_Masque_Layer = g_Pad_Master.m_Masque_Layer;
CurrentPad->m_Orient = g_Pad_Master.m_Orient + Module->m_Orient;
CurrentPad->SetPadName(g_Current_PadName);
CurrentPad->m_Netname = Current_PadNetName;
if ( Current_PadNetName.IsEmpty() ) CurrentPad->m_NetCode = 0;
switch ( CurrentPad->m_PadShape )
{
case CIRCLE:
CurrentPad->m_DeltaSize = wxSize(0,0);
CurrentPad->m_Size.y = CurrentPad->m_Size.x;
break;
case RECT:
CurrentPad->m_DeltaSize = wxSize(0,0);
break;
case OVALE:
CurrentPad->m_DeltaSize = wxSize(0,0);
break;
case TRAPEZE:
break;
case SPECIAL_PAD:
break;
}
switch ( CurrentPad->m_Attribut )
{
case STANDARD:
break;
case CONN:
case SMD:
CurrentPad->m_Offset = wxSize(0,0);
CurrentPad->m_Drill = 0;
break;
case P_HOLE:
case MECA:
break;
}
CurrentPad->ComputeRayon();
Module->Set_Rectangle_Encadrement();
CurrentPad->Display_Infos(m_Parent);
if ( m_DC ) CurrentPad->Draw(m_Parent->DrawPanel, m_DC, wxPoint(0,0), GR_OR);
m_Parent->GetScreen()->SetModify();
}
Close();
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
381
]
]
]
|
d6665485ed2a2cc0cf0fa166b0251e32bae23918 | f065febc4f2b6104ef8e844b4fae53add2760d71 | /Pow32/link32/Mycobarr.cpp | b7096e8602e48f7e6fad141b4e740a6d5822247c | []
| no_license | Spirit-of-Oberon/POW | 370bcceb2c93ffef941fd8bcb2f1ed5da4926846 | eaf5d9b1817ba4f51e2b3de4adbfe8d726ea3e9f | refs/heads/master | 2021-01-25T07:40:30.160481 | 2011-12-19T13:52:46 | 2011-12-19T13:52:46 | 3,012,201 | 7 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 9,386 | cpp | #ifndef __MYCOLL_HPP__
#include "MyColl.hpp"
#endif
IMPLEMENT_DYNAMIC(CMyObArray, CObArray)
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
CMyObArray::CMyObArray()
{
m_pData= NULL;
m_nSize= m_nMaxSize = m_nGrowBy = 0;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
CMyObArray::~CMyObArray()
{
free((BYTE *)m_pData);
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::SetSize(int nNewSize, int nGrowBy)
{
if (nGrowBy != -1)
m_nGrowBy= nGrowBy; // set new size
if (nNewSize == 0)
{
// shrink to nothing
free((BYTE *)m_pData);
m_pData= NULL;
m_nSize= m_nMaxSize = 0;
}
else if (m_pData == NULL)
{
m_pData= (CObject**) malloc(nNewSize * sizeof(CObject*));
memset(m_pData, 0, nNewSize * sizeof(CObject*)); // zero fill
m_nSize= m_nMaxSize = nNewSize;
}
else if (nNewSize <= m_nMaxSize)
{
if (nNewSize > m_nSize)
memset(&m_pData[m_nSize], 0, (nNewSize-m_nSize) * sizeof(CObject*));
m_nSize= nNewSize;
}
else
{
int nGrowBy= m_nGrowBy;
if (nGrowBy == 0)
{
// heuristically determine growth when nGrowBy == 0
// (this avoids heap fragmentation in many situations)
nGrowBy = min(1024, max(4, m_nSize / 8));
}
int nNewMax;
if (nNewSize < m_nMaxSize + nGrowBy)
nNewMax= m_nMaxSize + nGrowBy; // granularity
else
nNewMax= nNewSize; // no slush
CObject** pNewData = (CObject**) malloc(nNewMax * sizeof(CObject*));
// copy new data from old
memcpy(pNewData, m_pData, m_nSize * sizeof(CObject*));
memset(&pNewData[m_nSize], 0, (nNewSize-m_nSize) * sizeof(CObject*));
// get rid of old stuff (note: no destructors called)
free((BYTE *)m_pData);
m_pData= pNewData;
m_nSize= nNewSize;
m_nMaxSize= nNewMax;
}
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::FreeExtra()
{
if (m_nSize != m_nMaxSize)
{
CObject** pNewData= NULL;
if (m_nSize != 0)
{
pNewData= (CObject**) malloc(m_nSize * sizeof(CObject*));
// copy new data from old
memcpy(pNewData, m_pData, m_nSize * sizeof(CObject*));
}
// get rid of old stuff (note: no destructors called)
free((BYTE *)m_pData);
m_pData= pNewData;
m_nMaxSize= m_nSize;
}
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::SetAtGrow(int nIndex, CObject* newElement)
{
if (nIndex >= m_nSize)
SetSize(nIndex+1);
m_pData[nIndex]= newElement;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::InsertAt(int nIndex, CObject* newElement, int nCount)
{
if (nIndex >= m_nSize)
{
// adding after the end of the array
SetSize(nIndex + nCount); // grow so nIndex is valid
}
else
{
// inserting in the middle of the array
int nOldSize= m_nSize;
SetSize(m_nSize + nCount); // grow it to new size
// shift old data up to fill gap
memmove(&m_pData[nIndex+nCount], &m_pData[nIndex], (nOldSize-nIndex) * sizeof(CObject*));
// re-init slots we copied from
memset(&m_pData[nIndex], 0, nCount * sizeof(CObject*));
}
while (nCount--)
m_pData[nIndex++] = newElement;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::RemoveAt(int nIndex, int nCount)
{
// just remove a range
int nMoveCount= m_nSize - (nIndex + nCount);
if (nMoveCount)
memcpy(&m_pData[nIndex], &m_pData[nIndex + nCount], nMoveCount * sizeof(CObject*));
m_nSize -= nCount;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::InsertAt(int nStartIndex, CMyObArray* pNewArray)
{
if (pNewArray-> GetSize() > 0)
{
InsertAt(nStartIndex, pNewArray->GetAt(0), pNewArray->GetSize());
for (int i= 0; i < pNewArray-> GetSize(); i++)
SetAt(nStartIndex + i, pNewArray-> GetAt(i));
}
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
int CMyObArray::GetSize() const
{
return m_nSize;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
int CMyObArray::GetUpperBound() const
{
return m_nSize - 1;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
inline void CMyObArray::RemoveAll()
{
SetSize(0);
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
CObject* CMyObArray::GetAt(int nIndex) const
{
return m_pData[nIndex];
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
void CMyObArray::SetAt(int nIndex, CObject* newElement)
{
m_pData[nIndex] = newElement;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
inline CObject*& CMyObArray::ElementAt(int nIndex)
{
return m_pData[nIndex];
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
inline int CMyObArray::Add(CObject* newElement)
{
int nIndex= m_nSize;
SetAtGrow(nIndex, newElement);
return nIndex;
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
inline CObject* CMyObArray::operator[](int nIndex) const
{
return GetAt(nIndex);
}
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
inline CObject*& CMyObArray::operator[](int nIndex)
{
return ElementAt(nIndex);
}
| [
"[email protected]"
]
| [
[
[
1,
254
]
]
]
|
91826765054a9bdb205b33448734a1a108339c00 | a5cc77a18ce104eefd5d117ac21a623461fe98ca | /YAXCore/rulesdelegate.hpp | d69a0dd269db5a76b5b5e2f55aaedf57780368da | []
| no_license | vinni-au/yax | 7267ccaba9ce8e207a0a2ea60f3c61b2602895f9 | 122413eefc71a31f4e6700cc958406d244bf9a8f | refs/heads/master | 2016-09-10T03:16:43.293156 | 2011-12-15T19:37:53 | 2011-12-15T19:37:53 | 32,195,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | hpp | #ifndef RULESDELEGATE_HPP
#define RULESDELEGATE_HPP
#include <QStyledItemDelegate>
#include <QtGui>
#include <QSize>
#include "rulestreeitem.hpp"
#include "yaxmodels.hpp"
class RulesDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit RulesDelegate(QObject *parent = 0);
virtual QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
//virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
signals:
public slots:
};
class PremiseConclusionEditor : public QWidget
{
Q_OBJECT
QComboBox* m_cbVariable;
QComboBox* m_cbValue;
public:
explicit PremiseConclusionEditor(QWidget* parent = 0);
};
#endif // RULESDELEGATE_HPP
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
9b0af09aad6be602d19bff36f0b2ef0047ca05b9 | 16d8b25d0d1c0f957c92f8b0d967f71abff1896d | /OblivionOnline/GetLoadedModules.cpp | a2b5df278571fca598921068373db1fb65aa7e1d | []
| no_license | wlasser/oonline | 51973b5ffec0b60407b63b010d0e4e1622cf69b6 | fd37ee6985f1de082cbc9f8625d1d9307e8801a6 | refs/heads/master | 2021-05-28T23:39:16.792763 | 2010-05-12T22:35:20 | 2010-05-12T22:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,487 | cpp | /*----------------------------------------------------------------------
John Robbins - Microsoft Systems Journal Bugslayer Column
----------------------------------------------------------------------*/
#include <windows.h>
#include <tchar.h>
#include "BugslayerUtil.h"
// The project internal header file.
// The NT4 specific version of GetLoadedModules.
BOOL NT4GetLoadedModules ( DWORD dwPID ,
UINT uiCount ,
HMODULE * paModArray ,
LPUINT puiRealCount ) ;
// The TOOLHELP32 specific version of GetLoadedModules.
BOOL TLHELPGetLoadedModules ( DWORD dwPID ,
UINT uiCount ,
HMODULE * paModArray ,
LPUINT puiRealCount ) ;
// The documentation for this function is in BugslayerUtil.h.
BOOL BUGSUTIL_DLLINTERFACE GetLoadedModules ( DWORD dwPID ,
UINT uiCount ,
HMODULE * paModArray ,
LPUINT puiRealCount )
{
// Do the debug checking.
ASSERT ( NULL != puiRealCount ) ;
ASSERT ( FALSE == IsBadWritePtr ( puiRealCount , sizeof ( UINT ) ));
#ifdef _DEBUG
if ( 0 != uiCount )
{
ASSERT ( NULL != paModArray ) ;
ASSERT ( FALSE == IsBadWritePtr ( paModArray ,
uiCount *
sizeof ( HMODULE ) ));
}
#endif
// Do the parameter checking for real. Note that I only check the
// memory in paModArray if uiCount is > 0. The user can pass zero
// in uiCount if they are just interested in the total to be
// returned so they could dynamically allocate a buffer.
if ( ( TRUE == IsBadWritePtr ( puiRealCount , sizeof(UINT) ) ) ||
( ( uiCount > 0 ) &&
( TRUE == IsBadWritePtr ( paModArray ,
uiCount * sizeof(HMODULE) ) ) ) )
{
SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ;
return ( 0 ) ;
}
// Figure out which OS we are on.
OSVERSIONINFO stOSVI ;
memset ( &stOSVI , NULL , sizeof ( OSVERSIONINFO ) ) ;
stOSVI.dwOSVersionInfoSize = sizeof ( OSVERSIONINFO ) ;
BOOL bRet = GetVersionEx ( &stOSVI ) ;
ASSERT ( TRUE == bRet ) ;
if ( FALSE == bRet )
{
TRACE0 ( "GetVersionEx failed!\n" ) ;
return ( FALSE ) ;
}
// Check the version and call the appropriate thing.
if ( ( VER_PLATFORM_WIN32_NT == stOSVI.dwPlatformId ) &&
( 4 == stOSVI.dwMajorVersion ) )
{
// This is NT 4 so call it's specific version.
return ( NT4GetLoadedModules ( dwPID ,
uiCount ,
paModArray ,
puiRealCount ) );
}
else
{
// Everyone other OS goes through TOOLHELP32.
return ( TLHELPGetLoadedModules ( dwPID ,
uiCount ,
paModArray ,
puiRealCount ) ) ;
}
}
| [
"masterfreek64@2644d07b-d655-0410-af38-4bee65694944"
]
| [
[
[
1,
88
]
]
]
|
5b83892c08828b8bbd0a77b5060f9074c7d82746 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestsliderandicons/src/bctestsliderandiconsview.cpp | b73d7dab672bd56a17d1f32c90634d929d4e8f77 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,257 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: view class
*
*/
#include <aknviewappui.h>
#include "bctestsliderandicons.hrh"
#include <bctestsliderandicons.rsg>
#include "bctestsliderandiconsview.h"
#include "bctestsliderandiconscontainer.h"
#include "bctestutil.h"
#include "bctestforslider.h"
#include "bctestforicons.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// Symbian 2nd static Constructor
// ---------------------------------------------------------------------------
//
CBCTestSliderAndIconsView* CBCTestSliderAndIconsView::NewL()
{
CBCTestSliderAndIconsView* self = new( ELeave ) CBCTestSliderAndIconsView();
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop( self );
return self;
}
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTestSliderAndIconsView::CBCTestSliderAndIconsView()
{
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestSliderAndIconsView::ConstructL()
{
BaseConstructL( R_BCTESTSLIDERANDICONS_VIEW );
iContainer = new( ELeave ) CBCTestSliderAndIconsContainer();
iContainer->SetMopParent( this );
iContainer->ConstructL( ClientRect() );
AppUi()->AddToStackL( *this, iContainer );
iContainer->MakeVisible( ETrue );
iTestUtil = CBCTestUtil::NewL();
// Add test case here.
iTestUtil->AddTestCaseL( CBCTestForSlider::NewL( iContainer ),
_L("Slider test case") );
iTestUtil->AddTestCaseL( CBCTestForIcons::NewL( iContainer ),
_L("Icons test case") );
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestSliderAndIconsView::~CBCTestSliderAndIconsView()
{
if ( iContainer )
{
AppUi()->RemoveFromStack( iContainer );
}
delete iContainer;
delete iTestUtil;
}
// ---------------------------------------------------------------------------
// CBCTestSliderAndIconsView::Id
// ---------------------------------------------------------------------------
//
TUid CBCTestSliderAndIconsView::Id() const
{
return KBCTestSliderAndIconsViewId;
}
// ---------------------------------------------------------------------------
// CBCTestSliderAndIconsView::DoActivateL
// ---------------------------------------------------------------------------
//
void CBCTestSliderAndIconsView::DoActivateL( const TVwsViewId&, TUid, const TDesC8& )
{
}
// ---------------------------------------------------------------------------
// CBCTestSliderAndIconsView::DoDeactivate
// ---------------------------------------------------------------------------
//
void CBCTestSliderAndIconsView::DoDeactivate()
{
}
// ---------------------------------------------------------------------------
// CBCTestSliderAndIconsView::HandleCommandL
// ---------------------------------------------------------------------------
//
void CBCTestSliderAndIconsView::HandleCommandL( TInt aCommand )
{
switch ( aCommand )
{
case EProgCmdAutoTest:
iTestUtil->RunL();
break;
default:
if ( aCommand > EBCTestCmdEmptyOutline &&
aCommand < EBCTestCmdMaxOutline )
{
iTestUtil->RunL( aCommand );
}
break;
}
}
| [
"none@none"
]
| [
[
[
1,
134
]
]
]
|
cc730e2b96f277d6f416fc1aac9ea51344abc2f6 | 636990a23a0f702e3c82fa3fc422f7304b0d7b9e | /ocx/AnvizOcx/AnvizOcx/DoorStates.h | 47a6cdf1ab7394641a1c8956917cef2b689c3a0a | []
| no_license | ak869/armcontroller | 09599d2c145e6457aa8c55c8018514578d897de9 | da68e180cacce06479158e7b31374e7ec81c3ebf | refs/heads/master | 2021-01-13T01:17:25.501840 | 2009-02-09T18:03:20 | 2009-02-09T18:03:20 | 40,271,726 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,515 | h | // DoorStates.h : Declaration of the CDoorStates
#pragma once
#include "resource.h" // main symbols
#include "AnvizOcx_i.h"
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
// CDoorStates
class ATL_NO_VTABLE CDoorStates :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CDoorStates, &CLSID_DoorStates>,
public IDispatchImpl<IDoorStates, &IID_IDoorStates, &LIBID_AnvizOcxLib, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
CDoorStates()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_DOORSTATES)
BEGIN_COM_MAP(CDoorStates)
COM_INTERFACE_ENTRY(IDoorStates)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
public:
STDMETHOD(get_Item)(IDoorState** pVal);
STDMETHOD(get__NewEnum)(IUnknown** pVal);
STDMETHOD(get_Count)(LONG* pVal);
};
OBJECT_ENTRY_AUTO(__uuidof(DoorStates), CDoorStates)
| [
"leon.b.dong@41cf9b94-d0c3-11dd-86c2-0f8696b7b6f9"
]
| [
[
[
1,
55
]
]
]
|
f60be4119e2ca2a5d45adc2214988373405f98ea | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/server/so2/npc_creeper.cpp | 5189b26266b7b4cc9fa8cf03b30ac3b2e0d58945 | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 35,188 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: A slow-moving, once-human headcrab victim with only melee attacks.
//
//=============================================================================//
#include "cbase.h"
#include "doors.h"
#include "simtimer.h"
#include "ai_hull.h"
#include "ai_navigator.h"
#include "ai_memory.h"
#include "gib.h"
#include "soundenvelope.h"
#include "engine/IEngineSound.h"
#include "ammodef.h"
#include "npcevent.h"
#include "npc_so_BaseZombie.h"
// Blood loss system
#include "particle_parse.h"
#include "so_player.h"
#include "team.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// ACT_FLINCH_PHYSICS
ConVar so_creeper_health( "so_creeper_health", "250", FCVAR_GAMEDLL | FCVAR_NOTIFY, "Defines the amount of base health a creeper NPC spawns with" );
ConVar so_creeper_damage( "so_creeper_damage", "50", FCVAR_GAMEDLL | FCVAR_NOTIFY, "Defines the approximate amount of base damage a creeper NPC does to its target" );
envelopePoint_t envZombieMoanVolumeFast_creeper[] =
{
{ 7.0f, 7.0f,
0.1f, 0.1f,
},
{ 0.0f, 0.0f,
0.2f, 0.3f,
},
};
envelopePoint_t envZombieMoanVolume_creeper[] =
{
{ 1.0f, 1.0f,
0.1f, 0.1f,
},
{ 1.0f, 1.0f,
0.2f, 0.2f,
},
{ 0.0f, 0.0f,
0.3f, 0.4f,
},
};
envelopePoint_t envZombieMoanVolumeLong_creeper[] =
{
{ 1.0f, 1.0f,
0.3f, 0.5f,
},
{ 1.0f, 1.0f,
0.6f, 1.0f,
},
{ 0.0f, 0.0f,
0.3f, 0.4f,
},
};
envelopePoint_t envZombieMoanIgnited_creeper[] =
{
{ 1.0f, 1.0f,
0.5f, 1.0f,
},
{ 1.0f, 1.0f,
30.0f, 30.0f,
},
{ 0.0f, 0.0f,
0.5f, 1.0f,
},
};
//=============================================================================
//=============================================================================
class CNPC_Creeper : public CAI_BlendingHost<CNPC_SO_BaseZombie>
{
DECLARE_DATADESC();
DECLARE_CLASS( CNPC_Creeper, CAI_BlendingHost<CNPC_SO_BaseZombie> );
// Client-side support for class identification
DECLARE_SERVERCLASS();
public:
CNPC_Creeper()
: m_DurationDoorBash( 2, 6),
m_NextTimeToStartDoorBash( 3.0 )
{
// Blood loss system
m_bLosingBlood = false;
m_hBleedAttacker = NULL;
m_flBleedTime = 0.0f;
}
void Spawn( void );
void NPCThink( void );
void Precache( void );
void SetZombieModel( void );
void MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize );
bool ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold );
bool CanBecomeLiveTorso() { return !m_fIsHeadless; }
void GatherConditions( void );
int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
int TranslateSchedule( int scheduleType );
Activity NPC_TranslateActivity( Activity newActivity );
void OnStateChange( NPC_STATE OldState, NPC_STATE NewState );
void StartTask( const Task_t *pTask );
void RunTask( const Task_t *pTask );
virtual const char *GetLegsModel( void );
virtual const char *GetTorsoModel( void );
virtual const char *GetHeadcrabClassname( void );
virtual const char *GetHeadcrabModel( void );
virtual bool OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal,
CBaseDoor *pDoor,
float distClear,
AIMoveResult_t *pResult );
Activity SelectDoorBash();
void Ignite( float flFlameLifetime, bool bNPCOnly = true, float flSize = 0.0f, bool bCalledByLevelDesigner = false );
void Extinguish();
int OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo );
void Event_Killed( const CTakeDamageInfo &info );
bool IsHeavyDamage( const CTakeDamageInfo &info );
bool IsSquashed( const CTakeDamageInfo &info );
void BuildScheduleTestBits( void );
void PrescheduleThink( void );
int SelectSchedule ( void );
void PainSound( const CTakeDamageInfo &info );
void DeathSound( const CTakeDamageInfo &info );
void AlertSound( void );
void IdleSound( void );
void AttackSound( void );
void AttackHitSound( void );
void AttackMissSound( void );
void FootstepSound( bool fRightFoot );
void FootscuffSound( bool fRightFoot );
const char *GetMoanSound( int nSound );
int GetClawDamage( void );
void HandleAnimEvent( animevent_t *pEvent );
public:
DEFINE_CUSTOM_AI;
protected:
static const char *pMoanSounds[];
private:
CHandle< CBaseDoor > m_hBlockingDoor;
float m_flDoorBashYaw;
CRandSimTimer m_DurationDoorBash;
CSimTimer m_NextTimeToStartDoorBash;
Vector m_vPositionCharged;
// Blood loss system
bool m_bLosingBlood;
EHANDLE m_hBleedAttacker;
float m_flBleedTime;
};
LINK_ENTITY_TO_CLASS( npc_creeper, CNPC_Creeper );
LINK_ENTITY_TO_CLASS( npc_zombie_torso, CNPC_Creeper );
// Client-side support for class identification
IMPLEMENT_SERVERCLASS_ST( CNPC_Creeper, DT_NPC_Creeper )
END_SEND_TABLE()
//---------------------------------------------------------
//---------------------------------------------------------
const char *CNPC_Creeper::pMoanSounds[] =
{
"NPC_BaseZombie.Moan1",
"NPC_BaseZombie.Moan2",
"NPC_BaseZombie.Moan3",
"NPC_BaseZombie.Moan4",
};
//=========================================================
// Conditions
//=========================================================
enum
{
COND_BLOCKED_BY_DOOR = LAST_BASE_ZOMBIE_CONDITION,
COND_DOOR_OPENED,
COND_ZOMBIE_CHARGE_TARGET_MOVED,
};
//=========================================================
// Schedules
//=========================================================
enum
{
SCHED_ZOMBIE_BASH_DOOR = LAST_BASE_ZOMBIE_SCHEDULE,
SCHED_ZOMBIE_WANDER_ANGRILY,
SCHED_ZOMBIE_CHARGE_ENEMY,
SCHED_ZOMBIE_FAIL,
};
//=========================================================
// Tasks
//=========================================================
enum
{
TASK_ZOMBIE_EXPRESS_ANGER = LAST_BASE_ZOMBIE_TASK,
TASK_ZOMBIE_YAW_TO_DOOR,
TASK_ZOMBIE_ATTACK_DOOR,
TASK_ZOMBIE_CHARGE_ENEMY,
};
//-----------------------------------------------------------------------------
extern int ACT_ZOMBIE_TANTRUM;
extern int ACT_ZOMBIE_WALLPOUND;
BEGIN_DATADESC( CNPC_Creeper )
DEFINE_FIELD( m_hBlockingDoor, FIELD_EHANDLE ),
DEFINE_FIELD( m_flDoorBashYaw, FIELD_FLOAT ),
DEFINE_EMBEDDED( m_DurationDoorBash ),
DEFINE_EMBEDDED( m_NextTimeToStartDoorBash ),
DEFINE_FIELD( m_vPositionCharged, FIELD_POSITION_VECTOR ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Creeper::Precache( void )
{
BaseClass::Precache();
PrecacheModel( "models/Zombies/creeper1.mdl" );
PrecacheModel( "models/Zombies/creeper2.mdl" );
PrecacheModel( "models/Zombies/creeper3.mdl" );
PrecacheModel( "models/Zombies/creeper4.mdl" );
PrecacheModel( "models/Zombies/creeper5.mdl" );
PrecacheModel( "models/Zombies/creeper6.mdl" );
PrecacheModel( "models/Zombies/creeper7.mdl" );
PrecacheModel( "models/Zombies/creeper8.mdl" );
PrecacheModel( "models/Zombies/creeper9.mdl" );
PrecacheModel( "models/Zombies/creeper10.mdl" );
PrecacheModel( "models/Zombies/creeper11.mdl" );
PrecacheModel( "models/Zombies/creeper12.mdl" );
PrecacheModel( "models/Zombies/creeper13.mdl" );
PrecacheModel( "models/Zombies/creeper14.mdl" );
PrecacheModel( "models/Zombies/creeper15.mdl" );
PrecacheModel( "models/Zombies/creeper16.mdl" );
PrecacheModel( "models/Zombies/creeper17.mdl" );
PrecacheScriptSound( "Zombie.FootstepRight" );
PrecacheScriptSound( "Zombie.FootstepLeft" );
PrecacheScriptSound( "Zombie.FootstepLeft" );
PrecacheScriptSound( "Zombie.ScuffRight" );
PrecacheScriptSound( "Zombie.ScuffLeft" );
PrecacheScriptSound( "Zombie.AttackHit" );
PrecacheScriptSound( "Zombie.AttackMiss" );
PrecacheScriptSound( "Zombie.Pain" );
PrecacheScriptSound( "Zombie.Die" );
PrecacheScriptSound( "Zombie.Alert" );
PrecacheScriptSound( "Zombie.Idle" );
PrecacheScriptSound( "Zombie.Attack" );
PrecacheScriptSound( "NPC_BaseZombie.Moan1" );
PrecacheScriptSound( "NPC_BaseZombie.Moan2" );
PrecacheScriptSound( "NPC_BaseZombie.Moan3" );
PrecacheScriptSound( "NPC_BaseZombie.Moan4" );
// Blood loss system
PrecacheParticleSystem( "blood_advisor_puncture_withdraw" );
PrecacheScriptSound( "NPC_Creeper.HeadSquirt" );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Creeper::Spawn( void )
{
Precache();
if( FClassnameIs( this, "npc_creeper" ) )
{
m_fIsTorso = false;
}
else
{
// This was placed as an npc_zombie_torso
m_fIsTorso = true;
}
//m_fIsHeadless = true; // no headcrabs!
//SetBloodColor( BLOOD_COLOR_RED ); // normal red blood, not that stupid zombie/green blood crap!
m_iHealth = so_creeper_health.GetFloat();
//m_flFieldOfView = 1.0; // zombies see all!
//GetNavigator()->SetRememberStaleNodes( false );
CapabilitiesClear();
BaseClass::Spawn();
// Additional functionality (opening doors, jumping around, etc)
CapabilitiesAdd( bits_CAP_SQUAD | bits_CAP_DOORS_GROUP | bits_CAP_MOVE_JUMP );
// GetTeamNumber() support
//ChangeTeam( TEAM_ZOMBIES );
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 1.0, 4.0 );
}
void CNPC_Creeper::NPCThink( void )
{
BaseClass::NPCThink();
// Blood loss system
if ( m_bLosingBlood && (gpGlobals->curtime >= m_flBleedTime) && IsAlive() ) // too much blood loss? not dead yet? well, prepare to die zombitch!
{
KillMe(); // IT'S OVER.
// It's important we credit the player who caused the bleeding for their work in killing this zombie
CSO_Player *pBleedAttacker = ToSOPlayer( dynamic_cast<CBasePlayer*>( m_hBleedAttacker.Get() ) );
if ( pBleedAttacker && pBleedAttacker->IsPlayer() )
{
pBleedAttacker->IncrementFragCount( 1 );
GetGlobalTeam( pBleedAttacker->GetTeamNumber() )->AddScore( 1 );
}
// Reset all the variables that got us here
m_bLosingBlood = false;
m_hBleedAttacker = NULL;
m_flBleedTime = 0.0f;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Creeper::PrescheduleThink( void )
{
if( gpGlobals->curtime > m_flNextMoanSound )
{
if( CanPlayMoanSound() )
{
// Classic guy idles instead of moans.
IdleSound();
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 2.0, 5.0 );
}
else
{
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 1.0, 2.0 );
}
}
BaseClass::PrescheduleThink();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_Creeper::SelectSchedule ( void )
{
if( HasCondition( COND_PHYSICS_DAMAGE ) && !m_ActBusyBehavior.IsActive() )
return SCHED_FLINCH_PHYSICS;
// When we aren't doing anything, move around a bit instead of standing around like a moron...
if ( m_NPCState == NPC_STATE_IDLE )
return SCHED_ZOMBIE_WANDER_MEDIUM;
// This should make zombies react to nearby gunfire, etc. instead of standing around like idiots while their fellow undead die...
if ( HasCondition( COND_HEAR_DANGER | COND_HEAR_PLAYER | COND_HEAR_WORLD | COND_HEAR_BULLET_IMPACT | COND_HEAR_COMBAT ) )
return SCHED_INVESTIGATE_SOUND;
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
// Purpose: Sound of a footstep
//-----------------------------------------------------------------------------
void CNPC_Creeper::FootstepSound( bool fRightFoot )
{
if( fRightFoot )
{
EmitSound( "Zombie.FootstepRight" );
}
else
{
EmitSound( "Zombie.FootstepLeft" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Sound of a foot sliding/scraping
//-----------------------------------------------------------------------------
void CNPC_Creeper::FootscuffSound( bool fRightFoot )
{
if( fRightFoot )
{
EmitSound( "Zombie.ScuffRight" );
}
else
{
EmitSound( "Zombie.ScuffLeft" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack hit sound
//-----------------------------------------------------------------------------
void CNPC_Creeper::AttackHitSound( void )
{
EmitSound( "Zombie.AttackHit" );
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack miss sound
//-----------------------------------------------------------------------------
void CNPC_Creeper::AttackMissSound( void )
{
// Play a random attack miss sound
EmitSound( "Zombie.AttackMiss" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Creeper::PainSound( const CTakeDamageInfo &info )
{
// We're constantly taking damage when we are on fire. Don't make all those noises!
if ( IsOnFire() )
{
return;
}
EmitSound( "Zombie.Pain" );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Creeper::DeathSound( const CTakeDamageInfo &info )
{
EmitSound( "Zombie.Die" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Creeper::AlertSound( void )
{
EmitSound( "Zombie.Alert" );
// Don't let a moan sound cut off the alert sound.
m_flNextMoanSound += random->RandomFloat( 2.0, 4.0 );
}
//-----------------------------------------------------------------------------
// Purpose: Returns a moan sound for this class of zombie.
//-----------------------------------------------------------------------------
const char *CNPC_Creeper::GetMoanSound( int nSound )
{
return pMoanSounds[ nSound % ARRAYSIZE( pMoanSounds ) ];
}
//-----------------------------------------------------------------------------
// Purpose: Play a random idle sound.
//-----------------------------------------------------------------------------
void CNPC_Creeper::IdleSound( void )
{
if( GetState() == NPC_STATE_IDLE && random->RandomFloat( 0, 1 ) == 0 )
{
// Moan infrequently in IDLE state.
return;
}
if( IsSlumped() )
{
// Sleeping zombies are quiet.
return;
}
EmitSound( "Zombie.Idle" );
MakeAISpookySound( 360.0f );
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack sound.
//-----------------------------------------------------------------------------
void CNPC_Creeper::AttackSound( void )
{
EmitSound( "Zombie.Attack" );
}
//-----------------------------------------------------------------------------
// Purpose: Returns the classname (ie "npc_headcrab") to spawn when our headcrab bails.
//-----------------------------------------------------------------------------
const char *CNPC_Creeper::GetHeadcrabClassname( void )
{
return "npc_headcrab";
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const char *CNPC_Creeper::GetHeadcrabModel( void )
{
return "models/headcrabclassic.mdl";
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CNPC_Creeper::GetLegsModel( void )
{
return "models/zombie/classic_legs.mdl";
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const char *CNPC_Creeper::GetTorsoModel( void )
{
return "models/zombie/classic_torso.mdl";
}
//---------------------------------------------------------
//---------------------------------------------------------
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::SetZombieModel( void )
{
Hull_t lastHull = GetHullType();
int randcreepermodel = random->RandomInt(1,17);
switch( randcreepermodel )
{
case 1:
SetModel( "models/Zombies/creeper1.mdl" );
break;
case 2:
SetModel( "models/Zombies/creeper2.mdl" );
break;
case 3:
SetModel( "models/Zombies/creeper3.mdl" );
break;
case 4:
SetModel( "models/Zombies/creeper4.mdl" );
break;
case 5:
SetModel( "models/Zombies/creeper5.mdl" );
break;
case 6:
SetModel( "models/Zombies/creeper6.mdl" );
break;
case 7:
SetModel( "models/Zombies/creeper7.mdl" );
break;
case 8:
SetModel( "models/Zombies/creeper8.mdl" );
break;
case 9:
SetModel( "models/Zombies/creeper9.mdl" );
break;
case 10:
SetModel( "models/Zombies/creeper10.mdl" );
break;
case 11:
SetModel( "models/Zombies/creeper11.mdl" );
break;
case 12:
SetModel( "models/Zombies/creeper12.mdl" );
break;
case 13:
SetModel( "models/Zombies/creeper13.mdl" );
break;
case 14:
SetModel( "models/Zombies/creeper14.mdl" );
break;
case 15:
SetModel( "models/Zombies/creeper15.mdl" );
break;
case 16:
SetModel( "models/Zombies/creeper16.mdl" );
break;
case 17:
SetModel( "models/Zombies/creeper17.mdl" );
break;
}
SetHullType( HULL_HUMAN );
SetHullSizeNormal( true );
SetDefaultEyeOffset();
SetActivity( ACT_IDLE );
// hull changed size, notify vphysics
// UNDONE: Solve this generally, systematically so other
// NPCs can change size
if ( lastHull != GetHullType() )
{
if ( VPhysicsGetObject() )
{
SetupVPhysicsHull();
}
}
}
//---------------------------------------------------------
// Classic zombie only uses moan sound if on fire.
//---------------------------------------------------------
void CNPC_Creeper::MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize )
{
if( IsOnFire() )
{
BaseClass::MoanSound( pEnvelope, iEnvelopeSize );
}
}
//---------------------------------------------------------
//---------------------------------------------------------
bool CNPC_Creeper::ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold )
{
return false; // never become a torso
}
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::GatherConditions( void )
{
BaseClass::GatherConditions();
static int conditionsToClear[] =
{
COND_BLOCKED_BY_DOOR,
COND_DOOR_OPENED,
COND_ZOMBIE_CHARGE_TARGET_MOVED,
};
ClearConditions( conditionsToClear, ARRAYSIZE( conditionsToClear ) );
if ( m_hBlockingDoor == NULL ||
( m_hBlockingDoor->m_toggle_state == TS_AT_TOP ||
m_hBlockingDoor->m_toggle_state == TS_GOING_UP ) )
{
ClearCondition( COND_BLOCKED_BY_DOOR );
if ( m_hBlockingDoor != NULL )
{
SetCondition( COND_DOOR_OPENED );
m_hBlockingDoor = NULL;
}
}
else
SetCondition( COND_BLOCKED_BY_DOOR );
if ( ConditionInterruptsCurSchedule( COND_ZOMBIE_CHARGE_TARGET_MOVED ) )
{
if ( GetNavigator()->IsGoalActive() )
{
const float CHARGE_RESET_TOLERANCE = 60.0;
if ( !GetEnemy() ||
( m_vPositionCharged - GetEnemyLKP() ).Length() > CHARGE_RESET_TOLERANCE )
{
SetCondition( COND_ZOMBIE_CHARGE_TARGET_MOVED );
}
}
}
}
int CNPC_Creeper::GetClawDamage( void )
{
int tempdmg = random->RandomInt( so_creeper_damage.GetInt() - 10, so_creeper_damage.GetInt() + 10 );
if ( tempdmg <= 0 )
tempdmg = 1; // at least do some damage...
return tempdmg;
}
void CNPC_Creeper::HandleAnimEvent( animevent_t *pEvent )
{
if ( pEvent->event == AE_ZOMBIE_ATTACK_RIGHT )
{
Vector right, forward;
AngleVectors( GetLocalAngles(), &forward, &right, NULL );
right = right * 100;
forward = forward * 200;
ClawAttack( GetClawAttackRange(), GetClawDamage(), QAngle( -15, -20, -10 ), right + forward, ZOMBIE_BLOOD_RIGHT_HAND );
return;
}
if ( pEvent->event == AE_ZOMBIE_ATTACK_LEFT )
{
Vector right, forward;
AngleVectors( GetLocalAngles(), &forward, &right, NULL );
right = right * -100;
forward = forward * 200;
ClawAttack( GetClawAttackRange(), GetClawDamage(), QAngle( -15, 20, -10 ), right + forward, ZOMBIE_BLOOD_LEFT_HAND );
return;
}
if ( pEvent->event == AE_ZOMBIE_ATTACK_BOTH )
{
Vector forward;
QAngle qaPunch( 45, random->RandomInt(-5,5), random->RandomInt(-5,5) );
AngleVectors( GetLocalAngles(), &forward );
forward = forward * 200;
ClawAttack( GetClawAttackRange(), GetClawDamage(), qaPunch, forward, ZOMBIE_BLOOD_BOTH_HANDS );
return;
}
BaseClass::HandleAnimEvent( pEvent );
}
//---------------------------------------------------------
//---------------------------------------------------------
int CNPC_Creeper::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode )
{
if ( HasCondition( COND_BLOCKED_BY_DOOR ) && m_hBlockingDoor != NULL )
{
ClearCondition( COND_BLOCKED_BY_DOOR );
if ( m_NextTimeToStartDoorBash.Expired() && failedSchedule != SCHED_ZOMBIE_BASH_DOOR )
return SCHED_ZOMBIE_BASH_DOOR;
m_hBlockingDoor = NULL;
}
if ( failedSchedule != SCHED_ZOMBIE_CHARGE_ENEMY &&
IsPathTaskFailure( taskFailCode ) &&
random->RandomInt( 1, 100 ) < 50 )
{
return SCHED_ZOMBIE_CHARGE_ENEMY;
}
if ( failedSchedule != SCHED_ZOMBIE_WANDER_ANGRILY &&
( failedSchedule == SCHED_TAKE_COVER_FROM_ENEMY ||
failedSchedule == SCHED_CHASE_ENEMY_FAILED ) )
{
return SCHED_ZOMBIE_WANDER_ANGRILY;
}
return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode );
}
//---------------------------------------------------------
//---------------------------------------------------------
int CNPC_Creeper::TranslateSchedule( int scheduleType )
{
if ( scheduleType == SCHED_COMBAT_FACE && IsUnreachable( GetEnemy() ) )
return SCHED_TAKE_COVER_FROM_ENEMY;
if ( !m_fIsTorso && scheduleType == SCHED_FAIL )
return SCHED_ZOMBIE_FAIL;
return BaseClass::TranslateSchedule( scheduleType );
}
//---------------------------------------------------------
Activity CNPC_Creeper::NPC_TranslateActivity( Activity newActivity )
{
newActivity = BaseClass::NPC_TranslateActivity( newActivity );
if ( newActivity == ACT_RUN )
return ACT_WALK;
// Allows for jumping, etc.
// TODO: We could use a better system or even new animations here...
if ( (newActivity == ACT_FLY) ||
(newActivity == ACT_HOVER) ||
(newActivity == ACT_GLIDE) ||
(newActivity == ACT_SWIM) ||
(newActivity == ACT_JUMP) ||
(newActivity == ACT_HOP) ||
(newActivity == ACT_LEAP) ||
(newActivity == ACT_LAND) ||
(newActivity == ACT_CLIMB_UP) ||
(newActivity == ACT_CLIMB_DOWN) ||
(newActivity == ACT_CLIMB_DISMOUNT) )
{
return ACT_WALK_ON_FIRE;
}
if ( m_fIsTorso && ( newActivity == ACT_ZOMBIE_TANTRUM ) )
return ACT_IDLE;
return newActivity;
}
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::OnStateChange( NPC_STATE OldState, NPC_STATE NewState )
{
BaseClass::OnStateChange( OldState, NewState );
}
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_ZOMBIE_EXPRESS_ANGER:
{
if ( random->RandomInt( 1, 4 ) == 2 )
{
SetIdealActivity( (Activity)ACT_ZOMBIE_TANTRUM );
}
else
{
TaskComplete();
}
break;
}
case TASK_ZOMBIE_YAW_TO_DOOR:
{
AssertMsg( m_hBlockingDoor != NULL, "Expected condition handling to break schedule before landing here" );
if ( m_hBlockingDoor != NULL )
{
GetMotor()->SetIdealYaw( m_flDoorBashYaw );
}
TaskComplete();
break;
}
case TASK_ZOMBIE_ATTACK_DOOR:
{
m_DurationDoorBash.Reset();
SetIdealActivity( SelectDoorBash() );
break;
}
case TASK_ZOMBIE_CHARGE_ENEMY:
{
if ( !GetEnemy() )
TaskFail( FAIL_NO_ENEMY );
else if ( GetNavigator()->SetVectorGoalFromTarget( GetEnemy()->GetLocalOrigin() ) )
{
m_vPositionCharged = GetEnemy()->GetLocalOrigin();
TaskComplete();
}
else
TaskFail( FAIL_NO_ROUTE );
break;
}
default:
BaseClass::StartTask( pTask );
break;
}
}
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_ZOMBIE_ATTACK_DOOR:
{
if ( IsActivityFinished() )
{
if ( m_DurationDoorBash.Expired() )
{
TaskComplete();
m_NextTimeToStartDoorBash.Reset();
}
else
ResetIdealActivity( SelectDoorBash() );
}
break;
}
case TASK_ZOMBIE_CHARGE_ENEMY:
{
break;
}
case TASK_ZOMBIE_EXPRESS_ANGER:
{
if ( IsActivityFinished() )
{
TaskComplete();
}
break;
}
default:
BaseClass::RunTask( pTask );
break;
}
}
//---------------------------------------------------------
//---------------------------------------------------------
bool CNPC_Creeper::OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal, CBaseDoor *pDoor,
float distClear, AIMoveResult_t *pResult )
{
if ( BaseClass::OnObstructingDoor( pMoveGoal, pDoor, distClear, pResult ) )
{
if ( IsMoveBlocked( *pResult ) && pMoveGoal->directTrace.vHitNormal != vec3_origin )
{
m_hBlockingDoor = pDoor;
m_flDoorBashYaw = UTIL_VecToYaw( pMoveGoal->directTrace.vHitNormal * -1 );
}
return true;
}
return false;
}
//---------------------------------------------------------
//---------------------------------------------------------
Activity CNPC_Creeper::SelectDoorBash()
{
if ( random->RandomInt( 1, 3 ) == 1 )
return ACT_MELEE_ATTACK1;
return (Activity)ACT_ZOMBIE_WALLPOUND;
}
//---------------------------------------------------------
// Zombies should scream continuously while burning, so long
// as they are alive... but NOT IN GERMANY!
//---------------------------------------------------------
void CNPC_Creeper::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner )
{
if( !IsOnFire() && IsAlive() )
{
BaseClass::Ignite( flFlameLifetime, bNPCOnly, flSize, bCalledByLevelDesigner );
if ( !UTIL_IsLowViolence() )
{
RemoveSpawnFlags( SF_NPC_GAG );
MoanSound( envZombieMoanIgnited_creeper, ARRAYSIZE( envZombieMoanIgnited_creeper ) );
if ( m_pMoanSound )
{
ENVELOPE_CONTROLLER.SoundChangePitch( m_pMoanSound, 120, 1.0 );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pMoanSound, 1, 1.0 );
}
}
}
}
//---------------------------------------------------------
// If a zombie stops burning and hasn't died, quiet him down
//---------------------------------------------------------
void CNPC_Creeper::Extinguish()
{
if( m_pMoanSound )
{
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pMoanSound, 0, 2.0 );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pMoanSound, 100, 2.0 );
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 2.0, 4.0 );
}
BaseClass::Extinguish();
}
//---------------------------------------------------------
//---------------------------------------------------------
int CNPC_Creeper::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo )
{
CTakeDamageInfo info = inputInfo;
if ( info.GetDamageType() & (DMG_BULLET | DMG_BUCKSHOT) ) // creepers handle bullets and buckshot differently depending on where they're hit
{
if ( m_bHeadShot )
{
info.ScaleDamage( 2.0f ); // headshots hurt us a lot!
// Blood loss system
int shouldHeadExplode = random->RandomInt( 1, 10 ); // there's a 10% chance of our head bleeding when we get shot in the head
if ( shouldHeadExplode == 1 ) // sorry zombie, but here it comes!
{
EmitSound( "NPC_Creeper.HeadSquirt" ); // the sound...
DispatchParticleEffect( "blood_advisor_puncture_withdraw", PATTACH_POINT_FOLLOW, this, "eyes" ); // the blood...
AddFlag( FL_ONFIRE ); // this could have some nasty side-effects, but oh well!
RemoveSpawnFlags( SF_NPC_GAG );
MoanSound( envZombieMoanIgnited_creeper, ARRAYSIZE( envZombieMoanIgnited_creeper ) );
if ( m_pMoanSound ) // begin moaning like we're on fire since bleeding hurts :(
{
ENVELOPE_CONTROLLER.SoundChangePitch( m_pMoanSound, 120, 1.0 );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pMoanSound, 1, 1.0 );
}
m_bLosingBlood = true;
m_hBleedAttacker = info.GetAttacker();
m_flBleedTime = gpGlobals->curtime + 2.0f; // we're bleeding from our head, which means we should die pretty soon
}
}
else
{
info.ScaleDamage( 0.5f ); // other things do not hurt as much (we can survive with damaged limbs and whatnot)
}
}
// Throw some blood on the ground when we take damage (adds some realism)
trace_t tr;
AI_TraceLine( GetAbsOrigin()+Vector(0,0,1), GetAbsOrigin()-Vector(0,0,64), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
UTIL_BloodDecalTrace( &tr, BloodColor() );
return BaseClass::OnTakeDamage_Alive( info );
}
void CNPC_Creeper::Event_Killed( const CTakeDamageInfo &info )
{
// Blood loss system
StopSound( "NPC_Creeper.HeadSquirt" );
StopParticleEffects( this ); // make sure we end any attachment-based particle effects here
// not doing so would make them float around in the air because we're about to become a ragdoll
// actually, we may have become one already (not sure how it works), but better late than never
BaseClass::Event_Killed( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Creeper::IsHeavyDamage( const CTakeDamageInfo &info )
{
if ( info.GetDamageType() & DMG_BUCKSHOT )
{
if ( !m_fIsTorso && info.GetDamage() > (m_iMaxHealth/3) )
return true;
}
// Randomly treat all damage as heavy
if ( info.GetDamageType() & (DMG_BULLET | DMG_BUCKSHOT) )
{
// Don't randomly flinch if I'm melee attacking
if ( !HasCondition(COND_CAN_MELEE_ATTACK1) && (RandomFloat() > 0.5) )
{
// Randomly forget I've flinched, so that I'll be forced to play a big flinch
// If this doesn't happen, it means I may not fully flinch if I recently flinched
if ( RandomFloat() > 0.75 )
{
Forget(bits_MEMORY_FLINCHED);
}
return true;
}
}
return BaseClass::IsHeavyDamage(info);
}
//---------------------------------------------------------
//---------------------------------------------------------
#define ZOMBIE_SQUASH_MASS 300.0f // Anything this heavy or heavier squashes a zombie good. (show special fx)
bool CNPC_Creeper::IsSquashed( const CTakeDamageInfo &info )
{
if( GetHealth() > 0 )
{
return false;
}
if( info.GetDamageType() & DMG_CRUSH )
{
IPhysicsObject *pCrusher = info.GetInflictor()->VPhysicsGetObject();
if( pCrusher && pCrusher->GetMass() >= ZOMBIE_SQUASH_MASS && info.GetInflictor()->WorldSpaceCenter().z > EyePosition().z )
{
// This heuristic detects when a zombie has been squashed from above by a heavy
// item. Done specifically so we can add gore effects to Ravenholm cartraps.
// The zombie must take physics damage from a 300+kg object that is centered above its eyes (comes from above)
return true;
}
}
return false;
}
//---------------------------------------------------------
//---------------------------------------------------------
void CNPC_Creeper::BuildScheduleTestBits( void )
{
BaseClass::BuildScheduleTestBits();
if( !m_fIsTorso && !IsCurSchedule( SCHED_FLINCH_PHYSICS ) && !m_ActBusyBehavior.IsActive() )
{
SetCustomInterruptCondition( COND_PHYSICS_DAMAGE );
}
}
//=============================================================================
AI_BEGIN_CUSTOM_NPC( npc_creeper, CNPC_Creeper )
DECLARE_CONDITION( COND_BLOCKED_BY_DOOR )
DECLARE_CONDITION( COND_DOOR_OPENED )
DECLARE_CONDITION( COND_ZOMBIE_CHARGE_TARGET_MOVED )
DECLARE_TASK( TASK_ZOMBIE_EXPRESS_ANGER )
DECLARE_TASK( TASK_ZOMBIE_YAW_TO_DOOR )
DECLARE_TASK( TASK_ZOMBIE_ATTACK_DOOR )
DECLARE_TASK( TASK_ZOMBIE_CHARGE_ENEMY )
DECLARE_ACTIVITY( ACT_ZOMBIE_TANTRUM );
DECLARE_ACTIVITY( ACT_ZOMBIE_WALLPOUND );
DEFINE_SCHEDULE
(
SCHED_ZOMBIE_BASH_DOOR,
" Tasks"
" TASK_SET_ACTIVITY ACTIVITY:ACT_ZOMBIE_TANTRUM"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_TAKE_COVER_FROM_ENEMY"
" TASK_ZOMBIE_YAW_TO_DOOR 0"
" TASK_FACE_IDEAL 0"
" TASK_ZOMBIE_ATTACK_DOOR 0"
""
" Interrupts"
" COND_ZOMBIE_RELEASECRAB"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_DOOR_OPENED"
)
DEFINE_SCHEDULE
(
SCHED_ZOMBIE_WANDER_ANGRILY,
" Tasks"
" TASK_WANDER 480240" // 48 units to 240 units.
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 4"
""
" Interrupts"
" COND_ZOMBIE_RELEASECRAB"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_DOOR_OPENED"
)
DEFINE_SCHEDULE
(
SCHED_ZOMBIE_CHARGE_ENEMY,
" Tasks"
" TASK_ZOMBIE_CHARGE_ENEMY 0"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ZOMBIE_TANTRUM" /* placeholder until frustration/rage/fence shake animation available */
""
" Interrupts"
" COND_ZOMBIE_RELEASECRAB"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_DOOR_OPENED"
" COND_ZOMBIE_CHARGE_TARGET_MOVED"
)
DEFINE_SCHEDULE
(
SCHED_ZOMBIE_FAIL,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_ZOMBIE_TANTRUM"
" TASK_WAIT 1"
" TASK_WAIT_PVS 0"
""
" Interrupts"
" COND_CAN_RANGE_ATTACK1 "
" COND_CAN_RANGE_ATTACK2 "
" COND_CAN_MELEE_ATTACK1 "
" COND_CAN_MELEE_ATTACK2"
" COND_GIVE_WAY"
" COND_DOOR_OPENED"
)
AI_END_CUSTOM_NPC()
//=============================================================================
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
1227
]
]
]
|
c208c912af47817142291edc34923128cda799b5 | 8e4d21a99d0ce5413eab7a083544aff9f944b26f | /src/NthShape.cpp | 5375f052000463d33f58756a62d7fd9d608c6537 | []
| no_license | wangjunbao/nontouchsdk | 957612b238b8b221b4284efb377db220bd41186a | 81ab8519ea1af45dbb7ff66c6784961f14f9930c | refs/heads/master | 2021-01-23T13:57:20.020732 | 2010-10-31T12:03:49 | 2010-10-31T12:03:49 | 34,656,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | /*
* NthShape.cpp
* CopyRight @South China Institute of Software Engineering,.GZU
* Author:
* 2010/10/20
*/
#ifndef DLL_FILE
#define DLL_FILE
#endif
#include "NthShape.h"
NthShape::NthShape(void)
{
}
NthShape::~NthShape(void)
{
}
| [
"tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213"
]
| [
[
[
1,
20
]
]
]
|
6ebd9ba62ef7953d301d9bddb8bd0d27f6de066e | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/QtApp/JsComponent/src/NetGameComponent.cpp | e5c90c90e5f4a2efc5702f0633e656b3a6349f7e | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,039 | cpp | #include "JsComponentStableHeaders.h"
#include "NetGameComponent.h"
#include "Js.h"
#include <WheelGobal/WheelEvents.h>
using namespace Orz;
NetClock::NetClock(void):_allSecond(30),_second(0),_pass(0.f)
{
}
void NetClock::reset(void)
{
_second = 0;
}
NetClock::~NetClock(void)
{
}
//获取剩余时间
int NetClock::getLastSecond(void) const
{
return _allSecond - _second;
}
//获取当前时间
int NetClock::getSecond(void) const
{
return _second;
}
//获取总时间
int NetClock::getAllSecond(void) const
{
return _allSecond;
}
void NetClock::setTime(int time)
{
setSecond(_allSecond - time);
}
//设置当前时间
void NetClock::setSecond(int second)
{
if(_second != second)
{
_second = second;
}
}
//设置总时间
void NetClock::setAllSecond(int allSecond)
{
_allSecond = allSecond;
}
//void NetClock::setListener(NetClockListener * listener)
//{
// _callback = listener;
//}
void NetClock::update(TimeType interval)
{
/* _pass += interval;
if(_pass>=1.f)
{
_pass -= 1.f;
int second = getSecond() +1;
if(second <= _allSecond)
setSecond(second);
}*/
}
NetGameComponent::NetGameComponent(void):_gameInterface(new RouletteGameInterfaces())
,_clockInterface(new RouletteClockInterface())
,_uiInterface(new RouletteUIInterface())
{
_query.add(_clockInterface.get());
_query.add(_uiInterface.get());
_query.add(_gameInterface.get());
_gameInterface->update =boost::bind(&NetGameComponent::update, this, _1);
_gameInterface->enableState =boost::bind(&NetGameComponent::enableState, this, _1, _2);
_gameInterface->disableState =boost::bind(&NetGameComponent::disableState, this, _1);
_clockInterface->reset =boost::bind(&NetClock::reset, &_clock);
_clockInterface->update =boost::bind(&NetClock::update, &_clock, _1);
_clockInterface->time =boost::bind(&NetClock::getLastSecond, &_clock);
_uiInterface->setTheTime =boost::bind(&WheelGameUIRegister::setTheTime, &_uiRegister, _1);
_uiInterface->setStartVisible =boost::bind(&WheelGameUIRegister::setStartVisible, &_uiRegister, _1);
_uiInterface->setEndVisible =boost::bind(&WheelGameUIRegister::setEndVisible, &_uiRegister, _1);
_uiInterface->runWinner =boost::bind(&WheelGameUIRegister::runWinner, &_uiRegister);
_uiInterface->setLogoShow =boost::bind(&WheelGameUIRegister::setLogoShow, &_uiRegister, _1);
_uiInterface->addBottom =boost::bind(&WheelGameUIRegister::addBottom, &_uiRegister);
_uiInterface->update =boost::bind(&WheelGameUIRegister::update, &_uiRegister, _1);
Js::getInstancePtr()->subscribeStartGame(boost::bind(&NetGameComponent::startGame, this));
Js::getInstancePtr()->subscribeSetTime(boost::bind(&NetClock::setTime, &_clock, _1));
}
void NetGameComponent::disableState(Event::message_type evt)
{
// std::cout<<int(evt)<<std::endl;
// switch(evt)
// {
// case WheelEvents::PROCESS_START_DISABLE:
// //Js::getInstancePtr()->setButtonEnable(false);
// break;
// }
}
void NetGameComponent::enableState(Event::message_type evt, RouletteGameInterfaces::Referenced referenced)
{
switch(evt)
{
case WheelEvents::PROCESS_LOGO_ENABLE:
_holdLogo = referenced;
break;
/*case WheelEvents::PROCESS_START_ENABLE:
Js::getInstancePtr()->setButtonEnable(true);
break;*/
}
}
void NetGameComponent::startGame(void)
{
_holdLogo.reset();
}
//void NetGameComponent::stateEvent(Event::message_type evt)
//{
// switch(evt)
// {
// case WheelEvents::PROCESS_START_ENABLE:
// Js::getInstancePtr()->setButtonEnable(true);
// break;
// case WheelEvents::PROCESS_START_DISABLE:
// Js::getInstancePtr()->setButtonEnable(false);
// break;
// }
// std::cout<<int(evt)<<std::endl;
//}
NetGameComponent::~NetGameComponent(void)
{
}
void NetGameComponent::setTime(int time)
{
}
bool NetGameComponent::update(TimeType i)
{
_uiRegister.update(i);
return true;
} | [
"[email protected]"
]
| [
[
[
1,
176
]
]
]
|
d9cc911b1a99f06dde3c65f748f8d41f0b97f6c5 | b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa | /RadiantLaserCross/RLC_PlayerShip.cpp | 88e2a3ee65904c628eba72004dd1858db3df7be6 | []
| no_license | Klaim/radiant-laser-cross | f65571018bf612820415e0f672c216caf35de439 | bf26a3a417412c0e1b77267b4a198e514b2c7915 | refs/heads/master | 2021-01-01T18:06:58.019414 | 2010-11-06T14:56:11 | 2010-11-06T14:56:11 | 32,205,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,444 | cpp | #include "RLC_PlayerShip.h"
#include <cmath>
#include <boost/make_shared.hpp>
#include "sfml/Graphics/Shape.hpp"
#include "sfml/Graphics/Rect.hpp"
#include "sfml/Graphics/Color.hpp"
#include "sfml/Graphics/RenderWindow.hpp"
#include "RLC_Game.h"
#include "RLC_GameConfig.h"
#include "RLC_BulletType.h"
#include "RLC_GunType.h"
namespace rlc
{
namespace config
{
const float SHIP_WIDTH = 32.0f;
const float SHIP_HEIGHT = 32.0f;
const float GUN_DISTANCE = 26.0f;
const float GUN_WIDTH = 20.0f;
const float GUN_HEIGHT = 16.0f;
const float GUN_ANGLE_INTERVAL = 360.0f / float(MAX_PLAYER_GUNS);
const float GUN_FIRE_BORDER_ANGLE = (GUN_ANGLE_INTERVAL / 2.0f);
const float GUN_ROTATION_SPEED = 5.0f;
const float FULL_SHIP_WIDTH = SHIP_WIDTH + SHIP_HEIGHT;
const float SQUARE_ANGLE = 90.0f;
const float UP_ANGLE = SQUARE_ANGLE * 4.0f;
const float LEFT_ANGLE = SQUARE_ANGLE * 3.0f;
const float DOWN_ANGLE = SQUARE_ANGLE * 2.0f;
const float RIGHT_ANGLE = SQUARE_ANGLE;
}
using namespace config;
namespace test
{
class BulletType : public rlc::BulletType
{
public:
BulletType( sf::Color b_color ) : m_bullet_color( b_color ) {}
sf::Shape bullet_shape() const
{
return sf::Shape::Circle( 0.0f, 0.0f, 4.0f, m_bullet_color );
}
float bullet_speed() const { return 20.0f; }
sf::Color bullet_color() const { return m_bullet_color; }
void bullet_behavior( Bullet& bullet ) const { }
private:
sf::Color m_bullet_color;
};
class GunType : public rlc::GunType
{
public:
GunType( BulletTypePtr bt ) : m_bullet_type( bt ) { GC_ASSERT_NOT_NULL(m_bullet_type); }
BulletTypePtr bullet_type() const { return m_bullet_type;}
float fire_rate() const { return 5.0f; }
private:
BulletTypePtr m_bullet_type;
};
}
PlayerShip::PlayerShip()
: m_guns_orientation( 0.0f )
, m_guns_setup( GunsSetup_East )
{
core( Box(-4,-4,4,4) );
BulletTypePtr test_bullet_type_0 = boost::make_shared<test::BulletType>( gun_color(0) );
BulletTypePtr test_bullet_type_1 = boost::make_shared<test::BulletType>( gun_color(1) );
BulletTypePtr test_bullet_type_2 = boost::make_shared<test::BulletType>( gun_color(2) );
BulletTypePtr test_bullet_type_3 = boost::make_shared<test::BulletType>( gun_color(3) );
GunTypePtr test_gun_type_0 = boost::make_shared<test::GunType>( test_bullet_type_0 );
GunTypePtr test_gun_type_1 = boost::make_shared<test::GunType>( test_bullet_type_1 );
GunTypePtr test_gun_type_2 = boost::make_shared<test::GunType>( test_bullet_type_2 );
GunTypePtr test_gun_type_3 = boost::make_shared<test::GunType>( test_bullet_type_3 );
set_gun( boost::make_shared<Gun>( test_gun_type_0 ), 0 );
set_gun( boost::make_shared<Gun>( test_gun_type_1 ), 1 );
set_gun( boost::make_shared<Gun>( test_gun_type_2 ), 2 );
set_gun( boost::make_shared<Gun>( test_gun_type_3 ), 3 );
get_gun(0)->name( "Gun_A" );
get_gun(1)->name( "Gun_B" );
get_gun(2)->name( "Gun_C" );
get_gun(3)->name( "Gun_D" );
get_gun(0)->cannon( Position( GUN_DISTANCE + GUN_WIDTH, 0.0f ) );
get_gun(1)->cannon( Position( GUN_DISTANCE + GUN_WIDTH, 0.0f ) );
get_gun(2)->cannon( Position( GUN_DISTANCE + GUN_WIDTH, 0.0f ) );
get_gun(3)->cannon( Position( GUN_DISTANCE + GUN_WIDTH, 0.0f ) );
get_gun(0)->direction( Vector2( 1.0f, 0.0f ) );
get_gun(1)->direction( Vector2( 0.0f, -1.0f ) );
get_gun(2)->direction( Vector2( -1.0f, 0.0f ) );
get_gun(3)->direction( Vector2( 0.0f, 1.0f ) );
using namespace config;
position( Position( SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f ) ) ;
rotate_guns( 1 );
}
void PlayerShip::do_update()
{
update_move();
update_guns();
}
inline bool in_circle_angle( const float& val, const float& target_angle, const float& tolerance )
{
if( val < 0.0f ) return false;
const float min_angle = target_angle - tolerance;
const float max_angle = target_angle + tolerance;
return (( val >= min_angle )
&& ( val <= max_angle )
)
|| ( target_angle >= UP_ANGLE && val <= tolerance )
;
}
void PlayerShip::update_move()
{
using namespace sf;
const Input& input = Game::instance().display().GetInput();
Position move;
Position position = this->position();
static const float MOVE_JOYSTICK_TOLERANCE = 33.0f;
static const float FIRE_JOYSTICK_TOLERANCE = 66.0f;
static const float POV_ANGLE_TOLERANCE = 55.0f;
const float pov_angle = input.GetJoystickAxis( 0, sf::Joy::AxisPOV );
if( input.IsKeyDown( Key::Left )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_MOVE_LEFT ) )
|| input.GetJoystickAxis( 0, sf::Joy::AxisX ) < -MOVE_JOYSTICK_TOLERANCE
|| in_circle_angle( pov_angle, LEFT_ANGLE, POV_ANGLE_TOLERANCE )
)
{
if( position.x > FULL_SHIP_WIDTH/2 )
move.x -= 1;
}
if( input.IsKeyDown( Key::Right )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_MOVE_RIGHT ) )
|| input.GetJoystickAxis( 0, sf::Joy::AxisX ) > MOVE_JOYSTICK_TOLERANCE
|| in_circle_angle( pov_angle, RIGHT_ANGLE, POV_ANGLE_TOLERANCE )
)
{
if( position.x < ( SCREEN_WIDTH - (FULL_SHIP_WIDTH/2) ) )
move.x += 1;
}
if( input.IsKeyDown( Key::Up )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_MOVE_UP ) )
|| input.GetJoystickAxis( 0, sf::Joy::AxisY ) < -MOVE_JOYSTICK_TOLERANCE
|| in_circle_angle( pov_angle, UP_ANGLE, POV_ANGLE_TOLERANCE )
)
{
if( position.y > FULL_SHIP_WIDTH/2 )
move.y -= 1;
}
if( input.IsKeyDown( Key::Down )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_MOVE_DOWN ) )
|| input.GetJoystickAxis( 0, sf::Joy::AxisY ) > MOVE_JOYSTICK_TOLERANCE
|| in_circle_angle( pov_angle, DOWN_ANGLE, POV_ANGLE_TOLERANCE )
)
{
if( position.y < ( SCREEN_HEIGHT - (FULL_SHIP_WIDTH/2) ) )
move.y += 1;
}
move *= PLAYER_SHIP_SPEED;
position += move;
this->position( position );
if( !is_rotating_guns() )
{
if( input.IsKeyDown( Key::Numpad7 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_ROTATE_LEFT ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_ROTATE_LEFT )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_ROTATE_AXIS ) ) > MOVE_JOYSTICK_TOLERANCE
)
{
rotate_guns( 1 );
}
if( input.IsKeyDown( Key::Numpad9 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_ROTATE_RIGHT ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_ROTATE_RIGHT )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_ROTATE_AXIS ) ) < -MOVE_JOYSTICK_TOLERANCE
)
{
rotate_guns( -1 );
}
}
// FIRE
if( input.IsKeyDown( Key::Numpad6 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_FIRE_RIGHT ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_FIRE_RIGHT )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_FIRE_AXIS_X ) ) > FIRE_JOYSTICK_TOLERANCE
)
{
fire( GunsSetup_East );
}
if( input.IsKeyDown( Key::Numpad8 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_FIRE_UP ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_FIRE_UP )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_FIRE_AXIS_Y ) ) < -FIRE_JOYSTICK_TOLERANCE
)
{
fire( GunsSetup_North );
}
if( input.IsKeyDown( Key::Numpad4 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_FIRE_LEFT ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_FIRE_LEFT )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_FIRE_AXIS_X ) ) < -FIRE_JOYSTICK_TOLERANCE
)
{
fire( GunsSetup_West );
}
if( input.IsKeyDown( Key::Numpad5 )
|| input.IsKeyDown( Key::Code( KEYBOARD_PLAYERSHIP_FIRE_DOWN ) )
|| input.IsJoystickButtonDown( 0, JOYSTICK_PLAYERSHIP_FIRE_DOWN )
|| input.GetJoystickAxis( 0, Joy::Axis( JOYSTICK_PLAYERSHIP_FIRE_AXIS_Y ) ) > FIRE_JOYSTICK_TOLERANCE
)
{
fire( GunsSetup_South );
}
}
void PlayerShip::update_guns()
{
if( is_rotating_guns() )
{
const float target_orientation = slot_direction( m_guns_setup );
const float angle_difference = target_orientation - m_guns_orientation; // FUCK
const float result_angle = std::abs( angle_difference );
if( result_angle > GUN_ROTATION_SPEED )
{
const float rotation = GUN_ROTATION_SPEED * ( ( angle_difference > 0.0f ? 1 : -1 ) * (result_angle < 180.0f ? 1 : -1) );
m_guns_orientation += rotation;
if( m_guns_orientation > 360.0f )
{
m_guns_orientation -= 360.0f;
}
else if( m_guns_orientation < 0.0f )
{
m_guns_orientation += 360.0f;
}
}
else
{
m_guns_orientation = target_orientation;
}
for( unsigned int i = 0; i < guns_count(); ++i )
{
unsigned int gid = i;
if( has_gun( gid ) )
{
GunSlot gun = get_gun( gid );
Orientation gun_dir = gun_direction( gid );
gun->direction( gun_dir );
gun->orientation( gun_dir );
}
}
}
}
void PlayerShip::do_render()
{
render_guns();
render_ship();
}
void PlayerShip::render_ship()
{
Position pos = position();
const float ship_center_x = SHIP_WIDTH/2;
const float ship_center_y = SHIP_HEIGHT/2;
sf::Vector2f top_left( -ship_center_x, -ship_center_y );
sf::Vector2f bottom_right( ship_center_x, ship_center_y );
top_left += pos;
bottom_right += pos;
sf::Shape ship_shape = sf::Shape::Rectangle( top_left, bottom_right , sf::Color( 0, 180, 30 ) );
Game::instance().display().Draw( ship_shape );
Game::instance().display().Draw( core_shape() );
}
void PlayerShip::render_guns()
{
for( unsigned int i = 0; i < guns_count(); ++i )
{
if( has_gun( i ) )
render_gun( i );
}
}
void PlayerShip::render_gun( unsigned int gun_idx )
{
GunSlot gun = get_gun( gun_idx );
const float HALF_HEIGHT = GUN_HEIGHT / 2;
sf::Shape gun_shape = sf::Shape::Rectangle( GUN_DISTANCE, -HALF_HEIGHT, GUN_DISTANCE + GUN_WIDTH, HALF_HEIGHT , gun_color( gun_idx ) );
sf::Shape cannon_shape = sf::Shape::Circle( gun->cannon(), 3.0f, sf::Color::White );
Orientation gun_dir = gun_direction( gun_idx );
gun_shape.Rotate( gun_dir );
gun_shape.Move( position() );
cannon_shape.Move( position() );
Game::instance().display().Draw( gun_shape );
Game::instance().display().Draw( cannon_shape );
}
sf::Color PlayerShip::gun_color( unsigned int gun_idx ) const
{
static const sf::Uint8 ALPHA = 255;
static const std::array< sf::Color, MAX_PLAYER_GUNS > colors =
{ sf::Color( 255, 252, 0, ALPHA )
, sf::Color( 255, 174, 0, ALPHA )
, sf::Color( 255, 12, 0, ALPHA )
, sf::Color( 255, 60, 255, ALPHA )
};
return colors[ gun_idx ];
}
rlc::Orientation PlayerShip::gun_direction( unsigned int gun_idx ) const
{
float result = m_guns_orientation + slot_direction( gun_idx );
while( result >= 360.0f )
result -= 360.0f;
return result;
}
rlc::Orientation PlayerShip::slot_direction( unsigned int gun_idx ) const
{
return GUN_ANGLE_INTERVAL * gun_idx;
}
void PlayerShip::rotate_guns( int setups )
{
int new_setup = m_guns_setup + setups;
m_guns_setup = GunsSetup( new_setup % MAX_PLAYER_GUNS );
}
bool PlayerShip::is_rotating_guns() const
{
const float target_orientation = slot_direction( m_guns_setup );
return m_guns_orientation > target_orientation
|| m_guns_orientation < target_orientation
;
}
int PlayerShip::gun_id( unsigned int slot )
{
return ( slot - int(m_guns_setup) ) % MAX_PLAYER_GUNS;
}
void PlayerShip::fire( GunsSetup dir )
{
if( is_rotating_guns() )
{
const Orientation target_dir = slot_direction( dir );
Orientation min_orientation = target_dir - GUN_FIRE_BORDER_ANGLE;
Orientation max_orientation = target_dir + GUN_FIRE_BORDER_ANGLE;
for( unsigned int gun_idx = 0; gun_idx < guns_count(); ++gun_idx )
{
GunSlot gun = get_gun( gun_idx );
const Orientation gun_dir = gun->orientation();
if( gun_dir <= max_orientation && gun_dir >= min_orientation )
{
gun->fire();
}
}
}
else
{
fire_gun( gun_id( dir ) );
}
}
} | [
"[email protected]"
]
| [
[
[
1,
444
]
]
]
|
2754732f0b33d767a3e42d01fad10ef34b80b909 | d20b68a8117dd07fce7e52e28cc5b880ada3469b | /code/base/actor.cpp | 78135349729f0fb26d8f72e1e6ea064884fb909e | []
| no_license | zhengqq/uvmoonpatrol | 326002e1dab8a85b4cb286db23c7d777b4c9a428 | 91ba9a6e9407585ff19fed7968188f13bf4157ed | refs/heads/master | 2016-09-06T04:34:43.302709 | 2009-08-21T03:50:45 | 2009-08-21T03:50:45 | 42,767,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20 | cpp | #include "actor.h"
| [
"cthulhu32@591a4e72-d347-0410-ad9e-b354b1ae3366"
]
| [
[
[
1,
1
]
]
]
|
07f22b25e0d4599262f7b34d201edaad8e0faadb | d00be105055225808a242cd6bd8411b376c4f4e1 | /src/native/windows/directshow/ds_capture_device.cpp | 4a27ad453de3d98bb15c9195aa881274786e18ef | []
| no_license | zhiji6/sip-comm-jn | bae7d463353de91a5e95bfb4ea5bb85e42c7609c | 8259cf641bd4d868481c0ef4785a5ce75aac098d | refs/heads/master | 2020-04-29T02:52:02.743960 | 2010-11-08T19:48:29 | 2010-11-08T19:48:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,511 | cpp | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
/**
* \file ds_capture_device.cpp
* \brief DirectShow capture device.
* \author Sebastien Vincent
* \date 2010
*/
#include "ds_capture_device.h"
/**
* \brief Release the format block for a media type.
* \param mt reference to release
* \note This function comes from MSDN documentation. It is declared
* here to avoid use DirectShow Base Classes and link against strmbase.lib.
*/
static void FreeMediaType(AM_MEDIA_TYPE& mt)
{
if (mt.cbFormat != 0)
{
CoTaskMemFree((PVOID)mt.pbFormat);
mt.cbFormat = 0;
mt.pbFormat = NULL;
}
if (mt.pUnk != NULL)
{
// pUnk should not be used.
mt.pUnk->Release();
mt.pUnk = NULL;
}
}
/**
* \brief Delete a media type structure that was allocated on the heap.
* \param pmt pointer to release
* \note This function comes from MSDN documentation. It is declared
* here to avoid use DirectShow Base Classes and link against strmbase.lib.
*/
static void DeleteMediaType(AM_MEDIA_TYPE *pmt)
{
if (pmt != NULL)
{
FreeMediaType(*pmt);
CoTaskMemFree(pmt);
}
}
/* implementation of ISampleGrabber */
DSGrabberCallback::DSGrabberCallback()
{
}
DSGrabberCallback::~DSGrabberCallback()
{
}
STDMETHODIMP DSGrabberCallback::SampleCB(double time, IMediaSample* sample)
{
BYTE* data = NULL;
ULONG length = 0;
if(FAILED(sample->GetPointer(&data)))
{
return E_FAIL;
}
length = sample->GetActualDataLength();
printf("Sample received: %p %u\n", data, length);
return S_OK;
}
STDMETHODIMP DSGrabberCallback::BufferCB(double time, BYTE* buffer, long len)
{
/* do nothing */
return S_OK;
}
HRESULT DSGrabberCallback::QueryInterface(const IID& iid, void** ptr)
{
if(iid == IID_ISampleGrabberCB || iid == IID_IUnknown)
{
*ptr = (void*)reinterpret_cast<ISampleGrabberCB*>(this);
return S_OK;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) DSGrabberCallback::AddRef()
{
/* fake reference counting */
return 1;
}
STDMETHODIMP_(ULONG) DSGrabberCallback::Release()
{
/* fake reference counting */
return 1;
}
DSCaptureDevice::DSCaptureDevice(const WCHAR* name)
{
if(name)
{
m_name = wcsdup(name);
}
m_callback = NULL;
m_filterGraph = NULL;
m_captureGraphBuilder = NULL;
m_graphController = NULL;
m_srcFilter = NULL;
m_sampleGrabberFilter = NULL;
m_sampleGrabber = NULL;
m_renderer = NULL;
}
DSCaptureDevice::~DSCaptureDevice()
{
/* remove all added filters from filter graph */
m_filterGraph->RemoveFilter(m_srcFilter);
m_filterGraph->RemoveFilter(m_renderer);
m_filterGraph->RemoveFilter(m_sampleGrabberFilter);
/* clean up COM stuff */
if(m_renderer)
{
m_renderer->Release();
}
if(m_sampleGrabber)
{
m_sampleGrabber->Release();
}
if(m_sampleGrabberFilter)
{
m_sampleGrabberFilter->Release();
}
if(m_srcFilter)
{
m_srcFilter->Release();
}
if(m_captureGraphBuilder)
{
m_captureGraphBuilder->Release();
}
if(m_filterGraph)
{
m_filterGraph->Release();
}
if(m_name)
{
free(m_name);
}
}
const WCHAR* DSCaptureDevice::getName() const
{
return m_name;
}
bool DSCaptureDevice::setFormat(const VideoFormat& format)
{
HRESULT ret;
IAMStreamConfig* streamConfig = NULL;
AM_MEDIA_TYPE* mediaType = NULL;
/* force to stop */
stop();
/* get the right interface to change capture settings */
ret = m_captureGraphBuilder->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
m_srcFilter, IID_IAMStreamConfig, (void**)&streamConfig);
if(!FAILED(ret))
{
VIDEOINFOHEADER* videoFormat = NULL;
size_t bitCount = 0;
/* get the current format and change resolution */
streamConfig->GetFormat(&mediaType);
videoFormat = (VIDEOINFOHEADER*)mediaType->pbFormat;
videoFormat->bmiHeader.biWidth = (LONG)format.width;
videoFormat->bmiHeader.biHeight = (LONG)format.height;
if(format.pixelFormat == MEDIASUBTYPE_ARGB32.Data1 ||
format.pixelFormat == MEDIASUBTYPE_RGB32.Data1)
{
bitCount = 32;
}
else if(format.pixelFormat == MEDIASUBTYPE_RGB24.Data1)
{
bitCount = 24;
}
else
{
bitCount = videoFormat->bmiHeader.biBitCount;
}
/* find the media type */
for(std::list<VideoFormat>::iterator it = m_formats.begin() ;
it != m_formats.end() ; ++it)
{
if(format.pixelFormat == (*it).pixelFormat)
{
mediaType->subtype = (*it).mediaType;
break;
}
}
ret = streamConfig->SetFormat(mediaType);
if(FAILED(ret))
{
fprintf(stderr, "Failed to set format\n");
fflush(stderr);
}
else
{
m_bitPerPixel = bitCount;
m_format = format;
m_format.mediaType = mediaType->subtype;
}
DeleteMediaType(mediaType);
streamConfig->Release();
}
return !FAILED(ret);
}
DSGrabberCallback* DSCaptureDevice::getCallback()
{
return m_callback;
}
void DSCaptureDevice::setCallback(DSGrabberCallback* callback)
{
m_callback = callback;
m_sampleGrabber->SetCallback(callback, 0);
}
bool DSCaptureDevice::initDevice(IMoniker* moniker)
{
HRESULT ret = 0;
if(!m_name || !moniker)
{
return false;
}
if(m_filterGraph)
{
/* already initialized */
return false;
}
/* create the filter and capture graph */
ret = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IFilterGraph2, (void**)&m_filterGraph);
if(FAILED(ret))
{
return false;
}
ret = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL,
CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2,
(void**)&m_captureGraphBuilder);
if(FAILED(ret))
{
return false;
}
m_captureGraphBuilder->SetFiltergraph(m_filterGraph);
/* get graph controller */
ret = m_filterGraph->QueryInterface(IID_IMediaControl, (void**)&m_graphController);
if(FAILED(ret))
{
return false;
}
/* add source filter to the filter graph */
WCHAR* name = wcsdup(m_name);
ret = m_filterGraph->AddSourceFilterForMoniker(moniker, NULL, name, &m_srcFilter);
free(name);
if(ret != S_OK)
{
return false;
}
ret = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter,
(void**)&m_sampleGrabberFilter);
if(ret != S_OK)
{
return false;
}
/* get sample grabber */
ret = m_sampleGrabberFilter->QueryInterface(IID_ISampleGrabber, (void**)&m_sampleGrabber);
if(ret != S_OK)
{
return false;
}
/* and sample grabber to the filter graph */
m_filterGraph->AddFilter(m_sampleGrabberFilter, L"SampleGrabberFilter");
/* set media type */
/*
AM_MEDIA_TYPE mediaType;
memset(&mediaType, 0x00, sizeof(AM_MEDIA_TYPE));
mediaType.majortype = MEDIATYPE_Video;
mediaType.subtype = MEDIASUBTYPE_RGB24;
ret = m_sampleGrabber->SetMediaType(&mediaType);
*/
/* set the callback handler */
if(ret != S_OK)
{
return false;
}
/* set renderer */
ret = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (void**)&m_renderer);
if(ret != S_OK)
{
return false;
}
/* add renderer to the filter graph */
m_filterGraph->AddFilter(m_renderer, L"NullRenderer");
/* initialize the list of formats this device supports */
initSupportedFormats();
setFormat(m_formats.front());
return true;
}
void DSCaptureDevice::initSupportedFormats()
{
HRESULT ret;
IAMStreamConfig* streamConfig = NULL;
AM_MEDIA_TYPE* mediaType = NULL;
ret = m_captureGraphBuilder->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
m_srcFilter, IID_IAMStreamConfig, (void**)&streamConfig);
/* get to find all supported formats */
if(!FAILED(ret))
{
int nb = 0;
int size = 0;
BYTE* allocBytes = NULL;
streamConfig->GetNumberOfCapabilities(&nb, &size);
allocBytes = new BYTE[size];
for(int i = 0 ; i < nb ; i++)
{
if(streamConfig->GetStreamCaps(i, &mediaType, allocBytes) == S_OK)
{
struct VideoFormat format;
VIDEOINFOHEADER* hdr = (VIDEOINFOHEADER*)mediaType->pbFormat;
if(hdr)
{
format.height = hdr->bmiHeader.biHeight;
format.width = hdr->bmiHeader.biWidth;
format.pixelFormat = mediaType->subtype.Data1;
format.mediaType = mediaType->subtype;
m_formats.push_back(format);
}
}
}
delete allocBytes;
}
}
std::list<VideoFormat> DSCaptureDevice::getSupportedFormats() const
{
return m_formats;
}
bool DSCaptureDevice::buildGraph()
{
REFERENCE_TIME start = 0;
REFERENCE_TIME stop = MAXLONGLONG;
HRESULT ret = 0;
#ifndef RENDERER_DEBUG
ret = m_captureGraphBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
m_srcFilter, m_sampleGrabberFilter,
m_renderer);
#else
ret = m_captureGraphBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
m_srcFilter, m_sampleGrabberFilter,
NULL);
#endif
if(FAILED(ret))
{
/* fprintf(stderr, "problem render stream\n"); */
return false;
}
/* start capture */
ret = m_captureGraphBuilder->ControlStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
m_srcFilter, &start, &stop, 1, 2);
/* we need this to finalize graph (maybe other filter will be added) */
//m_graphController->Run();
//this->stop();
return !FAILED(ret);
}
bool DSCaptureDevice::start()
{
if(!m_renderer || !m_sampleGrabberFilter || !m_srcFilter || !m_graphController)
{
return false;
}
m_graphController->Run();
m_renderer->Run(0);
m_sampleGrabberFilter->Run(0);
m_srcFilter->Run(0);
return true;
}
bool DSCaptureDevice::stop()
{
if(!m_renderer || !m_sampleGrabberFilter || !m_srcFilter || !m_graphController)
{
return false;
}
m_srcFilter->Stop();
m_sampleGrabberFilter->Stop();
m_renderer->Stop();
m_graphController->Stop();
return true;
}
VideoFormat DSCaptureDevice::getFormat() const
{
return m_format;
}
size_t DSCaptureDevice::getBitPerPixel()
{
return m_bitPerPixel;
}
| [
"[email protected]"
]
| [
[
[
1,
482
]
]
]
|
ef42cb2438457c159d81044ca63702beac624927 | 26706a661c23f5c2c1f97847ba09f44b7b425cf6 | /TaskManager/DlgCPUProcessor.h | 28cb7b78b7ef9bade1157f0ef12b42041fcaf0c2 | []
| no_license | 124327288/nativetaskmanager | 96a54dbe150f855422d7fd813d3631eaac76fadd | e75b3d9d27c902baddbb1bef975c746451b1b8bb | refs/heads/master | 2021-05-29T05:18:26.779900 | 2009-02-10T13:23:28 | 2009-02-10T13:23:28 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 617 | h | #pragma once
// CDlgCPUProcessor 对话框
class CDlgCPUProcessor : public CDialog
{
DECLARE_DYNAMIC(CDlgCPUProcessor)
public:
CDlgCPUProcessor(HANDLE hProcess,CWnd* pParent = NULL); // 标准构造函数
virtual ~CDlgCPUProcessor();
// 对话框数据
enum { IDD = IDD_DIALOG_CPU };
private:
HANDLE m_hProcess; // 指定进程句柄
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual BOOL OnInitDialog();
public:
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedButtonCpuOk();
afx_msg void OnBnClickedButtonCpuCancel();
};
| [
"[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
30
]
]
]
|
376248119ee8dcc7ab599cd0e5745386233f2c74 | 4d7f00745c1e8c04282cbde64066fe0684d1144e | /itsumo/src/interface/routedialogimpl.cpp | 2486c6a9d577f2b17f963bf1a21aa74a97fbf147 | []
| no_license | NiNjA-CodE/itsumo | 45b5f7ce09c52300dee3a4a58a9e02c26ef46579 | 8bf7d590b520ec0be79f80a82370ee26314238da | refs/heads/master | 2021-01-23T21:30:46.344786 | 2011-10-13T00:07:06 | 2011-10-13T00:07:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,697 | cpp | #include "routedialogimpl.h"
#include <qradiobutton.h>
#include <qcombobox.h>
#include <qgroupbox.h>
#include <qtable.h>
#include <qcanvas.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <iostream>
using std::cout;
using std::endl;
using namespace std;
RouteDialogImpl::RouteDialogImpl(int type, NetHandler* nh, RouteList rl)
: RouteDialog()
{
net_ = nh;
routes_ = rl;
type_ = type;
xRange_ = net_->xRange();
yRange_ = net_->yRange();
show_();
tableRoute->setColumnReadOnly(0, true);
tableRoute->setColumnReadOnly(1, true);
redrawNet_(comboFrom->currentText(), comboTo->currentText());
}
RouteDialogImpl::~RouteDialogImpl()
{
}
void RouteDialogImpl::show_()
{
QString aux;
NodeList list = net_->nodes();
NodeList::iterator it;
//instert nodes with TLs into comboBox from
for(it = list.begin(); it!=list.end(); it++)
{
if (it->hastl)
comboFrom->insertItem(it->name);
}
if (routes_.size() == 0)
{
radioRandom->setChecked(true);
radioClicked_(0);
}
else
{
radioDefined->setChecked(true);
radioClicked_(1);
RouteList::iterator itR;
for (itR = routes_.begin(); itR!=routes_.end(); itR++)
{
QPair<QString, QString> nds = net_->lanesetNodes(itR->laneset);
tableRoute->insertRows(tableRoute->numRows());
tableRoute->setText(tableRoute->numRows()-1, 0, nds.first);
if (type_ != 2)
{
tableRoute->setText(tableRoute->numRows()-1, 1, nds.second);
}
else
itR->laneset = net_->nodeId_(nds.first);
}
}
fromChanged_(comboFrom->currentText());
}
void RouteDialogImpl::ok_()
{
if ((radioRandom->isOn()) && (comboTo->isHidden() == false))
routes_.clear();
emit done(routes_);
accept();
}
void RouteDialogImpl::toChanged_(const QString& to)
{
redrawNet_(comboFrom->currentText(), to);
}
void RouteDialogImpl::fromChanged_(const QString& from)
{
comboTo->clear();
QValueVector<QString> next = net_->nextNodes(from);
QValueVector<QString>::iterator itD;
for(itD = next.begin(); itD!=next.end(); itD++)
{
comboTo->insertItem(*itD);
}
redrawNet_(from, comboTo->currentText());
}
void RouteDialogImpl::add_()
{
QString aux;
Route r;
if (!comboTo->currentText().isEmpty())
{
r.laneset = net_->definedLaneset(comboFrom->currentText(), comboTo->currentText());
//when selecting traffic lights without routes
if (comboTo->isHidden())
r.laneset = net_->nodeId_(comboFrom->currentText());
if (!exists_(r))
{
tableRoute->insertRows(tableRoute->numRows());
tableRoute->setText(tableRoute->numRows()-1, 0, comboFrom->currentText());
tableRoute->setText(tableRoute->numRows()-1, 1, comboTo->currentText());
routes_.push_back(r);
}
}
}
void RouteDialogImpl::remove_()
{
int row = tableRoute->currentRow();
Route r;
r.laneset = net_->definedLaneset(tableRoute->text(row, 0), tableRoute->text(row, 1));
if (type_ == 2)
r.laneset = net_->nodeId_(tableRoute->text(row, 0));
RouteList::iterator it;
bool found = false;
for (it = routes_.begin(); it!=routes_.end(); it++)
{
if (it->laneset == r.laneset)
{
found = true;
break;
}
}
if (found)
{
routes_.erase(it);
tableRoute->removeRow(row);
}
}
void RouteDialogImpl::radioClicked_(int pos)
{
// just to avoid warnings
pos = 0;
if (radioRandom->isOn())
groupBox4->setEnabled(false);
else
groupBox4->setEnabled(true);
}
bool RouteDialogImpl::exists_(const Route& r)
{
RouteList::iterator it;
for (it = routes_.begin(); it!=routes_.end(); it++)
{
if (it->laneset == r.laneset)
return true;
}
return false;
}
QPoint RouteDialogImpl::realPoint_(QPoint p)
{
QPoint ans;
ans = p;
double xFactor = (xRange_.y()-xRange_.x());
xFactor = (MAXX)/xFactor;
double yFactor = (yRange_.y()-yRange_.x());
yFactor = (MAXY)/yFactor;
ans.setX((int) ((ans.x() * xFactor) - (xRange_.x() * xFactor) + 5) );
double y = (ans.y() * yFactor) - (yRange_.x() * yFactor) - 5;
// Bruno (25jun2007): subtract from MAXY to vertically flip the map
ans.setY((int) (MAXY-y) );
return ans;
}
//needs optimization to use same canvas (memory problem)
void RouteDialogImpl::redrawNet_(const QString& from, const QString& to)
{
c_ = new QCanvas(525, 205);
cv_ = new QCanvasView( c_, frameNet );
cv_->resize(530, 210);
int actual = net_->definedLaneset(from, to);
LanesetList lanesets;
LanesetList::iterator itL;
lanesets = net_->lanesets();
for (itL=lanesets.begin(); itL!=lanesets.end(); itL++)
{
QCanvasLine *line = new QCanvasLine( c_ );
QPoint begin = realPoint_(net_->nodeLocation(itL->begin));
QPoint end = realPoint_(net_->nodeLocation(itL->end));
if ( (itL->id == actual) && (type_ == 0) )
line->setPen( QPen( Qt::green, 2 ) );
else
line->setPen( QPen( Qt::black, 1 ) );
line->setPoints( begin.x(), begin.y(), end.x(), end.y() );
line->show();
}
NodeList nodes;
NodeList::iterator it;
nodes = net_->nodes();
for (it=nodes.begin(); it!=nodes.end(); it++)
{
QPoint p = realPoint_(net_->nodeLocation(it->id));
QCanvasPolygonalItem* i;
i = new QCanvasEllipse(8,8,c_);
if (it->hastl)
i = new QCanvasRectangle(p.x(), p.y(), 8, 8, c_);
if (it->type == SOURCE)
i->setBrush( Qt::blue );
else if (it->type == SINK)
i->setBrush( Qt::red );
else
i->setBrush( Qt::black );
if ( (it->name == from) && (type_ != 1 ) )
i->setBrush( Qt::green );
i->move(p.x(), p.y());
i->show();
}
c_->update();
cv_->show();
}
| [
"[email protected]"
]
| [
[
[
1,
277
]
]
]
|
9cc3f9bb537025595c83cebd884bd3f3e8514647 | 14bc620a0365e83444dad45611381c7f6bcd052b | /ITUEngine/Math/GeometricFigures2D.hpp | dea3c6fc15710b6e71f4d868f2d418d6d22b6178 | []
| no_license | jumoel/itu-gameengine | a5750bfdf391ae64407217bfc1df8b2a3db551c7 | 062dd47bc1be0f39a0add8615e81361bcaa2bd4c | refs/heads/master | 2020-05-03T20:39:31.307460 | 2011-12-19T10:54:10 | 2011-12-19T10:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,155 | hpp | #ifndef ITUENGINE_GEOMETRICFIGURES2D_H
#define ITUENGINE_GEOMETRICFIGURES2D_H
#include <Math/Vector2f.hpp>
#include <cmath>
struct Point
{
public:
//Do not use this, to initialize use other constructors
Point() {}
Point(Point &point) : X(point.X), Y(point.Y) {}
Point(Vector2f vect) : X(vect.x()), Y(vect.y()) {}
Point(float x, float y) : X(x), Y(y) {}
Point operator -(Point *point)
{
return Point((this->X-point->X), (this->Y-point->Y));
}
bool operator ==(Point *point)
{
float epsilon = 0.0001f;
float diffX = this->X - point->X;
float diffY = this->Y - point->Y;
if((-epsilon > diffX) || (diffX > epsilon))
{
return false;
}
if((-epsilon > diffY) || (diffY > epsilon))
{
return false;
}
return true;
}
Point GetNormalizedPoint()
{
float length = GetLength();
return Point(X/length, Y/length);
}
float GetLength()
{
return sqrt(X*X + Y*Y);
}
Point GetNegatedPoint()
{
return Point(-1*X, -1*Y);
}
float X, Y;
};
struct Line
{
public:
//Do not use this, to initialize use other constructors
Line() {}
Line(Point a, Point b) : A(a), B(b) {}
Line(Line &line) : A(line.A), B(line.B) {}
~Line() { }
Point A, B;
};
struct Circle
{
public:
//Do not use this, to initialize use other constructors
Circle() {}
Circle(Point center, float radius) : Center(center), Radius(radius), initialRadius(radius) {}
Circle(Circle &circle) : Center(circle.Center), Radius(circle.Radius), initialRadius(circle.Radius) {}
~Circle() { }
void setPos(float x, float y)
{
Center.X = x;
Center.Y = y;
}
void scale(float x, float y)
{
float temp = x;
if(temp < y)
{
temp = y;
}
Radius = initialRadius * temp;
}
Point Center;
float Radius;
float initialRadius;
};
struct Rectangle
{
public:
//Do not use this, to initialize use other constructors
Rectangle() {}
Rectangle(Point minXY, float width, float height) : MinXY(minXY), Width(width), Height(height), initialWidth(width), initialHeight(height)
{
Init();
}
Rectangle(Rectangle &rectangle) : MinXY(rectangle.MinXY), Width(rectangle.Width), Height(rectangle.Height), initialWidth(rectangle.Width), initialHeight(rectangle.Height)
{
Init();
}
~Rectangle() { }
void setPos(float x, float y)
{
MinXY.X = x - Width/2.0f;
MinXY.Y = y - Height/2.0f;
MinX = MinXY.X;
MaxX = MinXY.X + Width;
MinY = MinXY.Y;
MaxY = MinXY.Y + Height;
}
void scale(float x, float y)
{
Point temp;
temp.X = MinXY.X + Width/2.0f;
temp.Y = MinXY.Y + Height/2.0f;
Height = initialHeight * y;
Width = initialWidth * x;
MinXY.X = temp.X - Width/2.0f;
MinXY.Y = temp.Y - Height/2.0f;
MinX = MinXY.X;
MaxX = MinXY.X + Width;
MinY = MinXY.Y;
MaxY = MinXY.Y + Height;
}
Point MinXY;
float Width, Height, MinY, MaxY, MinX, MaxX, initialWidth, initialHeight;
private:
void Init()
{
MinX = MinXY.X;
MaxX = MinXY.X + Width;
MinY = MinXY.Y;
MaxY = MinXY.Y + Height;
}
};
#endif //ITUENGINE_GEOMETRICFIGURES2D_H | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
22
],
[
24,
78
],
[
80,
81
],
[
84,
85
],
[
98,
99
],
[
101,
113
],
[
115,
120
],
[
123,
126
],
[
128,
129
],
[
135,
136
],
[
140,
143
],
[
145,
146
],
[
149,
149
],
[
151,
163
]
],
[
[
23,
23
],
[
79,
79
],
[
82,
83
],
[
86,
97
],
[
100,
100
],
[
114,
114
],
[
121,
122
],
[
127,
127
],
[
130,
134
],
[
137,
139
],
[
144,
144
],
[
147,
148
],
[
150,
150
]
]
]
|
862af6cc0dda9a4aa7cf1abb58ba80677f3e52fe | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Game/IA/include/StateMachine.h | 710f8f9fcb8287e7aa78c318af65bcf85ef52f73 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | #pragma once
// en akesta classe a fer els new dels estats
class CStateMachine
{
public:
CStateMachine(void);
~CStateMachine(void);
};
| [
"edual1985@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
10
]
]
]
|
3f956d0142af7b126e0fa14c375df94a4fc4bd40 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2136/2136.cpp | 7bf22e583c7c9958e71e00a827639b564e0a3052 | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | #include "stdio.h"
#include "iostream"
#include "string.h"
#include "math.h"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "queue"
#include "list"
#include "stack"
using namespace std;
int main()
{
char a[4][100];
int i,j;
int cnt[26]={0};
for(i=0;i<4;i++){
cin.getline(a[i],100,'\n');
j=0;
while(a[i][j]){
if(a[i][j]<='Z' && a[i][j]>='A')
cnt[a[i][j]-'A']++;
j++;
}
}
int maxi=0;
for(i=0;i<26;i++)
if(cnt[i]>maxi) maxi=cnt[i];
while(maxi){
for(i=0;i<26;i++)
if(cnt[i]>=maxi) cout<<"* ";
else cout<<" ";
cout<<endl;
maxi--;
}
for(i=0;i<26;i++)
cout<<(char)(i+'A')<<' ';
cout<<endl;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
44
]
]
]
|
ccbe9a0dfa0f9d236ee37371d9c1a6a49b5e3de5 | 990e19b7ae3d9bd694ebeae175c50be589abc815 | /src/cwapp/story.cpp | 4c7e661178aa66211c650c03f83b6d4fd4f2a97d | []
| no_license | shadoof/CW2 | 566b43cc2bdea2c86bd1ccd1e7b7e7cd85b8f4f5 | a3986cb28270a702402c197cdb16373bf74b9d03 | refs/heads/master | 2020-05-16T23:39:56.007788 | 2011-12-08T06:10:22 | 2011-12-08T06:10:22 | 2,389,647 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,988 | cpp | #include "main.h"
//===========================================
//Story
//===========================================
StoryRef Story::the_story;
/*SoundClientOpenAL *Story::_defaultClient;*/
//===========================================
void Story::init(const string& file)
{
filename = file;
// Make sure all slashes are forward slashes
for (string::iterator it = filename.begin(); it != filename.end(); it++)
{
if (*it == '\\')
{
*it = '/';
}
}
parser = new Parser();
parser->init(filename);
init(parser->get_root());
delete parser;
}
//===========================================
void Story::init(const TiXmlElement* root)
{
if (!root) {
return;
}
init_global_settings(parser->get_element(root, "Global"));
Array<const TiXmlNode*> nodes;
const TiXmlElement *new_root = NULL;
new_root = parser->get_element(root, "PlacementRoot");
parser->get_elements(nodes, new_root, "Placement");
for (int i = 0; i < nodes.size(); i++) {
PlaceRef obj;
obj = new Placement();
obj->init((TiXmlElement*)nodes[i]);
placements.append(obj);
}
new_root = parser->get_element(root, "SoundRoot");
parser->get_elements(nodes, new_root, "Sound");
for (int i = 0; i < nodes.size(); i++) {
SoundRef obj;
obj = new SoundObject();
obj->init((TiXmlElement*)nodes[i]);
sounds.append(obj);
}
Array<const TiXmlNode*> particle_nodes;
new_root = parser->get_element(root, "ParticleActionRoot");
parser->get_elements(particle_nodes, new_root, "ParticleActionList");
ParticleActions::create_lists(particle_nodes.length());
for (int i = 0; i < particle_nodes.length(); i++) {
ParticleActionsRef obj;
obj = new ParticleActions();
obj->init((const TiXmlElement*)particle_nodes[i]);
particle_actions.append(obj);
}
//ParticleSystem::create_systems(0);
Array<const TiXmlNode*> obj_nodes;
new_root = parser->get_element(root, "ObjectRoot");
parser->get_elements(obj_nodes, new_root, "Object");
for (int i = 0; i < obj_nodes.size(); i++) {
ContentRef obj;
obj = get_new_content((const TiXmlElement*)obj_nodes[i]);
objects.append(obj);
if (obj->get_light()) {
lights.append(obj->get_light());
}
}
new_root = parser->get_element(root, "GroupRoot");
parser->get_elements(nodes, new_root, "Group");
for (int i = 0; i < nodes.size(); i++) {
GroupRef obj;
obj = new Group();
obj->init((const TiXmlElement*)nodes[i]);
groups.append(obj);
}
for (int i = 0; i < groups.size(); i++) {
groups[i]->resolve_group_refs((const TiXmlElement*)nodes[i]);
}
Array<const TiXmlNode*> time_nodes;
new_root = parser->get_element(root, "TimelineRoot");
parser->get_elements(time_nodes, new_root, "Timeline");
for (int i = 0; i < time_nodes.size(); i++) {
TimelineRef obj;
obj = new Timeline();
obj->init((const TiXmlElement*)time_nodes[i]);
timelines.append(obj);
}
Array<const TiXmlNode*> event_nodes;
new_root = parser->get_element(root, "EventRoot");
parser->get_elements(event_nodes, new_root);
for (int i = 0; i < event_nodes.size(); i++) {
EventTriggerRef obj;
obj = EventTrigger::create_new((const TiXmlElement*)event_nodes[i]);
obj->init((const TiXmlElement*)event_nodes[i]);
events.append(obj);
}
//Second Pass Init
//Objects
for (int i = 0; i < obj_nodes.size(); i++) {
objects[i]->init_actions((TiXmlElement*)obj_nodes[i]);
}
//Timelines
for (int i = 0; i < time_nodes.size(); i++) {
timelines[i]->init_actions((TiXmlElement*)time_nodes[i]);
}
//Events
for (int i = 0; i < event_nodes.size(); i++) {
events[i]->init_actions((TiXmlElement*)event_nodes[i]);
}
// Preload sound files
//bool success = SOUNDCLIENT->preload();
//debugAssertM(success, "Sounds Failed to Load");
// Reset the listener position
//SOUNDCLIENT->setListenerLoc(CoordinateFrame());
SOUNDCLIENT->load_all();
SOUNDCLIENT->set_listener(the_app.get_cam_frame(), Vector3::zero());
}
//===========================================
void Story::init_global_settings(const TiXmlElement* root)
{
if (!root) {
return;
}
string elem_name;
if (!the_app.is_caved_in()) {
elem_name = "CameraPos";
} else {
elem_name = "CaveCameraPos";
}
const TiXmlElement* cam_elem = parser->get_element(root, elem_name);
Placement cam_place;
if (cam_elem) {
cam_place.init(cam_elem->FirstChildElement("Placement"));
CoordinateFrame frame = cam_place.get_world_frame();
the_app.set_cam_frame(frame);
double far_clip = 0;
assign(far_clip, cam_elem->Attribute("far-clip"));
the_app.update_far_clip(far_clip);
} else {
the_app.set_cam_frame(CoordinateFrame());
}
const TiXmlElement* elem = parser->get_element(root, "Background");
if (elem) {
Color3 back_color;
assign(back_color, elem->Attribute("color"));
the_app.set_background_color(back_color);
}
elem = parser->get_element(root, "WandNavigation");
if (elem) {
assign(allow_movement, elem->Attribute("allow-movement"));
assign(allow_rotation, elem->Attribute("allow-rotation"));
}
}
//===========================================
ContentRef Story::get_new_content(const TiXmlElement* obj_node)
{
ContentRef content;
const TiXmlElement* content_elem = parser->get_element(obj_node, "Content");
if (!content_elem) {
return content;
}
const TiXmlElement* child = parser->get_first_element(content_elem);
if (!child) {
return content;
}
string content_type = child->ValueStr();
if (content_type == "Text") {
content = new TextContent();
} else if (content_type == "Image") {
content = new ImageContent();
} else if (content_type == "StereoImage") {
content = new ImageContent();
} else if (content_type == "Model") {
content = new ModelContent();
} else if (content_type == "None") {
content = new TextContent();
} else if (content_type == "Light") {
content = new LightContent();
} else if (content_type == "ParticleSystem") {
content = new ParticleSystem();
} else if (content_type == "Shader") {
content = new ShaderContent();
}
// } else if(content_type == "Sound") {
// content = new SoundContent();
// }
if (content.isNull()) {
msgBox("Content of Type \"" + content_type + "\" Not Supported");
} else {
content->init(obj_node, content_type);
}
return content;
}
//===========================================
void Story::do_collision_move(const Vector3& test_pos, Vector3& change_pos, const Vector3& dir)
{
if (!do_coll_test) {
change_pos += dir;
return;
}
Vector3 pos = test_pos;
Vector3 min_diff = dir;
float mag;
for (int i = 0; i < objects.length(); i++) {
if (objects[i]->get_content() == "Model") {
ModelContent *model = (ModelContent*)objects[i].pointer();
if (model->do_collision(pos, mag, dir)) {
Vector3 diff = pos - test_pos;
if (diff.length() < min_diff.length()) {
min_diff = diff;
}
}
}
}
change_pos += min_diff;
}
//===========================================
void Story::compute_total_bbox()
{
AABox box = objects[0]->get_bbox();
total_bbox.set(total_bbox.low().min(box.low()), total_bbox.high().max(box.high()));
for (int i = 0; i < objects.length(); i++) {
box = objects[i]->get_bbox();
total_bbox.set(total_bbox.low().min(box.low()), total_bbox.high().max(box.high()));
}
}
//===========================================
void Story::do_lighting(RenderDevice *rd)
{
if (!lights.size()) {
GLight light = GLight::point(Vector3(0, 0, 4), Color3::white());
rd->setLight(0, light);
}
int counter = 0;
for (int i = 0; i < lights.size(); i++) {
if (lights[i]->set_light(rd, counter)) {
counter++;
if (counter >= RenderDevice::MAX_LIGHTS) {
break;
}
}
}
}
//===========================================
void Story::render(RenderDevice *rd)
{
for (int i = 0; i < objects.size(); i++) {
objects[i]->render(rd);
}
if (draw_events) {
for (int i = 0; i < events.size(); i++) {
events[i]->render(rd);
}
}
}
//===========================================
void Story::select_new_obj_at_pointer(const Vector3& position, const Vector3& direction)
{
Ray ray = Ray::fromOriginAndDirection(position, direction);
float min_dist = G3D::inf();
float max_dist = G3D::inf();
if (selected_obj.notNull()) {
selected_obj->select(false);
selected_obj = ContentRef();
}
for (int i = 0; i < objects.size(); i++) {
float curr_t = ray.intersectionTime(objects[i]->get_bbox());
if (!isFinite(curr_t) || (curr_t < 0)) {
continue;
}
if (objects[i]->is_click_stop() && (curr_t <= min_dist) && (objects[i]->get_alpha() > .75)) {
min_dist = curr_t;
selected_obj = objects[i];
}
}
if (selected_obj.notNull() && selected_obj->is_active_link()) {
selected_obj->select(true);
}
}
//===========================================
void Story::check_selected_at_pointer(const Vector3& position, const Vector3& direction)
{
if (selected_obj.isNull()) {
return;
}
Ray ray = Ray::fromOriginAndDirection(position, direction);
float curr_t = ray.intersectionTime(selected_obj->get_bbox());
if (isFinite(curr_t) && (curr_t > 0)) {
selected_obj->select(true);
} else {
selected_obj->select(false);
}
}
//===========================================
void Story::activate_selected()
{
if (selected_obj.isNull()) {
return;
}
if (selected_obj->is_selected()) {
selected_obj->activate();
selected_obj->select(false);
}
selected_obj = ContentRef();
}
//===========================================
PlaceRef Story::get_place(const string& name)
{
for (int i = 0; i < placements.size(); i++) {
if (placements[i]->get_name() == name) {
return placements[i];
}
}
return PlaceRef();
}
//===========================================
SoundRef Story::get_sound(const string& name)
{
for (int i = 0; i < sounds.size(); i++) {
if (sounds[i]->get_name() == name) {
return sounds[i];
}
}
return SoundRef();
}
//===========================================
EventTriggerRef Story::get_event(const string& name)
{
for (int i = 0; i < events.size(); i++) {
if (events[i]->get_name() == name) {
return events[i];
}
}
return EventTriggerRef();
}
//===========================================
ParticleActionsRef Story::get_particle_actions(const string& name)
{
for (int i = 0; i < particle_actions.size(); i++) {
if (particle_actions[i]->get_name() == name) {
return particle_actions[i];
}
}
return ParticleActionsRef();
}
//===========================================
GroupRef Story::get_group(const string& name)
{
for (int i = 0; i < groups.size(); i++) {
if (groups[i]->get_name() == name) {
return groups[i];
}
}
return GroupRef();
}
//===========================================
TimelineRef Story::get_timeline(const string& name)
{
for (int i = 0; i < timelines.size(); i++) {
if (timelines[i]->get_name() == name) {
return timelines[i];
}
}
return TimelineRef();
}
//===========================================
void Story::add_action(const ActionInstRef& action)
{
action_insts.append(action);
}
//===========================================
void Story::process_actions()
{
for (int i = 0; i < action_insts.size(); i++) {
if (action_insts[i].notNull()) {
if (action_insts[i]->process()) {
action_insts[i] = ActionInstRef();
}
}
}
}
//===========================================
void Story::process_timelines()
{
for (int i = 0; i < timelines.size(); i++) {
timelines[i]->process();
}
}
//===========================================
void Story::process_events()
{
for (int i = 0; i < events.size(); i++) {
events[i]->process();
}
}
//===========================================
string Story::resolve_rel_path(const string& name)
{
string full;
if (beginsWith(name, "file:")) {
full = name.substr(5);
} else if (name[0] == '.') {
string path_name = the_story->filename;
// Path has been normalized to contain only forward /
size_t index = path_name.rfind('/');
if (index != string::npos) {
full = path_name.substr(0, index);
full += "/";
}
full += name;
} else {
full = name;
}
return full;
}
| [
"[email protected]"
]
| [
[
[
1,
513
]
]
]
|
75f9743c7e3f77eb7668327ddf5a7902fd761a4b | c5f209b0f9406b4be9d432959d4f01d4bbc0d1ab | /socket.cpp | a494367b6e32f78450c8b41ea0ff375ab7a82a0d | []
| no_license | bennyadr/themessenger | d9580d983e02382d915925a526dbb11b1c158748 | 4097aaea5f30eef08da5beaf7ef95b4caa23e636 | refs/heads/master | 2020-08-07T06:08:47.879815 | 2008-11-24T21:04:46 | 2008-11-24T21:04:46 | 38,587,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,178 | cpp | #include "socket.h"
#include "bits.h"
#include <assert.h>
/*****************************************/
/*****************************************/
/*****************************************/
/* Unix based socket */
/*****************************************/
/*****************************************/
/*****************************************/
#ifndef WINDOWS
/*****************************************/
c_Socket::c_Socket()
:m_iPort(PORT),
m_iSocketFd(-1)
{
m_sAddress = string(SERVER_ADDRESS);
memset( &m_tAddress , 0 , sizeof(m_tAddress) );
m_bStatus = false;
};
/*****************************************/
c_Socket::~c_Socket()
{
if(is_Opened())
{
close(m_iSocketFd);
}
};
/*****************************************/
void c_Socket::Connect()
{
m_iSocketFd=socket(AF_INET,SOCK_STREAM,0);
if(m_iSocketFd==-1)
throw c_Error_Socket(m_iSocketFd , "error creating socket : ");
m_tAddress.sin_family = AF_INET;
m_tAddress.sin_addr.s_addr = INADDR_ANY;
m_tAddress.sin_port = htons ( m_iPort );
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
int retsockopt = setsockopt(m_iSocketFd,SOL_SOCKET,SO_RCVTIMEO,(char*)&tv,sizeof(tv));
if(retsockopt < 0)
throw c_Error_Socket(retsockopt,"error setting socket timeout : ");
int status = inet_pton ( AF_INET, m_sAddress.c_str(), &m_tAddress.sin_addr );
if(status<0)
throw c_Error_Socket(status , "error creating network address structure : ");
if(status<1)
throw c_Error_Socket(status , "error creating network address structure : invalid address ");
status = connect ( m_iSocketFd , (sockaddr *) &m_tAddress, sizeof(m_tAddress) );
if(status==-1)
throw c_Error_Socket(status, "error connecting socket : ");
m_bStatus = true;
};
/*****************************************/
void c_Socket::Disconnect()const
{
if(is_Opened())
{
int close_ret = close(m_iSocketFd);
if(close_ret == -1)
throw c_Error_Socket(close_ret, "error closing socket : ");
}
m_bStatus = false;
};
/*****************************************/
void c_Socket::MakeBlocking()
{
int O_BLOCK = ~ O_NONBLOCK;
int ret = fcntl(m_iSocketFd,F_SETFL,O_BLOCK);
if(ret == -1)
throw c_Error_Socket(ret,"error makeing socket blocking : ");
};
/*****************************************/
void c_Socket::MakeNonBlocking()
{
int ret = fcntl(m_iSocketFd,F_SETFL,O_NONBLOCK);
if(ret == -1)
throw c_Error_Socket(ret,"error makeing socket non-blocking : ");
};
/*****************************************/
void c_Socket::Write(const c_Message& data)const
{
int ret_write = write(m_iSocketFd,data.GetBuffer(),data.GetSize());
if(ret_write==-1)
throw c_Error_Socket(ret_write,"error sending data : ");
};
/*****************************************/
void c_Socket::Write(const c_YPacket& data)const
{
if(!data.isSerialized())
{
data.Serialize();
}
int ret_write = write(m_iSocketFd,data.GetBuffer(),data.GetSize());
if(ret_write==-1)
throw c_Error_Socket(ret_write,"error sending data : ");
};
/*****************************************/
void c_Socket::Send(const c_Message& data,const int flag)
{
int ret_write = send(m_iSocketFd,data.GetBuffer(),data.GetSize(),flag);
if(ret_write==-1)
throw c_Error_Socket(ret_write,"error sending data : ");
};
/*****************************************/
void c_Socket::Read(c_Message& data,const unsigned int count)
{
char buffer[count];
int ret_read=read(m_iSocketFd,buffer,count);
if (ret_read==-1)
throw c_Error_Socket(ret_read,"error reading data");
data.SetBuffer(reinterpret_cast<unsigned char*>(buffer),ret_read);
};
/*****************************************/
void c_Socket::Recv(c_Message &data,const unsigned int count,const int flag)
{
char buffer[count];
int ret_recv = recv(m_iSocketFd,buffer,count,flag);
if(ret_recv==-1)
throw c_Error_Socket(ret_recv, "error receiving data");
data.SetBuffer(reinterpret_cast<unsigned char*>(buffer),ret_recv);
};
/*****************************************/
void c_Socket::Recv(c_YPacket& packet,const int flag)
{
unsigned char buffer[20];
int ret_recv = recv(m_iSocketFd,buffer,20,flag);
if(ret_recv<=0)
throw c_Error_Socket(ret_recv,"error receiving data");
unsigned short size = GetYPackSize(buffer);
char buffer_1[size+20];
memcpy(buffer_1,buffer,20);
ret_recv = recv(m_iSocketFd,(buffer_1+20),size,flag);
if(ret_recv<=0)
throw c_Error_Socket(ret_recv,"error receiving data");
packet.Deserialize(reinterpret_cast<unsigned char*>(buffer_1));
}
/*****************************************/
void c_Socket::Read(c_YPacket& packet)
{
unsigned char buffer[20];
int ret_read = read(m_iSocketFd,buffer,20);
if(ret_read<=0)
throw c_Error_Socket(ret_read,"error receiving data");
if(0 != strncmp(reinterpret_cast<const char*>(buffer),"YMSG",4))
{
throw c_Error_Socket(1,"wrong yahoo packet");
}
unsigned short size = GetYPackSize(buffer);
char buffer_1[size+YAHOO_HEADER_SIZE];
memcpy(buffer_1,buffer,YAHOO_HEADER_SIZE);
int offset = YAHOO_HEADER_SIZE;
while(size>0)
{
ret_read = read(m_iSocketFd,(buffer_1+offset),size);
if(ret_read<0)
throw c_Error_Socket(ret_read,"error receiving data");
size -= ret_read;
offset += ret_read;
}
assert(size==0);
packet.Deserialize(reinterpret_cast<unsigned char*>(buffer_1));
};
/*****************************************/
bool c_Socket::ReadNonBlocking(c_YPacket& packet)
{
unsigned char buffer[20];
int ret_read = read(m_iSocketFd,buffer,20);
if(ret_read < 0)
{
if(errno == EWOULDBLOCK)
return false;
else
throw c_Error_Socket(ret_read,"error reading from non-blocking socket : ");
};
if(0 != strncmp(reinterpret_cast<const char*>(buffer),"YMSG",4))
{
//throw c_Error_Socket(1,"wrong yahoo packet");
return false;
}
unsigned short size = GetYPackSize(buffer);
char buffer_1[size+YAHOO_HEADER_SIZE];
memcpy(buffer_1,buffer,YAHOO_HEADER_SIZE);
int offset = YAHOO_HEADER_SIZE;
while(size>0)
{
ret_read = read(m_iSocketFd,(buffer_1+offset),size);
if(ret_read<0)
throw c_Error_Socket(ret_read,"error receiving data");
size -= ret_read;
offset += ret_read;
}
assert(size==0);
packet.Deserialize(reinterpret_cast<unsigned char*>(buffer_1));
return true;
};
#endif
/*****************************************/
/*****************************************/
/*****************************************/
/* Windows based socket */
/*****************************************/
/*****************************************/
/*****************************************/
#ifdef WINDOWS
/*****************************************/
c_Socket::c_Socket()
:m_iPort(PORT),
m_iSocketFd(-1)
{
m_sAddress = string(SERVER_ADDRESS);
memset( &m_tAddress , 0 , sizeof(m_tAddress) );
m_bStatus = false;
//initialize socket
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
int err = WSAStartup(wVersionRequested, &wsaData);
if(err != 0)
throw c_Error_Socket(1 , "error requesting socket version ");
};
/*****************************************/
c_Socket::~c_Socket()
{
WSACleanup();
};
/*****************************************/
void c_Socket::Connect()
{
m_iSocketFd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_iSocketFd == INVALID_SOCKET)
throw c_Error_Socket(m_iSocketFd , "error creating socket : ");
m_tAddress.sin_family = AF_INET;
m_tAddress.sin_addr.s_addr = INADDR_ANY;
m_tAddress.sin_port = htons ( m_iPort );
//m_tAddress.sin_addr.S_un.S_addr = inet_addr(m_sAddress.c_str());
m_tAddress.sin_addr.s_addr = inet_addr(m_sAddress.c_str());
int status = connect ( m_iSocketFd , (sockaddr *) &m_tAddress, sizeof(m_tAddress) );
if(status == SOCKET_ERROR)
throw c_Error_Socket(status, "error connecting socket : ");
m_bStatus = true;
};
/*****************************************/
void c_Socket::Disconnect()const
{
if(is_Opened())
{
int close_ret = closesocket(m_iSocketFd);
if(close_ret == SOCKET_ERROR)
throw c_Error_Socket(close_ret, "error closing socket : ");
}
m_bStatus = false;
};
/*****************************************/
void c_Socket::MakeBlocking()
{
u_long iMode = 0;
int ret = ioctlsocket(m_iSocketFd,FIONBIO,&iMode);
if(ret == SOCKET_ERROR)
throw c_Error_Socket(ret,"error makeing socket blocking : ");
};
/*****************************************/
void c_Socket::MakeNonBlocking()
{
u_long iMode = 1;
int ret = ioctlsocket(m_iSocketFd,FIONBIO,&iMode);
if(ret == SOCKET_ERROR)
throw c_Error_Socket(ret,"error makeing socket non-blocking : ");
};
/*****************************************/
void c_Socket::Write(const c_YPacket& data)const
{
if(!data.isSerialized())
{
data.Serialize();
}
int ret_write = send(m_iSocketFd,reinterpret_cast<char*>(data.GetBuffer()),data.GetSize(),0);
if(ret_write == SOCKET_ERROR)
throw c_Error_Socket(ret_write,"error sending data : ");
};
/*****************************************/
void c_Socket::Read(c_YPacket& packet)
{
unsigned char buffer[20];
int ret_read = recv(m_iSocketFd,reinterpret_cast<char*>(buffer),20,0);
if(ret_read <= 0)
throw c_Error_Socket(ret_read,"error receiving data");
if(0 != strncmp(reinterpret_cast<const char*>(buffer),"YMSG",4))
{
throw c_Error_Socket(1,"wrong yahoo packet");
}
unsigned short size = GetYPackSize(buffer);
char buffer_1[size+YAHOO_HEADER_SIZE];
memcpy(buffer_1,buffer,YAHOO_HEADER_SIZE);
int offset = YAHOO_HEADER_SIZE;
while(size>0)
{
ret_read = recv(m_iSocketFd,reinterpret_cast<char*>(buffer_1+offset),size,0);
if(ret_read <= 0)
throw c_Error_Socket(ret_read,"error receiving data");
size -= ret_read;
offset += ret_read;
}
assert(size==0);
packet.Deserialize(reinterpret_cast<unsigned char*>(buffer_1));
};
/*****************************************/
bool c_Socket::ReadNonBlocking(c_YPacket& packet)
{
unsigned char buffer[20];
int ret_read = recv(m_iSocketFd,reinterpret_cast<char*>(buffer),20,0);
if(ret_read <= 0)
{
if(WSAGetLastError() == WSAEWOULDBLOCK)
return false;
else
throw c_Error_Socket(ret_read,"error reading from non-blocking socket : ");
};
if(0 != strncmp(reinterpret_cast<const char*>(buffer),"YMSG",4))
{
throw c_Error_Socket(1,"wrong yahoo packet");
}
unsigned short size = GetYPackSize(buffer);
char buffer_1[size+YAHOO_HEADER_SIZE];
memcpy(buffer_1,buffer,YAHOO_HEADER_SIZE);
int offset = YAHOO_HEADER_SIZE;
while(size>0)
{
ret_read = recv(m_iSocketFd,reinterpret_cast<char*>(buffer_1+offset),size,0);
if(ret_read <= 0)
{
if(WSAGetLastError() == WSAEWOULDBLOCK)
return false;
else
throw c_Error_Socket(ret_read,"error reading from non-blocking socket : ");
};
size -= ret_read;
offset += ret_read;
}
assert(size==0);
packet.Deserialize(reinterpret_cast<unsigned char*>(buffer_1));
return true;
};
#endif
| [
"biotech86@3b6a47cb-6844-0410-8745-ed9a1b79f187"
]
| [
[
[
1,
416
]
]
]
|
522c674e4e5ba1ad90b2d6af8397ed0019552292 | b4f709ac9299fe7a1d3fa538eb0714ba4461c027 | /trunk/powertabfileheader.cpp | f2fc6f9f49831742590d6738b1b249c5d30692b6 | []
| no_license | BackupTheBerlios/ptparser-svn | d953f916eba2ae398cc124e6e83f42e5bc4558f0 | a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c | refs/heads/master | 2020-05-27T12:26:21.811820 | 2005-11-06T14:23:18 | 2005-11-06T14:23:18 | 40,801,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,287 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: powertabfileheader.cpp
// Purpose: Stores all of the information found in the header of a Power Tab file
// Author: Brad Larsen
// Modified by:
// Created: Dec 4, 2004
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#include "stdwx.h"
#include "powertabfileheader.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Constants (see .h for details)
const wxUint32 PowerTabFileHeader::POWERTABFILE_MARKER = 0x62617470;
const wxWord PowerTabFileHeader::NUM_FILEVERSIONS = 4;
const wxWord PowerTabFileHeader::FILEVERSION_1_0 = 1;
const wxWord PowerTabFileHeader::FILEVERSION_1_0_2 = 2;
const wxWord PowerTabFileHeader::FILEVERSION_1_5 = 3;
const wxWord PowerTabFileHeader::FILEVERSION_1_7 = 4;
const wxWord PowerTabFileHeader::FILEVERSION_CURRENT = FILEVERSION_1_7;
const wxByte PowerTabFileHeader::NUM_FILETYPES = 2;
const wxByte PowerTabFileHeader::FILETYPE_SONG = 0;
const wxByte PowerTabFileHeader::FILETYPE_LESSON = 1;
const wxByte PowerTabFileHeader::CONTENTTYPE_NONE = 0;
const wxByte PowerTabFileHeader::CONTENTTYPE_GUITAR = 0x01;
const wxByte PowerTabFileHeader::CONTENTTYPE_BASS = 0x02;
const wxByte PowerTabFileHeader::CONTENTTYPE_PERCUSSION = 0x04;
const wxByte PowerTabFileHeader::CONTENTTYPE_ALL = (CONTENTTYPE_GUITAR | CONTENTTYPE_BASS | CONTENTTYPE_PERCUSSION);
const wxByte PowerTabFileHeader::NUM_RELEASETYPES = 4;
const wxByte PowerTabFileHeader::RELEASETYPE_PUBLIC_AUDIO = 0;
const wxByte PowerTabFileHeader::RELEASETYPE_PUBLIC_VIDEO = 1;
const wxByte PowerTabFileHeader::RELEASETYPE_BOOTLEG = 2;
const wxByte PowerTabFileHeader::RELEASETYPE_NOTRELEASED = 3;
const wxByte PowerTabFileHeader::NUM_AUDIORELEASETYPES = 6;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_SINGLE = 0;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_EP = 1;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_ALBUM = 2;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_DOUBLEALBUM = 3;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_TRIPLEALBUM = 4;
const wxByte PowerTabFileHeader::AUDIORELEASETYPE_BOXSET = 5;
const wxByte PowerTabFileHeader::NUM_AUTHORTYPES = 2;
const wxByte PowerTabFileHeader::AUTHORTYPE_AUTHORKNOWN = 0;
const wxByte PowerTabFileHeader::AUTHORTYPE_TRADITIONAL = 1;
const wxWord PowerTabFileHeader::NUM_MUSICSTYLES = 19;
const wxWord PowerTabFileHeader::MUSICSTYLE_ALTERNATIVE = 0;
const wxWord PowerTabFileHeader::MUSICSTYLE_BLUEGRASS = 1;
const wxWord PowerTabFileHeader::MUSICSTYLE_BLUES = 2;
const wxWord PowerTabFileHeader::MUSICSTYLE_COUNTRY = 3;
const wxWord PowerTabFileHeader::MUSICSTYLE_FINGERPICK = 4;
const wxWord PowerTabFileHeader::MUSICSTYLE_FLAMENCO = 5;
const wxWord PowerTabFileHeader::MUSICSTYLE_FOLK = 6;
const wxWord PowerTabFileHeader::MUSICSTYLE_FUNK = 7;
const wxWord PowerTabFileHeader::MUSICSTYLE_FUSION = 8;
const wxWord PowerTabFileHeader::MUSICSTYLE_GENERAL = 9;
const wxWord PowerTabFileHeader::MUSICSTYLE_JAZZ = 10;
const wxWord PowerTabFileHeader::MUSICSTYLE_METAL = 11;
const wxWord PowerTabFileHeader::MUSICSTYLE_OTHER = 12;
const wxWord PowerTabFileHeader::MUSICSTYLE_POP = 13;
const wxWord PowerTabFileHeader::MUSICSTYLE_PROGRESSIVE = 14;
const wxWord PowerTabFileHeader::MUSICSTYLE_PUNK = 15;
const wxWord PowerTabFileHeader::MUSICSTYLE_REGGAE = 16;
const wxWord PowerTabFileHeader::MUSICSTYLE_ROCK = 17;
const wxWord PowerTabFileHeader::MUSICSTYLE_SWING = 18;
const wxByte PowerTabFileHeader::NUM_LESSONLEVELS = 3;
const wxByte PowerTabFileHeader::LESSONLEVEL_BEGINNER = 0;
const wxByte PowerTabFileHeader::LESSONLEVEL_INTERMEDIATE = 1;
const wxByte PowerTabFileHeader::LESSONLEVEL_ADVANCED = 2;
// Compatibility Constants (used by v1.0-v1.5 formats)
const wxByte PowerTabFileHeader::NUM_RELEASEDONS = 11;
const wxByte PowerTabFileHeader::RO_SINGLE = 0;
const wxByte PowerTabFileHeader::RO_EP = 1;
const wxByte PowerTabFileHeader::RO_LP = 2;
const wxByte PowerTabFileHeader::RO_DOUBLELP = 3;
const wxByte PowerTabFileHeader::RO_TRIPLELP = 4;
const wxByte PowerTabFileHeader::RO_BOXSET = 5;
const wxByte PowerTabFileHeader::RO_BOOTLEG = 6;
const wxByte PowerTabFileHeader::RO_DEMO = 7;
const wxByte PowerTabFileHeader::RO_SOUNDTRACK = 8;
const wxByte PowerTabFileHeader::RO_VIDEO = 9;
const wxByte PowerTabFileHeader::RO_NONE = 10;
// Constructor/Destructor
/// Default Constructor
PowerTabFileHeader::PowerTabFileHeader()
{
//------Last Checked------//
// - Dec 4, 2004
LoadDefaults();
}
/// Copy Constructor
PowerTabFileHeader::PowerTabFileHeader(const PowerTabFileHeader& header)
{
//------Last Checked------//
// - Dec 4, 2004
LoadDefaults();
*this = header;
}
/// Destructor
PowerTabFileHeader::~PowerTabFileHeader()
{
//------Last Checked------//
// - Dec 4, 2004
}
// Operators
/// Assignment Operator
const PowerTabFileHeader& PowerTabFileHeader::operator=(const PowerTabFileHeader& header)
{
//------Last Checked------//
// - Dec 28, 2004
// Check for assignment to self
if (this != &header)
{
m_version = header.m_version;
m_fileType = header.m_fileType;
m_songData.contentType = header.m_songData.contentType;
m_songData.title = header.m_songData.title;
m_songData.artist = header.m_songData.artist;
m_songData.releaseType = header.m_songData.releaseType;
m_songData.audioData.type = header.m_songData.audioData.type;
m_songData.audioData.title = header.m_songData.audioData.title;
m_songData.audioData.year = header.m_songData.audioData.year;
m_songData.audioData.live = header.m_songData.audioData.live;
m_songData.videoData.title = header.m_songData.videoData.title;
m_songData.videoData.live = header.m_songData.videoData.live;
m_songData.bootlegData.title = header.m_songData.bootlegData.title;
m_songData.bootlegData.month = header.m_songData.bootlegData.month;
m_songData.bootlegData.day = header.m_songData.bootlegData.day;
m_songData.bootlegData.year = header.m_songData.bootlegData.year;
m_songData.authorType = header.m_songData.authorType;
m_songData.authorData.composer = header.m_songData.authorData.composer;
m_songData.authorData.lyricist = header.m_songData.authorData.lyricist;
m_songData.arranger = header.m_songData.arranger;
m_songData.guitarScoreTranscriber = header.m_songData.guitarScoreTranscriber;
m_songData.bassScoreTranscriber = header.m_songData.bassScoreTranscriber;
m_songData.copyright = header.m_songData.copyright;
m_songData.lyrics = header.m_songData.lyrics;
m_songData.guitarScoreNotes = header.m_songData.guitarScoreNotes;
m_songData.bassScoreNotes = header.m_songData.bassScoreNotes;
m_lessonData.title = header.m_lessonData.title;
m_lessonData.subtitle = header.m_lessonData.subtitle;
m_lessonData.musicStyle = header.m_lessonData.musicStyle;
m_lessonData.level = header.m_lessonData.level;
m_lessonData.author = header.m_lessonData.author;
m_lessonData.notes = header.m_lessonData.notes;
m_lessonData.copyright = header.m_lessonData.copyright;
}
return (*this);
}
/// Equality Operator
bool PowerTabFileHeader::operator==(const PowerTabFileHeader& header) const
{
//------Last Checked------//
// - Dec 28, 2004
return (
(m_version == header.m_version) &&
(m_fileType == header.m_fileType) &&
(m_songData.contentType == header.m_songData.contentType) &&
(m_songData.title == header.m_songData.title) &&
(m_songData.artist == header.m_songData.artist) &&
(m_songData.releaseType == header.m_songData.releaseType) &&
(m_songData.audioData.type == header.m_songData.audioData.type) &&
(m_songData.audioData.title == header.m_songData.audioData.title) &&
(m_songData.audioData.year == header.m_songData.audioData.year) &&
(m_songData.audioData.live == header.m_songData.audioData.live) &&
(m_songData.videoData.title == header.m_songData.videoData.title) &&
(m_songData.videoData.live == header.m_songData.videoData.live) &&
(m_songData.bootlegData.title == header.m_songData.bootlegData.title) &&
(m_songData.bootlegData.month == header.m_songData.bootlegData.month) &&
(m_songData.bootlegData.day == header.m_songData.bootlegData.day) &&
(m_songData.bootlegData.year == header.m_songData.bootlegData.year) &&
(m_songData.authorType == header.m_songData.authorType) &&
(m_songData.authorData.composer == header.m_songData.authorData.composer) &&
(m_songData.authorData.lyricist == header.m_songData.authorData.lyricist) &&
(m_songData.arranger == header.m_songData.arranger) &&
(m_songData.guitarScoreTranscriber == header.m_songData.guitarScoreTranscriber) &&
(m_songData.bassScoreTranscriber == header.m_songData.bassScoreTranscriber) &&
(m_songData.copyright == header.m_songData.copyright) &&
(m_songData.lyrics == header.m_songData.lyrics) &&
(m_songData.guitarScoreNotes == header.m_songData.guitarScoreNotes) &&
(m_songData.bassScoreNotes == header.m_songData.bassScoreNotes) &&
(m_lessonData.title == header.m_lessonData.title) &&
(m_lessonData.subtitle == header.m_lessonData.subtitle) &&
(m_lessonData.musicStyle == header.m_lessonData.musicStyle) &&
(m_lessonData.level == header.m_lessonData.level) &&
(m_lessonData.author == header.m_lessonData.author) &&
(m_lessonData.notes == header.m_lessonData.notes) &&
(m_lessonData.copyright == header.m_lessonData.copyright)
);
}
/// Inequality Operator
bool PowerTabFileHeader::operator!=(const PowerTabFileHeader& header) const
{
//------Last Checked------//
// - Dec 28, 2004
return (!operator==(header));
}
// Serialization Functions
/// Saves a PowerTabFileHeader object to an output stream
/// @param stream Output stream to save to
/// @return True if the object was serialized, false if not
bool PowerTabFileHeader::Serialize(wxOutputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
PowerTabOutputStream data_stream(stream);
return (Serialize(data_stream));
}
/// Saves a PowerTabFileHeader object to a Power Tab output stream
/// @param stream Power Tab output stream to save to
/// @return True if the object was serialized, false if not
bool PowerTabFileHeader::Serialize(PowerTabOutputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
stream << POWERTABFILE_MARKER << FILEVERSION_CURRENT << m_fileType;
wxCHECK(stream.CheckState(), false);
// Song
if (IsSong())
{
stream << m_songData.contentType;
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.title);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.artist);
wxCHECK(stream.CheckState(), false);
stream << m_songData.releaseType;
wxCHECK(stream.CheckState(), false);
if (m_songData.releaseType == RELEASETYPE_PUBLIC_AUDIO)
{
stream << m_songData.audioData.type;
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.audioData.title);
wxCHECK(stream.CheckState(), false);
stream << m_songData.audioData.year << m_songData.audioData.live;
wxCHECK(stream.CheckState(), false);
}
else if (m_songData.releaseType == RELEASETYPE_PUBLIC_VIDEO)
{
stream.WriteMFCString(m_songData.videoData.title);
wxCHECK(stream.CheckState(), false);
stream << m_songData.videoData.live;
wxCHECK(stream.CheckState(), false);
}
else if (m_songData.releaseType == RELEASETYPE_BOOTLEG)
{
stream.WriteMFCString(m_songData.bootlegData.title);
wxCHECK(stream.CheckState(), false);
stream << m_songData.bootlegData.month << m_songData.bootlegData.day << m_songData.bootlegData.year;
wxCHECK(stream.CheckState(), false);
}
stream << m_songData.authorType;
wxCHECK(stream.CheckState(), false);
if (m_songData.authorType == AUTHORTYPE_AUTHORKNOWN)
{
stream.WriteMFCString(m_songData.authorData.composer);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.authorData.lyricist);
wxCHECK(stream.CheckState(), false);
}
stream.WriteMFCString(m_songData.arranger);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.guitarScoreTranscriber);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.bassScoreTranscriber);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.copyright);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.lyrics);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.guitarScoreNotes);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_songData.bassScoreNotes);
wxCHECK(stream.CheckState(), false);
}
// Lesson
else if (IsLesson())
{
stream.WriteMFCString(m_lessonData.title);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_lessonData.subtitle);
wxCHECK(stream.CheckState(), false);
stream << m_lessonData.musicStyle << m_lessonData.level;
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_lessonData.author);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_lessonData.notes);
wxCHECK(stream.CheckState(), false);
stream.WriteMFCString(m_lessonData.copyright);
wxCHECK(stream.CheckState(), false);
}
return (stream.CheckState());
}
/// Loads a PowerTabFileHeader object from an input stream
/// @param stream Input stream to load from
/// @return True if the object was deserialized, false if not
bool PowerTabFileHeader::Deserialize(wxInputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
PowerTabInputStream data_stream(stream);
return (Deserialize(data_stream));
}
/// Loads a PowerTabFileHeader object from a Power Tab input stream
/// @param stream Power Tab input stream to load from
/// @return True if the object was deserialized, false if not
bool PowerTabFileHeader::Deserialize(PowerTabInputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
// Read the special Power Tab file marker
wxUint32 marker = 0;
stream >> marker;
wxCHECK(stream.CheckState(), false);
if (!IsValidPowerTabFileMarker(marker))
{
stream.m_lastPowerTabError = POWERTABSTREAM_INVALID_MARKER;
return (false);
}
// Read the file version
stream >> m_version;
wxCHECK(stream.CheckState(), false);
if (!IsValidFileVersion(m_version))
{
stream.m_lastPowerTabError = POWERTABSTREAM_INVALID_FILE_VERSION;
return (false);
}
// Based on the file version, deserialize
bool returnValue = false;
// Version 1.0 and 1.0.2
if (m_version == FILEVERSION_1_0 || m_version == FILEVERSION_1_0_2)
returnValue = DeserializeVersion1_0(stream);
// Version 1.5
else if (m_version == FILEVERSION_1_5)
returnValue = DeserializeVersion1_5(stream);
// Version 1.7 and up
else
returnValue = DeserializeVersion1_7(stream);
return (returnValue);
}
/// Loads a v1.7 PowerTabFileHeader object from a Power Tab input stream
/// @param stream Power Tab input stream to load from
/// @return True if the object was deserialized, false if not
bool PowerTabFileHeader::DeserializeVersion1_7(PowerTabInputStream& stream)
{
//------Last Checked------//
// - Dec 29, 2004
stream >> m_fileType;
wxCHECK(stream.CheckState(), false);
if (!IsValidFileType(m_fileType))
{
stream.m_lastPowerTabError = POWERTABSTREAM_INVALID_FILE_TYPE;
return (false);
}
if (m_fileType == FILETYPE_SONG)
{
stream >> m_songData.contentType;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.title);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.artist);
wxCHECK(stream.CheckState(), false);
stream >> m_songData.releaseType;
wxCHECK(stream.CheckState(), false);
// CASE: Public audio release
if (m_songData.releaseType == RELEASETYPE_PUBLIC_AUDIO)
{
stream >> m_songData.audioData.type;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.audioData.title);
wxCHECK(stream.CheckState(), false);
stream >> m_songData.audioData.year >> m_songData.audioData.live;
wxCHECK(stream.CheckState(), false);
}
// CASE: Public video release
else if (m_songData.releaseType == RELEASETYPE_PUBLIC_VIDEO)
{
stream.ReadMFCString(m_songData.videoData.title);
wxCHECK(stream.CheckState(), false);
stream >> m_songData.videoData.live;
wxCHECK(stream.CheckState(), false);
}
// CASE: Bootleg release
else if (m_songData.releaseType == RELEASETYPE_BOOTLEG)
{
stream.ReadMFCString(m_songData.bootlegData.title);
wxCHECK(stream.CheckState(), false);
stream >> m_songData.bootlegData.month >> m_songData.bootlegData.day >> m_songData.bootlegData.year;
wxCHECK(stream.CheckState(), false);
}
stream >> m_songData.authorType;
wxCHECK(stream.CheckState(), false);
// CASE: Author known
if (m_songData.authorType == AUTHORTYPE_AUTHORKNOWN)
{
stream.ReadMFCString(m_songData.authorData.composer);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.authorData.lyricist);
wxCHECK(stream.CheckState(), false);
}
stream.ReadMFCString(m_songData.arranger);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.guitarScoreTranscriber);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.bassScoreTranscriber);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.copyright);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.lyrics);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.guitarScoreNotes);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.bassScoreNotes);
wxCHECK(stream.CheckState(), false);
}
// Lesson
else if (m_fileType == FILETYPE_LESSON)
{
stream.ReadMFCString(m_lessonData.title);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_lessonData.subtitle);
wxCHECK(stream.CheckState(), false);
stream >> m_lessonData.musicStyle >> m_lessonData.level;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_lessonData.author);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_lessonData.notes);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_lessonData.copyright);
wxCHECK(stream.CheckState(), false);
}
return (stream.CheckState());
}
/// Loads a v1.5 PowerTabFileHeader object from a Power Tab input stream
/// @param stream Power Tab input stream to load from
/// @return True if the object was deserialized, false if not
bool PowerTabFileHeader::DeserializeVersion1_5(PowerTabInputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
wxByte releasedOn = 0, live = 0;
wxWord year = 0;
wxString releaseTitle = wxT("");
stream.ReadMFCString(m_songData.title);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.artist);
wxCHECK(stream.CheckState(), false);
stream >> releasedOn;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(releaseTitle);
wxCHECK(stream.CheckState(), false);
stream >> live;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.authorData.composer);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.authorData.lyricist);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.arranger);
wxCHECK(stream.CheckState(), false);
stream >> year >> m_songData.authorType;
wxCHECK(stream.CheckState(), false);
// Clear the composer and lyricist if the song is traditional
if (m_songData.authorType == AUTHORTYPE_TRADITIONAL)
{
m_songData.authorData.composer.Clear();
m_songData.authorData.lyricist.Clear();
}
stream.ReadMFCString(m_songData.copyright);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.lyrics);
wxCHECK(stream.CheckState(), false);
// Soundtrack becomes LP
if (releasedOn == RO_SOUNDTRACK)
releasedOn = RO_LP;
// Bootleg becomes bootleg
if (releasedOn == RO_BOOTLEG)
{
m_songData.releaseType = RELEASETYPE_BOOTLEG;
m_songData.bootlegData.title = releaseTitle;
m_songData.bootlegData.day = 1;
m_songData.bootlegData.month = 1;
m_songData.bootlegData.year = year;
}
// Demo or none become not-released
else if (releasedOn == RO_DEMO || releasedOn == RO_NONE)
m_songData.releaseType = RELEASETYPE_NOTRELEASED;
// Video becomes video
else if (releasedOn == RO_VIDEO)
{
m_songData.releaseType = RELEASETYPE_PUBLIC_VIDEO;
m_songData.videoData.title = releaseTitle;
m_songData.videoData.live = live;
}
// Single, EP, LP, Double LP, Triple LP, Boxset, Soundtrack become audio releases
else
{
m_songData.releaseType = RELEASETYPE_PUBLIC_AUDIO;
m_songData.audioData.title = releaseTitle;
m_songData.audioData.type = releasedOn;
m_songData.audioData.live = live;
m_songData.audioData.year = year;
}
return (stream.CheckState());
}
/// Loads a v1.0 or v1.0.2 format PowerTabFileHeader object from a Power Tab input stream
/// @param stream Power Tab input stream to load from
/// @return True if the object was deserialized, false if not
bool PowerTabFileHeader::DeserializeVersion1_0(PowerTabInputStream& stream)
{
//------Last Checked------//
// - Dec 28, 2004
wxByte releasedOn = 0, live = 0;
wxWord year = 0;
wxString releaseTitle;
stream.ReadMFCString(m_songData.title);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.artist);
wxCHECK(stream.CheckState(), false);
stream >> releasedOn;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(releaseTitle);
wxCHECK(stream.CheckState(), false);
stream >> live;
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.authorData.composer);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.authorData.lyricist);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.arranger);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.guitarScoreTranscriber);
wxCHECK(stream.CheckState(), false);
stream >> year >> m_songData.authorType;
wxCHECK(stream.CheckState(), false);
// Clear the composer and lyricist if the song is traditional
if (m_songData.authorType == AUTHORTYPE_TRADITIONAL)
{
m_songData.authorData.composer.Clear();
m_songData.authorData.lyricist.Clear();
}
stream.ReadMFCString(m_songData.copyright);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.lyrics);
wxCHECK(stream.CheckState(), false);
stream.ReadMFCString(m_songData.guitarScoreNotes);
wxCHECK(stream.CheckState(), false);
// Bootleg becomes bootleg
if (releasedOn == RO_BOOTLEG)
{
m_songData.releaseType = RELEASETYPE_BOOTLEG;
m_songData.bootlegData.title = releaseTitle;
m_songData.bootlegData.day = 1;
m_songData.bootlegData.month = 1;
m_songData.bootlegData.year = year;
}
// Demo becomes not-released
else if (releasedOn == RO_DEMO)
m_songData.releaseType = RELEASETYPE_NOTRELEASED;
// Single, EP, LP, Double LP, Triple LP, Boxset, Soundtrack become audio releases
else
{
m_songData.releaseType = RELEASETYPE_PUBLIC_AUDIO;
m_songData.audioData.title = releaseTitle;
m_songData.audioData.type = releasedOn;
m_songData.audioData.live = live;
m_songData.audioData.year = year;
}
return (stream.CheckState());
}
/// Gets the release title for a song (audio title or video title or bootleg title)
/// @return The release title for the song
wxString PowerTabFileHeader::GetSongReleaseTitle() const
{
//------Last Checked------//
// - Dec 28, 2004
wxString returnValue = wxT("");
wxByte releaseType = GetSongReleaseType();
// Video release
if (releaseType == RELEASETYPE_PUBLIC_VIDEO)
returnValue = GetSongVideoReleaseTitle();
// Bootleg
else if (releaseType == RELEASETYPE_BOOTLEG)
returnValue = GetSongBootlegTitle();
// Audio release
else
returnValue = GetSongAudioReleaseTitle();
return (returnValue);
}
/// Sets the song bootleg date
/// @param date Date to set
/// @return True if the bootleg date was set, false if not
bool PowerTabFileHeader::SetSongBootlegDate(const wxDateTime& date)
{
//------Last Checked------//
// - Dec 28, 2004
wxCHECK(date.IsValid(), false);
m_songData.bootlegData.month = (wxWord)date.GetMonth() + 1; // wxDateTime month is zero based, so add 1
m_songData.bootlegData.day = (wxWord)date.GetDay();
m_songData.bootlegData.year = (wxWord)date.GetYear();
return (true);
}
/// Gets the song bootleg date
/// @return The song bootleg date
wxDateTime PowerTabFileHeader::GetSongBootlegDate() const
{
//------Last Checked------//
// - Dec 28, 2004
wxDateTime returnValue;
returnValue.SetDay(m_songData.bootlegData.day);
returnValue.SetYear(m_songData.bootlegData.year);
switch (m_songData.bootlegData.month)
{
case 2:
returnValue.SetMonth(wxDateTime::Feb);
break;
case 3:
returnValue.SetMonth(wxDateTime::Mar);
break;
case 4:
returnValue.SetMonth(wxDateTime::Apr);
break;
case 5:
returnValue.SetMonth(wxDateTime::May);
break;
case 6:
returnValue.SetMonth(wxDateTime::Jun);
break;
case 7:
returnValue.SetMonth(wxDateTime::Jul);
break;
case 8:
returnValue.SetMonth(wxDateTime::Aug);
break;
case 9:
returnValue.SetMonth(wxDateTime::Sep);
break;
case 10:
returnValue.SetMonth(wxDateTime::Oct);
break;
case 11:
returnValue.SetMonth(wxDateTime::Nov);
break;
case 12:
returnValue.SetMonth(wxDateTime::Dec);
break;
default:
returnValue.SetMonth(wxDateTime::Jan);
break;
}
return (returnValue);
}
// Operations
/// Loads the default settings for the header
void PowerTabFileHeader::LoadDefaults()
{
//------Last Checked------//
// - Dec 28, 2004
m_version = FILEVERSION_CURRENT;
m_fileType = FILETYPE_SONG;
// Load default song data
m_songData.contentType = 0;
m_songData.title.Clear();
m_songData.artist.Clear();
m_songData.releaseType = RELEASETYPE_PUBLIC_AUDIO;
m_songData.audioData.type = AUDIORELEASETYPE_ALBUM;
m_songData.audioData.title.Clear();
m_songData.audioData.year = (wxWord)wxDateTime::Now().GetYear();
m_songData.audioData.live = 0;
m_songData.videoData.title.Clear();
m_songData.videoData.live = 0;
m_songData.bootlegData.title.Clear();
m_songData.bootlegData.month = (wxWord)wxDateTime::Now().GetMonth();
m_songData.bootlegData.day = (wxWord)wxDateTime::Now().GetDay();
m_songData.bootlegData.year = (wxWord)wxDateTime::Now().GetYear();
m_songData.authorType = AUTHORTYPE_AUTHORKNOWN;
m_songData.authorData.composer.Clear();
m_songData.authorData.lyricist.Clear();
m_songData.arranger.Clear();
m_songData.guitarScoreTranscriber.Clear();
m_songData.bassScoreTranscriber.Clear();
m_songData.copyright.Clear();
m_songData.lyrics.Clear();
m_songData.guitarScoreNotes.Clear();
m_songData.bassScoreNotes.Clear();
// Load default lesson data
m_lessonData.title.Clear();
m_lessonData.subtitle.Clear();
m_lessonData.musicStyle = MUSICSTYLE_GENERAL;
m_lessonData.level = LESSONLEVEL_INTERMEDIATE;
m_lessonData.author.Clear();
m_lessonData.notes.Clear();
m_lessonData.copyright.Clear();
}
| [
"blarsen@8c24db97-d402-0410-b267-f151a046c31a"
]
| [
[
[
1,
858
]
]
]
|
5e54f4a0855b68516e19e53e02b22db1d4efeefc | f794fd0abaed1011ede69129e36ce436347693fd | /CTexture.h | 26aa73fe80b2f9601fdb7753e09d5ac400959074 | []
| no_license | konradrodzik/raytracer-cpu-gpu | d7a048a45f94457d7dde5f1eb3b34ecc83867ffb | 0ac756a43998b4c0a3d6c923745922ba03cf7b6c | refs/heads/master | 2016-09-15T21:00:23.107984 | 2011-01-24T01:04:41 | 2011-01-24T01:04:41 | 32,467,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,645 | h | ////////////////////////////////////
// Konrad Rodrigo Rodzik (c) 2010 //
////////////////////////////////////
#ifndef __H_CTexture_H__
#define __H_CTexture_H__
class CTexture
{
public:
// Default constructor
CTexture();
// Initialize constructor
CTexture(CColor* surface, int width, int height);
CTexture(const char* fileName);
// Destructor
~CTexture();
// Get texture width
int getWidth();
// Get texture height
int getHeight();
// Get texture surface
CColor* getSurface();
// Get texel of texture in u,v
__device__ __host__ CColor getTexel(float u, float v)
{
float fu = (u + 1000.5f) * m_width;
float fv = (v + 1000.0f) * m_width;
int u1 = ((int)fu) % m_width;
int v1 = ((int)fv) % m_height;
int u2 = (u1 + 1) % m_width;
int v2 = (v1 + 1) % m_height;
float fracu = fu - floorf(fu);
float fracv = fv - floorf(fv);
// Calculate weights
float w1 = (1 - fracu) * (1 - fracv);
float w2 = fracu * (1 - fracv);
float w3 = (1 - fracu) * fracv;
float w4 = fracu * fracv;
CColor c1 = m_textureSurface[u1 + v1 * m_width];
CColor c2 = m_textureSurface[u2 + v1 * m_width];
CColor c3 = m_textureSurface[u1 + v2 * m_width];
CColor c4 = m_textureSurface[u2 + v2 * m_width];
return c1 * w1 + c2 * w2 + c3 * w3 + c4 * w4;
}
private:
void loadTextureFromFile(const char* fileName);
private:
int m_width; // Texture width
int m_height; // Texture height
CColor m_textureSurface[512*512]; // Texture surface
};
/*
// Bitmap header
typedef struct tagBITMAPFILEHEADER
{
WORD bfType; //specifies the file type
DWORD bfSize; //specifies the size in bytes of the bitmap file
WORD bfReserved1; //reserved; must be 0
WORD bfReserved2; //reserved; must be 0
DWORD bOffBits; //species the offset in bytes from the bitmapfileheader to the bitmap bits
}BITMAPFILEHEADER;
// Bitmap info header
typedef struct tagBITMAPINFOHEADER
{
DWORD biSize; //specifies the number of bytes required by the struct
LONG biWidth; //specifies width in pixels
LONG biHeight; //species height in pixels
WORD biPlanes; //specifies the number of color planes, must be 1
WORD biBitCount; //specifies the number of bit per pixel
DWORD biCompression;//spcifies the type of compression
DWORD biSizeImage; //size of image in bytes
LONG biXPelsPerMeter; //number of pixels per meter in x axis
LONG biYPelsPerMeter; //number of pixels per meter in y axis
DWORD biClrUsed; //number of colors used by th ebitmap
DWORD biClrImportant; //number of colors that are important
}BITMAPINFOHEADER;*/
#endif | [
"konrad.rodzik@8e044db2-5a41-7fc7-fe2a-5b7de51f5869"
]
| [
[
[
1,
92
]
]
]
|
27ab97dccafc59d12ff75f279c9c2095535e22e6 | f73eca356aba8cbc5c0cbe7527c977f0e7d6a116 | /Glop/third_party/raknet/BitStream_NoTemplate.h | 8da6744030cf84afba7715064dbb1de8888b9036 | [
"BSD-3-Clause"
]
| permissive | zorbathut/glop | 40737587e880e557f1f69c3406094631e35e6bb5 | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | refs/heads/master | 2016-08-06T22:58:18.240425 | 2011-10-20T04:22:20 | 2011-10-20T04:22:20 | 710,818 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,098 | h | /// \file
/// \brief This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.jenkinssoftware.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to 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.
#if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization
#ifndef __BITSTREAM_H
#define __BITSTREAM_H
#include "RakMemoryOverride.h"
#include "RakNetDefines.h"
#include "Export.h"
#include "RakNetTypes.h"
#include <assert.h>
#if defined(_PS3)
#include <math.h>
#else
#include <cmath>
#endif
#include <float.h>
#ifdef _MSC_VER
#pragma warning( push )
#endif
/// Arbitrary size, just picking something likely to be larger than most packets
#define BITSTREAM_STACK_ALLOCATION_SIZE 256
/// The namespace RakNet is not consistently used. It's only purpose is to avoid compiler errors for classes whose names are very common.
/// For the most part I've tried to avoid this simply by using names very likely to be unique for my classes.
namespace RakNet
{
/// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well.
/// \sa BitStreamSample.txt
class RAK_DLL_EXPORT BitStream : public RakNet::RakMemoryOverride
{
public:
/// Default Constructor
BitStream();
/// Create the bitstream, with some number of bytes to immediately allocate.
/// There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE.
/// In that case all it does is save you one or more realloc calls.
/// \param[in] initialBytesToAllocate the number of bytes to pre-allocate.
BitStream( int initialBytesToAllocate );
/// Initialize the BitStream, immediately setting the data it contains to a predefined pointer.
/// Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data.
/// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory
/// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows:
/// \code
/// RakNet::BitStream bs(packet->data, packet->length, false);
/// \endcode
/// \param[in] _data An array of bytes.
/// \param[in] lengthInBytes Size of the \a _data.
/// \param[in] _copyData true or false to make a copy of \a _data or not.
BitStream( unsigned char* _data, unsigned int lengthInBytes, bool _copyData );
/// Destructor
~BitStream();
/// Resets the bitstream for reuse.
void Reset( void );
/// Bidirectional serialize/deserialize any integral type to/from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] var The value to write
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool Serialize(bool writeToBitstream, bool &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, unsigned char &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, char &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, unsigned short &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, short &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, unsigned int &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, int &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, unsigned long &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, long &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, long long &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, float &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, double &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
bool Serialize(bool writeToBitstream, long double &var){if (writeToBitstream)Write(var);else return Read(var); return true;}
/// Bidirectional serialize/deserialize any integral type to/from a bitstream. If the current value is different from the last value
/// the current value will be written. Otherwise, a single bit will be written
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true.
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeDelta(bool writeToBitstream, bool ¤tValue, bool lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned char ¤tValue, unsigned char lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, char ¤tValue, char lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned short ¤tValue, unsigned short lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, short ¤tValue, short lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned int ¤tValue, unsigned int lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, int ¤tValue, int lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned long ¤tValue, unsigned long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, long long ¤tValue, long long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned long long ¤tValue, unsigned long long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, float ¤tValue, float lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, double ¤tValue, double lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, long double ¤tValue, long double lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;}
/// Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] currentValue The current value to write
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeDelta(bool writeToBitstream, bool ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned char ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, char ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned short ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, short ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned int ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, int ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned long ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, long long ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, unsigned long long ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, float ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, double ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
bool SerializeDelta(bool writeToBitstream, long double ¤tValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;}
/// Bidirectional serialize/deserialize any integral type to/from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] var The value to write
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeCompressed(bool writeToBitstream, bool &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, unsigned char &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, char &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, unsigned short &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, short &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, unsigned int &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, int &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, unsigned long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, long long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, float &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, double &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
bool SerializeCompressed(bool writeToBitstream, long double &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;}
/// Bidirectional serialize/deserialize any integral type to/from a bitstream. If the current value is different from the last value
/// the current value will be written. Otherwise, a single bit will be written
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true.
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeCompressedDelta(bool writeToBitstream, bool ¤tValue, bool lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned char ¤tValue, unsigned char lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, char ¤tValue, char lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned short ¤tValue, unsigned short lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, short ¤tValue, short lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned int ¤tValue, unsigned int lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, int ¤tValue, int lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned long ¤tValue, unsigned long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, long long ¤tValue, long long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned long long ¤tValue, unsigned long long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, float ¤tValue, float lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, double ¤tValue, double lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
bool SerializeCompressedDelta(bool writeToBitstream, long double ¤tValue, long double lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;}
/// Save as SerializeCompressedDelta(templateType ¤tValue, templateType lastValue) when we have an unknown second parameter
bool SerializeCompressedDelta(bool writeToBitstream, bool &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned char &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, char &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned short &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, short &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned int &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, int &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, long long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, float &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, double &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
bool SerializeCompressedDelta(bool writeToBitstream, long double &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;}
/// Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] input a byte buffer
/// \param[in] numberOfBytes the size of \a input in bytes
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool Serialize(bool writeToBitstream, char* input, const int numberOfBytes );
/// Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors.
/// Accurate to 1/32767.5.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeNormVector(bool writeToBitstream, float &x, float &y, float z ){if (writeToBitstream) WriteNormVector(x,y,z); else return ReadNormVector(x,y,z); return true;}
bool SerializeNormVector(bool writeToBitstream, double &x, double &y, double &z ){if (writeToBitstream) WriteNormVector(x,y,z); else return ReadNormVector(x,y,z); return true;}
/// Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12.
/// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeVector(bool writeToBitstream, float &x, float &y, float &z ){if (writeToBitstream) WriteVector(x,y,z); else return ReadVector(x,y,z); return true;}
bool SerializeVector(bool writeToBitstream, double &x, double &y, double &z ){if (writeToBitstream) WriteVector(x,y,z); else return ReadVector(x,y,z); return true;}
/// Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] w w
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeNormQuat(bool writeToBitstream, float &w, float &x, float &y, float &z){if (writeToBitstream) WriteNormQuat(w,x,y,z); else return ReadNormQuat(w,x,y,z); return true;}
bool SerializeNormQuat(bool writeToBitstream, double &w, double &x, double &y, double &z){if (writeToBitstream) WriteNormQuat(w,x,y,z); else return ReadNormQuat(w,x,y,z); return true;}
/// Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each
/// for 6 bytes instead of 36
/// Lossy, although the result is renormalized
bool SerializeOrthMatrix(
bool writeToBitstream,
float &m00, float &m01, float &m02,
float &m10, float &m11, float &m12,
float &m20, float &m21, float &m22 ){if (writeToBitstream) WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); else return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); return true;}
bool SerializeOrthMatrix(
bool writeToBitstream,
double &m00, double &m01, double &m02,
double &m10, double &m11, double &m12,
double &m20, double &m21, double &m22 ){if (writeToBitstream) WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); else return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); return true;}
/// Bidirectional serialize/deserialize numberToSerialize bits to/from the input. Right aligned
/// data means in the case of a partial byte, the bits are aligned
/// from the right (bit 0) rather than the left (as in the normal
/// internal representation) You would set this to true when
/// writing user data, and false when copying bitstream data, such
/// as writing one bitstream to another
/// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
/// \param[in] input The data
/// \param[in] numberOfBitsToSerialize The number of bits to write
/// \param[in] rightAlignedBits if true data will be right aligned
/// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
bool SerializeBits(bool writeToBitstream, unsigned char* input, int numberOfBitsToSerialize, const bool rightAlignedBits = true );
/// Write any integral type to a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// \param[in] var The value to write
void Write(bool var){if ( var ) Write1(); else Write0();}
void Write(unsigned char var){WriteBits( ( unsigned char* ) & var, sizeof( unsigned char ) * 8, true );}
void Write(char var){WriteBits( ( unsigned char* ) & var, sizeof( char ) * 8, true );}
void Write(unsigned short var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned short)); WriteBits( ( unsigned char* ) output, sizeof(unsigned short) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );}
void Write(short var) {if (DoEndianSwap()){unsigned char output[sizeof(short)]; ReverseBytes((unsigned char*)&var, output, sizeof(short)); WriteBits( ( unsigned char* ) output, sizeof(short) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(short) * 8, true );}
void Write(unsigned int var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned int)); WriteBits( ( unsigned char* ) output, sizeof(unsigned int) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );}
void Write(int var) {if (DoEndianSwap()){unsigned char output[sizeof(int)]; ReverseBytes((unsigned char*)&var, output, sizeof(int)); WriteBits( ( unsigned char* ) output, sizeof(int) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(int) * 8, true );}
void Write(unsigned long var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long)); WriteBits( ( unsigned char* ) output, sizeof(unsigned long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );}
void Write(long var) {if (DoEndianSwap()){unsigned char output[sizeof(long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long)); WriteBits( ( unsigned char* ) output, sizeof(long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long) * 8, true );}
void Write(long long var) {if (DoEndianSwap()){unsigned char output[sizeof(long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long long)); WriteBits( ( unsigned char* ) output, sizeof(long long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long long) * 8, true );}
void Write(unsigned long long var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long long)); WriteBits( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );}
void Write(float var) {if (DoEndianSwap()){unsigned char output[sizeof(float)]; ReverseBytes((unsigned char*)&var, output, sizeof(float)); WriteBits( ( unsigned char* ) output, sizeof(float) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(float) * 8, true );}
void Write(double var) {if (DoEndianSwap()){unsigned char output[sizeof(double)]; ReverseBytes((unsigned char*)&var, output, sizeof(double)); WriteBits( ( unsigned char* ) output, sizeof(double) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(double) * 8, true );}
void Write(long double var) {if (DoEndianSwap()){unsigned char output[sizeof(long double)]; ReverseBytes((unsigned char*)&var, output, sizeof(long double)); WriteBits( ( unsigned char* ) output, sizeof(long double) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long double) * 8, true );}
void Write(void* var) {if (DoEndianSwap()){unsigned char output[sizeof(void*)]; ReverseBytes((unsigned char*)&var, output, sizeof(void*)); WriteBits( ( unsigned char* ) output, sizeof(void*) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(void*) * 8, true );}
void Write(SystemAddress var){WriteBits( ( unsigned char* ) & var.binaryAddress, sizeof(var.binaryAddress) * 8, true ); Write(var.port);}
void Write(NetworkID var){if (NetworkID::IsPeerToPeerMode()) Write(var.systemAddress); Write(var.localSystemAddress);}
/// Write any integral type to a bitstream. If the current value is different from the last value
/// the current value will be written. Otherwise, a single bit will be written
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
void WriteDelta(bool currentValue, bool lastValue){
#pragma warning(disable:4100) // warning C4100: 'peer' : unreferenced formal parameter
Write(currentValue);
}
void WriteDelta(unsigned char currentValue, unsigned char lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(char currentValue, char lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(unsigned short currentValue, unsigned short lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(short currentValue, short lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(unsigned int currentValue, unsigned int lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(int currentValue, int lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(unsigned long currentValue, unsigned long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(long currentValue, long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(long long currentValue, long long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(unsigned long long currentValue, unsigned long long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(float currentValue, float lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(double currentValue, double lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(long double currentValue, long double lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(SystemAddress currentValue, SystemAddress lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
void WriteDelta(NetworkID currentValue, NetworkID lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}}
/// WriteDelta when you don't know what the last value is, or there is no last value.
/// \param[in] currentValue The current value to write
void WriteDelta(bool var){Write(var);}
void WriteDelta(unsigned char var){Write(true); Write(var);}
void WriteDelta(char var){Write(true); Write(var);}
void WriteDelta(unsigned short var){Write(true); Write(var);}
void WriteDelta(short var){Write(true); Write(var);}
void WriteDelta(unsigned int var){Write(true); Write(var);}
void WriteDelta(int var){Write(true); Write(var);}
void WriteDelta(unsigned long var){Write(true); Write(var);}
void WriteDelta(long var){Write(true); Write(var);}
void WriteDelta(long long var){Write(true); Write(var);}
void WriteDelta(unsigned long long var){Write(true); Write(var);}
void WriteDelta(float var){Write(true); Write(var);}
void WriteDelta(double var){Write(true); Write(var);}
void WriteDelta(long double var){Write(true); Write(var);}
void WriteDelta(SystemAddress var){Write(true); Write(var);}
void WriteDelta(NetworkID var){Write(true); Write(var);}
/// Write any integral type to a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// \param[in] var The value to write
void WriteCompressed(bool var) {Write(var);}
void WriteCompressed(unsigned char var) {WriteCompressed( ( unsigned char* ) & var, sizeof( unsigned char ) * 8, true );}
void WriteCompressed(char var) {WriteCompressed( (unsigned char* ) & var, sizeof( unsigned char ) * 8, true );}
void WriteCompressed(unsigned short var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned short)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned short)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned short) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );}
void WriteCompressed(short var) {if (DoEndianSwap()) {unsigned char output[sizeof(short)]; ReverseBytes((unsigned char*)&var, output, sizeof(short)); WriteCompressed( ( unsigned char* ) output, sizeof(short) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(short) * 8, true );}
void WriteCompressed(unsigned int var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned int)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned int)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned int) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );}
void WriteCompressed(int var) {if (DoEndianSwap()) { unsigned char output[sizeof(int)]; ReverseBytes((unsigned char*)&var, output, sizeof(int)); WriteCompressed( ( unsigned char* ) output, sizeof(int) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(int) * 8, true );}
void WriteCompressed(unsigned long var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );}
void WriteCompressed(long var) {if (DoEndianSwap()) {unsigned char output[sizeof(long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long)); WriteCompressed( ( unsigned char* ) output, sizeof(long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(long) * 8, true );}
void WriteCompressed(long long var) {if (DoEndianSwap()) {unsigned char output[sizeof(long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long long)); WriteCompressed( ( unsigned char* ) output, sizeof(long long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(long long) * 8, true );}
void WriteCompressed(unsigned long long var) {if (DoEndianSwap()) { unsigned char output[sizeof(unsigned long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long long)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );}
void WriteCompressed(float var) {assert(var > -1.01f && var < 1.01f); if (var < -1.0f) var=-1.0f; if (var > 1.0f) var=1.0f; Write((unsigned short)((var+1.0f)*32767.5f));}
void WriteCompressed(double var) {assert(var > -1.01 && var < 1.01); if (var < -1.0) var=-1.0; if (var > 1.0) var=1.0; Write((unsigned long)((var+1.0)*2147483648.0));}
void WriteCompressed(long double var) {assert(var > -1.01 && var < 1.01); if (var < -1.0) var=-1.0; if (var > 1.0) var=1.0; Write((unsigned long)((var+1.0)*2147483648.0));}
/// Write any integral type to a bitstream. If the current value is different from the last value
/// the current value will be written. Otherwise, a single bit will be written
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
void WriteCompressedDelta(bool currentValue, bool lastValue)
{
#pragma warning(disable:4100) // warning C4100: 'peer' : unreferenced formal parameter
Write(currentValue);
}
void WriteCompressedDelta(unsigned char currentValue, unsigned char lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(char currentValue, char lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(unsigned short currentValue, unsigned short lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(short currentValue, short lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(unsigned int currentValue, unsigned int lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(int currentValue, int lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(unsigned long currentValue, unsigned long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(long currentValue, long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(long long currentValue, long long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(unsigned long long currentValue, unsigned long long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(float currentValue, float lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(double currentValue, double lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
void WriteCompressedDelta(long double currentValue, long double lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}}
/// Save as WriteCompressedDelta(templateType currentValue, templateType lastValue) when we have an unknown second parameter
void WriteCompressedDelta(bool var) {Write(var);}
void WriteCompressedDelta(unsigned char var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(char var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(unsigned short var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(short var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(unsigned int var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(int var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(unsigned long var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(long var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(long long var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(unsigned long long var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(float var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(double var) { Write(true); WriteCompressed(var); }
void WriteCompressedDelta(long double var) { Write(true); WriteCompressed(var); }
/// Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping.
/// \param[in] var The value to read
bool Read(bool &var){if ( readOffset + 1 > numberOfBitsUsed ) return false;
if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) )
var = true;
else
var = false;
// Has to be on a different line for Mac
readOffset++;
return true;
}
bool Read(unsigned char &var) {return ReadBits( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );}
bool Read(char &var) {return ReadBits( ( unsigned char* ) &var, sizeof(char) * 8, true );}
bool Read(unsigned short &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned short) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned short)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );}
bool Read(short &var) {if (DoEndianSwap()){unsigned char output[sizeof(short)]; if (ReadBits( ( unsigned char* ) output, sizeof(short) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(short)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(short) * 8, true );}
bool Read(unsigned int &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned int) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned int)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );}
bool Read(int &var) {if (DoEndianSwap()){unsigned char output[sizeof(int)]; if (ReadBits( ( unsigned char* ) output, sizeof(int) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(int)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(int) * 8, true );}
bool Read(unsigned long &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );}
bool Read(long &var) {if (DoEndianSwap()){unsigned char output[sizeof(long)]; if (ReadBits( ( unsigned char* ) output, sizeof(long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long) * 8, true );}
bool Read(long long &var) {if (DoEndianSwap()){unsigned char output[sizeof(long long)]; if (ReadBits( ( unsigned char* ) output, sizeof(long long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long long) * 8, true );}
bool Read(unsigned long long &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );}
bool Read(float &var) {if (DoEndianSwap()){unsigned char output[sizeof(float)]; if (ReadBits( ( unsigned char* ) output, sizeof(float) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(float)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(float) * 8, true );}
bool Read(double &var) {if (DoEndianSwap()){unsigned char output[sizeof(double)]; if (ReadBits( ( unsigned char* ) output, sizeof(double) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(double)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(double) * 8, true );}
bool Read(long double &var) {if (DoEndianSwap()){unsigned char output[sizeof(long double)]; if (ReadBits( ( unsigned char* ) output, sizeof(long double) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long double)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long double) * 8, true );}
bool Read(void* &var) {if (DoEndianSwap()){unsigned char output[sizeof(void*)]; if (ReadBits( ( unsigned char* ) output, sizeof(void*) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(void*)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(void*) * 8, true );}
bool Read(SystemAddress &var){ReadBits( ( unsigned char* ) & var.binaryAddress, sizeof(var.binaryAddress) * 8, true ); return Read(var.port);}
bool Read(NetworkID &var){if (NetworkID::IsPeerToPeerMode()) Read(var.systemAddress); return Read(var.localSystemAddress);}
/// Read any integral type from a bitstream. If the written value differed from the value compared against in the write function,
/// var will be updated. Otherwise it will retain the current value.
/// ReadDelta is only valid from a previous call to WriteDelta
/// \param[in] var The value to read
bool ReadDelta(bool &var) {return Read(var);}
bool ReadDelta(unsigned char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(unsigned short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(unsigned int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(unsigned long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(unsigned long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(float &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(long double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(SystemAddress &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
bool ReadDelta(NetworkID &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;}
/// Read any integral type from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] var The value to read
bool ReadCompressed(bool &var) {return Read(var);}
bool ReadCompressed(unsigned char &var) {return ReadCompressed( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );}
bool ReadCompressed(char &var) {return ReadCompressed( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );}
bool ReadCompressed(unsigned short &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned short) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned short)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );}
bool ReadCompressed(short &var){if (DoEndianSwap()){unsigned char output[sizeof(short)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(short) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(short)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(short) * 8, true );}
bool ReadCompressed(unsigned int &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned int) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned int)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );}
bool ReadCompressed(int &var){if (DoEndianSwap()){unsigned char output[sizeof(int)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(int) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(int)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(int) * 8, true );}
bool ReadCompressed(unsigned long &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );}
bool ReadCompressed(long &var){if (DoEndianSwap()){unsigned char output[sizeof(long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(long) * 8, true );}
bool ReadCompressed(long long &var){if (DoEndianSwap()){unsigned char output[sizeof(long long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(long long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(long long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(long long) * 8, true );}
bool ReadCompressed(unsigned long long &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );}
bool ReadCompressed(float &var){unsigned short compressedFloat; if (Read(compressedFloat)) { var = ((float)compressedFloat / 32767.5f - 1.0f); return true;} return false;}
bool ReadCompressed(double &var) {unsigned long compressedFloat; if (Read(compressedFloat)) { var = ((double)compressedFloat / 2147483648.0 - 1.0); return true; } return false;}
bool ReadCompressed(long double &var) {unsigned long compressedFloat; if (Read(compressedFloat)) { var = ((long double)compressedFloat / 2147483648.0 - 1.0); return true; } return false;}
bool ReadCompressed(SystemAddress &var) {return Read(var);}
bool ReadCompressed(NetworkID &var) {return Read(var);}
/// Read any integral type from a bitstream. If the written value differed from the value compared against in the write function,
/// var will be updated. Otherwise it will retain the current value.
/// the current value will be updated.
/// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// ReadCompressedDelta is only valid from a previous call to WriteDelta
/// \param[in] var The value to read
bool ReadCompressedDelta(bool &var) {return Read(var);}
bool ReadCompressedDelta(unsigned char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(unsigned short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(unsigned int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(unsigned long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(unsigned long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(float &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
bool ReadCompressedDelta(long double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;}
/// Write an array or casted stream or raw data. This does NOT do endian swapping.
/// \param[in] input a byte buffer
/// \param[in] numberOfBytes the size of \a input in bytes
void Write( const char* input, const int numberOfBytes );
/// Write one bitstream to another
/// \param[in] numberOfBits bits to write
/// \param bitStream the bitstream to copy from
void Write( BitStream *bitStream, int numberOfBits );
void Write( BitStream *bitStream );
/// Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors.
/// Accurate to 1/32767.5.
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
void WriteNormVector( float x, float y, float z );
void WriteNormVector( double x, double y, double z ) {WriteNormVector((float)x,(float)y,(float)z);}
/// Write a vector, using 10 bytes instead of 12.
/// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
void WriteVector( float x, float y, float z );
void WriteVector( double x, double y, double z ) {WriteVector((float)x, (float)y, (float)z);}
/// Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
/// \param[in] w w
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
void WriteNormQuat( float w, float x, float y, float z);
void WriteNormQuat( double w, double x, double y, double z) {WriteNormQuat((float)w, (float) x, (float) y, (float) z);}
/// Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each
/// for 6 bytes instead of 36
/// Lossy, although the result is renormalized
void WriteOrthMatrix(
float m00, float m01, float m02,
float m10, float m11, float m12,
float m20, float m21, float m22 )
{
WriteOrthMatrix((double)m00,(double)m01,(double)m02,
(double)m10,(double)m11,(double)m12,
(double)m20,(double)m21,(double)m22);
}
void WriteOrthMatrix(
double m00, double m01, double m02,
double m10, double m11, double m12,
double m20, double m21, double m22 );
/// Read an array or casted stream of byte. The array
/// is raw data. There is no automatic endian conversion with this function
/// \param[in] output The result byte array. It should be larger than @em numberOfBytes.
/// \param[in] numberOfBytes The number of byte to read
/// \return true on success false if there is some missing bytes.
bool Read( char* output, const int numberOfBytes );
/// Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors.
/// Accurate to 1/32767.5.
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
bool ReadNormVector( float &x, float &y, float &z );
bool ReadNormVector( double &x, double &y, double &z ) {float fx, fy, fz; bool b = ReadNormVector(fx, fy, fz); x=fx; y=fy; z=fz; return b;}
/// Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector
/// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
bool ReadVector( float x, float y, float z );
bool ReadVector( double &x, double &y, double &z ) {return ReadVector((float)x, (float)y, (float)z);}
/// Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes.
/// \param[in] w w
/// \param[in] x x
/// \param[in] y y
/// \param[in] z z
bool ReadNormQuat( float &w, float &x, float &y, float &z){double dw, dx, dy, dz; bool b=ReadNormQuat(dw, dx, dy, dz); w=(float)dw; x=(float)dx; y=(float)dy; z=(float)dz; return b;}
bool ReadNormQuat( double &w, double &x, double &y, double &z);
/// Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolating the 4th.
/// for 6 bytes instead of 36
/// Lossy, although the result is renormalized
bool ReadOrthMatrix(
float &m00, float &m01, float &m02,
float &m10, float &m11, float &m12,
float &m20, float &m21, float &m22 );
bool ReadOrthMatrix(
double &m00, double &m01, double &m02,
double &m10, double &m11, double &m12,
double &m20, double &m21, double &m22 );
///Sets the read pointer back to the beginning of your data.
void ResetReadPointer( void );
/// Sets the write pointer back to the beginning of your data.
void ResetWritePointer( void );
///This is good to call when you are done with the stream to make
/// sure you didn't leave any data left over void
void AssertStreamEmpty( void );
/// RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging.
void PrintBits( void ) const;
/// Ignore data we don't intend to read
/// \param[in] numberOfBits The number of bits to ignore
void IgnoreBits( const int numberOfBits );
/// Ignore data we don't intend to read
/// \param[in] numberOfBits The number of bytes to ignore
void IgnoreBytes( const int numberOfBytes );
///Move the write pointer to a position on the array.
/// \param[in] offset the offset from the start of the array.
/// \attention
/// Dangerous if you don't know what you are doing!
/// For efficiency reasons you can only write mid-stream if your data is byte aligned.
void SetWriteOffset( const int offset );
/// Returns the length in bits of the stream
inline int GetNumberOfBitsUsed( void ) const {return GetWriteOffset();}
inline int GetWriteOffset( void ) const {return numberOfBitsUsed;}
///Returns the length in bytes of the stream
inline int GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );}
///Returns the number of bits into the stream that we have read
inline int GetReadOffset( void ) const {return readOffset;}
// Sets the read bit index
inline void SetReadOffset( int newReadOffset ) {readOffset=newReadOffset;}
///Returns the number of bits left in the stream that haven't been read
inline int GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;}
/// Makes a copy of the internal data for you \a _data will point to
/// the stream. Returns the length in bits of the stream. Partial
/// bytes are left aligned
/// \param[out] _data The allocated copy of GetData()
int CopyData( unsigned char** _data ) const;
/// Set the stream to some initial data.
/// \internal
void SetData( unsigned char *input );
/// Gets the data that BitStream is writing to / reading from
/// Partial bytes are left aligned.
/// \return A pointer to the internal state
inline unsigned char* GetData( void ) const {return data;}
/// Write numberToWrite bits from the input source Right aligned
/// data means in the case of a partial byte, the bits are aligned
/// from the right (bit 0) rather than the left (as in the normal
/// internal representation) You would set this to true when
/// writing user data, and false when copying bitstream data, such
/// as writing one bitstream to another
/// \param[in] input The data
/// \param[in] numberOfBitsToWrite The number of bits to write
/// \param[in] rightAlignedBits if true data will be right aligned
void WriteBits( const unsigned char* input, int numberOfBitsToWrite, const bool rightAlignedBits = true );
/// Align the bitstream to the byte boundary and then write the
/// specified number of bits. This is faster than WriteBits but
/// wastes the bits to do the alignment and requires you to call
/// ReadAlignedBits at the corresponding read position.
/// \param[in] input The data
/// \param[in] numberOfBytesToWrite The size of input.
void WriteAlignedBytes( void *input, const int numberOfBytesToWrite );
/// Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite
/// \param[in] input The data
/// \param[in] inputLength The size of input.
/// \param[in] maxBytesToWrite Max bytes to write
void WriteAlignedBytesSafe( void *input, const int inputLength, const int maxBytesToWrite );
/// Read bits, starting at the next aligned bits. Note that the
/// modulus 8 starting offset of the sequence must be the same as
/// was used with WriteBits. This will be a problem with packet
/// coalescence unless you byte align the coalesced packets.
/// \param[in] output The byte array larger than @em numberOfBytesToRead
/// \param[in] numberOfBytesToRead The number of byte to read from the internal state
/// \return true if there is enough byte.
bool ReadAlignedBytes( void *output, const int numberOfBytesToRead );
/// Reads what was written by WriteAlignedBytesSafe
/// \param[in] input The data
/// \param[in] maxBytesToRead Maximum number of bytes to read
bool ReadAlignedBytesSafe( void *input, int &inputLength, const int maxBytesToRead );
/// Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to
/// \param[in] input input will be deleted if it is not a pointer to 0
bool ReadAlignedBytesSafeAlloc( char **input, int &inputLength, const int maxBytesToRead );
/// Align the next write and/or read to a byte boundary. This can
/// be used to 'waste' bits to byte align for efficiency reasons It
/// can also be used to force coalesced bitstreams to start on byte
/// boundaries so so WriteAlignedBits and ReadAlignedBits both
/// calculate the same offset when aligning.
void AlignWriteToByteBoundary( void );
/// Align the next write and/or read to a byte boundary. This can
/// be used to 'waste' bits to byte align for efficiency reasons It
/// can also be used to force coalesced bitstreams to start on byte
/// boundaries so so WriteAlignedBits and ReadAlignedBits both
/// calculate the same offset when aligning.
void AlignReadToByteBoundary( void );
/// Read \a numberOfBitsToRead bits to the output source
/// alignBitsToRight should be set to true to convert internal
/// bitstream data to userdata. It should be false if you used
/// WriteBits with rightAlignedBits false
/// \param[in] output The resulting bits array
/// \param[in] numberOfBitsToRead The number of bits to read
/// \param[in] alignBitsToRight if true bits will be right aligned.
/// \return true if there is enough bits to read
bool ReadBits( unsigned char *output, int numberOfBitsToRead, const bool alignBitsToRight = true );
/// Write a 0
void Write0( void );
/// Write a 1
void Write1( void );
/// Reads 1 bit and returns true if that bit is 1 and false if it is 0
bool ReadBit( void );
/// If we used the constructor version with copy data off, this
/// *makes sure it is set to on and the data pointed to is copied.
void AssertCopyData( void );
/// Use this if you pass a pointer copy to the constructor
/// *(_copyData==false) and want to overallocate to prevent
/// *reallocation
void SetNumberOfBitsAllocated( const unsigned int lengthInBits );
/// Reallocates (if necessary) in preparation of writing numberOfBitsToWrite
void AddBitsAndReallocate( const int numberOfBitsToWrite );
/// \internal
/// \return How many bits have been allocated internally
unsigned int GetNumberOfBitsAllocated(void) const;
static bool DoEndianSwap(void);
static bool IsBigEndian(void);
static bool IsNetworkOrder(void);
static void ReverseBytes(unsigned char *input, unsigned char *output, int length);
static void ReverseBytesInPlace(unsigned char *data, int length);
private:
BitStream( const BitStream &invalid) {
#ifdef _MSC_VER
#pragma warning(disable:4100)
// warning C4100: 'invalid' : unreferenced formal parameter
#endif
}
/// Assume the input source points to a native type, compress and write it.
void WriteCompressed( const unsigned char* input, const int size, const bool unsignedData );
/// Assume the input source points to a compressed native type. Decompress and read it.
bool ReadCompressed( unsigned char* output, const int size, const bool unsignedData );
int numberOfBitsUsed;
int numberOfBitsAllocated;
int readOffset;
unsigned char *data;
/// true if the internal buffer is copy of the data passed to the constructor
bool copyData;
/// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded
unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE];
};
inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* input, int numberOfBitsToSerialize, const bool rightAlignedBits )
{
if (writeToBitstream)
WriteBits(input,numberOfBitsToSerialize,rightAlignedBits);
else
return ReadBits(input,numberOfBitsToSerialize,rightAlignedBits);
return true;
}
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
#endif // VC6
#endif | [
"[email protected]"
]
| [
[
[
1,
784
]
]
]
|
afd9a7fddd3b8f9b85d15c99f375dbafcdbb7f40 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Symbian/src/ImageConverter.cpp | 1e6b8fa5ff8a121a4b3e584c7fe4f706dea54683 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,949 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd 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 "ImageConverter.h"
#include <imageconversion.h>
#ifndef USE_TRACE
#define USE_TRACE
#endif
#undef USE_TRACE
#ifdef USE_TRACE
#include "TraceMacros.h"
#endif
class CImageConverter* CImageConverter::NewLC(class CImage& aPicture,
class RFs aFs,
const TDesC& aFile,
enum TPriority aPriority)
{
class CImageConverter* self = new (ELeave) CImageConverter(aPicture, aPriority);
CleanupStack::PushL(self);
self->ConstructL(aFs, aFile);
return self;
}
class CImageConverter* CImageConverter::NewL(class CImage& aPicture,
class RFs aFs,
const TDesC& aFile,
enum TPriority aPriority)
{
class CImageConverter* self = CImageConverter::NewLC(aPicture, aFs, aFile, aPriority);
CleanupStack::Pop();
return self;
}
CImageConverter::CImageConverter(class CImage& aPicture,
enum TPriority aPriority) :
CActive(aPriority), iPicture(aPicture), iDecoder(NULL)
{
CActiveScheduler::Add(this);
}
void CImageConverter::ConstructL(RFs aFs, const TDesC& aFile)
{
iDecoder = CImageDecoder::FileNewL(aFs, aFile);
const TFrameInfo& info = iDecoder->FrameInfo();
iBmpRotator = CBitmapRotator::NewL();
iBitmap = new (ELeave) CFbsBitmap();
iBitmap->Create(info.iOverallSizeInPixels, info.iFrameDisplayMode);
if(info.iFlags &
(TFrameInfo::ETransparencyPossible | TFrameInfo::EAlphaChannel)){
iMask = new (ELeave) CFbsBitmap();
iMask->Create(info.iOverallSizeInPixels, EGray256);
iDecoder->Convert(&iStatus, *iBitmap, *iMask);
} else {
iDecoder->Convert(&iStatus, *iBitmap);
}
#ifdef USE_TRACE
TRACE_FUNC();
#endif
SetActive();
}
CImageConverter::~CImageConverter()
{
if(IsActive()){
Cancel();
iPicture.DecodeCanceled();
}
delete iDecoder;
}
void CImageConverter::RunL()
{
if(iStatus == KErrNone){
iPicture.DecodeComplete(iBitmap, iMask);
delete iDecoder;
iDecoder = NULL;
} else if(iStatus == KErrUnderflow){
iDecoder->ContinueConvert(&iStatus);
#ifdef USE_TRACE
TRACE_FUNC();
#endif
SetActive();
}
}
void CImageConverter::DoCancel()
{
iDecoder->Cancel();
}
/****************************************************************************
=============================================================================
* ///////////////////////////////////////////////////////////////////////////
* *
* CImage -- Takes File name as input and call CImageConverter *
* *
* ///////////////////////////////////////////////////////////////////////////
=============================================================================
****************************************************************************/
void CImage::DecodeCanceled()
{
}
CImage::CImage() :
iActive(NULL), iRotateStatus(ERotationNone), iBitmap(NULL), iMask(NULL)
{
iIsReady = EFalse;
}
CImage::~CImage()
{
iFs.Close();
delete iBitmap;
delete iMask;
}
void CImage::DecodeComplete(CFbsBitmap* aBitmap, CFbsBitmap* aMask)
{
delete iBitmap;
delete iMask;
iBitmap = aBitmap;
iMask = aMask;
if(iRotateStatus == ERotationPending)
{
RotateImage();
iRotateStatus = ERotationNone;
}
iIsReady = ETrue;
DrawNow();
}
void CImage::ConstructL()
{
iFs.Connect();
}
void CImage::OpenL( RFs& /*aFs */, const TDesC &aFile )
{
iIsReady = EFalse;
delete iActive;
iActive = NULL;
iActive = CImageConverter::NewL(*this, iFs, aFile);
}
// void CImage::SizeChanged()
// {
// }
void CImage::Draw(const TRect& aRect) const
{
// Draw the parent control
//CEikBorderedControl::Draw(aRect);
// Get the standard graphics context
CWindowGc& gc = SystemGc();
// Gets the control's extent - Don't encroach on the border
TRect rect = Rect();//Border().InnerRect(Rect());
// set the clipping region
gc.SetClippingRect(rect);
if(iMask == NULL && iBitmap != NULL && rect.Intersects(aRect)){
gc.BitBlt(rect.iTl, iBitmap);
} else if(iMask != NULL && iBitmap != NULL && rect.Intersects(aRect)){
TRect pictRect(TPoint(0,0), iBitmap->SizeInPixels());
gc.BitBltMasked(rect.iTl, iBitmap, pictRect, iMask, EFalse);
}
}
void CImage::RotateImageClockwiseL(TImageRotateAngle aAngle)
{
iAngle = aAngle;
iRotateStatus = ERotationPending;
return;
}
void CImage::RotateImage()
{
CBitmapRotator::TRotationAngle LastRotation;
switch (iAngle)
{
case E90Degrees:
LastRotation = CBitmapRotator::ERotation90DegreesClockwise;
break;
case E180Degrees:
//Start an asynchronous process to rotate the bitmap
LastRotation = CBitmapRotator::ERotation180DegreesClockwise;
break;
case E270Degrees:
//Start an asynchronous process to rotate the bitmap
LastRotation = CBitmapRotator::ERotation270DegreesClockwise;
break;
default:
return ;
}
//Start an asynchronous process to rotate the bitmap
delete iBmpRot;
iBmpRot = NULL;
iBmpRot = CImageRotator::NewL(this, LastRotation);
iBmpRot->RotateBitmap();
return ;
}
void CImage::RotationComplete()
{
iRotateStatus = ERotationDone;
}
TSize CImage::GetSize() const
{
return iBitmap->SizeInPixels();
}
TBool CImage::IsReady() const
{
return iIsReady;
}
/*
=============================================================================
* ///////////////////////////////////////////////////////////////////////////
*
* CImage Rotator -- Used to rotate the Bitmap from CImage
*
* ///////////////////////////////////////////////////////////////////////////
=============================================================================
*/
class CImageRotator* CImageRotator::NewLC(class CImage* aPicture,
CBitmapRotator::TRotationAngle aAngle,
enum TPriority aPriority)
{
class CImageRotator* self = new (ELeave) CImageRotator(aPicture, aAngle, aPriority);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
class CImageRotator* CImageRotator::NewL(class CImage* aPicture,
CBitmapRotator::TRotationAngle aAngle,
enum TPriority aPriority)
{
class CImageRotator* self = CImageRotator::NewLC(aPicture, aAngle, aPriority);
CleanupStack::Pop();
return self;
}
CImageRotator::CImageRotator(class CImage* aPicture,
CBitmapRotator::TRotationAngle aAngle,
enum TPriority aPriority) :
CActive(aPriority), iPicture(aPicture), iAngle(aAngle)
{
CActiveScheduler::Add(this);
RotationNum = 0;
}
void CImageRotator::ConstructL()
{
iBmpRotator = CBitmapRotator::NewL();
iBitmap = iPicture->iBitmap;
iMask = iPicture->iMask;
}
CImageRotator::~CImageRotator()
{
if(IsActive()){
Cancel();
}
}
void CImageRotator::RunL()
{
if(iStatus == KErrNone){
if(RotationNum == 1)
{
RotationNum = 2;
iPicture->iBitmap = iBitmap;
if(iMask != NULL)
{
iBmpRotator->Rotate(&iStatus, *iMask, iAngle);
#ifdef USE_TRACE
TRACE_FUNC();
#endif
SetActive();
}
else
{
iPicture->RotationComplete();
DoCancel();
}
}
else if(RotationNum == 2)
{
RotationNum = 3;
iPicture->iMask = iMask;
iPicture->RotationComplete();
DoCancel();
}
}
}
void CImageRotator::DoCancel()
{
}
void CImageRotator::RotateBitmap()
{
RotationNum =1;
iBmpRotator->Rotate(&iStatus, *iBitmap, iAngle);
#ifdef USE_TRACE
TRACE_FUNC();
#endif
SetActive();
}
| [
"[email protected]"
]
| [
[
[
1,
338
]
]
]
|
9f7d9b81cc8bfdc6c4223ad43c7a2512e8fad259 | fb16850c6d70f89751d75413b9c16a7a72821c39 | /src/modules/mouse/sdl/wrap_Mouse.cpp | 152d0eab7cacfe74ba1f0d7c23cee9f07ec9d276 | [
"Zlib"
]
| permissive | tst2005/love | b5e852cc538c957e773cdf14f76d71263887f066 | bdec6facdf6054d24c89bea10b1f6146d89da11f | refs/heads/master | 2021-01-15T12:36:17.510573 | 2010-05-23T22:30:38 | 2010-05-23T22:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,007 | cpp | /**
* Copyright (c) 2006-2010 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "wrap_Mouse.h"
namespace love
{
namespace mouse
{
namespace sdl
{
static Mouse * instance = 0;
int w_getX(lua_State * L)
{
lua_pushnumber(L, instance->getX());
return 1;
}
int w_getY(lua_State * L)
{
lua_pushnumber(L, instance->getY());
return 1;
}
int w_getPosition(lua_State * L)
{
int x, y;
instance->getPosition(x, y);
lua_pushinteger(L, x);
lua_pushinteger(L, y);
return 2;
}
int w_setPosition(lua_State * L)
{
int x = luaL_checkint(L, 1);
int y = luaL_checkint(L, 2);
instance->setPosition(x, y);
return 0;
}
int w_isDown(lua_State * L)
{
Mouse::Button button;
if(!Mouse::getConstant(luaL_checkstring(L, 1), button))
luax_pushboolean(L, false);
else
luax_pushboolean(L, instance->isDown(button));
return 1;
}
int w_setVisible(lua_State * L)
{
bool b = luax_toboolean(L, 1);
instance->setVisible(b);
return 0;
}
int w_isVisible(lua_State * L)
{
luax_pushboolean(L, instance->isVisible());
return 1;
}
int w_setGrap(lua_State * L)
{
bool b = luax_toboolean(L, 1);
instance->setGrab(b);
return 0;
}
int w_isGrabbed(lua_State * L)
{
luax_pushboolean(L, instance->isGrabbed());
return 1;
}
// List of functions to wrap.
static const luaL_Reg functions[] = {
{ "getX", w_getX },
{ "getY", w_getY },
{ "setPosition", w_setPosition },
{ "isDown", w_isDown },
{ "setVisible", w_setVisible },
{ "isVisible", w_isVisible },
{ "getPosition", w_getPosition },
{ "setGrab", w_setGrap },
{ "isGrabbed", w_isGrabbed },
{ 0, 0 }
};
int luaopen_love_mouse(lua_State * L)
{
if(instance == 0)
{
try
{
instance = new Mouse();
}
catch(Exception & e)
{
return luaL_error(L, e.what());
}
}
else
instance->retain();
WrappedModule w;
w.module = instance;
w.name = "mouse";
w.flags = MODULE_T;
w.functions = functions;
w.types = 0;
return luax_register_module(L, w);
}
} // sdl
} // mouse
} // love
| [
"none@none"
]
| [
[
[
1,
140
]
]
]
|
ccd163fb53f622c69783d2dee74c62bed2e104ed | b9c9a4c5e7952e080a53c81a0781180a9bf80257 | /src/document/Document.h | 8bb601f8c90e78d78604c150e888d950e430fd9c | []
| no_license | kaelspencer/confero | 296aa9cd87c0254a662be136a571ffb9675d9fe9 | a41c71fe082017c316bc2f79e00c2b9e3a8ef7eb | refs/heads/master | 2021-01-19T17:47:44.444616 | 2011-06-12T00:25:25 | 2011-06-12T00:25:25 | 1,777,702 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 902 | h | #ifndef DOCUMENT_H
#define DOCUMENT_H
#include <QLinkedList>
#include <QString>
class kDocument
{
private:
QLinkedList<QLinkedList<char> * > * m_doc;
unsigned int m_lines;
unsigned int m_chCount;
QLinkedList<char> * getLine(unsigned int line) const;
QLinkedList<char> * getLine(unsigned int line, QMutableLinkedListIterator<QLinkedList<char> *> & inItor) const;
void calcPos(unsigned int pos, int & line, int & index);
void joinLines(int line);
public:
kDocument();
~kDocument();
kDocument(const kDocument & rhs);
kDocument & operator=(const kDocument & rhs);
void insertAt(unsigned int pos, char ch, int & line, int & index);
void insertAt(int line, int index, char ch);
void removeAt(unsigned int pos, int & line, int & index);
void removeAt(int line, int index);
QString Text() const;
};
#endif
| [
"kael@euler"
]
| [
[
[
1,
33
]
]
]
|
80f5023cd67bead0fabe55f157fe5c4acd7fa2f4 | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /inc/util/yastring.h | 2ec4d268eadbb5cb691f910399ff1a8c8bdee828 | []
| no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,134 | h | /*
* $Id$
*
* Copyright (C) 2009 Dorothea Wachmann
*
* 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/.
*/
#if !defined(YASTRING_H)
#define YASTRING_H
#include "util/yanew.h"
namespace bvr20983
{
namespace util
{
class YAString
{
public:
YAString();
YAString(LPCWSTR str);
YAString(LPCSTR str);
YAString(const YAString& str);
YAString(unsigned long);
YAString(long);
~YAString();
LPCTSTR c_str() const throw();
LPCWSTR w_str() const throw();
LPCSTR a_str() const throw();
operator LPCWSTR() const throw();
operator LPCSTR() const throw();
unsigned int Size() const throw();
void Resize(unsigned int s);
YAString& Append(LPCTSTR);
YAString& Append(unsigned long);
YAString& Append(long);
int IndexOf(LPCTSTR str) const throw();
int IndexOf(TCHAR c) const throw();
int LastIndexOf(LPCTSTR str) const throw();
int LastIndexOf(TCHAR c) const throw();
void ToLowerCase();
void ToUpperCase();
YAPtr<YAString> Substring(int beginIndex,int endIndex=-1) const;
YAString& operator+=(LPCTSTR);
YAString& operator+=(const YAString&);
YAString& operator+=(unsigned long);
YAString& operator+=(long);
YAString& operator=(LPCTSTR);
YAString& operator=(const YAString&);
bool operator==(const YAString&);
bool operator==(LPCTSTR);
bool operator!=(const YAString&);
bool operator!=(LPCTSTR);
private:
std::basic_string<TCHAR> m_str;
void* m_buffer;
unsigned int m_buffersize;
static YAAllocatorBase* m_pClassAllocator;
static YAAllocatorBase* RegisterAllocator();
void FreeBuffer();
void Wide2Ansi();
void Ansi2Wide();
}; // of class YAString
template<class charT, class Traits>
std::basic_ostream<charT, Traits>& operator <<(std::basic_ostream<charT, Traits >& os,const YAString& str);
} // of namespace util
} // of namespace bvr20983
#endif // YASTRING_H
/*==========================END-OF-FILE===================================*/
| [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
]
| [
[
[
1,
90
]
]
]
|
156d718efd6231d9a570ff7492422a95e61de5c2 | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/MpegMux/vac3dec/demux.h | 1540f0342c9c38b0075fa973846ce989ccd7101d | []
| no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 662 | h | #ifndef DEMUX_H
#define DEMUX_H
#include "defs.h"
#define DEMUX_SKIP 0
#define DEMUX_HEADER 1
#define DEMUX_DATA 2
//////////////////////////////////////////////////
// in-place MPEG1/2 PES demuxer
//
// PES-wrapped data in input buffer is replaced by
// unwrapped; length of unwrapped data is returned
class Demux
{
private:
int state;
uint8_t head_buf[268];
int state_bytes;
void move(uint8_t *data, int length);
public:
int errors;
Demux(): errors(0), state(DEMUX_SKIP), state_bytes(0) {};
void reset() { state = DEMUX_SKIP; state_bytes = 0; };
int decode(uint8_t *data, int length);
};
#endif
| [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
]
| [
[
[
1,
35
]
]
]
|
03b376540e2e7585d7dbf73009900fae241d9777 | fb16850c6d70f89751d75413b9c16a7a72821c39 | /src/modules/joystick/sdl/wrap_Joystick.h | 24e8d1e6a5bddb1ae4ff7dee2cfad5fccd91d4f5 | [
"Zlib"
]
| permissive | tst2005/love | b5e852cc538c957e773cdf14f76d71263887f066 | bdec6facdf6054d24c89bea10b1f6146d89da11f | refs/heads/master | 2021-01-15T12:36:17.510573 | 2010-05-23T22:30:38 | 2010-05-23T22:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,755 | h | /**
* Copyright (c) 2006-2010 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_JOYSTICK_SDL_WRAP_JOYSTICK_H
#define LOVE_JOYSTICK_SDL_WRAP_JOYSTICK_H
// LOVE
#include <common/config.h>
#include "Joystick.h"
namespace love
{
namespace joystick
{
namespace sdl
{
int w_getNumJoysticks(lua_State * L);
int w_getName(lua_State * L);
int w_open(lua_State * L);
int w_isOpen(lua_State * L);
int w_getNumAxes(lua_State * L);
int w_getNumBalls(lua_State * L);
int w_getNumButtons(lua_State * L);
int w_getNumHats(lua_State * L);
int w_getAxis(lua_State * L);
int w_getAxes(lua_State * L);
int w_getBall(lua_State * L);
int w_isDown(lua_State * L);
int w_getHat(lua_State * L);
int w_close(lua_State * L);
extern "C" LOVE_EXPORT int luaopen_love_joystick(lua_State * L);
} // sdl
} // joystick
} // love
#endif // LOVE_JOYSTICK_SDL_WRAP_JOYSTICK_H
| [
"none@none"
]
| [
[
[
1,
54
]
]
]
|
e40117a2c51031dc7a91db1d3e12ceafe0f0b7fa | b6bad03a59ec436b60c30fc793bdcf687a21cf31 | /som2416/wince5/sdbus.hpp | a15588c018af3f1c1e1a15ab24ca325ef9fad24c | []
| 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 | 11,727 | hpp | //
// 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.
//
//
//
// 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.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Module Name:
// Sdbus.hpp
// Abstract:
// Definition for the sd bus.
//
//
//
// Notes:
//
//
#pragma once
#include <CSync.h>
#include <CRefCon.h>
#include <defbus.h>
#include "sdworki.hpp"
class CSDBusRequest;
class CSDHost;
class CSDSlot;
#define _countof(x) sizeof(x)/sizeof(x[0])
// bus driver zones
#define SDBUS_ZONE_HCD SDCARD_ZONE_0
#define ENABLE_SDBUS_ZONE_HCD ZONE_ENABLE_0
#define SDBUS_ZONE_DISPATCHER SDCARD_ZONE_1
#define ENABLE_SDBUS_ZONE_DISPATCHER ZONE_ENABLE_1
#define SDCARD_ZONE_SHUTDOWN SDCARD_ZONE_2
#define ENABLE_SDBUS_ZONE_SHUTDOWN ZONE_ENABLE_2
#define SDBUS_ZONE_POWER SDCARD_ZONE_3
#define ENABLE_SDBUS_ZONE_POWER ZONE_ENABLE_3
#define SDBUS_ZONE_DEVICE SDCARD_ZONE_4
#define ENABLE_SDBUS_ZONE_DEVICE ZONE_ENABLE_4
#define SDBUS_ZONE_REQUEST SDCARD_ZONE_5
#define ENABLE_SDBUS_ZONE_REQUEST ZONE_ENABLE_5
#define SDBUS_ZONE_BUFFER SDCARD_ZONE_6
#define ENABLE_SDBUS_ZONE_BUFFER ZONE_ENABLE_6
#define SDBUS_SOFT_BLOCK SDCARD_ZONE_7
#define ENABLE_SDBUS_SOFT_BLOCK ZONE_ENABLE_7
#define BUS_REQUEST_FREE_SPACE_TAG 0xdaada5cc
#define SDCARD_REQUEST_RETRY_KEY TEXT("RequestRetryCount")
#define DEFAULT_BUS_REQUEST_RETRY_COUNT 3
#define SDCARD_THREAD_PRIORITY_KEY TEXT("ThreadPriority")
#define DEFAULT_THREAD_PRIORITY 100
#define SDCARD_PASTPATH_THRESHOLD TEXT("Threshold")
#define DEFAULT_PASTPATH_THRESHOLD 0x800 // 2k.
typedef struct _FREE_BUS_REQUEST_SPACE *PFREE_BUS_REQUEST_SPACE;
typedef struct _FREE_BUS_REQUEST_SPACE {
PFREE_BUS_REQUEST_SPACE pNextFreeTransfer;
DWORD dwFreeSpaceTag;
DWORD dwSpaceSize;
DWORD dwReserved;
} FREE_BUS_REQUEST_SPACE, *PFREE_BUS_REQUEST_SPACE;
#define BUS_VER_STR_2_0 (TEXT("VER 2.0"))
#define BUS_VER_FOR_HOST BUS_VER_STR_2_0
#define SD_MAXIMUM_SLOT_PER_SDHOST 16 // This is limited 4 bit count in device handle.
inline SD_CARD_INTERFACE ConvertFromEx(SD_CARD_INTERFACE_EX sdInterfaceEx)
{
#ifdef _MMC_SPEC_42_
/*************************************************************************/
/****** Date : 07.05.14 ******/
/****** Developer : HS.JANG ******/
/****** Description : to set SD_INTERFACE_MMC_8BIT to SDHC ******/
/*************************************************************************/
SD_INTERFACE_MODE temp;
if ( sdInterfaceEx.InterfaceModeEx.bit.hsmmc8Bit !=0 )
temp = SD_INTERFACE_MMC_8BIT;
else if ( sdInterfaceEx.InterfaceModeEx.bit.sd4Bit !=0 )
temp = SD_INTERFACE_SD_4BIT;
else
temp = SD_INTERFACE_SD_MMC_1BIT;
SD_CARD_INTERFACE sdCardInterface = {
temp,
/*************************************************************************/
#else
SD_CARD_INTERFACE sdCardInterface = {
sdInterfaceEx.InterfaceModeEx.bit.sd4Bit!=0?SD_INTERFACE_SD_4BIT: SD_INTERFACE_SD_MMC_1BIT,
#endif
sdInterfaceEx.ClockRate,
sdInterfaceEx.InterfaceModeEx.bit.sdWriteProtected!=0
};
return sdCardInterface;
}
// Debug Function.
extern "C" {
VOID SDOutputBuffer(__out_bcount(BufferSize) PVOID pBuffer, ULONG BufferSize) ;
BOOLEAN SDPerformSafeCopy(__out_bcount(Length) PVOID pDestination, __in_bcount(Length) const VOID *pSource,ULONG Length);
DWORD SDProcessException(LPEXCEPTION_POINTERS pException) ;
VOID SDCardDebugOutput(TCHAR *pDebugText, ...);
}
class CSDHost:public SDCARD_HC_CONTEXT, public CRefObject {
friend class CSDDevice;
friend class CSDSlot;
public:
CSDHost(DWORD dwNumSlot);
virtual ~CSDHost();
virtual BOOL Init();
virtual BOOL Attach();
virtual BOOL Detach();
BOOL IsAttached() { return m_fHostAttached; };
// SD Host Index.
public:
DWORD GetIndex() { return m_dwSdHostIndex; };
DWORD SetIndex (DWORD dwIndex) { return (m_dwSdHostIndex= dwIndex); };
DWORD GetSlotCount() { return m_dwNumOfSlot; };
CSDSlot * GetSlot(DWORD dwSlot) { return (dwSlot<m_dwNumOfSlot? m_SlotArray[dwSlot]: NULL) ; };
SD_API_STATUS BusRequestHandler(DWORD dwSlot, PSD_BUS_REQUEST pSdBusRequest) {
return pBusRequestHandler((PSDCARD_HC_CONTEXT)this,dwSlot,pSdBusRequest);
}; // bus request handler
SD_API_STATUS SlotOptionHandler(DWORD dwSlot, SD_SLOT_OPTION_CODE sdSlotOption, PVOID pvParam, ULONG uSize) { // slot option handler
return pSlotOptionHandler((PSDCARD_HC_CONTEXT)this,dwSlot,sdSlotOption,pvParam,uSize);
}
BOOL CancelIOHandler(DWORD dwSlot, PSD_BUS_REQUEST psdBusRequest) { // cancel request handler
return pCancelIOHandler((PSDCARD_HC_CONTEXT)this,dwSlot,psdBusRequest);
}
SD_API_STATUS InitHandler () { return pInitHandler((PSDCARD_HC_CONTEXT)this); }; // init handler
SD_API_STATUS DeinitHandler() { return pDeinitHandler((PSDCARD_HC_CONTEXT)this); }; // deinit handler
SD_API_STATUS ChangeCardPowerHandler(DWORD dwSlot, INT iPower) { ; // Pointer to power control handler
return pChangeCardPowerHandler((PSDCARD_HC_CONTEXT)this,dwSlot,iPower);
}
VOID SDHCAccessLock() {
EnterCriticalSection(&HCCritSection);
}
VOID SDHCAccessUnlock() {
LeaveCriticalSection(&HCCritSection);
}
protected:
DWORD m_dwSdHostIndex;
BOOL m_fIntialized;
BOOL m_fHostAttached;
SD_API_STATUS SlotSetupInterface(DWORD dwSlot, PSD_CARD_INTERFACE_EX psdCardInterfaceEx );
static SD_API_STATUS DefaultChangeCardPower(PSDCARD_HC_CONTEXT pHCCardContext,DWORD Slot,INT CurrentDelta);
// SD Slot.
private:
const DWORD m_dwNumOfSlot;
CSDSlot * m_SlotArray[ SD_MAXIMUM_SLOT_PER_SDHOST ];
};
#define SD_MAXIMUM_SDHOST 16
#define SD_SUB_BUSNAME_VALNAME TEXT("SubBusName") // device's name on the parent bus
#define SD_SUB_BUSNAME_VALTYPE REG_SZ
#define SD_SUB_BUSNAME_DEFAULT TEXT("SDBus")
class CSDHostContainerClass : public CStaticContainer <CSDHost, SD_MAXIMUM_SDHOST > {
};
class CSDHostContainer :public DefaultBusDriver, protected CSDHostContainerClass {
public:
CSDHostContainer(LPCTSTR pszActiveKey);
~CSDHostContainer();
virtual BOOL Init();
virtual DWORD GetBusNamePrefix(LPTSTR pszReturnBusName, DWORD cchReturnBusName);
virtual BOOL IOControl(DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut);
virtual BOOL SDC_IOControl(DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut);
// Help Function
static DWORD GetRetryCount() { return g_pSdContainer!=NULL? g_pSdContainer->m_BusRequestRetryCount: 0; };
protected:
virtual DWORD GetSlotInfo(PBUS_DRIVER_SLOT_INFO pslotInfoArray, DWORD Length) ;
virtual SD_API_STATUS GetSlotPowerControlInfo(DWORD slotIndexWanted,PSLOT_POWER_DATA pPCdata) ;
virtual SD_API_STATUS GetFunctionPowerControlInfo(DWORD slotIndexWanted, DWORD FunctionIndexWanted, PFUNCTION_POWER_DATA pFPCdata) ;
virtual SD_API_STATUS SetSlotPowerControl(DWORD slotIndexWanted, BOOL fEnablePowerControl);
virtual BOOL SlotCardSelectDeselect(DWORD SlotIndexWanted, SD_SLOT_EVENT Event) ;
private:
TCHAR m_szSubBusNamePrefix[DEVNAME_LEN];
CRegistryEdit m_deviceKey;
PFREE_BUS_REQUEST_SPACE m_pFreeBusRequestSpace;
DWORD m_dwMinSize;
DWORD m_BusRequestRetryCount;
PVOID AllocateBusRequestImp(size_t stSize);
void FreeBusRequestImp(CSDBusRequest *pBusRequest);
void DeleteAllTransferSpace();
public:
LPCTSTR GetSubBusNamePrefix();
static PVOID AllocateBusRequest(size_t stSize);
static void FreeBusRequest(CSDBusRequest *pBusRequest);
static CSDHostContainer * GetHostContainer () { return g_pSdContainer; };
static DWORD RegValueDWORD(LPTSTR lpRegName,DWORD dwDefault);
static PVOID DriverInit(LPCTSTR pszActiveKey);
static VOID DriverDeInit(PVOID pContent);
static CRegistryEdit& GetDeviceKey() {
PREFAST_ASSERT(g_pSdContainer!=NULL);
return g_pSdContainer->m_deviceKey;
}
static CSDHost * GetSDHost(DWORD dwIndex) {
PREFAST_ASSERT(g_pSdContainer!=NULL);
return g_pSdContainer->ObjectIndex(dwIndex);
}
static CSDHost * GetSDHost(CSDHost * pUnknowHost);
static CSDDevice * GetDeviceByDevice(HANDLE hDevice);
static CSDDevice * GetDeviceByRequest(HANDLE hDevice);
private:
BOOL GetHCandSlotbySlotIndex(CSDHost ** ppHost,CSDSlot**ppSlot,DWORD dwIndex );
public:
static CSDHost * InsertSDHost(CSDHost * psdHost ) {
PREFAST_ASSERT(g_pSdContainer!=NULL);
DWORD dwIndex;
if (psdHost) {
g_pSdContainer->CSDHostContainerClass::Lock();
psdHost = g_pSdContainer->InsertObjectAtEmpty(&dwIndex,psdHost);
if (psdHost)
psdHost->SetIndex(dwIndex);
g_pSdContainer->CSDHostContainerClass::Unlock();
return psdHost;
}
else
return NULL;
}
static CSDHost * RemoveSDHostBy(DWORD dwIndex) {
PREFAST_ASSERT(g_pSdContainer!=NULL);
return g_pSdContainer->RemoveObjectBy(dwIndex);
}
static CSDHost * RemoveSDHostBy(CSDHost * pSd) {
PREFAST_ASSERT(g_pSdContainer!=NULL);
return g_pSdContainer->RemoveObjectBy(pSd);
}
// Host HC Interface.
static SD_API_STATUS SDHCDAllocateContext__X(DWORD NumberOfSlots, PSDCARD_HC_CONTEXT *ppExternalHCContext);
static SD_API_STATUS SDHCDRegisterHostController__X(PSDCARD_HC_CONTEXT pExternalHCContext);
static SD_API_STATUS SDHCDDeregisterHostController__X(PSDCARD_HC_CONTEXT pExternalHCContext);
static VOID SDHCDDeleteContext__X(PSDCARD_HC_CONTEXT pExternalHCContext);
static VOID SDHCDPowerUpDown__X(PSDCARD_HC_CONTEXT pExternalHCContext,BOOL PowerUp,BOOL SlotKeepPower, DWORD SlotIndex);
static VOID SDHCDIndicateBusRequestComplete__X(PSDCARD_HC_CONTEXT pExternalHCContext,PSD_BUS_REQUEST pRequest, SD_API_STATUS Status);
static PSD_BUS_REQUEST SDHCDGetAndLockCurrentRequest__X(PSDCARD_HC_CONTEXT pExternalHCContext, DWORD SlotIndex);
static VOID SDHCDUnlockRequest__X(PSDCARD_HC_CONTEXT pExternalHCContext,PSD_BUS_REQUEST pRequest);
static VOID SDHCDIndicateSlotStateChange__X(PSDCARD_HC_CONTEXT pExternalHCContext, DWORD SlotNumber, SD_SLOT_EVENT Event);
private:
static CSDHostContainer * g_pSdContainer;
};
| [
"[email protected]"
]
| [
[
[
1,
269
]
]
]
|
fe990aa63518b5520f84abebb268426829b71af0 | f9ed86de48cedc886178f9e8c7ee4fae816ed42d | /src/shaders/standarddiffuse.h | 7d239a82d2f92717a8753036f23d97d94c9f63a0 | [
"MIT"
]
| permissive | rehno-lindeque/Flower-of-Persia | bf78d144c8e60a6f30955f099fe76e4a694ec51a | b68af415a09b9048f8b8f4a4cdc0c65b46bcf6d2 | refs/heads/master | 2021-01-25T04:53:04.951376 | 2011-01-29T11:41:38 | 2011-01-29T11:41:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,946 | h | #ifndef __STANDARD_DIFFUSE_H__
#define __STANDARD_DIFFUSE_H__
// This is a per-pixel diffuse shader
const char* diffuseVertexProgram = "\
varying vec3 normal;\n\
varying vec3 vertex_to_light_vector;\n\
varying vec2 texcoord;\n\
void main()\n\
{\n\
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n\
normal = gl_NormalMatrix * gl_Normal;\n\
vec4 vertex_in_modelview_space = gl_ModelViewMatrix * gl_Vertex;\n\
vertex_to_light_vector = (gl_LightSource[0].position-vertex_in_modelview_space).xyz;\n\
texcoord = vec2(gl_MultiTexCoord0);\n\
}";
const char* diffuseFragmentProgram = \
"varying vec3 normal;\n\
varying vec3 vertex_to_light_vector;\n\
varying vec2 texcoord;\n\
uniform sampler2D diffuseTexture;\n\
varying vec3 realcoord;\n\
void main()\n\
{\n\
vec4 AmbientColor = vec4(0.0, 0.0, 0.0, 1.0);\n\
vec4 DiffuseColor = texture2D(diffuseTexture, texcoord);\n\
vec3 normalized_normal = normalize(normal);\n\
vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);\n\
vec4 light_color = clamp(dot(normalized_normal, normalized_vertex_to_light_vector), 0.0, 1.0) * gl_LightSource[0].diffuse;\n\
gl_FragColor = AmbientColor + DiffuseColor * light_color;\n\
}";
const char* diffuseVertexProgram2Lights = "\
varying vec3 normal;\n\
varying vec3 vertex_to_light1;\n\
varying vec3 vertex_to_light2;\n\
varying vec2 texcoord;\n\
void main()\n\
{\n\
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n\
normal = gl_NormalMatrix * gl_Normal;\n\
vec4 vertex_in_modelview_space = gl_ModelViewMatrix * gl_Vertex;\n\
vertex_to_light1 = (gl_LightSource[0].position-vertex_in_modelview_space).xyz;\n\
vertex_to_light2 = (gl_LightSource[1].position-vertex_in_modelview_space).xyz;\n\
texcoord = vec2(gl_MultiTexCoord0);\n\
}";
const char* diffuseFragmentProgram2Lights = \
"varying vec3 normal;\n\
varying vec3 vertex_to_light1;\n\
varying vec3 vertex_to_light2;\n\
varying vec2 texcoord;\n\
uniform sampler2D diffuseTexture;\n\
varying vec3 realcoord;\n\
void main()\n\
{\n\
vec4 AmbientColor = vec4(0.0, 0.0, 0.0, 1.0);\n\
vec4 DiffuseColor = texture2D(diffuseTexture, texcoord);\n\
vec3 normalized_normal = normalize(normal);\n\
vec3 normalized_vertex_to_light1 = normalize(vertex_to_light1);\n\
vec3 normalized_vertex_to_light2 = normalize(vertex_to_light2);\n\
vec4 light1_color = clamp(dot(normalized_normal, normalized_vertex_to_light1), 0.0, 1.0) * gl_LightSource[0].diffuse;\n\
vec4 light2_color = clamp(dot(normalized_normal, normalized_vertex_to_light2), 0.0, 1.0) * gl_LightSource[1].diffuse;\n\
gl_FragColor = AmbientColor + DiffuseColor * (light1_color + light2_color);\n\
}";
template<int lights = 1>
class StandardDiffuseShader : public Shader
{
protected:
int diffuseTexture_sampler_uniform_location;
public:
StandardDiffuseShader() : Shader(diffuseVertexProgram, diffuseFragmentProgram)
{}
void setTexture(int textureID)
{
glUniform1iARB(diffuseTexture_sampler_uniform_location, textureID);
}
void build()
{
Shader::build();
diffuseTexture_sampler_uniform_location = glGetUniformLocationARB(programObject, "diffuseTexture");
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, textures.get(0));
}
};
template<>
class StandardDiffuseShader<2> : public Shader
{
protected:
int diffuseTexture_sampler_uniform_location;
public:
StandardDiffuseShader() : Shader(diffuseVertexProgram2Lights, diffuseFragmentProgram2Lights)
{}
void setTexture(int textureID)
{
glUniform1iARB(diffuseTexture_sampler_uniform_location, textureID);
}
void build()
{
Shader::build();
diffuseTexture_sampler_uniform_location = glGetUniformLocationARB(programObject, "diffuseTexture");
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, textures.get(0));
}
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
fe2c3b9a1bf685681270f8a75c4ade8bf2af2003 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Core/ComponentBaseClasses/elxResampleInterpolatorBase.h | a1b04e46ba8d01725207bc0835502338c1ed1b6a | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,647 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxResampleInterpolatorBase_h
#define __elxResampleInterpolatorBase_h
/** Needed for the macros */
#include "elxMacro.h"
#include "elxBaseComponentSE.h"
#include "itkInterpolateImageFunction.h"
namespace elastix
{
using namespace itk;
/**
* \class ResampleInterpolatorBase
* \brief This class is the elastix base class for all ResampleInterpolators.
*
* This class contains all the common functionality for ResampleInterpolators.
*
* \ingroup ResampleInterpolators
* \ingroup ComponentBaseClasses
*/
template <class TElastix>
class ResampleInterpolatorBase : public BaseComponentSE<TElastix>
{
public:
/** Standard ITK stuff. */
typedef ResampleInterpolatorBase Self;
typedef BaseComponentSE<TElastix> Superclass;
/** Run-time type information (and related methods). */
itkTypeMacro( ResampleInterpolatorBase, BaseComponentSE );
/** Typedef's from superclass. */
typedef typename Superclass::ElastixType ElastixType;
typedef typename Superclass::ElastixPointer ElastixPointer;
typedef typename Superclass::ConfigurationType ConfigurationType;
typedef typename Superclass::ConfigurationPointer ConfigurationPointer;
typedef typename Superclass::RegistrationType RegistrationType;
typedef typename Superclass::RegistrationPointer RegistrationPointer;
/** Typedef's from elastix. */
typedef typename ElastixType::MovingImageType InputImageType;
typedef typename ElastixType::CoordRepType CoordRepType;
/** Other typedef's. */
typedef InterpolateImageFunction<
InputImageType, CoordRepType > ITKBaseType;
/** Cast ti ITKBaseType. */
virtual ITKBaseType * GetAsITKBaseType(void)
{
return dynamic_cast<ITKBaseType *>(this);
}
/** Cast to ITKBaseType, to use in const functions. */
virtual const ITKBaseType * GetAsITKBaseType(void) const
{
return dynamic_cast<const ITKBaseType *>(this);
}
/** Execute stuff before the actual transformation:
* \li nothing here
*/
virtual int BeforeAllTransformix( void ){ return 0;};
/** Function to read transform-parameters from a file. */
virtual void ReadFromFile( void );
/** Function to write transform-parameters to a file. */
virtual void WriteToFile( void ) const;
protected:
/** The constructor. */
ResampleInterpolatorBase() {}
/** The destructor. */
virtual ~ResampleInterpolatorBase() {}
private:
/** The private constructor. */
ResampleInterpolatorBase( const Self& ); // purposely not implemented
/** The private copy constructor. */
void operator=( const Self& ); // purposely not implemented
}; // end class ResampleInterpolatorBase
} //end namespace elastix
#ifndef ITK_MANUAL_INSTANTIATION
#include "elxResampleInterpolatorBase.hxx"
#endif
#endif // end #ifndef __elxResampleInterpolatorBase_h
| [
"[email protected]"
]
| [
[
[
1,
113
]
]
]
|
9e084c09ac61027a2f231f362c86f6b644950557 | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/weak_ptr.hpp | 8d8fe1fee120437b1b748483af202a851e6d0c9b | []
| no_license | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 4,160 | hpp | #ifndef BOOST_WEAK_PTR_HPP_INCLUDED
#define BOOST_WEAK_PTR_HPP_INCLUDED
//
// weak_ptr.hpp
//
// Copyright (c) 2001, 2002, 2003 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/smart_ptr/weak_ptr.htm for documentation.
//
#include <memory> // boost.TR1 include order fix
#include <boost/detail/shared_count.hpp>
#include <boost/shared_ptr.hpp>
#ifdef BOOST_MSVC // moved here to work around VC++ compiler crash
# pragma warning(push)
# pragma warning(disable:4284) // odd return type for operator->
#endif
namespace boost
{
template<class T> class weak_ptr
{
private:
// Borland 5.5.1 specific workarounds
typedef weak_ptr<T> this_type;
public:
typedef T element_type;
weak_ptr(): px(0), pn() // never throws in 1.30+
{
}
// generated copy constructor, assignment, destructor are fine
//
// The "obvious" converting constructor implementation:
//
// template<class Y>
// weak_ptr(weak_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws
// {
// }
//
// has a serious problem.
//
// r.px may already have been invalidated. The px(r.px)
// conversion may require access to *r.px (virtual inheritance).
//
// It is not possible to avoid spurious access violations since
// in multithreaded programs r.px may be invalidated at any point.
//
template<class Y>
#if !defined( BOOST_SP_NO_SP_CONVERTIBLE )
weak_ptr( weak_ptr<Y> const & r, typename detail::sp_enable_if_convertible<Y,T>::type = detail::sp_empty() )
#else
weak_ptr( weak_ptr<Y> const & r )
#endif
: pn(r.pn) // never throws
{
px = r.lock().get();
}
template<class Y>
#if !defined( BOOST_SP_NO_SP_CONVERTIBLE )
weak_ptr( shared_ptr<Y> const & r, typename detail::sp_enable_if_convertible<Y,T>::type = detail::sp_empty() )
#else
weak_ptr( shared_ptr<Y> const & r )
#endif
: px( r.px ), pn( r.pn ) // never throws
{
}
#if !defined(BOOST_MSVC) || (BOOST_MSVC >= 1300)
template<class Y>
weak_ptr & operator=(weak_ptr<Y> const & r) // never throws
{
px = r.lock().get();
pn = r.pn;
return *this;
}
template<class Y>
weak_ptr & operator=(shared_ptr<Y> const & r) // never throws
{
px = r.px;
pn = r.pn;
return *this;
}
#endif
shared_ptr<T> lock() const // never throws
{
return shared_ptr<element_type>( *this, boost::detail::sp_nothrow_tag() );
}
long use_count() const // never throws
{
return pn.use_count();
}
bool expired() const // never throws
{
return pn.use_count() == 0;
}
void reset() // never throws in 1.30+
{
this_type().swap(*this);
}
void swap(this_type & other) // never throws
{
std::swap(px, other.px);
pn.swap(other.pn);
}
void _internal_assign(T * px2, boost::detail::shared_count const & pn2)
{
px = px2;
pn = pn2;
}
template<class Y> bool _internal_less(weak_ptr<Y> const & rhs) const
{
return pn < rhs.pn;
}
// Tasteless as this may seem, making all members public allows member templates
// to work in the absence of member template friends. (Matthew Langston)
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
private:
template<class Y> friend class weak_ptr;
template<class Y> friend class shared_ptr;
#endif
T * px; // contained pointer
boost::detail::weak_count pn; // reference counter
}; // weak_ptr
template<class T, class U> inline bool operator<(weak_ptr<T> const & a, weak_ptr<U> const & b)
{
return a._internal_less(b);
}
template<class T> void swap(weak_ptr<T> & a, weak_ptr<T> & b)
{
a.swap(b);
}
} // namespace boost
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
#endif // #ifndef BOOST_WEAK_PTR_HPP_INCLUDED
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
]
| [
[
[
1,
182
]
]
]
|
a5cc086e1a36638ddc5eb103dc6af36801aa7316 | 5fa8f06181e88d96a9166cb238d05b185ebe7a92 | /sliq_inc/incremental_engine.cc | 262c7d2c1e8c4bd419d100b1fdb8fd5e82c60b24 | []
| no_license | mohitkg/sliqimp | 6834092760a8a078428876baaa7cdab91b37e355 | 54f05bc55ad9c6b7e73abc51fcc0bd8e995d6b69 | refs/heads/master | 2016-09-07T07:13:04.793483 | 2007-06-20T10:49:44 | 2007-06-20T10:49:44 | 33,323,734 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,495 | cc | #include "incremental_engine.hh"
// Pour trouver l'arbre idéal, faire tourner sliq sur un exemple d'exemple
// représentant toutes les possibilités (en proportions correctes)
// Attention les classes suivantes n'ont pas toutes le même cardinal!
// Algo d'abord équiprobable de tomber sur chaque couleur:
// - on tire un nombre entre 1 et 6 (+ une chance de généner un truc complètement aléatoire qui pourra être du bruit)
// -
// plus simple:
// on tire trois chiffre au hasard entre 0 et 255, on vérifie si c'est une des couleurs,
// si oui -> ok, si non -> ok avec une tt petite proba
#define R 0
#define G 1
#define B 2
#define Rouge 1
#define Vert 2
#define Bleu 3
#define Jaune 4
#define Violet 5
#define Cyan 6
#define Bruit 7
int alea(int n)
{
int partSize = (n == RAND_MAX) ? 1 : 1 + (RAND_MAX - n)/(n+1);
int maxUsefull = partSize * n + (partSize-1);
int draw;
do
{
draw = rand();
}
while (draw > maxUsefull);
return draw/partSize;
}
namespace Incremental_sliq
{
Engine::Engine (std::string config_filename, std::vector<std::vector<int> > *examples)
{
srand((int)time(NULL));
*examples = load_examples(config_filename);
}
Sliq::Node *Engine::init_node(int id, int nb_classes)
{
return new Node(id, nb_classes);
}
void Engine::test(std::vector<Example> data)
{
int cpt = 0;
int good = 0;
std::vector<int> cpts;
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
cpts.push_back(0);
for (std::vector<std::vector<int> >::iterator it = data.begin ();
it != data.end ();
++it)
{
cpt++;
cpts[get_class(*it)]++;
// std::cout << "classify : " << engine_->classify(*it) << " ::: " << get_class(*it) << std::endl;
if (classify(*it) == get_class(*it))
good++;
else
{
(*it).push_back(classify(*it));
(*it).push_back(get_class(*it));
error_log_.push_back(*it);
}
}
std::cout << "Resultat pour " << cpt << " donnees : " << std::endl;
for (int i = 1; i < 8; ++i)
std::cout << i << ":" << (double) cpts[i] / cpt << std::endl;
std::cout << "Bien classifie : " << 100 * (double) good / cpt << " %" << std::endl;
std::cout << "---------" << std::endl;
update_tree_with_errors();
}
Example &Engine::generate_data ()
{
Example *result = new Example ();
int r = 0;
int g = 0;
int b = 0;
int cpt = 0;
result->push_back(r);
result->push_back(g);
result->push_back(b);
while (1)
{
(*result)[R] = alea(255);
(*result)[G] = alea(255);
(*result)[B] = alea(255);
if (get_class(*result) != Bruit)
{
// std::cout << cpt << std::endl;
return *result;
}
cpt++;
if (cpt > 10)
return *result;
}
return *result;
}
int Engine::get_class(Example &ex)
{
// rouge : R > G && R > B && abs(G - B) <= 20 && R - G >= 70
if (ex[R] > ex[G] && ex[R] > ex[B] && abs(ex[G] - ex[B]) <= 20 && ex[R] - ex[G] >= 70)
return Rouge;
// vert : G > R && G > B && abs(R - B) <= 20 && G - R >= 70
if (ex[G] > ex[R] && ex[G] > ex[B] && abs(ex[R] - ex[B]) <= 20 && ex[G] - ex[R] >= 70)
return Vert;
// bleu : B > R && B > G && abs(R - G) <= 20 && B - R >= 70
if (ex[B] > ex[R] && ex[B] > ex[G] && abs(ex[R] - ex[G]) <= 20 && ex[B] - ex[R] >= 70)
return Bleu;
// violet : B > G && R > G && abs(R - B) <= 20 && B - G >= 30
if (ex[B] > ex[G] && ex[R] > ex[G] && abs(ex[R] - ex[B]) <= 20 && ex[B] - ex[G] >= 30)
return Violet;
// jaune : R > B && G > B && abs(R - G) <= 20 && R - B >= 130
if (ex[R] > ex[B] && ex[G] > ex[B] && abs(ex[R] - ex[G]) <= 20 && ex[R] - ex[B] >= 100 /* 130 */)
return Jaune;
// cyan : B > R && G > R && abs(B - G) <= 20 && B - R >= 40
if (ex[B] > ex[R] && ex[G] > ex[R] && abs(ex[B] - ex[G]) <= 20 && ex[B] - ex[R] >= 40)
return Cyan;
else
return Bruit;
}
void Engine::update_tree_with_errors()
{
for (std::vector<Example>::iterator it = error_log_.begin ();
it != error_log_.end ();
++it)
{
Node *node = dynamic_cast<Node *>(tree_);
while (node)
{
int attribute = node->test_get().attribute_get ();
int lim = node->test_get().lim_get ();
node->error_set((*it)[attribute_names_.size () + 1]);
if ((*it)[attribute] <= lim)
node = dynamic_cast<Node *>(node->fg_get ());
else
node = dynamic_cast<Node *>(node->fd_get ());
}
}
}
}
| [
"davidlandais@af1a0f03-5433-0410-83de-a7259e581374"
]
| [
[
[
1,
173
]
]
]
|
7c63853b872a447a8bab36d22491bca90f117456 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/wspr/ws_thread.cpp | 096cffc787cc5b03e0b19d64b44d2aef36d7067d | []
| no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | cpp | #include "ws_thread.h"
ws_thread::ws_thread(void)
{
}
ws_thread::~ws_thread(void)
{
}
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
12
]
]
]
|
09d2dac5c542dee4a00db616fd6e0266b0f9490d | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /src/com/sc/coenumconnections.cpp | d263824253ee176885ebdbdb92561d8f0daf9a1f | []
| no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,348 | cpp | /*
* $Id$
*
* Connection point object that manages IUnknown pointers.
* This is a stand-alone object created from the implementation of IConnectionPointContainer.
*
* Copyright (C) 2008 Dorothea Wachmann
*
* 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 "os.h"
#include "com/coenumconnections.h"
namespace bvr20983
{
namespace COM
{
/*
* COEnumConnections::COEnumConnections
* COEnumConnections::~COEnumConnections
*
* Parameters (Constructor):
* pUnkRef LPUNKNOWN to use for reference counting.
* cConn ULONG number of connections in prgpConn
* prgConnData LPCONNECTDATA to the array to enumerate.
*/
COEnumConnections::COEnumConnections(ULONG cConn, LPCONNECTDATA prgConnData)
{ m_cRef = 0;
m_iCur = 0;
m_cConn = cConn;
m_rgConnData = new CONNECTDATA[(UINT)cConn];
UINT i;
if( NULL!=m_rgConnData )
for( i=0; i < cConn; i++ )
{ m_rgConnData[i]=prgConnData[i];
if( NULL!=m_rgConnData[i].pUnk )
m_rgConnData[i].pUnk->AddRef();
} // of for
} // of COEnumConnections::COEnumConnections()
/**
*
*/
COEnumConnections::~COEnumConnections()
{ if( NULL!=m_rgConnData )
{ UINT i;
for( i=0; i < m_cConn; i++ )
RELEASE_INTERFACE( m_rgConnData[i].pUnk );
delete [] m_rgConnData;
} // of if
} // of COEnumConnections::~COEnumConnections()
/*
* COEnumConnections::QueryInterface
* COEnumConnections::AddRef
* COEnumConnections::Release
*
* Purpose:
* IUnknown members for COEnumConnections object.
*/
STDMETHODIMP COEnumConnections::QueryInterface(REFIID riid, LPVOID *ppv)
{ HRESULT result = E_NOINTERFACE;
*ppv=NULL;
if( IID_IUnknown==riid || IID_IEnumConnections==riid )
*ppv=(LPVOID)this;
if( NULL!=*ppv )
{ ((LPUNKNOWN)*ppv)->AddRef();
result = NOERROR;
}
return result;
} // of COEnumConnections::QueryInterface()
/**
*
*/
STDMETHODIMP_(ULONG) COEnumConnections::AddRef()
{ ++m_cRef;
return m_cRef;
}
/**
*
*/
STDMETHODIMP_(ULONG) COEnumConnections::Release()
{ ULONG result = --m_cRef;
if( result<=0 )
delete this;
return result;
}
/*
*
*/
STDMETHODIMP COEnumConnections::Next(ULONG cConn, LPCONNECTDATA pConnData, ULONG *pulEnum)
{ HRESULT result = S_FALSE;
ULONG cReturn = 0L;
if( NULL!=m_rgConnData )
{ if( NULL==pulEnum && 1L!=cConn )
result = E_POINTER;
else
{ if( NULL!=pulEnum )
*pulEnum=0L;
if( NULL!=pConnData && m_iCur < m_cConn )
{
while( m_iCur<m_cConn && cConn>0 )
{ *pConnData++ = m_rgConnData[m_iCur];
if( NULL!=m_rgConnData[m_iCur].pUnk )
m_rgConnData[m_iCur++].pUnk->AddRef();
cReturn++;
cConn--;
} // of while
if( NULL!=pulEnum )
*pulEnum=cReturn;
result = NOERROR;
} // of if
} // of else
} // of if
return result;
} // of COEnumConnections::Next()
/**
*
*/
STDMETHODIMP COEnumConnections::Skip(ULONG cSkip)
{ HRESULT result = S_FALSE;
if( ((m_iCur+cSkip)<m_cConn) && NULL!=m_rgConnData )
{ result = NOERROR;
m_iCur+=cSkip;
} // of if
return NOERROR;
} // of COEnumConnections::Skip()
/**
*
*/
STDMETHODIMP COEnumConnections::Reset()
{ m_iCur=0;
return NOERROR;
} // of COEnumConnections::Reset()
/**
*
*/
STDMETHODIMP COEnumConnections::Clone(LPENUMCONNECTIONS* ppEnum)
{ HRESULT result = NOERROR;
*ppEnum = NULL;
//Create the clone
COEnumConnections* pNew = new COEnumConnections( m_cConn, m_rgConnData);
if( NULL!=pNew )
{ pNew->AddRef();
pNew->m_iCur=m_iCur;
*ppEnum=pNew;
} // of else
else
result = E_OUTOFMEMORY;
return result;
} // of COEnumConnections::Clone()
} // of namespace COM
} // of namespace bvr20983
/*==========================END-OF-FILE===================================*/
| [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
]
| [
[
[
1,
199
]
]
]
|
9a4558c8e0423b24a5ff809767fab528e13145b7 | 448ef6f020ff51ef3c4266e2504a49e18c032d04 | /CppTest/CppTest/Debug.h | 6d900bb694ef1428053494a6a60e14f3739edead | []
| no_license | weeeBox/oldies-cpp-template | f0990a1832e0f441db8523932a19a6addf16d620 | 00223721d33f95b396dc698a5596199224291e8b | refs/heads/master | 2020-05-20T07:33:33.792823 | 2011-12-09T16:45:10 | 2011-12-09T16:45:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 145 | h | #ifndef Debug_h__
#define Debug_h__
#include <cstdlib>
#include <iostream>
#define ASSERT(exp) if(!(exp)) abort();
#endif // Debug_h__ | [
"[email protected]@29e91505-0bf5-f861-a13c-499aeb2b9760"
]
| [
[
[
1,
9
]
]
]
|
e6d994a3f2dca720008d32791d51d2865c8dcaac | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/util/ParseException.hpp | 519451f51446be82df1fc06b3f00364b4bfd612f | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 989 | hpp | /*
* Copyright 2001,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: ParseException.hpp,v 1.3 2004/09/08 13:56:22 peiyongz Exp $
*/
#if !defined(PARSEEXCEPTION_HPP)
#define PARSEEXCEPTION_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
MakeXMLException(ParseException, XMLUTIL_EXPORT)
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
e5cd7f0295c9e11c0317f79d2567f3954a5e0b8b | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_graphics/geometry/juce_Path.cpp | 72454ca69d9e309aea162b5808cd1e031e708988 | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,354 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
// tests that some co-ords aren't NaNs
#define JUCE_CHECK_COORDS_ARE_VALID(x, y) \
jassert (x == x && y == y);
//==============================================================================
namespace PathHelpers
{
const float ellipseAngularIncrement = 0.05f;
String nextToken (String::CharPointerType& t)
{
t = t.findEndOfWhitespace();
String::CharPointerType start (t);
size_t numChars = 0;
while (! (t.isEmpty() || t.isWhitespace()))
{
++t;
++numChars;
}
return String (start, numChars);
}
inline double lengthOf (float x1, float y1, float x2, float y2) noexcept
{
return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
}
}
//==============================================================================
const float Path::lineMarker = 100001.0f;
const float Path::moveMarker = 100002.0f;
const float Path::quadMarker = 100003.0f;
const float Path::cubicMarker = 100004.0f;
const float Path::closeSubPathMarker = 100005.0f;
//==============================================================================
Path::Path()
: numElements (0),
pathXMin (0),
pathXMax (0),
pathYMin (0),
pathYMax (0),
useNonZeroWinding (true)
{
}
Path::~Path()
{
}
Path::Path (const Path& other)
: numElements (other.numElements),
pathXMin (other.pathXMin),
pathXMax (other.pathXMax),
pathYMin (other.pathYMin),
pathYMax (other.pathYMax),
useNonZeroWinding (other.useNonZeroWinding)
{
if (numElements > 0)
{
data.setAllocatedSize ((int) numElements);
memcpy (data.elements, other.data.elements, numElements * sizeof (float));
}
}
Path& Path::operator= (const Path& other)
{
if (this != &other)
{
data.ensureAllocatedSize ((int) other.numElements);
numElements = other.numElements;
pathXMin = other.pathXMin;
pathXMax = other.pathXMax;
pathYMin = other.pathYMin;
pathYMax = other.pathYMax;
useNonZeroWinding = other.useNonZeroWinding;
if (numElements > 0)
memcpy (data.elements, other.data.elements, numElements * sizeof (float));
}
return *this;
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
Path::Path (Path&& other) noexcept
: data (static_cast <ArrayAllocationBase <float, DummyCriticalSection>&&> (other.data)),
numElements (other.numElements),
pathXMin (other.pathXMin),
pathXMax (other.pathXMax),
pathYMin (other.pathYMin),
pathYMax (other.pathYMax),
useNonZeroWinding (other.useNonZeroWinding)
{
}
Path& Path::operator= (Path&& other) noexcept
{
data = static_cast <ArrayAllocationBase <float, DummyCriticalSection>&&> (other.data);
numElements = other.numElements;
pathXMin = other.pathXMin;
pathXMax = other.pathXMax;
pathYMin = other.pathYMin;
pathYMax = other.pathYMax;
useNonZeroWinding = other.useNonZeroWinding;
return *this;
}
#endif
bool Path::operator== (const Path& other) const noexcept
{
return ! operator!= (other);
}
bool Path::operator!= (const Path& other) const noexcept
{
if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
return true;
for (size_t i = 0; i < numElements; ++i)
if (data.elements[i] != other.data.elements[i])
return true;
return false;
}
void Path::clear() noexcept
{
numElements = 0;
pathXMin = 0;
pathYMin = 0;
pathYMax = 0;
pathXMax = 0;
}
void Path::swapWithPath (Path& other) noexcept
{
data.swapWith (other.data);
std::swap (numElements, other.numElements);
std::swap (pathXMin, other.pathXMin);
std::swap (pathXMax, other.pathXMax);
std::swap (pathYMin, other.pathYMin);
std::swap (pathYMax, other.pathYMax);
std::swap (useNonZeroWinding, other.useNonZeroWinding);
}
//==============================================================================
void Path::setUsingNonZeroWinding (const bool isNonZero) noexcept
{
useNonZeroWinding = isNonZero;
}
void Path::scaleToFit (const float x, const float y, const float w, const float h,
const bool preserveProportions) noexcept
{
applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
}
//==============================================================================
bool Path::isEmpty() const noexcept
{
size_t i = 0;
while (i < numElements)
{
const float type = data.elements [i++];
if (type == moveMarker)
{
i += 2;
}
else if (type == lineMarker
|| type == quadMarker
|| type == cubicMarker)
{
return false;
}
}
return true;
}
Rectangle<float> Path::getBounds() const noexcept
{
return Rectangle<float> (pathXMin, pathYMin,
pathXMax - pathXMin,
pathYMax - pathYMin);
}
Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const noexcept
{
return getBounds().transformed (transform);
}
//==============================================================================
void Path::startNewSubPath (const float x, const float y)
{
JUCE_CHECK_COORDS_ARE_VALID (x, y);
if (numElements == 0)
{
pathXMin = pathXMax = x;
pathYMin = pathYMax = y;
}
else
{
pathXMin = jmin (pathXMin, x);
pathXMax = jmax (pathXMax, x);
pathYMin = jmin (pathYMin, y);
pathYMax = jmax (pathYMax, y);
}
data.ensureAllocatedSize ((int) numElements + 3);
data.elements [numElements++] = moveMarker;
data.elements [numElements++] = x;
data.elements [numElements++] = y;
}
void Path::startNewSubPath (const Point<float>& start)
{
startNewSubPath (start.x, start.y);
}
void Path::lineTo (const float x, const float y)
{
JUCE_CHECK_COORDS_ARE_VALID (x, y);
if (numElements == 0)
startNewSubPath (0, 0);
data.ensureAllocatedSize ((int) numElements + 3);
data.elements [numElements++] = lineMarker;
data.elements [numElements++] = x;
data.elements [numElements++] = y;
pathXMin = jmin (pathXMin, x);
pathXMax = jmax (pathXMax, x);
pathYMin = jmin (pathYMin, y);
pathYMax = jmax (pathYMax, y);
}
void Path::lineTo (const Point<float>& end)
{
lineTo (end.x, end.y);
}
void Path::quadraticTo (const float x1, const float y1,
const float x2, const float y2)
{
JUCE_CHECK_COORDS_ARE_VALID (x1, y1);
JUCE_CHECK_COORDS_ARE_VALID (x2, y2);
if (numElements == 0)
startNewSubPath (0, 0);
data.ensureAllocatedSize ((int) numElements + 5);
data.elements [numElements++] = quadMarker;
data.elements [numElements++] = x1;
data.elements [numElements++] = y1;
data.elements [numElements++] = x2;
data.elements [numElements++] = y2;
pathXMin = jmin (pathXMin, x1, x2);
pathXMax = jmax (pathXMax, x1, x2);
pathYMin = jmin (pathYMin, y1, y2);
pathYMax = jmax (pathYMax, y1, y2);
}
void Path::quadraticTo (const Point<float>& controlPoint,
const Point<float>& endPoint)
{
quadraticTo (controlPoint.x, controlPoint.y,
endPoint.x, endPoint.y);
}
void Path::cubicTo (const float x1, const float y1,
const float x2, const float y2,
const float x3, const float y3)
{
JUCE_CHECK_COORDS_ARE_VALID (x1, y1);
JUCE_CHECK_COORDS_ARE_VALID (x2, y2);
JUCE_CHECK_COORDS_ARE_VALID (x3, y3);
if (numElements == 0)
startNewSubPath (0, 0);
data.ensureAllocatedSize ((int) numElements + 7);
data.elements [numElements++] = cubicMarker;
data.elements [numElements++] = x1;
data.elements [numElements++] = y1;
data.elements [numElements++] = x2;
data.elements [numElements++] = y2;
data.elements [numElements++] = x3;
data.elements [numElements++] = y3;
pathXMin = jmin (pathXMin, x1, x2, x3);
pathXMax = jmax (pathXMax, x1, x2, x3);
pathYMin = jmin (pathYMin, y1, y2, y3);
pathYMax = jmax (pathYMax, y1, y2, y3);
}
void Path::cubicTo (const Point<float>& controlPoint1,
const Point<float>& controlPoint2,
const Point<float>& endPoint)
{
cubicTo (controlPoint1.x, controlPoint1.y,
controlPoint2.x, controlPoint2.y,
endPoint.x, endPoint.y);
}
void Path::closeSubPath()
{
if (numElements > 0
&& data.elements [numElements - 1] != closeSubPathMarker)
{
data.ensureAllocatedSize ((int) numElements + 1);
data.elements [numElements++] = closeSubPathMarker;
}
}
Point<float> Path::getCurrentPosition() const
{
int i = (int) numElements - 1;
if (i > 0 && data.elements[i] == closeSubPathMarker)
{
while (i >= 0)
{
if (data.elements[i] == moveMarker)
{
i += 2;
break;
}
--i;
}
}
if (i > 0)
return Point<float> (data.elements [i - 1], data.elements [i]);
return Point<float>();
}
void Path::addRectangle (const float x, const float y,
const float w, const float h)
{
float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
if (w < 0) std::swap (x1, x2);
if (h < 0) std::swap (y1, y2);
data.ensureAllocatedSize ((int) numElements + 13);
if (numElements == 0)
{
pathXMin = x1;
pathXMax = x2;
pathYMin = y1;
pathYMax = y2;
}
else
{
pathXMin = jmin (pathXMin, x1);
pathXMax = jmax (pathXMax, x2);
pathYMin = jmin (pathYMin, y1);
pathYMax = jmax (pathYMax, y2);
}
data.elements [numElements++] = moveMarker;
data.elements [numElements++] = x1;
data.elements [numElements++] = y2;
data.elements [numElements++] = lineMarker;
data.elements [numElements++] = x1;
data.elements [numElements++] = y1;
data.elements [numElements++] = lineMarker;
data.elements [numElements++] = x2;
data.elements [numElements++] = y1;
data.elements [numElements++] = lineMarker;
data.elements [numElements++] = x2;
data.elements [numElements++] = y2;
data.elements [numElements++] = closeSubPathMarker;
}
void Path::addRoundedRectangle (const float x, const float y,
const float w, const float h,
float csx,
float csy)
{
csx = jmin (csx, w * 0.5f);
csy = jmin (csy, h * 0.5f);
const float cs45x = csx * 0.45f;
const float cs45y = csy * 0.45f;
const float x2 = x + w;
const float y2 = y + h;
startNewSubPath (x + csx, y);
lineTo (x2 - csx, y);
cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
lineTo (x2, y2 - csy);
cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
lineTo (x + csx, y2);
cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
lineTo (x, y + csy);
cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
closeSubPath();
}
void Path::addRoundedRectangle (const float x, const float y,
const float w, const float h,
float cs)
{
addRoundedRectangle (x, y, w, h, cs, cs);
}
void Path::addTriangle (const float x1, const float y1,
const float x2, const float y2,
const float x3, const float y3)
{
startNewSubPath (x1, y1);
lineTo (x2, y2);
lineTo (x3, y3);
closeSubPath();
}
void Path::addQuadrilateral (const float x1, const float y1,
const float x2, const float y2,
const float x3, const float y3,
const float x4, const float y4)
{
startNewSubPath (x1, y1);
lineTo (x2, y2);
lineTo (x3, y3);
lineTo (x4, y4);
closeSubPath();
}
void Path::addEllipse (const float x, const float y,
const float w, const float h)
{
const float hw = w * 0.5f;
const float hw55 = hw * 0.55f;
const float hh = h * 0.5f;
const float hh55 = hh * 0.55f;
const float cx = x + hw;
const float cy = y + hh;
startNewSubPath (cx, cy - hh);
cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
closeSubPath();
}
void Path::addArc (const float x, const float y,
const float w, const float h,
const float fromRadians,
const float toRadians,
const bool startAsNewSubPath)
{
const float radiusX = w / 2.0f;
const float radiusY = h / 2.0f;
addCentredArc (x + radiusX,
y + radiusY,
radiusX, radiusY,
0.0f,
fromRadians, toRadians,
startAsNewSubPath);
}
void Path::addCentredArc (const float centreX, const float centreY,
const float radiusX, const float radiusY,
const float rotationOfEllipse,
const float fromRadians,
float toRadians,
const bool startAsNewSubPath)
{
if (radiusX > 0.0f && radiusY > 0.0f)
{
const Point<float> centre (centreX, centreY);
const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
float angle = fromRadians;
if (startAsNewSubPath)
startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
if (fromRadians < toRadians)
{
if (startAsNewSubPath)
angle += PathHelpers::ellipseAngularIncrement;
while (angle < toRadians)
{
lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
angle += PathHelpers::ellipseAngularIncrement;
}
}
else
{
if (startAsNewSubPath)
angle -= PathHelpers::ellipseAngularIncrement;
while (angle > toRadians)
{
lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
angle -= PathHelpers::ellipseAngularIncrement;
}
}
lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
}
}
void Path::addPieSegment (const float x, const float y,
const float width, const float height,
const float fromRadians,
const float toRadians,
const float innerCircleProportionalSize)
{
float radiusX = width * 0.5f;
float radiusY = height * 0.5f;
const Point<float> centre (x + radiusX, y + radiusY);
startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
addArc (x, y, width, height, fromRadians, toRadians);
if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
{
closeSubPath();
if (innerCircleProportionalSize > 0)
{
radiusX *= innerCircleProportionalSize;
radiusY *= innerCircleProportionalSize;
startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
addArc (centre.x - radiusX, centre.y - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
}
}
else
{
if (innerCircleProportionalSize > 0)
{
radiusX *= innerCircleProportionalSize;
radiusY *= innerCircleProportionalSize;
addArc (centre.x - radiusX, centre.y - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
}
else
{
lineTo (centre);
}
}
closeSubPath();
}
//==============================================================================
void Path::addLineSegment (const Line<float>& line, float lineThickness)
{
const Line<float> reversed (line.reversed());
lineThickness *= 0.5f;
startNewSubPath (line.getPointAlongLine (0, lineThickness));
lineTo (line.getPointAlongLine (0, -lineThickness));
lineTo (reversed.getPointAlongLine (0, lineThickness));
lineTo (reversed.getPointAlongLine (0, -lineThickness));
closeSubPath();
}
void Path::addArrow (const Line<float>& line, float lineThickness,
float arrowheadWidth, float arrowheadLength)
{
const Line<float> reversed (line.reversed());
lineThickness *= 0.5f;
arrowheadWidth *= 0.5f;
arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
startNewSubPath (line.getPointAlongLine (0, lineThickness));
lineTo (line.getPointAlongLine (0, -lineThickness));
lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
lineTo (line.getEnd());
lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
closeSubPath();
}
void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
const float radius, const float startAngle)
{
jassert (numberOfSides > 1); // this would be silly.
if (numberOfSides > 1)
{
const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
for (int i = 0; i < numberOfSides; ++i)
{
const float angle = startAngle + i * angleBetweenPoints;
const Point<float> p (centre.getPointOnCircumference (radius, angle));
if (i == 0)
startNewSubPath (p);
else
lineTo (p);
}
closeSubPath();
}
}
void Path::addStar (const Point<float>& centre, const int numberOfPoints,
const float innerRadius, const float outerRadius, const float startAngle)
{
jassert (numberOfPoints > 1); // this would be silly.
if (numberOfPoints > 1)
{
const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
for (int i = 0; i < numberOfPoints; ++i)
{
const float angle = startAngle + i * angleBetweenPoints;
const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
if (i == 0)
startNewSubPath (p);
else
lineTo (p);
lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
}
closeSubPath();
}
}
void Path::addBubble (float x, float y,
float w, float h,
float cs,
float tipX,
float tipY,
int whichSide,
float arrowPos,
float arrowWidth)
{
if (w > 1.0f && h > 1.0f)
{
cs = jmin (cs, w * 0.5f, h * 0.5f);
const float cs2 = 2.0f * cs;
startNewSubPath (x + cs, y);
if (whichSide == 0)
{
const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
const float arrowX1 = x + cs + jmax (0.0f, (w - cs2 - arrowWidth) * arrowPos - halfArrowW);
lineTo (arrowX1, y);
lineTo (tipX, tipY);
lineTo (arrowX1 + halfArrowW * 2.0f, y);
}
lineTo (x + w - cs, y);
if (cs > 0.0f)
addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
if (whichSide == 3)
{
const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
const float arrowY1 = y + cs + jmax (0.0f, (h - cs2 - arrowWidth) * arrowPos - halfArrowH);
lineTo (x + w, arrowY1);
lineTo (tipX, tipY);
lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
}
lineTo (x + w, y + h - cs);
if (cs > 0.0f)
addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
if (whichSide == 2)
{
const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
const float arrowX1 = x + cs + jmax (0.0f, (w - cs2 - arrowWidth) * arrowPos - halfArrowW);
lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
lineTo (tipX, tipY);
lineTo (arrowX1, y + h);
}
lineTo (x + cs, y + h);
if (cs > 0.0f)
addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
if (whichSide == 1)
{
const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
const float arrowY1 = y + cs + jmax (0.0f, (h - cs2 - arrowWidth) * arrowPos - halfArrowH);
lineTo (x, arrowY1 + halfArrowH * 2.0f);
lineTo (tipX, tipY);
lineTo (x, arrowY1);
}
lineTo (x, y + cs);
if (cs > 0.0f)
addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
closeSubPath();
}
}
void Path::addPath (const Path& other)
{
size_t i = 0;
while (i < other.numElements)
{
const float type = other.data.elements [i++];
if (type == moveMarker)
{
startNewSubPath (other.data.elements [i],
other.data.elements [i + 1]);
i += 2;
}
else if (type == lineMarker)
{
lineTo (other.data.elements [i],
other.data.elements [i + 1]);
i += 2;
}
else if (type == quadMarker)
{
quadraticTo (other.data.elements [i],
other.data.elements [i + 1],
other.data.elements [i + 2],
other.data.elements [i + 3]);
i += 4;
}
else if (type == cubicMarker)
{
cubicTo (other.data.elements [i],
other.data.elements [i + 1],
other.data.elements [i + 2],
other.data.elements [i + 3],
other.data.elements [i + 4],
other.data.elements [i + 5]);
i += 6;
}
else if (type == closeSubPathMarker)
{
closeSubPath();
}
else
{
// something's gone wrong with the element list!
jassertfalse;
}
}
}
void Path::addPath (const Path& other,
const AffineTransform& transformToApply)
{
size_t i = 0;
while (i < other.numElements)
{
const float type = other.data.elements [i++];
if (type == closeSubPathMarker)
{
closeSubPath();
}
else
{
float x = other.data.elements [i++];
float y = other.data.elements [i++];
transformToApply.transformPoint (x, y);
if (type == moveMarker)
{
startNewSubPath (x, y);
}
else if (type == lineMarker)
{
lineTo (x, y);
}
else if (type == quadMarker)
{
float x2 = other.data.elements [i++];
float y2 = other.data.elements [i++];
transformToApply.transformPoint (x2, y2);
quadraticTo (x, y, x2, y2);
}
else if (type == cubicMarker)
{
float x2 = other.data.elements [i++];
float y2 = other.data.elements [i++];
float x3 = other.data.elements [i++];
float y3 = other.data.elements [i++];
transformToApply.transformPoints (x2, y2, x3, y3);
cubicTo (x, y, x2, y2, x3, y3);
}
else
{
// something's gone wrong with the element list!
jassertfalse;
}
}
}
}
//==============================================================================
void Path::applyTransform (const AffineTransform& transform) noexcept
{
size_t i = 0;
pathYMin = pathXMin = 0;
pathYMax = pathXMax = 0;
bool setMaxMin = false;
while (i < numElements)
{
const float type = data.elements [i++];
if (type == moveMarker)
{
transform.transformPoint (data.elements [i], data.elements [i + 1]);
if (setMaxMin)
{
pathXMin = jmin (pathXMin, data.elements [i]);
pathXMax = jmax (pathXMax, data.elements [i]);
pathYMin = jmin (pathYMin, data.elements [i + 1]);
pathYMax = jmax (pathYMax, data.elements [i + 1]);
}
else
{
pathXMin = pathXMax = data.elements [i];
pathYMin = pathYMax = data.elements [i + 1];
setMaxMin = true;
}
i += 2;
}
else if (type == lineMarker)
{
transform.transformPoint (data.elements [i], data.elements [i + 1]);
pathXMin = jmin (pathXMin, data.elements [i]);
pathXMax = jmax (pathXMax, data.elements [i]);
pathYMin = jmin (pathYMin, data.elements [i + 1]);
pathYMax = jmax (pathYMax, data.elements [i + 1]);
i += 2;
}
else if (type == quadMarker)
{
transform.transformPoints (data.elements [i], data.elements [i + 1],
data.elements [i + 2], data.elements [i + 3]);
pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
i += 4;
}
else if (type == cubicMarker)
{
transform.transformPoints (data.elements [i], data.elements [i + 1],
data.elements [i + 2], data.elements [i + 3],
data.elements [i + 4], data.elements [i + 5]);
pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
i += 6;
}
}
}
//==============================================================================
AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
const float w, const float h,
const bool preserveProportions,
const Justification& justification) const
{
Rectangle<float> bounds (getBounds());
if (preserveProportions)
{
if (w <= 0 || h <= 0 || bounds.isEmpty())
return AffineTransform::identity;
float newW, newH;
const float srcRatio = bounds.getHeight() / bounds.getWidth();
if (srcRatio > h / w)
{
newW = h / srcRatio;
newH = h;
}
else
{
newW = w;
newH = w * srcRatio;
}
float newXCentre = x;
float newYCentre = y;
if (justification.testFlags (Justification::left)) newXCentre += newW * 0.5f;
else if (justification.testFlags (Justification::right)) newXCentre += w - newW * 0.5f;
else newXCentre += w * 0.5f;
if (justification.testFlags (Justification::top)) newYCentre += newH * 0.5f;
else if (justification.testFlags (Justification::bottom)) newYCentre += h - newH * 0.5f;
else newYCentre += h * 0.5f;
return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
bounds.getHeight() * -0.5f - bounds.getY())
.scaled (newW / bounds.getWidth(),
newH / bounds.getHeight())
.translated (newXCentre, newYCentre);
}
else
{
return AffineTransform::translation (-bounds.getX(), -bounds.getY())
.scaled (w / bounds.getWidth(),
h / bounds.getHeight())
.translated (x, y);
}
}
//==============================================================================
bool Path::contains (const float x, const float y, const float tolerance) const
{
if (x <= pathXMin || x >= pathXMax
|| y <= pathYMin || y >= pathYMax)
return false;
PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
int positiveCrossings = 0;
int negativeCrossings = 0;
while (i.next())
{
if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
{
const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
if (intersectX <= x)
{
if (i.y1 < i.y2)
++positiveCrossings;
else
++negativeCrossings;
}
}
}
return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
: ((negativeCrossings + positiveCrossings) & 1) != 0;
}
bool Path::contains (const Point<float>& point, const float tolerance) const
{
return contains (point.x, point.y, tolerance);
}
bool Path::intersectsLine (const Line<float>& line, const float tolerance)
{
PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
Point<float> intersection;
while (i.next())
if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
return true;
return false;
}
Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
{
Line<float> result (line);
const bool startInside = contains (line.getStart());
const bool endInside = contains (line.getEnd());
if (startInside == endInside)
{
if (keepSectionOutsidePath == startInside)
result = Line<float>();
}
else
{
PathFlatteningIterator i (*this, AffineTransform::identity);
Point<float> intersection;
while (i.next())
{
if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
{
if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
result.setStart (intersection);
else
result.setEnd (intersection);
}
}
}
return result;
}
float Path::getLength (const AffineTransform& transform) const
{
float length = 0;
PathFlatteningIterator i (*this, transform);
while (i.next())
length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
return length;
}
Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
{
PathFlatteningIterator i (*this, transform);
while (i.next())
{
const Line<float> line (i.x1, i.y1, i.x2, i.y2);
const float lineLength = line.getLength();
if (distanceFromStart <= lineLength)
return line.getPointAlongLine (distanceFromStart);
distanceFromStart -= lineLength;
}
return Point<float> (i.x2, i.y2);
}
float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
const AffineTransform& transform) const
{
PathFlatteningIterator i (*this, transform);
float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
float length = 0;
Point<float> pointOnLine;
while (i.next())
{
const Line<float> line (i.x1, i.y1, i.x2, i.y2);
const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
if (distance < bestDistance)
{
bestDistance = distance;
bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
pointOnPath = pointOnLine;
}
length += line.getLength();
}
return bestPosition;
}
//==============================================================================
Path Path::createPathWithRoundedCorners (const float cornerRadius) const
{
if (cornerRadius <= 0.01f)
return *this;
size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
size_t n = 0;
bool lastWasLine = false, firstWasLine = false;
Path p;
while (n < numElements)
{
const float type = data.elements [n++];
if (type == moveMarker)
{
indexOfPathStart = p.numElements;
indexOfPathStartThis = n - 1;
const float x = data.elements [n++];
const float y = data.elements [n++];
p.startNewSubPath (x, y);
lastWasLine = false;
firstWasLine = (data.elements [n] == lineMarker);
}
else if (type == lineMarker || type == closeSubPathMarker)
{
float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
if (type == lineMarker)
{
endX = data.elements [n++];
endY = data.elements [n++];
if (n > 8)
{
startX = data.elements [n - 8];
startY = data.elements [n - 7];
joinX = data.elements [n - 5];
joinY = data.elements [n - 4];
}
}
else
{
endX = data.elements [indexOfPathStartThis + 1];
endY = data.elements [indexOfPathStartThis + 2];
if (n > 6)
{
startX = data.elements [n - 6];
startY = data.elements [n - 5];
joinX = data.elements [n - 3];
joinY = data.elements [n - 2];
}
}
if (lastWasLine)
{
const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
if (len1 > 0)
{
const double propNeeded = jmin (0.5, cornerRadius / len1);
p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
}
const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
if (len2 > 0)
{
const double propNeeded = jmin (0.5, cornerRadius / len2);
p.quadraticTo (joinX, joinY,
(float) (joinX + (endX - joinX) * propNeeded),
(float) (joinY + (endY - joinY) * propNeeded));
}
p.lineTo (endX, endY);
}
else if (type == lineMarker)
{
p.lineTo (endX, endY);
lastWasLine = true;
}
if (type == closeSubPathMarker)
{
if (firstWasLine)
{
startX = data.elements [n - 3];
startY = data.elements [n - 2];
joinX = endX;
joinY = endY;
endX = data.elements [indexOfPathStartThis + 4];
endY = data.elements [indexOfPathStartThis + 5];
const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
if (len1 > 0)
{
const double propNeeded = jmin (0.5, cornerRadius / len1);
p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
}
const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
if (len2 > 0)
{
const double propNeeded = jmin (0.5, cornerRadius / len2);
endX = (float) (joinX + (endX - joinX) * propNeeded);
endY = (float) (joinY + (endY - joinY) * propNeeded);
p.quadraticTo (joinX, joinY, endX, endY);
p.data.elements [indexOfPathStart + 1] = endX;
p.data.elements [indexOfPathStart + 2] = endY;
}
}
p.closeSubPath();
}
}
else if (type == quadMarker)
{
lastWasLine = false;
const float x1 = data.elements [n++];
const float y1 = data.elements [n++];
const float x2 = data.elements [n++];
const float y2 = data.elements [n++];
p.quadraticTo (x1, y1, x2, y2);
}
else if (type == cubicMarker)
{
lastWasLine = false;
const float x1 = data.elements [n++];
const float y1 = data.elements [n++];
const float x2 = data.elements [n++];
const float y2 = data.elements [n++];
const float x3 = data.elements [n++];
const float y3 = data.elements [n++];
p.cubicTo (x1, y1, x2, y2, x3, y3);
}
}
return p;
}
//==============================================================================
void Path::loadPathFromStream (InputStream& source)
{
while (! source.isExhausted())
{
switch (source.readByte())
{
case 'm':
{
const float x = source.readFloat();
const float y = source.readFloat();
startNewSubPath (x, y);
break;
}
case 'l':
{
const float x = source.readFloat();
const float y = source.readFloat();
lineTo (x, y);
break;
}
case 'q':
{
const float x1 = source.readFloat();
const float y1 = source.readFloat();
const float x2 = source.readFloat();
const float y2 = source.readFloat();
quadraticTo (x1, y1, x2, y2);
break;
}
case 'b':
{
const float x1 = source.readFloat();
const float y1 = source.readFloat();
const float x2 = source.readFloat();
const float y2 = source.readFloat();
const float x3 = source.readFloat();
const float y3 = source.readFloat();
cubicTo (x1, y1, x2, y2, x3, y3);
break;
}
case 'c':
closeSubPath();
break;
case 'n':
useNonZeroWinding = true;
break;
case 'z':
useNonZeroWinding = false;
break;
case 'e':
return; // end of path marker
default:
jassertfalse; // illegal char in the stream
break;
}
}
}
void Path::loadPathFromData (const void* const pathData, const size_t numberOfBytes)
{
MemoryInputStream in (pathData, numberOfBytes, false);
loadPathFromStream (in);
}
void Path::writePathToStream (OutputStream& dest) const
{
dest.writeByte (useNonZeroWinding ? 'n' : 'z');
size_t i = 0;
while (i < numElements)
{
const float type = data.elements [i++];
if (type == moveMarker)
{
dest.writeByte ('m');
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
}
else if (type == lineMarker)
{
dest.writeByte ('l');
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
}
else if (type == quadMarker)
{
dest.writeByte ('q');
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
}
else if (type == cubicMarker)
{
dest.writeByte ('b');
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
dest.writeFloat (data.elements [i++]);
}
else if (type == closeSubPathMarker)
{
dest.writeByte ('c');
}
}
dest.writeByte ('e'); // marks the end-of-path
}
String Path::toString() const
{
MemoryOutputStream s (2048);
if (! useNonZeroWinding)
s << 'a';
size_t i = 0;
float lastMarker = 0.0f;
while (i < numElements)
{
const float marker = data.elements [i++];
char markerChar = 0;
int numCoords = 0;
if (marker == moveMarker)
{
markerChar = 'm';
numCoords = 2;
}
else if (marker == lineMarker)
{
markerChar = 'l';
numCoords = 2;
}
else if (marker == quadMarker)
{
markerChar = 'q';
numCoords = 4;
}
else if (marker == cubicMarker)
{
markerChar = 'c';
numCoords = 6;
}
else
{
jassert (marker == closeSubPathMarker);
markerChar = 'z';
}
if (marker != lastMarker)
{
if (s.getDataSize() != 0)
s << ' ';
s << markerChar;
lastMarker = marker;
}
while (--numCoords >= 0 && i < numElements)
{
String coord (data.elements [i++], 3);
while (coord.endsWithChar ('0') && coord != "0")
coord = coord.dropLastCharacters (1);
if (coord.endsWithChar ('.'))
coord = coord.dropLastCharacters (1);
if (s.getDataSize() != 0)
s << ' ';
s << coord;
}
}
return s.toUTF8();
}
void Path::restoreFromString (const String& stringVersion)
{
clear();
setUsingNonZeroWinding (true);
String::CharPointerType t (stringVersion.getCharPointer());
juce_wchar marker = 'm';
int numValues = 2;
float values [6];
for (;;)
{
const String token (PathHelpers::nextToken (t));
const juce_wchar firstChar = token[0];
int startNum = 0;
if (firstChar == 0)
break;
if (firstChar == 'm' || firstChar == 'l')
{
marker = firstChar;
numValues = 2;
}
else if (firstChar == 'q')
{
marker = firstChar;
numValues = 4;
}
else if (firstChar == 'c')
{
marker = firstChar;
numValues = 6;
}
else if (firstChar == 'z')
{
marker = firstChar;
numValues = 0;
}
else if (firstChar == 'a')
{
setUsingNonZeroWinding (false);
continue;
}
else
{
++startNum;
values [0] = token.getFloatValue();
}
for (int i = startNum; i < numValues; ++i)
values [i] = PathHelpers::nextToken (t).getFloatValue();
switch (marker)
{
case 'm': startNewSubPath (values[0], values[1]); break;
case 'l': lineTo (values[0], values[1]); break;
case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
case 'z': closeSubPath(); break;
default: jassertfalse; break; // illegal string format?
}
}
}
//==============================================================================
Path::Iterator::Iterator (const Path& path_)
: path (path_),
index (0)
{
}
Path::Iterator::~Iterator()
{
}
bool Path::Iterator::next()
{
const float* const elements = path.data.elements;
if (index < path.numElements)
{
const float type = elements [index++];
if (type == moveMarker)
{
elementType = startNewSubPath;
x1 = elements [index++];
y1 = elements [index++];
}
else if (type == lineMarker)
{
elementType = lineTo;
x1 = elements [index++];
y1 = elements [index++];
}
else if (type == quadMarker)
{
elementType = quadraticTo;
x1 = elements [index++];
y1 = elements [index++];
x2 = elements [index++];
y2 = elements [index++];
}
else if (type == cubicMarker)
{
elementType = cubicTo;
x1 = elements [index++];
y1 = elements [index++];
x2 = elements [index++];
y2 = elements [index++];
x3 = elements [index++];
y3 = elements [index++];
}
else if (type == closeSubPathMarker)
{
elementType = closePath;
}
return true;
}
return false;
}
#undef JUCE_CHECK_COORDS_ARE_VALID
END_JUCE_NAMESPACE
| [
"ow3nskip"
]
| [
[
[
1,
1590
]
]
]
|
639ce00dce78fb0c891f27e037f25a12ad8e4251 | f6d91584f5b92a90b22a1eb09d2ce203d4185f00 | /ensembl/misc-scripts/alternative_splicing/AltSplicingToolkit/src/as/GeneFeature.cpp | 088fb2b30e48b5c6c205833d87b39977357370dc | [
"LicenseRef-scancode-philippe-de-muyter",
"BSD-2-Clause"
]
| permissive | pamag/pmgEnsembl | 8f807043bf6d0b6cfdfee934841d2af33c8d171c | ad0469e4d37171a69318f6bd1372477e85f4afb2 | refs/heads/master | 2021-06-01T10:58:22.839415 | 2011-10-18T16:09:52 | 2011-10-18T16:09:52 | 2,599,520 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,830 | cpp | /*
* AltSplicingToolkit
* Author: Gautier Koscielny <[email protected]>
*
* Copyright (c) 1999-2010 The European Bioinformatics Institute and
* Genome Research Limited, and others. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Ensembl" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected]
*
* 4. Products derived from this software may not be called "Ensembl"
* nor may "Ensembl" appear in their names without prior written
* permission of the Ensembl developers.
*
* 5. Redistributions in any form whatsoever must retain the following
* acknowledgement:
*
* "This product includes software developed by Ensembl
* (http://www.ensembl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE ENSEMBL GROUP ``AS IS'' AND ANY
* EXPRESSED 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 ENSEMBL GROUP OR ITS
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "GeneFeature.h"
namespace as
{
GeneFeature::GeneFeature(std::string featureIdentifier) : Feature(featureIdentifier)
{
}
GeneFeature::GeneFeature(int type, unsigned int start, unsigned int end, string chr, short int strand) : Feature::Feature(type, start, end, chr, strand)
{
}
GeneFeature::GeneFeature()
{
}
GeneFeature::~GeneFeature()
{
}
void GeneFeature::setGene(const shared_ptr<Gene> &gene)
{
this->gene = gene;
}
const shared_ptr<Gene> &GeneFeature::getGene() const
{
return gene;
}
}
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
ac5555a57524eb6bd27b8e8e220aaed88c7d0755 | 968aa9bac548662b49af4e2b873b61873ba6f680 | /e32tools/elf2e32/source/e32imagefile.h | d19465516b43a2bee5ca7f2b5b0ae6e3c9a97a6d | []
| no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,597 | h | // Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// Class for E32 Image implementation and dump of the elf2e32 tool
// @internalComponent
// @released
//
//
#ifndef E32IMAGEFILE_H
#define E32IMAGEFILE_H
#include "pl_elfrelocation.h"
#include "pl_elfrelocations.h"
#include "e32imagedefs.h"
#include "elfdefs.h"
#include <fstream>
#include <vector>
using std::vector;
#include <iostream>
using std::ifstream;
#include <e32std.h>
enum TFileSource
{
EE32Image=0,
EPeFile=1,
EElfFile=2,
};
class ELFExecutable;
class ElfFileSupplied;
/**
Class E32ImageChunkDesc for different sections in the E32 image.
@internalComponent
@released
*/
class E32ImageChunkDesc
{
public:
E32ImageChunkDesc(char * aData, size_t aSize, size_t aOffset, char * aDoc);
virtual ~E32ImageChunkDesc();
virtual void Write(char * aPlace);
public:
char * iData;
size_t iSize;
size_t iOffset;
char * iDoc;
};
/**
Class E32ImageChunks for a list of sections in the E32 image.
@internalComponent
@released
*/
class E32ImageChunks
{
public:
typedef vector<E32ImageChunkDesc *> ChunkList;
public:
E32ImageChunks();
virtual ~E32ImageChunks();
void AddChunk(char * aData, size_t aSize, size_t aOffset, char * aDoc);
size_t GetOffset();
void SetOffset(size_t aOffset);
ChunkList & GetChunks();
public:
ChunkList iChunks;
size_t iOffset;
};
class ElfFileSupplied;
/**
Class E32ImageFile for fields of an E32 image.
@internalComponent
@released
*/
class E32ImageFile
{
public:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned long uint32;
struct E32RelocPageDesc
{
uint32 aOffset;
uint32 aSize;
};
//public:
E32ImageFile(const char * aFileName, ElfExecutable * aExecutable, ElfFileSupplied * aUseCase);
virtual ~E32ImageFile();
void GenerateE32Image();
void ReadInputELFFile(const char * aName, size_t & aFileSize, Elf32_Ehdr * & aELFFile );
void ProcessImports();
const char * FindDSO(const char * aName);
void ProcessRelocations();
void ProcessCodeRelocations();
void ProcessDataRelocations();
void CreateRelocations(ElfRelocations::RelocationList & aRelocList, char * & aRelocs, size_t & aRelocSize);
size_t RelocationsSize(ElfRelocations::RelocationList & aRelocList);
uint16 GetE32RelocType(ElfRelocation * aReloc);
void ConstructImage();
virtual void InitE32ImageHeader();
virtual size_t GetE32ImageHeaderSize();
virtual size_t GetExtendedE32ImageHeaderSize();
virtual void SetExtendedE32ImageHeaderSize(size_t aSize);
virtual void ComputeE32ImageLayout();
virtual size_t GetE32ImageSize();
virtual size_t GetExportOffset();
virtual void CreateExportBitMap();
virtual void AddExportDescription();
virtual void AllocateE32Image();
virtual void FinalizeE32Image();
virtual uint16 GetCpuIdentifier();
virtual uint32 EntryPointOffset();
enum EEntryPointStatus
{
EEntryPointOK,
EEntryPointCorrupt,
EEntryPointNotSupported
};
EEntryPointStatus ValidateEntryPoint();
virtual void SetUpExceptions();
virtual void SetUids();
virtual void SetSecureId();
virtual void SetVendorId();
virtual void SetCallEntryPoints();
virtual void SetCapability();
virtual void SetPriority(bool isDllp);
virtual void SetFixedAddress(bool isDllp);
virtual void SetVersion();
virtual void SetCompressionType();
virtual void SetFPU();
virtual void SetPaged();
virtual void SetSymbolLookup();
virtual void SetDebuggable();
virtual void SetSmpSafe();
void UpdateHeaderCrc();
bool WriteImage(const char* aName);
public:
const char* iFileName;
char * iE32Image;
uint8 * iExportBitMap;
ElfExecutable * iElfExecutable;
std::vector<char*> cleanupStack;
char* iData;
ElfFileSupplied * iUseCase;
E32ImageHeaderV * iHdr;
size_t iHdrSize;
E32ImageChunks iChunks;
uint32 iNumDlls;
uint32 iNumImports;
uint32 * iImportSection;
size_t iImportSectionSize;
char * iCodeRelocs;
size_t iCodeRelocsSize;
char * iDataRelocs;
size_t iDataRelocsSize;
size_t iExportOffset;
bool iLayoutDone;
int iMissingExports;
// This table carries the byte offsets in the import table entries corresponding
// to the 0th ordinal entry of static dependencies.
std::vector<int> iImportTabLocations;
std::vector<uint32> iSymAddrTab;
std::vector<uint32> iSymNameOffTab;
std::string iSymbolNames;
uint32 iSymNameOffset;
public:
E32ImageFile();
TInt ReadHeader(ifstream& is);
TInt Open(const char* aFileName);
void Adjust(TInt aSize, TBool aAllowShrink=ETrue);
TUint TextOffset();
TUint DataOffset();
TUint BssOffset();
TUint32 Capability();
TUint32 Format();
void Dump(const char* aFileName,TInt aDumpFlags);
void DumpHeader(TInt aDumpFlags);
void DumpData(TInt aDumpFlags);
void DumpSymbolInfo(E32EpocExpSymInfoHdr *aSymInfoHdr);
void E32ImageExportBitMap();
TInt CheckExportDescription();
void ProcessSymbolInfo();
char* CreateSymbolInfo(size_t aBaseOffset);
void SetSymInfo(E32EpocExpSymInfoHdr& aSymInfo);
public:
inline TUint OrigCodeOffset() const {return OffsetUnadjust(iOrigHdr->iCodeOffset);}
inline TUint OrigDataOffset() const {return OffsetUnadjust(iOrigHdr->iDataOffset);}
inline TUint OrigCodeRelocOffset() const {return OffsetUnadjust(iOrigHdr->iCodeRelocOffset);}
inline TUint OrigDataRelocOffset() const {return OffsetUnadjust(iOrigHdr->iDataRelocOffset);}
inline TUint OrigImportOffset() const {return OffsetUnadjust(iOrigHdr->iImportOffset);}
inline TUint OrigExportDirOffset() const {return OffsetUnadjust(iOrigHdr->iExportDirOffset);}
inline TUint OffsetUnadjust(TUint a) const {return a ? a-iOrigHdrOffsetAdj : 0;}
inline void OffsetAdjust(TUint& a) { if (a) a+=iOrigHdrOffsetAdj; }
public:
TInt iSize;
E32ImageHeader* iOrigHdr;
TInt iError;
TFileSource iSource;
TUint iOrigHdrOffsetAdj;
TInt iFileSize;
};
ifstream &operator>>(ifstream &is, E32ImageFile &aImage);
void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
#endif // E32IMAGEFILE_H
| [
"[email protected]",
"none@none"
]
| [
[
[
1,
175
],
[
177,
178
],
[
180,
228
],
[
230,
265
]
],
[
[
176,
176
],
[
179,
179
],
[
229,
229
]
]
]
|
591eb9ebe143227b963d599b3d20cbca9a2f87bc | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/ServerStatusPlugin/ServerStatusPlugin.cpp | eb5e744440e1cbff688ccd414f8197758f5ec683 | []
| 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 | 14,617 | cpp | #include "StdAfx.h"
#include "../../../arcemu-shared/svn_revision.h"
#define SKIP_ALLOCATOR_SHARING 1
#include <ScriptSetup.h>
extern "C" SCRIPT_DECL uint32 _exp_get_script_type()
{
return SCRIPT_TYPE_INFODUMPER;
}
#ifdef WIN32
#pragma pack(push,8)
#include "PerfCounters.h"
#pragma pack(pop)
#include <Psapi.h>
#define SYSTEM_OBJECT_INDEX 2 // 'System' object
#define PROCESS_OBJECT_INDEX 230 // 'Process' object
#define PROCESSOR_OBJECT_INDEX 238 // 'Processor' object
#define TOTAL_PROCESSOR_TIME_COUNTER_INDEX 240 // '% Total processor time' counter (valid in WinNT under 'System' object)
#define PROCESSOR_TIME_COUNTER_INDEX 6 // '% processor time' counter (for Win2K/XP)
#pragma comment(lib, "advapi32")
#pragma comment(lib, "Psapi")
#endif
#define LOAD_THREAD_SLEEP 180
#ifdef WIN32
bool m_bFirstTime = true;
LONGLONG m_lnOldValue = 0;
LARGE_INTEGER m_OldPerfTime100nSec;
uint32 number_of_cpus;
#endif
// This is needed because windows is a piece of shit
#ifdef WIN32
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
return TRUE;
}
#endif
char Filename[MAX_PATH];
// Actual StatDumper Class
class StatDumper
{
public:
void DumpStats();
};
// Instance of StatDumper
StatDumper dumper;
// Thread Wrapper for StatDumper
struct StatDumperThread : public ThreadBase
{
#ifdef WIN32
HANDLE hEvent;
#else
pthread_cond_t cond;
pthread_mutex_t mutex;
#endif
bool running;
public:
StatDumperThread();
~StatDumperThread();
void OnShutdown();
bool run();
};
void StatDumperThread::OnShutdown()
{
running = false;
#ifdef WIN32
SetEvent( hEvent );
#else
pthread_cond_signal( &cond );
#endif
}
StatDumperThread::StatDumperThread()
{
}
StatDumperThread::~StatDumperThread()
{
#ifdef WIN32
CloseHandle(hEvent);
#else
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
#endif
}
bool StatDumperThread::run()
{
int delay_ms = Config.MainConfig.GetIntDefault( "StatDumper", "Interval", 120000 );
if( delay_ms < 1000 )
delay_ms = 1000;
int delay_s = delay_ms / 1000;
if( !Config.MainConfig.GetString( "StatDumper", Filename, "Filename", "stats.xml", MAX_PATH ) )
strcpy( Filename, "stats.xml" );
#ifdef WIN32
memset( &m_OldPerfTime100nSec, 0, sizeof( m_OldPerfTime100nSec ) );
SYSTEM_INFO si;
GetSystemInfo( &si );
number_of_cpus = si.dwNumberOfProcessors;
#endif
#ifdef WIN32
hEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
#else
struct timeval now;
struct timespec tv;
pthread_mutex_init( &mutex, NULL );
pthread_cond_init( &cond, NULL );
#endif
running = true;
for(;;)
{
dumper.DumpStats();
#ifdef WIN32
WaitForSingleObject( hEvent, delay_ms );
#else
gettimeofday( &now, NULL );
tv.tv_sec = now.tv_sec + delay_s;
tv.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock( &mutex );
pthread_cond_timedwait( &cond, &mutex, &tv );
pthread_mutex_unlock( &mutex );
#endif
if( !running )
break;
}
return true;
}
extern "C" SCRIPT_DECL void _exp_script_register(ScriptMgr* mgr)
{
ThreadPool.ExecuteTask( new StatDumperThread() );
}
#ifdef WIN32
/*** GRR ***/
int __cdecl HandleCrash(PEXCEPTION_POINTERS pExceptPtrs)
{
return 0;
}
#endif
void SetThreadName(const char* format, ...)
{
}
void GenerateUptimeString(char * Dest)
{
uint32 seconds = sWorld.GetUptime();
uint32 mins = 0;
uint32 hours = 0;
uint32 days = 0;
if(seconds >= 60)
{
mins = seconds / 60;
if(mins)
{
seconds -= mins*60;
if(mins >= 60)
{
hours = mins / 60;
if(hours)
{
mins -= hours*60;
if(hours >= 24)
{
days = hours/24;
if(days)
hours -= days*24;
}
}
}
}
}
sprintf(Dest, "%d days, %d hours, %d minutes, %d seconds", (int)days, (int)hours, (int)mins, (int)seconds);
}
#ifdef WIN32
float GetCPUUsageWin32()
{
CPerfCounters<LONGLONG> PerfCounters;
DWORD dwObjectIndex = PROCESS_OBJECT_INDEX;
DWORD dwCpuUsageIndex = PROCESSOR_TIME_COUNTER_INDEX;
int CpuUsage = 0;
LONGLONG lnNewValue = 0;
PPERF_DATA_BLOCK pPerfData = NULL;
LARGE_INTEGER NewPerfTime100nSec = {0};
lnNewValue = PerfCounters.GetCounterValueForProcessID(&pPerfData, dwObjectIndex, dwCpuUsageIndex, GetCurrentProcessId());
NewPerfTime100nSec = pPerfData->PerfTime100nSec;
if (m_bFirstTime)
{
m_bFirstTime = false;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
return 0;
}
LONGLONG lnValueDelta = lnNewValue - m_lnOldValue;
double DeltaPerfTime100nSec = (double)NewPerfTime100nSec.QuadPart - (double)m_OldPerfTime100nSec.QuadPart;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
double a = (double)lnValueDelta / DeltaPerfTime100nSec;
a /= double(number_of_cpus);
return float(a * 100.0);
}
float GetRAMUsageWin32()
{
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
float ram = (float)pmc.PagefileUsage;
ram /= 1024.0f;
ram /= 1024.0f;
return ram;
}
#endif
float GetCPUUsage()
{
#ifdef WIN32
return GetCPUUsageWin32();
#else
return 0.0f;
#endif
}
float GetRAMUsage()
{
#ifdef WIN32
return GetRAMUsageWin32();
#else
return 0.0f;
#endif
}
void FillOnlineTime(uint32 Time, char * Dest)
{
uint32 seconds = Time;
uint32 mins=0;
uint32 hours=0;
uint32 days=0;
if(seconds >= 60)
{
mins = seconds / 60;
if(mins)
{
seconds -= mins*60;
if(mins >= 60)
{
hours = mins / 60;
if(hours)
{
mins -= hours*60;
if(hours >= 24)
{
days = hours/24;
if(days)
hours -= days*24;
}
}
}
}
}
sprintf(Dest, "%d hours, %d minutes, %d seconds", (int)hours, (int)mins, (int)seconds);
}
void StatDumper::DumpStats()
{
if( Filename[0] == NULL )
return;
FILE* f = fopen( Filename, "w" );
if( !f )
return;
Log.Debug( "StatDumper", "Writing %s", Filename );
// Dump Header
fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(f, "<?xml-stylesheet type=\"text/xsl\" href=\"server_stats.xsl\"?>\n");
fprintf(f, "<serverpage>\n");
fprintf(f, " <status>\n");
uint32 races[RACE_DRAENEI+1];
uint32 classes[DRUID+1];
memset(&races[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
memset(&classes[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
std::deque<Player*> gms;
{
// Dump server information.
#ifdef WIN32
fprintf(f, " <platform>Ascent %s r%u/%s-Win-%s (www.ascentcommunity.com)</platform>\n", BUILD_TAG, BUILD_REVISION, CONFIG, ARCH);
#else
fprintf(f, " <platform>Ascent %s r%u/%s-%s (www.ascentcommunity.com)</platform>\n", BUILD_TAG, BUILD_REVISION, PLATFORM_TEXT, ARCH);
#endif
char uptime[80];
GenerateUptimeString(uptime);
float AvgLat;
uint32 GMCount;
int gm = 0;
int count = 0;
int avg = 0;
// lock players reader
objmgr._playerslock.AcquireReadLock();
HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;
for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
{
if(itr->second->GetSession() && itr->second->IsInWorld())
{
count++;
avg += itr->second->GetSession()->GetLatency();
if(itr->second->GetSession()->GetPermissionCount())
{
gm++;
gms.push_back(itr->second);
}
classes[itr->second->getClass()]++;
races[itr->second->getRace()]++;
}
}
objmgr._playerslock.ReleaseReadLock();
AvgLat = count ? (float)((float)avg / (float)count) : 0;
GMCount = gm;
fprintf(f, " <uptime>%s</uptime>\n", uptime);
fprintf(f, " <oplayers>%u</oplayers>\n", (unsigned int)(sWorld.AlliancePlayers + sWorld.HordePlayers));
fprintf(f, " <cpu>%2.2f</cpu>\n", GetCPUUsage());
fprintf(f, " <qplayers>%u</qplayers>\n", (unsigned int)sWorld.GetQueueCount());
fprintf(f, " <ram>%.3f</ram>\n", GetRAMUsage());
fprintf(f, " <avglat>%.3f</avglat>\n", AvgLat);
fprintf(f, " <threads>%u</threads>\n", (unsigned int)ThreadPool.GetActiveThreadCount());
fprintf(f, " <fthreads>%u</fthreads>\n", (unsigned int)ThreadPool.GetFreeThreadCount());
time_t t = (time_t)UNIXTIME;
fprintf(f, " <gmcount>%u</gmcount>\n", (unsigned int)GMCount);
fprintf(f, " <lastupdate>%s</lastupdate>\n", asctime(localtime(&t)));
fprintf(f, " <alliance>%u</alliance>\n", (unsigned int)sWorld.AlliancePlayers);
fprintf(f, " <horde>%u</horde>\n", (unsigned int)sWorld.HordePlayers);
fprintf(f, " <acceptedconns>%u</acceptedconns>\n", (unsigned int)sWorld.mAcceptedConnections);
fprintf(f, " <peakcount>%u</peakcount>\n", (unsigned int)sWorld.PeakSessionCount);
fprintf(f, " <wdbquerysize>%u</wdbquerysize>\n", WorldDatabase.GetQueueSize());
fprintf(f, " <cdbquerysize>%u</cdbquerysize>\n", CharacterDatabase.GetQueueSize());
}
fprintf(f, " </status>\n");
static const char * race_names[RACE_DRAENEI+1] = {
NULL,
"human",
"orc",
"dwarf",
"nightelf",
"undead",
"tauren",
"gnome",
"troll",
NULL,
"bloodelf",
"draenei",
};
static const char * class_names[DRUID+1] = {
NULL,
"warrior",
"paladin",
"hunter",
"rogue",
"priest",
NULL,
"shaman",
"mage",
"warlock",
NULL,
"druid",
};
fprintf(f, " <statsummary>\n");
uint32 i;
for(i = 0; i <= RACE_DRAENEI; ++i)
{
if( race_names[i] != NULL )
fprintf(f, " <%s>%u</%s>\n", race_names[i], races[i], race_names[i]);
}
for(i = 0; i <= DRUID; ++i)
{
if( class_names[i] != NULL )
fprintf(f, " <%s>%u</%s>\n", class_names[i], classes[i], class_names[i]);
}
fprintf(f, " </statsummary>\n");
Player * plr;
uint32 t = (uint32)time(NULL);
char otime[100];
{
fprintf(f, " <instances>\n");
// need a big buffer..
static char buf[500000];
memset(buf, 0, 500000);
// Dump Instance Information
//sWorldCreator.BuildXMLStats(buf);
sInstanceMgr.BuildXMLStats(buf);
fprintf(f, buf);
fprintf(f, " </instances>\n");
}
{
// GM Information
fprintf(f, " <gms>\n");
while(!gms.empty())
{
plr = gms.front();
gms.pop_front();
if(!plr->bGMTagOn)
continue;
FillOnlineTime(t - plr->OnlineTime, otime);
fprintf(f, " <gmplr>\n");
fprintf(f, " <name>%s</name>\n", plr->GetName());
fprintf(f, " <race>%u</race>\n", plr->getRace());
fprintf(f, " <class>%u</class>\n", (unsigned int)plr->getClass());
fprintf(f, " <gender>%u</gender>\n", (unsigned int)plr->getGender());
fprintf(f, " <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
fprintf(f, " <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
fprintf(f, " <map>%u</map>\n", (unsigned int)plr->GetMapId());
fprintf(f, " <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
fprintf(f, " <ontime>%s</ontime>\n", otime);
fprintf(f, " <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
fprintf(f, " <permissions>%s</permissions>\n", plr->GetSession()->GetPermissions());
fprintf(f, " </gmplr>\n");
}
fprintf(f, " </gms>\n");
}
{
fprintf(f, " <sessions>\n");
// Dump Player Information
objmgr._playerslock.AcquireReadLock();
HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;
for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
{
plr = itr->second;
if(itr->second->GetSession() && itr->second->IsInWorld())
{
FillOnlineTime(t - plr->OnlineTime, otime);
fprintf(f, " <plr>\n");
fprintf(f, " <name>%s</name>\n", plr->GetName());
fprintf(f, " <race>%u</race>\n", (unsigned int)plr->getRace());
fprintf(f, " <class>%u</class>\n", (unsigned int)plr->getClass());
fprintf(f, " <gender>%u</gender>\n", (unsigned int)plr->getGender());
fprintf(f, " <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
fprintf(f, " <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
fprintf(f, " <map>%u</map>\n", (unsigned int)plr->GetMapId());
fprintf(f, " <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
//requested by Zdarkside for he's online map. I hope it does not scre up any parser. If so, then make a better one :P
fprintf(f, " <xpos>%f</xpos>\n", plr->GetPositionX ());
fprintf(f, " <ypos>%f</ypos>\n", plr->GetPositionY());
fprintf(f, " <ontime>%s</ontime>\n", otime);
fprintf(f, " <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
fprintf(f, " </plr>\n");
if(plr->GetSession()->GetPermissionCount() > 0)
gms.push_back(plr);
}
}
objmgr._playerslock.ReleaseReadLock();
fprintf(f, " </sessions>\n");
}
fprintf(f, "</serverpage>\n");
fclose(f);
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1
],
[
3,
316
],
[
318,
318
],
[
320,
501
]
],
[
[
2,
2
],
[
317,
317
],
[
319,
319
]
]
]
|
1ad69874940c97cf42d0d2ce86edbf54af0d3147 | 8258620cb8eca7519a58dadde63e84f65d99cc80 | /rear/branches/movable-robot-camera-vers/Camera.h | a97f740274ac0beb367d4a65e0e7f3807244ba53 | []
| no_license | danieleferro/3morduc | bfdf4c296243dcd7c5ba5984bc899001bf74732b | a27901ae90065ded879f5dd119b2f44a2933c6da | refs/heads/master | 2016-09-06T06:02:39.202421 | 2011-03-23T08:51:56 | 2011-03-23T08:51:56 | 32,210,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | h | #ifndef __OPENGL
#define __OPENGL
#include <GL/glut.h> // Header File For The GLUT Library
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#endif
#ifndef __CAMERA__
#define __CAMERA__
#include "math.h"
/////////////////////////////////
//Note: All angles in degrees //
/////////////////////////////////
//Float 3d-vect, normally used
struct SF3dVector
{
GLfloat x,y,z;
};
struct SF2dVector
{
GLfloat x,y;
};
class Camera
{
private:
SF3dVector Position;
SF3dVector ViewDir; /*Not used for rendering the camera, but for "moveforwards"
So it is not necessary to "actualize" it always. It is only
actualized when ViewDirChanged is true and moveforwards is called*/
bool ViewDirChanged;
GLfloat RotatedX, RotatedY, RotatedZ;
void GetViewDir ( void );
public:
Camera(); //inits the values (Position: (0|0|0) Target: (0|0|-1) )
void Render ( void ); //executes some glRotates and a glTranslate command
//Note: You should call glLoadIdentity before using Render
void Move ( SF3dVector Direction );
void SetPosition(GLfloat x, GLfloat y, GLfloat z);
void SetViewDir(GLfloat x, GLfloat y, GLfloat z);
void RotateX ( GLfloat Angle );
void RotateY ( GLfloat Angle );
void RotateZ ( GLfloat Angle );
void RotateXYZ ( SF3dVector Angles );
void MoveForwards ( GLfloat Distance );
void StrafeRight ( GLfloat Distance );
};
SF3dVector F3dVector ( GLfloat x, GLfloat y, GLfloat z );
SF3dVector AddF3dVectors ( SF3dVector * u, SF3dVector * v);
void AddF3dVectorToVector ( SF3dVector * Dst, SF3dVector * V2);
#endif
| [
"loris.fichera@9b93cbac-0697-c522-f574-8d8975c4cc90"
]
| [
[
[
1,
64
]
]
]
|
5585cbe73aea98c705674db3fa6b471028e87094 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/ENIGMAsystem/SHELL/Universal_System/WITHconstruct.cpp | 5925154df2f61f44e3d6672f626eed41b0f0b1b5 | []
| no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,208 | cpp | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA is free software: you can redistribute it and/or modify it under the **
** terms of the GNU General Public License as published by the Free Software **
** Foundation, version 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
27
]
]
]
|
170ffd566cd7aa32f273fb3caff2b007f5b2b4d0 | 40e58042e635ea2a61a6216dc3e143fd3e14709c | /paradebot10/SimpleLog.h | 62d416a5dbaa56f585cc6f78e112e6f83685f6c0 | []
| no_license | chopshop-166/frc-2011 | 005bb7f0d02050a19bdb2eb33af145d5d2916a4d | 7ef98f84e544a17855197f491fc9f80247698dd3 | refs/heads/master | 2016-09-05T10:59:54.976527 | 2011-10-20T22:50:17 | 2011-10-20T22:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | h | /*******************************************************************************
* Project : Framework
* File Name : MemoryLog.h
* Owner : Software Group (FIRST Chopshop Team 166)
* Creation Date : January 18, 2010
* File Description : Header for general memory logger on chopshop robot
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <cstdio>
#include <ctime>
#include <string>
#include "FrameworkLogger.h"
using std::string;
//
// This class defines an interface to logging to memory and then into a .csv file
//
class SimpleLog : public FrameworkLogger
{
FILE *file;
public:
SimpleLog(string name, string values); // Format string
~SimpleLog();
bool PutOne(string frmtstr, ...); // Add some data to the log
bool operator()(string frmtstr, ...);
int DumpToFile(void); // Dump the log into a file
string name;
};
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
5e9706024706a34c8987b5de41ba697e42009a2c | 33b5565fb265463ed201c31f38ba3bd305a4e5d9 | /FLHook/trunk/src/source/HkCbDamage.cpp | 0b529bf3f9153e094510a929e97ea443d1ddcc50 | []
| no_license | HeIIoween/FLHook-And-88-Flak-m0tah | be1ee2fa0e240c24160dda168b8b23ad6aec2b48 | 3f0737f7456ef3eed5dd67cfec1b838d32b8b5e1 | refs/heads/master | 2021-05-07T14:00:34.880461 | 2011-01-28T00:21:41 | 2011-01-28T00:21:41 | 109,712,726 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,525 | cpp | #include "hook.h"
uint iDmgTo = 0;
uint iDmgToSpaceID = 0;
IObjRW *objDmgTo = 0;
Archetype::Equipment const *subObjArch = 0;
float fPrevHealth, fMaxHealth, fEquipPrevHealth, fEquipMaxHealth;
uint iType = 0;
bool bCrashyDmg = false;
bool g_gNonGunHitsBase = false;
float g_LastHitPts;
/**************************************************************************************************************
Called when a torp/missile/mine/wasp hits a ship
return 0 -> pass on to server.dll
return 1 -> suppress
**************************************************************************************************************/
FARPROC fpOldMissileTorpHit;
int __stdcall HkCB_MissileTorpHit(char *ECX, char *p1, DamageList *dmg)
{
try {
// get client id
char *szP;
memcpy(&szP, ECX + 0x10, 4);
uint iClientID;
memcpy(&iClientID, szP + 0xB4, 4);
iDmgTo = iClientID;
if(iClientID)
{ // a player was hit
uint iInflictorShip;
memcpy(&iInflictorShip, p1 + 4, 4);
uint iClientIDInflictor = HkGetClientIDByShip(iInflictorShip);
if(!iClientIDInflictor)
return 0; // hit by npc
if(!AllowPlayerDamage(iClientIDInflictor, iClientID))
return 1;
if(set_bChangeCruiseDisruptorBehaviour)
{
if(((dmg->get_cause() == 6) || (dmg->get_cause() == 0x15)) && !ClientInfo[iClientID].bCruiseActivated)
dmg->set_cause((enum DamageCause)0xC0); // change to sth else, so client won't recognize it as a disruptor
}
}
} catch(...) { LOG_EXCEPTION }
return 0;
}
__declspec(naked) void _HookMissileTorpHit()
{
__asm
{
mov eax, [esp+4]
mov edx, [esp+8]
push ecx
push edx
push eax
push ecx
call HkCB_MissileTorpHit
pop ecx
cmp eax, 1
jnz go_ahead
mov edx, [esp] ; suppress
add esp, 0Ch
jmp edx
go_ahead:
jmp [fpOldMissileTorpHit] //0x6CE9A90
}
}
void Clear_DmgTo()
{
iDmgToSpaceID = 0;
iDmgTo = 0;
objDmgTo = 0;
subObjArch = 0;
}
/**************************************************************************************************************
Called when ship was damaged
however you can't figure out here, which ship is being damaged, that's why i use the iDmgTo variable...
**************************************************************************************************************/
bool bTakeOverDmgEntry = false;
float fTakeOverHealth = 0.0f;
ushort iTakeOverSubObj = 0;
uint iTakeOverClientID = 0;
uint iTakeOverSpaceObj = 0;
DamageCause dcTakeOver = DC_HOOK;
void __stdcall HkCb_AddDmgEntry(DamageList *dmgList, unsigned short p1, float p2, enum DamageEntry::SubObjFate p3)
{
bool bAddDmgEntry = true;
DamageCause iRealDmgCause = dmgList->get_cause();
try {
if(bTakeOverDmgEntry)
{
p2 = fTakeOverHealth;
if(iTakeOverSubObj)
p1 = iTakeOverSubObj;
dmgList->set_inflictor_owner_player(iTakeOverClientID);
dmgList->set_inflictor_id(iTakeOverSpaceObj);
dmgList->set_cause(dcTakeOver);
dmgList->add_damage_entry(p1, p2, p3);
bTakeOverDmgEntry = false;
fTakeOverHealth = 0.0f;
iTakeOverSubObj = 0;
iTakeOverClientID = 0;
iTakeOverSpaceObj = 0;
dcTakeOver = DC_HOOK;
return;
}
//if(dmgList->is_inflictor_a_player())
//PrintUniverseText(L"p1=%u, p2=%f, DmgTo=%u, DmgToSpc=%u, iop=%u, id=%u cause=%u",p1, p2, iDmgTo, iDmgToSpaceID, dmgList->get_inflictor_owner_player(), dmgList->get_inflictor_id(), dmgList->get_cause());
//if(dmgList->is_inflictor_a_player()) {PrintUniverseText(L"%f", p2);}
if(g_gNonGunHitsBase && (dmgList->get_cause() == 5))
{
float fDamage = g_LastHitPts - p2;
p2 = g_LastHitPts - fDamage * set_fTorpMissileBaseDamageMultiplier;
if(p2 < 0)
p2 = 0;
}
if(set_bMissileDmgToMine && iRealDmgCause == DC_MISSILE)
dmgList->set_cause(DC_MINE);
else if(set_bTorpDmgToMine && iRealDmgCause == DC_TORPEDO)
dmgList->set_cause(DC_MINE);
if(!iDmgToSpaceID && iDmgTo)
pub::Player::GetShip(iDmgTo, iDmgToSpaceID);
/*if(objDmgTo)
{
uint *test = *((uint**)(objDmgTo)); //VFT
if(!test) //VFT missing !?!
Clear_DmgTo();
else
{
test += 2; //Second entry in VFT
if(!*test) //offset for some reason
objDmgTo = (IObjRW*)(((char*)objDmgTo) + 4);
objDmgTo->get_status(fPrevHealth, fMaxHealth);
}
}*/
if(!dmgList->get_inflictor_owner_player() && !dmgList->get_inflictor_id())
{
FLOAT_WRAP fw = FLOAT_WRAP(p2);
if(set_btSupressHealth->Find(&fw))
{
bAddDmgEntry = false;
}
}
//Check if damage should be redirected to hull
if(objDmgTo && p1 != 1 && p1 != 65521)
{
set<uint>::iterator equipIter = set_setEquipReDam.find(subObjArch->iEquipID);
if(equipIter != set_setEquipReDam.end())
{
float fHealth = fEquipPrevHealth;
p2 = fPrevHealth - (fHealth - p2);
p1 = 1;
}
}
//Repair Gun
if(g_bRepairPendHit)
{
if(dmgList->is_inflictor_a_player() && p2<=g_fRepairMaxHP)
{
dmgList->set_inflictor_owner_player(0); //NPCs don't mind you shooting at them when these are set to 0
dmgList->set_inflictor_id(0);
if(p1 != 65521) //Hull/equipment hit
{
if(p1 == 1) //Hull hit
{
p2 = g_fRepairDamage + g_fRepairBeforeHP;
if(p2 > g_fRepairMaxHP)
{
p2 = g_fRepairMaxHP;
}
}
else //Equipment hit
{
float fMaxHP = fEquipMaxHealth;
p2 = g_fRepairDamage + fEquipPrevHealth;
if(p2 > fMaxHP)
{
p2 = fMaxHP;
}
}
}
else //Shield hit
{
p2 += g_fRepairDamage;
float hullHealth = (g_fRepairBeforeHP + g_fRepairDamage*0.5f)/g_fRepairMaxHP;
if(hullHealth > 1.0f)
{
hullHealth = 1.0f;
}
pub::SpaceObj::SetRelativeHealth(g_iRepairShip, hullHealth);
}
}
g_bRepairPendHit = false;
}
} catch(...) { AddLog("Exception in %s0", __FUNCTION__); AddExceptionInfoLog(); AddLog("p1=%u, p2=%f, DmgTo=%u, DmgToSpc=%u, iop=%u, id=%u",p1, p2, iDmgTo, iDmgToSpaceID, dmgList->get_inflictor_owner_player(), dmgList->get_inflictor_id()); }
if(bAddDmgEntry)
{
dmgList->add_damage_entry(p1, p2, p3);
try {
if(objDmgTo && !bCrashyDmg && fPrevHealth)
{
uint iInflictor = dmgList->get_inflictor_id();
if(iInflictor)
{
if(iDmgTo)
{
if(p1 == 1)
{
DAMAGE_INFO dmgInfo;
dmgInfo.iInflictor = iInflictor;
dmgInfo.iCause = iRealDmgCause;
dmgInfo.fDamage = fPrevHealth - p2;
ClientInfo[iDmgTo].lstDmgRec.push_back(dmgInfo);
}
}
else if(p1 == 1)
{
if(iType & set_iNPCDeathType)
{
if(iRealDmgCause != DC_HOOK)
{
DAMAGE_INFO dmgInfo;
dmgInfo.fDamage = fPrevHealth - p2;
if(dmgInfo.fDamage > 0)
{
dmgInfo.iInflictor = iInflictor;
dmgInfo.iCause = iRealDmgCause;
if(p2 == 0 && iDmgToSpaceID / 1000000000)
{
lstSolarDestroyDelay.push_back(make_pair(iDmgToSpaceID, dmgInfo));
}
else
{
pair< map<uint, list<DAMAGE_INFO> >::iterator, bool> findSpaceObj = mapSpaceObjDmgRec.insert(make_pair(iDmgToSpaceID, list<DAMAGE_INFO>()));
findSpaceObj.first->second.push_back(dmgInfo);
}
}
}
}
if(p2 == 0)
{
if(iType & (OBJ_DOCKING_RING | OBJ_STATION))
{
uint iClientIDKiller = HkGetClientIDByShip(iInflictor);
BaseDestroyed(iDmgToSpaceID, iClientIDKiller);
}
}
}
}
}
} catch(...) {AddLog("Exception in %s1", __FUNCTION__); AddExceptionInfoLog(); }
}
Clear_DmgTo();
}
__declspec(naked) void _HkCb_AddDmgEntry()
{
__asm
{
push [esp+0Ch]
push [esp+0Ch]
push [esp+0Ch]
push ecx
call HkCb_AddDmgEntry
mov eax, [esp]
add esp, 10h
jmp eax
}
}
/**************************************************************************************************************
Called when ship was damaged
**************************************************************************************************************/
FARPROC fpOldGeneralDmg;
FARPROC fpOldOtherDmg;
void __stdcall HkCb_GeneralDmg(char *szECX)
{
try {
char *szP;
memcpy(&szP, szECX + 0x10, 4);
uint iClientID;
memcpy(&iClientID, szP + 0xB4, 4);
uint iSpaceID;
memcpy(&iSpaceID, szP + 0xB0, 4);
iDmgTo = iClientID;
iDmgToSpaceID = iSpaceID;
objDmgTo = (IObjRW*)szECX;
objDmgTo->get_status(fPrevHealth, fMaxHealth);
objDmgTo->get_type(iType);
bCrashyDmg = false;
} catch(...) { LOG_EXCEPTION }
}
__declspec(naked) void _HkCb_GeneralDmg()
{
__asm
{
push ecx
push ecx
call HkCb_GeneralDmg
pop ecx
jmp [fpOldGeneralDmg]
}
}
void __stdcall HkCb_OtherDmg(char *szECX, CEquip *equip)
{
try {
char *szP;
memcpy(&szP, szECX + 0x10, 4);
uint iClientID;
memcpy(&iClientID, szP + 0xB4, 4);
uint iSpaceID;
memcpy(&iSpaceID, szP + 0xB0, 4);
iDmgTo = iClientID;
iDmgToSpaceID = iSpaceID;
objDmgTo = (IObjRW*)szECX;
objDmgTo->get_status(fPrevHealth, fMaxHealth);
if(equip)
{
fEquipPrevHealth = equip->GetHitPoints();
fEquipMaxHealth = equip->GetMaxHitPoints();
subObjArch = equip->EquipArch();
}
else
{
subObjArch = 0;
}
objDmgTo->get_type(iType);
bCrashyDmg = true;
} catch(...) { LOG_EXCEPTION }
}
__declspec(naked) void _HkCb_OtherDmg()
{
__asm
{
push ecx
push [esp+8]
push ecx
call HkCb_OtherDmg
pop ecx
jmp [fpOldOtherDmg]
}
}
/**************************************************************************************************************
Called when ship was damaged
**************************************************************************************************************/
bool AllowPlayerDamage(uint iClientID, uint iClientIDTarget)
{
if(iClientID == iClientIDTarget)
return true;
if(iClientIDTarget)
{
// anti-dockkill check
if((timeInMS() - ClientInfo[iClientIDTarget].tmSpawnTime) <= set_iAntiDockKill)
return false; // target is protected
if((timeInMS() - ClientInfo[iClientID].tmSpawnTime) <= set_iAntiDockKill)
return false; // target may not shoot
// no-pvp token check
if(ClientInfo[iClientID].bNoPvp || ClientInfo[iClientIDTarget].bNoPvp)
return false;
// no-pvp check
uint iSystemID;
pub::Player::GetSystem(iClientID, iSystemID);
foreach(set_lstNoPVPSystems, uint, i)
{
if(iSystemID == (*i))
return false; // no pvp
}
}
return true;
}
/**************************************************************************************************************
**************************************************************************************************************/
FARPROC fpOldNonGunWeaponHitsBase;
float fHealthBefore;
uint iHitObject;
uint iClientIDInflictor;
void __stdcall HkCb_NonGunWeaponHitsBaseBefore(char *ECX, char *p1, DamageList *dmg)
{
CSimple *simple;
memcpy(&simple, ECX + 0x10, 4);
g_LastHitPts = simple->get_hit_pts();
/* try {
// get client id
char *szP;
memcpy(&szP, ECX + 0x10, 4);
memcpy(&iHitObject, szP + 0xB0, 4);
float fMaxHealth;
pub::SpaceObj::GetHealth(iHitObject, fHealthBefore, fMaxHealth);
uint iInflictorShip;
memcpy(&iInflictorShip, p1 + 4, 4);
iClientIDInflictor = HkGetClientIDByShip(iInflictorShip);
} catch(...) { LOG_EXCEPTION } */
g_gNonGunHitsBase = true;
}
void HkCb_NonGunWeaponHitsBaseAfter()
{
g_gNonGunHitsBase = false;
/* if(!fHealthBefore)
return; // was already destroyed
uint iType;
pub::SpaceObj::GetType(iHitObject, iType);
if(iType & 0x100) // 0x20 = docking ring, 0x02 = planet, 0x100 = base, 0x80 = tradelane
{
float fHealth;
float fMaxHealth;
pub::SpaceObj::GetHealth(iHitObject, fHealth, fMaxHealth);
if(!fHealth)
BaseDestroyed(iHitObject, iClientIDInflictor);
} */
}
ulong lRetAddress;
__declspec(naked) void _HkCb_NonGunWeaponHitsBase()
{
__asm
{
mov eax, [esp+4]
mov edx, [esp+8]
push ecx
push edx
push eax
push ecx
call HkCb_NonGunWeaponHitsBaseBefore
pop ecx
mov eax, [esp]
mov [lRetAddress], eax
lea eax, return_here
mov [esp], eax
jmp [fpOldNonGunWeaponHitsBase]
return_here:
pushad
call HkCb_NonGunWeaponHitsBaseAfter
popad
jmp [lRetAddress]
}
} | [
"M0tah@62241663-6891-49f9-b8c1-0f2e53ca0faf"
]
| [
[
[
1,
485
]
]
]
|
454c5ec922c5ac781134b0ac08b2720a4252b6e1 | 826479e30cfe9f7b9a1b7262211423d8208ffb68 | /RayTracer/CRay.h | a17aeb3d5f3cd0a5337e4058b4cf1499285813ac | []
| no_license | whztt07/real-time-raytracer | 5d1961c545e4703a3811fd7eabdff96017030abd | f54a75aed811b8ab6a509c70f879739896428fff | refs/heads/master | 2021-01-17T05:33:13.305151 | 2008-12-19T20:17:30 | 2008-12-19T20:17:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | h | // Author : Jean-Rene Bedard ([email protected])
#pragma once
#include "CVector.h"
class CRay
{
public:
CRay();
CRay(CVector &orig, CVector &dir);
virtual ~CRay();
CVector inline Reflect(CVector &n);
CVector o,d;
};
CVector inline CRay::Reflect(CVector &n)
{
return n * 2 * (n * -d) + d;
} | [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
c0cd9e95eb5e6144d5919e43dc06cd9091576c62 | 027eda7f41dc38eddeed50713bc23328c5bab6b4 | /Reversi/Reversi/gamecomm.h | c703a7b661e9cb1317372ab921d1cfc820944263 | []
| no_license | iamjwc/CS438 | 6e9872c88f639316beff32cc60bd4d5edf9cd037 | 9ebceb46abe063c3cacff299e0750b608358b216 | refs/heads/master | 2021-01-04T14:21:34.738661 | 2011-10-21T23:07:03 | 2011-10-21T23:07:03 | 2,623,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | h | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#define ROWS 8
#define COLS 8
using namespace std;
bool getGameBoard(int iGameBoard[ROWS][COLS])
{
int iCur;
char cInput;
ifstream in("board.txt");
for(iCur=0; iCur<ROWS*COLS; iCur++)
{
cInput=in.get();
switch(cInput)
{
case '\n':
case '\t':
iCur--;
break;
case 'X':
case 'x':
case '-':
iGameBoard[iCur/COLS][iCur%COLS] = -1;
break;
case 'O':
case 'o':
case '0':
case '+':
iGameBoard[iCur/COLS][iCur%COLS] = 1;
break;
case ' ':
case '.':
case '_':
iGameBoard[iCur/COLS][iCur%COLS] = 0;
break;
default:
in.close();
return false;
}
}
in.close();
return true;
}
bool putMove(int iMoveRow, int iMoveCol)
{
ofstream out("move.txt");
if(iMoveCol>=COLS || iMoveCol<0)
return false;
if(iMoveRow>=ROWS || iMoveRow<0)
return false;
out << iMoveRow << " " << iMoveCol << endl;
out.close();
return true;
} | [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
33e1aaaa560cec7cc7e22e957d6ef526f9cd602b | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_M6/Thread/Mutex.cpp | 7f4661983f218459bb0d00e174f613a412b8d418 | []
| no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | /**
* Mutex
*
* SE2 (+ SY and PL) Project SoSe 2011
*
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Mutex for a threadsafe implementation.
*
*/
#include "Mutex.h"
Mutex::Mutex() {
pthread_mutex_init(&mutex,NULL);
}
Mutex::~Mutex() {
pthread_mutex_destroy(&mutex);
}
void Mutex::lock(){
pthread_mutex_lock(&mutex);
}
void Mutex::unlock(){
pthread_mutex_unlock(&mutex);
}
pthread_mutex_t* Mutex::getMutex(){
return &mutex;
}
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
]
| [
[
[
1,
35
]
]
]
|
b97d8bfe3f7d46eb6037cb78fed681c4409d6da1 | db0d644f1992e5a82e22579e6287f45a8f8d357a | /Caster/Dispatcher/CallBack.h | 3615620a0ecd26990d2538ef8d99219fd0a49d72 | []
| no_license | arnout/nano-cast | 841a6dc394bfb30864134bce70e11d29b77c2411 | 5d11094da4dbb5027ce0a3c870b6a6cc9fcc0179 | refs/heads/master | 2021-01-01T05:14:29.996348 | 2011-01-15T17:27:48 | 2011-01-15T17:27:48 | 58,049,740 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,976 | h | #ifndef HandlerIncluded
#define HandlerIncluded
/*** dummy autodoc comment */
#include "Util.h" // for NULL
#include "List.h"
class Pollable;
class CallBack;
/** A CallBack is an object invoked to process an event
A CallBack can be placed in a queue to be processed when an
event of interest happens, say when data is available
on a socket or a new connection arrives. Also, one
CallBack can schedule another, allowing callbacks to
be daisy-chained together to form more complex functions.
This is a base class which should be used for
all callback functions. Each derived class provides a
Call() method, a destructor and data fields.
*/
typedef Status (CallBack::*CallBackMethod)(Status status);
class CallBack {
public:
CallBack* next;
bool status;
CallBackMethod Call;
public:
virtual ~CallBack(){}
/** Invoke the callback.
@param status indicates a possible error for the callback to handle
@returns !OK if the callback is complete and should be destroyed
*/
//virtual bool DefaultCall(bool status = OK)
//{return Error("CallBack base class shouldn't be called\n");}
/// Destroy the current callback and invoke the next
//CallBack* OnExit(CallBack* c);
//bool Exit(bool status = OK);
//bool Switch(CallBack* c, bool status = OK) ;
/// Schedule the current callback when data is available
bool WaitForRead(Pollable *p, int timeout = -1);
bool WaitForWrite(Pollable *p, int timeout = -1);
/// Reschedule the current callback
//bool Yield();
};
/// A WaitList is a list of CallBacks which are waiting for something
class WaitList : public List<CallBack>
{
public:
/// Add a CallBack to the waitlist
bool Wait(CallBack *c);
/// Invoke all the CallBacks on the waitlist
bool WakeupWaiters(bool status=OK);
};
#endif // BaseFragmentIncluded
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
f914fe3fc8680fc8c690b0dbd8fad0737056541d | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/DataTypes.h | 281fd9100ddeccbdf2b338d3ac8fb96bf1568b0c | []
| no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,719 | h | #pragma once
#include <windows.h>
#define WIN32_LEAN_AND_MEAN
#ifdef _WIN64
#define X64
#endif
#undef max
#undef min
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef unsigned char uchar;
typedef uchar byte;
typedef ushort word;
typedef ulong dword;
typedef unsigned long long qword;
typedef char int8;
typedef short int16;
typedef long int32;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned long uint32;
#ifdef _MSC_VER
typedef unsigned __int64 uint64;
#else
typedef unsigned long long uint64;
#endif
typedef uint index_t;
#ifdef X64
typedef uint64 ptr_t;
#else
typedef uint32 ptr_t;
#endif
typedef char s8;
typedef short s16;
typedef long s32;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
typedef unsigned long long u64;
template<class t>
class be_v {
public:
t n;
static u8 convert8(u8 n) {return n;}
static u8 convert(u8 n) {return n;}
static u16 convert16(u16 n) {return ((n&0xFF)<<8)|((n&0xFF00)>>8);}
static u16 convert(u16 n) {return ((n&0xFF)<<8)|((n&0xFF00)>>8);}
static u32 convert32(u32 n) {return ((n&0xFF)<<24)|((n&0xFF00)<<8)|((n&0xFF0000)>>8)|((n&0xFF000000)>>24);}
static u32 convert(u32 n) {return ((n&0xFF)<<24)|((n&0xFF00)<<8)|((n&0xFF0000)>>8)|((n&0xFF000000)>>24);}
be_v(t nn) : n(convert(nn)) {}
operator t() {return convert(n);}
be_v() {}
};
typedef be_v<s8> ns8;
typedef be_v<s16> ns16;
typedef be_v<s32> ns32;
typedef be_v<u8> nu8;
typedef be_v<u16> nu16;
typedef be_v<u32> nu32;
typedef void* PVOID;
#define NULL 0
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
]
| [
[
[
1,
73
]
]
]
|
49e1095bca8a784ee94cf1298d2b620c6f801e7d | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_代码统计专用文件夹/C++Primer中文版(第4版)/第十四章 重载操作符与转换/20090221_习题14.37_使用标准库函数对象和函数适配器定义一个对象.cpp | f8fe91d76f3e118f144ee54a11f931364e522f46 | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,283 | cpp | #include <iostream>
#include <functional>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
vector<string> svec;
string str;
cout << "Enter numbers(Ctrl+Z to end):" << endl;
while (cin >> ival)
ivec.push_back(ival);
cin.clear();
cout << "Enter some strings(Ctrl+Z to end):" << endl;
while (cin >> str)
svec.push_back(str);
cin.clear();
//查找大于1024的所有值
cout << "all values that are greater than 1024:" << endl;
vector<int>::iterator iter = ivec.begin();
while ((iter = find_if(iter, ivec.end(), bind2nd(greater<int>(), 1024)))
!= ivec.end()) {
cout << *iter << " ";
++iter;
}
//查找不等于"pooh"的所有字符串
cout << endl << "all strings that are not equal to pooh:" << endl;
vector<string>::iterator it = svec.begin();
while ((it = find_if(it, svec.end(), bind2nd(not_equal_to<string>(), "pooh")))
!= svec.end()) {
cout << *it << " ";
++it;
}
//将所有值乘以2
transform(ivec.begin(), ivec.end(), ivec.begin(), bind2nd(multiplies<int>(), 2));
cout << endl << "all values multiplies by 2:" << endl;
for (iter = ivec.begin(); iter != ivec.end(); ++iter)
cout << *iter << " ";
return 0;
}
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
50
]
]
]
|
8da7c0211b25ab2d6bd21a88f4d7bb176a1bee39 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/rules/include/Kampftechnik.h | 3f7bda70dec9c4fc462ba249f542dbf2c9582cb4 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __KAMPFTECHNIK_H__
#define __KAMPFTECHNIK_H__
#include "RulesPrerequisites.h"
#include "Tripel.h"
namespace rl
{
class _RlRulesExport Kampftechnik
{
private:
const CeGuiString mName;
const CeGuiString mDescription;
const int mEbe;
public:
Kampftechnik(const CeGuiString name,
const CeGuiString description,
int ebe);
bool operator==(const Kampftechnik& rhs) const;
bool operator<(const Kampftechnik& rhs) const;
CeGuiString getName() const;
CeGuiString getDescription() const;
int getEbe() const;
/// Berechnet effektive Behinderung
int calculateEbe(int be) const;
};
}
#endif //__KAMPFTECHNIK_H__
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
46
]
]
]
|
1df72992fd920bca1b619fbaea9df1d04165382e | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread_cond_timedwait.cpp | 3e55fd9a9f93bb4a4c44f6d0f17127706bf571cf | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | /*
* Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: POSIX implementation of pthread on Symbian
*
*/
#include "condvartypes.h"
EXPORT_C int pthread_cond_timedwait (pthread_cond_t * cond,pthread_mutex_t * mutex,const struct timespec *abstime)
{
if(!abstime)
{
return EINVAL;
}
return _internalCondWait(cond,mutex,abstime);
}
//End of File
| [
"none@none"
]
| [
[
[
1,
32
]
]
]
|
9e84940e4c23799f947ac8edb4d7ac10b00fae45 | 9566086d262936000a914c5dc31cb4e8aa8c461c | /EnigmaClient-Ogre/InGameChatManager.cpp | 3f670a1d015c3c3bde2e0190061257ffa74bcdf1 | []
| no_license | pazuzu156/Enigma | 9a0aaf0cd426607bb981eb46f5baa7f05b66c21f | b8a4dfbd0df206e48072259dbbfcc85845caad76 | refs/heads/master | 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 9,605 | cpp | /*
Copyright © 2011 Christopher Joseph Dean Schaefer (disks86)
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "InGameChatManager.hpp"
namespace Enigma
{
InGameChatManager::InGameChatManager(ClientTransmissionManager& clientTransmissionManager)
: ScreenManager(clientTransmissionManager)
{
this->mHistorySize=4096; //controls the number of history entries that are kept.
this->mClientTransmissionManager.GetClientSessionManager().RegisterChatEventListener(this);
}
InGameChatManager::~InGameChatManager()
{
}
void InGameChatManager::RegisterEvents()
{
CEGUI::Window* window = NULL;
window = CEGUI::WindowManager::getSingleton().getWindow("ChatWindow/ChatTabControl/MainChatWindow/MainChatEditbox");
if(window!=NULL)
{
window->subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&InGameChatManager::onMainChatTextAccepted, this));
}
window = CEGUI::WindowManager::getSingleton().getWindow("ChatWindow/ChatTabControl/PartyChatWindow/PartyChatEditbox");
if(window!=NULL)
{
window->subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&InGameChatManager::onPartyChatTextAccepted, this));
}
window = CEGUI::WindowManager::getSingleton().getWindow("ChatWindow/ChatTabControl/GuildChatWindow/GuildChatEditbox");
if(window!=NULL)
{
window->subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&InGameChatManager::onGuildChatTextAccepted, this));
}
window = CEGUI::WindowManager::getSingleton().getWindow("ChatWindow/ChatTabControl/MiscChatWindow/MiscChatEditbox");
if(window!=NULL)
{
window->subscribeEvent(CEGUI::Editbox::EventTextAccepted, CEGUI::Event::Subscriber(&InGameChatManager::onMiscChatTextAccepted, this));
}
}
bool InGameChatManager::onMainChatTextAccepted(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Editbox* chatText = static_cast<CEGUI::Editbox*> (winMgr.getWindow("ChatWindow/ChatTabControl/MainChatWindow/MainChatEditbox"));
std::string text = chatText->getText().c_str();
this->mClientTransmissionManager.GetClientSessionManager().ProcessCommand(text,CHAT_TYPE_MAP);
// Clear the text in the Editbox
chatText->setText("");
return true;
}
bool InGameChatManager::onPartyChatTextAccepted(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Editbox* chatText = static_cast<CEGUI::Editbox*> (winMgr.getWindow("ChatWindow/ChatTabControl/PartyChatWindow/PartyChatEditbox"));
std::string text = chatText->getText().c_str();
this->mClientTransmissionManager.GetClientSessionManager().ProcessCommand(text,CHAT_TYPE_PARTY);
// Clear the text in the Editbox
chatText->setText("");
return true;
}
bool InGameChatManager::onGuildChatTextAccepted(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Editbox* chatText = static_cast<CEGUI::Editbox*> (winMgr.getWindow("ChatWindow/ChatTabControl/GuildChatWindow/GuildChatEditbox"));
std::string text = chatText->getText().c_str();
this->mClientTransmissionManager.GetClientSessionManager().ProcessCommand(text,CHAT_TYPE_GUILD);
// Clear the text in the Editbox
chatText->setText("");
return true;
}
bool InGameChatManager::onMiscChatTextAccepted(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Editbox* chatText = static_cast<CEGUI::Editbox*> (winMgr.getWindow("ChatWindow/ChatTabControl/MiscChatWindow/MiscChatEditbox"));
std::string text = chatText->getText().c_str();
this->mClientTransmissionManager.GetClientSessionManager().ProcessCommand(text,CHAT_TYPE_BROADCAST);
// Clear the text in the Editbox
chatText->setText("");
return true;
}
void InGameChatManager::AddChatText(const CEGUI::String& text,const CEGUI::String& name)
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Listbox* chatHistory = static_cast<CEGUI::Listbox*> (winMgr.getWindow(name));
if(!text.empty())
{
CEGUI::ListboxTextItem* chatItem;
if(chatHistory->getItemCount() == mHistorySize)
{
chatItem = static_cast<CEGUI::ListboxTextItem*>(chatHistory->getListboxItemFromIndex(0));
chatItem->setAutoDeleted(false);
chatHistory->removeItem(chatItem);
chatItem->setAutoDeleted(true);
chatItem->setText(text);
}
else
{
chatItem = new CEGUI::ListboxTextItem(text);
}
chatHistory->addItem(chatItem);
chatHistory->ensureItemIsVisible(chatHistory->getItemCount());
}
}
void InGameChatManager::onInvited(size_t chatType, size_t inviteId, const std::string& organizationName)
{
}
void InGameChatManager::onJoined(size_t chatType, const std::string& organizationName)
{
std::stringstream s;
std::string text;
switch(chatType)
{
case CHAT_TYPE_GUILD:
s << "You have joined the " << organizationName << " guild." << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/GuildChatWindow/GuildChatListBox");
break;
case CHAT_TYPE_PARTY:
s << "You have joined " << organizationName << "'s party." << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/PartyChatWindow/PartyChatListBox");
break;
default:
break;
}
}
void InGameChatManager::onRankModified(size_t chatType, const std::string& rankName, size_t permissions)
{
}
void InGameChatManager::onModified(size_t chatType, const std::string& playerName, const std::string& rankName)
{
}
void InGameChatManager::onExpelled(size_t chatType, const std::string& organizationName, const std::string& reason)
{
std::stringstream s;
std::string text;
switch(chatType)
{
case CHAT_TYPE_GUILD:
s << "You have been expelled from the " << organizationName << " guild." << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/GuildChatWindow/GuildChatListBox");
break;
case CHAT_TYPE_PARTY:
s << "You have been expelled from " << organizationName << "'s party." << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/PartyChatWindow/PartyChatListBox");
break;
default:
break;
}
}
void InGameChatManager::onReceivedMessage(size_t chatType, const std::string& message, const std::string& sender)
{
std::stringstream s;
std::string text;
switch(chatType)
{
case CHAT_TYPE_BROADCAST:
s << sender << " broadcast: " << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MiscChatWindow/MiscChatListBox");
break;
case CHAT_TYPE_GUILD:
s << sender << " from your guild said: " << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/GuildChatWindow/GuildChatListBox");
break;
case CHAT_TYPE_MAP:
s << sender << " shouted: " << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MainChatWindow/MainChatListBox");
break;
case CHAT_TYPE_PARTY:
s << sender << " from your party said: " << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/PartyChatWindow/PartyChatListBox");
break;
case CHAT_TYPE_SYSTEM:
s << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MiscChatWindow/MiscChatListBox");
break;
case CHAT_TYPE_WHISPER:
s << sender << " whispered: " << message << std::endl;
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MainChatWindow/MainChatListBox");
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/PartyChatWindow/PartyChatListBox");
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/GuildChatWindow/GuildChatListBox");
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MiscChatWindow/MiscChatListBox");
break;
default:
s << sender << " spoke strangely: " << message << std::endl; //this shouldn't happen.
text=s.str();
this->AddChatText(text.c_str(),"ChatWindow/ChatTabControl/MiscChatWindow/MiscChatListBox");
break;
}
}
void InGameChatManager::onNpcResponse(size_t npcId, const std::string& response, const std::vector<std::string>& playerResponses)
{
}
}; | [
"[email protected]"
]
| [
[
[
1,
254
]
]
]
|
41b691f552790510e024fd83ebba7f696df8f21b | 4e418f441766936ec16715b54ec21eae25f63e86 | /lib/camera.h | 6c8323d6f83f7e3db3149e5df7d912593fdd432a | []
| no_license | DanielaSfregola/New-Elite | a02b24658cf7da2e63d977d144e9196beff5f06d | e58b41cafc86fdc59566f47dbd208a7fce40e9dd | refs/heads/master | 2021-01-25T08:48:58.591374 | 2011-05-28T19:04:06 | 2011-05-28T19:04:06 | 1,815,140 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | h | #ifndef _CAMERA_H
#define _CAMERA_H
#include <GL/glut.h>
#include "eliteutils.h"
/* ----------------------------------------------------------
Classe che implementa una telecamera in moviento. Lo stato della
telecamera e' dato dala sua posizione dal versore up e dal versore
della direzione di vista. La classe consente di gestire il movimento
della tc aggiornando lo stato e chiamando la glLookAt con i parametri
opportuni.
------------------------------------------------------------- */
class Camera {
public:
static const GLfloat MAXSPEED=0.01;
// vecchia velocita'
// static const GLfloat MAXSPEED=0.001;
// costruttore
Camera(GLfloat x, GLfloat y, GLfloat z);
/* cambia angolo di ROLL (rollio):
inclinazione del muso verso l'alto o verso il basso
*/
void roll(GLfloat angle);
/* cambia angolo di YAW (imbardata):
rotazione laterale dell'aereo
*/
void yaw(GLfloat angle);
/* cambia angolo di PITCH (beccheggio):
inclinazione laterale dell'aereo
*/
void pitch(GLfloat angle);
// aggiorna velocita'
void accelerate(GLfloat step);
// avanza di uno step, nella direzione di view
void step(GLfloat s);
// avanza in base alla velocita' (da chiamare in idle() )
void advance(GLfloat t);
// al posto della gluLookAt
void look();
// restituisce la posizione
Point3 getPos();
// restituisce la direzione di vista
Point3 getView();
// restituisce la direzione a destra
Point3 getRight();
// restituisce la direzione alto
Point3 getUp();
// restituisce la velocita'
GLfloat getSpeed();
// restituisce il massimo della velocità a cui puo' arrivare
GLfloat getMaxSpeed();
private:
Point3 eye;
Point3 view;
Point3 up;
float velocity;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
80
]
]
]
|
e9585d11d51b686f86ec6474d1a939257c36bc7c | 117838783b18e0e24ae9b0541f850fbefc89de30 | /sqlite3x/sqlite3x_cursor.cpp | 974dc4fee0a95c2bb4412ac50125d62fe704e118 | []
| no_license | r0ssar00/platform | 39950b156d5b7b478e87ce78762912bde0b6d7ed | 3868a9941bdff3749abfec02173c9d456b494ef3 | refs/heads/master | 2021-01-19T09:42:28.110732 | 2009-08-16T14:13:25 | 2009-08-16T14:13:25 | 147,022 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,893 | cpp | /*
Copyright (C) 2004-2005 Cory Nelson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <sqlite3.h>
#include "sqlite3x.hpp"
namespace sqlite3x {
sqlite3_cursor::sqlite3_cursor() : cmd(NULL) {}
sqlite3_cursor::sqlite3_cursor(const sqlite3_cursor ©) : cmd(copy.cmd) {
if(this->cmd) ++this->cmd->refs;
}
sqlite3_cursor::sqlite3_cursor(sqlite3_command & cmd) : cmd(&cmd) {
++this->cmd->refs;
}
sqlite3_cursor::~sqlite3_cursor() {
this->close();
}
sqlite3_cursor& sqlite3_cursor::operator=(const sqlite3_cursor ©) {
this->close();
this->cmd=copy.cmd;
if(this->cmd) ++this->cmd->refs;
return *this;
}
int sqlite3_cursor::colcount()
{
if( ! this->cmd )
{
throw database_error("sqlite3_cursor::colcount(): reader is closed");
}
return this->cmd->colcount();
}
bool sqlite3_cursor::step() {
if(!this->cmd) throw database_error("sqlite3_cursor::step(): reader is closed");
switch(sqlite3_step(this->cmd->stmt)) {
case SQLITE_ROW:
return true;
case SQLITE_DONE:
return false;
default:
throw database_error(this->cmd->con);
}
}
void sqlite3_cursor::reset() {
if(!this->cmd) throw database_error("sqlite3_cursor::reset(): reader is closed");
if(! this->cmd->reset() )
{
throw database_error("sqlite3_cursor::reset() db error: %s", this->cmd->con.errormsg().c_str() );
}
}
void sqlite3_cursor::close() {
if(this->cmd) {
if(--this->cmd->refs==0) { sqlite3_reset(this->cmd->stmt); }
this->cmd=NULL;
}
}
#define READER_CHECK(FUNC) \
if( ! this->cmd ) throw database_error( "sqlite3_cursor::%s(%d): reader is closed", # FUNC, index ); \
if( (index)>(this->cmd->argc-1)) throw database_error("sqlite3_cursor::%s(%d): index out of range", # FUNC, index );
bool sqlite3_cursor::isnull(int index) {
READER_CHECK(isnull);
return sqlite3_column_type(this->cmd->stmt, index) == SQLITE_NULL;
}
int sqlite3_cursor::getint(int index) {
READER_CHECK(getint);
return sqlite3_column_int(this->cmd->stmt, index);
}
int64_t sqlite3_cursor::getint64(int index) {
READER_CHECK(getint64);
return sqlite3_column_int64(this->cmd->stmt, index);
}
double sqlite3_cursor::getdouble(int index) {
READER_CHECK(getdouble);
return sqlite3_column_double(this->cmd->stmt, index);
}
std::string sqlite3_cursor::getstring(int index) {
READER_CHECK(string);
return std::string((const char*)sqlite3_column_text(this->cmd->stmt, index), sqlite3_column_bytes(this->cmd->stmt, index));
}
char const * sqlite3_cursor::getstring(int index, int & size) {
READER_CHECK(string);
size = sqlite3_column_bytes(this->cmd->stmt, index);
return (char const *)sqlite3_column_text(this->cmd->stmt, index);
}
#if SQLITE3X_USE_WCHAR
std::wstring sqlite3_cursor::getstring16(int index) {
READER_CHECK(wstring);
return std::wstring((const wchar_t*)sqlite3_column_text16(this->cmd->stmt, index), sqlite3_column_bytes16(this->cmd->stmt, index)/2);
}
#endif
std::string sqlite3_cursor::getblob(int index) {
READER_CHECK(string);
return std::string((const char*)sqlite3_column_blob(this->cmd->stmt, index), sqlite3_column_bytes(this->cmd->stmt, index));
}
void const * sqlite3_cursor::getblob(int index, int & size ) {
READER_CHECK(string);
size = sqlite3_column_bytes(this->cmd->stmt, index);
return sqlite3_column_blob(this->cmd->stmt, index);
}
std::string sqlite3_cursor::getcolname(int index) {
READER_CHECK(string);
char const * cn = sqlite3_column_name(this->cmd->stmt, index);
return cn ? cn : "";
}
// char const * sqlite3_cursor::getcolname(int index) {
// READER_CHECK(string);
// char const * cn = sqlite3_column_name(this->cmd->stmt, index);
// return cn ? cn : "";
// }
#if SQLITE3X_USE_WCHAR
std::wstring sqlite3_cursor::getcolname16(int index) {
READER_CHECK(wstring);
return (const wchar_t*)sqlite3_column_name16(this->cmd->stmt, index);
}
#endif
#undef READER_CHECK
}
| [
"[email protected]"
]
| [
[
[
1,
161
]
]
]
|
bee7fafaea94ec8ab2977d6be05f5dcfe816fc12 | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbFt/ftlist.cpp | 9229ee58ccf578b5fa1827b773a1149a4d1cfb2d | []
| no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,972 | cpp | #include "stdafx.h"
#include "ftlist.h"
#include "fthooks.h"
#include "ftpanel.h"
#include "fttourneylist.h"
FTLists::FTLists(QWidget *widget, QObject *parent) : FTWidgetHook(widget, parent)
{
}
FTList *FTLists::list(QString id)
{
FTList *list = qobject_cast<FTList*>(hookFor(id));
return list;
}
void FTLists::listUpdated(FTList *list)
{
emit listUpdatedEvent(list);
}
void FTLists::onRowsInserted(QAbstractItemView *view, int start, int end)
{
FTList *alist = qobject_cast<FTList*>(hookFor(view));
QAbstractItemModel *model = view->model();
//qLog(Debug)<<"rowsInserted("<<start<<","<<end<<")"<<QTUtil::widgetInfo(view)<<", model "<<model->metaObject()->className()<<":"<<model->objectName();
//FTList::dump(model,start, end);
if(0==alist)
{
QString modelClass = model->metaObject()->className();
//qLog(Info)<<"LIST-WIDGET "<<QTUtil::widgetInfo(view)<<" MODEL: "<<modelClass;
if(start==0)
{
if(ftSngLobbyModel==modelClass)
{
alist = new FTTourneyList(view, this);
alist->setObjectName(modelClass);
}
}
if(view->objectName()=="list_1")
{
alist = new FTList(view, this);
alist->setObjectName("filter1");
alist->setPainterMode(true);
}else if(view->objectName()=="list_2")
{
alist = new FTList(view, this);
alist->setObjectName("filter2");
alist->setPainterMode(true);
}else if(view->objectName()=="list_3")
{
alist = new FTList(view, this);
alist->setObjectName("filter3");
alist->setPainterMode(true);
}else if(view->objectName()=="list_4")
{
alist = new FTList(view, this);
alist->setObjectName("filter4");
alist->setPainterMode(true);
}else if(view->objectName()=="list_5")
{
alist = new FTList(view, this);
alist->setObjectName("filter5");
alist->setPainterMode(true);
}
//qLog(Debug)<<"rowsInserted("<<start<<","<<end<<")"<<QTUtil::widgetInfo(view)<<", model "<<model->metaObject()->className()<<":"<<model->objectName();
}
if(alist)
alist->onRowsInserted(view, start, end);
}
void FTLists::onWidgetSetVisible(QWidget *w, bool isVisible)
{
FTWidgetHook::onWidgetSetVisible(w, isVisible);
QAbstractItemView *view = qobject_cast<QAbstractItemView*>(w);
if(0!=view)
{
if(view->model()->metaObject()->className()==ftSngLobbyModel)
{
qLog(Debug)<<"List "<<ftSngLobbyModel<<" shows";
}
}
}
//CBrowseSitAndGoLobbyProxyModel
FTList::FTList(QWidget *widget, QObject *parent) : FTWidgetHook(widget, parent)
{
_painterMode = false;
_paintDone = false;
}
void FTList::onRowsInserted(QAbstractItemView *view, int start, int end)
{
_items.clear();
QAbstractItemModel *model = view->model();
// qLog(Debug)<<QTUtil::objectInfo(model);
/*
QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel*>(model);
while(0!=proxyModel)
{
model = proxyModel->sourceModel();
qLog(Debug)<<" is proxy for "<<QTUtil::objectInfo(model);
proxyModel = qobject_cast<QAbstractProxyModel*>(model);
}
*/
// trace(model, start, end);
emit listUpdatedEvent();
FTLists *lists = qobject_cast<FTLists*>(parent());
if(0!=lists)
lists->listUpdated(this);
}
void FTList::dump(QAbstractItemModel *model, int start, int end)
{
if(!model)
return;
QString s = "Header:";
for(int j=0;j<model->columnCount();j++)
{
QString hdrItem = model->headerData(j,Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
s+=" "+hdrItem;
}
qLog(Debug)<<s;
//for(int role = Qt::DisplayRole;role<=50;role++)
{
//qLog(Debug)<<"role"<<role;
for(int i=start;i<=end;i++)
{
s="";
for(int j=0;j<model->columnCount();j++)
{
QVariant v ;
v= model->data(model->index(i,j), Qt::DisplayRole);
s+=v.toString();
s+=" ";
}
qLog(Debug)<<i<<":"<<s;
}
}
}
int FTList::rowCount()
{
QAbstractItemModel *amodel = model();
if(!amodel)
{
qLog(Debug)<<"ERROR: FTList::rowCount model=0";
return 0;
}
return model()->rowCount();
}
QString FTList::value(int row, int col)
{
QString v = model()->data(model()->index(row, col)).toString();
if(!v.isEmpty())
return v;
if(_painterMode)
if(row>=0 && row<_items.size())
return _items.values()[row];
return "";
}
int FTList::indexOfColumn(QString column)
{
QAbstractItemModel *amodel = model();
for(int j=0;j<amodel->columnCount();j++)
{
QString header = amodel->headerData(j,Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
if(header==column)
return j;
}
return -1;
}
int FTList::indexOfRow(QString v)
{
QAbstractItemModel *amodel = model();
for(int j=0;j<amodel->rowCount();j++)
{
QString row = value(j,0);
if(row==v)
return j;
}
return -1;
}
class QAccessItemView : public QAbstractItemView
{
public:
void doubleClicked(const QModelIndex &index)
{
emit QAbstractItemView::doubleClicked(index);
}
};
QAbstractItemView *FTList::view()
{
QAbstractItemView *view = qobject_cast<QAbstractItemView*>(widget());
Q_ASSERT(view);
return view;
}
QAbstractItemModel *FTList::model()
{
QAbstractItemModel *amodel = view()->model();
Q_ASSERT(amodel);
return amodel;
}
static int n=0;
void FTList::dblClick(int row, int col)
{
QModelIndex index = model()->index(row,col);
QRect rc = view()->visualRect(index);
QPoint pt(rc.x()+rc.width()/3,rc.y()+rc.height()/2);
QWidget *widget = (QWidget*) view();
widget = widget->childAt(10,10);
QEvent *e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseMove,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseButtonPress,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseButtonRelease,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseButtonDblClick,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
}
void FTList::click(int row, int col, float subX, float subY)
{
QModelIndex index = model()->index(row,col);
QRect rc = view()->visualRect(index);
QPoint pt(rc.x()+rc.width()*subX,rc.y()+rc.height()*subY);
//qLog(Info)<<"click "<<objectName()<<" "<<pt.x()<<":"<<pt.y();
QWidget *widget = (QWidget*) view();
widget = widget->childAt(10,10);
QEvent *e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseMove,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseButtonPress,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
e = QMouseEvent::createExtendedMouseEvent(QEvent::MouseButtonRelease,
pt,widget->mapToGlobal(pt), Qt::LeftButton,Qt::LeftButton,0);
QApplication::postEvent(widget, e);
}
void FTList::onDrawTextItem(QWidget *w, const QPointF &p, const QTextItem &ti)
{
FTWidgetHook::onDrawTextItem(w, p, ti);
if(widget() && (widget()->isAncestorOf(w)))
{
if(_paintDone)
{
_paintDone=false;
_items.clear();
//qLog(Debug)<<"ITEMSCLEAR "<<QTUtil::widgetInfo(w);
}
//qLog(Debug)<<"DT: "<<p<<":"<<ti.text()<<QTUtil::widgetInfo(w);
if(_painterMode)
_items[p.y()] = ti.text();
}
}
void FTList::setPainterMode(bool pm)
{
_painterMode = pm;
}
void FTList::onPaint(QWidget *w)
{
FTWidgetHook::onPaint(w);
if(widget() && (widget()->isAncestorOf(w)))
{
//qLog(Debug)<<"PAINTDONE "<<QTUtil::widgetInfo(w);
FTLists *lists = qobject_cast<FTLists*>(parent());
if(0!=lists)
lists->paintDone(this);
_paintDone = true;
}
} | [
"[email protected]",
"mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740"
]
| [
[
[
1,
25
],
[
30,
32
],
[
35,
43
],
[
75,
79
],
[
82,
101
],
[
104,
109
],
[
112,
126
],
[
128,
134
],
[
136,
136
],
[
140,
161
],
[
163,
177
],
[
179,
180
],
[
188,
201
],
[
214,
264
],
[
266,
266
],
[
270,
270
],
[
275,
275
],
[
278,
278
],
[
282,
283
],
[
292,
293
],
[
295,
295
],
[
299,
299
],
[
301,
301
],
[
305,
305
],
[
309,
310
],
[
318,
318
],
[
321,
321
],
[
327,
327
]
],
[
[
26,
29
],
[
33,
34
],
[
44,
74
],
[
80,
81
],
[
102,
103
],
[
110,
111
],
[
127,
127
],
[
135,
135
],
[
137,
139
],
[
162,
162
],
[
178,
178
],
[
181,
187
],
[
202,
213
],
[
265,
265
],
[
267,
269
],
[
271,
274
],
[
276,
277
],
[
279,
281
],
[
284,
291
],
[
294,
294
],
[
296,
298
],
[
300,
300
],
[
302,
304
],
[
306,
308
],
[
311,
317
],
[
319,
320
],
[
322,
326
],
[
328,
328
]
]
]
|
15679b48f1b3ecae907d32bd2c045055b842fa2b | e0d903e81d0c4cbdee8868a748ede2ab45a75eff | /src/coherencytest.cpp | 44cdf43c1f4e3ce39292c277606051155698aa0e | []
| no_license | sbarthelemy/ColladaCoherencyTest | 7b84bfdf09c898dc9c7baf0cfcb9e016ee1a256e | 4ba6ad9ba95100b62dfd918f73c1f85d04982d4b | refs/heads/master | 2016-09-01T16:49:22.547713 | 2010-06-05T17:54:19 | 2010-06-05T17:54:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84,555 | cpp | /*
The MIT License
Copyright 2006 Sony Computer Entertainment Inc.
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.
*/
/*
List of Checks
Check_links It checks if all id are valid reference and if we can resolveElement and getElement
from a link
Check_unique_id It checks if all Ids in each document are unique
Check_counts It checks number counts are correctly set, eg.
skin vertex count should be = mesh vertex count
accessor has the right count on arrays from stride and counts.
Check_files It checks if the image files, cg/fx files, and other non-dae files that the document
referenced exist
Check_textures It checks if the textures are correctly defined/used (image, surface, sampler,
instancing...)
<texture> shouldn't directly reference to <image> id.
it should reference <newparam>'s sid, and have <sampler2D> with <source> reference to
another <newparam>'s sid that have <surface> with <init_from> refernce to <image> id.
Check_URI It checks if the URI are correct. It should also check for unescaped spaces because
a xml validator won't catch the problem. Reference http://www.w3.org/TR/xmlschema-2/#anyURI
Check_schema It checks if the document validates against the Schema
Check_inputs It checks if the required number of input elements are present and that they have the
correct semantic values for their sources.
Check_skin It will check if values in name_array should only reference to an existing SID,
and values in IDREF_array should only reference to an existing ID
Check_InstanceGeometry It checks if all Intance_geometry has bind_material that has a correct matching
bind_material between symbol and target
Check_Controller It checks if skin have same number of vertices weight as the vertices number of geometry.
It checks if morph have same number of vertices from source geometry as number of vertices
in all other target geometry.
Check_Float_array It checks if NaN, INF, -INF exist in all the float array
Check_sid It checks if a sid is a valid sid
CHECK_morph It checks if a morph have same number of targets and target_weights
It checks if all targets have the same number of vertices.
*/
#include "coherencytest.h"
#define VERSION_NUMBER "1.3"
string file_name, log_file;
string output_file_name = "";
FILE * file;
FILE * log;
bool quiet;
domUint fileerrorcount = 0;
string xmlschema_file = "http://www.collada.org/2005/11/COLLADASchema.xsd";
void PRINTF(const char * str)
{
if (str==0) return;
if (quiet == false)
printf("%s",str);
if (file)
fwrite(str, sizeof(char), strlen(str), file);
if (log)
fwrite(str, sizeof(char), strlen(str), log);
}
int VERBOSE;
void print_name_id(domElement * element);
domUint CHECK_error(domElement * element, bool b, const char * message= NULL);
void CHECK_warning(domElement * element, bool b, const char *message = NULL);
domUint CHECK_uri(const xsAnyURI & uri);
domUint CHECK_count(domElement * element, domInt expected, domInt result, const char *message = NULL);
bool CHECK_fileexist(const char * filename);
domUint CHECK_file(domElement *element, xsAnyURI & fileuri);
domUint GetMaxOffsetFromInputs(domInputLocalOffset_Array & inputs);
domUint CHECK_Triangles(domTriangles *triangles);
domUint CHECK_Polygons(domPolygons *polygons);
domUint CHECK_Polylists(domPolylist *polylist);
domUint CHECK_Tristrips(domTristrips *tristrips);
domUint CHECK_Trifans(domTrifans *trifans);
domUint CHECK_Lines(domLines *lines);
domUint CHECK_Linestrips(domLinestrips *linestrips);
domUint CHECK_Geometry(domGeometry *geometry);
domUint CHECK_InstanceGeometry(domInstance_geometry * instance_geometry);
domUint CHECK_Controller(domController *controller);
domUint CHECK_InstanceElementUrl(daeDatabase *db, daeInt instanceElementID);
domUint GetSizeFromType(xsNMTOKEN type);
domUint CHECK_Source(domSource * source);
// void _XMLSchemaValidityErrorFunc(void* ctx, const char* msg, ...);
// void _XMLSchemaValidityWarningFunc(void* ctx, const char* msg, ...);
domUint CHECK_validateDocument(_xmlDoc *LXMLDoc);
domUint CHECK_xmlfile(daeString filename);
domUint CHECK_counts (DAE *input, int verbose = 0);
domUint CHECK_links (DAE *input, int verbose = 0);
domUint CHECK_files (DAE *input, int verbose = 0);
domUint CHECK_unique_id (DAE *input, int verbose = 0);
domUint CHECK_texture (DAE *input, int verbose = 0);
domUint CHECK_schema (DAE *input, int verbose = 0);
domUint CHECK_skin (DAE *input, int verbose = 0);
domUint CHECK_inputs (domInputLocal_Array & inputs, const char * semantic);
domUint CHECK_inputs (domInputLocalOffset_Array & inputs, const char * semantic);
domUint CHECK_float_array (DAE *input, int verbose = 0);
domUint CHECK_Circular_Reference (DAE *input, int verbose = 0);
domUint CHECK_Index_Range (domElement * elem, domListOfUInts & listofint, domUint index_range, domUint offset, domUint maxoffset, int verbose = 0);
domUint CHECK_Index_Range (domElement * elem, domListOfInts & listofint, domUint index_range, domUint offset, domUint maxoffset, int verbose = 0);
domUint CHECK_sid(DAE *input, int verbose = 0);
domUint CHECK_morph(DAE *input, int verbose = 0);
const char VERSION[] =
"Coherencytest version " VERSION_NUMBER "\n"
"The MIT License\n"
"\n"
"Copyright 2009 Sony Computer Entertainment Inc.\n"
"\n"
"Permission is hereby granted, free of charge, to any person obtaining a copy\n"
"of this software and associated documentation files (the \"Software\"), to deal\n"
"in the Software without restriction, including without limitation the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
"copies of the Software, and to permit persons to whom the Software is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be included in\n"
"all copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"
"THE SOFTWARE.\n";
const char USAGE[] =
"Usage: coherencytest filename.dae ... [OPTION]...\n"
" option: \n"
" filename.dae - check collada file filename.dae, filename.dae should be a url format\n"
" -log filename.log - log warnings and errors in filename.log \n"
" -check SCHEMA COUNTS .. - check SCHEMA and COUNTS only, test all if not specify any\n"
" available checks: \n"
" SCHEMA \n"
" UNIQUE_ID \n"
" COUNTS \n"
" LINKS \n"
" TEXTURE \n"
" FILES \n"
" SKIN \n"
" FLOAT_ARRAY \n"
" CIRCULR_REFERENCE \n"
" INDEX_RANGE \n"
" SID \n"
" MORPH \n"
" -ignore SCHEMA COUNTS .. - ignore SCHEMA and COUNTS only, test all if not specify any\n"
" -quiet -q - disable printfs and MessageBox\n"
" -version - print version and copyright information\n"
" -help,-usage - print usage information\n"
" -xmlschema schema.xsd - use your own version of schema.xsd to do schema check\n"
" - the defualt schema is \"http://www.collada.org/2005/11/COLLADASchema.xsd\"\n"
" -ctf, - loging report for ctf\n";
std::map<string, bool> checklist;
int main(int Argc, char **argv)
{
std::vector<string> file_list;
int err = 0;
log = 0;
bool checkall = true;
domUint totalerrorcount = 0;
quiet = false;
for (int i=1; i<Argc; i++)
{
if (stricmp(argv[i], "-log") == 0)
{
i++;
if (i <= Argc)
log_file = argv[i];
log = fopen(log_file.c_str(), "a");
} else if (stricmp(argv[i], "-check") == 0)
{
i++;
if (i >= Argc)
break;
while (argv[i][0]!='-')
{
checkall = false;
for (size_t j=0; j<strlen(argv[i]); j++)
argv[i][j] = toupper(argv[i][j]);
checklist[argv[i]] = true;
i++;
if (i >= Argc)
break;
}
i--;
} else if (stricmp(argv[i], "-ignore") == 0)
{
checkall = false;
checklist["SCHEMA"] = true;
checklist["UNIQUE_ID"] = true;
checklist["COUNTS"] = true;
checklist["LINKS"] = true;
checklist["TEXTURE"] = true;
checklist["FILES"] = true;
checklist["SKIN"] = true;
checklist["FLOAT_ARRAY"] = true;
checklist["CIRCULR_REFERENCE"] = true;
checklist["INDEX_RANGE"] = true;
checklist["SID"] = true;
checklist["MORPH"] = true;
i++;
if (i >= Argc)
break;
while (argv[i][0]!='-')
{
for (size_t j=0; j<strlen(argv[i]); j++)
argv[i][j] = toupper(argv[i][j]);
checklist[argv[i]] = false;
i++;
if (i >= Argc)
break;
}
i--;
} else if (stricmp(argv[i], "-version") == 0)
{
printf(VERSION);
return 0;
} else if (stricmp(argv[i], "-quiet") == 0 || stricmp(argv[i], "-q") == 0)
{
quiet = true;
} else if (stricmp(argv[i], "-help") == 0 || stricmp(argv[i], "-usage") == 0)
{
printf(USAGE);
return 0;
} else if (stricmp(argv[i], "-ctf") == 0)
{
i++;
if (i <= Argc)
log_file = argv[i];
log = fopen(log_file.c_str(), "w");
quiet = true;
} else if (stricmp(argv[i], "-xmlschema") == 0)
{
i++;
if (i <= Argc)
xmlschema_file = argv[i];
} else
{
file_list.push_back(argv[i]);
}
}
if (file_list.size() == 0)
{
printf(USAGE);
return 0;
}
for (size_t i=0; i<file_list.size(); i++)
{
file_name = file_list[i];
char str[MAX_LOG_BUFFER];
time_t current_time = time(NULL);
tm * local_time = localtime(¤t_time);
char * str_time = asctime(local_time);
if (log && quiet == false)
{
sprintf(str, "BEGIN CHECK %s %s\n", file_name.c_str(), str_time);
if (log) fwrite(str, sizeof(char), strlen(str), log);
}
output_file_name = file_name + string(".log");
if (isalpha(file_name[0]) && file_name[1]==':' && file_name[2]=='\\')
{
file_name = string("/") + file_name;
for (unsigned int i=0; i<file_name.size(); i++)
{
if (file_name[i] =='\\')
file_name[i] = '/';
}
}
fileerrorcount = 0;
file = fopen(output_file_name.c_str(), "w+");
DAE * dae = new DAE;
CoherencyTestErrorHandler * errorHandler = new CoherencyTestErrorHandler();
daeErrorHandler::setErrorHandler(errorHandler);
err = dae->load(file_name.c_str());
if (err != 0) {
if (quiet == false)
{
printf("DOM Load error = %d\n", (int) err);
printf("filename = %s\n", file_name.c_str());
#ifdef WIN32
MessageBox(NULL, "Collada Dom Load Error", "Error", MB_OK);
#endif
}
return err;
}
if (checkall)
{
checklist["SCHEMA"] = true;
checklist["UNIQUE_ID"] = true;
checklist["COUNTS"] = true;
checklist["LINKS"] = true;
checklist["TEXTURE"] = true;
checklist["FILES"] = true;
checklist["SKIN"] = true;
checklist["FLOAT_ARRAY"] = true;
checklist["CIRCULR_REFERENCE"] = true;
checklist["INDEX_RANGE"] = true;
checklist["SID"] = true;
checklist["MORPH"] = true;
}
if (checklist["SCHEMA"])
fileerrorcount += CHECK_schema(dae);
if (checklist["UNIQUE_ID"])
fileerrorcount += CHECK_unique_id(dae);
if (checklist["COUNTS"])
fileerrorcount += CHECK_counts(dae);
if (checklist["LINKS"])
fileerrorcount += CHECK_links(dae);
if (checklist["TEXTURE"])
fileerrorcount += CHECK_texture(dae);
if (checklist["FILES"])
fileerrorcount += CHECK_files(dae);
if (checklist["SKIN"])
fileerrorcount += CHECK_skin(dae);
if (checklist["FLOAT_ARRAY"])
fileerrorcount += CHECK_float_array(dae);
if (checklist["CIRCULR_REFERENCE"])
fileerrorcount += CHECK_Circular_Reference (dae);
if (checklist["SID"])
fileerrorcount += CHECK_sid (dae);
if (checklist["MORPH"])
fileerrorcount += CHECK_morph (dae);
if (file) fclose(file);
delete errorHandler;
delete dae;
if (fileerrorcount == 0)
remove(output_file_name.c_str());
if (log && quiet == false)
{
sprintf(str, "END CHECK %s with %d errors\n\n", file_name.c_str(), (int) fileerrorcount);
fwrite(str, sizeof(char), strlen(str), log);
}
totalerrorcount += fileerrorcount ;
}
if (log) fclose(log);
return (int) totalerrorcount;
}
void print_name_id(domElement * element)
{
domElement * e = element;
while ( e->getID() == NULL)
e = e->getParentElement();
char temp[MAX_LOG_BUFFER];
sprintf(temp, "(type=%s,id=%s)", e->getTypeName(), e->getID());
PRINTF(temp);
}
domUint CHECK_error(domElement * element, bool b, const char * message)
{
if (b == false) {
PRINTF("ERROR: ");
if (element) print_name_id(element);
if (message) PRINTF(message);
return 1;
}
return 0;
}
void CHECK_warning(domElement * element, bool b, const char *message)
{
if (b == false) {
PRINTF("WARNING: ");
print_name_id(element);
if (message) PRINTF(message);
}
}
domUint CHECK_uri(const xsAnyURI & uri)
{
// uri.resolveElement();
if (uri.getElement() == NULL)
{
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: CHECK_uri Failed uri=%s not resolved\n",uri.getURI());
PRINTF(temp);
return 1;
}
return 0;//CHECK_escape_char(uri.getOriginalURI());
}
domUint CHECK_count(domElement * element, domInt expected, domInt result, const char *message)
{
if (expected != result)
{
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: CHECK_count Failed: expected=%d, result=%d", (int) expected, (int) result);
PRINTF(temp);
print_name_id(element);
if (message) PRINTF(message);
else PRINTF("\n");
return 1;
}
return 0;
}
bool CHECK_fileexist(const char * filename)
{
xmlTextReader * reader = xmlReaderForFile(filename, 0, 0);
if (!reader)
return false;
return true;
}
domUint CHECK_file(domElement *element, xsAnyURI & fileuri)
{
daeURI * uri = element->getDocumentURI();
string TextureFilePrefix = uri->pathDir();
// Build a path using the scene name ie: images/scene_Textures/boy.tga
daeChar newTexName[MAX_NAME_SIZE];
sprintf(newTexName, "%s%s", TextureFilePrefix.c_str(), fileuri.getURI() );
// Build a path for the Shared texture directory ie: images/Shared/boy.tga
daeChar sharedTexName[MAX_NAME_SIZE];
sprintf(sharedTexName, "%sShared/%s",TextureFilePrefix.c_str(), fileuri.pathFile().c_str() );
if (!CHECK_fileexist(fileuri.getURI()))
if(!CHECK_fileexist(newTexName))
if(!CHECK_fileexist(sharedTexName))
{
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: CHECK_file failed, %s not found\n", fileuri.getURI());
PRINTF(temp);
return 1;
}
return 0;
}
domUint GetMaxOffsetFromInputs(domInputLocalOffset_Array & inputs)
{
domUint maxoffset = 0;
domUint count = (domUint) inputs.getCount();
for(size_t i=0; i< count ;i++)
{
domUint thisoffset = inputs[i]->getOffset();
if (maxoffset < thisoffset) maxoffset = thisoffset;
}
return maxoffset + 1;
}
domUint GetIndexRangeFromInput(domInputLocalOffset_Array &input_array, domUint offset, domUint & error)
{
char message[1024];
for (size_t j=0; j<input_array.getCount(); j++)
{
if (input_array[j]->getOffset() == offset)
{
if (stricmp(input_array[j]->getSemantic(), "VERTEX") == 0)
{ // vertex
domVertices * vertices = (domVertices*)(domElement*) input_array[j]->getSource().getElement();
if (vertices)
{
domInputLocal_Array & inputs = vertices->getInput_array();
for (size_t i=0; i<inputs.getCount(); i++)
{
if (stricmp(inputs[i]->getSemantic(), "POSITION") == 0)
{
domSource * source = (domSource*)(domElement*) inputs[i]->getSource().getElement();
if (source)
{
domSource::domTechnique_common * technique_common = source->getTechnique_common();
if (technique_common)
{
domAccessor * accessor = technique_common->getAccessor();
if (accessor)
return accessor->getCount();
}
}
}
}
}
} else { // non-vertex
domSource * source = (domSource*)(domElement*) input_array[j]->getSource().getElement();
if (source->getElementType() != COLLADA_TYPE::SOURCE)
{
daeString semantic_str = input_array[j]->getSemantic();
daeString source_str = input_array[j]->getSource().getOriginalURI();
sprintf(message, "input with semantic=%s source=source_str is not referencing to a source\n", semantic_str, source_str);
CHECK_error(input_array[j], false, message);
error++;
continue;
}
if (source)
{
domSource::domTechnique_common * technique_common = source->getTechnique_common();
if (technique_common)
{
domAccessor * accessor = technique_common->getAccessor();
if (accessor)
return accessor->getCount();
}
}
}
}
}
sprintf(message, "Thera are no input with offset=%d, can't complete Index_Range\n", offset);
CHECK_error(NULL, false, message);
error++;
return 0;
}
domUint CHECK_Triangles(domTriangles *triangles)
{
domUint errorcount = 0;
domUint count = triangles->getCount();
domInputLocalOffset_Array & inputs = triangles->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domPRef p = triangles->getP();
domListOfUInts & ints = p->getValue();
// check count
errorcount += CHECK_count(triangles, 3 * count * maxoffset, (domInt) ints.getCount(),
"triangles, count doesn't match\n");
// check index range
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (triangles, ints, index_range, offset, maxoffset);
}
return errorcount;
}
domUint CHECK_Polygons(domPolygons *polygons)
{
domUint errorcount = 0;
domUint count = polygons->getCount();
domInputLocalOffset_Array & inputs = polygons->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domP_Array & parray = polygons->getP_array();
domPolygons::domPh_Array & pharray = polygons->getPh_array();
// check count
errorcount += CHECK_count(polygons, count, (domInt) parray.getCount() + pharray.getCount(),
"polygons, count doesn't match\n");
// check index range
for (size_t i=0; i<parray.getCount(); i++)
{
domListOfUInts & ints = parray[i]->getValue();
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (polygons, ints, index_range, offset, maxoffset);
}
}
return errorcount;
}
domUint CHECK_Polylists(domPolylist *polylist)
{
domUint errorcount = 0;
domUint count = polylist->getCount();
domInputLocalOffset_Array & inputs = polylist->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domPRef p = polylist->getP();
domPolylist::domVcountRef vcount = polylist->getVcount();
// check vcount
errorcount += CHECK_count(polylist, count, (domInt) vcount->getValue().getCount(),
"polylists, count doesn't match\n");
// check p count
domUint vcountsum = 0;
for (size_t i=0; i<count; i++)
{
vcountsum += vcount->getValue()[i];
}
errorcount += CHECK_count(polylist, (domInt) p->getValue().getCount(), vcountsum * maxoffset,
"polylists, total vcount and p count doesn't match\n");
// check index range
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (polylist, p->getValue(), index_range, offset, maxoffset);
}
return errorcount;
}
domUint CHECK_Tristrips(domTristrips *tristrips)
{
domUint errorcount = 0;
domUint count = tristrips->getCount();
domInputLocalOffset_Array & inputs = tristrips->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domP_Array & parray = tristrips->getP_array();
// check vcount
errorcount += CHECK_count(tristrips, count, (domInt) parray.getCount(),
"tristrips, count doesn't match\n");
// check p count
for (size_t i=0; i<count; i++)
{
errorcount += CHECK_count(tristrips, 3 * maxoffset <= parray[i]->getValue().getCount(), 1,
"tristrips, this p has less than 3 vertices\n");
errorcount += CHECK_count(tristrips, (domInt) parray[i]->getValue().getCount() % maxoffset, 0,
"tristrips, this p count is not in multiple of maxoffset\n");
}
// check index range
for (size_t i=0; i<parray.getCount(); i++)
{
domListOfUInts & ints = parray[i]->getValue();
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (tristrips, ints, index_range, offset, maxoffset);
}
}
return errorcount;
}
domUint CHECK_Trifans(domTrifans *trifans)
{
domUint errorcount = 0;
domUint count = trifans->getCount();
domInputLocalOffset_Array & inputs = trifans->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domP_Array & parray = trifans->getP_array();
// check vcount
errorcount += CHECK_count(trifans, count, (domInt) parray.getCount(),
"trifan, count doesn't match\n");
// check p count
for (size_t i=0; i<count; i++)
{
errorcount += CHECK_count(trifans, 3 * maxoffset <= parray[i]->getValue().getCount(), 1,
"trifan, this p has less than 3 vertices\n");
errorcount += CHECK_count(trifans, (domInt) parray[i]->getValue().getCount() % maxoffset, 0,
"trifan, this p count is not in multiple of maxoffset\n");
}
// check index range
for (size_t i=0; i<parray.getCount(); i++)
{
domListOfUInts & ints = parray[i]->getValue();
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (trifans, ints, index_range, offset, maxoffset);
}
}
return errorcount;
}
domUint CHECK_Lines(domLines *lines)
{
domUint errorcount = 0;
domUint count = lines->getCount();
domInputLocalOffset_Array & inputs = lines->getInput_array();
errorcount = CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domP * p = lines->getP();
// check p count
errorcount += CHECK_count(lines, 2 * count * maxoffset, (domInt) p->getValue().getCount(),
"lines, count doesn't match\n");
// check index range
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (lines, p->getValue(), index_range, offset, maxoffset);
}
return errorcount;
}
domUint CHECK_Linestrips(domLinestrips *linestrips)
{
domUint errorcount = 0;
domUint count = linestrips->getCount();
domInputLocalOffset_Array & inputs = linestrips->getInput_array();
errorcount += CHECK_inputs(inputs, "VERTEX");
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
domP_Array & parray = linestrips->getP_array();
// check p count
errorcount += CHECK_count(linestrips, count, (domInt) parray.getCount(),
"linestrips, count doesn't match\n");
// check inputs
for (size_t i=0; i<count; i++)
{
errorcount += CHECK_count(linestrips, 2 * maxoffset <= parray[i]->getValue().getCount(), 1,
"linestrips, this p has less than 2 vertices\n");
errorcount += CHECK_count(linestrips, (domInt) parray[i]->getValue().getCount() % maxoffset, 0,
"linestrips, this p is not in mutiple of maxoffset\n");
}
// check index range
for (size_t i=0; i<parray.getCount(); i++)
{
domListOfUInts & ints = parray[i]->getValue();
for (domUint offset=0; offset<maxoffset; offset++)
{
domUint index_range = GetIndexRangeFromInput(inputs, offset, errorcount);
errorcount += CHECK_Index_Range (linestrips, ints, index_range, offset, maxoffset);
}
}
return errorcount;
}
domUint CHECK_Geometry(domGeometry *geometry)
{
domUint errorcount = 0;
domMesh * mesh = geometry->getMesh();
if (mesh == NULL)
return 0;
// check vertices
domVertices *vertices = mesh->getVertices();
CHECK_error(geometry, vertices != NULL, "geometry, no vertices in this mesh\n");
if (vertices)
{
domInputLocal_Array & inputs = vertices->getInput_array();
errorcount += CHECK_inputs(inputs, "POSITION");
}
// triangles
domTriangles_Array & triangles = mesh->getTriangles_array();
for (size_t i=0; i<triangles.getCount(); i++)
{
errorcount += CHECK_Triangles(triangles[i]);
}
// polygons
domPolygons_Array & polygons = mesh->getPolygons_array();
for (size_t i=0; i<polygons.getCount(); i++)
{
errorcount += CHECK_Polygons(polygons[i]);
}
// polylist
domPolylist_Array & polylists = mesh->getPolylist_array();
for (size_t i=0; i<polylists.getCount(); i++)
{
errorcount += CHECK_Polylists(polylists[i]);
}
// tristrips
domTristrips_Array & tristrips = mesh->getTristrips_array();
for (size_t i=0; i<tristrips.getCount(); i++)
{
errorcount += CHECK_Tristrips(tristrips[i]);
}
// trifans
domTrifans_Array & trifans = mesh->getTrifans_array();
for (size_t i=0; i<trifans.getCount(); i++)
{
errorcount += CHECK_Trifans(trifans[i]);
}
// lines
domLines_Array & lines = mesh->getLines_array();
for (size_t i=0; i<lines.getCount(); i++)
{
errorcount += CHECK_Lines(lines[i]);
}
// linestrips
domLinestrips_Array & linestrips = mesh->getLinestrips_array();
for (size_t i=0; i<linestrips.getCount(); i++)
{
errorcount += CHECK_Linestrips(linestrips[i]);
}
return errorcount;
}
domUint CHECK_material_symbols(domGeometry * geometry, domBind_material * bind_material)
{
domUint errorcount = 0;
std::set<string> material_symbols;
if (bind_material == NULL) {
PRINTF("ERROR: CHECK_material_symbols failed no bind materials in this instance\n");
return 1;
}
if (bind_material->getTechnique_common() == NULL) {
PRINTF("ERROR: CHECK_material_symbols failed ");
print_name_id(bind_material);
PRINTF(" no technique_common in bind materials.\n");
return 0;
}
domInstance_material_Array & imarray = bind_material->getTechnique_common()->getInstance_material_array();
for (size_t i=0; i<imarray.getCount(); i++)
{
material_symbols.insert(string(imarray[i]->getSymbol()));
}
if (geometry == NULL) return errorcount;
domMesh * mesh = geometry->getMesh();
if (mesh) {
domTriangles_Array & triangles = mesh->getTriangles_array();
for (size_t i=0; i<triangles.getCount(); i++)
{
daeString material_group = triangles[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domPolygons_Array & polygons = mesh->getPolygons_array();
for (size_t i=0; i<polygons.getCount(); i++)
{
daeString material_group = polygons[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domPolylist_Array & polylists = mesh->getPolylist_array();
for (size_t i=0; i<polylists.getCount(); i++)
{
daeString material_group = polylists[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domTristrips_Array & tristrips = mesh->getTristrips_array();
for (size_t i=0; i<tristrips.getCount(); i++)
{
daeString material_group = tristrips[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domTrifans_Array & trifans = mesh->getTrifans_array();
for (size_t i=0; i<trifans.getCount(); i++)
{
daeString material_group = trifans[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domLines_Array & lines = mesh->getLines_array();
for (size_t i=0; i<lines.getCount(); i++)
{
daeString material_group = lines[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
domLinestrips_Array & linestrips = mesh->getLinestrips_array();
for (size_t i=0; i<linestrips.getCount(); i++)
{
daeString material_group = linestrips[i]->getMaterial();
if (material_group)
CHECK_warning(bind_material,
material_symbols.find(material_group) != material_symbols.end(),
"binding not found for material symbol\n");
}
}
return errorcount;
}
domUint CHECK_InstanceGeometry(domInstance_geometry * instance_geometry)
{
domUint errorcount = 0;
xsAnyURI & uri = instance_geometry->getUrl();
domGeometry * geometry = (domGeometry *) (domElement*) uri.getElement();
domBind_material * bind_material = instance_geometry->getBind_material();
errorcount += CHECK_error(instance_geometry, bind_material!=0, "bind_material not exist\n");
errorcount += CHECK_material_symbols(geometry, bind_material);
return errorcount;
}
domUint GetVertexCountFromGeometry(domGeometry * geometry)
{
domMesh * mesh = geometry->getMesh();
if (mesh)
{
domVertices * vertices = mesh->getVertices();
if (vertices)
{
domInputLocal_Array & inputs = vertices->getInput_array();
for (size_t i=0; i<inputs.getCount(); i++)
{
if (stricmp(inputs[i]->getSemantic(), "POSITION") == 0)
{
domSource * source = (domSource*) (domElement*) inputs[i]->getSource().getElement();
if(source)
{
domFloat_array * float_array = source->getFloat_array();
if (float_array)
return float_array->getCount();
}
}
}
}
}
PRINTF("ERROR: Can't get Vertices Count from geometry, something wrong here\n");
return 0;
}
domUint CHECK_Controller(domController *controller)
{
domUint errorcount = 0;
domSkin * skin = controller->getSkin();
if (skin)
{
xsAnyURI & uri = skin->getSource();
domElement * element = uri.getElement();
if (element == 0)
{
errorcount += CHECK_error(skin, element != 0, "can't resolve skin source\n");
return errorcount;
}
daeString type_str = element->getTypeName();
if (stricmp(type_str, "geometry") == 0)
{ // skin is reference directly to geometry
// get vertex count from skin
domSkin::domVertex_weights * vertex_weights = skin->getVertex_weights();
domUint vertex_weights_count = vertex_weights->getCount();
domGeometry * geometry = (domGeometry*) (domElement*) uri.getElement();
domMesh * mesh = geometry->getMesh();
if (mesh)
{ // get vertex count from geometry
domVertices * vertices = mesh->getVertices();
CHECK_error(geometry, vertices != NULL, "geometry, vertices in this mesh\n");
if (vertices)
{
xsAnyURI src = vertices->getInput_array()[0]->getSource();
domSource * source = (domSource*) (domElement*) src.getElement();
domUint vertices_count = source->getTechnique_common()->getAccessor()->getCount();
errorcount += CHECK_count(controller, vertices_count, vertex_weights_count,
"controller, vertex weight count != mesh vertex count\n");
}
} // TODO: it could be convex_mesh and spline
domUint vcount_count = (domUint) vertex_weights->getVcount()->getValue().getCount();
errorcount += CHECK_count(controller, vcount_count, vertex_weights_count,
"controller, vcount count != vertex weight count\n");
domInputLocalOffset_Array & inputs = vertex_weights->getInput_array();
domUint sum = 0;
for (size_t i=0; i<vcount_count; i++)
{
sum += vertex_weights->getVcount()->getValue()[i];
}
errorcount += CHECK_count(controller, sum * inputs.getCount(), (domInt) vertex_weights->getV()->getValue().getCount(),
"controller, total vcount doesn't match with numbers of v\n");
// check index range on <v>
domListOfInts & ints = vertex_weights->getV()->getValue();
domUint maxoffset = GetMaxOffsetFromInputs(inputs);
for (size_t j=0; j<maxoffset; j++)
{
domUint index_range = GetIndexRangeFromInput(inputs, j, errorcount);
CHECK_Index_Range(skin, ints, index_range, j, maxoffset);
}
}
}
domMorph * morph = controller->getMorph();
if (morph)
{
domUint source_geometry_vertices_count = 0;
xsAnyURI & uri = morph->getSource();
domElement * element = uri.getElement();
if (element == 0)
{
errorcount++;
PRINTF("ERROR: MORPH Source base mesh element does not resolve\n");
return errorcount;
}
daeString type_str = element->getTypeName();
if (stricmp(type_str, "geometry") == 0)
{
domGeometry * source_geometry = (domGeometry *) element;
source_geometry_vertices_count = GetVertexCountFromGeometry(source_geometry);
}
domInputLocal_Array & inputs = morph->getTargets()->getInput_array();
for (size_t i=0; i<inputs.getCount(); i++)
{
if(stricmp(inputs[i]->getSemantic(), "MORPH_TARGET") == 0)
{
domSource * source = (domSource*) (domElement*) inputs[i]->getSource().getElement();
domIDREF_array * IDREF_array = source->getIDREF_array();
if(IDREF_array)
{
xsIDREFS & ifrefs = IDREF_array->getValue();
for (size_t j=0; j<ifrefs.getCount(); j++)
{
domElement * element = ifrefs[j].getElement();
domGeometry * target_geometry = (domGeometry*) element;
domUint target_geo_vertices_count = GetVertexCountFromGeometry(target_geometry);
if (source_geometry_vertices_count !=target_geo_vertices_count)
{
errorcount++;
PRINTF("ERROR: MORPH Target vertices counts != MORPH Source vertices counts\n");
}
}
}
}
}
}
return errorcount;
}
domUint CHECK_InstanceElementUrl(daeDatabase *db, daeInt instanceElementID) {
domUint errorcount = 0;
vector<daeElement*> elements = db->typeLookup(instanceElementID);
for (size_t i = 0; i < elements.size(); i++)
errorcount += CHECK_uri(daeURI(*elements[i], elements[i]->getAttribute("url")));
return errorcount;
}
domUint GetSizeFromType(xsNMTOKEN type)
{
if (stricmp(type, "bool2")==0)
return 2;
else if (stricmp(type, "bool3")==0)
return 3;
else if (stricmp(type, "bool4")==0)
return 4;
else if (stricmp(type, "int2")==0)
return 2;
else if (stricmp(type, "int3")==0)
return 3;
else if (stricmp(type, "int4")==0)
return 4;
else if (stricmp(type, "float2")==0)
return 2;
else if (stricmp(type, "float3")==0)
return 3;
else if (stricmp(type, "float4")==0)
return 4;
else if (stricmp(type, "float2x2")==0)
return 4;
else if (stricmp(type, "float3x3")==0)
return 9;
else if (stricmp(type, "float4x4")==0)
return 16;
return 1;
}
domUint CHECK_Source(domSource * source)
{
domUint errorcount = 0;
// check if this is a source with children
daeTArray<daeSmartRef<daeElement> > children;
source->getChildren(children);
if (children.getCount() <= 0) return 0;
// prepare technique_common
domSource::domTechnique_common * technique_common = source->getTechnique_common();
domAccessor * accessor = 0;
domUint accessor_count = 0;
domUint accessor_stride = 0;
domUint accessor_size = 0;
domUint accessor_offset = 0;
domUint array_count = 0;
domUint array_value_count = 0;
if (technique_common)
{
accessor = technique_common->getAccessor();
if (accessor)
{
accessor_count = accessor->getCount();
accessor_stride = accessor->getStride();
accessor_offset = accessor->getOffset();
domParam_Array & param_array = accessor->getParam_array();
for(size_t i=0; i<param_array.getCount(); i++)
{
xsNMTOKEN type = param_array[i]->getType();
accessor_size += GetSizeFromType(type);
}
errorcount += CHECK_error(source, accessor_size <= accessor_stride, "total size of all params > accessor stride!\n");
errorcount += CHECK_error(source, accessor_size + accessor_offset <= accessor_stride, "total size of all params + offset > accessor stride!\n");
}
}
if (accessor)
{
domElement * element = (domElement*) accessor->getSource().getElement();
if (element == NULL)
{
errorcount += CHECK_error(source, element!=NULL, "accessor source can not resolve!\n");
return errorcount;
}
COLLADA_TYPE::TypeEnum type = element->getElementType();
// float_array
if (type == COLLADA_TYPE::FLOAT_ARRAY)
{
domFloat_array * float_array = (domFloat_array *) element;
array_count = float_array->getCount();
array_value_count = (domUint) float_array->getValue().getCount();
}
// int_array
if (type == COLLADA_TYPE::INT_ARRAY)
{
domInt_array * int_array = (domInt_array *) element;
array_count = int_array->getCount();
array_value_count = (domUint) int_array->getValue().getCount();
}
// bool_array
if (type == COLLADA_TYPE::BOOL_ARRAY)
{
domBool_array * bool_array = (domBool_array *) element;
array_count = bool_array->getCount();
array_value_count = (domUint) bool_array->getValue().getCount();
}
// idref_array
if (type == COLLADA_TYPE::IDREF_ARRAY)
{
domIDREF_array * idref_array = (domIDREF_array *) element;
array_count = idref_array->getCount();
array_value_count = (domUint) idref_array->getValue().getCount();
}
// name_array
if (type == COLLADA_TYPE::NAME_ARRAY)
{
domName_array * name_array = (domName_array *) element;
array_count = name_array->getCount();
array_value_count = (domUint) name_array->getValue().getCount();
}
}
errorcount += CHECK_count(source, array_count, array_value_count,
"array count != number of name in array value_count\n");
if (accessor)
{
errorcount += CHECK_count(source, array_count, accessor_count * accessor_stride,
"accessor_stride >= accessor_size but array_count != accessor_count * accessor_stride\n");
}
return errorcount ;
}
domUint CHECK_counts (DAE *input, int verbose)
{
// checklist = new std::map<daeString, domElement *>;
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
// check geometry
daeInt count = (daeInt) db->getElementCount(NULL, "geometry", file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGeometry *geometry;
error = db->getElement((daeElement**)&geometry, i, NULL, "geometry", file_name.c_str());
errorcount += CHECK_Geometry(geometry);
}
// check controller
count = (daeInt)db->getElementCount(NULL, "controller", file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domController *controller;
error = db->getElement((daeElement**)&controller, i, NULL, "controller", file_name.c_str());
errorcount += CHECK_Controller(controller);
}
// check instance_geometry
count = (daeInt)db->getElementCount(NULL, "instance_geometry", file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_geometry *instance_geometry;
error = db->getElement((daeElement**)&instance_geometry, i, NULL, "instance_geometry", file_name.c_str() );
errorcount += CHECK_InstanceGeometry(instance_geometry);
}
// check source
count = (daeInt)db->getElementCount(NULL, "source", file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domSource *source;
error = db->getElement((daeElement**)&source, i, NULL, "source", file_name.c_str() );
errorcount += CHECK_Source(source);
}
return errorcount;
}
domUint CHECK_links (DAE *input, int verbose)
{
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
// check links
daeInt count = (daeInt)db->getElementCount(NULL, "accessor", file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domAccessor *accessor;
error = db->getElement((daeElement**)&accessor, i, NULL, "accessor", file_name.c_str() );
xsAnyURI & uri = accessor->getSource();
errorcount += CHECK_uri(uri);
}
count = (daeInt)db->getElementCount(NULL, "channel", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domChannel *channel;
error = db->getElement((daeElement**)&channel, i, NULL, "channel", file_name.c_str());
xsAnyURI & uri = channel->getSource();
errorcount += CHECK_uri(uri);
}
count = (daeInt)db->getElementCount(NULL, "IDREF_array", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domIDREF_array *IDREF_array;
error = db->getElement((daeElement**)&IDREF_array, i, NULL, "IDREF_array", file_name.c_str());
for (size_t j=0; j<IDREF_array->getCount(); j++)
{
daeIDRef idref = IDREF_array->getValue()[j];
idref.resolveElement();
domElement * element = idref.getElement();
if (element == NULL)
{
char temp[MAX_LOG_BUFFER];
sprintf(temp, "IDREF_array value %s not referenced\n", idref.getID());
PRINTF(temp);
errorcount += CHECK_error(IDREF_array, element!=NULL, temp);
}
}
}
count = (daeInt)db->getElementCount(NULL, "input", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domInputLocalOffset *input;
error = db->getElement((daeElement**)&input, i, NULL, "input", file_name.c_str());
xsAnyURI & uri = input->getSource();
errorcount += CHECK_uri(uri);
}
count = (daeInt)db->getElementCount(NULL, "skeleton", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domInstance_controller::domSkeleton *skeleton;
error = db->getElement((daeElement**)&skeleton, i, NULL, "skeleton", file_name.c_str());
xsAnyURI & uri = skeleton->getValue();
errorcount += CHECK_uri(uri);
}
count = (daeInt)db->getElementCount(NULL, "skin", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domSkin *skin;
error = db->getElement((daeElement**)&skin, i, NULL, "skin", file_name.c_str());
xsAnyURI & uri = skin->getSource();
errorcount += CHECK_uri(uri);
}
// physics
/* for (size_t i=0; i<db->getElementCount(NULL, "program", NULL); i++)
{
domProgram *program;
error = db->getElement((daeElement**)&program, i, NULL, "program");
xsAnyURI & uri = program->getSource();
errorcount += CHECK_uri(uri);
}
*/
count = (daeInt)db->getElementCount(NULL, "instance_rigid_body", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domInstance_rigid_body *instance_rigid_body;
error = db->getElement((daeElement**)&instance_rigid_body, i, NULL, "instance_rigid_body", file_name.c_str());
xsAnyURI & uri = instance_rigid_body->getTarget();
errorcount += CHECK_uri(uri);
}
count = (daeInt)db->getElementCount(NULL, "ref_attachment", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domRigid_constraint::domRef_attachment *ref_attachment;
error = db->getElement((daeElement**)&ref_attachment, i, NULL, "ref_attachment", file_name.c_str());
xsAnyURI & uri = ref_attachment->getRigid_body();
errorcount += CHECK_uri(uri);
}
// FX, todo: color_target, connect_param, depth_target, param, stencil_target
count = (daeInt)db->getElementCount(NULL, "instance_material", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domInstance_material *instance_material;
error = db->getElement((daeElement**)&instance_material, i, NULL, "instance_material", file_name.c_str());
xsAnyURI & uri = instance_material->getTarget();
errorcount += CHECK_uri(uri);
}
// urls
daeInt instance_elements[] = {
domInstanceWithExtra::ID(), // instance_animation, instance_visual_scene, instance_physics_scene
domInstance_camera::ID(),
domInstance_controller::ID(),
domInstance_geometry::ID(),
domInstance_light::ID(),
domInstance_node::ID(),
domInstance_effect::ID(),
domInstance_force_field::ID(),
domInstance_physics_material::ID(),
domInstance_physics_model::ID()
};
domUint instance_elements_max = sizeof(instance_elements)/sizeof(daeInt);
for (size_t i=0; i<instance_elements_max ; i++)
{
errorcount += CHECK_InstanceElementUrl(db, instance_elements[i]);
}
return errorcount;
}
domUint CHECK_files (DAE *input, int verbose)
{
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
// files
daeInt count = (daeInt) db->getElementCount(NULL, "image", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domImage *image;
error = db->getElement((daeElement**)&image, i, NULL, "image", file_name.c_str());
domImage::domInit_from * init_from = image->getInit_from();
domImage::domData * data = image->getData();
errorcount += CHECK_error(image, init_from || data, "image, exactly one of the child element <data> or <init_from> must occur\n");
if (init_from)
{
xsAnyURI & uri = init_from->getValue();
errorcount += CHECK_file(init_from, uri);
}
}
count = (daeInt) db->getElementCount(NULL, "include", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domFx_include_common *include;
error = db->getElement((daeElement**)&include, i, NULL, "include", file_name.c_str());
xsAnyURI & uri = include->getUrl();
errorcount += CHECK_file(include, uri);
}
return errorcount;
}
domUint CHECK_escape_char(daeString str)
{
domUint errorcount = 0;
size_t len = strlen(str);
for(size_t i=0; i<len; i++)
{
switch(str[i])
{
case ' ':
case '#':
case '$':
case '%':
case '&':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '@':
case '[':
case '\\':
case ']':
case '^':
case '`':
case '{':
case '|':
case '}':
case '~':
char temp[1024];
sprintf(temp, "ERROR: string '%s' contains non-escaped char '%c'\n", str, str[i]);
PRINTF(temp);
errorcount++;
default:
continue;
}
}
return errorcount;
}
domUint CHECK_unique_id (DAE *input, int verbose)
{
std::pair<std::set<string>::iterator, bool> pair;
std::set<string> ids;
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
daeInt count = (daeInt) db->getElementCount(NULL, NULL, NULL);
for (daeInt i=0; i<count; i++)
{
domElement *element;
error = db->getElement((daeElement**)&element, i, NULL, NULL, NULL);
daeString id = element->getID();
if (id == NULL) continue;
errorcount += CHECK_escape_char(id);
daeString docURI = element->getDocumentURI()->getURI();
// check if there is second element with the same id.
error = db->getElement((daeElement**)&element, 1, id, NULL, docURI);
if (error == DAE_OK)
{
errorcount++;
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: Unique ID conflict id=%s, docURI=%s\n", id, docURI);
PRINTF(temp);
}
}
return errorcount;
}
domEffect *TextureGetEffect(domCommon_color_or_texture_type::domTexture *texture)
{
for (domElement * element = texture; element; element = element->getParentElement())
{
if (element->getTypeName())
if (stricmp(element->getTypeName(), "effect") == 0)
return (domEffect *)element;
}
return NULL;
}
domUint CHECK_texture (DAE *input, int verbose)
{
std::pair<std::set<string>::iterator, bool> pair;
std::set<string> ids;
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
daeInt count = (daeInt) db->getElementCount(NULL, "texture", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domCommon_color_or_texture_type::domTexture *texture;
error = db->getElement((daeElement**)&texture, i, NULL, "texture", file_name.c_str());
xsNCName texture_name = texture->getTexture();
char * target = new char[ strlen( texture_name ) + 3 ];
strcpy( target, "./" );
strcat( target, texture_name );
domEffect * effect = TextureGetEffect(texture);
if (effect==NULL)
continue;
daeSIDResolver sidRes( effect, target );
delete[] target;
target = NULL;
if ( sidRes.getElement() != NULL )
{ // it is doing the right way
continue;
}
daeIDRef ref(texture_name);
ref.setContainer(texture);
ref.resolveElement();
daeElement * element = ref.getElement();
if (element)
{ // it is directly linking the image
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: CHECK_texture failed, texture=%s is direct linking to image\n", texture_name);
PRINTF(temp);
} else {
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: CHECK_texture failed, texture=%s is not link to anything\n", texture_name);
PRINTF(temp);
}
}
return errorcount;
}
void _XMLSchemaValidityErrorFunc(void* ctx, const char* msg, ...)
{
va_list LVArgs;
char LTmpStr[MAX_LOG_BUFFER]; // FIXME: this is not buffer-overflow safe
memset(LTmpStr,0,MAX_LOG_BUFFER);
// DAEDocument* LDAEDocument = (DAEDocument*)ctx;
// xmlSchemaValidCtxt* LXMLSchemaValidContext = (xmlSchemaValidCtxt*) ctx;
// xmlNode* LXMLNode = xmlSchemaValidCtxtGetNode(ctx);
// xmlDoc * doc = (xmlDoc *) ctx;
va_start(LVArgs, msg);
vsprintf(LTmpStr, msg, LVArgs);
va_end(LVArgs);
// PRINTF("%s:%d Schema validation error:\n%s", LDAEDocument->Name, xmlGetLineNo(LXMLNode), LTmpStr);
// PRINTF("CHECK_schema Error msg=%c ctx=%p\n", msg, ctx);
char temp[MAX_LOG_BUFFER];
memset(temp,0,MAX_LOG_BUFFER);
sprintf(temp, "ERROR: CHECK_schema Error msg=%s", LTmpStr);
PRINTF(temp);
fileerrorcount++;
}
void _XMLSchemaValidityWarningFunc(void* ctx, const char* msg, ...)
{
va_list LVArgs;
char LTmpStr[MAX_LOG_BUFFER]; // FIXME: this is not buffer-overflow safe
memset(LTmpStr,0,MAX_LOG_BUFFER);
// DAEDocument* LDAEDocument = (DAEDocument*)ctx;
// xmlNode* LXMLNode = xmlSchemaValidCtxtGetNode(LDAEDocument->XMLSchemaValidContext);
// xmlDoc * doc = (xmlDoc *) ctx;
va_start(LVArgs, msg);
vsprintf(LTmpStr, msg, LVArgs);
va_end(LVArgs);
// PRINTF("%s:%d Schema validation warning:\n%s", LDAEDocument->Name, xmlGetLineNo(LXMLNode), LTmpStr);
char temp[MAX_LOG_BUFFER];
memset(temp,0,MAX_LOG_BUFFER);
sprintf(temp, "ERROR: CHECK_schema Warning msg=%s", LTmpStr);
PRINTF(temp);
fileerrorcount++;
}
//void dae_ValidateDocument(DAEDocument* LDAEDocument, xmlDocPtr LXMLDoc)
domUint CHECK_validateDocument(xmlDocPtr LXMLDoc)
{
// const char * dae_SchemaURL = "C:\\svn\\COLLADA_DOM\\doc\\COLLADASchema.xsd";
// const char * dae_SchemaURL = "http://www.collada.org/2005/11/COLLADASchema.xsd";
const char * dae_SchemaURL = xmlschema_file.c_str();
xmlSchemaParserCtxt* Ctxt = xmlSchemaNewDocParserCtxt(LXMLDoc);
xmlSchemaParserCtxt* LXMLSchemaParserCtxt = xmlSchemaNewParserCtxt(dae_SchemaURL);
if(LXMLSchemaParserCtxt)
{
xmlSchema* LXMLSchema = xmlSchemaParse(LXMLSchemaParserCtxt);
if(LXMLSchema)
{
xmlSchemaValidCtxt* LXMLSchemaValidContext = xmlSchemaNewValidCtxt(LXMLSchema);
if(LXMLSchemaValidContext)
{
int LSchemaResult;
// LDAEDocument->XMLSchemaValidContext = LXMLSchemaValidContext;
/* xmlSchemaSetParserErrors(LXMLSchemaParserCtxt,
_XMLSchemaValidityErrorFunc,
_XMLSchemaValidityWarningFunc,
LXMLDoc);
*/
// globalpointer = this;
xmlSchemaSetValidErrors(LXMLSchemaValidContext,
_XMLSchemaValidityErrorFunc,
_XMLSchemaValidityWarningFunc,
LXMLDoc);
LSchemaResult = xmlSchemaValidateDoc(LXMLSchemaValidContext, LXMLDoc);
// switch(LSchemaResult)
// {
// case 0: PRINTF("Document validated\n");break;
// case -1: PRINTF("API error\n");break;
// default: PRINTF("Error code: %d\n", LSchemaResult);break;
// }
// LDAEDocument->XMLSchemaValidContext = NULL;
xmlSchemaFreeValidCtxt(LXMLSchemaValidContext);
}
xmlSchemaFree(LXMLSchema);
}
else {
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: Could not parse schema from %s\n", dae_SchemaURL);
PRINTF(temp);
}
xmlSchemaFreeParserCtxt(LXMLSchemaParserCtxt);
}
else {
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: Could not load schema from '%s\n", dae_SchemaURL);
PRINTF(temp);
}
return 0;
}
domUint CHECK_xmlfile(daeString filename)
{
xmlDocPtr doc;
doc = xmlReadFile(filename, NULL, 0);
if (doc == NULL) {
char temp[MAX_LOG_BUFFER];
sprintf(temp, "ERROR: Failed to parse %s\n", filename);
PRINTF(temp);
return 1;
} else {
// load okay
CHECK_validateDocument(doc);
/* free up the parser context */
xmlFreeDoc(doc);
}
return 0;
}
domUint CHECK_schema (DAE *input, int verbose)
{
domInt errorcount = 0;
daeDatabase* db = input->getDatabase();
daeInt count = (daeInt) db->getDocumentCount();
for (daeInt i=0; i<count; i++)
{
daeDocument* doc = db->getDocument(i);
daeString xmldoc = doc->getDocumentURI()->getURI();
errorcount += CHECK_xmlfile(xmldoc);
}
return errorcount;
}
domUint CHECK_inputs (domInputLocalOffset_Array & inputs, const char * semantic)
{
domUint count = (domUint) inputs.getCount();
for (size_t i=0; i<count; i++)
{
if (stricmp(semantic, inputs[i]->getSemantic()) == 0)
return 0;
}
PRINTF("ERROR: CHECK inputs Failed ");
print_name_id(inputs[0]);
char temp[MAX_LOG_BUFFER];
sprintf(temp, " input with semantic=%s not found\n", semantic);
PRINTF(temp);
return 1;
}
domUint CHECK_inputs (domInputLocal_Array & inputs, const char * semantic)
{
domUint count = (domUint) inputs.getCount();
for (size_t i=0; i<count; i++)
{
if (stricmp(semantic, inputs[i]->getSemantic()) == 0)
return 0;
}
PRINTF("ERROR: CHECK inputs Failed ");
print_name_id(inputs[0]);
char temp[MAX_LOG_BUFFER];
sprintf(temp, " input with semantic=%s not found\n", semantic);
PRINTF(temp);
return 1;
}
domUint CHECK_skin (DAE *input, int verbose)
{
std::vector<domNode *> nodeset;
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
daeInt count = (daeInt) db->getElementCount(NULL, "instance_controller", file_name.c_str());
for (daeInt i=0; i<count; i++)
{
domInstance_controller *instance_controller;
error = db->getElement((daeElement**)&instance_controller, i, NULL, "instance_controller", file_name.c_str());
// get all skeletons
domInstance_controller::domSkeleton_Array & skeleton_array = instance_controller->getSkeleton_array();
domUint skeleton_count = (domUint) skeleton_array.getCount();
for (size_t i=0; i<skeleton_count; i++)
{
domNode * node = (domNode*) (domElement*) skeleton_array[i]->getValue().getElement();
nodeset.push_back(node);
}
//get joints from skin
domController * controller = (domController*) (domElement*) instance_controller->getUrl().getElement();
if (controller==NULL) continue;
domBind_material * bind_material = instance_controller->getBind_material();
errorcount += CHECK_error(instance_controller, bind_material!=0, "bind_material not exist\n");
domMorph * morph = controller->getMorph();
if (morph)
{
domGeometry * geometry = (domGeometry*) (domElement*) morph->getSource().getElement();
errorcount += CHECK_material_symbols(geometry, bind_material);
}
domSkin * skin = controller->getSkin();
if (skin)
{
domElement * element = (domElement*) skin->getSource().getElement();
if (element == NULL)
{
errorcount += CHECK_error(controller, false, "Skin source not found\n");
continue;
}
COLLADA_TYPE::TypeEnum type = element->getElementType();
switch(type)
{
case COLLADA_TYPE::GEOMETRY:
{
domGeometry * geometry = (domGeometry*) element;
errorcount += CHECK_material_symbols(geometry, bind_material);
break;
}
case COLLADA_TYPE::MORPH:
{
domMorph * morph = (domMorph*) element;
domGeometry * geometry = (domGeometry*) (domElement*) morph->getSource().getElement();
errorcount += CHECK_material_symbols(geometry, bind_material);
break;
}
default:
break;
}
// get source of name_array or IDREF_array
domSource * joint_source = NULL;
domSource * inv_bind_matrix_source = NULL;
domSkin::domJoints * joints = skin->getJoints();
if (joints==NULL) continue;
domInputLocal_Array &input_array = joints->getInput_array();
for(size_t i=0; i<input_array.getCount(); i++)
{
if (stricmp(input_array[i]->getSemantic(), "JOINT") == 0)
{
joint_source = (domSource *) (domElement*) input_array[i]->getSource().getElement();
if (joint_source) continue;
} else if (stricmp(input_array[i]->getSemantic(), "INV_BIND_MATRIX") == 0)
{
inv_bind_matrix_source = (domSource *) (domElement*) input_array[i]->getSource().getElement();
if (inv_bind_matrix_source) continue;
}
}
if (joint_source == NULL) continue;
if (inv_bind_matrix_source == NULL) continue;
//check count of joint source and inv_bind_matrix_source
domSource::domTechnique_common * techique_common = NULL;
domAccessor * accessor = NULL;
domUint joint_count = 0;
domUint inv_bind_matrix_count = 0;
techique_common = joint_source->getTechnique_common();
if (techique_common)
{
accessor = techique_common->getAccessor();
if (accessor)
domUint joint_count = accessor->getCount();
}
techique_common = inv_bind_matrix_source->getTechnique_common();
if (techique_common)
{
accessor = techique_common->getAccessor();
if (accessor)
domUint inv_bind_matrix_count = accessor->getCount();
}
errorcount += CHECK_count(skin, joint_count, inv_bind_matrix_count,
"WARNING, joint count and inv bind matrix count does not match.\n");
//name_array
domName_array * name_array = joint_source ->getName_array();
domIDREF_array * idref_array = joint_source ->getIDREF_array();
if (name_array)
{
domListOfNames &list_of_names = name_array->getValue();
domUint name_count = (domUint) list_of_names.getCount();
for (domUint j=0; j<name_count; j++)
{
char jointpath[MAX_PATH];
strcpy( jointpath, "./" );
strcat( jointpath, list_of_names[(size_t)j] );
domElement * e = NULL;
for (size_t k=0; k<nodeset.size(); k++)
{
daeSIDResolver sidRes( nodeset[k], jointpath );
e = sidRes.getElement();
if (e) break;
}
if (e==NULL) // this joint name is not match with any sid of skeleton nodes
{
char tempstr[MAX_PATH];
sprintf(tempstr, "instance_controller, can't find node with sid=%s of controller=%s\n", list_of_names[(size_t)j], controller->getId());
errorcount += CHECK_error(instance_controller, false, tempstr);
}
}
} else if (idref_array)
{
xsIDREFS & list_of_idref = idref_array->getValue();
domUint idref_count = (domUint) list_of_idref.getCount();
for (domUint j=0; j<idref_count; j++)
{
list_of_idref[(size_t)j].resolveElement();
domElement * element = list_of_idref[(size_t)j].getElement();
if (element == 0)
{
char tempstr[MAX_PATH];
sprintf(tempstr, "skin, idref=%s can't resolve\n", list_of_idref[(size_t)j].getID());
errorcount +=CHECK_error(joint_source, false, tempstr);
}
}
} else { // name_array and IDREF_array not found
errorcount +=CHECK_error(skin, false, "skin, both name_array and IDREF_array are not found");
}
} else // TODO: for other non-skin controllers
{
}
}
return errorcount;
}
domUint CHECK_float_array (DAE *input, int verbose)
{
domInt count = 0;
domInt error = 0;
domInt errorcount=0;
daeDatabase *db = input->getDatabase();
count = (daeInt) db->getElementCount(NULL, COLLADA_ELEMENT_FLOAT_ARRAY, file_name.c_str());
for (int i=0; i<count; i++)
{
domFloat_array * float_array;
error = db->getElement((daeElement**)&float_array, i, NULL, COLLADA_ELEMENT_FLOAT_ARRAY, file_name.c_str());
domListOfFloats & listoffloats = float_array->getValue();
for (size_t j=0; j<listoffloats.getCount(); j++)
{
if ( (listoffloats[j] == 0x7f800002) ||
(listoffloats[j] == 0x7f800000) ||
(listoffloats[j] == 0xff800000) )
{
errorcount++;
PRINTF("ERROR: Float_array contain either -INF, INF or NaN\n");
}
}
}
return errorcount;
}
enum eVISIT
{
NOT_VISITED = 0,
VISITING,
VISITED,
};
domUint CHECK_node (domNode * parent_node, std::map<domNode*,eVISIT> * node_map)
{
domUint errorcount = 0;
// eVISIT result = (*node_map)[parent_node];
switch((*node_map)[parent_node])
{
case VISITING:// means we are visiting this node again "circular reference detected.
PRINTF("ERROR: circular reference detected.\n");
return 1;
case VISITED: // means we already visited this node.
return 0;
default: // means we are visiting this node the first time.
(*node_map)[parent_node] = VISITING;
break;
}
domNode_Array & node_array = parent_node->getNode_array();
for (size_t i=0; i<node_array.getCount(); i++)
{
domNode * node = node_array[i];
if (node) errorcount += CHECK_node(node, node_map);
}
domInstance_node_Array & instance_node_array = parent_node->getInstance_node_array();
for (size_t i=0; i<instance_node_array.getCount(); i++)
{
domNode * node = (domNode*) (domElement*) instance_node_array[i]->getUrl().getElement();
if (node) errorcount += CHECK_node(node, node_map);
}
/* domInstance_controller_Array instance_controller_array & parent_node->getInstance_controller_array();
for (size_t i=0; i<instance_controller_array.getCount(); i++)
{
instance_controller_array[i]->getSkeleton_array()
domNode * node = (domNode*) (domElement*) ->getUrl().getElement();
CHECK_node(node);
}
*/
(*node_map)[parent_node] = VISITED;
return errorcount;
}
domUint CHECK_Circular_Reference (DAE *input, int verbose)
{
domInt errorcount=0;
std::map<domNode*,eVISIT> node_map;
domCOLLADA * collada = input->getDom(file_name.c_str());
domCOLLADA::domScene * scene = collada->getScene();
if (scene == NULL) return 0;
domInstanceWithExtra * instance_scene = scene->getInstance_visual_scene();
if (instance_scene == NULL) return 0;
domVisual_scene * visual_scene = (domVisual_scene*) (domElement*) instance_scene->getUrl().getElement();
if (visual_scene == NULL) return 0;
domNode_Array & node_array = visual_scene->getNode_array();
for (size_t i=0; i<node_array.getCount(); i++)
{
domNode * node = node_array[i];
CHECK_node(node, &node_map);
}
return errorcount;
}
// check if an index is indexing out of range
domUint CHECK_Index_Range (domElement * elem, domListOfUInts & listofint, domUint index_range, domUint offset, domUint maxoffset, int verbose)
{
if (checklist["INDEX_RANGE"] == false) return 0;
domInt errorcount=0;
if (index_range == 0)
{
errorcount += CHECK_error(elem, index_range != 0, "index_range == 0, can't complete CHECK_Index_Range index range checks if we are indexing out of range of a source\n");
return errorcount;
}
char message[1024];
for (size_t i=(size_t)offset; i<listofint.getCount(); i=(size_t)i+(size_t)maxoffset)
{
if (listofint[i] >= index_range)
{
sprintf(message, "Index out of range, index=%d < ranage=%d\n", (int) listofint[i], (int) index_range);
errorcount += CHECK_error(elem, listofint[i] < index_range, message);
}
}
return errorcount;
}
domUint CHECK_Index_Range (domElement * elem, domListOfInts & listofint, domUint index_range, domUint offset, domUint maxoffset, int verbose)
{
if (checklist["INDEX_RANGE"] == false) return 0;
domInt errorcount=0;
if (index_range == 0)
{
errorcount += CHECK_error(elem, index_range != 0, "index_range == 0, can't complete CHECK_Index_Range\n");
return errorcount;
}
char message[1024];
for (size_t i=(size_t)offset; i<listofint.getCount(); i=(size_t)i+(size_t)maxoffset)
{
if (listofint[i] >= (domInt) index_range)
{
sprintf(message, "Index out of range, index=%d < ranage=%d\n", (int) listofint[i], (int) index_range);
errorcount += CHECK_error(elem, listofint[i] < (domInt) index_range, message);
}
}
return errorcount;
}
domUint CHECK_validSid(domElement * elem, daeString sid)
{
size_t len = strlen(sid);
for (size_t i=0; i<len; i++)
{
switch(sid[i])
{
// case '.': // . is still allowed in 1.4
case '/':
case '(':
case ')':
{
string message = string("Sid=") + string(sid) + string(", is not a valid sid\n");
CHECK_error(NULL, false, message.c_str());
}
return 1;
default:
break;
}
}
return 0;
}
domUint CHECK_sid(DAE *input, int verbose)
{
domInt error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
{
daeString element_name = "node";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domNode *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "color";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domCommon_color_or_texture_type_complexType::domColor *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_animation";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstanceWithExtra *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_camera";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_camera *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_controller";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_controller *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_geometry";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_geometry *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_light";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_light *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_node";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_node *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_visual_scene";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstanceWithExtra *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "lookat";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domLookat *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "matrix";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domMatrix *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
/* {
daeString element_name = "param";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domParam *obj; // there many domParam, which one should I use?
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
*/ {
daeString element_name = "rotate";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domRotate *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "scale";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domScale *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "skew";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domSkew*obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "translate";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domTranslate *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_force_field";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_force_field *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_physics_matrial";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_physics_material *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_physics_model";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_physics_model *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_physics_scene";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstanceWithExtra *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_rigid_body";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_rigid_body *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "rigid_body";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domRigid_body *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "code";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domFx_code_profile *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "include";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domFx_include_common *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_effect";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_effect *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "instance_material";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domInstance_material *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "fx_newparam_common";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domFx_newparam_common *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "common_newparam_type";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domFx_newparam_common *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "fx_newparam";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domFx_newparam_common *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "glsl_newparam";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGlsl_newparam *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "cg_newparam";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGles_newparam *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "gles_newparam";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domCg_newparam *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
{
daeString element_name = "pass";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domProfile_GLES::domTechnique::domPass *objGLES;
error = db->getElement((daeElement**)&objGLES, i, NULL, element_name, file_name.c_str() );
if (objGLES) if (objGLES->getSid()) errorcount += CHECK_validSid(objGLES, objGLES->getSid());
domProfile_CG::domTechnique::domPass *objCG;
error = db->getElement((daeElement**)&objCG, i, NULL, element_name, file_name.c_str() );
if (objCG) if (objCG->getSid()) errorcount += CHECK_validSid(objCG, objCG->getSid());
domProfile_CG::domTechnique::domPass *objGLSL;
error = db->getElement((daeElement**)&objGLSL, i, NULL, element_name, file_name.c_str() );
if (objGLSL) if (objGLSL->getSid()) errorcount += CHECK_validSid(objGLSL, objGLSL->getSid());
}
}
{
daeString element_name = "sampler_state";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGles_sampler_state *objGLES;
error = db->getElement((daeElement**)&objGLES, i, NULL, element_name, file_name.c_str() );
if (objGLES) if (objGLES->getSid()) errorcount += CHECK_validSid(objGLES, objGLES->getSid());
}
}
{// TODO: Law: This code is turned off because I can't fix a objGLES->getSid() problem that happens in release mode only
/* daeString element_name = "technique";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domProfile_CG::domTechnique *objCG;
error = db->getElement((daeElement**)&objCG, i, NULL, element_name, file_name.c_str() );
if (objCG) if (objCG->getSid()) errorcount += CHECK_validSid(objCG, objCG->getSid());
domProfile_GLES::domTechnique *objGLES;
error = db->getElement((daeElement**)&objGLES, i, NULL, element_name, file_name.c_str() );
if (objGLES) if (objGLES->getSid()) errorcount += CHECK_validSid(objGLES, objGLES->getSid());
domProfile_GLSL::domTechnique *objGLSL;
error = db->getElement((daeElement**)&objGLSL, i, NULL, element_name, file_name.c_str() );
if (objGLSL) if (objGLSL->getSid()) errorcount += CHECK_validSid(objGLSL, objGLSL->getSid());
}
*/ }
{
daeString element_name = "texture_pipeline";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGles_texture_pipeline_complexType *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(NULL, obj->getSid());
}
}
{
daeString element_name = "texture_unit";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domGles_texture_unit *obj;
error = db->getElement((daeElement**)&obj, i, NULL, element_name, file_name.c_str() );
if (obj)
if (obj->getSid())
errorcount += CHECK_validSid(obj, obj->getSid());
}
}
return errorcount;
}
CoherencyTestErrorHandler::CoherencyTestErrorHandler() {
}
CoherencyTestErrorHandler::~CoherencyTestErrorHandler() {
}
void CoherencyTestErrorHandler::handleError( daeString msg ) {
char temp[MAX_LOG_BUFFER];
memset(temp,0,MAX_LOG_BUFFER);
sprintf(temp, "ERROR: DOM Error Handler msg=%s", msg);
PRINTF(temp);
fileerrorcount++;
}
void CoherencyTestErrorHandler::handleWarning( daeString msg ) {
char temp[MAX_LOG_BUFFER];
memset(temp,0,MAX_LOG_BUFFER);
sprintf(temp, "WARNING: DOM Warning Handler msg=%s", msg);
PRINTF(temp);
fileerrorcount++;
}
domUint CHECK_morph(DAE *input, int verbose)
{
domUint error = 0;
domUint errorcount = 0;
daeDatabase *db = input->getDatabase();
daeString element_name = "morph";
daeInt count = (daeInt)db->getElementCount(NULL, element_name, file_name.c_str() );
for (daeInt i=0; i<count; i++)
{
domMorph *morph = 0;
error = db->getElement((daeElement**)&morph, i, NULL, element_name, file_name.c_str() );
if (morph)
{
domMorph::domTargetsRef targets = morph->getTargets();
domInputLocal_Array & inputs = targets->getInput_array();
domUint morph_weight_count = 0;
domUint morph_target_count = 0;
for (size_t i=0; i<inputs.getCount(); i++)
{
const char * semantic = inputs[i]->getSemantic();
domSource * source = (domSource*) (domElement*) inputs[i]->getSource().getElement();
if (source && semantic)
{
if (stricmp(semantic, "MORPH_TARGET")==0)
{
domIDREF_array * idref_array = source->getIDREF_array();
morph_target_count = idref_array->getCount();
xsIDREFS & idrefs = source->getIDREF_array()->getValue();
domUint last_vertices_counts = 0;
for (size_t j=0; j<morph_target_count; j++) // for each target geometry
{
domGeometry * geometry = (domGeometry*) (domElement*) idrefs[j].getElement();
errorcount += CHECK_error(geometry, geometry != NULL, "morph target not found\n");
if (geometry==NULL) continue;
domMesh * mesh = geometry->getMesh();
if (mesh==NULL) continue;
domVertices * vertices= mesh->getVertices();
if (vertices==NULL) continue;
for (size_t k=0; k<vertices->getInput_array().getCount(); k++)
{
if (stricmp(vertices->getInput_array()[k]->getSemantic(), "POSITION")==0)
{
domSource * source = (domSource*) (domElement*) vertices->getInput_array()[k]->getSource().getElement();
if (source)
{
domUint vertices_counts = source->getFloat_array()->getCount();
if (last_vertices_counts == 0)
last_vertices_counts = vertices_counts;
else
errorcount += CHECK_error(idref_array, last_vertices_counts == vertices_counts, "morph target vertices count doesn't match\n");
break;
}
}
}
}
} else if (stricmp(semantic, "MORPH_WEIGHT")==0)
{
morph_weight_count = source->getFloat_array()->getCount();
}
}
}
errorcount += CHECK_error(morph, morph_target_count != 0, "Morph: target count can't be zero\n");
errorcount += CHECK_error(morph, morph_weight_count != 0, "Morph: weight count can't be zero\n");
errorcount += CHECK_error(morph, morph_weight_count == morph_target_count, "Morph: target count and weight count doesn't match\n");
}
}
return errorcount;
}
| [
"steve314@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4"
]
| [
[
[
1,
1
],
[
24,
60
],
[
62,
126
],
[
148,
469
],
[
471,
476
],
[
478,
529
],
[
533,
564
],
[
566,
567
],
[
569,
1926
],
[
1928,
1933
],
[
1935,
2407
],
[
2410,
2415
],
[
2421,
2424
],
[
2426,
2452
],
[
2460,
2463
],
[
2468,
2471
],
[
2478,
2546
]
],
[
[
2,
23
],
[
61,
61
],
[
127,
147
],
[
470,
470
],
[
477,
477
],
[
530,
532
],
[
565,
565
],
[
568,
568
],
[
1927,
1927
],
[
1934,
1934
],
[
2408,
2409
],
[
2416,
2420
],
[
2425,
2425
],
[
2453,
2459
],
[
2464,
2467
],
[
2472,
2477
],
[
2547,
2548
]
]
]
|
5a39f16d13e082b7f0e74b813122f44eaa02d5a9 | 63085faa10712a085c09af4b639db0ad4831553e | /DtwSequenceCompare/gesturewindow.h | b5f400d6cc6614954884fbf0ef3e628b24e52203 | []
| no_license | OlliD/DtwSequenceCompare | 4913c3562db8e22359527d079dc0215e3de8b9f5 | a10b07bdb8dd7c19c27f909191e3e669216181a5 | refs/heads/master | 2021-01-01T16:19:36.972405 | 2010-10-04T09:58:56 | 2010-10-04T09:58:56 | 960,016 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | // This class builds an sliding windows with a given length,
// the sequence will be written to an vector
#ifndef GESTUREWINDOW_H
#define GESTUREWINDOW_H
#include <QObject>
#include <QTimer>
#include <QList>
//#include "iisutracker.h"
#include "dataholder.h"
#include "dtw.h"
class GestureWindow : public QObject
{
Q_OBJECT
public:
explicit GestureWindow(QList<QList<int>* >*, DataHolder*, QObject *parent = 0);
//explicit GestureWindow(QList<QList<int>* >*, IisuTracker*, DataHolder*, QObject *parent = 0);
bool stopCaptureSignal;
private:
//IisuTracker *tracker;
QList< QList<int>* >* gesture;
QList< int > *xList;
QList< int > *yList;
QList< int > *zList;
DTW *dtw;
QList<DTWResult> results;
DataHolder *dataHolder;
signals:
void sendResult(QList <DTWResult>);
public slots:
void stopCapture();
void receiveCoordinatesList(QList<int>);
};
#endif // GESTUREWINDOW_H
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
9dcfa51073bf404e17696015a39f6fbf731436f6 | ad07c5438d04956b066f271238aee4ef553619a8 | /src/Game.h | e9783827129b5efa7c8e005a8c87f30d4b78fcff | []
| no_license | szennyezettmennyezet/sim | a822fd4de38e3a14ea9fb1daa667b3c99034762e | 23c515fd8aad1162d675987ede28a2d822516f56 | refs/heads/master | 2020-05-18T12:41:29.931626 | 2011-10-22T09:37:15 | 2011-10-22T09:37:15 | 2,622,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,484 | h | #ifndef GAME_INCLUDED
#define GAME_INCLUDED
#include "GL/gl.h"
#include <iostream>
#include <vector>
struct Vertex4 {
float x;
float y;
float z;
float w;
};
struct Color4 {
float r;
float g;
float b;
float a;
};
class Game {
Vertex4 *vertices;
Color4 *colors;
std::vector<Vertex4> cube;
std::vector<Color4> cubeColors;
double rotX, rotY;
public:
Vertex4 cameraPosition;
Vertex4 cameraRotation;
Game() {
cameraPosition.x = 0;
cameraPosition.y = 0;
cameraPosition.z = 0;
cameraPosition.w = 1;
cameraRotation.x = 0.0;
cameraRotation.y = 0.0;
cameraRotation.z = 0.0;
cameraRotation.w = 0.0;
std::cout << "draw" << std::endl;
vertices = new Vertex4[4];
vertices[0].x = 0; vertices[0].y = 0; vertices[0].z = 0; vertices[0].w = 1;
vertices[1].x = 30; vertices[1].y = 0; vertices[1].z = 0; vertices[1].w = 1;
vertices[2].x = 30; vertices[2].y = 30; vertices[2].z = 0; vertices[2].w = 1;
vertices[3].x = 0; vertices[3].y = 30; vertices[3].z = 0; vertices[3].w = 1;
colors = new Color4[4];
colors[0].r = 1.0; colors[0].g = 0.0; colors[0].b = 0.0; colors[0].a = 0.0;
colors[1].r = 1.0; colors[1].g = 1.0; colors[1].b = 0.0; colors[1].a = 0.0;
colors[2].r = 1.0; colors[2].g = 0.0; colors[2].b = 1.0; colors[2].a = 0.0;
colors[3].r = 1.0; colors[3].g = 1.0; colors[3].b = 1.0; colors[3].a = 0.0;
rotX = rotY = 0;
Vertex4 vertex;vertex.w = 0.0;
Color4 color;
color.r = 1.0; color.g = 0.0; color.b = 0.0; color.a = 0.0;
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
color.r = 0.0; color.g = 1.0; color.b = 0.0; color.a = 0.0;
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
color.r = 0.0; color.g = 0.0; color.b = 1.0; color.a = 0.0;
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 0.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 0.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 40.0; cube.push_back(vertex); cubeColors.push_back(color);
vertex.x = 40.0; vertex.y = 40.0; vertex.z = 0.0; cube.push_back(vertex); cubeColors.push_back(color);
}
void drawCube() {
glTranslatef(-20, -20, 0.0);
glBegin(GL_TRIANGLES);
for (unsigned int i = 0; i< cube.size(); i++) {
glColor3fv(&cubeColors.at(i).r);
glVertex3fv(&cube.at(i).x);
}
glEnd();
}
void draw() {
rotX += 0.01;
rotY += 0.01;
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
//for (unsigned int x = 0; x < 10; x++) {
//for (unsigned int y = 0; y < 10; y++) {
glLoadIdentity();
glTranslated(-cameraPosition.x, cameraPosition.y, 20.0);
//cameraRotation.x = 45;
//glRotated(cameraRotation.x, 1.0, 0.0, 0.0);
//glRotated(rotY, 0.0, 1.0, 0.0);
glPushMatrix();
glTranslatef(100, 100, 0.0);
drawCube();
glPopMatrix();
glPushMatrix();
glTranslatef(150, 100, 0.0);
drawCube();
glPopMatrix();
glPushMatrix();
glTranslatef(100, 180, 0.0);
drawCube();
glPopMatrix();
//glBegin(GL_QUADS);
/*for (unsigned int i = 0; i < 4; i++) {
glColor3fv(&colors[i].r);
glVertex3fv(&vertices[i].x);
//glColor3f(colors[i].r, colors[i].g, colors[i].b);
//glVertex3f(vertices[i].x, vertices[i].y, vertices[i].z);
}*/
/*glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
glColor3f(1, 1, 0); glVertex3f(30, 0, 0);
glColor3f(1, 0, 1); glVertex3f(30, 30, 0);
glColor3f(1, 1, 1); glVertex3f(0, 30, 0);*/
//glEnd();
//}
//}
}
};
#endif // GAME_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
188
]
]
]
|
27d201625bfef0cbd31908a85e1606dba9d0e968 | 5bb9dfdfc412f7bc257163874265b8e847c34d14 | /WordATron/node.h | 696f437bb90d4aa62290286b4a8722adf8cddc5d | []
| no_license | venkatarajasekhar/WordATron | cc403f1fac4610b0cfbccd64bb53cd9da1b2a62d | 32ab4e4a0d374746ad6df47664abe1b68cd1334a | refs/heads/master | 2020-06-12T10:43:28.972134 | 2011-05-31T09:33:43 | 2011-05-31T09:33:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,391 | h | #ifndef NODE_H
#define NODE_H
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
enum nERRORS//node errors
{
RECORD_ERROR, NO_DATA
};
template<typename T>
struct node
{
node();
node(T data);
node(const node<T> &other);
node<T> operator=(const node<T> &other);
void copy(const node<T> &other);
~node();
T word;
int wordCount;
int syllables;
void wordCounts()
{
wordCount++;
}
int totalSyllables()
{
return syllables*wordCount;
}
vector< vector<int> > paragrahsLines;
bool isString(T item);
void update(int paragraph, int line, int syllable);
void print(ostream &out);
node *lt, *gt;
};
template<typename T>
node<T>::node(const node<T> &other)
{
copy(other);
}
template<typename T>
node<T> node<T>::operator=(const node &other)
{
if(this == other)
return *this;
copy(other);
}
template<typename T>
void node<T>::copy(const node<T> &other)
{
word = other.word;
syllables = other.syllables;
gt = other.gt;
lt = other.lt;
wordCount = other.wordCount;
vector<T> row;
for(int i = 0; i < int(other.paragrahsLines.size()); i++)
{
for(int k = 0; k < int(other.paragrahsLines[i].size()); k++)
{
row.push_back(other.paragrahsLines[i][k]);
//node.paragrahsLines[i].push_back(other.paragrahsLines[i][k]);
}
paragrahsLines.push_back(row);
}
}
template<typename T>
void node<T>::print(ostream &out)
{
out << "\n"<<word <<endl<< " count" << "["<<wordCount << "] ";
for(int i = 0; i < int(paragrahsLines.size()); i++)
{
if(paragrahsLines[i].size() > 0)
{
out << "\n :[" << i << "]: ";
for(int k = 0; k < int(paragrahsLines[i].size()); k++)
{
out<<paragrahsLines[i][k] << " ";
}
}
}
}
template<typename T>
node<T>::node()
{
wordCount = 0;
syllables = 0;
lt = NULL;
gt = NULL;
}
template<typename T>
node<T>::node(T data)//look over! possible issues with counter
{
word = data;
syllables = 0;
wordCount++;
lt = NULL;
gt = NULL;
}
template<typename T>
node<T>::~node()
{
lt = NULL;
gt = NULL;
}
template<typename T>
void node<T>::update(int paragraph, int line, int syllable)
{
syllables = syllable;
//cout << "paragrahsLines.size()-1:" << paragrahsLines.size()-1 << endl;
if( int(paragrahsLines.size()) == 0 || int((paragrahsLines.size()-1)) < paragraph )
{
//cout << "toDo: " << (paragraph+1) - paragrahsLines.size() << endl;
int toDo = (paragraph+1) - paragrahsLines.size();
for(int i = 0; i < (toDo-1); i++)
{
vector<int> newRow;
for(int j = 0; j <= 1; j++)
{
//newRow.push_back('\0');
;
}
paragrahsLines.push_back(newRow);
}
vector<int> newRow2;
newRow2.push_back(line);
paragrahsLines.push_back(newRow2);
//cout << paragrahsLines[1][0] << endl;
}
else if( int((paragrahsLines.size()-1)) == paragraph )
{
//cout << paragrahsLines[1].size() << endl;
paragrahsLines[paragraph].push_back(line);
//cout << paragrahsLines[1][1] << endl;
}
else
{
throw RECORD_ERROR;
}
}
/*
template<typename T>
bool node<T>::operator<(node<T> lhs, node<T> rhs)
{
if(isString())
{
return (toUpper(lhs->word) < toUpper(rhs->word));
}
else
{
return (lhs < rhs);
}
}
template<typename T>
bool node<T>::operator==(node<T> lhs, node<T> rhs)
{
if(isString())
{
return( toUpper(lhs->word) == toUpper(rhs->word) );
}
else
return( lhs->word == rhs->word );
}
*/
template<typename T>
bool node<T>::isString(T item)
{
try
{
try
{
throw item;
}
catch(string x)
{
return true;
}
}
catch(...)
{
return false;
}
}
#endif // NODE_H
| [
"[email protected]"
]
| [
[
[
1,
208
]
]
]
|
dfbef2ca38634cab58d656dda3684c72b89dceaa | 406b4b18f5c58c689d2324f49db972377fe8feb6 | /ANE/Source/Foundation/Node.cpp | 15d357cc54d993d5b332e556eac3b97e7f6bc970 | []
| no_license | Mobiwoom/ane | e17167de36699c451ed92eab7bf733e7d41fe847 | ec20667c556a99351024f3ae9c8880e944c5bfbd | refs/heads/master | 2021-01-17T13:09:57.966141 | 2010-03-23T16:30:17 | 2010-03-23T16:30:17 | 33,132,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | #include "Foundation/Node.h"
#include "Foundation/LockedList.h"
namespace Ane
{
Node::Node()
:m_pPrev(NULL), m_pNext(NULL), m_CurrentList(NULL)
{
}
Node::~Node()
{
}
void Node::PopThis()
{
this->m_CurrentList->PopAt(this);
}
void Node::ReSet()
{
m_pPrev = NULL;
m_pNext = NULL;
m_CurrentList = NULL;
}
}//namespace AneUtil | [
"inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac"
]
| [
[
[
1,
27
]
]
]
|
1a7e37c959a7050560e6afea8c89ad7e5b5b3e99 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/26042005/include/gui/gui.h | d5804215e568d2ee9ef35f480b645f54941e62db | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,698 | h | #ifndef _USERINTERFACE_H_
#define _USERINTERFACE_H_
#include <input/InputDeviceDB.h>
#include <gui/ComponentLibrary.h>
#include <gui/GUIComponents.h>
#include <FusionSubsystem.h>
// external predeclared classes
class SceneGraph;
class IModuleDB;
//=====================================
// Window - holds components which
// make up the display of
// this object
//=====================================
class Window{
private:
bool m_active;
int m_comp_id;
char *m_title; // To hold a title for the window
WINDOWCOMPONENT m_components;
InputDeviceDB *m_inputdevicedb;
IWindowComponent *m_highlighted_component;
InputEvent *m_event;
SceneGraph *m_scenegraph;
// For state based machine
IWindowComponent *m_cache_wc;
//=========================
void ProcessEvents (void);
public:
int m_WindowID;
Window (InputDeviceDB *inputdevicedb, SceneGraph *scenegraph);
virtual ~Window ();
virtual bool Initialise (void);
virtual void SetTitle (char *title);
virtual char * GetTitle (void);
virtual void SetActive (bool Active);
virtual bool Update (void);
virtual IWindowComponent * AddComponent (WndComponentSetup *wcs);
virtual void SetCaps (int caps, union CapabilityData *cd);
virtual IWindowComponent * GetComponentPtr (int type,int value);
};
typedef std::vector<Window *> WINDOWLIST;
//==================
// UserInterface
//==================
class UserInterface
{
private:
WINDOWLIST m_windows;
IModuleDB *m_moduledb;
SceneGraph *m_scenegraph;
bool m_active;
public:
UserInterface (IModuleDB *moduledb,SceneGraph *scene);
virtual ~UserInterface ();
virtual Window * AddWindow (InputDeviceDB *inputdevicedb);
virtual void RemoveWindow (Window **window);
virtual Window * GetWindowPtr (char *title);
virtual bool Update (void);
virtual void SetActive (bool active);
};
typedef std::vector<UserInterface *> INTERFACELIST;
//==========================
// UserInterfaceDB class
//==========================
class UserInterfaceDB: public FusionSubsystem{
protected:
INTERFACELIST m_interface_list;
IModuleDB *m_moduledb;
public:
static ComponentLibrary m_library;
UserInterfaceDB ();
virtual ~UserInterfaceDB ();
virtual bool Initialise (void);
virtual UserInterface * AddUI (SceneGraph *scene);
virtual void RemoveUI (UserInterface *ui);
virtual void RemoveAllUI (void);
virtual bool Update (void);
virtual bool AddComponentLibrary (char *libfilename);
};
#endif // #ifndef _USERINTERFACE_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
93
]
]
]
|
7502e4102792c4d20cb250df04385e3cb9e2ac58 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /RakNet/NatTypeDetectionCommon.cpp | 806b54ffbcfd68d41a3bea9ca889d5a98554d4af | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,651 | cpp | #include "NatTypeDetectionCommon.h"
#include "SocketLayer.h"
#include "SocketIncludes.h"
using namespace RakNet;
bool RakNet::CanConnect(NATTypeDetectionResult type1, NATTypeDetectionResult type2)
{
/// If one system is NAT_TYPE_SYMMETRIC, the other must be NAT_TYPE_ADDRESS_RESTRICTED or less
/// If one system is NAT_TYPE_PORT_RESTRICTED, the other must be NAT_TYPE_PORT_RESTRICTED or less
bool connectionGraph[NAT_TYPE_COUNT][NAT_TYPE_COUNT] =
{
// None, Full Cone, Address Restricted, Port Restricted, Symmetric, Unknown, InProgress, Supports_UPNP
{true, true, true, true, true, false, false, false}, // None
{true, true, true, true, true, false, false, false}, // Full Cone
{true, true, true, true, true, false, false, false}, // Address restricted
{true, true, true, true, false, false, false, false}, // Port restricted
{true, true, true, false, false, false, false, false}, // Symmetric
{false, false, false, false, false, false, false, false}, // Unknown
{false, false, false, false, false, false, false, false}, // InProgress
{false, false, false, false, false, false, false, false} // Supports_UPNP
};
return connectionGraph[(int) type1][(int) type2];
}
const char *RakNet::NATTypeDetectionResultToString(NATTypeDetectionResult type)
{
switch (type)
{
case NAT_TYPE_NONE:
return "None";
case NAT_TYPE_FULL_CONE:
return "Full cone";
case NAT_TYPE_ADDRESS_RESTRICTED:
return "Address restricted";
case NAT_TYPE_PORT_RESTRICTED:
return "Port restricted";
case NAT_TYPE_SYMMETRIC:
return "Symmetric";
case NAT_TYPE_UNKNOWN:
return "Unknown";
case NAT_TYPE_DETECTION_IN_PROGRESS:
return "In Progress";
case NAT_TYPE_SUPPORTS_UPNP:
return "Supports UPNP";
case NAT_TYPE_COUNT:
return "NAT_TYPE_COUNT";
}
return "Error, unknown enum in NATTypeDetectionResult";
}
// None and relaxed can connect to anything
// Moderate can connect to moderate or less
// Strict can connect to relaxed or less
const char *RakNet::NATTypeDetectionResultToStringFriendly(NATTypeDetectionResult type)
{
switch (type)
{
case NAT_TYPE_NONE:
return "Open";
case NAT_TYPE_FULL_CONE:
return "Relaxed";
case NAT_TYPE_ADDRESS_RESTRICTED:
return "Relaxed";
case NAT_TYPE_PORT_RESTRICTED:
return "Moderate";
case NAT_TYPE_SYMMETRIC:
return "Strict";
case NAT_TYPE_UNKNOWN:
return "Unknown";
case NAT_TYPE_DETECTION_IN_PROGRESS:
return "In Progress";
case NAT_TYPE_SUPPORTS_UPNP:
return "Supports UPNP";
case NAT_TYPE_COUNT:
return "NAT_TYPE_COUNT";
}
return "Error, unknown enum in NATTypeDetectionResult";
}
SOCKET RakNet::CreateNonblockingBoundSocket(const char *bindAddr )
{
SOCKET s = SocketLayer::CreateBoundSocket( 0, false, bindAddr, true, 0, AF_INET );
#ifdef _WIN32
unsigned long nonblocking = 1;
ioctlsocket( s, FIONBIO, &nonblocking );
#else
fcntl( s, F_SETFL, O_NONBLOCK );
#endif
return s;
}
int RakNet::NatTypeRecvFrom(char *data, SOCKET socket, SystemAddress &sender)
{
sockaddr_in sa;
socklen_t len2;
const int flag=0;
len2 = sizeof( sa );
sa.sin_family = AF_INET;
sa.sin_port=0;
int len = recvfrom( socket, data, MAXIMUM_MTU_SIZE, flag, ( sockaddr* ) & sa, ( socklen_t* ) & len2 );
if (len>0)
{
sender.address.addr4.sin_family=AF_INET;
sender.address.addr4.sin_addr.s_addr = sa.sin_addr.s_addr;
//sender.SetPort( ntohs( sa.sin_port ) );
sender.SetPort( ntohs( sa.sin_port ) );
}
return len;
}
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
fab6670972e2159660dd245037c8753ee2a1a7e5 | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgreCapsule.h | 33c5e80cf3ec3e1408dfb5d5425b3e42052ad70f | []
| no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,440 | h | /** File: NxOgreCapsule.h
Created on: 15-Mar-09
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NxOgre is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_CAPSULE_H
#define NXOGRE_CAPSULE_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#include "NxOgrePointerClass.h"
#include "NxOgreShape.h"
#include "NxOgreShapeBlueprint.h"
namespace NxOgre_Namespace
{
/** \brief
*/
class NxOgrePublicClass Capsule : public PointerClass<Classes::_Capsule>, public Shape
{
friend class RigidBodyPrototype;
public: // Functions
using ::NxOgre::PointerClass<Classes::_Capsule>::operator new;
using ::NxOgre::PointerClass<Classes::_Capsule>::operator delete;
using ::NxOgre::PointerClass<Classes::_Capsule>::getClassType;
/** \brief Capsule
*/
Capsule(Real radius, Real height, ShapeBlueprint* box_blueprint = new ShapeBlueprint());
/** \brief Capsule
*/
~Capsule(void);
/** \brief Get the shape type based upon the Classes::xxxx enum.
*/
Enums::ShapeFunctionType getShapeFunctionType() const;
/** \brief Set Dimensions
*/
void setDimensions(Real radius, Real height);
/** \brief Set radius
*/
void setRadius(Real radius);
/** \brief Set radius
*/
void setHeight(Real height);
/** \brief Get radius
*/
Real getRadius(void) const;
/** \brief Get height
*/
Real getHeight(void) const;
/** \brief Retrives the capsule parameters in world space.
*/
SimpleCapsule getWorldCapsule(void);
protected:
/** \internal DO NOT USE.
*/
NxShapeDesc* create();
/** \internal DO NOT USE.
*/
void assign(NxShape*);
protected:
NxCapsuleShape* mCapsuleShape;
}; // class Capsule
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
]
| [
[
[
1,
116
]
]
]
|
5cd939e9958e76b9372a58dc0e79db0b2ab663e9 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/gfx/ngl_text.cc | 4a7e2aef9fb75e7a6728eaf9fb8cba38644e015e | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,273 | cc | #define N_IMPLEMENTS nGlServer
//-------------------------------------------------------------------
// ngl_text.cc
// GL text rendering functions.
// (C) 1999 A.Weissflog
//-------------------------------------------------------------------
#include "gfx/nglserver.h"
//-------------------------------------------------------------------
// BeginText()
// 21-Feb-99 floh created
// 26-Mar-00 floh Fog turned off...
//-------------------------------------------------------------------
bool nGlServer::BeginText(void)
{
if (this->text_initialized) {
this->in_begin_text = true;
glPushAttrib(GL_ALL_ATTRIB_BITS);
nSwitchGlCapsOff();
nSetGlCapability(false, GL_DEPTH_TEST);
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glFrustum(-1.0f,1.0f,-1.0f,1.0f,1.0f,10.0f);
return true;
}
return false;
}
//-------------------------------------------------------------------
// EndText()
// 21-Feb-99 floh created
//-------------------------------------------------------------------
bool nGlServer::EndText(void)
{
n_assert(this->in_begin_text);
if (this->text_initialized) {
// OpenGL iss schu geil...
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
return true;
}
//-------------------------------------------------------------------
// TextPos()
// 21-Feb-99 floh created
//-------------------------------------------------------------------
void nGlServer::TextPos(float x, float y)
{
n_assert(this->in_begin_text);
this->text_x = x;
this->text_y = y + 2.0f*(this->text_height / ((float)this->disp_h));
}
#define T_OFFS 0.025f
//-------------------------------------------------------------------
// Text()
// 21-Feb-99 floh created
//-------------------------------------------------------------------
bool nGlServer::Text(const char *s)
{
n_assert(this->in_begin_text);
bool scanning = true;
if (this->text_initialized) {
glListBase(this->text_listbase);
// FIXME! NICHT DBCS SAFE!!!
char c;
const char *s_start = s;
const char *str = s;
int num_chars = 0;
while (scanning) {
c = *str++;
if (c < 32) {
// ein Sonderzeichen, erstmal alles vorher anzeigen...
if (num_chars > 0) {
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glRasterPos3f(this->text_x*5.0f+T_OFFS, -this->text_y*5.0f, -5.0f);
glCallLists(num_chars, GL_UNSIGNED_BYTE, s_start);
glRasterPos3f(this->text_x*5.0f-T_OFFS, -this->text_y*5.0f, -5.0f);
glCallLists(num_chars, GL_UNSIGNED_BYTE, s_start);
glRasterPos3f(this->text_x*5.0f, -this->text_y*5.0f-T_OFFS, -5.0f);
glCallLists(num_chars, GL_UNSIGNED_BYTE, s_start);
glRasterPos3f(this->text_x*5.0f, -this->text_y*5.0f+T_OFFS, -5.0f);
glCallLists(num_chars, GL_UNSIGNED_BYTE, s_start);
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
glRasterPos3f(this->text_x*5.0f, -this->text_y*5.0f, -5.0f);
glCallLists(num_chars, GL_UNSIGNED_BYTE, s_start);
}
s_start = str;
num_chars = 0;
switch (c) {
case 0:
scanning=false;
break;
case '\n':
if (this->disp_h > 0) {
this->text_y += 2.0f*(this->text_height / ((float)this->disp_h));
glRasterPos3f(this->text_x*5.0f, -this->text_y*5.0f, -5.0f);
}
break;
}
} else num_chars++;
}
glListBase(0);
}
return true;
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
132
]
]
]
|
a7b45634aad77019463fdd6e07a268f44424b774 | fd0221edcf44c190efadd6d8b13763ef5bcbc6f6 | /fer_h264/fer_h264/rbsp_decoding.cpp | 8be0f6fe8dcfe69565480f02f4d3b8b8b4dbff54 | []
| no_license | zoltanmaric/h264-fer | 2ddb8ac5af293dd1a30d9ca37c8508377745d025 | 695c712a74a75ad96330613e5dd24938e29f96e6 | refs/heads/master | 2021-01-01T15:31:42.218179 | 2010-06-17T21:09:11 | 2010-06-17T21:09:11 | 32,142,996 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 11,562 | cpp | #include "nal.h"
#include "headers_and_parameter_sets.h"
#include "residual.h"
#include "expgolomb.h"
#include "h264_globals.h"
#include "rbsp_IO.h"
#include "intra.h"
#include "inttransform.h"
#include "fileIO.h"
#include "ref_frames.h"
#include "mocomp.h"
#include "mode_pred.h"
#include "moestimation.h"
#include "quantizationTransform.h"
#include "rbsp_decoding.h"
void RBSP_decode(NALunit nal_unit)
{
static int nalBrojac=0;
static int idr_frame_number=0;
printf("Entering RBPS_decode #%d\n",nalBrojac++);
initRawReader(nal_unit.rbsp_byte, nal_unit.NumBytesInRBSP);
//TYPE 7 = Sequence parameter set TODO: Provjera postoji li veŠ SPS
//READ SPS
if (nal_unit.nal_unit_type==NAL_UNIT_TYPE_SEI)
{
printf("RBSP_decode -> Not supported NAL unit type: SEI (type 6)\n");
}
else if (nal_unit.nal_unit_type==NAL_UNIT_TYPE_SPS)
{
fill_sps(&nal_unit);
init_h264_structures();
AllocateMemory();
}
//TYPE 8 = Picture parameter set TODO: Provjera postoji li veŠ PPS i SPS
else if (nal_unit.nal_unit_type==NAL_UNIT_TYPE_PPS)
{
fill_pps(&nal_unit);
}
//IDR or NOT IDR slice data
////////////////////////////////////////////////////////////////////
//Actual picture decoding takes place here
//The main loop works macroblock by macroblock until the end of the slice
//Macroblock skipping is implemented
else if ((nal_unit.nal_unit_type==NAL_UNIT_TYPE_IDR) || (nal_unit.nal_unit_type==NAL_UNIT_TYPE_NOT_IDR))
{
frameCount++;
//Read slice header
fill_shd(&nal_unit);
printf("Working on frame #%d...\n", frameCount);
int MbCount=shd.PicSizeInMbs;
//Norm: firstMbAddr=first_mb_in_slice * ( 1 + MbaffFrameFlag );
int firstMbAddr = 0;
CurrMbAddr = firstMbAddr;
//Norm: moreDataFlag = 1
bool moreDataFlag = true;
//Norm: prevMbSkipped = 0
int prevMbSkipped = 0;
//Used later on
int mb_skip_run;
// Prediction samples formed by either intra or inter prediction.
int predL[16][16], predCb[8][8], predCr[8][8];
QPy = shd.SliceQPy;
while (moreDataFlag && CurrMbAddr<MbCount)
{
/*for (int i = 0; i < 4; i++)
ChromaDCLevel[0][i] = ChromaDCLevel[1][i] = 0;
for (int i = 0; i < 16; i++)
LumaDCLevel[i] = 0;*/
if ((shd.slice_type%5)!=I_SLICE && (shd.slice_type%5)!=SI_SLICE)
{
//First decode various data at the beggining of each slice/frame
//Norm: if( !entropy_coding_mode_flag ) ... this "if clause" is skipped.
mb_skip_run=expGolomb_UD();
prevMbSkipped = (mb_skip_run > 0);
for(int i=0; i<mb_skip_run; i++ )
{
if (CurrMbAddr >= MbCount)
{
break;
}
mb_type = P_Skip;
mb_type_array[CurrMbAddr]=P_Skip;
// Inter prediction:
DeriveMVs();
Decode(predL, predCr, predCb);
// Norm: QpBdOffsetY == 0 in baseline
QPy = (QPy + mb_qp_delta + 52) % 52;
// Inverse transformation and decoded sample construction:
transformDecodingP_Skip(predL, predCb, predCr, QPy);
//Norm: CurrMbAddr = NextMbAddress( CurrMbAddr )
CurrMbAddr++;
}
if ((CurrMbAddr != firstMbAddr) || (mb_skip_run > 0))
{
moreDataFlag = more_rbsp_data();
}
}
if(moreDataFlag)
{
// Norm: start macroblock_layer()
mb_pos_array[CurrMbAddr]=(RBSP_current_bit+1)&7;
mb_type = expGolomb_UD();
mb_type_array[CurrMbAddr]=mb_type;
if ((mb_type > 31) || ((shd.slice_type == I_SLICE) && (mb_type > 24)))
{
printf("Fatal error: Unexpected mb_type value (%d)\n", mb_type);
printf("Slice type: %d\n", shd.slice_type);
printf("Frame #%d, CurrMbAddr = %d\n", frameCount, CurrMbAddr);
system("pause");
writeToPPM("errorFrame"); // dump the current frame
exit(1);
}
//Norm: if( mb_type != I_NxN && MbPartPredMode( mb_type, 0 ) != Intra_16x16 && NumMbPart( mb_type ) == 4 )
// I_NxN is an alias for Intra_4x4 and Intra_8x8 MbPartPredMode (mb_type in both cases equal to 0)
// mb_type (positive integer value) is equal to "Name of mb_type" (i.e. I_NxN). These are often interchanged in the norm
// Everything as described in norm page 119. table 7-11.
//Specific inter prediction?
// Norm: if (mb_type != I_NxN && MbPartPredMode(mb_type,0) != Intra_16x16 && NumMbPart(mb_type) == 4)
if(MbPartPredMode(mb_type,0) != Intra_4x4 && MbPartPredMode( mb_type, 0 )!=Intra_16x16 && NumMbPart( mb_type )==4 )
{
// Norm: start sub_mb_pred(mb_type)
int mbPartIdx;
for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
{
sub_mb_type[mbPartIdx]=expGolomb_UD();
}
for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
{
if ((shd.num_ref_idx_active_override_flag > 0) &&
(mb_type != P_8x8ref0) &&
(SubMbPredMode(sub_mb_type[mbPartIdx]) != Pred_L1))
{
ref_idx_l0_array[CurrMbAddr][mbPartIdx] = expGolomb_TD();
}
}
// Norm: there are no B-frames in baseline, so the stream
// does not contain ref_idx_l1 or mvd_l1
for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
{
for (int subMbPartIdx = 0; subMbPartIdx < NumSubMbPart(sub_mb_type[mbPartIdx]); subMbPartIdx++)
{
mvd_l0[mbPartIdx][subMbPartIdx][0] = expGolomb_SD();
mvd_l0[mbPartIdx][subMbPartIdx][1] = expGolomb_SD();
}
}
// Norm: end sub_mb_pred(mb_type)
}
else
{
//Norm: This is section "mb_pred( mb_type )"
if(MbPartPredMode(mb_type, 0) == Intra_4x4 /*|| MbPartPredMode(mb_type, 0) == Intra_8x8*/ || MbPartPredMode(mb_type, 0) == Intra_16x16 )
{
if(MbPartPredMode(mb_type, 0) == Intra_4x4)
{
for(int luma4x4BlkIdx=0; luma4x4BlkIdx<16; luma4x4BlkIdx++)
{
prev_intra4x4_pred_mode_flag[luma4x4BlkIdx] = (bool)getRawBit();
if(prev_intra4x4_pred_mode_flag[luma4x4BlkIdx]==false)
{
rem_intra4x4_pred_mode[luma4x4BlkIdx]=getRawBits(3);
}
}
}
//Norm:
//if( MbPartPredMode( mb_type, 0 ) = = Intra_8x8 )
//This if clause has been skipped, because "intra_8x8" is not supported in baseline.
//Norm:
//if( ChromaArrayType == 1 || ChromaArrayType == 2 )
//baseline defines "ChromaArrayType==1", so the if clause is skipped
intra_chroma_pred_mode=expGolomb_UD();
if (intra_chroma_pred_mode > 3)
{
printf("Fatal error: Unexpected intra_chroma_pred_mode value (%d)\n", intra_chroma_pred_mode);
printf("Frame #%d, CurrMbAddr = %d\n", frameCount, CurrMbAddr);
system("pause");
writeToPPM("errorFrame"); // dump the current frame
exit(1);
}
}
else
{
int mbPartIdx;
for (mbPartIdx = 0; mbPartIdx < NumMbPart(mb_type); mbPartIdx++)
{
if ((shd.num_ref_idx_l0_active_minus1 > 0) &&
(MbPartPredMode(mb_type, mbPartIdx) != Pred_L1))
{
ref_idx_l0_array[CurrMbAddr][mbPartIdx] = expGolomb_TD();
}
}
// Norm: there are no B-frames in baseline, so the stream
// does not contain ref_idx_l1 or mvd_l1
for (mbPartIdx = 0; mbPartIdx < NumMbPart(mb_type); ++mbPartIdx)
{
if (MbPartPredMode(mb_type, mbPartIdx) != Pred_L1)
{
mvd_l0[mbPartIdx][0][0] = expGolomb_SD();
mvd_l0[mbPartIdx][0][1] = expGolomb_SD();
}
}
}
// Norm: end mb_pred(mb_type)
}
//If the next if clause does not execute, this is the final value of coded block patterns for this macroblock
CodedBlockPatternLuma=-1;
CodedBlockPatternChroma=-1;
if(MbPartPredMode(mb_type,0)!=Intra_16x16)
{
int coded_block_pattern=expGolomb_UD();
if (coded_block_pattern > 47)
{
printf("Fatal error: Unexpected coded_block_pattern value (%d)\n", coded_block_pattern);
printf("Frame #%d, CurrMbAddr = %d\n", frameCount, CurrMbAddr);
system("pause");
writeToPPM("errorFrame"); // dump the current frame
exit(1);
}
//This is not real coded_block_pattern, it's the coded "codeNum" value which is now being decoded:
if(MbPartPredMode(mb_type,0)==Intra_4x4 /*|| MbPartPredMode(mb_type,0)==Intra_8x8*/ )
{
coded_block_pattern=codeNum_to_coded_block_pattern_intra[coded_block_pattern];
}
//Inter prediction
else
{
coded_block_pattern=codeNum_to_coded_block_pattern_inter[coded_block_pattern];
}
CodedBlockPatternLuma=coded_block_pattern & 15;
CodedBlockPatternChroma=coded_block_pattern >> 4;
//Norm:
/*
if( CodedBlockPatternLuma > 0 && transform_8x8_mode_flag && mb_type != I_NxN && noSubMbPartSizeLessThan8x8Flag &&
( mb_type != B_Direct_16x16 || direct_8x8_inference_flag))
*/
//This if clause is not implemented since transform_8x8_mode_flag is not supported
}
//DOES NOT EXIST IN THE NORM!
else
{
if (shd.slice_type % 5 == I_SLICE)
{
CodedBlockPatternChroma=I_Macroblock_Modes[mb_type][5];
CodedBlockPatternLuma=I_Macroblock_Modes[mb_type][6];
}
else
{
CodedBlockPatternChroma=P_and_SP_macroblock_modes[mb_type][5];
CodedBlockPatternLuma=P_and_SP_macroblock_modes[mb_type][6];
}
}
CodedBlockPatternLumaArray[CurrMbAddr] = CodedBlockPatternLuma;
CodedBlockPatternChromaArray[CurrMbAddr] = CodedBlockPatternChroma;
if(CodedBlockPatternLuma>0 || CodedBlockPatternChroma>0 || MbPartPredMode(mb_type,0)==Intra_16x16)
{
mb_qp_delta=expGolomb_SD();
if ((mb_qp_delta < -26) || (mb_qp_delta > 25))
{
printf("Fatal error: Unexpected mb_qp_delta value (%d)\n", mb_qp_delta);
printf("Frame #%d, CurrMbAddr = %d\n", frameCount, CurrMbAddr);
system("pause");
writeToPPM("errorFrame"); // dump the current frame
exit(1);
}
//Norm: decode residual data.
//residual_block_cavlc( coeffLevel, startIdx, endIdx, maxNumCoeff )
residual(0, 15);
}
else
{
clear_residual_structures();
}
// Norm: end macroblock_layer()
//Data ready for rendering
// Norm: QpBdOffsetY == 0 in baseline
QPy = (QPy + mb_qp_delta + 52) % 52;
if ((MbPartPredMode(mb_type , 0) == Intra_4x4) || (MbPartPredMode(mb_type , 0) == Intra_16x16))
{
intraPrediction(predL, predCr, predCb);
}
else
{
DeriveMVs();
Decode(predL, predCr, predCb);
}
if (MbPartPredMode(mb_type, 0) == Intra_16x16)
{
transformDecodingIntra_16x16Luma(Intra16x16DCLevel, Intra16x16ACLevel, predL, QPy);
}
else if (MbPartPredMode(mb_type, 0) != Intra_4x4) // Intra
{
for(int luma4x4BlkIdx = 0; luma4x4BlkIdx < 16; luma4x4BlkIdx++)
{
transformDecoding4x4LumaResidual(LumaLevel, predL, luma4x4BlkIdx, QPy);
}
}
transformDecodingChroma(ChromaDCLevel[0], ChromaACLevel[0], predCb, QPy, true);
transformDecodingChroma(ChromaDCLevel[1], ChromaACLevel[1], predCr, QPy, false);
moreDataFlag=more_rbsp_data();
++CurrMbAddr;
}
}
if (shd.slice_type%5 == I_SLICE)
{
// Reference frame list initialisation
initialisationProcess();
idr_frame_number++;
}
// Reference frame list modification
modificationProcess();
//writeToPPM("frame");
writeToY4M();
}
}
| [
"ljubo.mercep@9f3bdf0a-daf3-11de-b590-7f2b5bfbe1fd",
"[email protected]@9f3bdf0a-daf3-11de-b590-7f2b5bfbe1fd",
"tomislav.haramustek@9f3bdf0a-daf3-11de-b590-7f2b5bfbe1fd",
"davor.prugovecki@9f3bdf0a-daf3-11de-b590-7f2b5bfbe1fd"
]
| [
[
[
1,
7
],
[
15,
15
],
[
17,
19
],
[
23,
25
],
[
27,
36
],
[
38,
38
],
[
40,
49
],
[
51,
51
],
[
55,
55
],
[
57,
57
],
[
59,
59
],
[
62,
62
],
[
64,
64
],
[
67,
67
],
[
70,
70
],
[
73,
73
],
[
76,
76
],
[
78,
78
],
[
85,
85
],
[
87,
87
],
[
100,
100
],
[
104,
104
],
[
119,
119
],
[
125,
125
],
[
137,
137
],
[
142,
142
],
[
153,
153
],
[
163,
163
],
[
166,
166
],
[
178,
178
],
[
181,
181
],
[
186,
186
],
[
193,
193
],
[
197,
197
],
[
201,
201
],
[
237,
238
],
[
242,
242
],
[
254,
254
],
[
256,
256
],
[
266,
266
],
[
269,
269
],
[
277,
280
],
[
292,
292
],
[
297,
297
],
[
307,
307
],
[
318,
318
],
[
323,
323
],
[
345,
347
],
[
351,
352
],
[
367,
369
]
],
[
[
8,
13
],
[
16,
16
],
[
20,
22
],
[
26,
26
],
[
39,
39
],
[
50,
50
],
[
52,
54
],
[
56,
56
],
[
58,
58
],
[
60,
61
],
[
63,
63
],
[
65,
66
],
[
68,
69
],
[
71,
72
],
[
74,
75
],
[
77,
77
],
[
79,
79
],
[
82,
84
],
[
86,
86
],
[
88,
99
],
[
101,
103
],
[
105,
118
],
[
120,
124
],
[
126,
126
],
[
128,
136
],
[
143,
149
],
[
151,
151
],
[
154,
162
],
[
164,
165
],
[
167,
167
],
[
169,
172
],
[
174,
176
],
[
183,
183
],
[
185,
185
],
[
187,
187
],
[
191,
192
],
[
196,
196
],
[
200,
200
],
[
203,
218
],
[
220,
232
],
[
234,
236
],
[
246,
253
],
[
264,
264
],
[
267,
268
],
[
273,
273
],
[
281,
291
],
[
293,
294
],
[
299,
306
],
[
311,
311
],
[
313,
317
],
[
321,
322
],
[
324,
334
],
[
336,
336
],
[
338,
344
],
[
348,
350
],
[
353,
357
],
[
359,
366
]
],
[
[
14,
14
],
[
138,
141
],
[
150,
150
],
[
152,
152
],
[
168,
168
],
[
173,
173
],
[
177,
177
],
[
179,
180
],
[
182,
182
],
[
184,
184
],
[
188,
190
],
[
194,
195
],
[
198,
199
],
[
202,
202
],
[
219,
219
],
[
233,
233
],
[
239,
241
],
[
243,
245
],
[
255,
255
],
[
257,
263
],
[
265,
265
],
[
270,
272
],
[
274,
276
],
[
295,
296
],
[
298,
298
],
[
308,
310
],
[
312,
312
],
[
319,
320
],
[
335,
335
],
[
337,
337
]
],
[
[
37,
37
],
[
80,
81
],
[
127,
127
],
[
358,
358
]
]
]
|
768112eaa7789cb34c90dce435c388367af382a7 | 1ad310fc8abf44dbcb99add43f6c6b4c97a3767c | /samples_c++/cc/sprite_devl/Stub.cpp | c204347fd523a06d8e2ccc289ab90e91073397e9 | []
| no_license | Jazzinghen/spamOSEK | fed44979b86149809f0fe70355f2117e9cb954f3 | 7223a2fb78401e1d9fa96ecaa2323564c765c970 | refs/heads/master | 2020-06-01T03:55:48.113095 | 2010-05-19T14:37:30 | 2010-05-19T14:37:30 | 580,640 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,015 | cpp | #include "Stub.h"
#ifdef _MSC_VER
#include "SDL.h"
#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")
#endif
static SDL_Surface *screen = NULL;
static int timer = 0;
void display_gui()
{
bool fullscreen = false;
// Initialize SDL's subsystems - in this case, only video.
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
timer = SDL_GetTicks();
// Register SDL_Quit to be called at exit; makes sure things are
// cleaned up when we quit.
atexit(SDL_Quit);
if (fullscreen)
screen = SDL_SetVideoMode(100,64,16, SDL_DOUBLEBUF | SDL_SWSURFACE | SDL_FULLSCREEN);
else
screen = SDL_SetVideoMode(100,64,16, SDL_DOUBLEBUF | SDL_SWSURFACE);
// If we fail, return error.
if ( screen == NULL )
{
fprintf(stderr, "Unable to set 100x64 video: %s\n", SDL_GetError());
exit(1);
}
}
void display_bitmap_copy(const unsigned char* lcd, int width, int height, int x, int y)
{
if (SDL_MUSTLOCK(screen) != 0)
{
if (SDL_LockSurface(screen) < 0)
{
fprintf(stderr, "screen locking failed\n");
return;
}
}
int tpitch = screen->pitch / 2;
Uint16* tp = (Uint16*) screen->pixels;
SDL_Rect rect;
rect.x = 0;
rect.y = 0;
rect.w = 100;
rect.h = 64;
SDL_FillRect(SDL_GetVideoSurface(), &rect, 0xffffffff);
for (int j = 0; j < 64; ++j)
{
for (int i = 0; i < 100; ++i)
{
if(lcd[((j*100) + i)/8] & (1<<(((j*100) + i)%8)))
{
tp[i] = 0x0000;
}
}
tp += tpitch;
}
if (SDL_MUSTLOCK(screen))
{
SDL_UnlockSurface(screen);
}
}
void display_update()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYUP:
// If escape is pressed, return (and thus, quit)
if (event.key.keysym.sym == SDLK_ESCAPE)
exit(0);
break;
}
}
while(SDL_GetTicks() - timer < 15)
{
}
timer = SDL_GetTicks();
SDL_Flip(screen);
} | [
"jazzinghen@Jehuty.(none)"
]
| [
[
[
1,
105
]
]
]
|
90a230b0ceaa1a2caefbed6efde83f6271ca68f8 | 968aa9bac548662b49af4e2b873b61873ba6f680 | /e32tools/elf2e32/source/messageimplementation.cpp | 340f1e1ac5011729fce12be69492ed4123cc5326 | []
| no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,657 | cpp | // Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// Message Implementation Operations for elf2e32 tool
// @internalComponent
// @released
//
//
#include "messageimplementation.h"
#include "errorhandler.h"
#include<iostream>
#include<stdarg.h>
#include<string>
#include <stdio.h>
using std::endl;
using std::cout;
typedef std::string String;
char *errorMssgPrefix="elf2e32 : Error: E";
char *warnMssgPrefix="elf2e32 : Warning: W";
char *infoMssgPrefix="elf2e32 : Information: I";
char *colSpace=": ";
enum MessageArraySize{MAX=66};
//Messages stored required for the program
struct EnglishMessage MessageArray[MAX]=
{
{FILEOPENERROR,"Could not open file : %s."},
{FILEREADERROR,"Could not read file : %s."},
{FILEWRITEERROR,"Could not write file : %s."},
{ELFMAGICERROR,"Invalid ELF magic in file : %s."},
{ELFCLASSERROR,"ELF file %s is not 32 bit."},
{ELFABIVERSIONERROR,"ELF file %s is not BPABI conformant."},
{ELFLEERROR,"ELF file %s is not Little Endian."},
{ELFARMERROR,"ELF file %s does not target ARM."},
{ELFEXECUTABLEERROR,"ELF file %s is neither executable (ET_EXEC) or shared (ET_DYN)."},
{ELFSHSTRINDEXERROR,"Error in ELF Section Header String Index : %s."},
{NAMELIBRARYNOTCORRECT,"Name or Library not supplied correctly : %s[Line No=%d][%s]"},
{ORDINALSEQUENCEERROR,"Ordinal number is not in sequence : %s[Line No=%d][%s]."},
{ARGUMENTNAMEERROR,"Argument %s is not correct."},
{OPTIONNAMEERROR,"Option %s is Unrecognized."},
{NOARGUMENTERROR,"Missing arguments for option : %s."},
{OPTIONPREFIXERROR,"Option %s is neither preceedded by '-' nor '--'."},
{NOREQUIREDOPTIONERROR,"Missing options : %s."},
{NOFILENAMEERROR,"Missing argument for option : %s."},
{INVALIDARGUMENTERROR,"Argument '%s' not permitted for option %s."},
{HUFFMANBUFFEROVERFLOWERROR,"Huffman buffer overflow during E32Image compression."},
{HUFFMANTOOMANYCODESERROR,"Too many Huffman codes during E32Image compression."},
{HUFFMANINVALIDCODINGERROR,"Invalid Huffman coding during E32Image compression."},
{CAPABILITYALLINVERSIONERROR,"-ALL not a valid capability."},
{CAPABILITYNONEINVERSIONERROR,"+NONE not a valid capability."},
{UNRECOGNISEDCAPABILITYERROR,"Unrecognized capability : %s."},
{NOSTATICSYMBOLSERROR,"ELF File %s contains no static symbols."},
{DLLHASINITIALISEDDATAERROR,"ELF File %s contains initialized writable data."},
{DLLHASUNINITIALISEDDATAERROR,"ELF File %s contains uninitialized writable data."},
{ENTRYPOINTCORRUPTERROR,"ELF File %s has corrupt entry point."},
{ENTRYPOINTNOTSUPPORTEDERROR,"ELF File %s has unsupported entry point type."},
{EXCEPTIONDESCRIPTOROUTSIDEROERROR,"ELF File %s has invalid exception descriptor."},
{NOEXCEPTIONDESCRIPTORERROR,"ELF File %s has no exception descriptor."},
{NEEDSECTIONVIEWERROR,"ELF File %s has no section headers."},
{DSONOTFOUNDERROR,"DSO %s not found."},
{UNDEFINEDSYMBOLERROR,"Undefined Symbol %s found in ELF File %s."},
{SYMBOLMISSINGFROMELFERROR,"Symbol %s Missing from ELF File : %s."},
{MEMORYALLOCATIONERROR,"Memory allocation failure : %s."},
{E32IMAGEERROR,"Not able to write E32 Image file."},
{INVALIDINVOCATIONERROR,"Invalid invocation of elf2e32."},
{TARGETTYPENOTSPECIFIEDERROR,"Target Type Not Specified."},
{UNSUPPORTEDTARGETTYPEERROR,"Unsupported Target Type '%s'."},
{INDEXNOMESSAGEERROR,"There is no message for the message index[%d]."},
{INDEXNOTREQUIREDERROR,"Message index[%d] not required in message file."},
{INDEXNOTFOUNDERROR,"Message index [%d] not found in message file"},
{NOMESSAGEFILEERROR,"There is no message file."},
{ENTRYPOINTNOTSETERROR,"Entry point is not set for %s."},
{UNDEFINEDENTRYPOINTERROR,"Entry point and Text segment base both 0, can't tell if entry point set for %s."},
{ORDINALNOTANUMBER,"Ordinal not a Number : %s[Line No=%d][%s]."},
{UNRECOGNIZEDTOKEN,"Unrecognized Token : %s[Line No=%d][%s]."},
{NONAMEMISSING,"NONAME Missing : %s[Line No=%d][%s]."},
{EXPORTSEXPECTED,"EXPORTS expected before first export entry : %s[Line No=%d][%s]."},
{ATRATEMISSING,"@ Missing : %s[Line No=%d][%s]."},
{SYSDEFSMISMATCHERROR,"Symbol %s passed through '--sysdef' option is not at the specified ordinal in the DEF file %s."},
{SYSDEFERROR,"Ordinal number is not provided as input to the option: %s"},
{INVALIDE32IMAGEERROR,"%s is not a valid E32Image file."},
{HUFFMANBUFFERUNDERFLOWERROR,"Huffman buffer underflow on deflate."},
{HUFFMANINCONSISTENTSIZEERROR,"Inconsistent sizes discovered during uncompression."},
{MULTIPLESYSDEFERROR, "Multiple system definitions passed to %s should be separated by ';'"},
{SYSDEFNOSYMBOLERROR, "Symbol Name is not provided as input to the option: %s"},
{VALUEIGNOREDWARNING, "Value passed to '%s' is ignored"},
{ELFFILEERROR,"Error while processing the ELF file %s."},
{SYMBOLCOUNTMISMATCHERROR, "Symbol count provided by DT_ARM_SYMTABSZ is not same as that in the Hash Table in %s"},
{POSTLINKERERROR,"Fatal Error in Postlinker"},
{BYTEPAIRINCONSISTENTSIZEERROR, "Inconsistent sizes discovered during Byte pair uncompression." },
{ILLEGALEXPORTFROMDATASEGMENT,"'%s' : '%s' Import relocation does not refer to code segment."},
{VALIDATIONERROR,"Image failed validation"}
};
/**
Constructor to reset the logging option flag.
@internalComponent
@released
*/
MessageImplementation::MessageImplementation()
{
iLogging = false;
}
/**
Destructor to close log file if logging is enabled and to clear the messaged.
@internalComponent
@released
*/
MessageImplementation::~MessageImplementation()
{
if(iLogging)
{
fclose(iLogPtr);
}
iMessage.clear();
}
/**
Function to Get Message stored in map.
@internalComponent
@released
@param aMessageIndex
Index of the Message to be displayed
@return Message string to be displayed
*/
char * MessageImplementation::GetMessageString(int aMessageIndex)
{
Map::iterator p;
if(iMessage.empty())
{
if(aMessageIndex <= MAX)
{
return MessageArray[aMessageIndex-1].message;
}
else
{
return NULL;
}
}
else
{
p=iMessage.find(aMessageIndex);
if(p == iMessage.end())
{
if(aMessageIndex <= MAX)
{
return MessageArray[aMessageIndex-1].message;
}
else
{
return NULL;
}
}
if(aMessageIndex <= MAX)
{
return p->second;
}
else
{
return NULL;
}
}
}
/**
Function to display output and log message in log file if logging is enable.
@internalComponent
@released
@param aString
Message to be displayed
*/
void MessageImplementation::Output(const char *aString)
{
if (iLogging)
{
fputs(aString,iLogPtr);
fputs("\n",iLogPtr);
}
cout << aString << endl;
}
/**
Function to Get Message stored in map and to display the Message
@internalComponent
@released
@param
The type of the message, whether it is Error or Warning or Information.
@param
The index of the information and the corresponding arguments.
*/
void MessageImplementation::ReportMessage(int aMessageType, int aMsgIndex,...)
{
char *reportMessage, *ptr, *tmpMessage;
char intStr[16];
char mssgNo[MAXMSSGNOLENGTH];
int mssgIndex,k;
va_list ap;
va_start(ap,aMsgIndex);
reportMessage=GetMessageString(aMsgIndex);
if(reportMessage)
{
String message;
switch (aMessageType)
{
case ERROR:
message = errorMssgPrefix;
break;
case WARNING:
message = warnMssgPrefix;
break;
case INFORMATION:
message = infoMssgPrefix;
break;
}
mssgIndex = BASEMSSGNO + aMsgIndex;
sprintf(mssgNo,"%d",mssgIndex);
message += mssgNo;
message += colSpace;
ptr = strchr(reportMessage,'%');
while( ptr != NULL && (ptr[0]) == '%' )
{
tmpMessage=new char[ptr - reportMessage + 1];
strncpy(tmpMessage, reportMessage, ptr - reportMessage+1);
tmpMessage[ptr - reportMessage]='\0';
message += tmpMessage;
delete tmpMessage;
ptr++;
switch(ptr[0])
{
case 'd':
k = va_arg(ap, int);
sprintf(intStr,"%d",k);
message += intStr;
ptr++;
reportMessage = ptr;
break;
case 's':
message += va_arg(ap, char *);
ptr++;
reportMessage = ptr;
break;
case '%':
message += ptr[0];
reportMessage = ptr;
default:
break;
}
ptr=strchr(reportMessage,'%');
}
message += reportMessage;
Output(message.c_str());
}
}
/**
Function to start logging.
@internalComponent
@released
@param aFileName
Name of the Log file
*/
void MessageImplementation::StartLogging(char *aFileName)
{
char logFile[1024];
FILE *fptr;
strcpy(logFile,aFileName);
// open file for log etc.
if((fptr=fopen(logFile,"w"))==NULL)
{
ReportMessage(WARNING, FILEOPENERROR,aFileName);
}
else
{
iLogging = true;
iLogPtr=fptr;
}
}
/**
Function to Create Messages file.
@internalComponent
@released
@param aFileName
Name of the Message file to be dumped
*/
void MessageImplementation::CreateMessageFile(char *aFileName)
{
int i;
FILE *fptr;
// open file for writing messages.
if((fptr=fopen(aFileName,"w"))==NULL)
{
ReportMessage(WARNING, FILEOPENERROR,aFileName);
}
else
{
for(i=0;i<MAX;i++)
{
fprintf(fptr,"%d,%s\n",i+1,MessageArray[i].message);
}
fclose(fptr);
}
}
/**
Function to put Message string in map which is stored in message file.
If file is not available the put message in map from Message Array structure.
@internalComponent
@released
@param aFileName
Name of the Message file passed in
*/
void MessageImplementation::InitializeMessages(char *aFileName)
{
char index[16];
char *message, *errStr;
int i, lineLength;
int fileSize;
char *messageEntries, *lineToken;
FILE *fptr;
if(aFileName && (fptr=fopen(aFileName,"rb"))!=NULL)
{
iMessage.clear();
//Getting File size
fseek(fptr, 0, SEEK_END);
fileSize=ftell(fptr);
rewind(fptr);
messageEntries= new char[fileSize+2];
//Getting whole file in memory
fread(messageEntries, fileSize, 1, fptr);
//Adding ENTER at end
*(messageEntries+fileSize)='\n';
//Adding '\0' at end
*(messageEntries+fileSize+1)='\0';
fclose(fptr);
lineToken=strtok(messageEntries,"\n");
while(lineToken != NULL)
{
if( lineToken[0] == '\n' || lineToken[0] == '\r' )
{
lineToken=strtok(NULL,"\n");
continue;
}
lineLength=strlen(lineToken);
if( lineToken[strlen(lineToken)-1] == '\r' )
{
lineToken[strlen(lineToken)-1]='\0';
}
message=strchr(lineToken,',');
strncpy(index,lineToken,message-lineToken);
index[message-lineToken]='\0';
errStr = new char[strlen(message+1) + 1];
strcpy(errStr, (message+1));
iMessage.insert(std::pair<int,char*>(atoi(index),errStr));
lineToken=strtok(lineToken+lineLength+1,"\n");
}
delete messageEntries;
}
else
{
for(i=0;i<MAX;i++)
{
errStr = new char[strlen(MessageArray[i].message) + 1];
strcpy(errStr, MessageArray[i].message);
iMessage.insert(std::pair<int,char*>(MessageArray[i].index,errStr));
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
425
]
]
]
|
b6ae1fc1f3b99f925e8ae6219150767d77ec0e3f | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /projects/MainUI/MainUIDlg.h | 3b8f8f0c167ca5957c7b9aea80200424a66c2684 | []
| no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,054 | h | // MainUIDlg.h : 头文件
//
#pragma once
#include ".\basedlg.h"
#include ".\dlgwebsites.h"
#include ".\dlgcheckpassword.h"
#include ".\newMenu\NewMenu.h"
#include ".\DlgSwitchChildren.h"
#include ".\TrayIconPosition.h"
#include ".\dlgregister.h"
#include ".\RightRegionDlg.h"
#include ".\guilib1.5\guisystray.h"
#include "afxwin.h"
#include "afxcmn.h"
#include <UILib\PPTooltip\PPTooltip.h>
// CMainUIDlg 对话框
class CMainUIDlg : public CDialog
{
// 构造
public:
CMainUIDlg(CWnd* pParent = NULL); // 标准构造函数
~CMainUIDlg();
// 对话框数据
enum { IDD = IDD_MAINUI_DIALOG };
// 实现
protected:
HICON m_hIcon;
void setControlsFonts();
void setRulesTreeItems();
void setToolsTreeItems();
private:
CTreeCtrl m_treeNavigation; // 左侧的导航术
CImageList m_imageList; // 导航树上的图标
void InitTreeNodes(); // 初始化树的节点
// 树的数据分为两部分,高字节保存IDI, 低字节保存IDS
void setItemData(HTREEITEM hItem, WORD ids, WORD idi);
WORD getItemIcon();
WORD getItemIDS();
CRightRegionDlg m_dlgRight;
// 设置System Tray Menu;
void setupTrayMenu();
// 右侧树的位置
CRect m_rectRight;
// fonts
CFont m_fontTree;
CGuiSysTray m_sysTray;
CNewMenu m_trayMenu;
CStatic m_staFunFrame;
CGuiButton m_btnOkBAK; // if remove it, some error happens.
CImageList image_list_;
//
BOOL m_bShown; // 当前界面是否显示
protected:
afx_msg void OnNMClickTreeNavig(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnTvnSelchangedTreeNavig(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg LRESULT OnHotKey(WPARAM wParam, LPARAM lParam);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
// 按钮项
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedMainCancel();
afx_msg void OnBnClickedApply();
// 菜单处理项
afx_msg void OnMainExit();
afx_msg void OnTraymenuMainui();
afx_msg void OnMainChangepassword();
afx_msg void OnMainParents();
afx_msg void OnMainChildren();
afx_msg void OnToolsDesktopimage();
afx_msg void OnMainLockcomputer();
afx_msg void OnDestroy();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu);
afx_msg void OnWebhistoryImages();
afx_msg void OnWebhistorySearchkeyword();
afx_msg void OnWebhistoryWebsites();
afx_msg void OnMainRegister();
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
afx_msg BOOL OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg LRESULT OnShowServerMsg(WPARAM, LPARAM);
virtual HRESULT get_accHelp(VARIANT varChild, BSTR *pszHelp);
virtual BOOL OnInitDialog();
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual void OnOK();
virtual void OnCancel();
virtual BOOL PreTranslateMessage(MSG* pMsg);
DECLARE_MESSAGE_MAP()
protected:
// 根据当前状态初始化TrayMenu
// 此函数会在每次应用程序启动及状态切换时调用
void UpdateUIStateByModel();
// 根据当前模式,调整图标
void AdjustModelIcon();
private:
// 隐藏或是显示主界面
void ShowMainUI();
void HideMainUI(BOOL autoSwitchCheck = TRUE);
bool ShowOverTimeMsgBox();
BOOL isShown() const { return m_bShown;}
// 对话框
CDlgCheckPassword m_dlgCheckPassword_;
CDlgChangePassword m_dlgChangePassword_;
CDlgImageBrowser m_dlgImageBrowser_;
CDlgSearchWordList m_dlgSearchKeyword_;
CDlgWebsites m_dlgWebsites_;
CDlgSwitchChildren m_dlgSwitchChildren_;
CDlgRegister m_dlgRegister_;
private:
void OnRequestShowMainUI(); // 当用户要求执行显示对话框时,调用
void SwitchOnClose();
void ShowRegTipDlg();
// Tooltip相关
CTrayIconPosition m_tray_pos;
CPPToolTip m_traytip;
DWORD dwAppearLastTime_;
public:
afx_msg void OnTraymenuBuyonline();
afx_msg void OnTraymenuHomepage();
};
| [
"ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b",
"[email protected]"
]
| [
[
[
1,
5
],
[
19,
24
],
[
26,
32
],
[
35,
35
],
[
39,
39
],
[
45,
45
],
[
48,
51
],
[
53,
56
],
[
58,
58
],
[
60,
60
],
[
63,
63
],
[
65,
65
],
[
67,
70
],
[
84,
84
],
[
142,
142
]
],
[
[
6,
18
],
[
25,
25
],
[
33,
34
],
[
36,
38
],
[
40,
44
],
[
46,
47
],
[
52,
52
],
[
57,
57
],
[
59,
59
],
[
61,
62
],
[
64,
64
],
[
66,
66
],
[
71,
83
],
[
85,
141
]
]
]
|
7d63b6ab104bf5536b4783af6657fc3164499f4f | 55196303f36aa20da255031a8f115b6af83e7d11 | /include/bikini/system/thread.hpp | 6cb7953994ed21e435422877d6572ceeb3ab50ba | []
| no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,150 | hpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008-2010 Viktor Reutskyy
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#pragma once
namespace thread { /*----------------------------------------------------------------------------*/
/// _task_result_ - used internally by task_
template<typename _T> struct _task_result_ {
inline _task_result_() {}
inline _task_result_(const _T &_r) : r(_r) {}
inline _task_result_& operator = (const _T &_r) { r = _r; return *this; }
inline _T get() const { return r; }
private:
_T r;
};
/// set thread name
inline void set_thread_name(uint _ID, const achar* _name);
/// Thread task class template. Serves to start and manage separate thread.
/** Encloses a function, member function or functor with up to ten arguments.
Allows to check if enclosed function finished execution and to get execution result.
*/
template<typename _R, typename _A0 = notype, typename _A1 = notype, typename _A2 = notype, typename _A3 = notype, typename _A4 = notype, typename _A5 = notype, typename _A6 = notype, typename _A7 = notype, typename _A8 = notype, typename _A9 = notype>
struct task_ : noncopyable {
/// construct a task from a function or a functor
template<typename _F> inline task_(_F &_f, const achar* _name = 0, sint _priority = THREAD_PRIORITY_NORMAL, uint _stacksize = 0, uint _processor = bad_ID);
/// construct a task ftom a member function
template<typename _O, typename _M> inline task_(_O &_o, const _M &_m, const achar* _name = 0, sint _priority = THREAD_PRIORITY_NORMAL, uint _stacksize = 0, uint _processor = bad_ID);
/// destructor
inline ~task_();
/// start execution
inline bool run(_A0 _a0 = _A0(), _A1 _a1 = _A1(), _A2 _a2 = _A2(), _A3 _a3 = _A3(), _A4 _a4 = _A4(), _A5 _a5 = _A5(), _A6 _a6 = _A6(), _A7 _a7 = _A7(), _A8 _a8 = _A8(), _A9 _a9 = _A9());
/// check if execution is started
inline bool started() const;
/// check if execution is finished
inline bool done() const;
/// wait while execution will be finished and return the result
inline _R wait() const;
/// terminate execution (don't use this)
inline void terminate();
/// clear a task after execution is finished
inline void clear();
private:
astring m_name;
typedef functor_<_R, _A0, _A1, _A2, _A3, _A4, _A5, _A6, _A7, _A8, _A9> functor;
functor m_functor;
handle m_handle; uint m_ID;
sint m_priority;
uint m_stacksize;
uint m_processor;
_task_result_<_R> m_result;
};
typedef task_<void> task;
/// Event synchronization object wrapper.
/** Allows to create event, to set event signaled and nonsignaled state,
and to wait for event signaled state is set.
Unfortunately "event" is a reserved keyword in C++.
So I'll call my event a flag.
*/
struct flag : noncopyable {
/// constructor
inline flag(bool _manual = false, bool _state = false, const astring &_name = "");
/// destructor
inline ~flag();
/// set event signaled state
inline void set();
/// set event nonsignaled state
inline void reset();
/// a calling thead will wait for event signaled state is set
inline bool wait(real _timeout = infinity);
private:
handle m_handle;
};
/// Mutex synchronization object wrapper.
/**
*/
struct mutex {
inline mutex(bool _owned = false, const astring &_name = "");
inline ~mutex();
inline bool take(real _timeout = infinity);
inline void drop();
private:
handle m_handle;
};
///
/**
*/
struct section {
inline section();
inline ~section();
inline void enter();
inline bool try_enter();
inline void leave();
private:
CRITICAL_SECTION m_criticalsection;
};
///
struct locker {
inline locker(section &_section, bool _try_lock = false);
inline ~locker();
inline operator bool ();
private:
section &m_section;
bool m_locked;
};
#include "thread.inl"
} /* namespace thread ---------------------------------------------------------------------------*/
| [
"[email protected]",
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
]
| [
[
[
1,
3
],
[
6,
30
],
[
32,
39
],
[
42,
67
],
[
69,
69
],
[
71,
120
]
],
[
[
4,
5
],
[
31,
31
],
[
40,
41
],
[
68,
68
],
[
70,
70
]
]
]
|
fd4281295ad0934199ba3bf443479bd818653757 | 9c2a6fd19d8d1fede218b99749fc48d5123b248a | /3rdParty/Htmlayout/api/htmlayout_dialog.hpp | f723f590d402bb60f24923609d1780eca04e1178 | []
| no_license | ans-ashkan/expemerent | 0f6bed7e630301f63e71992e3fbad70a0075082a | 054c33f55408d1274c50a2d6eb4cbc5295c92739 | refs/heads/master | 2021-01-15T22:15:18.929759 | 2008-12-21T00:40:52 | 2008-12-21T00:40:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,377 | hpp | /*
* Terra Informatica Lightweight Embeddable HTMLayout control
* http://terrainformatica.com/htmlayout
*
* HTML dialog.
*
* The code and information provided "as-is" without
* warranty of any kind, either expressed or implied.
*
* (C) 2003-2004, Andrew Fedoniouk ([email protected])
*/
/**\file
* \brief Implementation of HTML based dialog
**/
#ifndef __htmlayout_dialog_hpp__
#define __htmlayout_dialog_hpp__
#include "htmlayout_dom.hpp"
#include "htmlayout_behavior.hpp"
#include "htmlayout_controls.hpp"
#include "htmlayout_notifications.hpp"
#include <assert.h>
#include <shellapi.h> // ShellExecute
#include <string>
#pragma warning(disable:4786) //identifier was truncated...
#pragma warning(disable:4996) //'strcpy' was declared deprecated
#pragma warning(disable:4100) //unreferenced formal parameter
#pragma once
/**HTMLayout namespace.*/
namespace htmlayout
{
class dialog: public event_handler,
public notification_handler<dialog>
{
public:
HWND parent;
POINT position;
INT alignment;
UINT style;
UINT style_ex;
named_values* pvalues;
dialog(HWND hWndParent, UINT styles = 0): pvalues(0),
event_handler( HANDLE_BEHAVIOR_EVENT | HANDLE_INITIALIZATION)
{
parent = hWndParent;
position.x = 0;
position.y = 0;
alignment = 0; // center of desktop
style = WS_DLGFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU | styles;
style_ex = WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE;
}
// SHOW function family - show modal dalog and return one of
// IDOK, IDCANCEL, etc. codes.
// Dialog buttons shall be defined as <button name="OK">, <button name="CANCEL">, etc.
// show HTML dialog from url
unsigned int show( LPCWSTR url );
// show HTML dialog from resource given by resource id
unsigned int show( UINT html_res_id );
// show HTML dialog from html in memory buffer
unsigned int show( LPCBYTE html, UINT html_length );
// INPUT function family - show modal dalog and return one of button codes,
// values collection is used for initializing and returning values of inputs.
// show HTML input dialog from url
unsigned int input( LPCWSTR url, named_values& values )
{
pvalues = &values;
return show(url);
}
// show HTML input dialog from resource given by resource id
unsigned int input( UINT html_res_id, named_values& values )
{
pvalues = &values;
return show(html_res_id);
}
// show HTML input dialog from html in memory buffer
unsigned int input( LPCBYTE html, UINT html_length, named_values& values )
{
pvalues = &values;
return show(html, html_length);
}
protected:
virtual void attached( HELEMENT he );
virtual BOOL handle_event ( HELEMENT he, BEHAVIOR_EVENT_PARAMS& params );
virtual BOOL handle_key ( HELEMENT he, KEY_PARAMS& params );
};
// implementations
// show HTML dialog from url
inline unsigned int dialog::show( LPCWSTR url )
{
return show( (LPCBYTE) url, 0);
}
// show HTML dialog from resource given by resource id
inline unsigned int dialog::show( UINT html_res_id )
{
PBYTE html;
DWORD html_length;
if(!load_html_resource(html_res_id, html, html_length ))
{
assert(false); // resource not found!
return 0;
}
return show(html, html_length);
}
// show HTML dialog from html in memory buffer
inline unsigned int dialog::show( LPCBYTE html, UINT html_length )
{
return (unsigned int)::HTMLayoutDialog(
parent,
position,
alignment,
style, style_ex,
¬ification_handler<dialog>::callback,
&event_handler::element_proc,
this, html, html_length );
}
inline void dialog::attached( HELEMENT he )
{
if(pvalues)
{
dom::element root = he;
set_values(root,*pvalues);
}
}
// handle button events.
// here it does special treatment of "dialog buttons"
inline BOOL dialog::handle_event (HELEMENT he, BEHAVIOR_EVENT_PARAMS& params )
{
dom::element src = params.heTarget;
if( params.cmd == BUTTON_CLICK )
{
const wchar_t* bname = src.get_attribute("name");
bool positive_answer = false;
UINT id = 0;
if( aux::wcseqi(bname,L"OK") ) { id =IDOK ; positive_answer = true; }
else if( aux::wcseqi(bname,L"CANCEL") ) id =IDCANCEL;
else if( aux::wcseqi(bname,L"ABORT ") ) id =IDABORT ;
else if( aux::wcseqi(bname,L"RETRY ") ) { id =IDRETRY ; positive_answer = true; }
else if( aux::wcseqi(bname,L"IGNORE") ) id =IDIGNORE;
else if( aux::wcseqi(bname,L"YES") ) { id =IDYES ; positive_answer = true; }
else if( aux::wcseqi(bname,L"NO") ) id =IDNO ;
else if( aux::wcseqi(bname,L"CLOSE") ) id =IDCLOSE ;
else if( aux::wcseqi(bname,L"HELP") ) id =IDHELP ; // ?
else
return FALSE;
HWND hwndLayout = src.get_element_hwnd(true);
if( !::IsWindow(hwndLayout) )
return FALSE;
HWND hwndDlg = GetParent(hwndLayout);
if(positive_answer && pvalues)
{
dom::element root = src.root();
pvalues->clear();
get_values(root,*pvalues);
}
EndDialog(hwndDlg, id);
return TRUE;
}
#if !defined( _WIN32_WCE )
else if (params.cmd == HYPERLINK_CLICK )
{
HWND hwndLayout = src.get_element_hwnd(true);
const wchar_t* url = src.get_attribute("href");
if( url )
{
#if !defined(UNICODE)
::ShellExecuteA(hwndLayout,"open", aux::w2a(url), NULL,NULL,SW_SHOWNORMAL);
#else
::ShellExecuteW(hwndLayout,L"open", url, NULL,NULL,SW_SHOWNORMAL);
#endif
}
}
#endif
return FALSE;
}
inline BOOL dialog::handle_key (HELEMENT he, KEY_PARAMS& params )
{
if(params.cmd != KEY_DOWN)
return FALSE;
dom::element root = he;
switch(params.key_code)
{
case VK_RETURN:
{
dom::element def = root.find_first("[role='default-button']");
if( def.is_valid() )
{
METHOD_PARAMS params; params.methodID = DO_CLICK;
return def.call_behavior_method(¶ms)? TRUE:FALSE;
}
} break;
case VK_ESCAPE:
{
dom::element def = root.find_first("[role='cancel-button']");
if( def.is_valid() )
{
METHOD_PARAMS params; params.methodID = DO_CLICK;
return def.call_behavior_method(¶ms)? TRUE:FALSE;
}
} break;
}
return FALSE;
}
}
#endif | [
"userstvo@9d5f44c3-c14b-0410-8269-bdf5c58671da"
]
| [
[
[
1,
249
]
]
]
|
c1bd1a8582aa3deeb565df17abe1ff9d73c74de0 | 7f783db3cfa388eb2c974635a89caa20312fcca3 | /samples/RSDNIntro/autosvr/Math.cpp | b6f4311a97b16c37ff9d960c8cb50508aaa77148 | []
| no_license | altmind/com_xmlparse | 4ca094ae1af005fa042bf0bef481d994ded0e86b | da2a09c631d581065a643cbb04fbdeb00e14b43e | refs/heads/master | 2021-01-23T08:56:46.017420 | 2010-11-24T14:46:38 | 2010-11-24T14:46:38 | 1,091,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | cpp | //
// Math.cpp : Implementation of CMath
//
#include "stdafx.h"
#include "AutoSvr.h"
#include "Math.h"
//////////////////
// CMath
//////////////////
STDMETHODIMP CMath::Add( long op1, long op2, long* pResult )
{
*pResult = op1 + op2;
return S_OK;
}
STDMETHODIMP CMath::Subtract( long op1, long op2, long* pResult )
{
*pResult = op1 - op2;
return S_OK;
}
STDMETHODIMP CMath::Multiply( long op1, long op2, long* pResult )
{
*pResult = op1 * op2;
return S_OK;
}
STDMETHODIMP CMath::Divide( long op1, long op2, long* pResult )
{
*pResult = op1 / op2;
return S_OK;
}
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
cff15f57fe4dd6323e176014a027917b8d0d2cca | 8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076 | /code/Math/fxPlane.h | abe03b411018fc3e66a31c184ff35a80b2dea4c0 | []
| no_license | BackupTheBerlios/insane | fb4c5c6a933164630352295692bcb3e5163fc4bc | 7dc07a4eb873d39917da61e0a21e6c4c843b2105 | refs/heads/master | 2016-09-05T11:28:43.517158 | 2001-01-31T20:46:38 | 2001-01-31T20:46:38 | 40,043,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,148 | h | //---------------------------------------------------------------------------
#ifndef fxPlaneH
#define fxPlaneH
//---------------------------------------------------------------------------
// fxPlane - this class represents a plane in R3
// equation: X*Normal = -Distance (HESSEsche Normalform)
#include "../insanefx.h"
#include "fxVector.h"
struct INSANEFX_API fxPlaneData
{
fxVector Normal;
float Distance;
};
class INSANEFX_API fxPlane
{
protected:
fxPlaneData data;
public:
fxPlane();
fxPlane(fxVector normal, float distance);
fxPlane(fxPlaneData Data);
fxPlane(fxVector * v1,fxVector * v2,fxVector * v3);
fxPlane * Clone(void);
void Copy(fxPlane * plane);
// constructs a plane from 3 points that lie on the plane
void FromPoints(fxVector * v1, fxVector * v2, fxVector * v3);
// returns the distance from the plane
float Distance(fxVector * v);
// returns 1 if the point lies in front of the plane
// -1 if the point lies behind the plane
// 0 if the point lies on the plane
int ClassifyPoint(fxVector * vector);
};
#endif
| [
"josef"
]
| [
[
[
1,
48
]
]
]
|
f61ddded1fdfa4ecc40e7b519b154959863f4810 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/messages/player_messages/chat_msg_item.cpp | c22f9f58cf72c0ee3949350a39fd0166efdb5bad | []
| no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 4,644 | cpp | #include "config.hpp"
#include "chat_msg_item.hpp"
#include "tags.hpp"
namespace {
enum {chat_line_max = 115};
enum {chat_line_min = 90};
enum {chat_line_preffex_max = 64};
std::string get_preffix(tags& tag, size_t pos) {
std::string preffix = tag.get_closed_tag_val<std::string>("preffix", pos, "");
if (preffix.length() > chat_line_preffex_max) {
// Обрезаем слишком длинный префикс
preffix = preffix.substr(0, chat_line_preffex_max);
}
return preffix;
}
void add_chat_item(chat_msg_items_t& items, unsigned int msg_color, std::string const& msg_text, size_t tag_pos, tags& tag) {
if ("none" != tag.get_closed_tag_val<std::string>("nonewline", tag_pos, "none")) {
// Не разбиваем на несколько строчек
std::string preffix = get_preffix(tag, tag_pos);
items.push_back(chat_msg_item_t(msg_color, preffix + msg_text));
}
else {
std::size_t msg_len = msg_text.length();
std::size_t pos_start = 0;
// Разбиваем на несколько строк
for (;;) {
std::string preffix = get_preffix(tag, tag_pos + pos_start);
if (msg_len + preffix.length() - pos_start < chat_line_max) {
// Оставшияся строка влезает на 1 строчку
if (msg_text.length() > pos_start) {
// Не добавляем пустых строк
items.push_back(chat_msg_item_t(msg_color, preffix + msg_text.substr(pos_start)));
}
break;
}
else {
// Строку необходимо разбивать
std::size_t space_pos = msg_text.rfind(' ', chat_line_max - preffix.length() + pos_start);
if (std::string::npos == space_pos || space_pos < chat_line_min - preffix.length() + pos_start) {
// Режем строчку жестко
items.push_back(chat_msg_item_t(msg_color, preffix + msg_text.substr(pos_start, chat_line_max - preffix.length())));
pos_start += chat_line_max - preffix.length();
}
else {
// Режем по пробелу
items.push_back(chat_msg_item_t(msg_color, preffix + msg_text.substr(pos_start, space_pos - pos_start)));
pos_start += space_pos - pos_start + 1;
}
}
}
}
}
}
chat_msg_item_t::chat_msg_item_t(unsigned int color, std::string const& msg): color(color), msg(msg), is_clear(false) {
}
chat_msg_item_t::chat_msg_item_t(): color(0xffffff), is_clear(true) {
}
chat_msg_item_t::~chat_msg_item_t() {
}
chat_msg_items_t create_chat_items(std::string const& msg) {
chat_msg_items_t rezult;
tags message(msg);
if ("none" != message.get_closed_tag_val<std::string>("clear", 0, "none")) {
rezult.push_back(chat_msg_item_t());
}
std::string msg_str = message.get_untaget_str();
size_t pos_start = 0;
size_t pos_curr;
for (;;) {
pos_curr = msg_str.find("\\n", pos_start);
unsigned int msg_color = message.get_closed_tag_val<unsigned int>("color", pos_start, 0xFFFFFF);
if (std::string::npos == pos_curr) {
add_chat_item(rezult, msg_color, msg_str.substr(pos_start), pos_start, message);
break;
}
else {
add_chat_item(rezult, msg_color, msg_str.substr(pos_start, pos_curr - pos_start), pos_start, message);
pos_start = pos_curr + 2;
}
}
return rezult;
}
chat_bubble_t::chat_bubble_t()
:color(0xFFFFFFFF)
,draw_distance(0.0f)
,expire_time(1000)
{
}
chat_bubble_t::chat_bubble_t(int expire_time)
:color(0xFFFFFFFF)
,draw_distance(0.0f)
,expire_time(expire_time)
{
}
chat_bubble_t create_chat_bubble(std::string const& text) {
chat_bubble_t rezult;
tags tags_text(text);
rezult.color = tags_text.get_closed_tag_val<unsigned int>("color", 0, 0xFFFFFF);
rezult.draw_distance = tags_text.get_closed_tag_val<float>("distance", 0, 0.0f);
rezult.expire_time = tags_text.get_closed_tag_val<unsigned int>("time", 0, 0);
rezult.text = tags_text.get_untaget_str();
return rezult;
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
]
| [
[
[
1,
118
]
]
]
|
4c3119fa9b28086fc723d75bd274c8192379491c | 3387244856041685a94b72264d41a80ae35c3f80 | /source/TowerBarrier.cpp | e295329eee503f73906ba9ece973118544a5ffb3 | []
| no_license | kinfung0602/ogre-tower-defense | 768c9ae0c0972379cfbddf91361cf343b8c76dfb | ce950d36b49ea46e294d936f3cd363bcc73c8468 | refs/heads/master | 2021-01-10T08:22:05.424893 | 2011-07-11T01:32:05 | 2011-07-11T01:32:05 | 53,152,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | cpp | #include "TowerBarrier.h"
TowerBarrier::TowerBarrier(TowerBase* parent)
: Tower(parent, "Barrier", DEFENSIVE)
{
}
TowerBarrier::~TowerBarrier(void)
{
}
void TowerBarrier::upgrade(void)
{
}
void TowerBarrier::sell(void)
{
}
bool TowerBarrier::createGraphics(void)
{
bool retval = false;
if (mpsSceneMgr)
{
mMaterialName = "Material/Tower/Barrier";
// Create simple graphics
retval = createSimpleGraphics(mStrUid);
}
return retval;
}
void TowerBarrier::update(float t)
{
} | [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
ab1408b6439e67945d5259a4e131f3938ac32ec7 | 1efa9ffc73895ab3da9c03d2cb730a5d7b0d897c | /source/MapEdit/Src/scrollable_game.h | dda7c166755193761bf8721a509d502a152e2542 | []
| no_license | sydlawrence/CorsixTH-HTML5-Port | fc9356c8bfd0f00955877ec0da1a486e6892ba4c | 95d272e0ad27758fed7d231d8ab7f79aa4b0773f | refs/heads/master | 2021-01-23T00:07:18.124534 | 2011-09-25T20:06:11 | 2011-09-25T20:06:11 | 2,455,933 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | h | /*
Copyright (c) 2010 Peter "Corsix" Cawley
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.
*/
#pragma once
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers)
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// ----------------------------
#include "embedded_game.h"
class ScrollableGamePanel : public wxPanel, public IEmbeddedGamePanel
{
public:
ScrollableGamePanel(wxWindow *pParent);
~ScrollableGamePanel();
void setExtraLuaInitFunction(lua_CFunction fn, void* arg);
void setLogWindow(frmLog *pLogWindow);
bool loadLua();
lua_State* getLua();
THMap* getMap();
enum
{
ID_X_SCROLL = wxID_HIGHEST + 1,
ID_Y_SCROLL
};
protected:
EmbeddedGamePanel* m_pGamePanel;
wxScrollBar* m_pMapScrollX;
wxScrollBar* m_pMapScrollY;
lua_CFunction m_fnExtraInit;
void* m_pExtraInitArg;
bool m_bShouldRespondToScroll;
void _onResize(wxSizeEvent& e);
void _onScroll(wxScrollEvent& e);
static int _l_extra_init(lua_State *L);
static int _l_init_with_app(lua_State *L);
static int _l_on_ui_scroll_map(lua_State *L);
DECLARE_EVENT_TABLE();
};
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
888c4b2abf3067316e67262cf6ef7f4fc86b2ec0 | eb039fcb8dccfef9cec68dd97bdc3fa63d420845 | /kifaru.old/effect.cpp | 04349aa135f923262bc7251f70b868e7420afe2b | []
| no_license | BackupTheBerlios/kifaru | 8fead5b2de6a838aee9cfb0c3c869caaffc35038 | b694dffbd4e85c07689d35af5198f1ed1c415f5f | refs/heads/master | 2020-12-02T16:00:17.331679 | 2006-06-28T18:22:20 | 2006-06-28T18:22:20 | 40,044,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,221 | cpp | #include <iostream>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_Image.h>
#include "primitives.h"
#include "inits.h"
#include "effect.h"
#define MAX_TEXTURE_SIZE_X 256
#define MAX_TEXTURE_SIZE_Y 256
using namespace std;
namespace ephidrena
{
SDL_Surface *morn;
Image::Image()
{
xofs=0;
yofs=0;
}
Image::~Image()
{
}
void Image::Render (SDL_Surface *screen)
{
SDL_Rect dest;
dest.x = this->xofs;
dest.y = this->yofs;
SDL_BlitSurface(this->pic, NULL, screen, &dest);
return;
}
SDL_Surface* Image::Scale (SDL_Surface *texture, Uint32 destSizeX, Uint32 destSizeY)
{
SDL_Surface *scaled_texture;
Uint32 ytable[MAX_TEXTURE_SIZE_Y];
Uint32 ofs;
float srcX=0,srcY=0;
float xstep,ystep,step;
Uint32 dstX=0,dstY=0;
if (destSizeX == 0 || destSizeY == 0) return NULL;
PreScale(texture, ytable);
xstep = float(MAX_TEXTURE_SIZE_X / destSizeX);
ystep = float(MAX_TEXTURE_SIZE_Y / destSizeY);
for (dstY=0; dstY < destSizeY; dstY++)
{
for (dstX = 0; dstX < destSizeX; dstX++;)
{
ofs = Uint32(srcX) + ytable[Uint32(srcY)];
srcX += xstep;
texture[ofs+
}
srcY += ystep;
}
return scaled_texture;
}
void Image::PreScale (SDL_Surface* texture, Uint32* ytable)
{
Uint32 i=0;
while ( i < MAX_TEXTURE_SIZE_Y )
{
ytable[i] = (i * texture->pitch);
i++;
}
}
void Image::LoadBMP()
{
this->pic=SDL_LoadBMP(fileName);
cout << "image loaded" << endl;
}
void Image::LoadPNG()
{
SDL_RWops *rwop;
rwop = SDL_RWFromFile(fileName, "rb");
this->pic=IMG_LoadPNG_RW(rwop);
if(!this->pic) cout << "LoadPNG tryna!" << endl;
}
Effect::Effect()
{
return;
}
Effect::~Effect()
{
return;
}
void Effect::Render(SDL_Surface *screen)
{
}
void Effect::LoadPNG()
{
}
void Effect::LoadBMP()
{
}
void Effect::SLock(SDL_Surface *screen)
{
if ( SDL_MUSTLOCK(screen) )
{
if (SDL_LockSurface(screen) < 0) return;
}
}
void Effect::SULock(SDL_Surface *screen)
{
if ( SDL_MUSTLOCK(screen) ) SDL_UnlockSurface(screen);
}
Jall::Jall()
{
}
Jall::~Jall()
{
}
void Jall::Render(SDL_Surface *screen)
{
static float XSin=0,YSin=0;
static Uint8 vri=11;
static float vreng=53;
static Uint8 xs,ys;
static Uint8 t;
Uint32 x,y;
SLock(screen);
for( y=0; y<screen->h; y++ )
{
for ( x=0; x<screen->w; x++ )
{
t = vri+x+(y*ys);
PutPixel(screen,x, y, t/3,t/2,t/2);
}
YSin += 0.7;
if (YSin > 1) YSin = -1;
ys = Uint8(sin (YSin) );
//if (vri >= 255) vri=1;
vri++;
vreng+=0.7;
//if (vreng >=256 ) vri=1;
XSin+=0.13;
YSin+=0.15;
}
SULock(screen);
}
};
| [
"nerve-"
]
| [
[
[
1,
190
]
]
]
|
8532499a0d855839e320b8c8b8f49d258f3b1120 | 353bd39ba7ae46ed521936753176ed17ea8546b5 | /src/layer4_editor/engine/src/axen_engine.h | a832a5c9217fb9bf80a7d8ade4751516be228b1a | []
| no_license | d0n3val/axe-engine | 1a13e8eee0da667ac40ac4d92b6a084ab8a910e8 | 320b08df3a1a5254b776c81775b28fa7004861dc | refs/heads/master | 2021-01-01T19:46:39.641648 | 2007-12-10T18:26:22 | 2007-12-10T18:26:22 | 32,251,179 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | h | /**
* @file
* Engine singleton
* @author Ricard Pillosu <d0n3val\@gmail.com>
* @date 11 Sep 2004
*/
#ifndef __AXEN_ENGINE_H__
#define __AXEN_ENGINE_H__
#include "axen_stdafx.h"
#include "opengl.h"
#include "modelheaders.h"
#include "opengl.h"
/*$1- Back declarations ------------------------------------------------------*/
class axen_window;
class axen_control;
class axe_string;
class opengl;
struct ModelVertex;
struct ModelHeader;
extern opengl* mopengl;
/**
* Engine singleton
*/
class axen_engine
{
/*$1- Singleton stuff ------------------------------------------------------*/
public:
static axen_engine* create();
~axen_engine();
private:
static bool active;
static axen_engine* instance;
axen_engine();
/*$1- Methods --------------------------------------------------------------*/
public:
inline axen_window* get_window()
{
AXE_ASSERT( window != NULL );
return( window );
}
inline const axen_window* get_window() const
{
AXE_ASSERT( window != NULL );
return( window );
}
inline axen_control* get_input()
{
AXE_ASSERT( input != NULL );
return( input );
}
inline const axen_control* get_input() const
{
AXE_ASSERT( input != NULL );
return( input );
}
bool init();
bool start_window();
bool loop_window();
bool end_window();
void exit();
void check_keys();
void load_model();
void draw_model();
/*$1- Log ----------------------------------------------------------------*/
void log( const axe_string& str );
/*$1- Function to call on start and end ----------------------------------*/
axe_string function_on_start;
axe_string function_on_end;
/*$1- Properties -----------------------------------------------------------*/
private:
axen_window* window;
axen_control* input;
AXE_ID timer_id;
axe_euler_angles cam;
axe_matrix_4x4 virtual_camera;
ModelHeader header;
ModelVertex* origVertices;
size_t nIndices;
uint16* indices;
ModelRenderPass pass;
axe_vector3* vertices;
axe_vector2* text_coords;
unsigned int* textures;
AXE_ID tex_id;
AXE_ID id_file;
};
#endif // __AXEN_ENGINE_H__
/* $Id: axen_engine.h,v 1.1 2004/09/20 21:28:14 doneval Exp $ */
| [
"d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54"
]
| [
[
[
1,
103
]
]
]
|
32b7983f8e959abf2c5488764cad67f28ebefeab | 38664d844d9fad34e88160f6ebf86c043db9f1c5 | /branches/initialize/skin/examples/mfc/mfc42_sb/mfc42_sb.cpp | 980a82f49b1d30601b7f0fea8fa30a941f5bbccc | []
| no_license | cnsuhao/jezzitest | 84074b938b3e06ae820842dac62dae116d5fdaba | 9b5f6cf40750511350e5456349ead8346cabb56e | refs/heads/master | 2021-05-28T23:08:59.663581 | 2010-11-25T13:44:57 | 2010-11-25T13:44:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,245 | cpp | // mfc42_sb.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "mfc42_sb.h"
#include "MainFrm.h"
#include "mfc42_sbDoc.h"
#include "mfc42_sbView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMfc42_sbApp
BEGIN_MESSAGE_MAP(CMfc42_sbApp, CWinApp)
//{{AFX_MSG_MAP(CMfc42_sbApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMfc42_sbApp construction
CMfc42_sbApp::CMfc42_sbApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CMfc42_sbApp object
CMfc42_sbApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CMfc42_sbApp initialization
BOOL CMfc42_sbApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views.
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CMfc42_sbDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CMfc42_sbView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it.
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// 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)
// No message handlers
//}}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()
// App command to run the dialog
void CMfc42_sbApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
/////////////////////////////////////////////////////////////////////////////
// CMfc42_sbApp message handlers
| [
"ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd"
]
| [
[
[
1,
154
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.