blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
602f5af47b9c879acd4c9a2d2957e45c1dbee019 | 0f457762985248f4f6f06e29429955b3fd2c969a | /physics/trunk/sdk/ggfsdk/tokenizer.cpp | 5ea95c8e0f002739e5843f58ba909da24b78dd8c | [] | no_license | tk8812/ukgtut | f19e14449c7e75a0aca89d194caedb9a6769bb2e | 3146ac405794777e779c2bbb0b735b0acd9a3f1e | refs/heads/master | 2021-01-01T16:55:07.417628 | 2010-11-15T16:02:53 | 2010-11-15T16:02:53 | 37,515,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,499 | cpp | /************************************************************************
The zlib/libpng License
Copyright (c) 2006 Joerg Wiedenmann
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.
***********************************************************************/
/********************************************************************
created: 2006-01-28
filename: tokenizer.cpp
author: J?g Wiedenmann
purpose: A tokenizer function which provides a very
customizable way of breaking up strings.
history: 2006-01-28, Original version
2006-03-04, Fixed a small parsing bug, thanks Elias.
*********************************************************************/
//#include "stdafx.h"
#include "tokenizer.h"
using namespace std;
void tokenize(
const string& str,
vector<string>& result,
const string& delimiters
)
{
tokenize(str,result,delimiters,std::string(""),std::string("\""),std::string("\\"));
}
void tokenize ( const string& str, vector<string>& result,
const string& delimiters, const string& delimiters_preserve,
const string& quote, const string& esc )
{
// clear the vector
if ( false == result.empty() )
{
result.clear();
}
string::size_type pos = 0; // the current position (char) in the string
char ch = 0; // buffer for the current character
char delimiter = 0; // the buffer for the delimiter char which
// will be added to the tokens if the delimiter
// is preserved
char current_quote = 0; // the char of the current open quote
bool quoted = false; // indicator if there is an open quote
string token; // string buffer for the token
bool token_complete = false; // indicates if the current token is
// read to be added to the result vector
string::size_type len = str.length(); // length of the input-string
// for every char in the input-string
while ( len > pos )
{
// get the character of the string and reset the delimiter buffer
ch = str.at(pos);
delimiter = 0;
// assume ch isn't a delimiter
bool add_char = true;
// check ...
// ... if the delimiter is an escaped character
bool escaped = false; // indicates if the next char is protected
if ( false == esc.empty() ) // check if esc-chars are provided
{
if ( string::npos != esc.find_first_of(ch) )
{
// get the escaped char
++pos;
if ( pos < len ) // if there are more chars left
{
// get the next one
ch = str.at(pos);
// add the escaped character to the token
add_char = true;
}
else // cannot get any more characters
{
// don't add the esc-char
add_char = false;
}
// ignore the remaining delimiter checks
escaped = true;
}
}
// ... if the delimiter is a quote
if ( false == quote.empty() && false == escaped )
{
// if quote chars are provided and the char isn't protected
if ( string::npos != quote.find_first_of(ch) )
{
// if not quoted, set state to open quote and set
// the quote character
if ( false == quoted )
{
quoted = true;
current_quote = ch;
// don't add the quote-char to the token
add_char = false;
}
else // if quote is open already
{
// check if it is the matching character to close it
if ( current_quote == ch )
{
// close quote and reset the quote character
quoted = false;
current_quote = 0;
// don't add the quote-char to the token
add_char = false;
}
} // else
}
}
// ... if the delimiter isn't preserved
if ( false == delimiters.empty() && false == escaped &&
false == quoted )
{
// if a delimiter is provided and the char isn't protected by
// quote or escape char
if ( string::npos != delimiters.find_first_of(ch) )
{
// if ch is a delimiter and the token string isn't empty
// the token is complete
if ( false == token.empty() ) // BUGFIX: 2006-03-04
{
token_complete = true;
}
// don't add the delimiter to the token
add_char = false;
}
}
// ... if the delimiter is preserved - add it as a token
bool add_delimiter = false;
if ( false == delimiters_preserve.empty() && false == escaped &&
false == quoted )
{
// if a delimiter which will be preserved is provided and the
// char isn't protected by quote or escape char
if ( string::npos != delimiters_preserve.find_first_of(ch) )
{
// if ch is a delimiter and the token string isn't empty
// the token is complete
if ( false == token.empty() ) // BUGFIX: 2006-03-04
{
token_complete = true;
}
// don't add the delimiter to the token
add_char = false;
// add the delimiter
delimiter = ch;
add_delimiter = true;
}
}
// add the character to the token
if ( true == add_char )
{
// add the current char
token.push_back( ch );
}
// add the token if it is complete
if ( true == token_complete && false == token.empty() )
{
// add the token string
result.push_back( token );
// clear the contents
token.clear();
// build the next token
token_complete = false;
}
// add the delimiter
if ( true == add_delimiter )
{
// the next token is the delimiter
string delim_token;
delim_token.push_back( delimiter );
result.push_back( delim_token );
// REMOVED: 2006-03-04, Bugfix
}
// repeat for the next character
++pos;
} // while
// add the final token
if ( false == token.empty() )
{
result.push_back( token );
}
}
| [
"gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b"
] | [
[
[
1,
233
]
]
] |
970134d90f70afe8d17acf817545473284a9f4fd | 56c17f756480a02c77aecc69b217c29294f4c180 | /Src/Libs/Rastering/FPSView.h | e61a01f46272d0538b359fb74f91af78156da793 | [] | no_license | sangongs/qbert3d | 5fd88b9720b68ca7617a8c5510568911b3dc34c5 | 296b78451b73032e16e64ae1cc4f0200ef7ca734 | refs/heads/master | 2021-01-10T04:02:37.685309 | 2008-09-12T16:13:04 | 2008-09-12T16:13:04 | 46,944,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | h | #pragma once
#include "SimpleQbertView.h"
namespace BGComplete
{
class FPSView : public SimpleQbertView
{
protected:
void SetUpCamera();
void CameraMove(float deltaX, float deltaY, float deltaZ, float xRotate, float yRotate, float zRotate, char viewKey);
};
} | [
"haimbender@97581c8e-fe54-0410-aa42-dd6ba39e7182"
] | [
[
[
1,
17
]
]
] |
6c3519397453f1a4ad8c2009595b0392a8847392 | 53f155c92599ccaa92be24c259893911bf03aff8 | /trunk/source/geographyaspect.cpp | fa20f34be68f975992d377f413fb0fb0862507e2 | [] | no_license | BackupTheBerlios/framework-svn | 6813d63b9fab1eef7873d3e115be339c1f7a73a1 | 8bd8bedee4456d00fdb03b9a76cfe0b9e364ef73 | refs/heads/master | 2021-01-01T16:00:01.456584 | 2006-12-13T22:03:46 | 2006-12-13T22:03:46 | 40,671,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,761 | cpp | #include "framework.h"
#include "geographyaspect.h"
#include "distributions.h"
#define IABS(a,b) (a>b ? a-b : b-a)
void GeographyAspect::Evolve()
{
}
int GeographyAspect::GetInfoSize()
{
return sizeof(GeographyInfo);
}
void GeographyAspect::InitializeAspect()
{
/*int xFocusWidth = GetConfigInt("FocusWidth");*/
/*int yFocusHeight = GetConfigInt("FocusHeight");*/
Alfa = GetConfigFloat("Alfa");
_delta = GetConfigFloat("Delta");
// Get aspects
//_distanceAspect = (DistanceAspect *) this->GetAspect(typeid(DistanceAspect).name());
_seed = GetConfigLong("Seed"); Seed = &_seed;
}
void GeographyAspect::Start()
{
float xWidth = GetConfigFloat("Width");
float yHeight = GetConfigFloat("Height");
/* Initialize values for the agents */
GeographyInfo *element;
for (Population::Iterator agentId = this->begin;
agentId != this->end; ++agentId)
{
element = (*this)[*agentId];
do
element->X = xWidth / 2 + gasdev(Seed) * xWidth / 3;
while (element->X < 0 || element->X > xWidth);
do
element->Y = yHeight / 2 + gasdev(Seed) * yHeight / 3;
while (element->Y < 0 || element->Y > yHeight);
}
// Gets the sum of all probas
_sum_of_all_probas_norm = GetProbaNormalization(&_norm_of_sum);
}
bool GeographyAspect::hasInCache(int cellsX, int cellsY, int size, float _alfa, float _delta)
{
float ret;
return getFromCache(cellsX, cellsY, size, _alfa, _delta, &ret) > -1;
}
float GeographyAspect::getFromCache(int cellsX, int cellsY, int size, float _alfa, float _delta, float *norm_of_sum)
{
if (cellsX == 10 && cellsY == 10 && size == 500 && Alfa == 2.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.010000;
return 0.054910;
}
if (cellsX == 100 && cellsY == 100 && size == 500 && Alfa == 4.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 0.002132;
}
if (cellsX == 100 && cellsY == 100 && size == 500 && Alfa == 2.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 0.003386;
}
if (cellsX == 100 && cellsY == 100 && size == 500 && Alfa == 0.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 1.000000;
}
if (cellsX == 100 && cellsY == 100 && size == 100000 && Alfa == 2.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 0.008573;
}
if (cellsX == 100 && cellsY == 100 && size == 10000 && Alfa == 0.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 0.786092;
}
if (cellsX == 100 && cellsY == 100 && size == 100000 && Alfa == 0.000000 && _delta == 1.000000)
{
*norm_of_sum = 0.000100;
return 4.081978;
}
else
return -1;
}
float GeographyAspect::GetProbaNormalization(float *norm_of_sum)
{
float xWidth = GetConfigFloat("Width");
float yHeight = GetConfigFloat("Height");
int cellsX = (int) xWidth; int cellsY = (int) yHeight;
int size = this->begin->GetSize();
if (hasInCache(cellsX, cellsY, size, Alfa, _delta))
{
return getFromCache(cellsX, cellsY, size, Alfa, _delta, norm_of_sum);
}
// Calculate n for the grid
int *count = new int[cellsX * cellsY];
memset(count, 0, sizeof(int) * (cellsX * cellsY));
GeographyInfo *element;
for (Population::Iterator agentId = this->begin;
agentId != this->end; ++agentId)
{
element = (*this)[*agentId];
count[(int) (element->X) * cellsX +
(int) (element->Y)]++;
}
int x1, x2; int y1, y2;
float dist;
float proba;
float sum_of_all_probas = 0;
for (y1 = 0; y1 < cellsY; y1++)
for (x1 = 0; x1 < cellsX; x1++)
{
// Goes through each cell
for (y2 = 0; y2 < cellsY; y2++)
for (x2 = 0; x2 < cellsX; x2++)
{
dist = GeographicDistance(x1, y1, x2, y2);
proba = this->pdistrGeographicRaw(dist);
int c1 = count[x1 * cellsX + y1];
int c2 = count[x2 * cellsX + y2];
float add = proba * c1 * c2;
if (add > 0)
sum_of_all_probas += add;
}
}
float sum_of_all_probas_norm;
sum_of_all_probas_norm = sum_of_all_probas / (size * size);
*norm_of_sum = 1.0F / (cellsX * cellsY);
// done
free(count);
//
printf("\nNoncached value for: cellsX == %i && cellsY == %i && size == %i && Alfa == %f && _delta == %f\n", cellsX, cellsY, size, Alfa, _delta);
printf("*norm_of_sum = %f; sum_of_all_probas_norm = %f;\n\n", *norm_of_sum, sum_of_all_probas_norm);
return sum_of_all_probas_norm;
}
float GeographyAspect::GeographicDistance(float x1, float y1, float x2, float y2)
{
float dist=0.0;
/*Generic Minkowski metric delta=1 Manhattan delta=2 Euclid*/
if (x1 != x2)
dist += exp(_delta * log(IABS(x1, x2)));
if (y1 != y2)
dist += exp(_delta * log(IABS(y1, y2)));
if (dist)
return exp(log(dist) / _delta);
else
return 0.0;
}
float GeographyAspect::pdistrGeographic(float gdist)
{
return pdistrGeographicRaw(gdist) / _sum_of_all_probas_norm * _norm_of_sum;
}
float GeographyAspect::pdistrGeographicRaw(float gdist)
{
float proba;
proba = (float) exp(-Alfa * log(gdist + 1.0F));
return proba;
}
GeographyInfo * GeographyAspect::operator[](key agentId)
{
return (GeographyInfo *) this->GetInfo(agentId);
}
void GeographyAspect::ReleaseAspect()
{
if (this->_initialized == false) return;
}
void GeographyAspect::ShowValues(int agentId, std::vector <char *> & fields,
varValue *values)
{
for (std::vector <char *>::size_type n = 0; n < fields.size();n++)
{
if (strcmp(fields[n], "X")==0)
values[n] = varValue((*this)[agentId]->X);
else if (strcmp(fields[n], "Y")==0)
values[n] = varValue((*this)[agentId]->Y);
else if (strcmp(fields[n], "Alfa")==0)
values[n] = varValue(Alfa);
else
values[n] = varValue(0);
}
}
| [
"pablodegrande@8096f40a-0115-0410-8a2f-ff4c50103d81",
"meguia@8096f40a-0115-0410-8a2f-ff4c50103d81"
] | [
[
[
1,
16
],
[
20,
25
],
[
27,
163
],
[
166,
170
],
[
175,
199
]
],
[
[
17,
19
],
[
26,
26
],
[
164,
165
],
[
171,
174
]
]
] |
4cf2562bc682031ae3b3f934218e94dbebc1c16f | 658a1222b06267650db18923a269d7cf7ae0f100 | /PhysicalObject.h | 864df0c46613a18f6d74640a328766cb588b32f7 | [] | no_license | imclab/H.E.A.D | 4c3eb84ea8fd12a6b1b6c0598dd910f541aa92e0 | 02303c25be37d3708a8db66a8f7bb5ee9610c841 | refs/heads/master | 2021-01-18T10:42:07.368559 | 2010-09-19T17:43:49 | 2010-09-19T17:43:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | h | #pragma once
#include <ClanLib/display.h>
#include <Box2D/Box2D.h>
//forward declaration do screenmanager
class ScreenManager;
enum EObjectType
{
O_BLOCK,
O_BALL,
O_TRAMPOLIN,
O_PIT,
O_GOAL,
O_GOALSENSOR,
O_STARTRAMP,
O_KRAMP,
O_BUMPER,
O_INVALID
};
class PhysicalObject
{
public:
PhysicalObject(void);
virtual ~PhysicalObject(void);
protected:
EObjectType type;
CL_Sprite * sprite;
CL_CollisionOutline coutline;
b2Body * body;
b2BodyDef bodydef;
b2Shape * bodyshape;
b2FixtureDef fixturedef;
float pX,pY;
float angle;
ScreenManager * sm;
public:
virtual void draw();
virtual void handleevents();
EObjectType getType();
void setPosition(float x , float y);
inline CL_CollisionOutline * getCollisionOutline(){return &coutline;}
};
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
426ffe3730cb765956d251e25927868734e1f6ec | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/CodeJam/practice/Multiples.cpp | b81928615fe55fcf3a464ebdd326bde54397c7a4 | [] | 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 | 3,917 | cpp | // BEGIN CUT HERE
// PROBLEM STATEMENT
//
// You are to create a class Multiples with a method number,
// which takes three ints: min, max, and factor.
//
//
//
// Given a range of integers from min to max (inclusive),
// determine how many numbers within that range are evenly
// divisible by factor.
//
//
// DEFINITION
// Class:Multiples
// Method:number
// Parameters:int, int, int
// Returns:int
// Method signature:int number(int min, int max, int factor)
//
//
// NOTES
// -If x is evenly divisble by y, there exists some integer k
// such that k * y = x.
//
//
// CONSTRAINTS
// -min will be between -1000000 and 1000000, inclusive.
// -max will be between -1000000 and 1000000, inclusive.
// -max will be greater than or equal to min.
// -factor will be between 1 and 1000, inclusive.
//
//
// EXAMPLES
//
// 0)
// 0
// 14
// 5
//
// Returns: 3
//
// The numbers 0, 5, and 10 are evenly divisible by 5, so
// this returns 3.
//
// 1)
// 7
// 24
// 3
//
// Returns: 6
//
// The numbers 9, 12, 15, 18, 21, 24 are evenly divisible by
// 3, so this returns 6.
//
//
// 2)
// -123456
// 654321
// 997
//
// Returns: 780
//
// 3)
// -75312
// 407891
// 14
//
// Returns: 34515
//
// END CUT HERE
#line 73 "Multiples.cpp"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#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 stringstream SS;
typedef istringstream ISS;
typedef ostringstream OSS;
#define FOR(i,a,b) for(int i=(a);i<int(b);++i)
#define REP(i,n) FOR(i,0,n)
template<class U,class T> T cast(U x){T y; OSS a; a<<x; ISS b(a.str());b>>y;return y;}
#define ALL(v) (v).begin(),(v).end()
#define SZ(v) ((int)(v).size())
#define FOUND(v,p) (find(ALL(v),p)!=v.end())
#define DV(v) REP(i,SZ(v)) cout << v[i] << " "; cout << endl
#define SUM(v) accumulate(ALL(v),0)
#define SE(i) (i)->second
class Multiples
{
public:
int number(int min, int max, int factor)
{
while(min<=max&&min%factor!=0) min++;
while(min<=max&&max%factor!=0) max--;
return (max-min)/factor+1;
}
// 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 = 0; int Arg1 = 14; int Arg2 = 5; int Arg3 = 3; verify_case(0, Arg3, number(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arg0 = 7; int Arg1 = 24; int Arg2 = 3; int Arg3 = 6; verify_case(1, Arg3, number(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arg0 = -123456; int Arg1 = 654321; int Arg2 = 997; int Arg3 = 780; verify_case(2, Arg3, number(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arg0 = -75312; int Arg1 = 407891; int Arg2 = 14; int Arg3 = 34515; verify_case(3, Arg3, number(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Multiples ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
] | [
[
[
1,
139
]
]
] |
49d07e3c04c19149e2bb4dc714077bf4eea0d41a | f43c7dc0c3ca9031175fc3f13461a86b9c4ce667 | /help/AseHtmlConv/test.cpp | 20975e81105d49e39445a8fd6b955d99701e2aa4 | [] | no_license | ebakker/aseisql | 998c8b10f4ba3499d53c2e74b2276620a694ef28 | faf31bf448dfb18b66b4f395188201989ccd3ced | refs/heads/master | 2021-01-18T20:19:41.247243 | 2009-11-09T21:45:48 | 2009-11-09T21:45:48 | 36,292,766 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,932 | cpp | #include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <SHARE.H>
bool swap(char*src,char*dst){
if(!CopyFile(src,dst,false)){
printf("can't copy \"%s\" to \"%s\"\n",src,dst);
return false;
}
if(remove(src)){
printf("can't remove \"s\"\n",src);
return false;
}
return true;
}
bool Access(char*f,DWORD dwDesiredAccess){
//dwDesiredAccess=0 | GENERIC_READ | GENERIC_WRITE
HANDLE h=CreateFile(f,dwDesiredAccess,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(h==INVALID_HANDLE_VALUE){
//printf("file not accessible \"%s\"\n",f);
return false;
}
CloseHandle(h);
return true;
}
bool format(char*src){
if(!Access(src,GENERIC_WRITE))return false;
char * tmp="format.tmp";
FILE* fr=_fsopen(src,"rt",SH_DENYRW);
if(!fr){
printf("can't open file %s\n",src);
return false;
}
FILE* fw=_fsopen(tmp,"wt",SH_DENYRW);
bool nlf=true;
char c;
if(fw){
while( (c = getc( fr )) != EOF ){
if( c=='<' ){
if(!nlf)putc('\n',fw);
nlf=true;
putc(c,fw);
}else if( c=='>' ){
putc(c,fw);
if(!nlf)putc('\n',fw);
nlf=true;
}else if( c=='\n' ){
//if(!nlf)putc('\n',fw);
//nlf=true;
putc(' ',fw);
}else{
putc(c,fw);
nlf=false;
}
}
}else{
printf("can't open file %s\n",tmp);
fclose(fr);
return false;
}
fclose(fr);
fflush(fw);
fclose(fw);
return swap(tmp,src);
}
bool unformat(char*src){
if(!Access(src,GENERIC_WRITE))return false;
char * tmp="unformat.tmp";
FILE* fr=_fsopen(src,"rt",SH_DENYRW);
if(!fr){
printf("can't open file %s\n",src);
return false;
}
FILE* fw=_fsopen(tmp,"wt",SH_DENYRW);
char c;
if(fw){
while( (c = getc( fr )) != EOF ){
if( c=='\n' ){
//putc(c,fw);
}else if( c=='\r' ){
//putc(c,fw);
}else{
putc(c,fw);
}
}
}else{
printf("can't open file %s\n",tmp);
fclose(fr);
return false;
}
fclose(fr);
fflush(fw);
fclose(fw);
return swap(tmp,src);
}
bool chtitle(char*src,char*title,int nest){
// for(int i=1;i<nest;i++)printf(" ");
// printf("processing \"%s\"\n",src);
char buf[4000];
char link[4000];
if(!format(src))return false;
FILE*tmp=tmpfile();
if(!tmp){
printf("can't create temp file\n");
return false;
}
FILE*f=_fsopen(src,"rt",SH_DENYRW);
if(!f){
fclose(tmp);
printf("can't open file \"%s\"\n",src);
return false;
}
while(fgets(buf,sizeof(buf),f)){
if( !strcmpi("<title>\n",buf) ){
fputs(buf,tmp);
fputs(title,tmp);
fputs("\n",tmp);
while(fgets(buf,sizeof(buf),f)){
if( !strcmpi("</title>\n",buf) )break;
}
fputs(buf,tmp);
}else if( !strnicmp("<a name=\"#",buf,10) ){
fputs("<a name=\"",tmp);
fputs(buf+10,tmp);
}else if( !strnicmp("<a href=\"",buf,9) ){
fputs(buf,tmp);
strcpy(link,buf+9);
char*cc=strchr(link,'\"');
if(cc)cc[0]=0;
if( !Access(link,0) ){
printf("\"%s\" wrong link? \"%s\"\n",src,link);
}else{
// strncat(title," :: ",4000-1);
strcpy(title,"");
while(fgets(buf,sizeof(buf),f)){
fputs(buf,tmp);
if( !strcmpi("</a>\n",buf) )break;
strncat(title,buf,4000-1);
}
chtitle(link,title,nest+1);
}
}else{
fputs(buf,tmp);
}
}
//now copy tmp back to original file
fflush(tmp);
fseek( tmp, 0, SEEK_SET );
fclose(f);
f=_fsopen(src,"wt",SH_DENYRW);
if(!f){
fclose(tmp);
printf("can't open file \"%s\"\n",src);
return false;
}
char c;
while( (c = fgetc( tmp )) != EOF )
fputc( c, f );
fflush( f );
fclose( f );
fclose( tmp );
unformat(src);
return true;
}
int main(int argc, char* argv[])
{
if(argc!=3){printf("two parameters required\n");return 1;}
char title[4000];
strcpy(title,argv[2]);
chtitle(argv[1],title,1);
return 0;
}
| [
"[email protected]@9f3282c0-2842-11de-b858-7de967f63ef5"
] | [
[
[
1,
192
]
]
] |
3ea2adef514064c132719a8b5017ff173905ba50 | 3761dcce2ce81abcbe6d421d8729af568d158209 | /include/cybergarage/http/ParameterList.h | 0a174c54d8a2f83c521441fb9f5799836c9666e3 | [
"BSD-3-Clause"
] | permissive | claymeng/CyberLink4CC | af424e7ca8529b62e049db71733be91df94bf4e7 | a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2 | refs/heads/master | 2021-01-17T07:51:48.231737 | 2011-04-08T15:10:49 | 2011-04-08T15:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | h | /******************************************************************
*
* CyberHTTP for C++
*
* Copyright (C) Satoshi Konno 2002-2004
*
* File: ParameterList.h
*
* Revision;
*
* 03/09/04
* - first revision
*
******************************************************************/
#ifndef _CHTTP_PARAMETERLIST_H_
#define _CHTTP_PARAMETERLIST_H_
#include <cybergarage/util/Vector.h>
#include <cybergarage/util/StringUtil.h>
#include <cybergarage/http/Parameter.h>
namespace CyberHTTP {
class ParameterList : public CyberUtil::Vector
{
public:
ParameterList()
{
}
~ParameterList()
{
int nLists = size();
for (int n=0; n<nLists; n++) {
Parameter *param = at(n);
delete param;
}
}
Parameter *at(int n)
{
return (Parameter *)Vector::get(n);
}
Parameter *getParameter(int n)
{
return (Parameter *)Vector::get(n);
}
Parameter *getParameter(const char *name)
{
if (name == NULL)
return NULL;
int nLists = size();
for (int n=0; n<nLists; n++) {
Parameter *param = at(n);
if (CyberUtil::StringEquals(name, param->getName()) == true)
return param;
}
return NULL;
}
const char *getValue(const char *name)
{
Parameter *param = getParameter(name);
if (param == NULL)
return "";
return param->getValue();
}
};
}
#endif
| [
"skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e"
] | [
[
[
1,
78
]
]
] |
4a16341f4c3771d7809810f94f52db2519b361b3 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/wspr/wsuSingleLock.cpp | 6f41815bf6d66d234f0c2050fe88c955745f3192 | [] | 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 | 498 | cpp | // wsuSingleLock.cpp
#include "wsuSingleLock.h"
#include "wsuSyncObject.h"
wsuSingleLock::wsuSingleLock(wsuSyncObject * pObject) : m_pSO( pObject )
{
if (pObject) pObject->Lock();
}
wsuSingleLock::~wsuSingleLock(void)
{
Unlock();
}
void wsuSingleLock::Unlock(void)
{
wsuSyncObject * pObject = m_pSO;
m_pSO = WS_NULL;
if (pObject) pObject->Unlock();
}
ws_boolean wsuSingleLock::IsLocked(void)
{
return ((m_pSO) ? WS_TRUE : WS_FALSE);
}
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
30
]
]
] |
701ca877a40ae17e30efeefa794e8562ac461e4f | 3b76b2980485417cb656215379b93b27d4444815 | /7.Ung dung/Source code/Client/Client/myapp.cpp | 73cde199375b53b7dbfa98973612f078ab8f078f | [] | no_license | hemprasad/lvmm-sc | 48d48625b467b3756aa510b5586af250c3a1664c | 7c68d1d3b1489787f5ec3d09bc15b4329b0c087a | refs/heads/master | 2016-09-06T11:05:32.770867 | 2011-07-25T01:09:07 | 2011-07-25T01:09:07 | 38,108,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp | // myapp.cpp: implementation of the myapp class.
//
//////////////////////////////////////////////////////////////////////
#include <afxwin.h>
#include "myapp.h"
#include "resource.h"
#include "Display.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL myapp::InitInstance()
{
Display dlg(IDD_DIALOG1);
m_pMainWnd=&dlg;
dlg.DoModal();
return FALSE;
}
myapp a; | [
"funnyamauter@72c74e6c-5204-663f-ea46-ae2a288fd484"
] | [
[
[
1,
24
]
]
] |
3ad4fae57b5bb8d488e74d5a390980a15cb3c432 | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnSystem/Source/GnDebugAllocator.h | 005c2ef11fcf557be77305bdac273536b501dac6 | [] | no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | h | #pragma once
#include "GnAllocator.h"
#ifdef GN_MEMORY_DEBUGGER
//#ifdef WIN32
#include <map>
//#endif // WIN32
class GnAllocUnit
{
public:
void* mpMeomry;
size_t mAllocSize;
char maFileName[256];
char maFunctionName[256];
int mFileLine;
};
class GNSYSTEM_ENTRY GnDebugAllocator : public GnAllocator
{
public:
GnDebugAllocator(GnAllocator* actualAllocator, bool writeToLog = true,
gtuint initialSize = 65536, gtuint growBy = 4096,
bool alwaysValidateAll = false, bool checkArrayOverruns = true);
virtual ~GnDebugAllocator(void);
// Encapsulate all memory management through a
// single set of API calls.
// Note that the size and alignment are passed-by-reference.
// This allows the allocator to adjust the values
// internally and pass the results back to the caller.
virtual void* Allocate(gsize& stSizeInBytes, gsize& stAlignment,
GnMemoryEventType eEventType, bool bProvideAccurateSizeOnDeallocate,
const gchar* pcFile, int iLine, const gchar* pcFunction);
virtual void Deallocate(void* pvMemory, GnMemoryEventType eEventType,
gsize stSizeInBytes);
virtual void* Reallocate(void* pvMemory, gsize& stSizeInBytes,
gsize& stAlignment, GnMemoryEventType eEventType,
bool bProvideAccurateSizeOnDeallocate, gsize stSizeCurrent,
const gchar* pcFile, int iLine, const gchar* pcFunction);
virtual bool TrackAllocate(const void* const pvMemory, gsize stSizeInBytes,
GnMemoryEventType eEventType, const gchar* pcFile,
int iLine, const gchar* pcFunction);
virtual bool TrackDeallocate(const void* const pvMemory, GnMemoryEventType eEventType);
virtual bool SetMarker(const char* pcMarkerType, const char* pcClassifier,
const char* pcString);
virtual void Initialize();
virtual void Shutdown();
virtual bool VerifyAddress(const void* pvMemory);
gsize PadForArrayOverrun(gsize stAlignment, gsize stSizeOriginal);
void AllocateAssert(const gchar* allocateFunction, gsize ID, gsize size);
protected:
bool mCheckArrayOverruns;
GnAllocator* mActualAlloctor;
//#ifdef WIN32
std::map<void*, GnAllocUnit> mpAllocList;
//#endif // WIN32
};
#endif // GN_MEMORY_DEBUGGER
| [
"[email protected]"
] | [
[
[
1,
71
]
]
] |
9259835439c227830ddb7fc7cdf82aafbb968ba2 | 563e71cceb33a518f53326838a595c0f23d9b8f3 | /v3/ProcTerrain/ProcTerrain/Shaders/RenderingShader.h | 1a64e9f00d5e55f1fdee5a7842513b5c10964007 | [] | no_license | fabio-miranda/procedural | 3d937037d63dd16cd6d9e68fe17efde0688b5a0a | e2f4b9d34baa1315e258613fb0ea66d1235a63f0 | refs/heads/master | 2021-05-28T18:13:57.833985 | 2009-10-07T21:09:13 | 2009-10-07T21:09:13 | 39,636,279 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | #ifndef RenderingShader_H
#define RenderingShader_H
#include "Shader.h"
class RenderingShader : public Shader{
public:
RenderingShader(bool complex);
~RenderingShader();
GLuint m_locTexture;
GLuint m_locTime;
GLuint m_locGPUGenerated;
GLuint m_locShowBlendTexture;
GLuint m_locShowLight;
GLuint m_locShowHeightMap;
GLuint m_locShowVerticesDisplacement;
GLuint *m_locBlendTextures;
};
#endif | [
"fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9"
] | [
[
[
1,
26
]
]
] |
1025470b7acffa19e55f00400e8b6c5c1d3ba02f | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/FitLine.cpp | 69769aa4979ce38988e08c73b8c2f7e369384314 | [
"LicenseRef-scancode-public-domain"
] | permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,239 | cpp | #ifdef PRECOMPILED_HEADER
#include "common.h"
#endif
#include "Fitting.h"
#include "Numerics.h"
using namespace std;
using namespace numerics;
FitLine::FitLine(std::vector< std::vector<double> >* xy, size_t x_column, size_t y_column, string output_dir) :
FitObject(xy, x_column, y_column, output_dir)
{
Guesses.push_back(new NormalGuess);
}
std::vector<double> FitLine::NormalGuess::GuessBaseParams(numerics::FitObject* fit)
{
FitLine* pFL = dynamic_cast<FitLine*>(fit);
base_params.resize(fit->BaseParamsSize());
assert( pFL->m_y.size() >= 2 );
//very crude initial guess for fit parameters
base_params[Slope] = ( pFL->m_y.back() - pFL->m_y[0] ) / ( pFL->m_x.back() - pFL->m_x[0] ) ;
base_params[Offset] = pFL->m_y[0];
return base_params;
}
std::vector<double> FitLine::NormalGuess::InitialFitParams(numerics::FitObject* fit)
{
fit_params = vector<double>(fit->FitParamsSize(), 1);
fit_params[Offset] = 0;
return fit_params;
}
bool FitLine::CheckFit()
{
IsGoodFit = true;
fill(fit_params.begin(), fit_params.end(), 1);
fit_params[Offset] = 0;
return IsGoodFit;
}
void FitLine::UpdateParams()
{
base_params[Slope] *= fit_params[Slope];
base_params[Offset] += fit_params[Offset];
fill(fit_params.begin(), fit_params.end(), 1);
fit_params[Offset] = 0;
}
void FitLine::PrintParams(ostream* os)
{
*os << "FitLine params" << endl;
*os << setprecision(10);
*os << setw(12) << "f0 = " << base_params[Offset] << endl;
*os << setw(12) << "x0 = " << m_x[0] << endl;
*os << setw(12) << "m = " << base_params[Slope] << endl;
}
void FitLine::fitfunction(const double* params,
const std::vector<double>& x,
std::vector<double>& f_of_x)
{
double l_f0 = base_params[Offset] + params[Offset];
double l_m = base_params[Slope] * params[Slope];
for (size_t i = 0; i < x.size(); i++)
f_of_x[i] = l_f0 + l_m * (x[i] - x[0]);
}
double FitLine::GetSlope() const
{
return base_params[Slope];
}
double FitLine::GetOffset() const
{
return base_params[Offset];
}
void FitLine::UpdateScanPage(ExpSCAN*)
{
throw runtime_error("This isn't set up yet.");
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
] | [
[
[
1,
99
]
]
] |
c223579fdf53be7aa4190dd84711e54f7da7a555 | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /EIBStdLib/include/DiffieHellman.h | 0e777e3421962341fe7109ea5056b8b9d09ccb01 | [] | no_license | radtek/eibsuite | 0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd | 4504fcf4fa8c7df529177b3460d469b5770abf7a | refs/heads/master | 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,363 | h | /*! \file DiffieHellman.h
\brief Diffie Hellman Class - Source file
This is The header file for CDiffieHellman class. This Class handles the DiffeHellman protocol.
*/
#ifndef __DIFFIE_HELLMAN_HEADER__
#define __DIFFIE_HELLMAN_HEADER__
#include "EibStdLib.h"
#include "CString.h"
// CRYPTO LIBRARY FOR EXCHANGING KEYS
// USING THE DIFFIE-HELLMAN KEY EXCHANGE PROTOCOL
#define MAX_RANDOM_INTEGER 2147483648UL //Should make these numbers massive to be more secure
#define MAX_PRIME_NUMBER 2147483648UL //Bigger the number the slower the algorithm
//Linear Feedback Shift Registers
#define LFSR(n) {if (n&1) n=((n^0x80000055)>>1)|0x80000000; else n>>=1;}
//Rotate32
#define ROT(x, y) (x=(x<<y)|(x>>(32-y)))
#define CLEAN_ALL_MEMORY 1
#define CLEAN_ALL_MEMORY_EXCEPT_KEY 2
#define MODULUS 1
#define GENERATOR 2
#define PRIVATE_A 3
#define PRIVATE_B 4
#define PUBLIC_A 5
#define PUBLIC_B 6
#define KEY 7
/*! \class CDiffieHellman
\brief DiffieHellman class. this class is responsible to implement all the neccessary action taken during
the diffe-hellman protocol. this class genrate random numbers acroding to the CPU time stamp.
(EAX opcode in the x86 processors). to generate large random number we use integer in 64 bit size. in addition,
Miller-Rabin algorithm is used to determine whether a number is prime or not.
*/
class EIB_STD_EXPORT CDiffieHellman
{
public:
/*!Default Constructor*/
CDiffieHellman();
/*!Destructor*/
virtual ~CDiffieHellman();
/*!
\brief Method to generate the base numbers for the diffie hellman algorithm. (the mudulus factor and the generator)
\fn void CreateKeys(int64 &Generator, int64 &Modulus);
\param Generator will be filled with the generated value
\param Modulus will be filled with the generated value
*/
void CreateKeys(int64 &Generator, int64 &Modulus);
/*!
\brief Method to generate the sender Public key
\fn void CreateSenderInterKey(int64 &InterKey);
\param InterKey will be filled with the generated value
*/
void CreateSenderInterKey(int64 &InterKey);
/*!
\brief Method to generate the Recipient Public key
\fn void CreateRecipientInterKey(int64 &InterKey, int64 Generator, int64 Modulus)
\param InterKey will be filled with the generated value
\param Generator the generator value to use
\param Modulus the modulus value to use
*/
void CreateRecipientInterKey(int64 &InterKey, int64 Generator, int64 Modulus);
/*!
\brief Method to generate the sender Private key
\fn void CreateSenderEncryptionKey(int64 &EncryptionKey, int64 RecipientInterKey)
\param EncryptionKey will be filled with the generated value
\param RecipientInterKey the Recipient Public key
*/
void CreateSenderEncryptionKey(int64 &EncryptionKey, int64 RecipientInterKey);
/*!
\brief Method to generate the Recipient Private key
\fn void CreateRecipientEncryptionKey(int64 &EncryptionKey, int64 SendersInterKey)
\param EncryptionKey will be filled with the generated value
\param SendersInterKey the sender Public key
*/
void CreateRecipientEncryptionKey(int64 &EncryptionKey, int64 SendersInterKey);
/*!
\brief Get Method
\fn int GetValue(int64 &value, unsigned int flags = KEY)
\param value will be filled according to the flags parameter
\param flags the value to get
*/
int GetValue(int64 &value, unsigned int flags = KEY);
/*!
\brief Get Method
\fn int64 GetPublicSender()
\return Sender public key
*/
int64 GetPublicSender() { return _public_a;}
/*!
\brief Get Method
\fn int64 GetPublicRecipient()
\return Recipient public key
*/
int64 GetPublicRecipient() { return _public_b;}
/*!
\brief Get Method
\fn const CString& GetSharedKey()
\return The shared key
*/
const CString& GetSharedKey() { return _shared_key_str; }
private:
int64 XpowYmodN(int64 x, int64 y, int64 N);
uint64 GenerateRandomNumber( void );
uint64 GeneratePrime();
int64 GetRTSC( void );
bool IsItPrime (int64 n, int64 a);
bool MillerRabin (int64 n, int64 trials);
int64 _generator;
int64 _modulus;
int64 _private_a;
int64 _private_b;
int64 _public_a;
int64 _public_b;
int64 _shared_key;
CString _shared_key_str;
void CleanMem(unsigned int flags = CLEAN_ALL_MEMORY);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
134
]
]
] |
e08718fdae2a34991cc85ecc888dc084783d796c | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Limn/LimnDW/LimnDW/SimpleMixer.h | 745c43e87bcf0ed655768b34a43b24f0ae41eec4 | [] | 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 | 1,032 | h | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#ifndef __SIMPLEMIXER_H
#define __SIMPLEMIXER_H
//---------------------------------------------------------------------------
class CSimpleMixer : public MBaseMethod
{
public:
CSimpleMixer(MUnitDefBase * pUnitDef, TaggedObject * pNd);
virtual void Init();
virtual void BuildDataFields();
virtual bool ExchangeDataFields();
virtual void EvalProducts();
virtual bool GetModelAction(CMdlActionArray & Acts);
virtual bool SetModelAction(CMdlAction & Act);
virtual bool GetModelGraphic(CMdlGraphicArray & Grfs);
virtual bool OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf);
protected:
C_ModelParameters_DiamondWizard_SimpleMixer m_DWParms;
bool m_LBtnDn;
bool m_RBtnDn;
CPoint m_MousePt;
};
#endif | [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
f980bc6c4921a9aee6c5237a30a0868bf36d609b | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/WindowsCE/WinFileReader.cpp | d5aad8a9871fe2987dc4c1b12d55d6c87021e913 | [] | no_license | danste/ars-framework | 5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6 | 90f99d43804d3892432acbe622b15ded6066ea5d | refs/heads/master | 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null | UTF-8 | C++ | false | false | 1,539 | cpp |
#include <FileReader.hpp>
FileReader::FileReader():
handle_(INVALID_HANDLE_VALUE)
{}
FileReader::~FileReader()
{
if (isOpen())
close();
}
status_t FileReader::close()
{
assert(isOpen());
BOOL res=::CloseHandle(handle_);
handle_=INVALID_HANDLE_VALUE;
if (!res)
return ::GetLastError();
else
return errNone;
}
status_t FileReader::read(int& ret)
{
assert(isOpen());
char chr;
DWORD result;
BOOL res=::ReadFile(handle_, &chr, 1, &result, NULL);
if (res)
{
if (0==result)
ret=npos;
else
ret=chr;
return errNone;
}
else
return ::GetLastError();
}
status_t FileReader::read(int& ret, String& dst, int offset, int range)
{
assert(isOpen());
DWORD result;
BOOL res=::ReadFile(handle_, &dst[offset], range, &result, NULL);
if (res)
{
ret=result;
return errNone;
}
else
return ::GetLastError();
}
status_t FileReader::open(const char_t* fileName, ulong_t access, ulong_t shareMode, LPSECURITY_ATTRIBUTES securityAttributes,
ulong_t creationDisposition, ulong_t flagsAndAttributes, HANDLE templateFile)
{
if (isOpen())
close();
handle_=::CreateFile(fileName, access, shareMode, securityAttributes, creationDisposition, flagsAndAttributes, templateFile);
if (INVALID_HANDLE_VALUE==handle_)
return ::GetLastError();
else
return errNone;
}
| [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
] | [
[
[
1,
3
],
[
7,
7
],
[
13,
13
],
[
24,
24
],
[
32,
32
],
[
38,
38
],
[
42,
42
],
[
49,
49
],
[
56,
56
]
],
[
[
4,
6
],
[
8,
12
],
[
14,
23
],
[
25,
31
],
[
33,
37
],
[
39,
41
],
[
43,
48
],
[
50,
55
],
[
57,
67
]
]
] |
8766d94f7c0f7ad8383468360f71b0031e7e7027 | ff50aa2a11ffb3c1914cf1c8232de0546f8555ae | /noiseutils.h | 27b3542eb04c9001442bf0ec7d4e2496d7e8ec63 | [] | no_license | zapo/BomberSFML-3D | b2d0e486a454a33f55235a3fa000ef6eea2aea62 | 90d9ae3f5eff1fe5a67bbd7f58fd0db556394098 | refs/heads/master | 2021-01-10T19:13:36.314511 | 2011-12-12T07:21:51 | 2011-12-12T07:21:51 | 1,492,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 96,839 | h | // noiseutils.h
//
// Copyright (C) 2003-2005 Jason Bevins
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License (COPYING.txt) for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// The developer's email is [email protected] (for great email, take
// off every 'zig'.)
//
#ifndef NOISEUTILS_H
#define NOISEUTILS_H
#include <stdlib.h>
#include <string.h>
#include <string>
#include <libnoise/noise.h>
using namespace noise;
namespace noise
{
namespace utils
{
/// @mainpage noiseutils
///
/// @section intro Introduction
///
/// This library contains useful classes for creating and rendering
/// two-dimensional noise maps containing coherent noise that was
/// generated from the libnoise library. These classes are used to create
/// procedural textures and terrain height maps.
///
/// noiseutils is known to compile under Windows 2000 Service Pack 4
/// (using Microsoft Visual C++ 5.0) and under Gentoo Linux 10.0 (using
/// gcc 3.3.4). It should be portable across all platforms that can
/// compile libnoise.
///
/// @section classes Classes
///
/// This library contains the following classes:
/// - A <i>noise map</i> class: This class implements a two-dimensional
/// array that stores floating-point values. It's designed to store
/// coherent-noise values generated by a noise module.
/// - Several <i>noise-map builder</i> classes: Each of these classes
/// fills a noise map with coherent-noise values generated by a noise
/// module. While filling a noise map, it iterates the coordinates of
/// the input value along the surface of a specific mathematical object.
/// Each of these classes implements a different mathematical object,
/// such as a plane, a cylinder, or a sphere.
/// - An <i>image</i> class: This class implements a two-dimensional array
/// that stores color values.
/// - Several <i>image-renderer</i> classes: these classes render images
/// given the contents of a noise map. Each of these classes renders an
/// image in a different way.
///
/// @section contact Contact
///
/// Contact jas for questions about noiseutils. The spam-resistant email
/// address is [email protected] (For great email, take off every
/// <a href=http://www.planettribes.com/allyourbase/story.shtml>zig</a>.)
/// The maximum width of a raster.
const int RASTER_MAX_WIDTH = 32767;
/// The maximum height of a raster.
const int RASTER_MAX_HEIGHT = 32767;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// The raster's stride length must be a multiple of this constant.
const int RASTER_STRIDE_BOUNDARY = 4;
#endif
/// A pointer to a callback function used by the NoiseMapBuilder class.
///
/// The NoiseMapBuilder::Build() method calls this callback function each
/// time it fills a row of the noise map with coherent-noise values.
///
/// This callback function has a single integer parameter that contains
/// a count of the rows that have been completed. It returns void. Pass
/// a function with this signature to the NoiseMapBuilder::SetCallback()
/// method.
typedef void(*NoiseMapCallback) (int row);
/// Number of meters per point in a Terragen terrain (TER) file.
const double DEFAULT_METERS_PER_POINT = 30.0;
/// Same as the DEFAULT_METERS_PER_POINT constant, but for us
/// canuckleheads.
const double DEFAULT_METRES_PER_POINT = DEFAULT_METERS_PER_POINT;
/// Defines a color.
///
/// A color object contains four 8-bit channels: red, green, blue, and an
/// alpha (transparency) channel. Channel values range from 0 to 255.
///
/// The alpha channel defines the transparency of the color. If the alpha
/// channel has a value of 0, the color is completely transparent. If the
/// alpha channel has a value of 255, the color is completely opaque.
class Color
{
public:
/// Constructor.
Color ()
{
}
/// Constructor.
///
/// @param r Value of the red channel.
/// @param g Value of the green channel.
/// @param b Value of the blue channel.
/// @param a Value of the alpha (transparency) channel.
Color (noise::uint8 r, noise::uint8 g, noise::uint8 b,
noise::uint8 a):
red (r), green (g), blue (b), alpha (a)
{
}
/// Value of the alpha (transparency) channel.
noise::uint8 alpha;
/// Value of the blue channel.
noise::uint8 blue;
/// Value of the green channel.
noise::uint8 green;
/// Value of the red channel.
noise::uint8 red;
};
/// Defines a point used to build a color gradient.
///
/// A color gradient is a list of gradually-changing colors. A color
/// gradient is defined by a list of <i>gradient points</i>. Each
/// gradient point has a position and a color. In a color gradient, the
/// colors between two adjacent gradient points are linearly interpolated.
///
/// The ColorGradient class defines a color gradient by a list of these
/// objects.
struct GradientPoint
{
/// The position of this gradient point.
double pos;
/// The color of this gradient point.
Color color;
};
/// Defines a color gradient.
///
/// A color gradient is a list of gradually-changing colors. A color
/// gradient is defined by a list of <i>gradient points</i>. Each
/// gradient point has a position and a color. In a color gradient, the
/// colors between two adjacent gradient points are linearly interpolated.
///
/// To add a gradient point to the color gradient, pass its position and
/// color to the AddGradientPoint() method.
///
/// To retrieve a color from a specific position in the color gradient,
/// pass that position to the GetColor() method.
///
/// This class is a useful tool for coloring height maps based on
/// elevation.
///
/// <b>Gradient example</b>
///
/// Suppose a gradient object contains the following gradient points:
/// - -1.0 maps to black.
/// - 0.0 maps to white.
/// - 1.0 maps to red.
///
/// If an application passes -0.5 to the GetColor() method, this method
/// will return a gray color that is halfway between black and white.
///
/// If an application passes 0.25 to the GetColor() method, this method
/// will return a very light pink color that is one quarter of the way
/// between white and red.
class GradientColor
{
public:
/// Constructor.
GradientColor ();
/// Destructor.
~GradientColor ();
/// Adds a gradient point to this gradient object.
///
/// @param gradientPos The position of this gradient point.
/// @param gradientColor The color of this gradient point.
///
/// @pre No two gradient points have the same position.
///
/// @throw noise::ExceptionInvalidParam See the precondition.
///
/// It does not matter which order these gradient points are added.
void AddGradientPoint (double gradientPos,
const Color& gradientColor);
/// Deletes all the gradient points from this gradient object.
///
/// @post All gradient points from this gradient object are deleted.
void Clear ();
/// Returns the color at the specified position in the color gradient.
///
/// @param gradientPos The specified position.
///
/// @returns The color at that position.
const Color& GetColor (double gradientPos) const;
/// Returns a pointer to the array of gradient points in this object.
///
/// @returns A pointer to the array of gradient points.
///
/// Before calling this method, call GetGradientPointCount() to
/// determine the number of gradient points in this array.
///
/// It is recommended that an application does not store this pointer
/// for later use since the pointer to the array may change if the
/// application calls another method of this object.
const GradientPoint* GetGradientPointArray () const
{
return m_pGradientPoints;
}
/// Returns the number of gradient points stored in this object.
///
/// @returns The number of gradient points stored in this object.
int GetGradientPointCount () const
{
return m_gradientPointCount;
}
private:
/// Determines the array index in which to insert the gradient point
/// into the internal gradient-point array.
///
/// @param gradientPos The position of this gradient point.
///
/// @returns The array index in which to insert the gradient point.
///
/// @pre No two gradient points have the same input value.
///
/// @throw noise::ExceptionInvalidParam See the precondition.
///
/// By inserting the gradient point at the returned array index, this
/// object ensures that the gradient-point array is sorted by input
/// value. The code that maps a value to a color requires a sorted
/// gradient-point array.
int FindInsertionPos (double gradientPos);
/// Inserts the gradient point at the specified position in the
/// internal gradient-point array.
///
/// @param insertionPos The zero-based array position in which to
/// insert the gradient point.
/// @param gradientPos The position of this gradient point.
/// @param gradientColor The color of this gradient point.
///
/// To make room for this new gradient point, this method reallocates
/// the gradient-point array and shifts all gradient points occurring
/// after the insertion position up by one.
///
/// Because this object requires that all gradient points in the array
/// must be sorted by the position, the new gradient point should be
/// inserted at the position in which the order is still preserved.
void InsertAtPos (int insertionPos, double gradientPos,
const Color& gradientColor);
/// Number of gradient points.
int m_gradientPointCount;
/// Array that stores the gradient points.
GradientPoint* m_pGradientPoints;
/// A color object that is used by a gradient object to store a
/// temporary value.
mutable Color m_workingColor;
};
/// Implements a noise map, a 2-dimensional array of floating-point
/// values.
///
/// A noise map is designed to store coherent-noise values generated by a
/// noise module, although it can store values from any source. A noise
/// map is often used as a terrain height map or a grayscale texture.
///
/// The size (width and height) of the noise map can be specified during
/// object construction or at any other time.
///
/// The GetValue() and SetValue() methods can be used to access individual
/// values stored in the noise map.
///
/// This class manages its own memory. If you copy a noise map object
/// into another noise map object, the original contents of the noise map
/// object will be freed.
///
/// If you specify a new size for the noise map and the new size is
/// smaller than the current size, the allocated memory will not be
/// reallocated.
/// Call ReclaimMem() to reclaim the wasted memory.
///
/// <b>Border Values</b>
///
/// All of the values outside of the noise map are assumed to have a
/// common value known as the <i>border value</i>.
///
/// To set the border value, call the SetBorderValue() method.
///
/// The GetValue() method returns the border value if the specified value
/// lies outside of the noise map.
///
/// <b>Internal Noise Map Structure</b>
///
/// Internally, the values are organized into horizontal rows called @a
/// slabs. Slabs are ordered from bottom to top.
///
/// Each slab contains a contiguous row of values in memory. The values
/// in a slab are organized left to right.
///
/// The offset between the starting points of any two adjacent slabs is
/// called the <i>stride amount</i>. The stride amount is measured by
/// the number of @a float values between these two starting points, not
/// by the number of bytes. For efficiency reasons, the stride is often a
/// multiple of the machine word size.
///
/// The GetSlabPtr() and GetConstSlabPtr() methods allow you to retrieve
/// pointers to the slabs themselves.
class NoiseMap
{
public:
/// Constructor.
///
/// Creates an empty noise map.
NoiseMap ();
/// Constructor.
///
/// @param width The width of the new noise map.
/// @param height The height of the new noise map.
///
/// @pre The width and height values are positive.
/// @pre The width and height values do not exceed the maximum
/// possible width and height for the noise map.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// Creates a noise map with uninitialized values.
///
/// It is considered an error if the specified dimensions are not
/// positive.
NoiseMap (int width, int height);
/// Copy constructor.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
NoiseMap (const NoiseMap& rhs);
/// Destructor.
///
/// Frees the allocated memory for the noise map.
~NoiseMap ();
/// Assignment operator.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// @returns Reference to self.
///
/// Creates a copy of the noise map.
NoiseMap& operator= (const NoiseMap& rhs);
/// Clears the noise map to a specified value.
///
/// @param value The value that all positions within the noise map are
/// cleared to.
void Clear (float value);
/// Returns the value used for all positions outside of the noise map.
///
/// @returns The value used for all positions outside of the noise
/// map.
///
/// All positions outside of the noise map are assumed to have a
/// common value known as the <i>border value</i>.
float GetBorderValue () const
{
return m_borderValue;
}
/// Returns a const pointer to a slab.
///
/// @returns A const pointer to a slab at the position (0, 0), or
/// @a NULL if the noise map is empty.
const float* GetConstSlabPtr () const
{
return m_pNoiseMap;
}
/// Returns a const pointer to a slab at the specified row.
///
/// @param row The row, or @a y coordinate.
///
/// @returns A const pointer to a slab at the position ( 0, @a row ),
/// or @a NULL if the noise map is empty.
///
/// @pre The coordinates must exist within the bounds of the noise
/// map.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
const float* GetConstSlabPtr (int row) const
{
return GetConstSlabPtr (0, row);
}
/// Returns a const pointer to a slab at the specified position.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns A const pointer to a slab at the position ( @a x, @a y ),
/// or @a NULL if the noise map is empty.
///
/// @pre The coordinates must exist within the bounds of the noise
/// map.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
const float* GetConstSlabPtr (int x, int y) const
{
return m_pNoiseMap + (size_t)x + (size_t)m_stride * (size_t)y;
}
/// Returns the height of the noise map.
///
/// @returns The height of the noise map.
int GetHeight () const
{
return m_height;
}
/// Returns the amount of memory allocated for this noise map.
///
/// @returns The amount of memory allocated for this noise map.
///
/// This method returns the number of @a float values allocated.
size_t GetMemUsed () const
{
return m_memUsed;
}
/// Returns a pointer to a slab.
///
/// @returns A pointer to a slab at the position (0, 0), or @a NULL if
/// the noise map is empty.
float* GetSlabPtr ()
{
return m_pNoiseMap;
}
/// Returns a pointer to a slab at the specified row.
///
/// @param row The row, or @a y coordinate.
///
/// @returns A pointer to a slab at the position ( 0, @a row ), or
/// @a NULL if the noise map is empty.
///
/// @pre The coordinates must exist within the bounds of the noise
/// map.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
float* GetSlabPtr (int row)
{
return GetSlabPtr (0, row);
}
/// Returns a pointer to a slab at the specified position.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns A pointer to a slab at the position ( @a x, @a y ) or
/// @a NULL if the noise map is empty.
///
/// @pre The coordinates must exist within the bounds of the noise
/// map.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
float* GetSlabPtr (int x, int y)
{
return m_pNoiseMap + (size_t)x + (size_t)m_stride * (size_t)y;
}
/// Returns the stride amount of the noise map.
///
/// @returns The stride amount of the noise map.
///
/// - The <i>stride amount</i> is the offset between the starting
/// points of any two adjacent slabs in a noise map.
/// - The stride amount is measured by the number of @a float values
/// between these two points, not by the number of bytes.
int GetStride () const
{
return m_stride;
}
/// Returns a value from the specified position in the noise map.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns The value at that position.
///
/// This method returns the border value if the coordinates exist
/// outside of the noise map.
float GetValue (int x, int y) const;
/// Returns the width of the noise map.
///
/// @returns The width of the noise map.
int GetWidth () const
{
return m_width;
}
/// Reallocates the noise map to recover wasted memory.
///
/// @throw noise::ExceptionOutOfMemory Out of memory. (Yes, this
/// method can return an out-of-memory exception because two noise
/// maps will temporarily exist in memory during this call.)
///
/// The contents of the noise map is unaffected.
void ReclaimMem ();
/// Sets the value to use for all positions outside of the noise map.
///
/// @param borderValue The value to use for all positions outside of
/// the noise map.
///
/// All positions outside of the noise map are assumed to have a
/// common value known as the <i>border value</i>.
void SetBorderValue (float borderValue)
{
m_borderValue = borderValue;
}
/// Sets the new size for the noise map.
///
/// @param width The new width for the noise map.
/// @param height The new height for the noise map.
///
/// @pre The width and height values are positive.
/// @pre The width and height values do not exceed the maximum
/// possible width and height for the noise map.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// On exit, the contents of the noise map are undefined.
///
/// If the @a OUT_OF_MEMORY exception occurs, this noise map object
/// becomes empty.
///
/// If the @a INVALID_PARAM exception occurs, the noise map is
/// unmodified.
void SetSize (int width, int height);
/// Sets a value at a specified position in the noise map.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
/// @param value The value to set at the given position.
///
/// This method does nothing if the noise map object is empty or the
/// position is outside the bounds of the noise map.
void SetValue (int x, int y, float value);
/// Takes ownership of the buffer within the source noise map.
///
/// @param source The source noise map.
///
/// On exit, the source noise map object becomes empty.
///
/// This method only moves the buffer pointer so this method is very
/// quick.
void TakeOwnership (NoiseMap& source);
private:
/// Returns the minimum amount of memory required to store a noise map
/// of the specified size.
///
/// @param width The width of the noise map.
/// @param height The height of the noise map.
///
/// @returns The minimum amount of memory required to store the noise
/// map.
///
/// The returned value is measured by the number of @a float values
/// required to store the noise map, not by the number of bytes.
size_t CalcMinMemUsage (int width, int height) const
{
return CalcStride ((size_t)width) * (size_t)height;
}
/// Calculates the stride amount for a noise map.
///
/// @param width The width of the noise map.
///
/// @returns The stride amount.
///
/// - The <i>stride amount</i> is the offset between the starting
/// points of any two adjacent slabs in a noise map.
/// - The stride amount is measured by the number of @a float values
/// between these two points, not by the number of bytes.
size_t CalcStride (int width) const
{
return (size_t)(((width + RASTER_STRIDE_BOUNDARY - 1)
/ RASTER_STRIDE_BOUNDARY) * RASTER_STRIDE_BOUNDARY);
}
/// Copies the contents of the buffer in the source noise map into
/// this noise map.
///
/// @param source The source noise map.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// This method reallocates the buffer in this noise map object if
/// necessary.
///
/// @warning This method calls the standard library function
/// @a memcpy, which probably violates the DMCA because it can be used
//. to make a bitwise copy of anything, like, say, a DVD. Don't call
/// this method if you live in the USA.
void CopyNoiseMap (const NoiseMap& source);
/// Resets the noise map object.
///
/// This method is similar to the InitObj() method, except this method
/// deletes the buffer in this noise map.
void DeleteNoiseMapAndReset ();
/// Initializes the noise map object.
///
/// @pre Must be called during object construction.
/// @pre The noise map buffer must not exist.
void InitObj ();
/// Value used for all positions outside of the noise map.
float m_borderValue;
/// The current height of the noise map.
int m_height;
/// The amount of memory allocated for this noise map.
///
/// This value is equal to the number of @a float values allocated for
/// the noise map, not the number of bytes.
size_t m_memUsed;
/// A pointer to the noise map buffer.
float* m_pNoiseMap;
/// The stride amount of the noise map.
int m_stride;
/// The current width of the noise map.
int m_width;
};
/// Implements an image, a 2-dimensional array of color values.
///
/// An image can be used to store a color texture.
///
/// These color values are of type Color.
///
/// The size (width and height) of the image can be specified during
/// object construction or at any other time.
///
/// The GetValue() and SetValue() methods can be used to access individual
/// color values stored in the image.
///
/// This class manages its own memory. If you copy an image object into
/// another image object, the original contents of the image object will
/// be freed.
///
/// If you specify a new size for the image and the new size is smaller
/// than the current size, the allocated memory will not be reallocated.
/// Call ReclaimMem() to reclaim the wasted memory.
///
/// <b>Border Values</b>
///
/// All of the color values outside of the image are assumed to have a
/// common color value known as the <i>border value</i>.
///
/// To set the border value, call the SetBorderValue() method.
///
/// The GetValue() method returns the border value if the specified
/// position lies outside of the image.
///
/// <b>Internal Image Structure</b>
///
/// Internally, the color values are organized into horizontal rows called
/// @a slabs. Slabs are ordered from bottom to top.
///
/// Each slab contains a contiguous row of color values in memory. The
/// color values in a slab are organized left to right. These values are
/// of type Color.
///
/// The offset between the starting points of any two adjacent slabs is
/// called the <i>stride amount</i>. The stride amount is measured by the
/// number of Color objects between these two starting points, not by the
/// number of bytes. For efficiency reasons, the stride is often a
/// multiple of the machine word size.
///
/// The GetSlabPtr() methods allow you to retrieve pointers to the slabs
/// themselves.
class Image
{
public:
/// Constructor.
///
/// Creates an empty image.
Image ();
/// Constructor.
///
/// @param width The width of the new image.
/// @param height The height of the new image.
///
/// @pre The width and height values are positive.
/// @pre The width and height values do not exceed the maximum
/// possible width and height for the image.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// Creates an image with uninitialized color values.
///
/// It is considered an error if the specified dimensions are not
/// positive.
Image (int width, int height);
/// Copy constructor.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
Image (const Image& rhs);
/// Destructor.
///
/// Frees the allocated memory for the image.
~Image ();
/// Assignment operator.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// @returns Reference to self.
///
/// Creates a copy of the image.
Image& operator= (const Image& rhs);
/// Clears the image to a specified color value.
///
/// @param value The color value that all positions within the image
/// are cleared to.
void Clear (const Color& value);
/// Returns the color value used for all positions outside of the
/// image.
///
/// @returns The color value used for all positions outside of the
/// image.
///
/// All positions outside of the image are assumed to have a common
/// color value known as the <i>border value</i>.
Color GetBorderValue () const
{
return m_borderValue;
}
/// Returns a const pointer to a slab.
///
/// @returns A const pointer to a slab at the position (0, 0), or
/// @a NULL if the image is empty.
const Color* GetConstSlabPtr () const
{
return m_pImage;
}
/// Returns a const pointer to a slab at the specified row.
///
/// @param row The row, or @a y coordinate.
///
/// @returns A const pointer to a slab at the position ( 0, @a row ),
/// or @a NULL if the image is empty.
///
/// @pre The coordinates must exist within the bounds of the image.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
const Color* GetConstSlabPtr (int row) const
{
return GetConstSlabPtr (0, row);
}
/// Returns a const pointer to a slab at the specified position.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns A const pointer to a slab at the position ( @a x, @a y ),
/// or @a NULL if the image is empty.
///
/// @pre The coordinates must exist within the bounds of the image.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
const Color* GetConstSlabPtr (int x, int y) const
{
return m_pImage + (size_t)x + (size_t)m_stride * (size_t)y;
}
/// Returns the height of the image.
///
/// @returns The height of the image.
int GetHeight () const
{
return m_height;
}
/// Returns the amount of memory allocated for this image.
///
/// @returns The amount of memory allocated for this image.
///
/// This method returns the number of Color objects allocated.
size_t GetMemUsed () const
{
return m_memUsed;
}
/// Returns a pointer to a slab.
///
/// @returns A pointer to a slab at the position (0, 0), or @a NULL if
/// the image is empty.
Color* GetSlabPtr ()
{
return m_pImage;
}
/// Returns a pointer to a slab at the specified row.
///
/// @param row The row, or @a y coordinate.
///
/// @returns A pointer to a slab at the position ( 0, @a row ), or
/// @a NULL if the image is empty.
///
/// @pre The coordinates must exist within the bounds of the image.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
Color* GetSlabPtr (int row)
{
return GetSlabPtr (0, row);
}
/// Returns a pointer to a slab at the specified position.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns A pointer to a slab at the position ( @a x, @a y ), or
/// @a NULL if the image is empty.
///
/// @pre The coordinates must exist within the bounds of the image.
///
/// This method does not perform bounds checking so be careful when
/// calling it.
Color* GetSlabPtr (int x, int y)
{
return m_pImage + (size_t)x + (size_t)m_stride * (size_t)y;
}
/// Returns the stride amount of the image.
///
/// @returns The stride amount of the image.
///
/// - The <i>stride amount</i> is the offset between the starting
/// points of any two adjacent slabs in an image.
/// - The stride amount is measured by the number of Color objects
/// between these two points, not by the number of bytes.
int GetStride () const
{
return m_stride;
}
/// Returns a color value from the specified position in the image.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
///
/// @returns The color value at that position.
///
/// This method returns the border value if the coordinates exist
/// outside of the image.
Color GetValue (int x, int y) const;
/// Returns the width of the image.
///
/// @returns The width of the image.
int GetWidth () const
{
return m_width;
}
/// Reallocates the image to recover wasted memory.
///
/// @throw noise::ExceptionOutOfMemory Out of memory. (Yes, this
/// method can return an out-of-memory exception because two images
/// will exist temporarily in memory during this call.)
///
/// The contents of the image is unaffected.
void ReclaimMem ();
/// Sets the color value to use for all positions outside of the
/// image.
///
/// @param borderValue The color value to use for all positions
/// outside of the image.
///
/// All positions outside of the image are assumed to have a common
/// color value known as the <i>border value</i>.
void SetBorderValue (const Color& borderValue)
{
m_borderValue = borderValue;
}
/// Sets the new size for the image.
///
/// @param width The new width for the image.
/// @param height The new height for the image.
///
/// @pre The width and height values are positive.
/// @pre The width and height values do not exceed the maximum
/// possible width and height for the image.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// On exit, the contents of the image are undefined.
///
/// If the @a OUT_OF_MEMORY exception occurs, this image becomes
/// empty.
///
/// If the @a INVALID_PARAM exception occurs, the image is unmodified.
void SetSize (int width, int height);
/// Sets a color value at a specified position in the image.
///
/// @param x The x coordinate of the position.
/// @param y The y coordinate of the position.
/// @param value The color value to set at the given position.
///
/// This method does nothing if the image is empty or the position is
/// outside the bounds of the image.
void SetValue (int x, int y, const Color& value);
/// Takes ownership of the buffer within the source image.
///
/// @param source The source image.
///
/// On exit, the source image object becomes empty.
///
/// This method only moves the buffer pointer so this method is very
/// quick.
void TakeOwnership (Image& source);
private:
/// Returns the minimum amount of memory required to store an image of
/// the specified size.
///
/// @param width The width of the image.
/// @param height The height of the image.
///
/// @returns The minimum amount of memory required to store the image.
///
/// The returned color value is measured by the number of Color
/// objects required to store the image, not by the number of bytes.
size_t CalcMinMemUsage (int width, int height) const
{
return CalcStride ((size_t)width) * (size_t)height;
}
/// Calculates the stride amount for an image.
///
/// @param width The width of the image.
///
/// @returns The stride amount.
///
/// - The <i>stride amount</i> is the offset between the starting
/// points of any two adjacent slabs in an image.
/// - The stride amount is measured by the number of Color objects
/// between these two points, not by the number of bytes.
size_t CalcStride (int width) const
{
return (size_t)(((width + RASTER_STRIDE_BOUNDARY - 1)
/ RASTER_STRIDE_BOUNDARY) * RASTER_STRIDE_BOUNDARY);
}
/// Copies the contents of the buffer in the source image into this
/// image.
///
/// @param source The source image.
///
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// This method reallocates the buffer in this image object if
/// necessary.
///
/// @warning This method calls the standard library function
/// @a memcpy, which probably violates the DMCA because it can be used
/// to make a bitwise copy of anything, like, say, a DVD. Don't call
/// this method if you live in the USA.
void CopyImage (const Image& source);
/// Resets the image object.
///
/// This method is similar to the InitObj() method, except this method
/// deletes the memory allocated to the image.
void DeleteImageAndReset ();
/// Initializes the image object.
///
/// @pre Must be called during object construction.
/// @pre The image buffer must not exist.
void InitObj ();
/// The Color value used for all positions outside of the image.
Color m_borderValue;
/// The current height of the image.
int m_height;
/// The amount of memory allocated for the image.
///
/// This value is equal to the number of Color objects allocated for
/// the image, not the number of bytes.
size_t m_memUsed;
/// A pointer to the image buffer.
Color* m_pImage;
/// The stride amount of the image.
int m_stride;
/// The current width of the image.
int m_width;
};
/// Windows bitmap image writer class.
///
/// This class creates a file in Windows bitmap (*.bmp) format given the
/// contents of an image object.
///
/// <b>Writing the image</b>
///
/// To write the image to a file, perform the following steps:
/// - Pass the filename to the SetDestFilename() method.
/// - Pass an Image object to the SetSourceImage() method.
/// - Call the WriteDestFile() method.
///
/// The SetDestFilename() and SetSourceImage() methods must be called
/// before calling the WriteDestFile() method.
class WriterBMP
{
public:
/// Constructor.
WriterBMP ():
m_pSourceImage (NULL)
{
}
/// Returns the name of the file to write.
///
/// @returns The name of the file to write.
std::string GetDestFilename () const
{
return m_destFilename;
}
/// Sets the name of the file to write.
///
/// @param filename The name of the file to write.
///
/// Call this method before calling the WriteDestFile() method.
void SetDestFilename (const std::string& filename)
{
m_destFilename = filename;
}
/// Sets the image object that is written to the file.
///
/// @param sourceImage The image object to write.
///
/// This object only stores a pointer to an image object, so make sure
/// this object exists before calling the WriteDestFile() method.
void SetSourceImage (Image& sourceImage)
{
m_pSourceImage = &sourceImage;
}
/// Writes the contents of the image object to the file.
///
/// @pre SetDestFilename() has been previously called.
/// @pre SetSourceImage() has been previously called.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
/// @throw noise::ExceptionUnknown An unknown exception occurred.
/// Possibly the file could not be written.
///
/// This method encodes the contents of the image and writes it to a
/// file. Before calling this method, call the SetSourceImage()
/// method to specify the image, then call the SetDestFilename()
/// method to specify the name of the file to write.
void WriteDestFile ();
protected:
/// Calculates the width of one horizontal line in the file, in bytes.
///
/// @param width The width of the image, in points.
///
/// @returns The width of one horizontal line in the file.
///
/// Windows bitmap files require that the width of one horizontal line
/// must be aligned to a 32-bit boundary.
int CalcWidthByteCount (int width) const;
/// Name of the file to write.
std::string m_destFilename;
/// A pointer to the image object that will be written to the file.
Image* m_pSourceImage;
};
/// Terragen Terrain writer class.
///
/// This class creates a file in Terrage Terrain (*.ter) format given the
/// contents of a noise map object. This class treats the values in the
/// noise map as elevations measured in meters.
///
/// <a href=http://www.planetside.co.uk/terragen/>Terragen</a> is a
/// terrain application that renders realistic landscapes. Terragen is
/// available for Windows and MacOS; unfortunately, Terragen does not have
/// UN*X versions.
///
/// <b>Writing the noise map</b>
///
/// To write the noise map, perform the following steps:
/// - Pass the filename to the SetDestFilename() method.
/// - Pass a NoiseMap object to the SetSourceNoiseMap() method.
/// - Call the WriteDestFile() method.
///
/// The SetDestFilename() and SetSourceNoiseMap() methods must be called
/// before calling the WriteDestFile() method.
class WriterTER
{
public:
/// Constructor.
WriterTER ():
m_pSourceNoiseMap (NULL),
m_metersPerPoint (DEFAULT_METERS_PER_POINT)
{
}
/// Returns the name of the file to write.
///
/// @returns The name of the file to write.
std::string GetDestFilename () const
{
return m_destFilename;
}
/// Returns the distance separating adjacent points in the noise map,
/// in meters.
///
/// @returns The distance separating adjacent points in the noise map.
float GetMetersPerPoint () const
{
return m_metersPerPoint;
}
/// Sets the name of the file to write.
///
/// @param filename The name of the file to write.
///
/// Call this method before calling the WriteDestFile() method.
void SetDestFilename (const std::string& filename)
{
m_destFilename = filename;
}
/// Sets the distance separating adjacent points in the noise map, in
/// meters.
///
/// @param metersPerPoint The distance separating adjacent points in
/// the noise map.
void SetMetersPerPoint (float metersPerPoint)
{
m_metersPerPoint = metersPerPoint;
}
/// Sets the noise map object that is written to the file.
///
/// @param sourceNoiseMap The noise map object to write.
///
/// This object only stores a pointer to a noise map object, so make
/// sure this object exists before calling the WriteDestFile() method.
void SetSourceNoiseMap (NoiseMap& sourceNoiseMap)
{
m_pSourceNoiseMap = &sourceNoiseMap;
}
/// Writes the contents of the noise map object to the file.
///
/// @pre SetDestFilename() has been previously called.
/// @pre SetSourceNoiseMap() has been previously called.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
/// @throw noise::ExceptionUnknown An unknown exception occurred.
/// Possibly the file could not be written.
///
/// This method encodes the contents of the noise map and writes it to
/// a file. Before calling this method, call the SetSourceNoiseMap()
/// method to specify the noise map, then call the SetDestFilename()
/// method to specify the name of the file to write.
///
/// This object assumes that the noise values represent elevations in
/// meters.
void WriteDestFile ();
protected:
/// Calculates the width of one horizontal line in the file, in bytes.
///
/// @param width The width of the noise map, in points.
///
/// @returns The width of one horizontal line in the file.
int CalcWidthByteCount (int width) const;
/// Name of the file to write.
std::string m_destFilename;
/// The distance separating adjacent points in the noise map, in
/// meters.
float m_metersPerPoint;
/// A pointer to the noise map that will be written to the file.
NoiseMap* m_pSourceNoiseMap;
};
/// Abstract base class for a noise-map builder
///
/// A builder class builds a noise map by filling it with coherent-noise
/// values generated from the surface of a three-dimensional mathematical
/// object. Each builder class defines a specific three-dimensional
/// surface, such as a cylinder, sphere, or plane.
///
/// A builder class describes these input values using a coordinate system
/// applicable for the mathematical object (e.g., a latitude/longitude
/// coordinate system for the spherical noise-map builder.) It then
/// "flattens" these coordinates onto a plane so that it can write the
/// coherent-noise values into a two-dimensional noise map.
///
/// <b>Building the Noise Map</b>
///
/// To build the noise map, perform the following steps:
/// - Pass the bounding coordinates to the SetBounds() method.
/// - Pass the noise map size, in points, to the SetDestSize() method.
/// - Pass a NoiseMap object to the SetDestNoiseMap() method.
/// - Pass a noise module (derived from noise::module::Module) to the
/// SetSourceModule() method.
/// - Call the Build() method.
///
/// You may also pass a callback function to the SetCallback() method.
/// The Build() method calls this callback function each time it fills a
/// row of the noise map with coherent-noise values. This callback
/// function has a single integer parameter that contains a count of the
/// rows that have been completed. It returns void.
///
/// Note that SetBounds() is not defined in the abstract base class; it is
/// only defined in the derived classes. This is because each model uses
/// a different coordinate system.
class NoiseMapBuilder
{
public:
/// Constructor.
NoiseMapBuilder ();
/// Builds the noise map.
///
/// @pre SetBounds() was previously called.
/// @pre SetDestNoiseMap() was previously called.
/// @pre SetSourceModule() was previously called.
/// @pre The width and height values specified by SetDestSize() are
/// positive.
/// @pre The width and height values specified by SetDestSize() do not
/// exceed the maximum possible width and height for the noise map.
///
/// @post The original contents of the destination noise map is
/// destroyed.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
/// @throw noise::ExceptionOutOfMemory Out of memory.
///
/// If this method is successful, the destination noise map contains
/// the coherent-noise values from the noise module specified by
/// SetSourceModule().
virtual void Build () = 0;
/// Returns the height of the destination noise map.
///
/// @returns The height of the destination noise map, in points.
///
/// This object does not change the height in the destination noise
/// map object until the Build() method is called.
double GetDestHeight () const
{
return m_destHeight;
}
/// Returns the width of the destination noise map.
///
/// @returns The width of the destination noise map, in points.
///
/// This object does not change the height in the destination noise
/// map object until the Build() method is called.
double GetDestWidth () const
{
return m_destWidth;
}
/// Sets the callback function that Build() calls each time it fills a
/// row of the noise map with coherent-noise values.
///
/// @param pCallback The callback function.
///
/// This callback function has a single integer parameter that
/// contains a count of the rows that have been completed. It returns
/// void. Pass a function with this signature to the SetCallback()
/// method.
void SetCallback (NoiseMapCallback pCallback);
/// Sets the destination noise map.
///
/// @param destNoiseMap The destination noise map.
///
/// The destination noise map will contain the coherent-noise values
/// from this noise map after a successful call to the Build() method.
///
/// The destination noise map must exist throughout the lifetime of
/// this object unless another noise map replaces that noise map.
void SetDestNoiseMap (NoiseMap& destNoiseMap)
{
m_pDestNoiseMap = &destNoiseMap;
}
/// Sets the source module.
///
/// @param sourceModule The source module.
///
/// This object fills in a noise map with the coherent-noise values
/// from this source module.
///
/// The source module must exist throughout the lifetime of this
/// object unless another noise module replaces that noise module.
void SetSourceModule (const module::Module& sourceModule)
{
m_pSourceModule = &sourceModule;
}
/// Sets the size of the destination noise map.
///
/// @param destWidth The width of the destination noise map, in
/// points.
/// @param destHeight The height of the destination noise map, in
/// points.
///
/// This method does not change the size of the destination noise map
/// until the Build() method is called.
void SetDestSize (int destWidth, int destHeight)
{
m_destWidth = destWidth ;
m_destHeight = destHeight;
}
protected:
/// The callback function that Build() calls each time it fills a row
/// of the noise map with coherent-noise values.
///
/// This callback function has a single integer parameter that
/// contains a count of the rows that have been completed. It returns
/// void. Pass a function with this signature to the SetCallback()
/// method.
NoiseMapCallback m_pCallback;
/// Height of the destination noise map, in points.
int m_destHeight;
/// Width of the destination noise map, in points.
int m_destWidth;
/// Destination noise map that will contain the coherent-noise values.
NoiseMap* m_pDestNoiseMap;
/// Source noise module that will generate the coherent-noise values.
const module::Module* m_pSourceModule;
};
/// Builds a cylindrical noise map.
///
/// This class builds a noise map by filling it with coherent-noise values
/// generated from the surface of a cylinder.
///
/// This class describes these input values using an (angle, height)
/// coordinate system. After generating the coherent-noise value from the
/// input value, it then "flattens" these coordinates onto a plane so that
/// it can write the values into a two-dimensional noise map.
///
/// The cylinder model has a radius of 1.0 unit and has infinite height.
/// The cylinder is oriented along the @a y axis. Its center is at the
/// origin.
///
/// The x coordinate in the noise map represents the angle around the
/// cylinder's y axis. The y coordinate in the noise map represents the
/// height above the x-z plane.
///
/// The application must provide the lower and upper angle bounds of the
/// noise map, in degrees, and the lower and upper height bounds of the
/// noise map, in units.
class NoiseMapBuilderCylinder: public NoiseMapBuilder
{
public:
/// Constructor.
NoiseMapBuilderCylinder ();
virtual void Build ();
/// Returns the lower angle boundary of the cylindrical noise map.
///
/// @returns The lower angle boundary of the noise map, in degrees.
double GetLowerAngleBound () const
{
return m_lowerAngleBound;
}
/// Returns the lower height boundary of the cylindrical noise map.
///
/// @returns The lower height boundary of the noise map, in units.
///
/// One unit is equal to the radius of the cylinder.
double GetLowerHeightBound () const
{
return m_lowerHeightBound;
}
/// Returns the upper angle boundary of the cylindrical noise map.
///
/// @returns The upper angle boundary of the noise map, in degrees.
double GetUpperAngleBound () const
{
return m_upperAngleBound;
}
/// Returns the upper height boundary of the cylindrical noise map.
///
/// @returns The upper height boundary of the noise map, in units.
///
/// One unit is equal to the radius of the cylinder.
double GetUpperHeightBound () const
{
return m_upperHeightBound;
}
/// Sets the coordinate boundaries of the noise map.
///
/// @param lowerAngleBound The lower angle boundary of the noise map,
/// in degrees.
/// @param upperAngleBound The upper angle boundary of the noise map,
/// in degrees.
/// @param lowerHeightBound The lower height boundary of the noise
/// map, in units.
/// @param upperHeightBound The upper height boundary of the noise
/// map, in units.
///
/// @pre The lower angle boundary is less than the upper angle
/// boundary.
/// @pre The lower height boundary is less than the upper height
/// boundary.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
///
/// One unit is equal to the radius of the cylinder.
void SetBounds (double lowerAngleBound, double upperAngleBound,
double lowerHeightBound, double upperHeightBound)
{
if (lowerAngleBound >= upperAngleBound
|| lowerHeightBound >= upperHeightBound) {
throw noise::ExceptionInvalidParam ();
}
m_lowerAngleBound = lowerAngleBound ;
m_upperAngleBound = upperAngleBound ;
m_lowerHeightBound = lowerHeightBound;
m_upperHeightBound = upperHeightBound;
}
private:
/// Lower angle boundary of the cylindrical noise map, in degrees.
double m_lowerAngleBound;
/// Lower height boundary of the cylindrical noise map, in units.
double m_lowerHeightBound;
/// Upper angle boundary of the cylindrical noise map, in degrees.
double m_upperAngleBound;
/// Upper height boundary of the cylindrical noise map, in units.
double m_upperHeightBound;
};
/// Builds a planar noise map.
///
/// This class builds a noise map by filling it with coherent-noise values
/// generated from the surface of a plane.
///
/// This class describes these input values using (x, z) coordinates.
/// Their y coordinates are always 0.0.
///
/// The application must provide the lower and upper x coordinate bounds
/// of the noise map, in units, and the lower and upper z coordinate
/// bounds of the noise map, in units.
///
/// To make a tileable noise map with no seams at the edges, call the
/// EnableSeamless() method.
class NoiseMapBuilderPlane: public NoiseMapBuilder
{
public:
/// Constructor.
NoiseMapBuilderPlane ();
virtual void Build ();
/// Enables or disables seamless tiling.
///
/// @param enable A flag that enables or disables seamless tiling.
///
/// Enabling seamless tiling builds a noise map with no seams at the
/// edges. This allows the noise map to be tileable.
void EnableSeamless (bool enable = true)
{
m_isSeamlessEnabled = enable;
}
/// Returns the lower x boundary of the planar noise map.
///
/// @returns The lower x boundary of the planar noise map, in units.
double GetLowerXBound () const
{
return m_lowerXBound;
}
/// Returns the lower z boundary of the planar noise map.
///
/// @returns The lower z boundary of the noise map, in units.
double GetLowerZBound () const
{
return m_lowerZBound;
}
/// Returns the upper x boundary of the planar noise map.
///
/// @returns The upper x boundary of the noise map, in units.
double GetUpperXBound () const
{
return m_upperXBound;
}
/// Returns the upper z boundary of the planar noise map.
///
/// @returns The upper z boundary of the noise map, in units.
double GetUpperZBound () const
{
return m_upperZBound;
}
/// Determines if seamless tiling is enabled.
///
/// @returns
/// - @a true if seamless tiling is enabled.
/// - @a false if seamless tiling is disabled.
///
/// Enabling seamless tiling builds a noise map with no seams at the
/// edges. This allows the noise map to be tileable.
bool IsSeamlessEnabled () const
{
return m_isSeamlessEnabled;
}
/// Sets the boundaries of the planar noise map.
///
/// @param lowerXBound The lower x boundary of the noise map, in
/// units.
/// @param upperXBound The upper x boundary of the noise map, in
/// units.
/// @param lowerZBound The lower z boundary of the noise map, in
/// units.
/// @param upperZBound The upper z boundary of the noise map, in
/// units.
///
/// @pre The lower x boundary is less than the upper x boundary.
/// @pre The lower z boundary is less than the upper z boundary.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
void SetBounds (double lowerXBound, double upperXBound,
double lowerZBound, double upperZBound)
{
if (lowerXBound >= upperXBound
|| lowerZBound >= upperZBound) {
throw noise::ExceptionInvalidParam ();
}
m_lowerXBound = lowerXBound;
m_upperXBound = upperXBound;
m_lowerZBound = lowerZBound;
m_upperZBound = upperZBound;
}
private:
/// A flag specifying whether seamless tiling is enabled.
bool m_isSeamlessEnabled;
/// Lower x boundary of the planar noise map, in units.
double m_lowerXBound;
/// Lower z boundary of the planar noise map, in units.
double m_lowerZBound;
/// Upper x boundary of the planar noise map, in units.
double m_upperXBound;
/// Upper z boundary of the planar noise map, in units.
double m_upperZBound;
};
/// Builds a spherical noise map.
///
/// This class builds a noise map by filling it with coherent-noise values
/// generated from the surface of a sphere.
///
/// This class describes these input values using a (latitude, longitude)
/// coordinate system. After generating the coherent-noise value from the
/// input value, it then "flattens" these coordinates onto a plane so that
/// it can write the values into a two-dimensional noise map.
///
/// The sphere model has a radius of 1.0 unit. Its center is at the
/// origin.
///
/// The x coordinate in the noise map represents the longitude. The y
/// coordinate in the noise map represents the latitude.
///
/// The application must provide the southern, northern, western, and
/// eastern bounds of the noise map, in degrees.
class NoiseMapBuilderSphere: public NoiseMapBuilder
{
public:
/// Constructor.
NoiseMapBuilderSphere ();
virtual void Build ();
/// Returns the eastern boundary of the spherical noise map.
///
/// @returns The eastern boundary of the noise map, in degrees.
double GetEastLonBound () const
{
return m_eastLonBound;
}
/// Returns the northern boundary of the spherical noise map
///
/// @returns The northern boundary of the noise map, in degrees.
double GetNorthLatBound () const
{
return m_northLatBound;
}
/// Returns the southern boundary of the spherical noise map
///
/// @returns The southern boundary of the noise map, in degrees.
double GetSouthLatBound () const
{
return m_southLatBound;
}
/// Returns the western boundary of the spherical noise map
///
/// @returns The western boundary of the noise map, in degrees.
double GetWestLonBound () const
{
return m_westLonBound;
}
/// Sets the coordinate boundaries of the noise map.
///
/// @param southLatBound The southern boundary of the noise map, in
/// degrees.
/// @param northLatBound The northern boundary of the noise map, in
/// degrees.
/// @param westLonBound The western boundary of the noise map, in
/// degrees.
/// @param eastLonBound The eastern boundary of the noise map, in
/// degrees.
///
/// @pre The southern boundary is less than the northern boundary.
/// @pre The western boundary is less than the eastern boundary.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
void SetBounds (double southLatBound, double northLatBound,
double westLonBound, double eastLonBound)
{
if (southLatBound >= northLatBound
|| westLonBound >= eastLonBound) {
throw noise::ExceptionInvalidParam ();
}
m_southLatBound = southLatBound;
m_northLatBound = northLatBound;
m_westLonBound = westLonBound ;
m_eastLonBound = eastLonBound ;
}
private:
/// Eastern boundary of the spherical noise map, in degrees.
double m_eastLonBound;
/// Northern boundary of the spherical noise map, in degrees.
double m_northLatBound;
/// Southern boundary of the spherical noise map, in degrees.
double m_southLatBound;
/// Western boundary of the spherical noise map, in degrees.
double m_westLonBound;
};
/// Renders an image from a noise map.
///
/// This class renders an image given the contents of a noise-map object.
///
/// An application can configure the output of the image in three ways:
/// - Specify the color gradient.
/// - Specify the light source parameters.
/// - Specify the background image.
///
/// <b>Specify the color gradient</b>
///
/// This class uses a color gradient to calculate the color for each pixel
/// in the destination image according to the value from the corresponding
/// position in the noise map.
///
/// A color gradient is a list of gradually-changing colors. A color
/// gradient is defined by a list of <i>gradient points</i>. Each
/// gradient point has a position and a color. In a color gradient, the
/// colors between two adjacent gradient points are linearly interpolated.
///
/// For example, suppose this class contains the following color gradient:
///
/// - -1.0 maps to dark blue.
/// - -0.2 maps to light blue.
/// - -0.1 maps to tan.
/// - 0.0 maps to green.
/// - 1.0 maps to white.
///
/// The value 0.5 maps to a greenish-white color because 0.5 is halfway
/// between 0.0 (mapped to green) and 1.0 (mapped to white).
///
/// The value -0.6 maps to a medium blue color because -0.6 is halfway
/// between -1.0 (mapped to dark blue) and -0.2 (mapped to light blue).
///
/// The color gradient requires a minimum of two gradient points.
///
/// This class contains two pre-made gradients: a grayscale gradient and a
/// color gradient suitable for terrain. To use these pre-made gradients,
/// call the BuildGrayscaleGradient() or BuildTerrainGradient() methods,
/// respectively.
///
/// @note The color value passed to AddGradientPoint() has an alpha
/// channel. This alpha channel specifies how a pixel in the background
/// image (if specified) is blended with the calculated color. If the
/// alpha value is high, this class weighs the blend towards the
/// calculated color, and if the alpha value is low, this class weighs the
/// blend towards the color from the corresponding pixel in the background
/// image.
///
/// <b>Specify the light source parameters</b>
///
/// This class contains a parallel light source that lights the image. It
/// interprets the noise map as a bump map.
///
/// To enable or disable lighting, pass a Boolean value to the
/// EnableLight() method.
///
/// To set the position of the light source in the "sky", call the
/// SetLightAzimuth() and SetLightElev() methods.
///
/// To set the color of the light source, call the SetLightColor() method.
///
/// To set the intensity of the light source, call the SetLightIntensity()
/// method. A good intensity value is 2.0, although that value tends to
/// "wash out" very light colors from the image.
///
/// To set the contrast amount between areas in light and areas in shadow,
/// call the SetLightContrast() method. Determining the correct contrast
/// amount requires some trial and error, but if your application
/// interprets the noise map as a height map that has its elevation values
/// measured in meters and has a horizontal resolution of @a h meters, a
/// good contrast amount to use is ( 1.0 / @a h ).
///
/// <b>Specify the background image</b>
///
/// To specify a background image, pass an Image object to the
/// SetBackgroundImage() method.
///
/// This class determines the color of a pixel in the destination image by
/// blending the calculated color with the color of the corresponding
/// pixel from the background image.
///
/// The blend amount is determined by the alpha of the calculated color.
/// If the alpha value is high, this class weighs the blend towards the
/// calculated color, and if the alpha value is low, this class weighs the
/// blend towards the color from the corresponding pixel in the background
/// image.
///
/// <b>Rendering the image</b>
///
/// To render the image, perform the following steps:
/// - Pass a NoiseMap object to the SetSourceNoiseMap() method.
/// - Pass an Image object to the SetDestImage() method.
/// - Pass an Image object to the SetBackgroundImage() method (optional)
/// - Call the Render() method.
class RendererImage
{
public:
/// Constructor.
RendererImage ();
/// Adds a gradient point to this gradient object.
///
/// @param gradientPos The position of this gradient point.
/// @param gradientColor The color of this gradient point.
///
/// @pre No two gradient points have the same position.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
///
/// This object uses a color gradient to calculate the color for each
/// pixel in the destination image according to the value from the
/// corresponding position in the noise map.
///
/// The gradient requires a minimum of two gradient points.
///
/// The specified color value passed to this method has an alpha
/// channel. This alpha channel specifies how a pixel in the
/// background image (if specified) is blended with the calculated
/// color. If the alpha value is high, this object weighs the blend
/// towards the calculated color, and if the alpha value is low, this
/// object weighs the blend towards the color from the corresponding
/// pixel in the background image.
void AddGradientPoint (double gradientPos,
const Color& gradientColor);
/// Builds a grayscale gradient.
///
/// @post The original gradient is cleared and a grayscale gradient is
/// created.
///
/// This color gradient contains the following gradient points:
/// - -1.0 maps to black
/// - 1.0 maps to white
void BuildGrayscaleGradient ();
/// Builds a color gradient suitable for terrain.
///
/// @post The original gradient is cleared and a terrain gradient is
/// created.
///
/// This gradient color at position 0.0 is the "sea level". Above
/// that value, the gradient contains greens, browns, and whites.
/// Below that value, the gradient contains various shades of blue.
void BuildTerrainGradient ();
/// Clears the color gradient.
///
/// Before calling the Render() method, the application must specify a
/// new color gradient with at least two gradient points.
void ClearGradient ();
/// Enables or disables the light source.
///
/// @param enable A flag that enables or disables the light source.
///
/// If the light source is enabled, this object will interpret the
/// noise map as a bump map.
void EnableLight (bool enable = true)
{
m_isLightEnabled = enable;
}
/// Enables or disables noise-map wrapping.
///
/// @param enable A flag that enables or disables noise-map wrapping.
///
/// This object requires five points (the initial point and its four
/// neighbors) to calculate light shading. If wrapping is enabled,
/// and the initial point is on the edge of the noise map, the
/// appropriate neighbors that lie outside of the noise map will
/// "wrap" to the opposite side(s) of the noise map. Otherwise, the
/// appropriate neighbors are cropped to the edge of the noise map.
///
/// Enabling wrapping is useful when creating spherical renderings and
/// tileable textures.
void EnableWrap (bool enable = true)
{
m_isWrapEnabled = enable;
}
/// Returns the azimuth of the light source, in degrees.
///
/// @returns The azimuth of the light source.
///
/// The azimuth is the location of the light source around the
/// horizon:
/// - 0.0 degrees is east.
/// - 90.0 degrees is north.
/// - 180.0 degrees is west.
/// - 270.0 degrees is south.
double GetLightAzimuth () const
{
return m_lightAzimuth;
}
/// Returns the brightness of the light source.
///
/// @returns The brightness of the light source.
double GetLightBrightness () const
{
return m_lightBrightness;
}
/// Returns the color of the light source.
///
/// @returns The color of the light source.
Color GetLightColor () const
{
return m_lightColor;
}
/// Returns the contrast of the light source.
///
/// @returns The contrast of the light source.
///
/// The contrast specifies how sharp the boundary is between the
/// light-facing areas and the shadowed areas.
///
/// The contrast determines the difference between areas in light and
/// areas in shadow. Determining the correct contrast amount requires
/// some trial and error, but if your application interprets the noise
/// map as a height map that has a spatial resolution of @a h meters
/// and an elevation resolution of 1 meter, a good contrast amount to
/// use is ( 1.0 / @a h ).
double GetLightContrast () const
{
return m_lightContrast;
}
/// Returns the elevation of the light source, in degrees.
///
/// @returns The elevation of the light source.
///
/// The elevation is the angle above the horizon:
/// - 0 degrees is on the horizon.
/// - 90 degrees is straight up.
double GetLightElev () const
{
return m_lightElev;
}
/// Returns the intensity of the light source.
///
/// @returns The intensity of the light source.
double GetLightIntensity () const
{
return m_lightIntensity;
}
/// Determines if the light source is enabled.
///
/// @returns
/// - @a true if the light source is enabled.
/// - @a false if the light source is disabled.
bool IsLightEnabled () const
{
return m_isLightEnabled;
}
/// Determines if noise-map wrapping is enabled.
///
/// @returns
/// - @a true if noise-map wrapping is enabled.
/// - @a false if noise-map wrapping is disabled.
///
/// This object requires five points (the initial point and its four
/// neighbors) to calculate light shading. If wrapping is enabled,
/// and the initial point is on the edge of the noise map, the
/// appropriate neighbors that lie outside of the noise map will
/// "wrap" to the opposite side(s) of the noise map. Otherwise, the
/// appropriate neighbors are cropped to the edge of the noise map.
///
/// Enabling wrapping is useful when creating spherical renderings and
/// tileable textures
bool IsWrapEnabled () const
{
return m_isWrapEnabled;
}
/// Renders the destination image using the contents of the source
/// noise map and an optional background image.
///
/// @pre SetSourceNoiseMap() has been previously called.
/// @pre SetDestImage() has been previously called.
/// @pre There are at least two gradient points in the color gradient.
/// @pre No two gradient points have the same position.
/// @pre If a background image was specified, it has the exact same
/// size as the source height map.
///
/// @post The original contents of the destination image is destroyed.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
///
/// The background image and the destination image can safely refer to
/// the same image, although in this case, the destination image is
/// irretrievably blended into the background image.
void Render ();
/// Sets the background image.
///
/// @param backgroundImage The background image.
///
/// If a background image has been specified, the Render() method
/// blends the pixels from the background image onto the corresponding
/// pixels in the destination image. The blending weights are
/// determined by the alpha channel in the pixels in the destination
/// image.
///
/// The destination image must exist throughout the lifetime of this
/// object unless another image replaces that image.
void SetBackgroundImage (const Image& backgroundImage)
{
m_pBackgroundImage = &backgroundImage;
}
/// Sets the destination image.
///
/// @param destImage The destination image.
///
/// The destination image will contain the rendered image after a
/// successful call to the Render() method.
///
/// The destination image must exist throughout the lifetime of this
/// object unless another image replaces that image.
void SetDestImage (Image& destImage)
{
m_pDestImage = &destImage;
}
/// Sets the azimuth of the light source, in degrees.
///
/// @param lightAzimuth The azimuth of the light source.
///
/// The azimuth is the location of the light source around the
/// horizon:
/// - 0.0 degrees is east.
/// - 90.0 degrees is north.
/// - 180.0 degrees is west.
/// - 270.0 degrees is south.
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightAzimuth (double lightAzimuth)
{
m_lightAzimuth = lightAzimuth;
m_recalcLightValues = true;
}
/// Sets the brightness of the light source.
///
/// @param lightBrightness The brightness of the light source.
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightBrightness (double lightBrightness)
{
m_lightBrightness = lightBrightness;
m_recalcLightValues = true;
}
/// Sets the color of the light source.
///
/// @param lightColor The light color.
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightColor (const Color& lightColor)
{
m_lightColor = lightColor;
}
/// Sets the contrast of the light source.
///
/// @param lightContrast The contrast of the light source.
///
/// @pre The specified light contrast is positive.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
///
/// The contrast specifies how sharp the boundary is between the
/// light-facing areas and the shadowed areas.
///
/// The contrast determines the difference between areas in light and
/// areas in shadow. Determining the correct contrast amount requires
/// some trial and error, but if your application interprets the noise
/// map as a height map that has a spatial resolution of @a h meters
/// and an elevation resolution of 1 meter, a good contrast amount to
/// use is ( 1.0 / @a h ).
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightContrast (double lightContrast)
{
if (lightContrast <= 0.0) {
throw noise::ExceptionInvalidParam ();
}
m_lightContrast = lightContrast;
m_recalcLightValues = true;
}
/// Sets the elevation of the light source, in degrees.
///
/// @param lightElev The elevation of the light source.
///
/// The elevation is the angle above the horizon:
/// - 0 degrees is on the horizon.
/// - 90 degrees is straight up.
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightElev (double lightElev)
{
m_lightElev = lightElev;
m_recalcLightValues = true;
}
/// Returns the intensity of the light source.
///
/// @returns The intensity of the light source.
///
/// A good value for intensity is 2.0.
///
/// Make sure the light source is enabled via a call to the
/// EnableLight() method before calling the Render() method.
void SetLightIntensity (double lightIntensity)
{
if (lightIntensity < 0.0) {
throw noise::ExceptionInvalidParam ();
}
m_lightIntensity = lightIntensity;
m_recalcLightValues = true;
}
/// Sets the source noise map.
///
/// @param sourceNoiseMap The source noise map.
///
/// The destination image must exist throughout the lifetime of this
/// object unless another image replaces that image.
void SetSourceNoiseMap (const NoiseMap& sourceNoiseMap)
{
m_pSourceNoiseMap = &sourceNoiseMap;
}
private:
/// Calculates the destination color.
///
/// @param sourceColor The source color generated from the color
/// gradient.
/// @param backgroundColor The color from the background image at the
/// corresponding position.
/// @param lightValue The intensity of the light at that position.
///
/// @returns The destination color.
Color CalcDestColor (const Color& sourceColor,
const Color& backgroundColor, double lightValue) const;
/// Calculates the intensity of the light given some elevation values.
///
/// @param center Elevation of the center point.
/// @param left Elevation of the point directly left of the center
/// point.
/// @param right Elevation of the point directly right of the center
/// point.
/// @param down Elevation of the point directly below the center
/// point.
/// @param up Elevation of the point directly above the center point.
///
/// These values come directly from the noise map.
double CalcLightIntensity (double center, double left, double right,
double down, double up) const;
/// The cosine of the azimuth of the light source.
mutable double m_cosAzimuth;
/// The cosine of the elevation of the light source.
mutable double m_cosElev;
/// The color gradient used to specify the image colors.
GradientColor m_gradient;
/// A flag specifying whether lighting is enabled.
bool m_isLightEnabled;
/// A flag specifying whether wrapping is enabled.
bool m_isWrapEnabled;
/// The azimuth of the light source, in degrees.
double m_lightAzimuth;
/// The brightness of the light source.
double m_lightBrightness;
/// The color of the light source.
Color m_lightColor;
/// The contrast between areas in light and areas in shadow.
double m_lightContrast;
/// The elevation of the light source, in degrees.
double m_lightElev;
/// The intensity of the light source.
double m_lightIntensity;
/// A pointer to the background image.
const Image* m_pBackgroundImage;
/// A pointer to the destination image.
Image* m_pDestImage;
/// A pointer to the source noise map.
const NoiseMap* m_pSourceNoiseMap;
/// Used by the CalcLightIntensity() method to recalculate the light
/// values only if the light parameters change.
///
/// When the light parameters change, this value is set to True. When
/// the CalcLightIntensity() method is called, this value is set to
/// false.
mutable bool m_recalcLightValues;
/// The sine of the azimuth of the light source.
mutable double m_sinAzimuth;
/// The sine of the elevation of the light source.
mutable double m_sinElev;
};
/// Renders a normal map from a noise map.
///
/// This class renders an image containing the normal vectors from a noise
/// map object. This image can then be used as a bump map for a 3D
/// application or game.
///
/// This class encodes the (x, y, z) components of the normal vector into
/// the (red, green, blue) channels of the image. Like any 24-bit
/// true-color image, the channel values range from 0 to 255. 0
/// represents a normal coordinate of -1.0 and 255 represents a normal
/// coordinate of +1.0.
///
/// You should also specify the <i>bump height</i> before rendering the
/// normal map. The bump height specifies the ratio of spatial resolution
/// to elevation resolution. For example, if your noise map has a spatial
/// resolution of 30 meters and an elevation resolution of one meter, set
/// the bump height to 1.0 / 30.0.
///
/// <b>Rendering the normal map</b>
///
/// To render the image containing the normal map, perform the following
/// steps:
/// - Pass a NoiseMap object to the SetSourceNoiseMap() method.
/// - Pass an Image object to the SetDestImage() method.
/// - Call the Render() method.
class RendererNormalMap
{
public:
/// Constructor.
RendererNormalMap ();
/// Enables or disables noise-map wrapping.
///
/// @param enable A flag that enables or disables noise-map wrapping.
///
/// This object requires three points (the initial point and the right
/// and up neighbors) to calculate the normal vector at that point.
/// If wrapping is/ enabled, and the initial point is on the edge of
/// the noise map, the appropriate neighbors that lie outside of the
/// noise map will "wrap" to the opposite side(s) of the noise map.
/// Otherwise, the appropriate neighbors are cropped to the edge of
/// the noise map.
///
/// Enabling wrapping is useful when creating spherical and tileable
/// normal maps.
void EnableWrap (bool enable = true)
{
m_isWrapEnabled = enable;
}
/// Returns the bump height.
///
/// @returns The bump height.
///
/// The bump height specifies the ratio of spatial resolution to
/// elevation resolution. For example, if your noise map has a
/// spatial resolution of 30 meters and an elevation resolution of one
/// meter, set the bump height to 1.0 / 30.0.
///
/// The spatial resolution and elevation resolution are determined by
/// the application.
double GetBumpHeight () const
{
return m_bumpHeight;
}
/// Determines if noise-map wrapping is enabled.
///
/// @returns
/// - @a true if noise-map wrapping is enabled.
/// - @a false if noise-map wrapping is disabled.
///
/// This object requires three points (the initial point and the right
/// and up neighbors) to calculate the normal vector at that point.
/// If wrapping is/ enabled, and the initial point is on the edge of
/// the noise map, the appropriate neighbors that lie outside of the
/// noise map will "wrap" to the opposite side(s) of the noise map.
/// Otherwise, the appropriate neighbors are cropped to the edge of
/// the noise map.
///
/// Enabling wrapping is useful when creating spherical and tileable
/// normal maps.
bool IsWrapEnabled () const
{
return m_isWrapEnabled;
}
/// Renders the noise map to the destination image.
///
/// @pre SetSourceNoiseMap() has been previously called.
/// @pre SetDestImage() has been previously called.
///
/// @post The original contents of the destination image is destroyed.
///
/// @throw noise::ExceptionInvalidParam See the preconditions.
void Render ();
/// Sets the bump height.
///
/// @param bumpHeight The bump height.
///
/// The bump height specifies the ratio of spatial resolution to
/// elevation resolution. For example, if your noise map has a
/// spatial resolution of 30 meters and an elevation resolution of one
/// meter, set the bump height to 1.0 / 30.0.
///
/// The spatial resolution and elevation resolution are determined by
/// the application.
void SetBumpHeight (double bumpHeight)
{
m_bumpHeight = bumpHeight;
}
/// Sets the destination image.
///
/// @param destImage The destination image.
///
/// The destination image will contain the normal map after a
/// successful call to the Render() method.
///
/// The destination image must exist throughout the lifetime of this
/// object unless another image replaces that image.
void SetDestImage (Image& destImage)
{
m_pDestImage = &destImage;
}
/// Sets the source noise map.
///
/// @param sourceNoiseMap The source noise map.
///
/// The destination image must exist throughout the lifetime of this
/// object unless another image replaces that image.
void SetSourceNoiseMap (const NoiseMap& sourceNoiseMap)
{
m_pSourceNoiseMap = &sourceNoiseMap;
}
private:
/// Calculates the normal vector at a given point on the noise map.
///
/// @param nc The height of the given point in the noise map.
/// @param nr The height of the left neighbor.
/// @param nu The height of the up neighbor.
/// @param bumpHeight The bump height.
///
/// @returns The normal vector represented as a color.
///
/// This method encodes the (x, y, z) components of the normal vector
/// into the (red, green, blue) channels of the returned color. In
/// order to represent the vector as a color, each coordinate of the
/// normal is mapped from the -1.0 to 1.0 range to the 0 to 255 range.
///
/// The bump height specifies the ratio of spatial resolution to
/// elevation resolution. For example, if your noise map has a
/// spatial resolution of 30 meters and an elevation resolution of one
/// meter, set the bump height to 1.0 / 30.0.
///
/// The spatial resolution and elevation resolution are determined by
/// the application.
Color CalcNormalColor (double nc, double nr, double nu,
double bumpHeight) const;
/// The bump height for the normal map.
double m_bumpHeight;
/// A flag specifying whether wrapping is enabled.
bool m_isWrapEnabled;
/// A pointer to the destination image.
Image* m_pDestImage;
/// A pointer to the source noise map.
const NoiseMap* m_pSourceNoiseMap;
};
}
}
#endif
| [
"[email protected]",
"Antoine@antoine-vm.(none)"
] | [
[
[
1,
1287
],
[
1289,
1728
],
[
1730,
1884
],
[
1886,
1891
],
[
1893,
2515
],
[
2517,
2540
]
],
[
[
1288,
1288
],
[
1729,
1729
],
[
1885,
1885
],
[
1892,
1892
],
[
2516,
2516
]
]
] |
77376d899bdeeba1564e8049b343f34f94bab198 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Graphics/WS/DirectForS60/src/DirectApplication.cpp | 2b55460999abc0e88fe05d107112a464b15d4df4 | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | cpp | /*
============================================================================
Name : DirectApplication.cpp
Author :
Copyright : Your copyright notice
Description : Main application class
============================================================================
*/
// INCLUDE FILES
#include "Direct.hrh"
#include "DirectDocument.h"
#include "DirectApplication.h"
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CDirectApplication::CreateDocumentL()
// Creates CApaDocument object
// -----------------------------------------------------------------------------
//
CApaDocument* CDirectApplication::CreateDocumentL()
{
// Create an Direct document, and return a pointer to it
return CDirectDocument::NewL(*this);
}
// -----------------------------------------------------------------------------
// CDirectApplication::AppDllUid()
// Returns application UID
// -----------------------------------------------------------------------------
//
TUid CDirectApplication::AppDllUid() const
{
// Return the UID for the Direct application
return KUidDirectApp;
}
// End of File
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
39
]
]
] |
51776d526a62fdd8929318bb8ee54d95acc68fde | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/mod/resource/src/resource_handle.cc | a8072f8cf527f7fda551e2e140fd92a12e51e6b9 | [] | no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | cc | //
// resource_handle.cc for in
//
// Made by texane
// Login <[email protected]>
//
// Started on Wed Mar 22 10:38:42 2006 texane
// Last update Wed Mar 22 10:40:01 2006 texane
//
#include "include/buffer.hh"
#include "include/resource.hh"
// either the recopy constructor is not ok
// either the hdr_buffer is not ok
// either the + operator is enot ok
resource::e_error resource::handle::prepend_header(buffer& hdr_buf)
{
data = hdr_buf + data;
return E_SUCCESS;
}
resource::e_error resource::handle::alter_content(void (buffer&, void*), void*)
{
return E_SUCCESS;
}
bool resource::handle::is_input() const
{
if (omode == O_INPUT || omode == O_BOTH)
return true;
return false;
}
bool resource::handle::is_output() const
{
if (omode == O_OUTPUT || omode == O_BOTH)
return true;
return false;
}
unsigned int resource::handle::input_size()
{
return in_size;
}
bool resource::handle::is_prefetched_input()
{
return in_buf.size() ? true : false;
}
void resource::handle::get_prefetched_input(buffer& data)
{
data = in_buf;
in_buf.clear();
}
resource::handle::handle()
{
}
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
] | [
[
[
1,
71
]
]
] |
e7a4de709a5e4c2ccc9f9f30111bab4b963bf2de | 14a00dfaf0619eb57f1f04bb784edd3126e10658 | /lab4/Quadric.h | 66b4b882ea5f49a5206557611a53651042c2f65f | [] | no_license | SHINOTECH/modanimation | 89f842262b1f552f1044d4aafb3d5a2ce4b587bd | 43d0fde55cf75df9d9a28a7681eddeb77460f97c | refs/heads/master | 2021-01-21T09:34:18.032922 | 2010-04-07T12:23:13 | 2010-04-07T12:23:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,417 | h | /*************************************************************************************************
*
* Modeling and animation (TNM079) 2007
* Code base for lab assignments. Copyright:
* Gunnar Johansson ([email protected])
* Ken Museth ([email protected])
* Michael Bang Nielsen ([email protected])
* Ola Nilsson ([email protected])
* Andreas Söderström ([email protected])
*
*************************************************************************************************/
#ifndef __quadric_h__
#define __quadric_h__
#include "Implicit.h"
/*! \brief Quadric base class */
class Quadric : public Implicit{
public:
//! Initialize the quadric from matrix q
Quadric(const Matrix4x4<float> & q);
virtual ~Quadric();
//! evaluate the quadric at world coordinates x y z
virtual float getValue(float x, float y, float z) const;
//! calculate the gradient at world coordinates x y z
virtual Vector3<float> getGradient(float x, float y, float z, float delta = 1e-3) const;
//! calculate the curvature at world coordinates x y z
virtual float getCurvature(float x, float y, float z) const;
//! Set transformation for the Q
virtual void setTransform(const Matrix4x4<float> & transform);
protected:
//! The quadrics coefficent matrix
Matrix4x4<float> mQuadric;
Matrix4x4<float> mQuadricPrime;
};
#endif
| [
"onnepoika@da195381-492e-0410-b4d9-ef7979db4686"
] | [
[
[
1,
39
]
]
] |
ce49635de5b6912d2e6df04fdf1c817b9ce36252 | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp1/src/ode_runge_kutta4.h | a3152deb233b8c50a9ef105e09606cd9f4ba9bac | [] | no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | h | #ifndef ODE_RUNGE_KUTTA4_H
#define ODE_RUNGE_KUTTA4_H
#include "ode_solver.h"
/// Runge-Kutta Fourth Order
/// Yi+1 = Yi + 1/6(k1 + 2 * k2 + 2 * k3 + k4)
/// with
/// k1 = h * F(Ti, Yi)
/// k2 = h * F(Ti + h/2, Yi + k1/2)
/// k3 = h * F(Ti + h/2, Yi + k2/2)
/// k4 = h * F(Ti + h, Yi + k3)
/// where
/// Y0 = initialValue (from constructor)
/// Yi = mLastValue
/// h = mStepSize
/// F(T, Y) = mFunction(mCurrentStep, mLastValue)
template <class Real>
class OdeRungeKutta4 : public OdeSolver<Real>
{
public:
OdeRungeKutta4(Real* initialValue, INT dimension, typename OdeSolver<Real>::Function function,
Real stepSize, Real startStep = 0.0f);
virtual ~OdeRungeKutta4();
virtual Real* step();
protected:
using OdeSolver<Real>::mLastValue;
using OdeSolver<Real>::mDimension;
using OdeSolver<Real>::mStepSize;
using OdeSolver<Real>::mCurrentStep;
using OdeSolver<Real>::mFunction;
};
typedef OdeRungeKutta4<FLOAT> OdeRungeKutta4f;
typedef OdeRungeKutta4<DOUBLE> OdeRungeKutta4d;
#endif
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
03ec539a5ddb70911ee4f3bbddc73bf05640486f | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASFootball/Shared/Source/ASFootballObjectShelf.h | ed6e16ed138ff34c18ef91b586ee557dec40a2c1 | [] | no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | h | /* ASFootballObjectShelf.h */
/******************************************************************************/
/******************************************************************************/
#ifndef ASFootballObjectShelfH
#define ASFootballObjectShelfH
#include "ObjectStore.h"
#include "ASFootballType.h"
#include "ASFootballObjectBuilder.h"
namespace asfootball
{
/******************************************************************************/
class ProfTeamScheduleObjectShelf : public ObjectShelf<TProfGameWeek,
TFootballProfTeamSchedulePtr>
{
public:
ProfTeamScheduleObjectShelf(ASFootballObjectBuilder& builder) :
ObjectShelf<TProfGameWeek,TFootballProfTeamSchedulePtr>(builder) {}
TFootballProfTeamSchedulePtr findByContainsGameDate(
TDateTime gameDate,CommonAccessMode getMode);
TFootballProfTeamSchedulePtr findCurrentAsOfToday(CommonAccessMode getMode);
};
/******************************************************************************/
}; //namespace asfootball
#endif //ASFootballObjectShelfH
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
e1725a2aefe6543a1eb4d4261cfeca6d642f3bae | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testsemaphore/src/tsemaphoreblocks.cpp | a094fedd25be574a2d3344150e1cada662206c64 | [] | 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 | 106,105 | cpp | /*
* Copyright (c) 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:
*
*/
/*
* ==============================================================================
* Name : tsemaphoreblocks.cpp
* Part of : testsemaphore
*
* Description : ?Description
* Version: 0.5
*
*/
// INCLUDE FILES
#include "tsemaphore.h"
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#define MAXVAL 3
#define UNIX_BASE TTime(MAKE_TINT64(0x00dcddb3,0x0f2f8000))
#define MESSAGE_Q_KEY 1000
#define WITH_ERROR 1
#define WITHOUT_ERROR 0
#define IPC_KEY 1000
#define IPC_CREAT_EXCL 3000
#define IPC_NO_CREAT_EXCL 2000
#define INVALID_SEM_COMMAND 1024
#define TH_CASE_SEMOP_NEGATIVE_VAL 1024
#define TH_CASE_SEMOP_ZERO_VAL 1025
#define MAX_SEM_OPS 3
#define RETURN_ON_ERROR(err) if ( err ) \
{ \
ERR_PRINTF2(KFunc, err); \
return err; \
}
TInt iFlag;
TInt CTestSemaphore::SemKey( TInt& aKey )
{
_LIT(KFunc, "SemKey");
INFO_PRINTF1 ( KFunc);
_LIT( KaKey, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaKey,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aKey);
if(!res)
{
_LIT(Kerr , "Unable to retrieve aKey") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
return KErrNone;
}
TInt CTestSemaphore::SemNum( TInt& aSemNum )
{
_LIT(KFunc, "SemNum");
INFO_PRINTF1 ( KFunc);
_LIT( KaSemNum, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aSemNum);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore number") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
return KErrNone;
}
TInt CTestSemaphore::SemFlag( TInt& aFlag )
{
_LIT(KFunc, "SemFlag");
INFO_PRINTF1 ( KFunc);
_LIT( KaFlag, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaFlag,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aFlag);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore flag") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
return KErrNone;
}
TInt CTestSemaphore::SemOpVal( TInt& aSemOp )
{
_LIT(KFunc, "SemOpVal");
INFO_PRINTF1 ( KFunc);
_LIT( KaSemOp, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaSemOp,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aSemOp);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore operation value");
ERR_PRINTF1(Kerr);
return KErrGeneral ;
}
return KErrNone;
}
TInt CTestSemaphore::ErrCode( TInt& aErrCode )
{
_LIT(KFunc, "ErrCode");
INFO_PRINTF1 ( KFunc());
_LIT( KaErrCode, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaErrCode,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aErrCode);
if(!res)
{
_LIT(Kerr , "Unable to retrieve error code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemNCreate
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemNCreate( )
{
_LIT(KFunc, "SemCreate");
INFO_PRINTF1 ( KFunc);
TInt key;
TInt semFlag;
TInt terror;
TInt retVal = KErrNone;
TInt numberOfSem = 0;
// retrieve passed parameters
retVal = SemKey( key);
RETURN_ON_ERROR(retVal);
retVal = SemNum( iSemNum);
RETURN_ON_ERROR(retVal);
retVal = SemFlag( semFlag);
RETURN_ON_ERROR(retVal);
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
retVal = SemNum( numberOfSem);
RETURN_ON_ERROR(retVal);
TInt semid = 0;
int startIndex = 0;
TInt index = 0;
for(index = 0; index < MAX_IPC_OBJ; index++)
{
if(iNumberOfCreateSem[index] == -1)
{
startIndex = index;
break;
}
}
for(index = 0; index < numberOfSem; index++)
{
semid = semget(key +index, iSemNum, semFlag);
if(semid == -1)
{
break;
}
iNumberOfCreateSem[startIndex + index] = semid;
}
if (semid == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
else
{
TInt errCode = 0;
_LIT( KerrCode, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KerrCode,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, errCode);
if(!res)
{
_LIT(Kerr , "Unable to retrieve eror code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ( errCode == errno)
{
retVal = KErrNone;
}
}
}
else
{
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
if(retVal != KErrNone && index < numberOfSem && numberOfSem > 1)
{
// do the cleanup
for(index = startIndex; index < MAX_IPC_OBJ; index++)
{
if(iNumberOfCreateSem[index] > 0)
semctl(iNumberOfCreateSem[index], iSemNum, IPC_RMID);
}
}
//DebugLogPrintL ( KFunc(), OUT, retVal);
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemNClose
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemNClose( )
{
_LIT(KFunc, "SemClose");
INFO_PRINTF1 ( KFunc);
TInt retVal = KErrNone;
TInt terror;
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
TInt err = KErrNone;
for(TInt index = 0; index < MAX_IPC_OBJ; index++)
{
if(iNumberOfCreateSem[index] > 0)
err = semctl(iNumberOfCreateSem[index], iSemNum, IPC_RMID);
}
if (err == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
}
else
{
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemCreate
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemCreate( )
{
_LIT(KFunc, "SemCreate");
INFO_PRINTF1 ( KFunc);
TInt key;
TInt semFlag;
TInt terror;
TInt retVal = KErrNone;
// retrieve passed parameters
retVal = SemKey( key);
RETURN_ON_ERROR(retVal);
retVal = SemNum( iSemNum);
RETURN_ON_ERROR(retVal);
retVal = SemFlag( semFlag);
RETURN_ON_ERROR(retVal);
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
TInt semid = semget(key, iSemNum, semFlag);
if (semid == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
else
{
TInt errCode = 0;
_LIT( KerrCode, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KerrCode,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, errCode);
if(!res)
{
_LIT(Kerr , "Unable to retrieve eror code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ( errCode == errno)
{
retVal = KErrNone;
}
}
}
else
{
iNumberOfCreateSem[0] = semid;
iKey = key;
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemOp
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemOp( )
{
_LIT(KFunc, "SemOp");
INFO_PRINTF1 ( KFunc);
TInt key = iNumberOfCreateSem[0];
TInt semnops;
TInt terror;
TInt retVal = KErrNone;
// retrieve passed parameters
if(iReadSemIdFlag)
{
retVal = SemKey( key);
RETURN_ON_ERROR(retVal);
}
// nsops
_LIT( Ksemnops, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(Ksemnops,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, semnops);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semnops") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if(semnops > MAX_SEM_OPS)
{
return KErrGeneral;
}
struct sembuf lSemBuf[MAX_SEM_OPS];
for(TInt index = 0; index < semnops; index++)
{
TInt sem_num;
TInt sem_op;
TInt sem_flg;
_LIT( Ksem_num, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(Ksem_num,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, sem_num);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem_num") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
_LIT( Ksem_op, "Param%d" );
pNameBuf.Zero();
pNameBuf.Format(Ksem_op,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, sem_op);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem_op") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
_LIT( Ksem_flg, "Param%d" );
pNameBuf.Zero();
pNameBuf.Format(Ksem_flg,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, sem_flg);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem_flg") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
lSemBuf[index].sem_num = sem_num;
lSemBuf[index].sem_op = sem_op;
lSemBuf[index].sem_flg = sem_flg;
}
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
iSemopStartFlag = ETrue;
TInt err = semop(key, &lSemBuf[0], semnops);
if (err == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
else
{
TInt errCode = 0;
_LIT( KerrCode, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KerrCode,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, errCode);
if(!res)
{
_LIT(Kerr , "Unable to retrieve eror code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ( errCode == errno)
{
retVal = KErrNone;
}
}
}
else
{
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemCtl
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemCtl( )
{
_LIT(KFunc, "SemCtl");
INFO_PRINTF1 ( KFunc);
TInt key = iNumberOfCreateSem[0];
TInt semCmd,err1;
TInt terror;
TInt retVal = KErrNone;
TInt semNum;
// retrieve passed parameters
if(iReadSemIdFlag)
{
retVal = SemKey( key);
RETURN_ON_ERROR(retVal);
}
retVal = SemNum( semNum);
RETURN_ON_ERROR(retVal);
// semaphore command
retVal = SemNum( semCmd);
RETURN_ON_ERROR(retVal);
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
union semun psemun;
psemun.array = NULL;
psemun.buf = NULL;
TInt expectedReturn = 0;
TInt semNumbers = 0;
TInt seq = 0;
TBool freeReq = EFalse;
TBuf<8> pNameBuf;
TBool res ;
_LIT( KexpectedReturn, "Param%d" );
switch(semCmd)
{
case IPC_RMID:
pNameBuf.Format(KexpectedReturn,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
break;
case GETNCNT:
case GETZCNT:
case GETVAL:
case INVALID_SEM_COMMAND:
pNameBuf.Format(KexpectedReturn,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
break;
case SETVAL:
{
pNameBuf.Format(KexpectedReturn,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
INFO_PRINTF1 ( _L("SETVAL"));
_LIT( Kval, "Param%d" );
pNameBuf.Format(Kval,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, psemun.val);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semun val") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
break;
}
case GETPID:
{
RThread thread;
expectedReturn = thread.Id();
break;
}
case GETALL:
{
pNameBuf.Format(KexpectedReturn,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
_LIT( KsemNumbers, "Param%d" );
pNameBuf.Zero();
pNameBuf.Format(KsemNumbers,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, semNumbers);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem numbers") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
psemun.array = (unsigned short*)malloc(semNumbers * sizeof(unsigned short));
freeReq = ETrue;
}
break;
case SETALL:
{
pNameBuf.Format(KexpectedReturn,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
_LIT( KsemNumbers, "Param%d" );
pNameBuf.Zero();
pNameBuf.Format(KsemNumbers,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, semNumbers);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem numbers") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
psemun.array = (unsigned short*)malloc(semNumbers * sizeof(unsigned short));
freeReq = ETrue;
for(TInt index = 0; index < semNumbers; index++)
{
TInt val = 0;
_LIT( Kval, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(Kval,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, val);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem val") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
psemun.array[index] = val;
}
}
break;
case IPC_STAT:
{
pNameBuf.Format(KexpectedReturn,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
psemun.buf = (struct semid_ds*)malloc(sizeof(struct semid_ds));
freeReq = ETrue;
}
break;
case IPC_SET:
{
pNameBuf.Format(KexpectedReturn,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, expectedReturn);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected return value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
psemun.buf = (struct semid_ds*)malloc(sizeof(struct semid_ds));
freeReq = ETrue;
// fetch the data.
TInt err = semctl(key, semNum, IPC_STAT, psemun);
RETURN_ON_ERROR(err);
_LIT( Kseq, "Param%d" );
pNameBuf.Zero();
pNameBuf.Format(Kseq,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, seq);
if(!res)
{
_LIT(Kerr , "Unable to retrieve expected seq value") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
((struct semid_ds*)psemun.buf)->sem_perm.mode = seq;
}
break;
default:
break;
}
err1 = semctl(key, semNum, semCmd, psemun);
if(expectedReturn != err1)
{
return KErrGeneral;
}
if (freeReq)
{
if (semCmd == IPC_SET)
{
TInt err = semctl(key, semNum, IPC_STAT, psemun);
RETURN_ON_ERROR(err);
if(((struct semid_ds*)psemun.buf)->sem_perm.mode != seq)
{
return KErrGeneral;
}
}
else if (semCmd == GETALL)
{
for(TInt index = 0; semCmd == GETALL && index < semNumbers; index++)
{
TInt val = 0;
_LIT( Kval, "Param%d" );
pNameBuf.Format(Kval,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, val);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem val") ;
ERR_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if (val != psemun.array[index])
{
return KErrGeneral;
}
}
}
else
{
}
//since array and buf is within union, there is no issue.
free(psemun.array);
psemun.array = NULL;
}
if (err1 == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
else
{
TInt errCode = 0;
_LIT( KerrCode, "Param%d" );
pNameBuf.Format(KerrCode,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, errCode);
if(!res)
{
_LIT(Kerr , "Unable to retrieve eror code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ( errCode == errno)
{
retVal = KErrNone;
}
}
}
else
{
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::SemClose
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::SemClose( )
{
_LIT(KFunc, "SemClose");
INFO_PRINTF1 ( KFunc);
TInt retVal = KErrNone;
TInt terror;
retVal = ErrCode( terror);
RETURN_ON_ERROR(retVal);
TInt err = semctl(iNumberOfCreateSem[0], iSemNum, IPC_RMID);
if (err == -1)
{
if(terror == WITHOUT_ERROR)
{
retVal = errno;
}
}
else
{
if(terror == WITH_ERROR)
{
retVal = errno;
}
}
return retVal;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::ReadSemId
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::ReadSemId( )
{
_LIT(KFunc, "ReadSemId");
INFO_PRINTF1 ( KFunc);
_LIT( KiReadSemIdFlag, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KiReadSemIdFlag,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, iReadSemIdFlag);
if(!res)
{
_LIT(Kerr , "Unable to retrieve SemIdFlag") ;
INFO_PRINTF1(Kerr) ;
iReadSemIdFlag = EFalse;
}
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::CreateThreadL
// -----------------------------------------------------------------------------
//
TInt CTestSemaphore::CreateThreadL( )
{
_LIT(KFunc, "CreateThreadL");
INFO_PRINTF1 ( KFunc);
TInt threadType, err;
_LIT( KthreadType, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KthreadType,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, threadType);
if(!res)
{
_LIT(Kerr , "Unable to retrieve eror code") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
switch(threadType)
{
case GETNCNT:
err = pthread_create((unsigned int *)&iThreadId,(pthread_attr_t *)NULL,ThreadEntryFunctionSemOpGetNcnt,(void*)this);
break;
case GETZCNT:
err = pthread_create((unsigned int *)&iThreadId,(pthread_attr_t *)NULL,ThreadEntryFunctionSemOpGetZcnt,(void*)this);
break;
case TH_CASE_SEMOP_NEGATIVE_VAL:
err = pthread_create((unsigned int *)&iThreadId,(pthread_attr_t *)NULL,ThreadEntryFunctionSemOpNegativeVal,(void*)this);
break;
case TH_CASE_SEMOP_ZERO_VAL:
err = pthread_create((unsigned int *)&iThreadId,(pthread_attr_t *)NULL,ThreadEntryFunctionSemOpZeroVal,(void*)this);
break;
default:
err = KErrNone;
break;
}
if ( err )
{
ERR_PRINTF2 ( _L("pthread_create error"), err);
}
return err;
}
void CTestSemaphore::SendSignal()
{
iExitVal = 1;
}
TInt CTestSemaphore::WaitForThreadCompleteL( )
{
_LIT(KFunc, "WaitForThreadCompleteL");
INFO_PRINTF1 ( KFunc);
iExitVal = 0;
while (!iExitVal)
{
//spin over here.
_LIT(Kerr , "Unable to retrieve eror code %d") ;
INFO_PRINTF2(Kerr,iExitVal) ;
User::After (100000);
}
iExitVal = 0;
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::ThreadEntryFunctionSemOpGetNcntW
// -----------------------------------------------------------------------------
//
void* CTestSemaphore::ThreadEntryFunctionSemOpGetNcnt(void* arg)
{
CTestSemaphore *self = static_cast<CTestSemaphore*> (arg);
struct sembuf lSemBuf[MAX_SEM_OPS];
TInt semid = semget(self->iKey, self->iSemNum, IPC_CREAT|IPC_W|IPC_R);
if(semid != -1)
{
// semaphore is created successfully.
}
lSemBuf[0].sem_num = 0;
lSemBuf[0].sem_op = -1;
lSemBuf[0].sem_flg = 0;
// thread is supposed to block over here.
TInt err = semop(semid, &lSemBuf[0], 1);
if (err == -1)
{
}
User::After(500000);
self->SendSignal();
return NULL;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::ThreadEntryFunctionSemOpNegativeVal
// -----------------------------------------------------------------------------
//
void* CTestSemaphore::ThreadEntryFunctionSemOpZeroVal(void* arg)
{
CTestSemaphore *self = static_cast<CTestSemaphore*> (arg);
struct sembuf lSemBuf[MAX_SEM_OPS];
TInt semid = semget(self->iKey, self->iSemNum, IPC_CREAT|IPC_W|IPC_R);
if(semid != -1)
{
// semaphore is created successfully.
}
lSemBuf[0].sem_num = 0;
lSemBuf[0].sem_op = -1;
lSemBuf[0].sem_flg = 0;
while(!self->iSemopStartFlag)
{
User::After(50000);
}
// thread is supposed to block over here.
TInt err = semop(semid, &lSemBuf[0], 1);
if (err == -1)
{
}
return NULL;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::ThreadEntryFunctionSemOpNegativeVal
// -----------------------------------------------------------------------------
//
void* CTestSemaphore::ThreadEntryFunctionSemOpNegativeVal(void* arg)
{
CTestSemaphore *self = static_cast<CTestSemaphore*> (arg);
struct sembuf lSemBuf[MAX_SEM_OPS];
TInt semid = semget(self->iKey, self->iSemNum, IPC_CREAT|IPC_W|IPC_R);
if(semid != -1)
{
// semaphore is created successfully.
}
lSemBuf[0].sem_num = 0;
lSemBuf[0].sem_op = 1;
lSemBuf[0].sem_flg = 0;
while(!self->iSemopStartFlag)
{
User::After(50000);
}
// thread is supposed to block over here.
TInt err = semop(semid, &lSemBuf[0], 1);
if (err == -1)
{
}
return NULL;
}
// -----------------------------------------------------------------------------
// CTestSemaphore::ThreadEntryFunctionSemOpGetZcnt
// -----------------------------------------------------------------------------
//
void* CTestSemaphore::ThreadEntryFunctionSemOpGetZcnt(void* arg)
{
CTestSemaphore *self = static_cast<CTestSemaphore*> (arg);
struct sembuf lSemBuf[MAX_SEM_OPS];
TInt semid = semget(self->iKey, self->iSemNum, IPC_CREAT|IPC_W|IPC_R);
if(semid != -1)
{
// semaphore is created successfully.
}
lSemBuf[0].sem_num = 0;
lSemBuf[0].sem_op = 0;
lSemBuf[0].sem_flg = 0;
// thread is supposed to block over here.
TInt err = semop(semid, &lSemBuf[0], 1);
if (err == -1)
{
}
User::After(500000);
self->SendSignal();
return NULL;
}
TInt CTestSemaphore::IntgTest1()
{
TInt err = SemCreate();
if(!err)
{
err = SemClose();
}
return err;
}
TInt CTestSemaphore::IntgTest2()
{
TInt err = SemCreate();
if(!err)
{
err = SemCreate();
if(!err)
{
err = SemClose();
}
}
return err;
}
TInt CTestSemaphore::IntgTest3()
{
TInt err = ReadSemId();
if(!err)
{
err = SemCtl();
}
return err;
}
TInt CTestSemaphore::IntgTest4()
{
TInt err = SemCreate();
if(!err)
{
err = ReadSemId();
if(!err)
{
err = SemCtl();
if(!err)
{
err = SemClose();
}
}
}
return err;
}
TInt CTestSemaphore::IntgTest5()
{
TInt err = SemCreate();
if(!err)
{
err = ReadSemId();
if(!err)
{
err = SemCtl();
if(!err)
{
err = SemCtl();
if(!err)
{
err = SemClose();
}
}
}
}
return err;
}
TInt CTestSemaphore::IntgTest6()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = CreateThreadL();
if(err)
{
return err;
}
err = SemCtl();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = WaitForThreadCompleteL();
if(err)
{
return err;
}
err = SemClose();
return err;
}
TInt CTestSemaphore::IntgTest7()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = SemCtl();
if(err)
{
return err;
}
err = SemClose();
return err;
}
TInt CTestSemaphore::IntgTest8()
{
TInt err = SemCreate();
if(!err)
{
err = ReadSemId();
if(!err)
{
err = SemCtl();
}
}
return err;
}
TInt CTestSemaphore::IntgTest9()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = SemCtl();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = SemCtl();
return err;
}
TInt CTestSemaphore::IntgTest10()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = SemCtl();
return err;
}
TInt CTestSemaphore::IntgTest11()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = CreateThreadL();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = SemCtl();
return err;
}
TInt CTestSemaphore::IntgTest12()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = ReadSemId();
if(err)
{
return err;
}
err = SemCtl();
if(err)
{
return err;
}
err = CreateThreadL();
if(err)
{
return err;
}
err = SemOp();
if(err)
{
return err;
}
err = SemCtl();
return err;
}
TInt CTestSemaphore::IntgTest13()
{
TInt err = SemCreate();
if(err)
{
return err;
}
err = SemNClose ();
return err;
}
TInt CTestSemaphore::IntgTest14()
{
key_t key;
int semid;
union semun arg;
INFO_PRINTF1(_L("IntgTest14"));
char *path;
#if defined (__EPOC32__)
path = "c:\\tstdapis\\tsemaphore.ini";
#else
path = "c:\\tstdapis\\tsemaphore.ini";
#endif
if ((key = ftok(path, 'P')) == -1)
{
ERR_PRINTF1(_L("ftok error!"));
return KErrGeneral;
}
/* create a semaphore set with 1 semaphore: */
if ((semid = semget(key, 1, 0666 | IPC_CREAT)) == -1)
{
ERR_PRINTF1(_L("semget error!"));
return KErrGeneral;
}
/* initialize semaphore #0 to 1: */
arg.val = 1;
if (semctl(semid, 0, SETVAL, arg) == -1)
{
ERR_PRINTF1(_L("semctl error!"));
return KErrGeneral;
}
return KErrNone;
}
TInt CTestSemaphore::ReadIntParam(TInt& aParam)
{
_LIT(KFunc, "ReadIntParam");
INFO_PRINTF1 ( KFunc());
_LIT( KaParam, "Param%d" );
TBuf<8> pNameBuf;
pNameBuf.Format(KaParam,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aParam);
if(!res)
{
_LIT(Kerr , "Unable to retrieve parameter") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreateKey()
// Description : This test creates an array of specified number of semaphores
// with the specified key, and deletes them.
// Param1 : Key to use for semget
// Param2 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreateKey()
{
int key = 0;
int numberOfSem = 0;
int sem_id = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(key, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreatePrivate()
// Description : This test creates a private array of specified number of semaphores
// and deletes them.
// Param1 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreatePrivate()
{
int numberOfSem = 0;
int sem_id = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(IPC_PRIVATE, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetGetPrivate()
// Description : This test creates a private array of specified number of
// semaphores and deletes them.
// Param1 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetGetPrivate()
{
int numberOfSem = 0;
int sem_id = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(IPC_PRIVATE, numberOfSem, 0)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreateKeyMax()
// Description : This test tries to create upto specified number of arrays of
// specified number of semaphores with the specified key,
// and deletes them. Creation must fail before it reaches the
// specified count, and ENOSPC must be returned on failure.
// Param1 : Starting value of key to use for semget
// Param2 : Number of semaphores in array
// Param3 : Number of arrays to create
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreateKeyMax()
{
int key = 0;
int numberOfSem = 0;
int arrayCount = 0;
TBuf<8> pNameBuf;
int rval = KErrNone;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, arrayCount);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore array count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int idx = 0;
int* sem_id = 0;
int limitHit = 0;
int createdCount = arrayCount;
sem_id = (int*)malloc(arrayCount * sizeof(int));
if(sem_id == 0)
{
_LIT(Kerr , "Out of memory") ;
INFO_PRINTF1(Kerr) ;
return KErrNoMemory ;
}
for(idx=0;idx<arrayCount;idx++)
{
if ((sem_id[idx] = semget(key+idx, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
if(errno == ENOSPC)
{
limitHit = 1;
}
createdCount = idx;
break;
}
}
if(limitHit == 0)
rval = KErrGeneral;
for(idx=0;idx<createdCount;idx++)
{
if (semctl(sem_id[idx], 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
rval = KErrGeneral;
}
}
free(sem_id);
sem_id = 0;
return rval;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreatePvtMax()
// Description : This test tries to create upto specified number of private
// arrays of specified number of semaphores, and deletes them.
// Creation must fail before it reaches the specified count,
// and ENOSPC must be returned on failure.
// Param1 : Number of semaphores in array
// Param2 : Number of arrays to create
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreatePvtMax()
{
int numberOfSem = 0;
int arrayCount = 0;
TBuf<8> pNameBuf;
int rval = KErrNone;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, arrayCount);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore array count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int idx = 0;
int* sem_id = 0;
int limitHit = 0;
int createdCount = arrayCount;
sem_id = (int*)malloc(arrayCount * sizeof(int));
if(sem_id == 0)
{
_LIT(Kerr , "Out of memory") ;
INFO_PRINTF1(Kerr) ;
return KErrNoMemory ;
}
for(idx=0;idx<arrayCount;idx++)
{
if ((sem_id[idx] = semget(IPC_PRIVATE, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
if(errno == ENOSPC)
{
limitHit = 1;
}
createdCount = idx;
break;
}
}
if(limitHit == 0)
rval = KErrGeneral;
for(idx=0;idx<createdCount;idx++)
{
if (semctl(sem_id[idx], 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
rval = KErrGeneral;
}
}
free(sem_id);
sem_id = 0;
return rval;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetGetNonExisting()
// Description : This test tries to get a non-existing semaphore with
// specified key and size.
// Param1 : Key to use for semget
// Param2 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetGetNonExisting()
{
int key = 0;
int numberOfSem = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int sem_id;
sem_id = semget(key ,numberOfSem, IPC_CREAT & 0);
if(sem_id == -1)
{
if(errno == ENOENT)
{
_LIT(KFunc, "semget failed with the proper errno\n");
INFO_PRINTF1(KFunc);
return KErrNone;
}
else
{
_LIT(KFunc, "semget failed with wrong errno\n");
INFO_PRINTF1(KFunc);
return KErrGeneral;
}
}
else
{
_LIT(KErr,"semget did not fail. key exists!\n");
INFO_PRINTF1(KErr);
return KErrGeneral;
}
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreateInvalidSizeK()
// Description : This test tries to create a semaphore with
// specified key and an invalid size.
// Param1 : Key to use for semget
// Param2 : Number of semaphores in array (invalid value)
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreateInvalidSizeK()
{
int key = 0;
int numberOfSem = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int sem_id;
sem_id = semget(key ,numberOfSem, IPC_CREAT | IPC_EXCL | 0666);
if (sem_id == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semaphore set the proper errno\n");
INFO_PRINTF1(KFunc);
return KErrNone;
}
_LIT(KFunc, "semaphore failed to set the errno but returned -1 \n");
INFO_PRINTF1(KFunc);
return KErrGeneral;
}
return KErrGeneral;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreateInvalidSizeP()
// Description : This test tries to create a private semaphore array with
// an invalid size.
// Param1 : Number of semaphores in array (invalid value)
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreateInvalidSizeP()
{
int numberOfSem = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int sem_id;
sem_id = semget(IPC_PRIVATE ,numberOfSem, IPC_CREAT | IPC_EXCL | 0666);
if (sem_id == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semaphore set the proper errno\n");
INFO_PRINTF1(KFunc);
return KErrNone;
}
_LIT(KFunc, "semaphore failed to set the errno but returned -1 \n");
INFO_PRINTF1(KFunc);
return KErrGeneral;
}
return KErrGeneral;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetGetMore()
// Description : This test creates a semaphore array with specified key and
// size and then tried to get a larger array with same key.
// Param1 : Key to use for semget
// Param2 : Number of semaphores in array
// Param3 : Number of semaphore to get (invalid value)
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetGetMore()
{
int key = 0;
int numberOfSem = 0;
int numberOfSem2 = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem2);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int sem_id,sem_id1,ret=KErrNone;
if ((sem_id = semget(key, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
sem_id1 = semget(key, numberOfSem2, 0);
if (sem_id1 == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semaphore set the proper errno \n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
}
if (semctl(sem_id, numberOfSem, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetCreateExisting()
// Description : This test creates a semaphore array with specified key and
// size and then tried to create one more array with same key.
// Param1 : Key to use for semget
// Param2 : Number of semaphores in first array
// Param3 : Number of semaphore in second array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetCreateExisting()
{
int key = 0;
int numberOfSem = 0;
int numberOfSem2 = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem2);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
int sem_id1,sem_id2;
if ((sem_id1 = semget(key, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
else
{
sem_id2 = semget(key, numberOfSem2, IPC_CREAT | IPC_EXCL | 0666);
if(sem_id2 == -1 && errno == EEXIST)
{
_LIT(KFunc, "semaphore set the proper the errno\n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semaphore didnt set the proper the errno\n");
INFO_PRINTF1(KFunc);
return KErrGeneral;
}
}
if (semctl(sem_id1, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return KErrNone;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemgetGetExisting()
// Description : This test creates an array of specified number of semaphores
// with specified key and tries to get it again with same key.
// Param1 : Key for the semaphore array
// Param2 : Number of semaphores to create
// Param3 : Number of semaphores to get
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemgetGetExisting()
{
int key = 0;
int numberOfSem = 0;
int numberOfSem2 = 0;
int sem_id1 = 0;
int sem_id2 = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, key);
if(!res)
{
_LIT(Kerr , "Unable to retrieve semaphore key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem);
if(!res)
{
_LIT(Kerr , "Unable to retrieve create semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
pNameBuf.Format(KaSemNum,++iParamCnt);
res = GetIntFromConfig(ConfigSection(), pNameBuf, numberOfSem2);
if(!res)
{
_LIT(Kerr , "Unable to retrieve get semaphore count") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id1 = semget(key, numberOfSem, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
sem_id2 = semget(key, numberOfSem2, 0);
if (sem_id2 == -1)
{
_LIT(KFunc, "semaphore get failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id1, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return KErrNone;
}
//SEMCTL
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlInvalidId()
// Description : This test tries to call IPC_RMID with an invalid Id.
// Param1 : Id to delete (invalid)
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlInvalidId()
{
int sem_id = 0;
TBuf<8> pNameBuf;
_LIT( KaSemNum, "Param%d" );
pNameBuf.Format(KaSemNum,++iParamCnt);
TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, sem_id);
if(!res)
{
_LIT(Kerr , "Unable to retrieve sem id") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((semctl(sem_id,1 , IPC_RMID) == -1) && errno == EINVAL )
{
_LIT(KFunc, "semctl set the proper errno\n");
INFO_PRINTF1(KFunc);
return KErrNone;
}
return KErrGeneral;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlInvalidArgsK()
// Description : This test tries to pass an invalid cmd.
// Param1 : Key for semaphore array
// Param2 : Count to pass to semctl
// Param3 : Command to pass to semctl
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlInvalidArgsK()
{
int sem_id = 0;
int key = 0;
int num = 0;
int cmd = 0;
TInt rval = KErrNone;
TInt res = ReadIntParam(key);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(cmd);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve cmd") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(key,1, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id, num, cmd) == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semctl set the proper errno\n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semctl returned improper errno\n");
INFO_PRINTF1(KFunc);
rval = KErrGeneral;
}
}
else
{
_LIT(KFunc, "semctl returned success (error expected)\n");
INFO_PRINTF1(KFunc);
rval = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore1 delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return rval;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlInvalidArgsP()
// Description : This test tries to pass an invalid cmd.
// Param1 : Count to pass to semctl
// Param2 : Command to pass to semctl
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlInvalidArgsP()
{
int sem_id = 0;
int num = 0;
int cmd = 0;
TInt rval = KErrNone;
TInt res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(cmd);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve cmd") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(IPC_PRIVATE,1, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
if (semctl(sem_id, num, cmd) == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semctl set the proper errno\n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semctl returned improper errno\n");
INFO_PRINTF1(KFunc);
rval = KErrGeneral;
}
}
else
{
_LIT(KFunc, "semctl returned success (error expected)\n");
INFO_PRINTF1(KFunc);
rval = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore1 delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
return rval;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlStatK()
// Description : This test creates a sem array, stats it and verifies the
// returned values
// Param1 : Key for creating array
// Param2 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlStatK()
{
int sem_id,ret=KErrNone;
struct semid_ds semid_ds1;
int mode;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg;
int key = 0, num = 0;
TInt res = ReadIntParam(key);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
mode = IPC_R|IPC_CREAT | IPC_EXCL ;
mode = mode | 0666;
if ((sem_id = semget(key, num, mode)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(arg.buf->sem_nsems != num)
{
ret = KErrGeneral;
}
if(arg.buf->sem_otime != 0)
{
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlStatP()
// Description : This test creates a private sem array, stats it and verifies
// the returned values
// Param1 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlStatP()
{
int sem_id,ret=KErrNone;
struct semid_ds semid_ds1;
int mode;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg;
int num = 0;
TInt res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
mode = IPC_R|IPC_CREAT | IPC_EXCL ;
mode = mode | 0666;
if ((sem_id = semget(IPC_PRIVATE, num, mode)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(arg.buf->sem_nsems != num)
{
ret = KErrGeneral;
}
if(arg.buf->sem_otime != 0)
{
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlSetK()
// Description : This test creates a sem array, set values, and then stats it
// and verifies the returned values
// Param1 : Key for creating array
// Param2 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlSetK()
{
int sem_id,ret=KErrNone;
struct semid_ds semid_ds1;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg,arg1;
int key = 0, num = 0;
TInt res = ReadIntParam(key);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(key, num, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg) == -1)
{
_LIT(KFunc, "semaphore IPC_STAT failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
arg.buf->sem_perm.mode = IPC_W | IPC_R | IPC_M;
if(semctl(sem_id,0,IPC_SET,arg) == -1)
{
_LIT(KFunc, "semaphore IPC_SET failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
arg1.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg1) == -1)
{
_LIT(KFunc, "semaphore IPC_STAT failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(arg1.buf->sem_perm.mode != (IPC_W | IPC_R | IPC_M) )
{
ret = KErrGeneral;
}
if(arg1.buf->sem_nsems != num)
{
ret = KErrGeneral;
}
if(arg1.buf->sem_otime != 0)
{
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlSetP()
// Description : This test creates a sem array, set values, and then stats it
// and verifies the returned values
// Param1 : Number of semaphores in array
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlSetP()
{
int sem_id,ret=KErrNone;
struct semid_ds semid_ds1;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg,arg1;
int num = 0;
TInt res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(IPC_PRIVATE, num, IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg) == -1)
{
_LIT(KFunc, "semaphore IPC_STAT failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
arg.buf->sem_perm.mode = IPC_W | IPC_R | IPC_M;
if(semctl(sem_id,0,IPC_SET,arg) == -1)
{
_LIT(KFunc, "semaphore IPC_SET failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
arg1.buf = & semid_ds1;
if (semctl(sem_id, 0, IPC_STAT,arg1) == -1)
{
_LIT(KFunc, "semaphore IPC_STAT failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(arg1.buf->sem_perm.mode != (IPC_W | IPC_R | IPC_M) )
{
ret = KErrGeneral;
}
if(arg1.buf->sem_nsems != num)
{
ret = KErrGeneral;
}
if(arg1.buf->sem_otime != 0)
{
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlGetValK()
// Description : This test creates a sem array, gets its values, and logs it
// Param1 : Key of the semaphore array
// Param2 : Number of semaphores in array
// Param3 : Invalid semnum to check
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlGetValK()
{
int sem_id,ret=KErrNone,get=0;
int key = 0, num = 0, inval = 0;
TInt res = ReadIntParam(key);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve key") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(inval);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve inval") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(key, num, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int idx=0;idx<num;idx++)
{
get = semctl(sem_id, idx, GETVAL);
if (get == -1)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc, "semaphore variable semval[%d] is %d\n");
INFO_PRINTF3(KFunc, idx, get);
}
get = semctl(sem_id, inval, GETVAL);
if (get == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semctl set the proper errno\n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semctl failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
}
else
{
_LIT(KFunc, "semctl succeeded (failure expected)");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
//-------------------------------------------------------------------------------
// Function Name : CTestSemaphore::SemctlGetValP()
// Description : This test creates a private sem array, gets its values, and
// logs it
// Param1 : Number of semaphores in array
// Param2 : Invalid semnum to check
//-------------------------------------------------------------------------------
TInt CTestSemaphore::SemctlGetValP()
{
int sem_id,ret=KErrNone,get=0;
int num = 0, inval = 0;
TInt res = ReadIntParam(num);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve num") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
res = ReadIntParam(inval);
if(res!=KErrNone)
{
_LIT(Kerr , "Unable to retrieve inval") ;
INFO_PRINTF1(Kerr) ;
return KErrGeneral ;
}
if ((sem_id = semget(IPC_PRIVATE, num, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int idx=0;idx<num;idx++)
{
get = semctl(sem_id, idx, GETVAL);
if (get == -1)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc, "semaphore variable semval[%d] is %d\n");
INFO_PRINTF3(KFunc, idx, get);
}
get = semctl(sem_id, inval, GETVAL);
if (get == -1)
{
if(errno == EINVAL)
{
_LIT(KFunc, "semctl set the proper errno\n");
INFO_PRINTF1(KFunc);
}
else
{
_LIT(KFunc, "semctl failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
}
else
{
_LIT(KFunc, "semctl succeeded (failure expected)");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// successful SETVAL
TInt CTestSemaphore::semctltest8()
{
int sem_id,ret=KErrNone,get=0;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg;
if ((sem_id = semget(IPC_PRIVATE,1, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.val = 3;
get = semctl(sem_id, 0, GETVAL);
if (get == -1)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc, "semaphore variable semval before change is %d\n");
INFO_PRINTF2(KFunc, get);
get = semctl(sem_id, 0, SETVAL,arg);
if (get == -1)
{
_LIT(KFunc, "semaphore SETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
get = semctl(sem_id, 0, GETVAL);
if (get != 3)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc1, "semaphore variable semval after change is %d\n");
INFO_PRINTF2(KFunc1, get);
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// SETVAL with errno ERANGE
TInt CTestSemaphore::semctltest9()
{
int sem_id,ret=KErrNone,get=0,get1=0;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} arg;
if ((sem_id = semget(IPC_PRIVATE,1, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
arg.val = -3;
get1 = semctl(sem_id, 0, GETVAL);
if (get1 == -1)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc, "semaphore variable semval before change is %d\n");
INFO_PRINTF2(KFunc, get1);
get = semctl(sem_id, 0, SETVAL,arg);
if (get != -1 && errno != ERANGE)
{
_LIT(KFunc, "semaphore SETVAL didnt set the proper errno");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
get = semctl(sem_id, 0, GETVAL);
if (get != get1)
{
_LIT(KFunc, "semaphore GETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KFunc1, "semaphore variable semval after change is %d\n");
INFO_PRINTF2(KFunc1, get);
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// for getpid
TInt CTestSemaphore::semctltest10()
{
int sem_id,ret=KErrNone,get=0;
if ((sem_id = semget(IPC_PRIVATE,1, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
get = semctl(sem_id, 0, GETPID);
if (get == -1)
{
_LIT(KFunc, "semaphore GETPID failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(get != 0)
{
_LIT(KFunc, "semaphore GETPID didnt get the proper pid\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// for getncnt
TInt CTestSemaphore::semctltest11()
{
int sem_id,ret=KErrNone,get=0;
if ((sem_id = semget(IPC_PRIVATE,1, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
get = semctl(sem_id, 0, GETNCNT);
if (get != 0)
{
_LIT(KFunc, "semaphore GETNCNT failed with errno %d\n");
INFO_PRINTF2(KFunc, get);
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// for getzcnt
TInt CTestSemaphore::semctltest12()
{
int sem_id,ret=KErrNone,get=0;
if ((sem_id = semget(IPC_PRIVATE,1, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
get = semctl(sem_id, 0, GETZCNT);
if (get != 0)
{
_LIT(KFunc, "semaphore GETZCNT failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (semctl(sem_id, 0, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// proper SETVAL and GETVAL
TInt CTestSemaphore::semctltest13()
{
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
};
int semid;
union semun tmpo;
int ret = KErrNone,ret1;
unsigned short tmp[4];
unsigned short tmpi[4];
tmp[0] = 3;
tmp[1] = 7;
tmp[2] = 9;
tmp[3] = 19;
semid = semget(IPC_PRIVATE ,4, IPC_CREAT | IPC_EXCL | 0666);
if(semid == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
tmpo.array = &tmp[0];
ret1 = semctl(semid, 3, SETALL ,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore SETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
tmpo.array = &tmpi[0];
ret1 = semctl(semid, 3,GETALL ,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if(tmpi[0] != tmp[0] || tmpi[1] != tmp[1] || tmpi[2] != tmp[2] || tmpi[3] != tmp[3])
{
_LIT(KFunc, "semaphore SETALL didnt set the proper values %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (semctl(semid, 3, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// SETVAL and GETVAL which sets the errno ERANGE
TInt CTestSemaphore::semctltest14()
{
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
};
int semid;
union semun tmpo;
int ret=KErrNone,ret1;
unsigned short tmp[3];
tmp[0] = 3;
tmp[1] = 7;
tmp[2] = 9;
semid = semget(IPC_PRIVATE ,4, IPC_CREAT | IPC_EXCL | 0666);
if(semid == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
tmpo.array = &tmp[0];
ret1 = semctl(semid, 3, SETALL ,tmpo);
if(ret1 != -1 && errno != ERANGE)
{
_LIT(KFunc, "semaphore SETALL didnt set the proper errno\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(semid, 3, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// SEMOP
// check for the errno E2BIG
TInt CTestSemaphore::semoptest1()
{
int msq_id,ret=KErrNone,semnops=35,err;
struct sembuf lSemBuf[35];
if ((msq_id = semget(IPC_PRIVATE,35, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = i;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != E2BIG)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (semctl(msq_id, 34, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// check for the errno EFBIG with sem_num < 0
TInt CTestSemaphore::semoptest2()
{
int msq_id,ret=KErrNone,semnops=3;
struct sembuf lSemBuf[3];
if ((msq_id = semget(IPC_PRIVATE,3, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = i-1;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EFBIG)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (semctl(msq_id, 2, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// check for the errno EFBIG with sem_num >= nsems
TInt CTestSemaphore::semoptest3()
{
int msq_id,ret=KErrNone,semnops=3;
struct sembuf lSemBuf[3];
if ((msq_id = semget(IPC_PRIVATE,3, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = semnops+3;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EFBIG)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (semctl(msq_id, 2, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// check for the errno EIDRM
TInt CTestSemaphore::semoptest4()
{
int msq_id,ret=KErrNone,semnops=3;
struct sembuf lSemBuf[3];
if ((msq_id = semget(IPC_PRIVATE,3, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =i;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
if (semctl(msq_id, 2, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EIDRM)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// check for the errno EINVAL with invalid semid
TInt CTestSemaphore::semoptest5()
{
int msq_id=-1,ret=KErrNone,semnops=3;
struct sembuf lSemBuf[3];
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =i;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EINVAL)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is a positive integer and the calling process has alter permission, the value of sem_op shall be added to semval
TInt CTestSemaphore::semoptest6()
{
int msq_id,ret=KErrNone,semnops=2;
int ret1,i;
struct sembuf lSemBuf[3];
union semun tmpo;
unsigned short tmpi[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =1;
lSemBuf[i].sem_op = 1;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err == -1)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
if( tmpi[0] != 0 && tmpi[1] != 2)
{
_LIT(KFunc, "semaphore semop failed and didnt modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is 0 and the calling process has read permission,
// If semval is 0, semop() shall return immediately. ( with out any flags )
TInt CTestSemaphore::semoptest7()
{
int msq_id,ret=KErrNone,semnops=2;
int ret1,i;
struct sembuf lSemBuf[3];
union semun tmpo;
unsigned short tmpi[2];
unsigned short tmp1[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =1;
lSemBuf[i].sem_op = 0;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err == -1)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmp1[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmp1[i]);
}
if( tmp1[0] != tmpi[0] && tmp1[1] != tmpi[1])
{
_LIT(KFunc, "semaphore semop failed and didnt modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is 0 and the calling process has read permission,
// If semval is 0, semop() shall return immediately. ( with IPC_NOWAIT flags )
TInt CTestSemaphore::semoptest8()
{
int msq_id,ret=KErrNone,semnops=2;
int ret1,i;
struct sembuf lSemBuf[3];
union semun tmpo;
unsigned short tmpi[2];
unsigned short tmp1[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =1;
lSemBuf[i].sem_op = 0;
lSemBuf[i].sem_flg = IPC_NOWAIT;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err == -1)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmp1[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmp1[i]);
}
if( tmp1[0] != tmpi[0] && tmp1[1] != tmpi[1])
{
_LIT(KFunc, "semaphore semop failed and modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is 0 and the calling process has read permission,
// If semval is non-zero and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately.
TInt CTestSemaphore::semoptest9()
{
int msq_id,ret=KErrNone,semnops=2;
int ret1,i,get;
struct sembuf lSemBuf[3];
union semun tmpo,arg;
unsigned short tmpi[2];
unsigned short tmp1[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
// setval to be done
arg.val = 3;
get = semctl(msq_id, 1, SETVAL,arg);
if (get == -1)
{
_LIT(KFunc, "semaphore SETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num =1;
lSemBuf[i].sem_op = 0;
lSemBuf[i].sem_flg = IPC_NOWAIT;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EAGAIN)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmp1[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmp1[i]);
}
if( tmp1[0] != 0 && tmp1[1] != 3)
{
_LIT(KFunc, "semaphore semop failed and didnt modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is a negative integer and the calling process has alter permission,
// If semval is greater than or equal to the absolute value of sem_op, the absolute value of sem_op is subtracted from semval.
TInt CTestSemaphore::semoptest10()
{
int msq_id,ret=KErrNone,semnops=1;
int ret1,i,get;
struct sembuf lSemBuf[3];
union semun tmpo,arg;
unsigned short tmpi[2];
unsigned short tmp1[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
// for(i=0;i<2;i++)
// {
lSemBuf[0].sem_num = 1;
lSemBuf[0].sem_op = -1;
lSemBuf[0].sem_flg = 0;
// }
arg.val = 3;
get = semctl(msq_id, 1, SETVAL,arg);
if (get == -1)
{
_LIT(KFunc, "semaphore SETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err == -1)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmp1[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmp1[i]);
}
if( tmp1[0] != tmpi[0] && tmp1[1] != (tmpi[1] - 2))
{
_LIT(KFunc, "semaphore semop failed and didnt modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is a negative integer and the calling process has alter permission,
// If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately.
TInt CTestSemaphore::semoptest11()
{
int msq_id,ret=KErrNone,semnops=1;
int ret1,i;
struct sembuf lSemBuf[3];
union semun tmpo;
unsigned short tmpi[2];
unsigned short tmp1[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
lSemBuf[0].sem_num = 1;
lSemBuf[0].sem_op = -1;
lSemBuf[0].sem_flg = IPC_NOWAIT;
TInt err = semop(msq_id, &lSemBuf[0], semnops);
if(err != -1 && errno != EAGAIN)
{
_LIT(KFunc, "semaphore operation failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
_LIT(KStmt,"After Semop operations ");
INFO_PRINTF1(KStmt);
tmpo.array = &tmp1[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmp1[i]);
}
if( tmp1[0] != tmpi[0] && tmp1[1] != tmpi[1] )
{
_LIT(KFunc, "semaphore semop failed and modified the semval\n");
INFO_PRINTF1(KFunc);
ret = KErrGeneral;
}
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// THREADS
// If sem_op is 0 and the calling process has read permission,
// If semval is non-zero and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semzcnt associated with the specified semaphore and suspend execution of the calling thread until one of the following occurs:
// The value of semval becomes 0, at which time the value of semzcnt associated with the specified semaphore shall be decremented.
void* ThreadEntryOp(void* arg)
{
int semnops=2;
int msgq_id = (int)arg;
struct sembuf lSemBuf[3];
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = 1;
lSemBuf[i].sem_op = 0;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msgq_id, &lSemBuf[0], 2); // blocks here
// check semzcnt
int get = semctl(msgq_id, 1, GETZCNT);
return NULL;
}
TInt ThreadSemOpTest(int msgq_id)
{
int get;
union semun arg;
int ret = KErrNone;
// check semzcnt
get = semctl(msgq_id, 1, GETZCNT);
if( get != 1 )
{
ret = KErrGeneral;
}
// make semval to 0
arg.val = 0;
get = semctl(msgq_id, 1, SETVAL,arg);
if (get == -1)
{
ret = KErrGeneral;
}
// wait ;
sleep(10);
return ret;
}
TInt SemOpThreadMain( int id )
{
TInt err = KErrNone;
int threadRetVal = 0,get;
void *threadRetValPtr = (void*)&threadRetVal;
pthread_t testThread;
err = pthread_create(&testThread,(pthread_attr_t *)NULL,ThreadEntryOp,(TAny*)id);
if (!err)
{
sleep(2);
err = ThreadSemOpTest(id);
}
get = semctl(id, 1, GETZCNT);
if( get != 0 )
{
err = KErrGeneral;
}
pthread_join(testThread, &threadRetValPtr);
return err;
}
TInt CTestSemaphore::semoptest12()
{
int msq_id,ret=KErrNone;
int ret1,i,get;
union semun tmpo,arg;
unsigned short tmpi[2];
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
// setval to be done
arg.val = 3;
get = semctl(msq_id, 1, SETVAL,arg);
if (get == -1)
{
_LIT(KFunc, "semaphore SETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
ret = SemOpThreadMain(msq_id);
sleep(2);
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
return ret;
}
// If sem_op is 0 and the calling process has read permission, one of the following shall occur:
//If semval is non-zero and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semzcnt associated with the specified semaphore and suspend execution of the calling thread until one of the following occurs:
//The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.
void* ThreadEntryOp1(void* arg)
{
int semnops=2,err;
int msgq_id = (int)arg;
struct sembuf lSemBuf[3];
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = 1;
lSemBuf[i].sem_op = 0;
lSemBuf[i].sem_flg = 0;
}
err = semop(msgq_id, &lSemBuf[0], 2); // blocks here
if(err == -1 && errno == EIDRM)
{
iFlag=1;
}
return NULL;
}
TInt ThreadSemOpTest1(int msgq_id)
{
int get;
int ret = KErrNone;
// check semzcnt
get = semctl(msgq_id, 1, GETZCNT);
if( get != 1 )
{
ret = KErrGeneral;
}
// delete the semaphore
if (semctl(msgq_id, 1, IPC_RMID) == -1)
{
ret = KErrGeneral;
}
// wait ;
sleep(10);
return ret;
}
TInt SemOpThreadMain1( int id )
{
TInt err = KErrNone;
int threadRetVal = 0;
void *threadRetValPtr = (void*)&threadRetVal;
pthread_t testThread;
err = pthread_create(&testThread,(pthread_attr_t *)NULL,ThreadEntryOp1,(TAny*)id);
if (!err)
{
sleep(2);
err = ThreadSemOpTest1(id);
}
pthread_join(testThread, &threadRetValPtr);
return err;
}
TInt CTestSemaphore::semoptest13()
{
int msq_id,ret=KErrNone;
int ret1,i,get;
union semun tmpo,arg;
unsigned short tmpi[2];
iFlag = 0;
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
// setval to be done
arg.val = 3;
get = semctl(msq_id, 1, SETVAL,arg);
if (get == -1)
{
_LIT(KFunc, "semaphore SETVAL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
ret = SemOpThreadMain1(msq_id);
sleep(2);
if(!iFlag)
{
ret = KErrGeneral;
}
return ret;
}
// If sem_op is a negative integer and the calling process has alter permission, one of the following shall occur:
// If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semncnt associated with the specified semaphore and suspend execution of the calling thread until one of the following conditions occurs:
// The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.
void* ThreadEntryOp2(void* arg)
{
int semnops=2;
int msgq_id = (int)arg;
struct sembuf lSemBuf[3];
for(int i=0;i<semnops;i++)
{
lSemBuf[i].sem_num = 1;
lSemBuf[i].sem_op = -1;
lSemBuf[i].sem_flg = 0;
}
TInt err = semop(msgq_id, &lSemBuf[0], 2); // blocks here
if(err == -1 && errno == EIDRM)
{
iFlag=1;
}
return NULL;
}
TInt ThreadSemOpTest2(int msgq_id)
{
int get;
int ret = KErrNone;
// check semzcnt
get = semctl(msgq_id, 1, GETNCNT);
if( get != 1 )
{
ret = KErrGeneral;
}
// delete the semaphore
if (semctl(msgq_id, 1, IPC_RMID) == -1)
{
ret = KErrGeneral;
}
// wait ;
sleep(10);
return ret;
}
TInt SemOpThreadMain2( int id )
{
TInt err = KErrNone;
int threadRetVal = 0;
void *threadRetValPtr = (void*)&threadRetVal;
pthread_t testThread;
err = pthread_create(&testThread,(pthread_attr_t *)NULL,ThreadEntryOp2,(TAny*)id);
if (!err)
{
sleep(2);
err = ThreadSemOpTest2(id);
}
pthread_join(testThread, &threadRetValPtr);
return err;
}
TInt CTestSemaphore::semoptest14()
{
int msq_id,ret=KErrNone;
int ret1,i;
union semun tmpo;
unsigned short tmpi[2];
iFlag = 0;
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
ret = SemOpThreadMain2(msq_id);
sleep(2);
if(!iFlag)
{
ret = KErrGeneral;
}
return ret;
}
// If sem_op is a negative integer and the calling process has alter permission, one of the following shall occur:
// If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semncnt associated with the specified semaphore and suspend execution of the calling thread until one of the following conditions occurs:
// The value of semval becomes greater than or equal to the absolute value of sem_op. When this occurs, the value of semncnt associated with the specified semaphore shall be decremented, the absolute value of sem_op shall be subtracted from semval
void* ThreadEntryOp3(void* arg)
{
int get;
int msgq_id = (int)arg;
struct sembuf lSemBuf[3];
lSemBuf[0].sem_num = 0;
lSemBuf[0].sem_op = 0;
lSemBuf[0].sem_flg = 0;
lSemBuf[1].sem_num = 1;
lSemBuf[1].sem_op = -1;
lSemBuf[1].sem_flg = 0;
TInt err = semop(msgq_id, &lSemBuf[0], 2); // blocks here
if(err == -1)
{
iFlag = 0 ;
}
// check semzcnt
get = semctl(msgq_id, 1, GETNCNT);
if( get != 0 )
{
iFlag = 0;
}
// get the semval
get = semctl(msgq_id, 1, GETVAL);
if (get != 2)
{
iFlag = 0;
}
return NULL;
}
TInt ThreadSemOpTest3(int msgq_id)
{
int get;
union semun arg;
int ret = KErrNone;
// check semzcnt
get = semctl(msgq_id, 1, GETNCNT);
if( get != 1 )
{
ret = KErrGeneral;
}
// make semval to 3
arg.val = 3;
get = semctl(msgq_id, 1, SETVAL,arg);
if (get == -1)
{
ret = KErrGeneral;
}
// wait ;
sleep(10);
return ret;
}
TInt SemOpThreadMain3( int id )
{
TInt err = KErrNone;
int threadRetVal = 0,get;
void *threadRetValPtr = (void*)&threadRetVal;
pthread_t testThread;
err = pthread_create(&testThread,(pthread_attr_t *)NULL,ThreadEntryOp3,(TAny*)id);
if (!err)
{
sleep(2);
err = ThreadSemOpTest3(id);
}
get = semctl(id, 1, GETZCNT);
if( get != 0 )
{
err = KErrGeneral;
}
pthread_join(testThread, &threadRetValPtr);
return err;
}
TInt CTestSemaphore::semoptest15()
{
int msq_id,ret=KErrNone;
int ret1,i;
union semun tmpo;
unsigned short tmpi[2];
iFlag = 1;
if ((msq_id = semget(IPC_PRIVATE,2, IPC_R|IPC_CREAT | IPC_EXCL | 0666)) == -1)
{
_LIT(KFunc, "semaphore create failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
return KErrGeneral;
}
_LIT(KStmt1,"Before Semop operations ");
INFO_PRINTF1(KStmt1);
tmpo.array = &tmpi[0];
ret1 = semctl(msq_id, 1,GETALL,tmpo);
if(ret1 == -1)
{
_LIT(KFunc, "semaphore GETALL failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
for(i=0;i<2;i++)
{
_LIT(KFunc, "semaphore GETVAL for the %d semaphore is %d \n");
INFO_PRINTF3(KFunc, i,tmpi[i]);
}
ret = SemOpThreadMain3(msq_id);
sleep(2);
if (semctl(msq_id, 1, IPC_RMID) == -1)
{
_LIT(KFunc, "semaphore delete failed with errno %d\n");
INFO_PRINTF2(KFunc, errno);
ret = KErrGeneral;
}
if (!iFlag)
{
ret = KErrGeneral;
}
return ret;
}
| [
"none@none"
] | [
[
[
1,
4256
]
]
] |
96f2e48b010cadfb4fd5df44164af28067f5e7aa | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /GServerEngine/Public/CList.h | 4e8ad8c0ff5713dba9a47700531a6b835dec31bb | [] | no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 2,512 | h | /*
* File : CList.h
* Brief : 实现一个简单双向链表类
* Author: Expter
* Creat Date: [2009/11/2]
*/
#pragma once
template<class T>
class TLinkedList
{
public:
int Size;
T *Head;
T *Tail;
TLinkedList()
{
Head = Tail = NULL;
Size = 0;
}
~TLinkedList(){ ReleaseList(); }
/*
* 链表的Get操作
*/
T* GetHead(){ return Head; }
T* GetTail(){ return Tail; }
T* GetNext(T* Node){ return Node->next;}
T* GetPrev(T* Node){ return Node->prev;}
int GetSize() { return Size; }
/*
* Add , Insert ,Delete操作
*/
void AddNode(T* Node)
{
Node->next = Node->prev = NULL;
if(this->Head == NULL)
{
this->Head = Node;
this->Tail = Node;
this->Size = 1;
}
else
{
this->Tail->next = Node;
Node->prev = this->Tail;
this->Tail = Node;
this->Size++;
}
}
void AddNodeToHead(T* Node)
{
Node->next = Node->prev = NULL;
if(this->Head == NULL)
{
this->Head = Node;
this->Tail = Node;
this->Size = 1;
}
else
{
this->Head->prev = Node;
Node->next = this->Head;
this->Head = Node;
this->Size++;
}
}
void InsertNode(T* Find_Node,T* Insert_Node)
{
Insert_Node->next = Insert_Node->prev = NULL;
if(Find_Node->next != NULL)
{
T temp;
temp.next = Find_Node->next;
Find_Node->next = Insert_Node;
Insert_Node->next = temp.next;
Insert_Node->prev = Find_Node;
temp.next->prev = Insert_Node;
}
else
{
Insert_Node->prev = Find_Node;
Find_Node->next = Insert_Node;
this->Tail = Insert_Node;
}
this->Size++;
}
void RemoveNode(T* Del_Node)
{
// head point
if(Del_Node->prev == NULL)
{
if(Del_Node->next != NULL)
{
this->Head = Del_Node->next;
this->Head->prev = NULL;
this->Size--;
}
else
{
this->Head = this->Tail = NULL;
this->Size = 0;
}
}
else
{
if(Del_Node->next != NULL)
{
Del_Node->prev->next = Del_Node->next;
Del_Node->next->prev = Del_Node->prev;
this->Size--;
}
else
{
Tail = Del_Node->prev;
Tail->next = NULL;
this->Size--;
}
}
Del_Node->prev = Del_Node->next = NULL;
}
void ReleaseList()
{
if(this->Head)
{
T* temp1=this->Head;
T* temp2;
while(temp1)
{
temp2 = temp1->next;
RemoveNode(temp1);
temp1 = temp2;
}
}
}
};
| [
"[email protected]"
] | [
[
[
1,
166
]
]
] |
a5bdcde663c6a4a3a93ff847c3f752db9579f380 | 3d6cc0b90c27288f44ebc00f9f91e333a82bf335 | /src/tutorial_1/percentdonecallback.h | 1fa3b8437448a50d8ae7dbf4c24d66f334073f81 | [] | no_license | JohnnyRussian7/fife-tutorials | 3b5527641c3a6dfc8208afceee71c920bfb30702 | d57f57def7c6f5ddb569b10d97d45ab23ace7d53 | refs/heads/master | 2021-01-10T16:36:58.622231 | 2011-04-04T04:12:47 | 2011-04-04T04:12:47 | 54,366,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,824 | h | /***************************************************************************
* Copyright (C) 2005-2008 by the FIFE team *
* http://www.fifengine.de *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
#ifndef FIFE_PERCENT_DONE_CALLBACK_H
#define FIFE_PERCENT_DONE_CALLBACK_H
// Standard C++ library includes
#include <vector>
// 3rd party library includes
#include "util/base/fife_stdint.h"
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
namespace FIFE
{
class PercentDoneListener
{
public:
virtual ~PercentDoneListener();
virtual void OnEvent(unsigned int percentDone);
};
class PercentDoneCallback
{
public:
PercentDoneCallback();
virtual ~PercentDoneCallback();
void setTotalNumberOfElements(unsigned int totalElements);
void setPercentDoneInterval(unsigned int percent);
void incrementCount();
void reset();
void addListener(PercentDoneListener* listener);
void removeListener(PercentDoneListener* listener);
private:
void fireEvent(unsigned int percent);
private:
uint32_t m_totalElements;
uint32_t m_percent;
uint32_t m_numberOfEvents;
uint32_t m_count;
typedef std::vector<PercentDoneListener*> ListenerContainer;
ListenerContainer m_listeners;
};
PercentDoneListener* createPercentDoneListener();
}
#endif
| [
"manning.jesse@38a4def6-a25c-11de-9e49-a714085a53fc"
] | [
[
[
1,
73
]
]
] |
abae128b72a825fc8e70377a6ab499be8df293dd | 9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab | /tests/729/sft/TalkDll/SendClient.cpp | 83e6fdce215efc0d300ebd2670ba72f72db68dc4 | [] | no_license | zzjs2001702/sfsipua-svn | ca3051b53549066494f6264e8f3bf300b8090d17 | e8768338340254aa287bf37cf620e2c68e4ff844 | refs/heads/master | 2022-01-09T20:02:20.777586 | 2006-03-29T13:24:02 | 2006-03-29T13:24:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,242 | cpp | // SendClient.cpp : implementation file
//
#include "stdafx.h"
#include "SendClient.h"
#include "head.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSendClient
CSendClient::CSendClient(CMyWaveIn *pIn,CInterface *pInterface):
m_pIn(NULL),
m_pInterFace(NULL)
{
m_pBuffer = new char[1024];
m_pIn = pIn;
m_pInterFace = pInterface;
}
CSendClient::~CSendClient()
{
delete [1024]m_pBuffer;
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CSendClient, CAsyncSocket)
//{{AFX_MSG_MAP(CSendClient)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CSendClient member functions
void CSendClient::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
struct TalkFrame *frame;
frame = (struct TalkFrame *)m_pBuffer;
int iLen = sizeof(struct TalkFrame);
while(iLen > 0)
{
int i = Receive (m_pBuffer + sizeof(struct TalkFrame) - iLen,iLen);
if (i == SOCKET_ERROR )
return ;
iLen -= i;
}
if (strcmp(frame->cFlag ,"TalkFrame") != 0)
{
return;
}
iLen = frame->iLen;
frame->iLen;
while (iLen > 0)
{
int i = Receive (
m_pBuffer + sizeof(struct TalkFrame) + (frame->iLen - iLen),
iLen);
if (i == SOCKET_ERROR)
return ;
iLen -= i;
}
CString add;
UINT port;
switch (frame->iCom )
{
case TC_AGREE_TALK:
GetPeerName (add,port);
m_pInterFace->TalkStart (add);
m_pIn->EnableSend (TRUE);
m_pInterFace->m_bWork = TRUE;
break;
default:
break;
}
CAsyncSocket::OnReceive(nErrorCode);
}
void CSendClient::OnClose(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
m_bConnect = FALSE;
m_pInterFace->BeClose ();
CAsyncSocket::OnClose(nErrorCode);
}
void CSendClient::OnConnect(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
m_pInterFace->ConnectResult(nErrorCode);
CAsyncSocket::OnConnect(nErrorCode);
}
| [
"yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd"
] | [
[
[
1,
106
]
]
] |
5012481e2547cf396b3a8753b28e864b627690ac | 203f8465075e098f69912a6bbfa3498c36ce2a60 | /sandbox/point_cloud_clustering/src/3rd_party/KmUtils.cpp | a9fe55d8693450edc7fa2bbd6f656fc6435e70d1 | [] | no_license | robcn/personalrobots-pkg | a4899ff2db9aef00a99274d70cb60644124713c9 | 4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a | refs/heads/master | 2021-06-20T16:28:29.549716 | 2009-09-04T23:56:10 | 2009-09-04T23:56:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | // See KmUtils.h
//
// Author: David Arthur ([email protected]), 2009
//#include "KmUtils.h"
#include <point_cloud_clustering/3rd_party/KmUtils.h>
#include <iostream>
using namespace std;
int __KMeansAssertionFailure(const char *file, int line, const char *expression) {
cout << "ASSERTION FAILURE, " << file << " line " << line << ":" << endl;
cout << " " << expression << endl;
exit(-1);
}
| [
"danmuno@f5854215-dd47-0410-b2c4-cdd35faa7885"
] | [
[
[
1,
14
]
]
] |
d2ae9f46684ba6b8d38e9c3572eecdfb5ebac2bc | 279b68f31b11224c18bfe7a0c8b8086f84c6afba | /playground/shelta/obsolete/findik-poc-3/request_parser.cpp | e08a5bb438d53bdebdbe303d8f15240fd87988ce | [] | no_license | bogus/findik | 83b7b44b36b42db68c2b536361541ee6175bb791 | 2258b3b3cc58711375fe05221588d5a068da5ea8 | refs/heads/master | 2020-12-24T13:36:19.550337 | 2009-08-16T21:46:57 | 2009-08-16T21:46:57 | 32,120,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,437 | cpp | #include "request_parser.hpp"
#include "request.hpp"
namespace findik {
namespace io {
request_parser::request_parser()
: state_(method_start)
{
}
void request_parser::reset()
{
state_ = method_start;
}
boost::tribool request_parser::consume(request& req, char input)
{
switch (state_)
{
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
state_ = method;
req.method.push_back(input);
return boost::indeterminate;
}
case method:
if (input == ' ')
{
state_ = uri;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
req.method.push_back(input);
return boost::indeterminate;
}
case uri_start:
if (is_ctl(input))
{
return false;
}
else
{
state_ = uri;
req.uri.push_back(input);
return boost::indeterminate;
}
case uri:
if (input == ' ')
{
state_ = http_version_h;
return boost::indeterminate;
}
else if (is_ctl(input))
{
return false;
}
else
{
req.uri.push_back(input);
return boost::indeterminate;
}
case http_version_h:
if (input == 'H')
{
state_ = http_version_t_1;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_t_1:
if (input == 'T')
{
state_ = http_version_t_2;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_t_2:
if (input == 'T')
{
state_ = http_version_p;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_p:
if (input == 'P')
{
state_ = http_version_slash;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_slash:
if (input == '/')
{
req.http_version_major = 0;
req.http_version_minor = 0;
state_ = http_version_major_start;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_major_start:
if (is_digit(input))
{
req.http_version_major = req.http_version_major * 10 + input - '0';
state_ = http_version_major;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_major:
if (input == '.')
{
state_ = http_version_minor_start;
return boost::indeterminate;
}
else if (is_digit(input))
{
req.http_version_major = req.http_version_major * 10 + input - '0';
return boost::indeterminate;
}
else
{
return false;
}
case http_version_minor_start:
if (is_digit(input))
{
req.http_version_minor = req.http_version_minor * 10 + input - '0';
state_ = http_version_minor;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_minor:
if (input == '\r')
{
state_ = expecting_newline_1;
return boost::indeterminate;
}
else if (is_digit(input))
{
req.http_version_minor = req.http_version_minor * 10 + input - '0';
return boost::indeterminate;
}
else
{
return false;
}
case expecting_newline_1:
if (input == '\n')
{
state_ = header_line_start;
return boost::indeterminate;
}
else
{
return false;
}
case header_line_start:
if (input == '\r')
{
state_ = expecting_newline_3;
return boost::indeterminate;
}
else if (!req.headers.empty() && (input == ' ' || input == '\t'))
{
state_ = header_lws;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
req.headers.push_back(header());
req.headers.back().name.push_back(input);
state_ = header_name;
return boost::indeterminate;
}
case header_lws:
if (input == '\r')
{
state_ = expecting_newline_2;
return boost::indeterminate;
}
else if (input == ' ' || input == '\t')
{
return boost::indeterminate;
}
else if (is_ctl(input))
{
return false;
}
else
{
state_ = header_value;
req.headers.back().value.push_back(input);
return boost::indeterminate;
}
case header_name:
if (input == ':')
{
state_ = space_before_header_value;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
req.headers.back().name.push_back(input);
return boost::indeterminate;
}
case space_before_header_value:
if (input == ' ')
{
state_ = header_value;
return boost::indeterminate;
}
else
{
return false;
}
case header_value:
if (input == '\r')
{
state_ = expecting_newline_2;
return boost::indeterminate;
}
else if (is_ctl(input))
{
return false;
}
else
{
req.headers.back().value.push_back(input);
return boost::indeterminate;
}
case expecting_newline_2:
if (input == '\n')
{
state_ = header_line_start;
return boost::indeterminate;
}
else
{
return false;
}
case expecting_newline_3:
return (input == '\n');
default:
return false;
}
}
bool request_parser::is_char(int c)
{
return c >= 0 && c <= 127;
}
bool request_parser::is_ctl(int c)
{
return c >= 0 && c <= 31 || c == 127;
}
bool request_parser::is_tspecial(int c)
{
switch (c)
{
case '(': case ')': case '<': case '>': case '@':
case ',': case ';': case ':': case '\\': case '"':
case '/': case '[': case ']': case '?': case '=':
case '{': case '}': case ' ': case '\t':
return true;
default:
return false;
}
}
bool request_parser::is_digit(int c)
{
return c >= '0' && c <= '9';
}
} // namespace server3
} // namespace http
| [
"shelta@d40773b4-ada0-11de-b0a2-13e92fe56a31"
] | [
[
[
1,
316
]
]
] |
aa989016c2ea1551cb8e8a858de3fd55c5683a99 | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/unordered/detail/hash_table.hpp | 7a27082cdc9fbdbf4615b086cca047fb2053d64c | [] | 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 | 10,785 | hpp |
// Copyright (C) 2003-2004 Jeremy B. Maitin-Shepard.
// Copyright (C) 2005-2008 Daniel James
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNORDERED_DETAIL_HASH_TABLE_HPP_INCLUDED
#define BOOST_UNORDERED_DETAIL_HASH_TABLE_HPP_INCLUDED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <boost/config.hpp>
#include <cstddef>
#include <boost/config/no_tr1/cmath.hpp>
#include <algorithm>
#include <utility>
#include <stdexcept>
#include <boost/iterator.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/limits.hpp>
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/unordered/detail/allocator_helpers.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/mpl/aux_/config/eti.hpp>
#if defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL)
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/not.hpp>
#endif
#if BOOST_WORKAROUND(__BORLANDC__, <= 0x0582)
#define BOOST_UNORDERED_BORLAND_BOOL(x) (bool)(x)
#else
#define BOOST_UNORDERED_BORLAND_BOOL(x) x
#endif
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
#define BOOST_UNORDERED_MSVC_RESET_PTR(x) unordered_detail::reset(x)
#else
#define BOOST_UNORDERED_MSVC_RESET_PTR(x)
#endif
namespace boost {
namespace unordered_detail {
template <class T> struct type_wrapper {};
static const std::size_t default_initial_bucket_count = 50;
static const float minimum_max_load_factor = 1e-3f;
template <class T>
inline void hash_swap(T& x, T& y)
{
#if defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP)
std::swap(x,y);
#else
using std::swap;
swap(x, y);
#endif
}
inline std::size_t double_to_size_t(double f)
{
return f >= static_cast<double>((std::numeric_limits<std::size_t>::max)()) ?
(std::numeric_limits<std::size_t>::max)() :
static_cast<std::size_t>(f);
}
// prime number list, accessor
template<typename T> struct prime_list_template
{
static std::size_t const value[];
static std::ptrdiff_t const length;
};
template<typename T>
std::size_t const prime_list_template<T>::value[] = {
53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul };
template<typename T>
std::ptrdiff_t const prime_list_template<T>::length = 28;
typedef prime_list_template<std::size_t> prime_list;
// no throw
inline std::size_t next_prime(std::size_t n) {
std::size_t const* const prime_list_begin = prime_list::value;
std::size_t const* const prime_list_end = prime_list_begin +
prime_list::length;
std::size_t const* bound =
std::lower_bound(prime_list_begin, prime_list_end, n);
if(bound == prime_list_end)
bound--;
return *bound;
}
// no throw
inline std::size_t prev_prime(std::size_t n) {
std::size_t const* const prime_list_begin = prime_list::value;
std::size_t const* const prime_list_end = prime_list_begin +
prime_list::length;
std::size_t const* bound =
std::upper_bound(prime_list_begin,prime_list_end, n);
if(bound != prime_list_begin)
bound--;
return *bound;
}
// Controls how many buckets are allocated and which buckets hash
// values map to. Does not contain the buckets themselves, or ever
// deal with them directly.
struct bucket_manager {
std::size_t bucket_count_;
bucket_manager()
: bucket_count_(0) {}
explicit bucket_manager(std::size_t n)
: bucket_count_(next_prime(n)) {}
std::size_t bucket_count() const {
return bucket_count_;
}
std::size_t bucket_from_hash(std::size_t hashed) const {
return hashed % bucket_count_;
}
std::size_t max_bucket_count(std::size_t max_size) const {
return prev_prime(max_size);
}
};
// pair_cast - used to convert between pair types.
template <class Dst1, class Dst2, class Src1, class Src2>
inline std::pair<Dst1, Dst2> pair_cast(std::pair<Src1, Src2> const& x)
{
return std::pair<Dst1, Dst2>(Dst1(x.first), Dst2(x.second));
}
#if !defined(BOOST_NO_STD_DISTANCE)
using ::std::distance;
#else
template <class ForwardIterator>
inline std::size_t distance(ForwardIterator i, ForwardIterator j) {
std::size_t x;
std::distance(i, j, x);
return x;
}
#endif
struct move_tag {};
// Both hasher and key_equal's copy/assign can throw so double
// buffering is used to copy them.
template <typename Hash, typename Pred>
struct buffered_functions
{
typedef Hash hasher;
typedef Pred key_equal;
class functions
{
std::pair<hasher, key_equal> functions_;
public:
functions(hasher const& h, key_equal const& k)
: functions_(h, k) {}
hasher const& hash_function() const
{
return functions_.first;
}
key_equal const& key_eq() const
{
return functions_.second;
}
};
typedef functions buffered_functions::*functions_ptr;
buffered_functions(hasher const& h, key_equal const& k)
: func1_(h, k), func2_(h, k), func_(&buffered_functions::func1_) {}
// This copies the given function objects into the currently unused
// function objects and returns a pointer, that func_ can later be
// set to, to commit the change.
//
// Strong exception safety (since only usued function objects are
// changed).
functions_ptr buffer(buffered_functions const& x) {
functions_ptr ptr = func_ == &buffered_functions::func1_
? &buffered_functions::func2_ : &buffered_functions::func1_;
this->*ptr = x.current();
return ptr;
}
void set(functions_ptr ptr) {
BOOST_ASSERT(ptr != func_);
func_ = ptr;
}
functions const& current() const {
return this->*func_;
}
private:
functions func1_;
functions func2_;
functions_ptr func_; // The currently active functions.
};
}
}
#define BOOST_UNORDERED_EQUIVALENT_KEYS 1
#include <boost/unordered/detail/hash_table_impl.hpp>
#undef BOOST_UNORDERED_EQUIVALENT_KEYS
#define BOOST_UNORDERED_EQUIVALENT_KEYS 0
#include <boost/unordered/detail/hash_table_impl.hpp>
#undef BOOST_UNORDERED_EQUIVALENT_KEYS
namespace boost {
namespace unordered_detail {
class iterator_access
{
public:
template <class Iterator>
static BOOST_DEDUCED_TYPENAME Iterator::base const& get(Iterator const& it) {
return it.base_;
}
};
template <class ValueType, class KeyType,
class Hash, class Pred, class Alloc>
class hash_types_unique_keys
{
public:
typedef BOOST_DEDUCED_TYPENAME
boost::unordered_detail::rebind_wrap<Alloc, ValueType>::type
value_allocator;
typedef hash_table_unique_keys<ValueType, KeyType, Hash, Pred,
value_allocator> hash_table;
typedef hash_table_data_unique_keys<value_allocator> data;
typedef BOOST_DEDUCED_TYPENAME data::iterator_base iterator_base;
typedef hash_const_local_iterator_unique_keys<value_allocator> const_local_iterator;
typedef hash_local_iterator_unique_keys<value_allocator> local_iterator;
typedef hash_const_iterator_unique_keys<value_allocator> const_iterator;
typedef hash_iterator_unique_keys<value_allocator> iterator;
typedef BOOST_DEDUCED_TYPENAME data::size_type size_type;
typedef std::ptrdiff_t difference_type;
};
template <class ValueType, class KeyType,
class Hash, class Pred, class Alloc>
class hash_types_equivalent_keys
{
public:
typedef BOOST_DEDUCED_TYPENAME
boost::unordered_detail::rebind_wrap<Alloc, ValueType>::type
value_allocator;
typedef hash_table_equivalent_keys<ValueType, KeyType, Hash, Pred,
value_allocator> hash_table;
typedef hash_table_data_equivalent_keys<value_allocator> data;
typedef BOOST_DEDUCED_TYPENAME data::iterator_base iterator_base;
typedef hash_const_local_iterator_equivalent_keys<value_allocator> const_local_iterator;
typedef hash_local_iterator_equivalent_keys<value_allocator> local_iterator;
typedef hash_const_iterator_equivalent_keys<value_allocator> const_iterator;
typedef hash_iterator_equivalent_keys<value_allocator> iterator;
typedef BOOST_DEDUCED_TYPENAME data::size_type size_type;
typedef std::ptrdiff_t difference_type;
};
} // namespace boost::unordered_detail
} // namespace boost
#undef BOOST_UNORDERED_BORLAND_BOOL
#undef BOOST_UNORDERED_MSVC_RESET_PTR
#endif // BOOST_UNORDERED_DETAIL_HASH_TABLE_HPP_INCLUDED
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] | [
[
[
1,
307
]
]
] |
0c77bcf3379d2dc054fde70d4c4a2e3fbff6d61d | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/GUI/DynamicTheme.h | 2525579a8d7bad37c804ff20992497b4e4bf5062 | [] | no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,059 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## DefaultPainter.h - Default GUI painter //
// ### # # ### //
// # ### # ### Default painter for all nuclex GUI elements //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_GUI_DYNAMICTHEME_H
#define NUCLEX_GUI_DYNAMICTHEME_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Storage/Serializer.h"
#include "Nuclex/Storage/ResourceSet.h"
#include "Nuclex/GUI/Theme.h"
#include "Nuclex/Support/Color.h"
#include "Nuclex/Video/VertexDrawer.h"
#include <deque>
#include <map>
namespace Nuclex {
namespace Storage { class StorageServer; }
namespace Video { class VideoServer; class Image; }
namespace Text { class TextServer; }
}
namespace Nuclex { namespace GUI {
// //
// Nuclex::GUI::DynamicTheme //
// //
/// Dynamic GUI theme
/** GUI theme with dynamically loaded layout description. The layout can for example
be read from an XML description using the XML serializer implementation.
*/
class DynamicTheme :
public Theme {
public:
/// Constructor
NUCLEX_API DynamicTheme(
const shared_ptr<Storage::StorageServer> &spStorageServer,
const shared_ptr<Video::VideoServer> &spVideoServer,
const shared_ptr<Text::TextServer> &spTextServer
);
/// Destructor
NUCLEX_API virtual ~DynamicTheme();
//
// DynamicTheme implementation
//
public:
/// Load object from serializer
NUCLEX_API void load(const shared_ptr<Storage::Serializer> &spSerializer);
//
// Theme implementation
//
public:
/// Draw skinned cell
NUCLEX_API void drawCell(
Video::VertexDrawer &VD,
const string &sStyle,
const Box2<float> &Region,
const string &sState = "normal"
);
/// Draw text
NUCLEX_API void drawText(
Video::VertexDrawer &VD,
const string &sStyle,
const Box2<float> &Region,
const wstring &sText,
const string &sState = "normal"
);
/// Measure text region
NUCLEX_API Box2<float> measureRegion(
const string &sStyle,
const wstring &sText,
const string &sState = "normal"
);
/// Draw cursor
NUCLEX_API void drawCaret(
Video::VertexDrawer &VD,
const string &sStyle,
const Box2<float> &Region,
const wstring &sText,
size_t CursorPos,
bool bInsertMode,
const string &sState = "normal"
);
private:
/// A deque of strings
typedef std::deque<string> ResourceDeque;
/// Stores the layout of a widget
struct Style {
/// State which a widget can be in
struct State {
/// Image used for the widget's visualization
struct Image {
/// How to place the bitmap
enum Placement {
P_TOPLEFT, ///< Place in top left corner
P_TOP, ///< Stretch over top border
P_TOPRIGHT, ///< Place in top right corner
P_LEFT, ///< Stretch over left border
P_CENTER, ///< Stretch in center
P_RIGHT, ///< Stretch over right border
P_BOTTOMLEFT, ///< Place in bottom left corner
P_BOTTOM, ///< Stretch over bottom border
P_BOTTOMRIGHT ///< Place in bottom right corner
};
shared_ptr<Video::Image> spImage; ///< The bitmap
Color ImageColor; ///< The bitmap's color
};
/// A map of bitmaps
typedef std::map<Image::Placement, Image> ImageMap;
ImageMap Images; ///< Images for this state
shared_ptr<Text::Font> spFont; ///< Font to use for text
Text::Font::Alignment eTextAlignment; ///< How to align text
Color TextColor; ///< Color for the text
Point2<float> TextOffset; ///< Offset of text from center
};
/// A map of states
typedef std::map<string, State> StateMap;
StateMap States; ///< States of the widget
};
/// A map of widget layouts
typedef std::map<string, Style> StyleMap;
/// Get bitmap placement from string
static Style::State::Image::Placement placementFromString(const string &sPlacement);
/// Get alignment of font from string
static Text::Font::Alignment alignmentFromString(const string &sAlignment);
string m_sName; ///< The theme's name
shared_ptr<Video::VideoServer> m_spVideoServer; ///< Image server to store bitmaps in
Storage::ResourceSet m_Resources; ///< Resources of the theme
StyleMap m_Styles; ///< The theme's styles
};
}} // namespace Nuclex::GUI
#endif // NUCLEX_GUI_DYNAMICTHEME_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
] | [
[
[
1,
153
]
]
] |
55894d8a5af7b698fe64c45f869f4b58177121c2 | aad1b23210f64324190a93d998a13f9e42f27fbc | /Visualizers/TicTacToe/TicTacToe/Game.cpp | 1806dfe83a5ef9e957fe816be0c03868802edf7f | [] | no_license | abreslav-from-google-code/abreslav | 9272ecdd8d3abf1d541d8f85fad8756184d1c2db | 2d0882e29de0833097bf604ece541b9258ed296f | refs/heads/master | 2016-09-05T15:15:50.343707 | 2010-11-18T22:26:53 | 2010-11-18T22:26:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,270 | cpp | #include "stdafx.h"
#include "Game.h"
////////////////////////////////////////////////////////////////////////////////////////////
const int line = 5;
void Game::clearField()
{
status = PLAY;
surrenderStatus = PLAY;
for (int x = 0; x < H_CELLS; x++)
{
for (int y = 0; y < V_CELLS; y++)
{
field[x][y] = EMPTY;
}
}
notify();
}
void Game::playerSurrendered(CellState s)
{
if ((surrenderStatus == PLAY) && (status == PLAY))
{
surrenderStatus = (s == CIRCLE) ? CROSS_WON : CIRCLE_WON;
notify();
}
}
Game::Status Game::getStatus() const
{
return (surrenderStatus == PLAY) ? status : surrenderStatus;
}
Game::Status Game::checkStatus(int xx, int yy)
{
int l = max(xx - line + 1, 0);
int t = max (yy - line + 1, 0);
int r = min (xx + line - 1, H_CELLS - 1);
int b = min (yy + line - 1, V_CELLS - 1);
#define CHECK_LINE(x, y, dx, dy) \
{\
Status r = checkLine(x, y, dx, dy);\
if (r != PLAY) \
{\
return r;\
}\
}
CHECK_LINE(l, t, 1, 1);// main diagonal
CHECK_LINE(l, b, 1, -1); // secondary diagonal
CHECK_LINE(xx, t, 0, 1); // vertical
CHECK_LINE(l, yy, 1, 0); // horizontal
return PLAY;
}
Game::Status Game::checkLine(int x0, int y0, int dx, int dy)
{
int c = 0;
CellState lastState = EMPTY;
for (int i = 0; i < line * 2 + 1; i++)
{
int x = x0 + i * dx;
int y = y0 + i * dy;
if (field[x][y] == lastState)
{
c++;
if (c >= 5)
{
break;
}
}
else
{
lastState = field[x][y];
c = 1;
}
}
if (c >= 5)
{
if (lastState == CROSS)
{
return CROSS_WON;
}
else if (lastState == CIRCLE)
{
return CIRCLE_WON;
}
}
return PLAY;
}
void Game::setCellState(int x, int y, Game::CellState value)
{
if (status != PLAY)
{
return;
}
if ((x < 0) || (x >= H_CELLS)
|| (y < 0) || (y >= V_CELLS)
|| field[x][y] != EMPTY)
{
status = (value == CROSS) ? CROSS_ERROR : CIRCLE_ERROR;
}
else
{
field[x][y] = value;
status = checkStatus(x, y);
}
notify();
return;
}
Game::CellState Game::getCellState(int x, int y) const
{
if ((x < 0) || (x >= H_CELLS)
|| (y < 0) || (y >= V_CELLS))
{
throw FieldIndexOutOfBounds();
}
return field[x][y];
} | [
"abreslav@f8d81c2c-b11e-0410-9df4-1f401b7bbd07"
] | [
[
[
1,
125
]
]
] |
2d12dc4d940fbf473f9a38c345d2fd9ad33b95a1 | c3531ade6396e9ea9c7c9a85f7da538149df2d09 | /Param/src/OGF/basic/debug/assert.h | f5661adceaa88bbd5594a3ce84a6a3df0f295d21 | [] | no_license | feengg/MultiChart-Parameterization | ddbd680f3e1c2100e04c042f8f842256f82c5088 | 764824b7ebab9a3a5e8fa67e767785d2aec6ad0a | refs/heads/master | 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,576 | h | /*
* OGF/Graphite: Geometry and Graphics Programming Library + Utilities
* Copyright (C) 2000 Bruno Levy
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* [email protected]
*
* ISA Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
* Note that the GNU General Public License does not permit incorporating
* the Software into proprietary programs.
*/
#ifndef __OGF_BASIC_DEBUG_ASSERT__
#define __OGF_BASIC_DEBUG_ASSERT__
#include "OGF/basic/common/common.h"
#include "OGF/basic/debug/logger.h"
#include <string>
namespace OGF {
void BASIC_API ogf_assertion_failed(
const std::string& condition_string,
const std::string& file, int line
) ;
void BASIC_API ogf_range_assertion_failed(
double value, double min_value, double max_value,
const std::string& file, int line
) ;
void BASIC_API ogf_should_not_have_reached(
const std::string& file, int line
) ;
}
// Three levels of assert:
// use ogf_assert() and ogf_range_assert() for non-expensive asserts
// use ogf_debug_assert() and ogf_debug_range_assert() for expensive asserts
// use ogf_parano_assert() and ogf_parano_range_assert() for very exensive asserts
#define ogf_assert(x) { \
if(!(x)) { \
::OGF::ogf_assertion_failed(#x,__FILE__, __LINE__) ; \
} \
}
#define ogf_range_assert(x,min_val,max_val) { \
if(((x) < (min_val)) || ((x) > (max_val))) { \
::OGF::ogf_range_assertion_failed(x, min_val, max_val, \
__FILE__, __LINE__ \
) ; \
} \
}
#define ogf_assert_not_reached { \
::OGF::ogf_should_not_have_reached(__FILE__, __LINE__) ; \
}
#ifdef OGF_DEBUG
#define ogf_debug_assert(x) ogf_assert(x)
#define ogf_debug_range_assert(x,min_val,max_val) ogf_range_assert(x,min_val,max_val)
#else
#define ogf_debug_assert(x)
#define ogf_debug_range_assert(x,min_val,max_val)
#endif
#ifdef OGF_PARANOID
#define ogf_parano_assert(x) ogf_assert(x)
#define ogf_parano_range_assert(x,min_val,max_val) ogf_range_assert(x,min_val,max_val)
#else
#define ogf_parano_assert(x)
#define ogf_parano_range_assert(x,min_val,max_val)
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
102
]
]
] |
589c9a01db0c0d1afef582d35285829ff4e37281 | 453607cc50d8e248e83472e81e8254c5d6997f64 | /packet/include/liftbase.h | 6661ed788e300015efedd478723c23b1b2005023 | [] | no_license | wbooze/test | 9242ba09b65547d422defec34405b843b289053f | 29e20eae9f1c1900bf4bb2433af43c351b9c531e | refs/heads/master | 2016-09-05T11:23:41.471171 | 2011-02-10T10:08:59 | 2011-02-10T10:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,785 | h |
#ifndef _LIFTBASE_H_
#define _LIFTBASE_H_
/** \file
<b>Copyright and Use</b>
You may use this source code without limitation and without
fee as long as you include:
<blockquote>
This software was written and is copyrighted by Ian Kaplan, Bear
Products International, www.bearcave.com, 2002.
</blockquote>
This software is provided "as is", without any warranty or
claim as to its usefulness. Anyone who uses this source code
uses it at their own risk. Nor is any support provided by
Ian Kaplan and Bear Products International.
Please send any bug fixes or suggested source changes to:
<pre>
[email protected]
</pre>
@author Ian Kaplan
*/
#include <assert.h>
/**
This is the base class for simple Lifting Scheme wavelets using
split, predict, update or update, predict, merge steps.
Simple lifting scheme wavelets consist of three steps,
a split/merge step, predict step and an update step:
<ul>
<li>
<p>
The split step divides the elements in an array so that
the even elements are in the first half and the odd
elements are in the second half.
</p>
</li>
<li>
<p>
The merge step is the inverse of the split step. It takes
two regions of an array, an odd region and an even region
and merges them into a new region where an even element
alternates with an odd element.
</p>
</li>
<li>
<p>
The predict step calculates the difference
between an odd element and its predicted value based
on the even elements. The difference between the
predicted value and the actual value replaces the
odd element.
</p>
</li>
<li>
<p>
The predict step operates on the odd elements. The update
step operates on the even element, replacing them with a
difference between the predict value and the actual odd element.
The update step replaces each even element with an average.
The result of the update step becomes the input to the
next recursive step in the wavelet calculation.
</p>
</li>
</ul>
The split and merge methods are shared by all Lifting Scheme wavelet
algorithms. This base class provides the transform and inverse
transform methods (forwardTrans and inverseTrans). The predict
and update methods are abstract and are defined for a particular
Lifting Scheme wavelet sub-class.
This is a template version of the lifting scheme base class. The
template must be instantiated with an array or an object that acts
like an array. Objects that act like arrays define the left hand
side and right hand side index operators: []. To allow wavelet
transforms based on this base class to be used with the wavelet
packet transform, this class makes public both the forward
and inverse transforms (forwardTrans and inverseTrans) and
the forward and inverse transform steps (forwardStep and
inverseStep). These "step" functions are used to calculate
the wavelet packet transform.
<b>Instantiating the Template</b>
The liftbase template takes two type arguments:
<ol>
<li>
The type of the array or '[]' operator indexable object.
</li>
<li>
The type of the data element.
</li>
</ol>
The simplest example is a wavelet class derived from an instance of
the liftbase tempate which takes a double array and has a double
element type. This declaration is shown below:
<pre>
class Haar : public liftbase<double *, double>
</pre>
An object type can be used for the first template argument,
as long as the object supports the '[]' operator, which returns
an element whose type is defined by the second argument. In the
example below, the packcontainer '[]' operator returns a
double.
<pre>
class Poly : public liftbase<packcontainer, double>
</pre>
<b>References:</b>
<ul>
<li>
<a href="http://www.bearcave.com/misl/misl_tech/wavelets/packet/index.html">
<i>The Wavelet Packet Transform</i></a> by Ian Kaplan, www.bearcave.com.
</li>
<li>
<a
href="http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html">
<i>The Wavelet Lifting Scheme</i></a> by Ian Kaplan, www.bearcave.com.
This is the parent web page for this Java source code.
</li>
<li>
<i>Ripples in Mathematics: the Discrete Wavelet Transform</i>
by Arne Jense and Anders la Cour-Harbo, Springer, 2001
</li>
<li>
<i>Building Your Own Wavelets at Home</i> in <a
href="http://www.multires.caltech.edu/teaching/courses/waveletcourse/">
Wavelets in Computer Graphics</a>
</li>
</ul>
\author Ian Kaplan
*/
template <class T, class T_elem >
class liftbase {
public:
typedef enum {
/** "enumeration" for forward wavelet transform */
forward = 1,
/** "enumeration" for inverse wavelet transform */
inverse = 2
} transDirection;
/**
Split the <i>vec</i> into even and odd elements,
where the even elements are in the first half
of the vector and the odd elements are in the
second half.
*/
void split( T& vec, int N )
{
int start = 1;
int end = N - 1;
while (start < end) {
for (int i = start; i < end; i = i + 2) {
T_elem tmp = vec[i];
vec[i] = vec[i+1];
vec[i+1] = tmp;
}
start = start + 1;
end = end - 1;
}
}
/**
Merge the odd elements from the second half of the N element
region in the array with the even elements in the first
half of the N element region. The result will be the
combination of the odd and even elements in a region
of length N.
*/
void merge( T& vec, int N )
{
int half = N >> 1;
int start = half-1;
int end = half;
while (start > 0) {
for (int i = start; i < end; i = i + 2) {
T_elem tmp = vec[i];
vec[i] = vec[i+1];
vec[i+1] = tmp;
}
start = start - 1;
end = end + 1;
}
}
/**
Predict step, to be defined by the subclass
@param vec input array
@param N size of region to act on (from 0..N-1)
@param direction forward or inverse transform
*/
virtual void predict( T& vec, int N, transDirection direction ) = 0;
/**
Reverse predict step.
The predict step applied the high pass filter to the data
set and places the result in the upper half of the array.
The reverse predict step applies the high pass filter and
places the result in the lower half of the array.
This reverse predict step is only used by wavelet packet
frequency analysis algorithms. The default version
of this algorihtm does nothing.
*/
virtual void predictRev( T& vec, int N, transDirection direction ) {};
/**
Update step, to be defined by the subclass
@param vec input array
@param N size of region to act on (from 0..N-1)
@param direction forward or inverse transform
*/
virtual void update( T& vec, int N, transDirection direction ) = 0;
/**
Reverse update step
*/
virtual void updateRev( T& vec, int N, transDirection direction ) {}
public:
/**
One step in the forward wavelet transform
*/
virtual void forwardStep( T& vec, const int n )
{
split( vec, n );
predict( vec, n, forward );
update( vec, n, forward );
} // forwardStep
/**
Reverse forward transform step. The result of the high
pass filter is stored in the lower half of the array
and the result of the low pass filter is stored in the
upper half.
This function should be defined by any subclass that
is used for wavelet frequency analysis.
*/
virtual void forwardStepRev( T& vec, const int N )
{
assert(false);
}
/**
Simple wavelet Lifting Scheme forward transform
forwardTrans is passed an indexable object. The object must
contain a power of two number of data elements. Lifting Scheme
wavelet transforms are calculated in-place and the result is
returned in the argument array.
The result of forwardTrans is a set of wavelet coefficients
ordered by increasing frequency and an approximate average
of the input data set in vec[0]. The coefficient bands
follow this element in powers of two (e.g., 1, 2, 4, 8...).
*/
virtual void forwardTrans( T& vec, const int N )
{
for (int n = N; n > 1; n = n >> 1) {
forwardStep( vec, n );
}
} // forwardTrans
/**
One inverse wavelet transform step
*/
virtual void inverseStep( T& vec, const int n )
{
update( vec, n, inverse );
predict( vec, n, inverse );
merge( vec, n );
}
/**
Reverse inverse transform step. Calculate the inverse transform
from a high pass filter result stored in the lower half of the
array and a low pass filter result stored in the upper half.
This function should be defined by any subclass that
is used for wavelet frequency analysis.
*/
virtual void inverseStepRev( T& vec, const int n )
{
assert( false );
}
/**
Default two step Lifting Scheme inverse wavelet transform
inverseTrans is passed the result of an ordered wavelet
transform, consisting of an average and a set of wavelet
coefficients. The inverse transform is calculated
in-place and the result is returned in the argument array.
*/
virtual void inverseTrans( T& vec, const int N )
{
for (int n = 2; n <= N; n = n << 1) {
inverseStep( vec, n );
}
} // inverseTrans
}; // liftbase
#endif
| [
"[email protected]"
] | [
[
[
1,
350
]
]
] |
2c0c48c89f0837c950458d71fe1bdfb78fc3cb7b | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/dingus/audio/AudioListener.h | 316aefa6b67ff6aa5f225cebe27be329924de32c | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | h | #ifndef __AUDIO_LISTENER_H
#define __AUDIO_LISTENER_H
#include "../math/Matrix4x4.h"
namespace dingus {
class SAudioListener {
public:
SAudioListener()
: velocity(0,0,0), rolloffFactor(1.0f), dopplerFactor(1.0f) { transform.identify(); }
/// World space transform
SMatrix4x4 transform;
/// World space velocity
SVector3 velocity;
/// Rolloff factor
float rolloffFactor;
/// Doppler factor
float dopplerFactor;
};
}; // namespace
#endif
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
000a2a5d038d3bb46a874433ec2baf1ba99ab938 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/graphics/core/win32/direct3d09/materiald3d09.h | 443249a553730854d1ddd5c7cf122f05abcff3c5 | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | h | #ifndef maid2_graphics_core_materiald3d09_h
#define maid2_graphics_core_materiald3d09_h
#include"../../../../config/define.h"
#include"../../imaterial.h"
#include"common.h"
namespace Maid { namespace Graphics {
class MaterialD3D09 : public IMaterial
{
public:
MaterialD3D09( const SPRESOURCE& pRes, const CREATEMATERIALPARAM& param ):IMaterial(pRes,param){}
};
}}
#endif | [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
774cde0a49857ab796ed0a3a3f8cfcf817d42679 | edc5deb5739fdae8494f72380b2d931ec271ebfe | /src/imocapdatabvh.h | e5e573fe5e51f89694566571fbcfaad804dbaf45 | [] | no_license | shuncox/mocapfileimporter | 0d1f5f00ed8b5637261b00bd07f7d57dfbd04245 | ae8a9b45826c81680ff159beb0a9a185843d27c8 | refs/heads/master | 2021-01-10T22:28:27.250839 | 2009-01-08T15:13:57 | 2009-01-08T15:13:57 | 33,865,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | h | ////////////////////////////////////////////////////////////////////////////
//
// MoCap File Importer
// Copyright(c) Shun Cox ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
//
// $Id: imocapdatabvh.h,v 1.2 2006/05/26 07:18:59 zhangshun Exp $
//
////////////////////////////////////////////////////////////////////////////
#ifndef __IMOCAPDATABVH_H__
#define __IMOCAPDATABVH_H__
#include "imocapdata.h"
#define MC_GET_WORD if ((result = tokenBvh.getWord(word)) != MC_SUCCESS) break;
#define MC_TO_UPPER toUppercase(word);
///////////////////////////////////////////////////////////////////////////////
// class for BVH mocap files
//
class iMocapDataBvh : public iMocapData {
public:
iMocapDataBvh(istream *in, iSkeleton *sk) : iMocapData(in, sk) {}
private:
//////////////////////////////////////
// inner class for file parsing
//
class iTokenizerBvh {
istream *input;
vector<string> words;
vector<string>::iterator iter;
public:
iTokenizerBvh() : input(NULL), iter(words.begin()) {}
iTokenizerBvh(istream *in) : input(in), iter(words.begin()) {}
int attach(istream *in);
int getWord(string &oneword);
};
//
//////////////////////////////////////
//////////////////////////////////////
// inner struct for linkage between joints and channels
//
struct iChannelLink {
string jointName;
string typeOrder;
};
//
//////////////////////////////////////
// parse mocap data
int parsing();
};
#endif // #ifndef __IMOCAPDATABVH_H__
| [
"shuncox@50fdbc7c-dc67-11dd-9759-139c9ab14fc6"
] | [
[
[
1,
61
]
]
] |
7ef92749b992d92127cc142b301cbfa9e87d0bc4 | ac12251d20c26624305043453386812170b3d890 | /src/ScriptProvider.cpp | ccfa50e3a57757b96bfa193dbd07081877c360d3 | [] | no_license | minuowa/mono-embed | 3a891bbccb3c5d14744f828ae655c6320b91b5a6 | 5d7df7262653bdd95cf1805645c877f30a937ca8 | refs/heads/master | 2021-01-18T06:45:59.137348 | 2011-05-05T20:23:11 | 2011-05-05T20:23:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp |
#include "ScriptProvider.h"
#include "ScriptType.h"
namespace Talon
{
ScriptProvider ScriptProvider::Instance;
MonoDomain* ScriptProvider::ScriptDomain = NULL;
MonoAssembly* ScriptProvider::ScriptAssembly = NULL;
MonoImage* ScriptProvider::ScriptAssemblyImage = NULL;
monobind::module ScriptProvider::Module(NULL, NULL);
std::vector<ScriptType*>* ScriptProvider::s_registeredTypes = NULL;
void ScriptProvider::Initialize()
{
const char* szScriptAssembly = "TalonScript.dll";
ScriptDomain = mono_jit_init(szScriptAssembly);
ScriptAssembly = mono_domain_assembly_open(ScriptDomain, szScriptAssembly);
ScriptAssemblyImage = mono_assembly_get_image(ScriptAssembly);
Module.SetDomain(ScriptDomain);
Module.SetImage(ScriptAssemblyImage);
printf("Mapping Scripted Types:\n");
std::vector<ScriptType*>::iterator itCurrent = s_registeredTypes->begin();
std::vector<ScriptType*>::iterator itEnd = s_registeredTypes->end();
while (itCurrent != itEnd)
{
ScriptType* pType = *itCurrent;
printf("\t%s\n", pType->GetName());
pType->MapType();
itCurrent++;
}
}
void ScriptProvider::Shutdown()
{
mono_jit_cleanup(ScriptDomain);
}
void ScriptProvider::RegisterType(ScriptType* pType)
{
if (s_registeredTypes == NULL)
s_registeredTypes = new std::vector<ScriptType*>;
s_registeredTypes->push_back(pType);
}
} | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
19
],
[
21,
22
],
[
24,
51
]
],
[
[
20,
20
],
[
23,
23
]
]
] |
b1ca1138440036b18fb9617e476738089898ff16 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_6_029.hpp | 4b376643dd37805b6130d1036324dcec96658553 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,292 | hpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests error reporting: ill-formed group in a source file.
// 17.5: Errorneous #endif without #if in an included file.
#endif
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
46
]
]
] |
89de3a7a181432f2b3aeb9db5960ffd2f40a6763 | cfa1c9f0d1e0bef25f48586d19395b5658752f5b | /Proj_2/ScreenBase.h | 9b98eef610f479e0db63b2ebb4727d559eeb5df6 | [] | no_license | gemini14/AirBall | de9c9a9368bb58d7f7c8fe243a900b11d0596227 | 5d41d3f2c5282f50e7074010f7c1d3b5a804be77 | refs/heads/master | 2021-03-12T21:42:26.819173 | 2011-05-11T08:10:51 | 2011-05-11T08:10:51 | 1,732,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h | #ifndef SCREENBASE_H
#define SCREENBASE_H
#include <boost/noncopyable.hpp>
#include <irrlicht.h>
#include <map>
#include <memory>
#include <string>
#include "EnumsConstants.h"
#include "Game.h"
#include "GUIButton.h"
#include "State.h"
namespace Tuatara
{
class Game;
class GUIButton;
class ScreenBase : public State<Game>, public irr::IEventReceiver, boost::noncopyable
{
protected:
Game *game;
irr::video::ITexture *menuBackground;
typedef std::map<int, GUIButton*> ButtonMap;
ButtonMap buttonList; // derived class add buttons here
public:
ScreenBase();
~ScreenBase();
std::string backgroundPath; // derived class sets this
// will be called when a button is clicked
virtual bool OnClick( int ID ) = 0;
virtual bool OnKeyEvent( irr::EKEY_CODE code ) = 0;
// IEventReceiver, event callback:
virtual bool OnEvent( const irr::SEvent& event);
// State<Game> functions:
virtual void Enter( Game* game );
virtual void Execute( Game* game );
virtual void Exit( Game* game );
};
}
#endif | [
"devnull@localhost"
] | [
[
[
1,
53
]
]
] |
95ab419bedc0cee75e6ded4e3cdfd8622cbb80be | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/include/bikini/system/device.hpp | bc5e566f799bc9056951bbbf5e118e16055e962a | [] | no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | hpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#pragma once
struct device : manager {
struct resource : manager::object {
struct info : manager::object::info {
typedef resource object;
typedef device manager;
info(uint _type);
};
resource(const info &_info, device &_device);
virtual ~resource();
virtual bool create();
virtual bool load();
virtual void destroy();
inline device& get_device() const { return static_cast<device&>(get_manager()); }
inline bool valid() const { return m_version != bad_ID; }
protected:
typedef thread::locker _lock;
inline thread::section& section() { return m_section; }
private:
thread::section m_section;
uint m_version;
};
device();
virtual ~device();
}; | [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef"
] | [
[
[
1,
34
]
]
] |
969f1a6a79db7286cc1b25048623dcfe3ab4b99f | bb8965cede71d539880e29e1b4f1cfaa2d3bf047 | /abanq-2.3-win/src/plugins/styles/kde/styles/plastik/style/config/plastikconf.cpp | dbf53b83c6fbbbd61b49c1b61623333c5cea07f8 | [] | no_license | AliYousuf/abanq-port | 5c968c2e46916f6cac47571a99d50ca429ef2ade | e5d31403325506ea8ee40e01daaa8161607f4c59 | refs/heads/master | 2016-09-01T14:40:02.784138 | 2009-03-19T02:54:48 | 2009-03-19T02:54:48 | 51,658,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,328 | cpp | /*
Copyright (C) 2003 Sandro Giessl <[email protected]>
based on the Keramik configuration dialog:
Copyright (c) 2003 Maksim Orlovich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <qcheckbox.h>
#include <qlayout.h>
#include <qhbox.h>
#include <qsettings.h>
#include <qcolor.h>
#include <qgroupbox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kcolorbutton.h>
//#include <kdemacros.h>
#include "plastikconf.h"
extern "C" DLL_EXPORT
QWidget* allocate_kstyle_config(QWidget* parent)
{
//KGlobal::locale()->insertCatalogue("kstyle_plastik_config");
return new PlastikStyleConfig(parent);
}
PlastikStyleConfig::PlastikStyleConfig(QWidget* parent, const char * name): QWidget(parent)
{
//Should have no margins here, the dialog provides them
QVBoxLayout* layout = new QVBoxLayout(this, 0, 0);
//KGlobal::locale()->insertCatalogue("kstyle_plastik_config");
// scrollBarLines = new QCheckBox(i18n("Scrollbar handle lines"), this);
animateProgressBar = new QCheckBox(i18n("Animate progress bars"), this);
drawToolBarSeparator = new QCheckBox(i18n("Draw toolbar separator"), this);
drawToolBarItemSeparator = new QCheckBox(i18n("Draw toolbar item separators"), this);
// drawFocusRect = new QCheckBox(i18n("Draw focus rectangles"), this);
drawTriangularExpander = new QCheckBox(i18n("Triangular tree expander"), this);
inputFocusHighlight = new QCheckBox(i18n("Highlight focused text input fields"), this);
customFocusHighlightColor = new QCheckBox(i18n("Custom text input highlight color:"), this);
QHBox *hbox1 = new QHBox(this);
hbox1->layout()->addItem(new QSpacerItem(20, 0, QSizePolicy::Fixed, QSizePolicy::Minimum) );
focusHighlightColor = new KColorButton(hbox1);
customOverHighlightColor = new QCheckBox(i18n("Custom mouseover highlight color:"), this);
QHBox *hbox2 = new QHBox(this);
hbox2->layout()->addItem(new QSpacerItem(20, 0, QSizePolicy::Fixed, QSizePolicy::Minimum) );
overHighlightColor = new KColorButton(hbox2);
customCheckMarkColor = new QCheckBox(i18n("Custom checkmark color:"), this);
QHBox *hbox3 = new QHBox(this);
hbox3->layout()->addItem(new QSpacerItem(20, 0, QSizePolicy::Fixed, QSizePolicy::Minimum) );
checkMarkColor = new KColorButton(hbox3);
// layout->add(scrollBarLines);
layout->add(animateProgressBar);
layout->add(drawToolBarSeparator);
layout->add(drawToolBarItemSeparator);
// layout->add(drawFocusRect);
layout->add(drawTriangularExpander);
layout->add(inputFocusHighlight);
layout->add(customFocusHighlightColor);
layout->add(hbox1);
layout->add(customOverHighlightColor);
layout->add(hbox2);
layout->add(customCheckMarkColor);
layout->add(hbox3);
layout->addStretch(1);
QSettings s;
// origScrollBarLines = s.readBoolEntry("/plastikstyle/Settings/scrollBarLines", false);
// scrollBarLines->setChecked(origScrollBarLines);
origAnimProgressBar = s.readBoolEntry("/plastikstyle/Settings/animateProgressBar", false);
animateProgressBar->setChecked(origAnimProgressBar);
origDrawToolBarSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarSeparator", true);
drawToolBarSeparator->setChecked(origDrawToolBarSeparator);
origDrawToolBarItemSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarItemSeparator", true);
drawToolBarItemSeparator->setChecked(origDrawToolBarItemSeparator);
// origDrawFocusRect = s.readBoolEntry("/plastikstyle/Settings/drawFocusRect", true);
// drawFocusRect->setChecked(origDrawFocusRect);
origDrawTriangularExpander = s.readBoolEntry("/plastikstyle/Settings/drawTriangularExpander", false);
drawTriangularExpander->setChecked(origDrawTriangularExpander);
origInputFocusHighlight = s.readBoolEntry("/plastikstyle/Settings/inputFocusHighlight", true);
inputFocusHighlight->setChecked(origInputFocusHighlight);
origCustomOverHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customOverHighlightColor", false);
customOverHighlightColor->setChecked(origCustomOverHighlightColor);
origOverHighlightColor = s.readEntry("/plastikstyle/Settings/overHighlightColor", "black");
overHighlightColor->setColor(origOverHighlightColor);
origCustomFocusHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customFocusHighlightColor", false);
customFocusHighlightColor->setChecked(origCustomFocusHighlightColor);
origFocusHighlightColor = s.readEntry("/plastikstyle/Settings/focusHighlightColor", "black");
focusHighlightColor->setColor(origFocusHighlightColor);
origCustomCheckMarkColor = s.readBoolEntry("/plastikstyle/Settings/customCheckMarkColor", false);
customCheckMarkColor->setChecked(origCustomCheckMarkColor);
origCheckMarkColor = s.readEntry("/plastikstyle/Settings/checkMarkColor", "black");
checkMarkColor->setColor(origCheckMarkColor);
// connect(scrollBarLines, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(animateProgressBar, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(drawToolBarSeparator, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(drawToolBarItemSeparator, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
// connect(drawFocusRect, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(drawTriangularExpander, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(inputFocusHighlight, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(customOverHighlightColor, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(overHighlightColor, SIGNAL( changed(QColor) ), SLOT( updateChanged() ) );
connect(customFocusHighlightColor, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(focusHighlightColor, SIGNAL( changed(QColor) ), SLOT( updateChanged() ) );
connect(customCheckMarkColor, SIGNAL( toggled(bool) ), SLOT( updateChanged() ) );
connect(checkMarkColor, SIGNAL( changed(QColor) ), SLOT( updateChanged() ) );
if ( customOverHighlightColor->isChecked() )
overHighlightColor->setEnabled(true);
else
overHighlightColor->setEnabled(false);
if ( customFocusHighlightColor->isChecked() )
focusHighlightColor->setEnabled(true);
else
focusHighlightColor->setEnabled(false);
if ( customCheckMarkColor->isChecked() )
checkMarkColor->setEnabled(true);
else
checkMarkColor->setEnabled(false);
}
PlastikStyleConfig::~PlastikStyleConfig()
{
}
void PlastikStyleConfig::save()
{
QSettings s;
// s.writeEntry("/plastikstyle/Settings/scrollBarLines", scrollBarLines->isChecked());
s.writeEntry("/plastikstyle/Settings/animateProgressBar", animateProgressBar->isChecked());
s.writeEntry("/plastikstyle/Settings/drawToolBarSeparator", drawToolBarSeparator->isChecked());
s.writeEntry("/plastikstyle/Settings/drawToolBarItemSeparator", drawToolBarItemSeparator->isChecked());
// s.writeEntry("/plastikstyle/Settings/drawFocusRect", drawFocusRect->isChecked());
s.writeEntry("/plastikstyle/Settings/drawTriangularExpander", drawTriangularExpander->isChecked());
s.writeEntry("/plastikstyle/Settings/inputFocusHighlight", inputFocusHighlight->isChecked());
s.writeEntry("/plastikstyle/Settings/customOverHighlightColor", customOverHighlightColor->isChecked());
s.writeEntry("/plastikstyle/Settings/overHighlightColor", QColor(overHighlightColor->color()).name());
s.writeEntry("/plastikstyle/Settings/customFocusHighlightColor", customFocusHighlightColor->isChecked());
s.writeEntry("/plastikstyle/Settings/focusHighlightColor", QColor(focusHighlightColor->color()).name());
s.writeEntry("/plastikstyle/Settings/customCheckMarkColor", customCheckMarkColor->isChecked());
s.writeEntry("/plastikstyle/Settings/checkMarkColor", QColor(checkMarkColor->color()).name());
}
void PlastikStyleConfig::defaults()
{
// scrollBarLines->setChecked(false);
animateProgressBar->setChecked(false);
drawToolBarSeparator->setChecked(true);
drawToolBarItemSeparator->setChecked(true);
// drawFocusRect->setChecked(true);
drawTriangularExpander->setChecked(false);
inputFocusHighlight->setChecked(true);
customOverHighlightColor->setChecked(false);
overHighlightColor->setColor("black");
customFocusHighlightColor->setChecked(false);
focusHighlightColor->setColor("black");
customCheckMarkColor->setChecked(false);
checkMarkColor->setColor("black");
//updateChanged would be done by setChecked already
}
void PlastikStyleConfig::updateChanged()
{
if ( customOverHighlightColor->isChecked() )
overHighlightColor->setEnabled(true);
else
overHighlightColor->setEnabled(false);
if ( customFocusHighlightColor->isChecked() )
focusHighlightColor->setEnabled(true);
else
focusHighlightColor->setEnabled(false);
if ( customCheckMarkColor->isChecked() )
checkMarkColor->setEnabled(true);
else
checkMarkColor->setEnabled(false);
if (/*(scrollBarLines->isChecked() == origScrollBarLines) &&*/
(animateProgressBar->isChecked() == origAnimProgressBar) &&
(drawToolBarSeparator->isChecked() == origDrawToolBarSeparator) &&
(drawToolBarItemSeparator->isChecked() == origDrawToolBarItemSeparator) &&
// (drawFocusRect->isChecked() == origDrawFocusRect) &&
(drawTriangularExpander->isChecked() == origDrawTriangularExpander) &&
(inputFocusHighlight->isChecked() == origInputFocusHighlight) &&
(customOverHighlightColor->isChecked() == origCustomOverHighlightColor) &&
(overHighlightColor->color() == origOverHighlightColor) &&
(customFocusHighlightColor->isChecked() == origCustomFocusHighlightColor) &&
(focusHighlightColor->color() == origFocusHighlightColor) &&
(customCheckMarkColor->isChecked() == origCustomCheckMarkColor) &&
(checkMarkColor->color() == origCheckMarkColor)
)
emit changed(false);
else
emit changed(true);
}
#include "moc_plastikconf.cpp"
| [
"project.ufa@9bbcd52c-0291-11de-9d1a-b59b2e1864b6"
] | [
[
[
1,
225
]
]
] |
045b31586f6744d1015e9c33c4f289ea3f938cfc | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_core/network/juce_URL.cpp | f4dbe4a51df2dbb87ca1d6470acedd486fb5ec9e | [] | 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 | 14,456 | 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
//==============================================================================
URL::URL()
{
}
URL::URL (const String& url_)
: url (url_)
{
int i = url.indexOfChar ('?');
if (i >= 0)
{
do
{
const int nextAmp = url.indexOfChar (i + 1, '&');
const int equalsPos = url.indexOfChar (i + 1, '=');
if (equalsPos > i + 1)
{
if (nextAmp < 0)
{
parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
removeEscapeChars (url.substring (equalsPos + 1)));
}
else if (nextAmp > 0 && equalsPos < nextAmp)
{
parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
}
}
i = nextAmp;
}
while (i >= 0);
url = url.upToFirstOccurrenceOf ("?", false, false);
}
}
URL::URL (const URL& other)
: url (other.url),
postData (other.postData),
parameters (other.parameters),
filesToUpload (other.filesToUpload),
mimeTypes (other.mimeTypes)
{
}
URL& URL::operator= (const URL& other)
{
url = other.url;
postData = other.postData;
parameters = other.parameters;
filesToUpload = other.filesToUpload;
mimeTypes = other.mimeTypes;
return *this;
}
bool URL::operator== (const URL& other) const
{
return url == other.url
&& postData == other.postData
&& parameters == other.parameters
&& filesToUpload == other.filesToUpload
&& mimeTypes == other.mimeTypes;
}
bool URL::operator!= (const URL& other) const
{
return ! operator== (other);
}
URL::~URL()
{
}
namespace URLHelpers
{
String getMangledParameters (const StringPairArray& parameters)
{
String p;
for (int i = 0; i < parameters.size(); ++i)
{
if (i > 0)
p << '&';
p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
<< '='
<< URL::addEscapeChars (parameters.getAllValues() [i], true);
}
return p;
}
int findStartOfDomain (const String& url)
{
int i = 0;
while (CharacterFunctions::isLetterOrDigit (url[i])
|| url[i] == '+' || url[i] == '-' || url[i] == '.')
++i;
return url[i] == ':' ? i + 1 : 0;
}
void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
{
MemoryOutputStream data (postData, false);
if (url.getFilesToUpload().size() > 0)
{
// need to upload some files, so do it as multi-part...
const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
data << "--" << boundary;
int i;
for (i = 0; i < url.getParameters().size(); ++i)
{
data << "\r\nContent-Disposition: form-data; name=\""
<< url.getParameters().getAllKeys() [i]
<< "\"\r\n\r\n"
<< url.getParameters().getAllValues() [i]
<< "\r\n--"
<< boundary;
}
for (i = 0; i < url.getFilesToUpload().size(); ++i)
{
const File file (url.getFilesToUpload().getAllValues() [i]);
const String paramName (url.getFilesToUpload().getAllKeys() [i]);
data << "\r\nContent-Disposition: form-data; name=\"" << paramName
<< "\"; filename=\"" << file.getFileName() << "\"\r\n";
const String mimeType (url.getMimeTypesOfUploadFiles()
.getValue (paramName, String::empty));
if (mimeType.isNotEmpty())
data << "Content-Type: " << mimeType << "\r\n";
data << "Content-Transfer-Encoding: binary\r\n\r\n"
<< file << "\r\n--" << boundary;
}
data << "--\r\n";
}
else
{
data << getMangledParameters (url.getParameters()) << url.getPostData();
// just a short text attachment, so use simple url encoding..
headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
<< (int) data.getDataSize() << "\r\n";
}
}
void concatenatePaths (String& path, const String& suffix)
{
if (! path.endsWithChar ('/'))
path << '/';
if (suffix.startsWithChar ('/'))
path += suffix.substring (1);
else
path += suffix;
}
}
String URL::toString (const bool includeGetParameters) const
{
if (includeGetParameters && parameters.size() > 0)
return url + "?" + URLHelpers::getMangledParameters (parameters);
else
return url;
}
bool URL::isWellFormed() const
{
//xxx TODO
return url.isNotEmpty();
}
String URL::getDomain() const
{
int start = URLHelpers::findStartOfDomain (url);
while (url[start] == '/')
++start;
const int end1 = url.indexOfChar (start, '/');
const int end2 = url.indexOfChar (start, ':');
const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
: jmin (end1, end2);
return url.substring (start, end);
}
String URL::getSubPath() const
{
int start = URLHelpers::findStartOfDomain (url);
while (url[start] == '/')
++start;
const int startOfPath = url.indexOfChar (start, '/') + 1;
return startOfPath <= 0 ? String::empty
: url.substring (startOfPath);
}
String URL::getScheme() const
{
return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
}
URL URL::withNewSubPath (const String& newPath) const
{
int start = URLHelpers::findStartOfDomain (url);
while (url[start] == '/')
++start;
const int startOfPath = url.indexOfChar (start, '/') + 1;
URL u (*this);
if (startOfPath > 0)
u.url = url.substring (0, startOfPath);
URLHelpers::concatenatePaths (u.url, newPath);
return u;
}
URL URL::getChildURL (const String& subPath) const
{
URL u (*this);
URLHelpers::concatenatePaths (u.url, subPath);
return u;
}
//==============================================================================
bool URL::isProbablyAWebsiteURL (const String& possibleURL)
{
const char* validProtocols[] = { "http:", "ftp:", "https:" };
for (int i = 0; i < numElementsInArray (validProtocols); ++i)
if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
return true;
if (possibleURL.containsChar ('@')
|| possibleURL.containsChar (' '))
return false;
const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
.fromLastOccurrenceOf (".", false, false));
return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
}
bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
{
const int atSign = possibleEmailAddress.indexOfChar ('@');
return atSign > 0
&& possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
&& (! possibleEmailAddress.endsWithChar ('.'));
}
//==============================================================================
InputStream* URL::createInputStream (const bool usePostCommand,
OpenStreamProgressCallback* const progressCallback,
void* const progressCallbackContext,
const String& extraHeaders,
const int timeOutMs,
StringPairArray* const responseHeaders) const
{
String headers;
MemoryBlock headersAndPostData;
if (usePostCommand)
URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
headers += extraHeaders;
if (! headers.endsWithChar ('\n'))
headers << "\r\n";
return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
progressCallback, progressCallbackContext,
headers, timeOutMs, responseHeaders);
}
//==============================================================================
bool URL::readEntireBinaryStream (MemoryBlock& destData,
const bool usePostCommand) const
{
const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
if (in != nullptr)
{
in->readIntoMemoryBlock (destData);
return true;
}
return false;
}
String URL::readEntireTextStream (const bool usePostCommand) const
{
const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
if (in != nullptr)
return in->readEntireStreamAsString();
return String::empty;
}
XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
{
return XmlDocument::parse (readEntireTextStream (usePostCommand));
}
//==============================================================================
URL URL::withParameter (const String& parameterName,
const String& parameterValue) const
{
URL u (*this);
u.parameters.set (parameterName, parameterValue);
return u;
}
URL URL::withFileToUpload (const String& parameterName,
const File& fileToUpload,
const String& mimeType) const
{
jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
URL u (*this);
u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
u.mimeTypes.set (parameterName, mimeType);
return u;
}
URL URL::withPOSTData (const String& postData_) const
{
URL u (*this);
u.postData = postData_;
return u;
}
const StringPairArray& URL::getParameters() const
{
return parameters;
}
const StringPairArray& URL::getFilesToUpload() const
{
return filesToUpload;
}
const StringPairArray& URL::getMimeTypesOfUploadFiles() const
{
return mimeTypes;
}
//==============================================================================
String URL::removeEscapeChars (const String& s)
{
String result (s.replaceCharacter ('+', ' '));
if (! result.containsChar ('%'))
return result;
// We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
// after all the replacements have been made, so that multi-byte chars are handled.
Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
for (int i = 0; i < utf8.size(); ++i)
{
if (utf8.getUnchecked(i) == '%')
{
const int hexDigit1 = CharacterFunctions::getHexDigitValue ((juce_wchar) (uint8) utf8 [i + 1]);
const int hexDigit2 = CharacterFunctions::getHexDigitValue ((juce_wchar) (uint8) utf8 [i + 2]);
if (hexDigit1 >= 0 && hexDigit2 >= 0)
{
utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
utf8.removeRange (i + 1, 2);
}
}
}
return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
}
String URL::addEscapeChars (const String& s, const bool isParameter)
{
const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
: ",$_-.*!'()");
Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
for (int i = 0; i < utf8.size(); ++i)
{
const char c = utf8.getUnchecked(i);
if (! (CharacterFunctions::isLetterOrDigit (c)
|| legalChars.indexOf ((juce_wchar) c) >= 0))
{
if (c == ' ')
{
utf8.set (i, '+');
}
else
{
static const char hexDigits[] = "0123456789abcdef";
utf8.set (i, '%');
utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
utf8.insert (++i, hexDigits [c & 15]);
}
}
}
return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
}
//==============================================================================
bool URL::launchInDefaultBrowser() const
{
String u (toString (true));
if (u.containsChar ('@') && ! u.containsChar (':'))
u = "mailto:" + u;
return Process::openDocument (u, String::empty);
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
] | [
[
[
1,
470
]
]
] |
afd0960915e9e516873e645a735a7e029ee6a63d | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/UploadBandwidthThrottler.h | 92962c4a834321793e99941d4e01739163543506 | [] | no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,565 | h | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "ThrottledSocket.h" // ZZ:UploadBandWithThrottler (UDP)
class UploadBandwidthThrottler :
public CWinThread
{
public:
UploadBandwidthThrottler(void);
~UploadBandwidthThrottler(void);
//Xman Xtreme Upload unused
//uint64 GetNumberOfSentBytesSinceLastCallAndReset();
//uint64 GetNumberOfSentBytesOverheadSinceLastCallAndReset();
//uint32 GetHighestNumberOfFullyActivatedSlotsSinceLastCallAndReset();
uint32 GetStandardListSize() { return m_StandardOrder_list.GetSize(); };
//void ReplaceSocket(ThrottledFileSocket* oldsocket, ThrottledFileSocket* newsocket); //Xman Xtreme Upload: Peercache-part
bool ReplaceSocket(ThrottledFileSocket* normalsocket, ThrottledFileSocket* pcsocket, ThrottledFileSocket* newsocket); //Xman Xtreme Upload: Peercache-part
// ==> Superior Client Handling [Stulle] - Stulle
/*
void AddToStandardList(bool first, ThrottledFileSocket* socket); //Xman bugfix: sometimes a socket was placed on wrong position
*/
void AddToStandardList(int posCounter, ThrottledFileSocket* socket); //Xman bugfix: sometimes a socket was placed on wrong position
// <== Superior Client Handling [Stulle] - Stulle
bool RemoveFromStandardList(ThrottledFileSocket* socket);
void QueueForSendingControlPacket(ThrottledControlSocket* socket, bool hasSent = false); // ZZ:UploadBandWithThrottler (UDP)
void RemoveFromAllQueues(ThrottledControlSocket* socket) { RemoveFromAllQueues(socket, true); }; // ZZ:UploadBandWithThrottler (UDP)
void RemoveFromAllQueues(ThrottledFileSocket* socket);
void EndThread();
void Pause(bool paused);
//static uint32 UploadBandwidthThrottler::GetSlotLimit(uint32 currentUpSpeed); //Xman upload unused
//Xman Xtreme Upload
void SetNoNeedSlot();
uint16 GetNumberOfFullyActivatedSlots() {return m_highestNumberOfFullyActivatedSlots_out;}
void SetNumberOfFullyActivatedSlots() {m_highestNumberOfFullyActivatedSlots_out=m_highestNumberOfFullyActivatedSlots;}
void SetNextTrickleToFull();
void RecalculateOnNextLoop();
bool needslot;
//Xman count block/success send
float GetAvgBlockRatio() const {return avgBlockRatio;}
//Xman upload health
float GetAvgHealth() const {return avg_health;}
#ifdef PRINT_STATISTIC
void PrintStatistic();
#endif
private:
static UINT RunProc(LPVOID pParam);
UINT RunInternal();
void RemoveFromAllQueues(ThrottledControlSocket* socket, bool lock); // ZZ:UploadBandWithThrottler (UDP)
bool RemoveFromStandardListNoLock(ThrottledFileSocket* socket);
//uint32 CalculateChangeDelta(uint32 numberOfConsecutiveChanges) const; //Xman upload unused
CTypedPtrList<CPtrList, ThrottledControlSocket*> m_ControlQueue_list; // a queue for all the sockets that want to have Send() called on them. // ZZ:UploadBandWithThrottler (UDP)
CTypedPtrList<CPtrList, ThrottledControlSocket*> m_ControlQueueFirst_list; // a queue for all the sockets that want to have Send() called on them. // ZZ:UploadBandWithThrottler (UDP)
CTypedPtrList<CPtrList, ThrottledControlSocket*> m_TempControlQueue_list; // sockets that wants to enter m_ControlQueue_list // ZZ:UploadBandWithThrottler (UDP)
CTypedPtrList<CPtrList, ThrottledControlSocket*> m_TempControlQueueFirst_list; // sockets that wants to enter m_ControlQueue_list and has been able to send before // ZZ:UploadBandWithThrottler (UDP)
CArray<ThrottledFileSocket*, ThrottledFileSocket*> m_StandardOrder_list; // sockets that have upload slots. Ordered so the most prioritized socket is first
CTypedPtrList<CPtrList, ThrottledFileSocket*> m_StandardOrder_list_full; //Xman Xtreme Upload
CCriticalSection sendLocker;
CCriticalSection tempQueueLocker;
CEvent* threadEndedEvent;
CEvent* pauseEvent;
//Xman Xtreme Upload unused
//uint64 m_SentBytesSinceLastCall;
//uint64 m_SentBytesSinceLastCallOverhead;
uint16 m_highestNumberOfFullyActivatedSlots; //used inside
volatile uint16 m_highestNumberOfFullyActivatedSlots_out; //used outside
bool doRun;
//Xman Xtreme Upload
bool recalculate;
bool nexttrickletofull;
//Xman count block/success send
float avgBlockRatio;
//Xman upload health
struct ratio_struct{
float ratio; // % successful upload loops
uint32 timestamp; // time in 1024 ms units
};
//Xman end
typedef CList<ratio_struct> HealthHistory;
HealthHistory m_healthhistory;
float avg_health; //the average health of last 10 seconds
float sum_healthhistory; //the sum of all stored ratio samples
uint16 m_countsend; //count the sends during ~one second
uint16 m_countsendsuccessful; // " successful
};
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
36
],
[
39,
39
],
[
43,
51
],
[
53,
77
],
[
80,
98
],
[
101,
122
]
],
[
[
37,
38
],
[
40,
42
],
[
52,
52
],
[
78,
79
],
[
99,
100
]
]
] |
8ab06f7469a8ce64abf6e1ce6f5823cf082f911f | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume IX/00948.cpp | 9eb681d3f429ab0e73325d14d13b97267c85663d | [] | no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 675 | cpp | /////////////////////////////////
// 00948 - Fibonaccimal Base
/////////////////////////////////
#include<cstdio>
unsigned short cnum;
unsigned int fib[40],i,tofib;
char tail, ans[100];
int main(void){
fib[0] = fib[1] = 1;
for(i = 2; i < 40; i++) fib[i] = fib[i-1]+fib[i-2];
scanf("%u\n",&cnum);
while(cnum--){
scanf("%u\n",&tofib);
printf("%u = ",tofib);
for(i = 1; fib[i] <= tofib; i++);
tail = 0;
do {
i--;
if(fib[i] <= tofib) tofib -= fib[i], ans[tail++] = '1',i--;
ans[tail++] = '0';
} while(tofib);
if(i==0) tail--;
else while(--i) ans[tail++] = '0';
ans[tail] = 0;
printf("%s (fib)\n",ans);
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
2fa777fbd5de93019ffca6a1690b5a929eb181eb | 960a896c95a759a41a957d0e7dbd809b5929c999 | /Game/AI.h | e413750a01b3a57967e6284fb5bb81cd8abc6b16 | [] | no_license | WSPSNIPER/dangerwave | 8cbd67a02eb45563414eaf9ecec779cc1a7f09d5 | 51af1171880104aa823f6ef8795a2f0b85b460d8 | refs/heads/master | 2016-08-12T09:50:00.996204 | 2010-08-24T22:55:52 | 2010-08-24T22:55:52 | 48,472,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | h | #ifndef _AI_H_
#define _AI_H_
#include "Entity.h"
#include "Trig.h"
#include "LuaManager.h"
using namespace cell;
/**************************************************************************************************
* @class AI
* this is a class for lua that basically will make the AI scripting
* easier lol
***************************************************************************************************/
class AI
{
AI();
public:
virtual ~AI();
static AI *GetInst();
int GetMaxRange() const { return m_range; }
void SetMaxRange(int range) { m_range = range; }
// cant use vectors cause then i would have to give them to lua :(
bool InRange(int x1, int y1, int x2, int y2);
bool InView(float x1, float y1, float x2, float y2, float facingAngle = 0.f);
private:
static AI *m_instance;
int m_range;
};
extern void ExportAI(AI*);
#endif // _AI_H_
| [
"lukefangel@e78017d1-81bd-e181-eab4-ba4b7880cff6"
] | [
[
[
1,
35
]
]
] |
4c0bc006f4c34f898934dd5dabc620aefed35c99 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/C++/vc源码/source/source/2HtmlDlg.h | 09b0ed96ec4b2dceea6c7a4ab23115af72cc9503 | [] | 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 | 1,525 | h | #if !defined(AFX_2HTMLDLG_H__76D701A5_4B1B_11D5_953D_C12A6E8DBB23__INCLUDED_)
#define AFX_2HTMLDLG_H__76D701A5_4B1B_11D5_953D_C12A6E8DBB23__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// 2HtmlDlg.h : header file
//
#include "FlashWnd.h"
/////////////////////////////////////////////////////////////////////////////
// C2HtmlDlg dialog
class C2HtmlDlg : public CDialog
{
// Construction
public:
~C2HtmlDlg();
CString m_TempFileName;
void SaveCodes(CString FileName);
void UpdateCode();
CFlashWnd * p_Flash;
C2HtmlDlg(CFlashWnd *pFlash,BOOL URLMode); // standard constructor
// Dialog Data
//{{AFX_DATA(C2HtmlDlg)
enum { IDD = IDD_2HTML };
CString m_Code;
CString m_Title;
BOOL m_URLMode;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(C2HtmlDlg)
public:
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(C2HtmlDlg)
virtual BOOL OnInitDialog();
afx_msg void OnCopy();
afx_msg void OnMoviePath();
afx_msg void OnChangeHtmlTitle();
afx_msg void OnSave();
afx_msg void OnPreview();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_2HTMLDLG_H__76D701A5_4B1B_11D5_953D_C12A6E8DBB23__INCLUDED_)
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
60
]
]
] |
efd8e50ef9b98ac16bf5d08f44391cab84961de2 | 826479e30cfe9f7b9a1b7262211423d8208ffb68 | /RayTracer.cpp | b2af07137718e3c50246c71ee0eab3cc83c98229 | [] | 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 | 3,148 | cpp | // RayTracer.cpp : Defines the class behaviors for the application.
//
// Author : Jean-Rene Bedard ([email protected])
#include "stdafx.h"
#include "RayTracer.h"
#include "MainFrm.h"
#include "RayTracerDoc.h"
#include "RayTracerView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CRayTracerApp
BEGIN_MESSAGE_MAP(CRayTracerApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()
// CRayTracerApp construction
CRayTracerApp::CRayTracerApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CRayTracerApp object
CRayTracerApp theApp;
// CRayTracerApp initialization
BOOL CRayTracerApp::InitInstance()
{
CWinApp::InitInstance();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(0); // 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(CRayTracerDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CRayTracerView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
return TRUE;
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// App command to run the dialog
void CRayTracerApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CRayTracerApp message handlers
| [
"[email protected]"
] | [
[
[
1,
120
]
]
] |
161d15dd7e977553dfa85ab8972b682be4611124 | 927e18c69355c4bf87b59dffefe59c2974e86354 | /super-go-proj/GoPlayerMove.cpp | acc36c6e76e1b72246b77d4f33b35861fc85a9ca | [] | no_license | lqhl/iao-gim-ca | 6fc40adc91a615fa13b72e5b4016a8b154196b8f | f177268804d1ba6edfd407fa44a113a44203ec30 | refs/heads/master | 2020-05-18T17:07:17.972573 | 2011-06-17T03:54:51 | 2011-06-17T03:54:51 | 32,191,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | //----------------------------------------------------------------------------
/** @file GoPlayerMove.cpp */
//----------------------------------------------------------------------------
#include "GoPlayerMove.h"
#include <iostream>
//----------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, GoPlayerMove mv)
{
out << (mv.Color() == SG_BLACK ? "B " : "W ") << SgWritePoint(mv.Point());
return out;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
17
]
]
] |
2384067b180baf07b3b6c7731a2ed8ed19f7a8f3 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestutilities/src/bctestutilitiescontainer.cpp | 49baad19cdeb2d83dd0fada89de0b20a16c9ba4c | [] | 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 | 3,639 | 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: container
*
*/
#include <aknlists.h>
#include <barsread.h>
#include <bctestutilities.rsg>
#include "bctestutilitiescontainer.h"
#include "bctestutilitiescase.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTestUtilitiesContainer::CBCTestUtilitiesContainer()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestUtilitiesContainer::~CBCTestUtilitiesContainer()
{
ResetControl();
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestUtilitiesContainer::ConstructL( const TRect& aRect )
{
CreateWindowL();
SetRect( aRect );
ActivateL();
}
// ----------------------------------------------------------------------------
// CBCTestUtilitiesContainer::Draw
// Fills the window's rectangle.
// ----------------------------------------------------------------------------
//
void CBCTestUtilitiesContainer::Draw( const TRect& aRect ) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle( CGraphicsContext::ENullPen );
gc.SetBrushColor( KRgbGray );
gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
gc.DrawRect( aRect );
}
// ---------------------------------------------------------------------------
// CBCTestUtilitiesContainer::CountComponentControls
// ---------------------------------------------------------------------------
//
TInt CBCTestUtilitiesContainer::CountComponentControls() const
{
if ( iControl )
{
return 1;
}
else
{
return 0;
}
}
// ---------------------------------------------------------------------------
// CBCTestUtilitiesContainer::ComponentControl
// ---------------------------------------------------------------------------
//
CCoeControl* CBCTestUtilitiesContainer::ComponentControl( TInt ) const
{
return iControl;
}
// ---------------------------------------------------------------------------
// CBCTestUtilitiesContainer::SetControl
// ---------------------------------------------------------------------------
//
void CBCTestUtilitiesContainer::SetControl( CCoeControl* aControl )
{
iControl = aControl;
if ( iControl )
{
// You can change the position and size
iControl->SetExtent( Rect().iTl, Rect().Size() );
DrawNow();
}
}
// ---------------------------------------------------------------------------
// CBCTestUtilitiesContainer::ResetControl
// ---------------------------------------------------------------------------
//
void CBCTestUtilitiesContainer::ResetControl()
{
delete iControl;
iControl = NULL;
}
| [
"none@none"
] | [
[
[
1,
118
]
]
] |
a33e3d2639a0c75339d8d70c6a72c3e7655b75ce | 9e4b72c504df07f6116b2016693abc1566b38310 | /back/Convert.h | 4776aa34a51e3a0e7dd8c01537b52b4007de41a4 | [
"MIT"
] | permissive | mmeeks/rep-snapper | 73311cadd3d8753462cf87a7e279937d284714aa | 3a91de735dc74358c0bd2259891f9feac7723f14 | refs/heads/master | 2016-08-04T08:56:55.355093 | 2010-12-05T19:03:03 | 2010-12-05T19:03:03 | 704,101 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | h | #pragma once
// File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <typeinfo>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(const std::string& s)
: std::runtime_error(s)
{ }
};
template<typename T> inline std::string stringify(const T& x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion(std::string("stringify(") + typeid(x).name() + ")");
return o.str();
}
/*
void myCode()
{
Foo x;
...
std::string s = "this is a Foo: " + stringify(x);
...
} */
template<typename T> inline void convert(const std::string& s, T& x, bool failIfLeftoverChars = true)
{
std::istringstream i(s);
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c))) throw BadConversion(s);
}
/*
void myCode()
{
std::string s = ...a string representation of a Foo...;
...
Foo x;
convert(s, x);
...
...code that uses x...
}
*/
template<typename T>
inline T convertTo(const std::string& s, bool failIfLeftoverChars = true)
{
T x;
convert(s, x, failIfLeftoverChars);
return x;
}
/*
#include "convert.h"
void myCode()
{
std::string a = ...string representation of an int...;
std::string b = ...string representation of an int...;
...
if (convertTo<int>(a) < convertTo<int>(b))
...;
*/ | [
"[email protected]"
] | [
[
[
1,
68
]
]
] |
bd63edfed46c55172e5425333a6b82afc7237c5d | ad85dfd8765f528fd5815d94acde96e28e210a43 | /trunk/include/OpenLayer/Blenders.hpp | 0f43d2666c119d95c8b87beb996a9e9163d8877f | [] | no_license | BackupTheBerlios/openlayer-svn | c53dcdd84b74fd4687c919642e6ccef3dd4bba79 | 3086e76972e6674c9b40282bb7028acb031d0593 | refs/heads/master | 2021-01-01T19:25:13.382956 | 2007-07-18T17:09:55 | 2007-07-18T17:09:55 | 40,823,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,891 | hpp | #ifndef OL_BLENDERS_HPP
#define OL_BLENDERS_HPP
#include "Includes.hpp"
#include "Declspec.hpp"
#include <stack>
namespace ol {
// Blenders - different color blending styles
// Alpha blender (default): renders translucent bitmaps,
// alpha values of the source pixels tell the opacity
//
// Additive blender: Increases the lightness of the underlying pixels
// alpha values of the source pixels tell the intensity
//
// Subtractive blender: Decreases the lightness of the underlying pixels
// alpha values the source pixels tell the intensity
enum Blender {
ALPHA_BLENDER,
ADDITIVE_BLENDER,
SUBTRACTIVE_BLENDER,
COPY_BLENDER,
FULL_ADDITIVE_BLENDER,
CUSTOM
};
class OL_LIB_DECLSPEC Blenders {
public:
// Sets the active blending function //
// Additive blender lits the destination bitmap, //
// subtractive blender darkens it. //
static void Set( Blender blender );
// Sets a custom OpenGL blender as the active blending function //
static void Set( GLenum sourceFactor, GLenum destFactor );
// Pushes the active blender to the blender stack //
inline static void Push() {
blenderStack.push( activeBlender );
}
// Pops the most recently added blender from the blender stack //
static void Pop();
// Selects the active blender (automatically done) //
static void SelectBlender();
private:
class BlenderObj {
public:
BlenderObj()
: source( GL_ONE ), dest( GL_ZERO ) {}
BlenderObj( GLenum source, GLenum dest )
: source( source ), dest( dest ) {}
GLenum source, dest;
};
static BlenderObj activeBlender;
static std::stack< BlenderObj > blenderStack;
};
}
#endif // OL_BLENDERS_HPP
| [
"bradeeoh@9f4572f3-6e0d-0410-ba3b-903ab02ac46b",
"juvinious@9f4572f3-6e0d-0410-ba3b-903ab02ac46b"
] | [
[
[
1,
4
],
[
6,
31
],
[
33,
76
]
],
[
[
5,
5
],
[
32,
32
]
]
] |
f79c0d994020ee950c1dbf5cfe6b4bb2e8c5053e | 208475bcab65438eed5d8380f26eacd25eb58f70 | /GlobalShare/md5.h | f36c9b9b524a10091f1e02e85df79f5fe178ea67 | [] | no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,899 | h | /////////////////////////////////////////////////////////////////////////
// MD5.cpp
// Implementation file for MD5 class
//
// This C++ Class implementation of the original RSA Data Security, Inc.
// MD5 Message-Digest Algorithm is copyright (c) 2002, Gary McNickle.
// All rights reserved. This software is a derivative of the "RSA Data
// Security, Inc. MD5 Message-Digest Algorithm"
//
// You may use this software free of any charge, but without any
// warranty or implied warranty, provided that you follow the terms
// of the original RSA copyright, listed below.
//
// Original RSA Data Security, Inc. Copyright notice
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
// rights reserved.
//
// License to copy and use this software is granted provided that it
// is identified as the "RSA Data Security, Inc. MD5 Message-Digest
// Algorithm" in all material mentioning or referencing this software
// or this function.
// License is also granted to make and use derivative works provided
// that such works are identified as "derived from the RSA Data
// Security, Inc. MD5 Message-Digest Algorithm" in all material
// mentioning or referencing the derived work.
// RSA Data Security, Inc. makes no representations concerning either
// the merchantability of this software or the suitability of this
// software for any particular purpose. It is provided "as is"
// without express or implied warranty of any kind.
// These notices must be retained in any copies of any part of this
// documentation and/or software.
/////////////////////////////////////////////////////////////////////////
/*#if !defined(AFX_MD5KEYGEN_H__EA78E559_1E9F_40D2_BBBE_DF0B0FC97D10__INCLUDED_)
#define AFX_MD5KEYGEN_H__EA78E559_1F9F_40D2_BBBE_DF0B0FC97D10__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
*/
#ifndef _MD5_H_
#define _MD5_H_
typedef unsigned int uint4;
typedef unsigned short int uint2;
typedef unsigned char uchar;
class CMd5
{
// Methods
public:
bool get_car_id(byte *out);
CMd5();
//void Init();
void Update(uchar* chInput, uint4 nInputLen);
void Finalize();
uchar* Digest() { return m_Digest; }
bool PrintMD5(uchar md5Digest[16], char *md5);
bool MD5String(char* szString, BYTE nLen, char *md5);
bool MD5File(char* szFilename, char *md5);
bool MD5File16(char* szFilename, uchar *md5);
private:
void Transform(uchar* block);
void Encode(uchar* dest, uint4* src, uint4 nLength);
void Decode(uint4* dest, uchar* src, uint4 nLength);
inline uint4 rotate_left(uint4 x, uint4 n)
{ return ((x << n) | (x >> (32-n))); }
inline uint4 F(uint4 x, uint4 y, uint4 z)
{ return ((x & y) | (~x & z)); }
inline uint4 G(uint4 x, uint4 y, uint4 z)
{ return ((x & z) | (y & ~z)); }
inline uint4 H(uint4 x, uint4 y, uint4 z)
{ return (x ^ y ^ z); }
inline uint4 I(uint4 x, uint4 y, uint4 z)
{ return (y ^ (x | ~z)); }
inline void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{ a += F(b, c, d) + x + ac; a = rotate_left(a, s); a += b; }
inline void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{ a += G(b, c, d) + x + ac; a = rotate_left(a, s); a += b; }
inline void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{ a += H(b, c, d) + x + ac; a = rotate_left(a, s); a += b; }
inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{ a += I(b, c, d) + x + ac; a = rotate_left(a, s); a += b; }
// Data
private:
uint4 m_State[4];
uint4 m_Count[2];
uchar m_Buffer[64];
uchar m_Digest[16];
uchar m_Finalized;
};
#endif
//#endif // !defined(AFX_MD5KEYGEN_H__EA78E559_1F9F_40D2_BBBE_DF0B0FC97D10__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
113
]
]
] |
3945031661c95b8316ff3bb5d080e2d63f3ebbcb | dde32744a06bb6697823975956a757bd6c666e87 | /bwapi/SCProjects/BTHAIModule/Source/ValkyrieAgent.h | d4462c4f388b0542192cf3e1f1bb031ae89caf5f | [] | no_license | zarac/tgspu-bthai | 30070aa8f72585354ab9724298b17eb6df4810af | 1c7e06ca02e8b606e7164e74d010df66162c532f | refs/heads/master | 2021-01-10T21:29:19.519754 | 2011-11-16T16:21:51 | 2011-11-16T16:21:51 | 2,533,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | h | #ifndef __VALKYRIEAGENT_H__
#define __VALKYRIEAGENT_H__
#include <BWAPI.h>
#include "UnitAgent.h"
using namespace BWAPI;
using namespace std;
/** The ValkyrieAgent handles Terran Valkyrie flying units.
*
* Implemented special abilities:
* - Valkyries doesnt have any special abilities.
*
* Author: Johan Hagelback ([email protected])
*/
class ValkyrieAgent : public UnitAgent {
private:
public:
ValkyrieAgent(Unit* mUnit);
/** Called each update to issue orders. */
void computeActions();
/** Returns the unique type name for unit agents. */
string getTypeName();
};
#endif | [
"rymdpung@.(none)"
] | [
[
[
1,
30
]
]
] |
bb7d165114caa609dce1876040b64932835d6889 | 4275e8a25c389833c304317bdee5355ed85c7500 | /KylTek/Bullet.h | a2bc491fcf8acfa8409c3d473582ebd62c800de3 | [] | no_license | kumorikarasu/KylTek | 482692298ef8ff501fd0846b5f41e9e411afe686 | be6a09d20159d0a320abc4d947d4329f82d379b9 | refs/heads/master | 2021-01-10T07:57:40.134888 | 2010-07-26T12:10:09 | 2010-07-26T12:10:09 | 55,943,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | h | #pragma once
#ifndef BULLET_H_
#define BULLET_H_
#include "CObject.h"
#include "Weapon.h"
class Bullet : public CObject{
public:
int m_xs, m_ys, m_direction;
float m_dis;
int m_alpha;
Bullet(){};
Bullet(CEntity* _parent, float _dir, float _dis);
~Bullet();
virtual void Step(CDeviceHandler *DH);
virtual void Draw(CGraphicsHandler *g);
virtual void onCollision(const Vector2& result, CEntity* pCollideEnt);
};
#endif | [
"Sean Stacey@localhost"
] | [
[
[
1,
26
]
]
] |
bfdc5c9619a19c359bfaf598e7947c9be2e1b175 | 0f3224fcbe7dbfddb1a98f75762a48cd1cfdbf07 | /src/maincharacter.cpp | 07273c20d59fe2c6e1c86df47a7149d8040bbb15 | [] | no_license | Karethoth/LudumDare20 | a534972c3669d7612bbcf60270894156e485e1f4 | 0b5c3f50a1178f37ac5dee9e185700ba081378d5 | refs/heads/master | 2020-05-27T17:06:16.673518 | 2011-05-01T23:37:16 | 2011-05-01T23:37:16 | 1,683,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | #include "maincharacter.hpp"
MainCharacter::MainCharacter()
{
}
MainCharacter::~MainCharacter()
{}
| [
"[email protected]"
] | [
[
[
1,
12
]
]
] |
0c75faa053fab12ad2a634e167238f79aa6e3f67 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/ndebug/src/ndebug/ndebugtrail_main.cc | 30f8bcad3bf8233ed826edd18ffe0fbab75d5c2b | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cc | //------------------------------------------------------------------------------
// ndebugtrail_main.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchndebug.h"
#include "ndebug/ndebugtrail.h"
#include "gfx2/ngfxserver2.h"
//------------------------------------------------------------------------------
/**
*/
nDebugTrail::nDebugTrail()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nDebugTrail::~nDebugTrail()
{
// empty
}
//------------------------------------------------------------------------------
/**
@param gfxServer graphics server
*/
void
nDebugTrail::Draw( nGfxServer2 * const gfxServer )
{
vector4 color;
this->GetColor( color );
gfxServer->BeginLines();
gfxServer->DrawLines3d( this->points.Begin(), this->points.Size() , color );
gfxServer->EndLines();
}
//------------------------------------------------------------------------------
/**
@param point new point
*/
void
nDebugTrail::InsertPoint( const vector3 & point )
{
this->points.Append( point );
}
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
52
]
]
] |
655d98d098cd1a07d4b0d1187d3035b087de1471 | a04058c189ce651b85f363c51f6c718eeb254229 | /Src/Forms/SelectCurrencyForm.hpp | f7d88894ba21dc4f6e70eed940aa87731927addc | [] | no_license | kjk/moriarty-palm | 090f42f61497ecf9cc232491c7f5351412fba1f3 | a83570063700f26c3553d5f331968af7dd8ff869 | refs/heads/master | 2016-09-05T19:04:53.233536 | 2006-04-04T06:51:31 | 2006-04-04T06:51:31 | 18,799 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | hpp | #ifndef _SELECT_CURRENCY_FORM_HPP_
#define _SELECT_CURRENCY_FORM_HPP_
#include "MoriartyForm.hpp"
#include <FormObject.hpp>
#include <HmStyleList.hpp>
#include "MoriartyPreferences.hpp"
class UniversalDataFormat;
class CurrencyListDrawHandler: public ExtendedList::CustomDrawHandler
{
const Preferences& prefs_;
const UniversalDataFormat& currencyData_;
double* amount_;
double* rate_;
public:
enum {
currenciesListItemLines = 1,
currenciesListLineHeight = 12
};
enum Mode
{
modeAvailable,
modeSelected
};
private:
Mode mode_;
public:
CurrencyListDrawHandler(const UniversalDataFormat& currencyData);
CurrencyListDrawHandler(const UniversalDataFormat& currencyData, double& amount, double& rate);
void drawItem(Graphics& graphics, ExtendedList& list, uint_t item, const ArsRectangle& itemBounds);
uint_t itemsCount() const;
~CurrencyListDrawHandler();
};
class SelectCurrencyForm: public MoriartyForm {
HmStyleList currenciesList_;
Control okButton_;
Control cancelButton_;
typedef std::auto_ptr<ExtendedList::CustomDrawHandler> ListDrawHandlerPtr;
ListDrawHandlerPtr currenciesListDrawHandler_;
void handleControlSelected(const EventType& event);
void handleListItemSelected(const EventType& event);
protected:
void attachControls();
bool handleOpen();
void resize(const ArsRectangle& screenBounds);
bool handleEvent(EventType& event);
public:
SelectCurrencyForm(MoriartyApplication& app);
~SelectCurrencyForm();
private:
/*
enum OkMode
{
defaultMode, //one selection possible
multiselectMode
};
OkMode okMode_;
*/
};
#endif // _SELECT_CURRENCY_FORM_HPP_
| [
"andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c"
] | [
[
[
1,
92
]
]
] |
b0c593dc6b3212b3da79535efe8ca2ebfa62f793 | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /AITerm/src/XMLLib/XMLLib.h | 259e5f693ad47b95f916299882f5bc2844f16438 | [] | no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 881 | h |
#include "TinyXML/tinyxml.h"
class XmlNode : private TiXmlNode
{
public:
const XmlNode * GetNode( const char * tagName, unsigned int idx = 0 ) const;
// 태그가 일치하는 자식의 개수를 반환한다.
unsigned int GetNodeCount( const char * tagName ) const;
XmlNode * AddNode( const char * tagName );
const char * GetAttribute( const char * attName ) const;
void SetAttribute( const char * attName, const char * attValue );
enum TextType
{
STRING = 0, NUMBER
};
const char * GetText() const;
void SetText( const char * text, TextType textType );
};
class XmlDocument : private TiXmlDocument
{
public:
bool LoadFile( const char * filename );
bool SaveFile( const char * filename ) const;
const XmlNode * GetNode( const char * tagName, unsigned int idx = 0 ) const;
XmlNode * AddNode( const char * tagName );
};
| [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
] | [
[
[
1,
35
]
]
] |
a838626dac4d91c29e9c104188ab9f7008529794 | bc0a05b60c7ef7180120c577e377a977abd4c725 | /Creatures.cpp | 1be11db749ea0a03d2995a3b771eececea4e887c | [] | no_license | swak/stonesense | 7f0b821d4dcd48ba02b4c0df2850cd7355b4f2fa | 54b791c019d4874c0880fc44903b26af2925231f | refs/heads/master | 2021-01-06T20:37:39.613771 | 2011-08-04T16:55:09 | 2011-08-04T16:55:09 | 42,753,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,050 | cpp | #include "common.h"
#include "Creatures.h"
#include "WorldSegment.h"
#include "CreatureConfiguration.h"
#include "ContentLoader.h"
#include "GUI.h"
#include "Block.h"
#include "SpriteColors.h"
//vector<t_matgloss> v_creatureNames;
//vector<CreatureConfiguration> creatureTypes;
int32_t charToUpper(int32_t c)
{
if(c >= 0x61 && c <= 0x7A)
return c-0x20;
else if(c >= 0xE0 && c <= 0xF6)
return c-0x20;
else if(c >= 0xF8 && c <= 0xFE)
return c-0x20;
else return c;
}
ALLEGRO_USTR* bufferToUstr(const char* buffer, int length)
{
ALLEGRO_USTR* temp = al_ustr_new("");
for(int i = 0; i < length; i++)
{
switch((unsigned char)buffer[i])
{
case 0:
{
i = length;
break;
}
case 128:
{
al_ustr_append_chr(temp, 0xC7);
break;
}
case 129:
{
al_ustr_append_chr(temp, 0xFC);
break;
}
case 130:
{
al_ustr_append_chr(temp, 0xE9);
break;
}
case 131:
{
al_ustr_append_chr(temp, 0xE2);
break;
}
case 132:
{
al_ustr_append_chr(temp, 0xE4);
break;
}
case 133:
{
al_ustr_append_chr(temp, 0xE0);
break;
}
case 134:
{
al_ustr_append_chr(temp, 0xE5);
break;
}
case 135:
{
al_ustr_append_chr(temp, 0xE7);
break;
}
case 136:
{
al_ustr_append_chr(temp, 0xEA);
break;
}
case 137:
{
al_ustr_append_chr(temp, 0xEB);
break;
}
case 138:
{
al_ustr_append_chr(temp, 0xE8);
break;
}
case 139:
{
al_ustr_append_chr(temp, 0xEF);
break;
}
case 140:
{
al_ustr_append_chr(temp, 0xEE);
break;
}
case 141:
{
al_ustr_append_chr(temp, 0xC4);
break;
}
case 142:
{
al_ustr_append_chr(temp, 0xC5);
break;
}
case 143:
{
al_ustr_append_chr(temp, 0xC9);
break;
}
case 144:
{
al_ustr_append_chr(temp, 0xFC);
break;
}
case 145:
{
al_ustr_append_chr(temp, 0xE9);
break;
}
case 146:
{
al_ustr_append_chr(temp, 0xC6);
break;
}
case 147:
{
al_ustr_append_chr(temp, 0xF4);
break;
}
case 148:
{
al_ustr_append_chr(temp, 0xF6);
break;
}
case 149:
{
al_ustr_append_chr(temp, 0xF2);
break;
}
case 150:
{
al_ustr_append_chr(temp, 0xFB);
break;
}
case 151:
{
al_ustr_append_chr(temp, 0xF9);
break;
}
case 152:
{
al_ustr_append_chr(temp, 0xFF);
break;
}
case 153:
{
al_ustr_append_chr(temp, 0xD6);
break;
}
case 154:
{
al_ustr_append_chr(temp, 0xDC);
break;
}
case 160:
{
al_ustr_append_chr(temp, 0xE1);
break;
}
case 161:
{
al_ustr_append_chr(temp, 0xED);
break;
}
case 162:
{
al_ustr_append_chr(temp, 0xF3);
break;
}
case 163:
{
al_ustr_append_chr(temp, 0xFA);
break;
}
case 164:
{
al_ustr_append_chr(temp, 0xF1);
break;
}
case 165:
{
al_ustr_append_chr(temp, 0xD1);
break;
}
default:
{
al_ustr_append_chr(temp, buffer[i]);
break;
}
}
}
return temp;
}
bool IsCreatureVisible( t_creature* c ){
if( config.show_all_creatures ) return true;
if( c->flags1.bits.dead )
return false;
if( c->flags1.bits.caged )
return false;
if( c->flags1.bits.hidden_in_ambush )
return false;
return true;
}
void DrawCreature(int drawx, int drawy, t_creature* creature, Block * b){
vector<int> statusIcons;
//if(config.show_creature_happiness)
if(config.show_creature_moods)
{
if(creature->happiness == 0)
statusIcons.push_back(6);
else if(creature->happiness >= 1 && creature->happiness <= 25)
statusIcons.push_back(5);
else if(creature->happiness >= 26 && creature->happiness <= 50)
statusIcons.push_back(4);
else if(creature->happiness >= 51 && creature->happiness <= 75)
statusIcons.push_back(3);
else if(creature->happiness >= 76 && creature->happiness <= 125)
statusIcons.push_back(2);
else if(creature->happiness >= 126 && creature->happiness <= 150)
statusIcons.push_back(1);
else if(creature->happiness >= 151)
statusIcons.push_back(0);
if(creature->mood == 0)
statusIcons.push_back(19);
else if(creature->mood == 1)
statusIcons.push_back(19);
else if(creature->mood == 2)
statusIcons.push_back(21);
else if(creature->mood == 3)
statusIcons.push_back(19);
else if(creature->mood == 4)
statusIcons.push_back(19);
else if(creature->mood == 5)
statusIcons.push_back(18);
else if(creature->mood == 6)
statusIcons.push_back(18);
if(creature->current_job.active && creature->current_job.jobType == 21)
statusIcons.push_back(16);
else if(creature->current_job.active && creature->current_job.jobType == 52)
statusIcons.push_back(17);
}
c_sprite * sprite = GetCreatureSpriteMap( creature );
//if(creature->x == 151 && creature->y == 145)
// int j = 10;
sprite->draw_world(creature->x,creature->y, creature->z, b);
if(statusIcons.size())
{
for(int i = 0; i < statusIcons.size(); i++)
{
unsigned int sheetx = 16 * (statusIcons[i] % 7);
unsigned int sheety = 16 * (statusIcons[i] / 7);
al_draw_bitmap_region(IMGStatusSheet, sheetx, sheety, 16, 16, drawx - (statusIcons.size()*8) + (16*i) + (SPRITEWIDTH/2), drawy - (16 + WALLHEIGHT + al_get_font_line_height(font)), 0);
}
}
}
void DrawCreatureText(int drawx, int drawy, t_creature* creature ){
if( config.show_creature_names )
if (creature->name.nickname[0] && config.names_use_nick)
{
draw_textf_border(font, al_map_rgb(255,255,255), drawx, drawy-(WALLHEIGHT+al_get_font_line_height(font)), 0,
"%s", creature->name.nickname );
}
else if (creature->name.first_name[0])
{
char buffer[128];
strncpy(buffer,creature->name.first_name,127);
buffer[127]=0;
ALLEGRO_USTR* temp = bufferToUstr(buffer, 128);
al_ustr_set_chr(temp, 0, charToUpper(al_ustr_get(temp, 0)));
draw_ustr_border(font, al_map_rgb(255,255,255), drawx, drawy-(WALLHEIGHT+al_get_font_line_height(font)), 0,
temp );
al_ustr_free(temp);
}
else if (config.names_use_species)
{
if(!config.skipCreatureTypes)
draw_textf_border(font, al_map_rgb(255,255,255), drawx, drawy-(WALLHEIGHT+al_get_font_line_height(font)), 0,
"[%s]", contentLoader.Mats->race.at(creature->race).id);
}
}
//t_creature* global = 0;
void ReadCreaturesToSegment( DFHack::Context& DF, WorldSegment* segment)
{
int x1 = segment->x;
int x2 = segment->x + segment->sizex;
int y1 = segment->y;
int y2 = segment->y + segment->sizey;
int z1 = segment->z;
int z2 = segment->z + segment->sizez;
uint32_t numcreatures;
DFHack::Creatures * Creatures;
if(!config.skipCreatures)
{
try
{
Creatures = DF.getCreatures();
}
catch(exception &err)
{
WriteErr("DFhack exeption: %s\n", err.what());
config.skipCreatures = true;
return;
}
}
try
{
if(!Creatures->Start(numcreatures)) return;
}
catch(exception &err)
{
WriteErr("DFhack exeption: %s \n", err.what());
config.skipCreatures = true;
return;
}
if(!numcreatures) return;
if(x1<0) x1=0;
if(y1<0) y1=0;
if(z1<0) z1=0;
if(x2<0) x2=0;
if(y2<0) y2=0;
if(z2<0) z2=0;
t_creature *tempcreature = new t_creature();
/*for (uint32_t index = 0; index < numcreatures ; index++)
{
Creatures->ReadCreature( index, *tempcreature );*/
uint32_t index = 0;
if(!config.skipCreatures)
{
try
{
while((index = Creatures->ReadCreatureInBox( index, *tempcreature, x1,y1,z1,x2,y2,z2)) != -1 )
{
index++;
if( IsCreatureVisible( tempcreature ) )
{
Block* b = segment->getBlock (tempcreature->x, tempcreature->y, tempcreature->z );
if(!b)
{
//inside segment, but no block to represent it
b = new Block(segment);
b->x = tempcreature->x;
b->y = tempcreature->y;
b->z = tempcreature->z;
// fake block occupancy where needed. This is starting to get hacky...
b->creaturePresent=true;
segment->addBlock( b );
}
if (!b->creature)
{
b->creaturePresent=true;
b->creature = tempcreature;
// add shadow to nearest floor block
for (int bz = tempcreature->z;bz>=z1;bz--)
{
b = segment->getBlock (tempcreature->x, tempcreature->y, bz );
if (!b) continue;
if (b->floorType > 0 || b->wallType > 0 || b->ramp.type > 0)
{
// todo figure out appropriate shadow size
int tempShadow = GetCreatureShadowMap( tempcreature );
if (b->shadow < tempShadow)
b->shadow=tempShadow;
break;
}
}
// need a new tempcreature now
// old tempcreature should be deleted when b is
tempcreature = new t_creature;
}
}
}
}
catch (exception &e)
{
WriteErr("DFhack exeption: %s\n", e.what());
config.skipCreatures = true;
}
}
delete(tempcreature); // there will be one left over
Creatures->Finish();
}
CreatureConfiguration *GetCreatureConfig( t_creature* c ){
//find list for creature type
vector<CreatureConfiguration>* creatureData;
uint32_t num = (uint32_t)contentLoader.creatureConfigs.size();
if (c->race >= num)
{
return NULL;
}
creatureData = contentLoader.creatureConfigs[c->race];
if (creatureData == NULL)
{
return NULL;
}
int rando = randomCube[c->x%RANDOM_CUBE][c->y%RANDOM_CUBE][c->z%RANDOM_CUBE];
int offsetAnimFrame = (currentAnimationFrame + rando) % MAX_ANIMFRAME;
num = (uint32_t)creatureData->size();
for(uint32_t i=0; i < num; i++)
{
CreatureConfiguration *testConfig = &((*creatureData)[i]);
bool creatureMatchesJob = true;
if( testConfig->professionID != INVALID_INDEX )
{
creatureMatchesJob = testConfig->professionID == c->profession;
}
if(!creatureMatchesJob) continue;
bool creatureMatchesSex = true;
if( testConfig->sex != 0 )
{
creatureMatchesSex =
(c->sex == testConfig->sex-1);
}
if(!creatureMatchesSex) continue;
bool creatureMatchesSpecial = true;
if (testConfig->special != eCSC_Any)
{
if (testConfig->special == eCSC_Zombie && !c->flags1.bits.zombie) creatureMatchesSpecial = false;
if (testConfig->special == eCSC_Skeleton && !c->flags1.bits.skeleton) creatureMatchesSpecial = false;
if (testConfig->special == eCSC_Normal && (c->flags1.bits.zombie || c->flags1.bits.skeleton)) creatureMatchesSpecial = false;
}
if(!creatureMatchesSpecial) continue;
if (!(testConfig->sprite.get_animframes() & (1 << offsetAnimFrame)))
continue;
// dont try to match strings until other tests pass
if( testConfig->professionstr[0])
{ //cant be NULL, so check has length
creatureMatchesJob = (strcmp(testConfig->professionstr,c->custom_profession)==0);
}
if(!creatureMatchesJob) continue;
return testConfig;
}
return NULL;
}
c_sprite* GetCreatureSpriteMap( t_creature* c )
{
static c_sprite * defaultSprite = new c_sprite;
defaultSprite->reset();
defaultSprite->set_defaultsheet(IMGCreatureSheet);
CreatureConfiguration *testConfig = GetCreatureConfig( c );
if (testConfig == NULL)
return defaultSprite;
testConfig->sprite.set_defaultsheet(IMGCreatureSheet);
return &(testConfig->sprite);
}
int GetCreatureShadowMap( t_creature* c )
{
CreatureConfiguration *testConfig = GetCreatureConfig( c );
if (testConfig == NULL)
return 4;
return testConfig->shadow;
}
void generateCreatureDebugString( t_creature* c, char* strbuffer){
if(c->flags1.bits.active_invader)
strcat(strbuffer, "activeInvader ");
if(c->flags1.bits.caged)
strcat(strbuffer, "Caged ");
if(c->flags1.bits.chained)
strcat(strbuffer, "chained ");
if(c->flags1.bits.coward)
strcat(strbuffer, "coward ");
if(c->flags1.bits.dead)
strcat(strbuffer, "Dead ");
if(c->flags1.bits.diplomat)
strcat(strbuffer, "Diplomat ");
if(c->flags1.bits.drowning)
strcat(strbuffer, "drowning ");
if(c->flags1.bits.forest)
strcat(strbuffer, "lostLeaving ");
if(c->flags1.bits.fortress_guard)
strcat(strbuffer, "FortGuard ");
if(c->flags1.bits.had_mood)
strcat(strbuffer, "HadMood ");
if(c->flags1.bits.has_mood)
strcat(strbuffer, "Mood ");
if(c->flags1.bits.hidden_ambusher)
strcat(strbuffer, "hiddenAmbush ");
if(c->flags1.bits.hidden_in_ambush)
strcat(strbuffer, "hiddenInAmbush ");
if(c->flags1.bits.important_historical_figure)
strcat(strbuffer, "Historical ");
if(c->flags1.bits.incoming)
strcat(strbuffer, "Incoming ");
if(c->flags1.bits.invades)
strcat(strbuffer, "invading ");
if(c->flags1.bits.marauder)
strcat(strbuffer, "marauder ");
if(c->flags1.bits.merchant)
strcat(strbuffer, "merchant ");
if(c->flags1.bits.on_ground)
strcat(strbuffer, "onGround ");
if(c->flags1.bits.projectile)
strcat(strbuffer, "projectile ");
if(c->flags1.bits.ridden)
strcat(strbuffer, "ridden ");
if(c->flags1.bits.royal_guard)
strcat(strbuffer, "RoyGuard ");
if(c->flags1.bits.skeleton)
strcat(strbuffer, "Skeleton ");
if(c->flags1.bits.tame)
strcat(strbuffer, "Tame ");
if(c->flags1.bits.zombie)
strcat(strbuffer, "Zombie ");
if(c->flags2.bits.slaughter)
strcat(strbuffer, "ReadyToSlaughter ");
if(c->flags2.bits.resident)
strcat(strbuffer, "Resident ");
if(c->flags2.bits.sparring)
strcat(strbuffer, "Sparring ");
if(c->flags2.bits.swimming)
strcat(strbuffer, "Swimming ");
if(c->flags2.bits.underworld)
strcat(strbuffer, "Underworld ");
//if(c->flags1.bits.can_swap)
// strcat(strbuffer, "canSwap ");
//if(c->flags1.bits.check_flows)
// strcat(strbuffer, "checFlows ");
//if(c->flags1.bits.invader_origin)
// strcat(strbuffer, "invader_origin ");
}
| [
"Japa.Mala.Illo@4d48de78-bd66-11de-9616-7b1d4728551e",
"japa.mala.illo@4d48de78-bd66-11de-9616-7b1d4728551e"
] | [
[
[
1,
7
],
[
9,
225
],
[
227,
267
],
[
269,
270
],
[
272,
286
],
[
288,
296
],
[
298,
303
],
[
305,
310
],
[
312,
341
],
[
343,
357
],
[
359,
359
],
[
361,
361
],
[
380,
380
],
[
400,
403
],
[
410,
427
],
[
430,
459
],
[
461,
461
],
[
463,
475
],
[
477,
477
],
[
481,
482
],
[
486,
566
]
],
[
[
8,
8
],
[
226,
226
],
[
268,
268
],
[
271,
271
],
[
287,
287
],
[
297,
297
],
[
304,
304
],
[
311,
311
],
[
342,
342
],
[
358,
358
],
[
360,
360
],
[
362,
379
],
[
381,
399
],
[
404,
409
],
[
428,
429
],
[
460,
460
],
[
462,
462
],
[
476,
476
],
[
478,
480
],
[
483,
485
]
]
] |
2eed4dad92166e3b11cabbcb3fedb1d535d84a0e | 617f35a270887e23ba4dcb69d4b58f0d7943b883 | /canoneos.cpp | daef5671e10d859c83c739bb91aaa8b0062f82d1 | [] | no_license | kkkjackyboy/Arduino_Camera_Control | f0b0c7e4a56c1eae35f23e7ad36367bab1c28059 | 6085d65dee37822d069106960e79bfdf8546bc9f | refs/heads/master | 2020-04-08T20:37:50.255006 | 2010-05-13T21:25:35 | 2010-05-13T21:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,461 | cpp | #include "canoneos.h"
uint32_t ImgQualitySupplier::GetDataSize()
{
return ((pictFormat & 0xFFFF0000) ? 0x0000002C : 0x0000001C);
}
void ImgQualitySupplier::GetData(const uint16_t len, uint8_t *pbuf)
{
uint8_t num_files = (pictFormat & 0xFFFF0000) ? 2 : 1;
((uint32_t*)pbuf)[0] = (num_files == 2) ? 0x0000002C : 0x0000001C;
((uint32_t*)pbuf)[1] = (uint32_t) EOS_DPC_ImageQuality;
((uint32_t*)pbuf)[2] = (uint32_t) num_files;
uint32_t format = pictFormat;
for (uint8_t i=0, pos=3; i<num_files; i++)
{
((uint32_t*)pbuf)[pos++] = 0x00000010;
for (uint8_t j=0; j<3; j++, format >>= 4)
((uint32_t*)pbuf)[pos++] = (uint32_t)(format & 0xF);
}
}
CanonEOS::CanonEOS(uint8_t addr, uint8_t epin, uint8_t epout, uint8_t epint, uint8_t nconf, PTPMAIN pfunc)
: PTP(addr, epin, epout, epint, nconf, pfunc)
{
}
uint16_t CanonEOS::SetImageQuality(uint32_t format)
{
uint16_t ptp_error = PTP_RC_GeneralError;
OperFlags flags = { 0, 0, 1, 1, 1, 0 };
ImgQualitySupplier sup;
sup.SetPictureFormat(format);
if ( (ptp_error = Transaction(PTP_OC_EOS_SetDevicePropValue, &flags, NULL, (void*)&sup)) != PTP_RC_OK)
Message(PSTR("SetImageQuality error"), ptp_error);
return ptp_error;
}
uint16_t CanonEOS::SetPCConnectMode(uint8_t mode)
{
uint32_t params[1];
params[0] = (uint32_t) mode;
return Operation(PTP_OC_EOS_SetPCConnectMode, 1, params);
}
uint16_t CanonEOS::SetExtendedEventInfo(uint8_t mode)
{
uint32_t params[1];
params[0] = (uint32_t) mode;
return Operation(PTP_OC_EOS_SetExtendedEventInfo, 1, params);
}
uint16_t CanonEOS::Initialize(bool binit)
{
uint16_t result1 = PTP_RC_OK, result2 = PTP_RC_OK;
if (binit)
{
result2 = SetExtendedEventInfo(1);
result1 = SetPCConnectMode(1);
}
else
{
result1 = SetPCConnectMode(0);
result2 = SetExtendedEventInfo(0);
}
return (((result1 == PTP_RC_OK) && (result2 == PTP_RC_OK)) ? PTP_RC_OK : PTP_RC_GeneralError);
}
uint16_t CanonEOS::StartBulb()
{
uint32_t params[3];
params[0] = 0xfffffff8;
params[1] = 0x00001000;
params[2] = 0x00000000;
Operation(0x911A, 3, params);
Operation(0x911B, 0, NULL);
Operation(0x9125, 0, NULL);
return PTP_RC_OK;
}
uint16_t CanonEOS::StopBulb()
{
uint32_t params[3];
params[0] = 0xffffffff;
params[1] = 0x00001000;
params[2] = 0x00000000;
Operation(0x911A, 3, params);
params[0] = 0xfffffffc;
Operation(0x911A, 3, params);
Operation(0x9126, 0, NULL);
delay(50);
Operation(0x911C, 0, NULL);
delay(50);
}
uint16_t CanonEOS::SwitchLiveView(bool on)
{
uint16_t ptp_error = PTP_RC_GeneralError;
if ((ptp_error = SetProperty(EOS_DPC_LiveView, (on) ? 2 : 0)) == PTP_RC_OK)
{
if (on)
{
if ((ptp_error = SetProperty(0xD1B3, 0)) != PTP_RC_OK)
{
Message(PSTR("LiveView start failure:"), ptp_error);
SetProperty(EOS_DPC_LiveView, 0);
return PTP_RC_GeneralError;
}
}
}
return ptp_error;
}
uint16_t CanonEOS::MoveFocus(uint16_t step)
{
uint16_t ptp_error = PTP_RC_GeneralError;
OperFlags flags = { 1, 0, 0, 0, 0, 0 };
uint32_t params[1];
params[0] = (uint32_t) step;
if ( (ptp_error = Transaction(PTP_OC_EOS_MoveFocus, &flags, params, NULL)) != PTP_RC_OK)
Message(PSTR("MoveFocus error."), ptp_error);
else
Message(PSTR("MoveFocus: Success."), ptp_error);
return ptp_error;
}
uint16_t CanonEOS::EventCheck(PTPReadParser *parser)
{
uint16_t ptp_error = PTP_RC_GeneralError;
OperFlags flags = { 0, 0, 0, 1, 1, 0 };
if ( (ptp_error = Transaction(0x9116, &flags, NULL, parser)) != PTP_RC_OK)
Message(PSTR("EOSEventCheck error."), ptp_error);
return ptp_error;
}
uint16_t CanonEOS::Capture()
{
return Operation(PTP_OC_EOS_Capture, 0, NULL);
}
uint16_t CanonEOS::Test()
{
uint16_t ptp_error = PTP_RC_GeneralError;
if ((ptp_error = Operation(0x9802, 0, NULL)) != PTP_RC_OK)
Message(PSTR("Test: Error: "), ptp_error);
return ptp_error;
}
uint16_t CanonEOS::SetProperty(uint16_t prop, uint32_t val)
{
uint16_t ptp_error = PTP_RC_GeneralError;
OperFlags flags = { 0, 0, 1, 1, 3, 12 };
uint32_t params[3];
params[0] = 0x0000000C;
params[1] = (uint32_t)prop;
params[2] = val;
if ( (ptp_error = Transaction(PTP_OC_EOS_SetDevicePropValue, &flags, NULL, (void*)params)) != PTP_RC_OK)
Message(PSTR("SetProperty: Error."), ptp_error);
return ptp_error;
}
| [
"[email protected]"
] | [
[
[
1,
186
]
]
] |
991923c006660c798f682ce9207f825ea04532a8 | e87cea8c829923b1adedb7e9b28e13988ea848a7 | /oberon/KeywordTable.h | a1c953a7e3556cd2efbfb81fcb92104eb134e8c0 | [] | no_license | joycode/oberon-0 | cd2bedf0aa835061aaf11fc8e7685f97374a6d5f | 92c4806d8eaf3c294dd6a8c3b5be93026836ccf6 | refs/heads/master | 2021-01-25T08:48:15.103032 | 2011-06-02T09:47:59 | 2011-06-02T09:47:59 | 1,970,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | h | #ifndef KEYWORD_TABLE_H
#define KEYWORD_TABLE_H
#include <cassert>
#include <string>
#include <vector>
#include "SymbolKind.h"
#include "Util.h"
struct KeywordInfo;
typedef const KeywordInfo * CP_KeywordInfo;
class KeywordTable {
private:
struct KeywordInfo {
std::string m_keyword;
SymbolKind::T_SymbolKind m_symbolKind;
KeywordInfo(std::string keyword, SymbolKind::T_SymbolKind symbolKind)
{
m_keyword = keyword;
m_symbolKind = symbolKind;
}
};
// simple but ineffcient
static const CP_KeywordInfo m_keywords[];
static const std::vector<CP_KeywordInfo> m_keywords2;
public:
// test if @word is a keyword?
// if true, store corresponding Symbol Kind in @result
static bool isKeyword(std::string word, SymbolKind::T_SymbolKind *result)
{
for (int i = 0;;i++) {
if (m_keywords[i] == NULL) {
return false;
}
else if (((KeywordInfo *)m_keywords[i])->m_keyword.compare(word) == 0) {
*result = ((KeywordInfo *)m_keywords[i])->m_symbolKind;
return true;
}
}
}
};
const CP_KeywordInfo KeywordTable::m_keywords[] = {
(CP_KeywordInfo)new KeywordInfo("DIV", SymbolKind::DIV),
(CP_KeywordInfo)new KeywordInfo("MOD", SymbolKind::MOD),
(CP_KeywordInfo)new KeywordInfo("OR", SymbolKind::OR),
(CP_KeywordInfo)new KeywordInfo("OF", SymbolKind::OF),
(CP_KeywordInfo)new KeywordInfo("THEN", SymbolKind::THEN),
(CP_KeywordInfo)new KeywordInfo("DO", SymbolKind::DO),
(CP_KeywordInfo)new KeywordInfo("END", SymbolKind::END),
(CP_KeywordInfo)new KeywordInfo("ELSE", SymbolKind::ELSE),
(CP_KeywordInfo)new KeywordInfo("ELSEIF", SymbolKind::ELSEIF),
(CP_KeywordInfo)new KeywordInfo("IF", SymbolKind::IF),
(CP_KeywordInfo)new KeywordInfo("WHILE", SymbolKind::WHILE),
(CP_KeywordInfo)new KeywordInfo("ARRAY", SymbolKind::ARRAY),
(CP_KeywordInfo)new KeywordInfo("RECORD", SymbolKind::RECORD),
(CP_KeywordInfo)new KeywordInfo("CONST", SymbolKind::CONST),
(CP_KeywordInfo)new KeywordInfo("TYPE", SymbolKind::TYPE),
(CP_KeywordInfo)new KeywordInfo("VAR", SymbolKind::VAR),
(CP_KeywordInfo)new KeywordInfo("PROCEDURE", SymbolKind::PROCEDURE),
(CP_KeywordInfo)new KeywordInfo("BEGIN", SymbolKind::BEGIN),
(CP_KeywordInfo)new KeywordInfo("MODULE", SymbolKind::MODULE),
NULL };
#endif | [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
e2d3b6fc935eee8355844e126f9959f2e079a83a | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/ButtonVE.cpp | b361a6c8c8f80b20ad4eafa0bf73a029cd52a69a | [] | no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | //
// Owner Drawn WinXP/Vista themes aware button implementation...
//
#include "stdafx.h"
#include "ButtonVE.h"
#if _MSC_VER>=1600
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC(CButtonVE, CButton)
BEGIN_MESSAGE_MAP(CButtonVE, CButton)
ON_WM_GETDLGCODE()
ON_WM_KILLFOCUS()
ON_WM_TIMER()
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_NCDESTROY()
ON_WM_SYSCOLORCHANGE()
ON_WM_ERASEBKGND()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDBLCLK()
ON_WM_LBUTTONUP()
ON_MESSAGE(BM_SETSTYLE, OnSetStyle)
ON_MESSAGE(BM_SETCHECK, OnSetCheck)
ON_MESSAGE(BM_GETCHECK, OnGetCheck)
ON_MESSAGE(WM_UPDATEUISTATE, OnUpdateUIState)
END_MESSAGE_MAP()
#endif | [
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
33
]
]
] |
89dd0f18f4db37db44bcc46c01a326c1ddb15e24 | 01acea32aaabe631ce84ff37340c6f20da3065a6 | /ships.cpp | a3645f9ebba9a3b21676931c695e5f070d3b1aa2 | [] | no_license | olooney/pattern-space | db2804d75249fe42427c15260ecb665bc489e012 | dcf07e63a6cb7644452924212ed087d45c301e78 | refs/heads/master | 2021-01-20T09:38:41.065323 | 2011-04-20T01:25:58 | 2011-04-20T01:25:58 | 1,638,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | /*
Implementation for SpriteMass
*/
#include "ships.h"
#include "vector2d.h"
#include "image.h"
#include "mass.h"
namespace PatternSpace {
/********************* SpriteMass *********************/
// simply bind the image to the mass!
Vector2d SpriteMass::position() { return mass.position(); }
double SpriteMass::angle() { return mass.angle(); }
Image& SpriteMass::image() { return img; }
SpriteMass::SpriteMass(Image i, Mass& m):
img(i), mass(m) {}
void SpriteMass::step(double dT) {
mass.step(dT);
}
} // end namespace PatternSpace
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
e123992b57b16b0b135ee688719170113a915a98 | ad59241b534bd17660dfbff28cdf8145f53aac92 | /CLIENT Avant refonte GUI/Buttons.h | f030ca0add3e5acc53e4389d7eaa65b79f5c3791 | [] | no_license | CromFr/CromTPS | dc0e5c42d8c37b6169e014975d9f0ca8c9d3ad1f | 145ff39c2ab319e1d53e065ca8e92f137131cb38 | refs/heads/master | 2021-01-19T22:14:01.984408 | 2011-09-21T22:09:10 | 2011-09-21T22:09:10 | 2,282,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,727 | h | #ifndef BUTTONHANDLER_H_INCLUDED
#define BUTTONHANDLER_H_INCLUDED
#define _BUTTON_WIDTH 200
#define _BUTTON_HEIGHT 60
class Button
{
public://=======================================
///Les skins sont définis ici !
Button(int nPosX, int nPosY, std::string sText, int nID, int nSkin=0);
///Change le mode du bouton : 0=inactive, 1=active, 2=pressed
void SetMode(int nMode);
///Dessine le bouton sur l'écran
void DrawButton();
///Retourne l'ID du bouton
int GetID()const;
///Délimitation du bouton
///Sa position étant (GetXMin, GetYMin)
int GetXMin()const;
int GetXMax()const;
int GetYMin()const;
int GetYMax()const;
private://=======================================
sf::Sprite* sprDefault;
sf::Sprite* sprOnMouseOver;
sf::Sprite* sprOnClick;
int m_nID;
int m_nPosX;
int m_nPosY;
sf::String m_sText;
int m_nMode;
};
class ButtonHandler
{
public://=======================================
ButtonHandler();
///Supprime les boutons à la destruction
~ButtonHandler();
///Modifie l'état des boutons en fonction de l'event
///En cas de clic sur un bouton, retourne l'ID de celui ci
int OnEvent(sf::Event eEvent);
///Ajoute un bouton à la liste
///l'ID doit etre superieure à 0 (strict)
void AddButton(int nPosCenterX, int nPosCenterY, std::string sText, int nID, int nSkin=0);
///Dessine les boutons
void DrawButtons() const;
private://=======================================
std::vector<Button::Button*> m_pListeButton;
bool GetIsOnButton(sf::Vector2<float>::Vector2<float> vMouse, Button::Button* pButton);
};
#endif // BUTTONHANDLER_H_INCLUDED
| [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
1a43f12ef126a2628dc237ac803776eedfebd181 | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkXMLShader.h | c8ecd4cf199cb421b0ad4c67f365ea78db1d8877 | [] | no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,362 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkXMLShader.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
// .NAME vtkXMLShader - encapsulates a Shader XML description.
// .SECTION Description
// vtkXMLShader encapsulates the XML description for a Shader.
// It provides convenient access to various attributes/properties
// of a shader.
// .SECTION Thanks
// Shader support in VTK includes key contributions by Gary Templet at
// Sandia National Labs.
#ifndef __vtkXMLShader_h
#define __vtkXMLShader_h
#include "vtkObject.h"
class vtkXMLDataElement;
class VTK_IO_EXPORT vtkXMLShader : public vtkObject
{
public:
static vtkXMLShader* New();
vtkTypeRevisionMacro(vtkXMLShader, vtkObject);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Get/Set the XML root element that describes this shader.
vtkGetObjectMacro(RootElement, vtkXMLDataElement);
void SetRootElement(vtkXMLDataElement*);
// Description:
// Returns the shader's language as defined in the XML description.
int GetLanguage();
// Description:
// Returns the type of the shader as defined in the XML description.
int GetScope();
// Description:
// Returns the location of the shader as defined in the XML description.
int GetLocation();
// Description:
// Get the name of the Shader.
const char* GetName();
// Description:
// Get the entry point to the shader code as defined in the XML.
const char* GetEntry();
// Description:
// Get the shader code.
const char* GetCode();
// Description:
// Returns an null terminate array of the pointers to space sepatared Args
// defined in the XML description.
const char** GetArgs();
// Description:
// Searches the file in the VTK_MATERIALS_DIRS.
// Note that this allocates new memory for the string.
// The caller must delete it.
static char* LocateFile(const char* filename);
//BTX
enum LanguageCodes
{
LANGUAGE_NONE=0,
LANGUAGE_MIXED,
LANGUAGE_CG,
LANGUAGE_GLSL
};
enum ScopeCodes
{
SCOPE_NONE=0,
SCOPE_MIXED,
SCOPE_VERTEX,
SCOPE_FRAGMENT
};
enum LocationCodes
{
LOCATION_NONE=0,
LOCATION_INLINE,
LOCATION_FILE,
LOCATION_LIBRARY
};
//ETX
protected:
vtkXMLShader();
~vtkXMLShader();
// Reads the file and fills it in this->Code.
void ReadCodeFromFile(const char* fullpath);
char* Code; // cache for the code.
vtkSetStringMacro(Code);
vtkXMLDataElement* RootElement;
vtkXMLDataElement* SourceLibraryElement;
void SetSourceLibraryElement(vtkXMLDataElement*);
char** Args;
void CleanupArgs();
private:
vtkXMLShader(const vtkXMLShader&); // Not implemented.
void operator=(const vtkXMLShader&); // Not implemented.
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
] | [
[
[
1,
125
]
]
] |
c15436cd31fa8dd0f338cbeb1d2546b28305f095 | 4ab592fb354f75b42181d5375d485031960aaa7d | /DES_GOBSTG/DES_GOBSTG/Header/Export_Lua_HGEHelp.h | d04f14a57b51c18d0715477ccab8454d9831f9d8 | [] | no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24T14:55:56.999923 | 2010-07-23T04:24:59 | 2010-07-23T04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,533 | h | #ifndef __NOTUSELUA
#include "Export_Lua.h"
class Export_Lua_HGEHelp : public Export_Lua
{
public:
static bool _LuaRegistFunction(LuaObject * obj);
static bool _LuaRegistConst(LuaObject * obj);
static hgeFont * _Helper_New_hgeFont();
static hgeFont * _Helper_New_hgeFont(const char * filename, bool bMipmap=false);
static hgeSprite * _Helper_New_hgeSprite();
static hgeSprite * _Helper_New_hgeSprite(HTEXTURE tex, float x, float y, float w, float h);
static hgeSprite * _Helper_New_hgeSprite(const hgeSprite & spr);
static hgeEffectSystem * _Helper_New_hgeES();
static hgeEffectSystem * _Helper_New_hgeES(const char * filename, HTEXTURE tex = 0);
static hgeEffectSystem * _Helper_New_hgeES(const hgeEffectSystem & eff);
// Font
static hgeFont * _LuaHelper_hgeFont_Get(LuaStack * args);
static void _LuaHelper_hgeFont_DeleteFont(hgeFont * _font);
static void _LuaHelper_hgeFont_DeleteAllFont();
static int LuaFn_hgeFont_NewFont(LuaState * ls);
static int LuaFn_hgeFont_DeleteFont(LuaState * ls);
static int LuaFn_hgeFont_Render(LuaState * ls);
static int LuaFn_hgeFont_printfb(LuaState * ls);
static int LuaFn_hgeFont_SetColor(LuaState * ls);
static int LuaFn_hgeFont_SetZ(LuaState * ls);
static int LuaFn_hgeFont_SetBlendMode(LuaState * ls);
static int LuaFn_hgeFont_SetScale(LuaState * ls);
static int LuaFn_hgeFont_SetProportion(LuaState * ls);
static int LuaFn_hgeFont_SetRotation(LuaState * ls);
static int LuaFn_hgeFont_SetTracking(LuaState * ls);
static int LuaFn_hgeFont_SetSpacing(LuaState * ls);
static int LuaFn_hgeFont_GetColor(LuaState * ls);
static int LuaFn_hgeFont_GetZ(LuaState * ls);
static int LuaFn_hgeFont_GetBlendMode(LuaState * ls);
static int LuaFn_hgeFont_GetScale(LuaState * ls);
static int LuaFn_hgeFont_GetProportion(LuaState * ls);
static int LuaFn_hgeFont_GetRotation(LuaState * ls);
static int LuaFn_hgeFont_GetTracking(LuaState * ls);
static int LuaFn_hgeFont_GetSpacing(LuaState * ls);
static int LuaFn_hgeFont_ChangeSprite(LuaState * ls);
static int LuaFn_hgeFont_GetSprite(LuaState * ls);
static int LuaFn_hgeFont_GetPreWidth(LuaState * ls);
static int LuaFn_hgeFont_GetPostWidth(LuaState * ls);
static int LuaFn_hgeFont_GetHeight(LuaState * ls);
static int LuaFn_hgeFont_GetStringWidth(LuaState * ls);
// Sprite
static hgeSprite * _LuaHelper_hgeSprite_Get(LuaStack * args);
static void _LuaHelper_hgeSprite_DeleteSprite(hgeSprite * _sprite);
static void _LuaHelper_hgeSprite_DeleteAllSprite();
static int LuaFn_hgeSprite_NewSprite(LuaState * ls);
static int LuaFn_hgeSprite_DeleteSprite(LuaState * ls);
static int LuaFn_hgeSprite_Render(LuaState * ls);
static int LuaFn_hgeSprite_RenderStretch(LuaState * ls);
static int LuaFn_hgeSprite_Render4V(LuaState * ls);
static int LuaFn_hgeSprite_SetTexture(LuaState * ls);
static int LuaFn_hgeSprite_SetTextureRect(LuaState * ls);
static int LuaFn_hgeSprite_SetColor(LuaState * ls);
static int LuaFn_hgeSprite_SetZ(LuaState * ls);
static int LuaFn_hgeSprite_SetBlendMode(LuaState * ls);
static int LuaFn_hgeSprite_SetHotSpot(LuaState * ls);
static int LuaFn_hgeSprite_SetFlip(LuaState * ls);
static int LuaFn_hgeSprite_GetTexture(LuaState * ls);
static int LuaFn_hgeSprite_GetTextureRect(LuaState * ls);
static int LuaFn_hgeSprite_GetColor(LuaState * ls);
static int LuaFn_hgeSprite_GetZ(LuaState * ls);
static int LuaFn_hgeSprite_GetBlendMode(LuaState * ls);
static int LuaFn_hgeSprite_GetHotSpot(LuaState * ls);
static int LuaFn_hgeSprite_GetFlip(LuaState * ls);
static int LuaFn_hgeSprite_GetWidth(LuaState * ls);
static int LuaFn_hgeSprite_GetHeight(LuaState * ls);
static int LuaFn_hgeSprite_GetBoundingBox(LuaState * ls);
// EffectSystem
static hgeEffectSystem * _LuaHelper_hgeES_Get(LuaStack * args);
static void _LuaHelper_hgeES_DeleteES(hgeEffectSystem * _es);
static void _LuaHelper_hgeES_DeleteAllES();
static int LuaFn_hgeES_NewES(LuaState * ls);
static int LuaFn_hgeES_DeleteES(LuaState * ls);
static int LuaFn_hgeES_Load(LuaState * ls);
static int LuaFn_hgeES_Save(LuaState * ls);
static int LuaFn_hgeES_Render(LuaState * ls);
static int LuaFn_hgeES_MoveTo(LuaState * ls);
static int LuaFn_hgeES_Fire(LuaState * ls);
static int LuaFn_hgeES_Stop(LuaState * ls);
static int LuaFn_hgeES_Update(LuaState * ls);
public:
static list<hgeFont *>fontList;
static list<hgeSprite *>spriteList;
static list<hgeEffectSystem *>esList;
};
#endif | [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
] | [
[
[
1,
110
]
]
] |
12e02af91c94d8e086e3f44b8d2d987f0ab27368 | 09a84291381a2ae9e366b848aff5ac94342e6d4b | /SubstSvc/Source/SubstSvcApp.h | fb20e9673353c010cb68131eaefba02aca19908f | [] | no_license | zephyrer/xsubst | 0088343300d62d909a87e235da490728b9af5106 | 111829b6094d796aefb7c8e4ec7bd40bae4d6449 | refs/heads/master | 2020-05-20T03:22:44.200074 | 2011-06-18T05:50:34 | 2011-06-18T05:50:34 | 40,066,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | h | // SubstSvc NT service.
// Copyright (c) 2004-2011 by Elijah Zarezky,
// All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SubstSvcApp.h - interface of the CSubstSvcApp class
#if !defined(__SubstSvcApp_h)
#define __SubstSvcApp_h
#if defined(_MSC_VER) && (_MSC_VER > 1000)
#pragma once
#endif // _MSC_VER
class CSubstSvcApp: public CWinApp
{
friend int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]);
DECLARE_DYNAMIC(CSubstSvcApp)
// construction/destruction
public:
CSubstSvcApp(void);
virtual ~CSubstSvcApp(void);
};
#endif // __SubstSvcApp_h
// end of file
| [
"Elijah Zarezky@9a190745-9f41-0410-876d-23307a9d09e3",
"elijah@9a190745-9f41-0410-876d-23307a9d09e3"
] | [
[
[
1,
4
],
[
17,
28
],
[
30,
40
]
],
[
[
5,
16
],
[
29,
29
]
]
] |
7bb3b9c4bd03158ff835e0540d83338a0f9a2421 | cfa667b1f83649600e78ea53363ee71dfb684d81 | /code/extlibs/raknet/DataBlockEncryptor.cc | b7c5040a17b38bdd367698772ad62fe23a29b983 | [] | no_license | zhouxh1023/nebuladevice3 | c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f | 3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241 | refs/heads/master | 2021-01-23T08:56:15.823698 | 2011-08-26T02:22:25 | 2011-08-26T02:22:25 | 32,018,644 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,149 | cc | /// \file
///
/// This file is part of RakNet Copyright 2003 Jenkins Software LLC
///
/// Usage of RakNet is subject to the appropriate license agreement.
#include "DataBlockEncryptor.h"
#include "CheckSum.h"
#include "GetTime.h"
#include "Rand.h"
#include "RakAssert.h"
#include <string.h>
#include "Rijndael.h"
//#include "Types.h"
DataBlockEncryptor::DataBlockEncryptor()
{
keySet = false;
}
DataBlockEncryptor::~DataBlockEncryptor()
{}
bool DataBlockEncryptor::IsKeySet( void ) const
{
return keySet;
}
void DataBlockEncryptor::SetKey( const unsigned char key[ 16 ] )
{
keySet = true;
//secretKeyAES128.set_key( key );
makeKey(&keyEncrypt, DIR_ENCRYPT, 16, (char*)key);
makeKey(&keyDecrypt, DIR_DECRYPT, 16, (char*)key);
cipherInit(&cipherInst, MODE_ECB, 0); // ECB is not secure except that I chain manually farther down.
}
void DataBlockEncryptor::UnsetKey( void )
{
keySet = false;
}
void DataBlockEncryptor::Encrypt( unsigned char *input, unsigned int inputLength, unsigned char *output, unsigned int *outputLength, RakNetRandom *rnr )
{
unsigned index, byteIndex, lastBlock;
unsigned int checkSum;
unsigned char paddingBytes;
unsigned char encodedPad;
unsigned char randomChar;
CheckSum checkSumCalculator;
#ifdef _DEBUG
RakAssert( keySet );
#endif
RakAssert( input && inputLength );
// randomChar will randomize the data so the same data sent twice will not look the same
randomChar = (unsigned char) rnr->RandomMT();
// 16-(((x-1) % 16)+1)
// # of padding bytes is 16 -(((input_length + extra_data -1) % 16)+1)
paddingBytes = (unsigned char) ( 16 - ( ( ( inputLength + sizeof( randomChar ) + sizeof( checkSum ) + sizeof( encodedPad ) - 1 ) % 16 ) + 1 ) );
// Randomize the pad size variable
encodedPad = (unsigned char) rnr->RandomMT();
encodedPad <<= 4;
encodedPad |= paddingBytes;
*outputLength = inputLength + sizeof( randomChar ) + sizeof( checkSum ) + sizeof( encodedPad ) + paddingBytes;
// Write the data first, in case we are overwriting ourselves
if ( input == output )
memmove( output + sizeof( checkSum ) + sizeof( randomChar ) + sizeof( encodedPad ) + paddingBytes, input, inputLength );
else
memcpy( output + sizeof( checkSum ) + sizeof( randomChar ) + sizeof( encodedPad ) + paddingBytes, input, inputLength );
// Write the random char
memcpy( output + sizeof( checkSum ), ( char* ) & randomChar, sizeof( randomChar ) );
// Write the pad size variable
memcpy( output + sizeof( checkSum ) + sizeof( randomChar ), ( char* ) & encodedPad, sizeof( encodedPad ) );
// Write the padding
for ( index = 0; index < paddingBytes; index++ )
*( output + sizeof( checkSum ) + sizeof( randomChar ) + sizeof( encodedPad ) + index ) = (unsigned char) rnr->RandomMT();
// Calculate the checksum on the data
checkSumCalculator.Add( output + sizeof( checkSum ), inputLength + sizeof( randomChar ) + sizeof( encodedPad ) + paddingBytes );
checkSum = checkSumCalculator.Get();
// Write checksum
#ifdef HOST_ENDIAN_IS_BIG
output[0] = checkSum&0xFF;
output[1] = (checkSum>>8)&0xFF;
output[2] = (checkSum>>16)&0xFF;
output[3] = (checkSum>>24)&0xFF;
#else
memcpy( output, ( char* ) & checkSum, sizeof( checkSum ) );
#endif
// AES on the first block
// secretKeyAES128.encrypt16( output );
blockEncrypt(&cipherInst, &keyEncrypt, output, 16, output);
lastBlock = 0;
// Now do AES on every other block from back to front
for ( index = *outputLength - 16; index >= 16; index -= 16 )
{
for ( byteIndex = 0; byteIndex < 16; byteIndex++ )
output[ index + byteIndex ] ^= output[ lastBlock + byteIndex ];
//secretKeyAES128.encrypt16( output + index );
blockEncrypt(&cipherInst, &keyEncrypt, output+index, 16, output+index);
lastBlock = index;
}
}
bool DataBlockEncryptor::Decrypt( unsigned char *input, unsigned int inputLength, unsigned char *output, unsigned int *outputLength )
{
unsigned index, byteIndex, lastBlock;
unsigned int checkSum;
unsigned char paddingBytes;
unsigned char encodedPad;
unsigned char randomChar = 0;
CheckSum checkSumCalculator;
#ifdef _DEBUG
RakAssert( keySet );
#endif
if ( input == 0 || inputLength < 16 || ( inputLength % 16 ) != 0 )
{
return false;
}
// Unchain in reverse order
for ( index = 16; index <= inputLength - 16;index += 16 )
{
// secretKeyAES128.decrypt16( input + index );
blockDecrypt(&cipherInst, &keyDecrypt, input + index, 16, output + index);
for ( byteIndex = 0; byteIndex < 16; byteIndex++ )
{
if ( index + 16 == ( unsigned ) inputLength )
output[ index + byteIndex ] ^= input[ byteIndex ];
else
output[ index + byteIndex ] ^= input[ index + 16 + byteIndex ];
}
lastBlock = index;
};
// Decrypt the first block
//secretKeyAES128.decrypt16( input );
blockDecrypt(&cipherInst, &keyDecrypt, input, 16, output);
// Read checksum
#ifdef HOST_ENDIAN_IS_BIG
checkSum = (unsigned int)output[0] | (unsigned int)(output[1]<<8) |
(unsigned int)(output[2]<<16)|(unsigned int)(output[3]<<24);
#else
memcpy( ( char* ) & checkSum, output, sizeof( checkSum ) );
#endif
// Read the pad size variable
memcpy( ( char* ) & encodedPad, output + sizeof( randomChar ) + sizeof( checkSum ), sizeof( encodedPad ) );
// Ignore the high 4 bytes
paddingBytes = encodedPad & 0x0F;
// Get the data length
*outputLength = inputLength - sizeof( randomChar ) - sizeof( checkSum ) - sizeof( encodedPad ) - paddingBytes;
// Calculate the checksum on the data.
checkSumCalculator.Add( output + sizeof( checkSum ), *outputLength + sizeof( randomChar ) + sizeof( encodedPad ) + paddingBytes );
if ( checkSum != checkSumCalculator.Get() )
return false;
// Read the data
//if ( input == output )
memmove( output, output + sizeof( randomChar ) + sizeof( checkSum ) + sizeof( encodedPad ) + paddingBytes, *outputLength );
//else
// memcpy( output, input + sizeof( randomChar ) + sizeof( checkSum ) + sizeof( encodedPad ) + paddingBytes, *outputLength );
return true;
}
| [
"[email protected]"
] | [
[
[
1,
197
]
]
] |
b20370bba28f46f3288b207fbaab33cd05a753a6 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_9_005.cpp | 14c61807a3c17df2e3dc4c4776afec12890deff4 | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Tests, if no universal character values are to be generated accidently by
// concatenation
#define CONCAT(a, b) PRIMITIVE_CONCAT(a, b)
#define PRIMITIVE_CONCAT(a, b) a ## b
#define STRINGIZE(x) STRINGIZE_D(x)
#define STRINGIZE_D(x) # x
//R #line 19 "t_9_005.cpp"
STRINGIZE( CONCAT(\, u00ff) ) //R "\u00ff"
STRINGIZE( CONCAT(\u00, ff) ) //R "\u00ff"
STRINGIZE( CONCAT(\u00ff, 56) ) //R "\u00ff56"
CONCAT(\, u00ff) //R \u00ff
CONCAT(\u00, ff) //R \ u00ff
CONCAT(\u00ff, 56) //R \u00ff56
//E t_9_005.cpp(27): error: a universal character name cannot designate a character in the basic character set: \u0061
STRINGIZE( CONCAT(\, u0061) ) // reports an error
| [
"metrix@Blended.(none)"
] | [
[
[
1,
27
]
]
] |
8734c1381d7862b7f63bb347eeb3b619dbfd7652 | b822313f0e48cf146b4ebc6e4548b9ad9da9a78e | /KylinSdk/Core/Source/Scene.h | 837bb4ef986b208a29d8c1482564947f168df990 | [] | no_license | dzw/kylin001v | 5cca7318301931bbb9ede9a06a24a6adfe5a8d48 | 6cec2ed2e44cea42957301ec5013d264be03ea3e | refs/heads/master | 2021-01-10T12:27:26.074650 | 2011-05-30T07:11:36 | 2011-05-30T07:11:36 | 46,501,473 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,279 | h | #pragma once
namespace Kylin
{
struct SceneHag
{
SceneHag();
// 场景ID
KUINT m_uSceneID;
// 场景类型
KUINT m_uType;
// 场景级别
KUINT m_uLevel;
// 场景名称
KSTR m_sName;
// 背景音乐
KINT m_nBgSound;
// 场景文件
KSTR m_sSceneFile;
// 是否通过
KBOOL m_bPass;
};
class Scene
{
public:
Scene(const SceneHag& kSceneHag);
~Scene();
virtual KVOID Tick(KFLOAT fElapsed);
//进入场景
virtual KVOID EnterScene(KVOID);
//离开场景
virtual KVOID LeaveScene(KVOID);
//场景位置是否合法
virtual KBOOL IsValidPosition(const KPoint2& fvPos);
//获得场景加载接口
SceneLoader* GetSceneLoader();
protected:
virtual KVOID SpawnScene();
//环境音效列表
struct EnvSound_t
{
KINT nID;
KINT nSoundID;
KUINT nPosx;
KUINT nPosz;
KUINT nDistance;
//tSoundSource* pSoundSource;
};
KVEC<EnvSound_t> m_kEnvSoundList;
private:
friend class KylinRoot;
//场景数据
SceneHag m_kSceneHag;
//
//场景加载接口
SceneLoader* m_pSceneLoader;
//场景ENTITY管理器
EntityManager* m_pEntityManager;
//事件管理器
EventManager* m_pEventManager;
};
}
| [
"[email protected]",
"apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f"
] | [
[
[
1,
37
],
[
40,
70
]
],
[
[
38,
39
]
]
] |
49c5f93fdaa9e3858a5ff57415654d3b0db9e99f | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/map/aux_/contains_impl.hpp | 3642516fd570eb3494ef6d30cfaa0ed40e10abbd | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | hpp |
#ifndef BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
#define BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
//
// 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/mpl for documentation.
// $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/map/aux_/contains_impl.hpp,v $
// $Date: 2006/04/17 23:49:40 $
// $Revision: 1.1 $
#include <boost/mpl/contains_fwd.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/map/aux_/at_impl.hpp>
#include <boost/mpl/map/aux_/tag.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
template<>
struct contains_impl< aux::map_tag >
{
template< typename Map, typename Pair > struct apply
: is_same<
typename at_impl<aux::map_tag>::apply<
Map
, typename Pair::first
>::type
, typename Pair::second
>
{
};
};
}}
#endif // BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
43
]
]
] |
f75941414cbc861840c9b93903cc39bb0a0163e7 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/Material.cpp | f79cebbcff42bea109f172a4c920bff6256c8d02 | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 5,222 | cpp | #include "stdafx.h"
#include <d3d9.h>
#include <d3dx9.h>
#include <stdio.h>
#include "material.h"
#include "..\_DirectX\dxutil.h"
#include "..\_UnhandledException\ExceptionHandler.h"
#include "HwOption.h"
#include "path.h"
#include "vutil.h"
#include "xutil.h"
CTextureManager g_TextureMng;
CTextureManager :: CTextureManager()
{
// int i;
memset( m_pMaterial, 0, sizeof(m_pMaterial) );
// for( i = 0; i < MAX_MATERIAL; i ++ )
// {
// m_pMaterial[i].m_bActive = FALSE;
// m_pMaterial[i].strBitMapFileName[0] = 0;
// }
m_nMaxTexture = 0;
//m_pd3dDevice = NULL;
}
CTextureManager :: ~CTextureManager()
{
DeleteDeviceObjects();
// m_pd3dDevice = NULL;
}
HRESULT CTextureManager::DeleteDeviceObjects()
{
int i;
for( i = 0; i < MAX_MATERIAL; i ++ )
{
if( m_pMaterial[i].m_bActive )
SAFE_RELEASE( m_pMaterial[i].m_pTexture );
m_pMaterial[i].m_bActive = FALSE;
m_pMaterial[i].strBitMapFileName[0] = 0;
}
m_nMaxTexture = 0;
return S_OK;
}
// pTexture를 사용하는 매터리얼을 찾아 삭제한다.
// 공유되어 있는 텍스쳐라면 사용카운터를 보고 1인것만 삭제한다..
int CTextureManager::DeleteMaterial( LPDIRECT3DTEXTURE9 pTexture )
{
int i;
if( pTexture == NULL ) return FALSE;
if( m_nMaxTexture == 0 ) return FALSE;
for( i = 0; i < MAX_MATERIAL; i ++ )
{
if( m_pMaterial[i].m_bActive )
{
if( m_pMaterial[i].m_pTexture == pTexture ) // pTexture를 찾았다.
{
if( m_pMaterial[i].m_nUseCnt == 1 ) // 공유된게 아니다(usecnt == 1)
{
SAFE_RELEASE( m_pMaterial[i].m_pTexture ); // 삭제.
m_pMaterial[i].m_bActive = FALSE; // 텍스쳐 관리자에서도 삭제.
m_pMaterial[i].strBitMapFileName[0] = 0;
m_nMaxTexture --;
return TRUE;
}
}
}
}
return FALSE;
}
MATERIAL* CTextureManager :: AddMaterial( LPDIRECT3DDEVICE9 pd3dDevice, D3DMATERIAL9 *pMaterial, LPCTSTR strFileName, LPCTSTR szPath )
{
#ifdef __WORLDSERVER
return NULL;
#endif
int i;
MATERIAL *pMList = m_pMaterial;
LPDIRECT3DTEXTURE9 pTexture = NULL;
// 이미 읽은건지 검사.
for( i = 0; i < MAX_MATERIAL; i ++ )
{
if( pMList->m_bActive )
{
if( strcmpi(strFileName, pMList->strBitMapFileName) == 0 && pMList->m_pd3dDevice == pd3dDevice ) // 이미 읽은건 다시 읽지 않음. 역시 땜빵 -_-;;
{
pMList->m_nUseCnt ++; // 이미로딩한걸 공유하고 있다면 카운트 올림.
return pMList;
}
}
pMList ++;
}
pMList = NULL;
CString strPath;
if( szPath == NULL )
{
#ifdef __WORLDSERVER
strPath = MakePath( DIR_MODELTEX, strFileName );
#else
if( g_Option.m_nTextureQuality == 0 )
strPath = MakePath( DIR_MODELTEX, strFileName );
else
if( g_Option.m_nTextureQuality == 1 )
strPath = MakePath( DIR_MODELTEXMID, strFileName );
else
strPath = MakePath( DIR_MODELTEXLOW, strFileName );
#endif // not worldserver
}
else
{
strPath = MakePath( szPath, strFileName ); // 경로가 지정되어 있을땐 그걸쓴다.
}
if( FAILED( LoadTextureFromRes( pd3dDevice, strPath,
D3DX_DEFAULT, D3DX_DEFAULT, 4, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4,
D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR ,
D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR , 0x00000000, NULL, NULL, &pTexture ) ) )
{
if( !IsEmpty(strFileName) )
Error( "%s texture bitmap", strPath );
}
// 빈 슬롯이 있는지 검사.
pMList = m_pMaterial;
for( i = 0; i < MAX_MATERIAL; i ++ )
{
if( pMList->m_bActive == FALSE ) break;
pMList++;
}
if( i >= MAX_MATERIAL )
{
LPCTSTR szErr = Error( "CTextureManager::AddMaterial : 텍스쳐 갯수를 넘어섰다." );
ADDERRORMSG( szErr );
return NULL;
}
pMList->m_bActive = TRUE;
#ifndef __CHERRY
pMaterial->Ambient.r = 1;
pMaterial->Ambient.g = 1;
pMaterial->Ambient.b = 1;
pMaterial->Diffuse.r = 1;
pMaterial->Diffuse.g = 1;
pMaterial->Diffuse.b = 1;
pMaterial->Specular.r = 1;
pMaterial->Specular.g = 1;
pMaterial->Specular.b = 1;
pMaterial->Emissive.r = 0;
pMaterial->Emissive.g = 0;
pMaterial->Emissive.b = 0;
pMaterial->Power = 0.0f;
#endif
pMList->m_Material = *pMaterial;
// memcpy( &pMList->m_Material, pMaterial, sizeof(D3DMATERIAL9) ); // 매터리얼내용 카피
// memcpy( pMList->strBitMapFileName, strFileName, strlen(strFileName) ); // 텍스쳐 파일명 카피
#ifdef _XDEBUG
if( strlen(strFileName)+1 > 32 )
Error( "CTextureManager::AddMaterial() : %s의 길이가 너무 길다", strFilename );
#endif
strcpy( pMList->strBitMapFileName, strFileName ); // 텍스쳐 파일명 카피
pMList->m_pTexture = pTexture;
pMList->m_pd3dDevice = pd3dDevice;
pMList->m_nUseCnt = 1; // 처음 등록된것이기땜에 1부터 시작.
m_nMaxTexture ++;
return pMList;
}
D3DMATERIAL9* CTextureManager::GetMaterial( LPDIRECT3DDEVICE9 m_pd3dDevice, int nIdx )
{
return &m_pMaterial[ nIdx ].m_Material;
}
LPDIRECT3DTEXTURE9 CTextureManager::GetTexture( LPDIRECT3DDEVICE9 m_pd3dDevice, int nIdx )
{
return m_pMaterial[ nIdx ].m_pTexture;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
189
]
]
] |
6fd6a308925c4b8900d29e28001cf94b400f404a | be7eef50e21e11340134d150f78db8d6f5423e66 | /L2/L2.cpp | 9247d5ef897c5d3588287571a0c19713f6aa3869 | [] | no_license | Maciej-Poleski/Algorytmika | 8023aef976c1087e25a4f9079de65769cf690ae3 | 3a3818f82738d9ea42aba24dea89e9280d504f00 | refs/heads/master | 2023-07-06T03:57:54.430947 | 2011-05-26T15:57:11 | 2011-05-26T15:57:11 | 395,015,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | #include <cstdio>
#include <algorithm>
#define MAX_LONG_LONG 1000000900
using std::min;
struct eer
{
long long d,x,y;
eer(int dd,int xx,int yy) : d(dd),x(xx),y(yy) {}
};
struct mlesr
{
long long x0,c;
mlesr() : x0(MAX_LONG_LONG),c(0LL) {}
mlesr(long long aa,long long bb) : x0(aa),c(bb) {}
};
inline eer ee(long long a,long long b)
{
if(b==0)
return eer(a,1,0);
eer p=ee(b,a%b);
return eer(p.d,p.y,p.x-(a/b)*p.y);
}
inline mlesr mles(long long a,long long b,long long n)
{
if(b<0)
b=-b,a=-a;
b%=n;
if(n==1)
return mlesr(0,1);
if(a==0 && b==0)
return mlesr(0,n);
if(a==0)
return mlesr();
if(a<0)
a=-a,b=-b;
eer p=ee(a,n);
if(b%p.d)
return mlesr();
mlesr r;
long long x0=p.x*(b/p.d);
if(x0<0)
{
x0+=n*((-x0)/n);
if(x0<0)
x0+=n;
}
x0%=n;
for(int i=0;i<p.d;++i)
++r.c,r.x0=min(r.x0,(x0+i*(n/p.d))%n);
return r;
}
int main()
{
int z;
scanf("%d",&z);
while(z--)
{
int a,b,n;
scanf("%d%d%d",&a,&b,&n);
mlesr w=mles(a,b,n);
if(w.c)
{
// while(w.x0<0)
// w.x0+=n;
printf("%lld %lld\n",w.c,w.x0);
}
else
printf("0\n");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
80
]
]
] |
6ec754a19c84c1bc054c7483cc3373a2f9ba6943 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestvolume/src/bctestvolumeapp.cpp | 36c14e1088f227d3659a3b7fbaf8aa0d51b4af25 | [] | 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 | 1,951 | cpp | /*
* Copyright (c) 2002 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: Avkon volume test app
*
*/
// INCLUDE FILES
#include "BCTestVolumeApp.h"
#include "BCTestVolumeDocument.h"
#include <eikstart.h>
// ================= MEMBER FUNCTIONS =========================================
// ----------------------------------------------------------------------------
// TUid CBCTestVolumeApp::AppDllUid()
// Returns application UID.
// ----------------------------------------------------------------------------
//
TUid CBCTestVolumeApp::AppDllUid() const
{
return KUidBCTestVolume;
}
// ----------------------------------------------------------------------------
// CApaDocument* CBCTestVolumeApp::CreateDocumentL()
// Creates CBCTestVolumeDocument object.
// ----------------------------------------------------------------------------
//
CApaDocument* CBCTestVolumeApp::CreateDocumentL()
{
return CBCTestVolumeDocument::NewL( *this );
}
// ================= OTHER EXPORTED FUNCTIONS =================================
//
// ----------------------------------------------------------------------------
// CApaApplication* NewApplication()
// Constructs CBCTestVolumeApp.
// Returns: CApaDocument*: created application object
// ----------------------------------------------------------------------------
//
LOCAL_C CApaApplication* NewApplication()
{
return new CBCTestVolumeApp;
}
GLDEF_C TInt E32Main()
{
return EikStart::RunApplication(NewApplication);
}
// End of File
| [
"none@none"
] | [
[
[
1,
64
]
]
] |
33b9daff12de62f8201274003554e05e857ac837 | 570b21085112e47df93208796c656c363221bb96 | /source/CGE/Music.cpp | 4c03949fff325e5f6cd418b9de6297b47cd2b6e8 | [] | no_license | TheBuzzSaw/legacy-nullocity | ce6dff1f19e5cd945671ac3c24fcfb6c0d2fdb7d | 81e5f52ac60055ff006108378013a767464894b9 | refs/heads/master | 2020-04-13T22:48:37.794701 | 2011-09-20T21:27:45 | 2011-09-20T21:27:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | cpp | #include "Music.h"
#include "Exception.h"
namespace CGE
{
Music::Music() : mMusic(NULL), mVolume(20)
{
Mix_VolumeMusic(mVolume);
}
Music::Music(const char* inFile) : mMusic(NULL), mVolume(20)
{
Mix_VolumeMusic(mVolume);
load(inFile);
}
Music::~Music()
{
if (Mix_PlayingMusic())
Mix_HaltMusic();
Mix_FreeMusic(mMusic); // safe to call on NULL value
}
void Music::increaseVolume()
{
mVolume += 5;
if (mVolume > 128)
{
mVolume = 128;
}
Mix_VolumeMusic(mVolume);
}
void Music::decreaseVolume()
{
mVolume -= 5;
if (mVolume < 0)
{
mVolume = 0;
}
Mix_VolumeMusic(mVolume);
}
void Music::setVolume(int inVolume)
{
mVolume = inVolume;
if (mVolume > 128)
{
mVolume = 128;
}
else if (mVolume < 0)
{
mVolume = 0;
}
Mix_VolumeMusic(mVolume);
}
void Music::load(const char* inFile)
{
static const char* functionName = "Music::load";
if (!inFile || !*inFile)
throw Exception(functionName, "invalid file");
if ((mMusic = Mix_LoadMUS(inFile)) == NULL)
{
std::string message(Mix_GetError());
message += ' ';
message += inFile;
throw Exception(functionName, message);
}
}
void Music::play()
{
static const char* functionName = "Music::play";
if (!mMusic) return;
if (!Mix_PlayingMusic())
{
// This begins playing the music - the first argument is a
// pointer to Mix_Music structure, and the second is how many
// times you want it to loop (use -1 for infinite, and 0 to
// have it just play once)
if ((Mix_PlayMusic(mMusic, -1)) == -1)
throw Exception(functionName, Mix_GetError());
}
}
void Music::stop()
{
if (Mix_PlayingMusic())
Mix_HaltMusic();
}
}
| [
"buzz@ubu64.(none)"
] | [
[
[
1,
106
]
]
] |
479284f6589995968c09d8c77165d3dc8b382e6c | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/FileList.h | 65f79cf90c9488da587cc1f366006bae6b302d3b | [
"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 | 5,032 | h | /*
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.
*/
#ifndef FILE_OBJECT_H
#define FILE_OBJECT_H
#include <e32base.h> //CBase
#include <badesca.h> //CDesCArray
class CFileObject : public CBase
{
public:
enum TFileObjectAction {
EDoNothing = 0,
EInstallSisFile = 1,
};
private:
///@name Constructor and destructor.
//@{
CFileObject(TUint32 aFilesize,
TUint32 aAction);
void ConstructL(const char* aFilename, const char* aUrl,
const char *aChecksum,
const char *aVersion, const char *aVersionFile,
const char *aVersionCheck = NULL,
const char* aIsoLang = NULL);
public:
static class CFileObject* NewLC(const char* aFilename, const char* aUrl,
TUint32 aFilesize, const char* aChecksum,
TUint32 aAction, const char *aVersion,
const char *aVersionfile,
const char* aVersionCheck = NULL,
const char* aIsoLang = NULL);
static class CFileObject* NewL(const char* aFilename, const char* aUrl,
TUint32 aFilesize, const char* aChecksum,
TUint32 aAction, const char *aVersion,
const char *aVersionfile,
const char* aVersionCheck = NULL,
const char* aIsoLang = NULL);
virtual ~CFileObject();
//@}
void Reset();
const char *getUrl() const;
const char *getFilename() const;
TUint32 getFileSize() const;
const char* getCheckSum() const;
TUint32 getAction() const;
void SetAction(TUint32 aAction);
const char *getVersionFile() const;
const char *getVersion() const;
const char *getVersionCheck() const;
const char* getIsoCode() const;
TUint32 getCurrentSize() const;
void setCurrentSize(TUint32 newSize);
void SetFilenameL(const TDesC& aFilename);
private:
char *m_filename;
char *m_url;
TUint32 m_filesize;
char* m_checksum;
TUint32 m_action;
TUint32 m_currentSize;
char *m_version;
char *m_versionFile;
char *m_versionCheck;
char* m_isoLang;
public:
class CFileObject *next;
class CFileObject *prev;
};
class CFileObjectHolder : public CBase {
public:
CFileObjectHolder(void) {
};
virtual ~CFileObjectHolder() {
clear();
};
static class CFileObjectHolder* NewLC(MDesCArray& aDownloadList,
const TDesC& aBasepath,
const TDesC& aBaseUrl);
/*
* Dequeues the first object or returns NULL
* if the list is empty.
*/
class CFileObject* shift(void);
/*
* Adds the object at the beginning of the list.
*/
void unshift(class CFileObject *newItem);
void remove(class CFileObject *target);
TInt CheckVersionsL(class RFs& fsSession);
char *getVersionFromFile(class RFs& fsSession, const TDesC &versionFile);
TInt getNumItems() {
return m_numItems;
};
TInt getTotalSize() {
return m_totalSize;
};
void clear(void);
private:
class CFileObject *m_first;
class CFileObject *m_last;
TUint32 m_numItems;
TUint32 m_totalSize;
};
#endif /* FILE_OBJECT_H */
| [
"[email protected]"
] | [
[
[
1,
140
]
]
] |
a04b861237c8efb3b0f9d3222c91aa2be3c40a9a | 80716d408715377e88de1fc736c9204b87a12376 | /TspLib3/Samples/Dssp/Tsp/STDAFX.CPP | f96fc484636ee9609ecc372dcf33a9c453a3e1c3 | [] | no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | //
// Pre-compiled portion
//
#include "stdafx.h"
| [
"Owner@.(none)"
] | [
[
[
1,
5
]
]
] |
5af0206cdb6ffdcfaddff3faf8fa4580f9813d43 | a4756c3232fd88a74df199acc84ab70ec48d7875 | /FileManagerServer/GUI/serverexplorer.h | a0a1133085cfd2675b5e35ff40c55d6fabb224f4 | [] | no_license | raygray/filemanagermlf | a7a0cdd14cd558657116b6ae641bcb743084ba37 | 0648183e9c88d6e883861f1f1dcbe67550e5c11f | refs/heads/master | 2021-01-10T05:03:12.702335 | 2010-07-14T13:31:02 | 2010-07-14T13:31:02 | 49,008,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | #ifndef SERVEREXPLORER_H
#define SERVEREXPLORER_H
#include "baseexplorer.h"
#include <QTreeWidgetItem>
#include <QFileSystemModel>
#include <QScrollBar>
#include <QMenu>
#include <QAction>
#include <QFileInfoList>
class ServerExplorer : public BaseExplorer
{
Q_OBJECT
public:
ServerExplorer(BaseExplorer *baseExplorer = 0);
~ServerExplorer();
private:
void setServerSpecificText();
void createWidgets();
void setupTreeView();
void setupFileListView();
void allConnect();
private slots:
void pressOnTreeView(const QModelIndex &);
void clkOnFileList(const QModelIndex &index);
void doubleClkOnFileList(const QModelIndex & index);
void popMenuRequested(const QPoint &point);
void addToTransList();
void openFileOrDir();
void renameFile();
void delFile();
void clkOnTransButton();
private:
QFileSystemModel *m_fileSysModel;
QScrollBar *m_scrollList;
};
#endif // SERVEREXPLORER_H
| [
"malongfei88@0a542be3-54de-31ef-7baa-42960c810bab"
] | [
[
[
1,
50
]
]
] |
da2fab8e867da3a809e35a736761fa034a831946 | a7513d1fb4865ea56dbc1fcf4584fb552e642241 | /shiftable_files/detail/header.hpp | e20fb83e8aa1fd8bebc034d9866f41eec096fb72 | [
"MIT"
] | permissive | det/avl_array | f0cab062fa94dd94cdf12bea4321c5488fb5cdcc | d57524a623af9cfeeff060b479cc47285486d741 | refs/heads/master | 2021-01-15T19:40:10.287367 | 2010-05-06T13:13:35 | 2010-05-06T13:13:35 | 35,425,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,280 | hpp | ///////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2010, Universidad de Alcala //
// //
// See accompanying LICENSE.TXT //
// //
///////////////////////////////////////////////////////////////////
/*
header.hpp
----------
Definition of shiftable_files' header.
*/
#ifndef _SHF_HEADER_HPP_
#define _SHF_HEADER_HPP_
#include "../shiftable_files.hpp"
#ifdef __GNUC__
#define GCC_ATTR_PACKED __attribute__((__packed__))
#else
#define GCC_ATTR_PACKED
#endif
#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
#define MAGIC_BYTES { 's', 'h', 'f', 'U', 'A', 'H', 'e', 's' }
#define NUM_MAGIC_BYTES 8
#define VERSION_HIGH 0
#define VERSION_LOW 1
#define CLOSED_OK 0U
#define OPEN (1U<<0)
#define OP_MASK (7U<<1)
#define OP_NONE (0U<<1)
#define OP_RESIZE_GROW (1U<<1)
#define OP_INSERT_GROW (2U<<1)
#define OP_WRITE_GROW (3U<<1)
#define OP_NORMAL_SHRINK (4U<<1)
#define OP_DELAYED_SHRINK (5U<<1)
namespace shiftable_files
{
namespace detail
{
typedef union
{
uint32_t num;
int8_t bytes[sizeof(uint32_t)];
}
endianness_t;
class header
{
private:
// Signature for open files
int8_t m_magic[NUM_MAGIC_BYTES]; // (non-compacted)
int8_t m_version_high;
int8_t m_version_low;
int8_t m_sizeof_unsigned;
#if (NUM_MAGIC_BYTES+3)&7
int8_t padding[8-((NUM_MAGIC_BYTES+3)&7)];
#endif
uint32_t m_endianness; // Configuration data for
uint32_t m_block_size; // detection of compatibility
// isues
public:
uint32_t m_map_size; // (size in bytes, metadata included)
uint32_t m_meta_data_size; // (metadata size in bytes)
uint32_t m_free_list_first; // (index of fist free node)
uint32_t m_free_list_last; // (index of last free node)
uint32_t m_free_count; // (number of free nodes)
uint32_t m_state_flags;
uint32_t m_op_start_pos;
uint32_t m_op_bytes_requested;
uint32_t m_op_bytes_done;
void init () // Initialize the header (new file)
{
int i;
int8_t m[NUM_MAGIC_BYTES] = MAGIC_BYTES;
endianness_t e;
for (i=0; i<NUM_MAGIC_BYTES; i++)
m_magic[i] = m[i];
m_version_high = VERSION_HIGH;
m_version_low = VERSION_LOW;
m_sizeof_unsigned = sizeof(uint32_t);
for (i=0; i<(int)sizeof(e.bytes); i++)
e.bytes[i] = (int8_t)i;
m_endianness = e.num;
m_block_size = BLOCK_SIZE;
}
bool check_magic_bytes () const
{
int i;
int8_t m[NUM_MAGIC_BYTES] = MAGIC_BYTES;
for (i=0; i<NUM_MAGIC_BYTES; i++)
if (m_magic[i] != m[i])
return false;
return true;
}
bool verify_compatibility () const // Check compatibility
{ // of an existing file
int i;
endianness_t e = {0};
for (i=0; i<(int)sizeof(e.bytes); i++)
e.bytes[i] = (int8_t)i;
if (m_version_high != VERSION_HIGH ||
m_version_low != VERSION_LOW ||
m_sizeof_unsigned != sizeof(uint32_t))
return false;
if (m_endianness != e.num)
return false;
if (m_block_size != BLOCK_SIZE)
return false;
return true;
}
void set_current_op (uint32_t op,
uint32_t start_pos=0,
uint32_t bytes_requested=0,
uint32_t bytes_done=0)
{
m_state_flags = (m_state_flags & ~OP_MASK) |
(op & OP_MASK);
m_op_start_pos = start_pos;
m_op_bytes_requested = bytes_requested;
m_op_bytes_done = bytes_done;
}
}
GCC_ATTR_PACKED;
} // namespace detail
} // namespace shiftable_files
#ifdef _MSC_VER
#pragma pack(pop)
#endif
#undef GCC_ATTR_PACKED
#endif
| [
"martin@ROBOTITO"
] | [
[
[
1,
170
]
]
] |
d5a1ed6b1a93eb5247e6eabdcc78aad7c06beeed | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Source/Toxid/Game/Planet.cpp | 1d5f5f51e0bf52e6a6a3733f24c5f17eb0a73f3d | [] | no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cpp | // //
// ##### # # #### -= Nuclex Library =- //
// # ## ## # # Episode.cpp - Set of maps //
// # ### # # //
// # ### # # A set of maps which can be played through //
// # ## ## # # //
// # # # #### R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#include "Toxid/Game/Planet.h"
using namespace Toxid;
| [
"[email protected]"
] | [
[
[
1,
11
]
]
] |
7f12a3212e63da410d8709043f474558b9a8e277 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Agent/MiscAgent/Transform/hkpTransformAgent.h | a90a7bd6674879ed8676db543a40eb66fb718d06 | [] | no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,878 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_TRANSFORM_AGENT_H
#define HK_COLLIDE2_TRANSFORM_AGENT_H
#include <Physics/Collide/Agent/hkpCollisionAgent.h>
#include <Physics/Collide/Dispatch/hkpCollisionDispatcher.h>
class hkpCollisionDispatcher;
/// This agent handles collisions between hkpTransformShape and other shapes.
class hkpTransformAgent : public hkpCollisionAgent
{
public:
/// Registers this agent with the collision dispatcher.
static void HK_CALL registerAgent(hkpCollisionDispatcher* dispatcher);
// hkpCollisionAgent interface implementation.
virtual void processCollision(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& result);
// hkpCollisionAgent interface implementation.
virtual void linearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
// hkpCollisionAgent interface implementation.
static void HK_CALL staticLinearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
// hkpCollisionAgent interface implementation.
virtual void getClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& pointDetails);
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, class hkpCdPointCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void getPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetPenetrations( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void cleanup( hkCollisionConstraintOwner& constraintOwner );
// hkpCollisionAgent interface implementation.
virtual void invalidateTim( const hkpCollisionInput& input);
// hkpCollisionAgent interface implementation.
virtual void warpTime(hkTime oldTime, hkTime newTime, const hkpCollisionInput& input);
// hkpCollisionAgent interface implementation.
virtual void removePoint( hkContactPointId idToRemove );
// hkpCollisionAgent interface implementation.
virtual void commitPotential( hkContactPointId newId );
// hkpCollisionAgent interface implementation.
virtual void createZombie( hkContactPointId idTobecomeZombie );
void calcContentStatistics( hkStatisticsCollector* collector, const hkClass* cls ) const;
protected:
HK_FORCE_INLINE hkpTransformAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
virtual void updateShapeCollectionFilter( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkCollisionConstraintOwner& constraintOwner );
/// Agent creation function used by the hkpCollisionDispatcher.
static hkpCollisionAgent* HK_CALL createTransformAAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
static hkpCollisionAgent* HK_CALL createTransformBAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
protected:
hkpCollisionAgent* m_childAgent;
};
#endif // HK_COLLIDE2_TRANSFORM_AGENT_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
] | [
[
[
1,
96
]
]
] |
1cf54859af2a5a84e5fa48da92609c8b6332131d | ad33a51b7d45d8bf1aa900022564495bc08e0096 | /samples/demo6/test.cpp | fc90081f63f87fee924c1e42f8a22bbea4553741 | [] | no_license | CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4 | 31aff43df2571d334672929c88dfd41315a4098a | f33d52bbb59dfb758b24c0651449322ecd1b56b7 | refs/heads/master | 2016-09-11T02:42:42.116248 | 2011-09-26T04:30:32 | 2011-09-26T04:30:32 | 32,192,691 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,311 | cpp | #include "libnge2.h"
/**
* nge_gif:显示一张gif图片
*/
//退出标识
int game_quit = 0;
//背景图片
image_p p_bg = NULL;
//logo图片
image_p p_logo = NULL;
enum{
SCREEN_1X= 0,//原图显示
SCREEN_FULL, //满屏显示
SCREEN_2X //二倍显示
};
gif_desc_p pgif = NULL;
int display_flag = SCREEN_1X;
void btn_down(int keycode)
{
switch(keycode)
{
case PSP_BUTTON_UP:
break;
case PSP_BUTTON_DOWN:
break;
case PSP_BUTTON_LEFT:
break;
case PSP_BUTTON_RIGHT:
break;
case PSP_BUTTON_TRIANGLE:
display_flag = SCREEN_2X;
break;
case PSP_BUTTON_CIRCLE:
display_flag = SCREEN_FULL;
break;
case PSP_BUTTON_CROSS:
display_flag = SCREEN_1X;
break;
case PSP_BUTTON_SQUARE:
break;
case PSP_BUTTON_SELECT:
//按下选择键退出
game_quit = 1;
break;
case PSP_BUTTON_START:
//按下开始键退出
game_quit = 1;
break;
}
}
void DrawScene()
{
BeginScene(1);
ImageToScreen(p_bg,0,0);
switch(display_flag)
{
case SCREEN_FULL:
DrawGifAnimation(pgif,0,0,0,0,0,0,480,272);
break;
case SCREEN_1X:
GifAnimationToScreen(pgif,0,0);
break;
case SCREEN_2X:
RenderGifAnimation(pgif,0,0,0,0,0,0,2,2,0,pgif->gif_image_chains->pimage->mask);
break;
default:
break;
}
EndScene();
}
extern "C"
int main(int argc, char* argv[])
{
//初始化NGE分为VIDEO,AUDIO,这里是只初始化VIDEO,如果初始化所有用INIT_VIDEO|INIT_AUDIO,或者INIT_ALL
NGE_Init(INIT_VIDEO);
//初始化按键处理btn_down是按下响应,后面是弹起时的响应,0是让nge处理home消息(直接退出),填1就是让PSP系统处理
//home消息,通常填1正常退出(1.50版的自制程序需要填0)
InitInput(btn_down,NULL,1);
//最后一个参数是psp swizzle优化,通常填1
p_bg = image_load("images/demo0.jpg",DISPLAY_PIXEL_FORMAT_8888,1);
if(p_bg == NULL)
printf("can not open file\n");
pgif = gif_animation_load("images/simple.gif",DISPLAY_PIXEL_FORMAT_5551,1);
if(pgif == NULL)
printf("can not open file\n");
while ( !game_quit )
{
ShowFps();
InputProc();
DrawScene();
LimitFps(60);
}
image_free(p_bg);
image_free(p_logo);
gif_animation_free(pgif);
NGE_Quit();
return 0;
}
| [
"CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa"
] | [
[
[
1,
109
]
]
] |
efb667c371ca65c79885ec1b017e193d629ceb7e | 3aa3d03b639dca4cdf631e1982f8d1b6bf94f6c5 | /Addins/Nop.cpp | 59f49f7a9a1aa9182d10c82035b32832298cc4da | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | figment/nifcmd | e040ffba464f5bf0a3f4e8f72e11e4cd7360862d | 09c6eec62d700e2c99ebff32224eec044a302e10 | refs/heads/master | 2020-05-17T15:16:09.761021 | 2011-11-21T06:07:50 | 2011-11-21T06:07:50 | 2,817,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,716 | cpp | #include "stdafx.h"
#include "NifCmd.h"
using namespace std;
static void HelpString(NifCmd::HelpType type){
switch (type)
{
case NifCmd::htShort: cout << "NOP - Read/write with no modifications."; break;
case NifCmd::htLong:
{
char fullName[MAX_PATH], exeName[MAX_PATH];
GetModuleFileName(NULL, fullName, MAX_PATH);
_splitpath(fullName, NULL, NULL, exeName, NULL);
cout << "Usage: " << exeName << " nop [-opts[modifiers]]" << endl
<< " Simply read and write the file back out." << endl
<< endl
<< "<Switches>" << endl
<< " i <path> Input File" << endl
<< " o <path> Output File - Defaults to input file with '-out' appended" << endl
<< " v x.x.x.x Nif Version to write as - Defaults to input version" << endl
<< endl
;
}
break;
}
}
static bool ExecuteCmd(NifCmdLine &cmdLine)
{
string current_file = cmdLine.current_file;
string outfile = cmdLine.outfile;
unsigned outver = cmdLine.outver;
int argc = cmdLine.argc;
char **argv = cmdLine.argv;
list<NifCmd *> plugins;
for (int i = 0; i < argc; i++)
{
char *arg = argv[i];
if (arg == NULL)
continue;
if (arg[0] == '-' || arg[0] == '/')
{
fputs( "ERROR: Unknown argument specified \"", stderr );
fputs( arg, stderr );
fputs( "\".\n", stderr );
}
else if (current_file.empty())
{
current_file = arg;
}
}
if (current_file.empty()){
NifCmd::PrintHelp();
return false;
}
if (outfile.empty()) {
char path[MAX_PATH], drive[MAX_PATH], dir[MAX_PATH], fname[MAX_PATH], ext[MAX_PATH];
_splitpath(current_file.c_str(), drive, dir, fname, ext);
strcat(fname, "-out");
_makepath(path, drive, dir, fname, ext);
outfile = path;
}
unsigned int ver = GetNifVersion( current_file );
if ( ver == VER_UNSUPPORTED ) cout << "unsupported...";
else if ( ver == VER_INVALID ) cout << "invalid...";
else
{
// Finally alter block tree
Niflib::NifInfo info;
Niflib::NifOptions opts;
opts.exceptionOnErrors = false;
vector<NiObjectRef> blocks = ReadNifList( current_file, &info, &opts );
if (IsSupportedVersion(outver)) {
info.version = cmdLine.outver;
info.userVersion = cmdLine.uoutver;
info.userVersion2 = 0;
}
NiObjectRef root = blocks[0];
WriteNifTree(outfile, root, info);
return true;
}
return true;
}
REGISTER_COMMAND(Nop, HelpString, ExecuteCmd); | [
"tazpn@8bfd41d8-e20e-0410-8fd3-cfff02c53e26",
"tazpn314@8bfd41d8-e20e-0410-8fd3-cfff02c53e26",
"[email protected]"
] | [
[
[
1,
73
],
[
84,
84
],
[
86,
91
]
],
[
[
74,
74
],
[
79,
83
],
[
85,
85
]
],
[
[
75,
78
]
]
] |
45767dd9387222431a1f56f9f0b8d0b93761f809 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-06/pcbnew/autoplac.cpp | f8e6494abbf6814d527a02fd5424adc9b7f0b297 | [] | 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 | 34,657 | cpp | /*************************************************/
/* Routines de placement automatique des MODULES */
/*************************************************/
/* Fichier autoplac.cpp */
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "cell.h"
#include "protos.h"
/************************************************************/
/* Menu et Routines de placement automatique des composants */
/************************************************************/
#define GAIN 16
#define PENALITE 500
/* Penalite pour orientation donnee par CntRot90 et CntRot180:
gradue de 0 ( rotation interdite ) a 10 ( rotation a cout null )
Le cout est ici donne en majoration
*/
static float OrientPenality[11] = {
2.0, /* CntRot = 0 en fait rotation interdite */
1.9, /* CntRot = 1 */
1.8, /* CntRot = 2 */
1.7, /* CntRot = 3 */
1.6, /* CntRot = 4 */
1.5, /* CntRot = 5 */
1.4, /* CntRot = 5 */
1.3, /* CntRot = 7 */
1.2, /* CntRot = 8 */
1.1, /* CntRot = 9 */
1.0}; /* CntRot = 10 rotation autorisee, penalite nulle */
/* Etat d'une cellule */
#define OUT_OF_BOARD -2
#define OCCUPED_By_MODULE -1
/* variables locales */
static wxPoint CurrPosition; // position courante du module en cours de placement
static bool AutoPlaceShowAll = TRUE;
float MinCout;
/* Fonctions locales */
static int TstModuleOnBoard(BOARD * Pcb, MODULE * Module, bool TstOtherSide);
static void Build_PlacedPads_List(BOARD * Pcb);
static int Tri_PlaceModules(MODULE ** pt_ref, MODULE ** pt_compare);
static void TracePenaliteRectangle(BOARD * Pcb, int ux0, int uy0, int ux1, int uy1,
int marge, int Penalite, int masque_layer);
static MODULE * PickModule( WinEDA_PcbFrame * pcbframe, wxDC * DC );
/* variables importees */
extern CHEVELU * local_liste_chevelu; // adresse de base du buffer des chevelus locaux
extern int nb_local_chevelu; // nbr de links du module en deplacement
/********************************************************************************/
void WinEDA_PcbFrame::AutoPlaceModule(MODULE * Module, int place_mode, wxDC * DC)
/********************************************************************************/
/* Routine de Placement Automatique des composants dans le contour du PCB
Les composants ayant le status FIXE ne sont pas bouges
Si le menu appelant est le placement de 1 module, il sera replace
*/
{
int ii, activ;
MODULE * ThisModule = NULL;
MODULE ** BaseListeModules;
wxPoint PosOK;
wxPoint memopos;
int error;
int NbModules = 0;
int NbTotalModules = 0;
float Pas;
int lay_tmp_TOP, lay_tmp_BOTTOM, OldPasRoute;
if( m_Pcb->m_Modules == NULL ) return;
DrawPanel->m_AbortRequest = FALSE;
DrawPanel->m_AbortEnable = TRUE;
switch( place_mode )
{
case PLACE_1_MODULE:
ThisModule = Module;
if(ThisModule == NULL) return;
ThisModule->m_ModuleStatus &= ~(MODULE_is_PLACED|MODULE_to_PLACE);
break;
case PLACE_OUT_OF_BOARD:
break;
case PLACE_ALL:
if( ! IsOK(this, _("Footprints NOT LOCKED will be moved") ))
return;
break;
case PLACE_INCREMENTAL:
if( ! IsOK(this, _("Footprints NOT PLACED will be moved")) )
return;
break;
}
memopos = CurrPosition;
lay_tmp_BOTTOM = Route_Layer_BOTTOM;
lay_tmp_TOP = Route_Layer_TOP;
OldPasRoute = pas_route;
pas_route = m_CurrentScreen->GetGrid().x;
/* Generation du plan de placement */
if( GenPlaceBoard() == 0) return;
/* Mise a jour des parametres modules utiles au placement */
BaseListeModules = GenListeModules(m_Pcb, &NbTotalModules );
MyFree(BaseListeModules);
/* Placement des modules fixes sur le plan de placement */
Module = m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext) // remise a jour du rect d'encadrement
{
Module->Set_Rectangle_Encadrement();
Module->SetRectangleExinscrit();
}
Module = m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext )
{
Module->m_ModuleStatus &= ~MODULE_to_PLACE;
switch( place_mode )
{
case PLACE_1_MODULE:
if( ThisModule == Module )
Module->m_ModuleStatus |= MODULE_to_PLACE;
break;
case PLACE_OUT_OF_BOARD:
Module->m_ModuleStatus &= ~MODULE_is_PLACED;
if( Module->m_ModuleStatus & MODULE_is_LOCKED ) break;
if( ! m_Pcb->m_BoundaryBox.Inside(Module->m_Pos) )
Module->m_ModuleStatus |= MODULE_to_PLACE;
break;
case PLACE_ALL:
Module->m_ModuleStatus &= ~MODULE_is_PLACED;
if( Module->m_ModuleStatus & MODULE_is_LOCKED ) break;
Module->SetState(MODULE_to_PLACE, TRUE);
break;
case PLACE_INCREMENTAL:
if( Module->m_ModuleStatus & MODULE_is_LOCKED )
{
Module->m_ModuleStatus &= ~MODULE_is_PLACED; break;
}
if( ! (Module->m_ModuleStatus & MODULE_is_PLACED) )
Module->m_ModuleStatus |= MODULE_to_PLACE;
break;
}
if( Module->m_ModuleStatus & MODULE_to_PLACE ) // Erase from screen
{
NbModules++;
Module->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR);
}
else
{
GenModuleOnBoard(Module);
}
}
/* Placement des modules */
activ = 0; Pas = 100.0;
if( NbModules ) Pas = 100.0 / (float)NbModules;
while( (Module = PickModule(this, DC) ) != NULL )
{
float BestScore;
DisplayActivity((int)(activ * Pas) , wxEmptyString ); activ++;
/* Affichage du remplissage: surface de placement, obstacles, penalites */
DrawInfoPlace(DC);
/* Recherche du placement: orientation 0 */
error = RecherchePlacementModule(Module, DC);
BestScore = MinCout;
PosOK = CurrPosition;
if ( error == ESC ) goto end_of_tst;
/* Recherche du placement: orientation 180 */
ii = Module->m_CntRot180 & 0x0F;
if( ii != 0 )
{
int Angle_Rot_Module = 1800;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
Module->SetRectangleExinscrit();
error = RecherchePlacementModule(Module, DC );
MinCout *= OrientPenality[ii];
if( BestScore > MinCout ) /* Cette orientation est meilleure */
{
PosOK = CurrPosition;
BestScore = MinCout;
}
else
{
Angle_Rot_Module = -1800;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
}
if ( error == ESC ) goto end_of_tst;
}
/* Recherche du placement: orientation 90 */
ii = Module->m_CntRot90 & 0x0F;
if( ii != 0 )
{
int Angle_Rot_Module = 900;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
error = RecherchePlacementModule(Module, DC );
MinCout *= OrientPenality[ii];
if( BestScore > MinCout ) /* Cette orientation est meilleure */
{
PosOK = CurrPosition;
BestScore = MinCout;
}
else
{
Angle_Rot_Module = -900;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
}
if ( error == ESC ) goto end_of_tst;
}
/* Recherche du placement: orientation -90 (ou 270 degres) */
ii = (Module->m_CntRot90 >> 4 ) & 0x0F;
if( ii != 0 )
{
int Angle_Rot_Module = 2700;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
error = RecherchePlacementModule(Module, DC );
MinCout *= OrientPenality[ii];
if( BestScore > MinCout ) /* Cette orientation est meilleure */
{
PosOK = CurrPosition;
BestScore = MinCout;
}
else
{
Angle_Rot_Module = -2700;
Rotate_Module(DC, Module, Angle_Rot_Module, FALSE);
}
if ( error == ESC ) goto end_of_tst;
}
end_of_tst:
Module->SetRectangleExinscrit();
if ( error == ESC ) break;
/* placement du module */
CurrPosition = m_CurrentScreen->m_Curseur;
m_CurrentScreen->m_Curseur = PosOK;
Place_Module(Module, DC);
m_CurrentScreen->m_Curseur = CurrPosition;
GenModuleOnBoard(Module);
Module->m_ModuleStatus |= MODULE_is_PLACED;
Module->m_ModuleStatus &= ~MODULE_to_PLACE;
}
CurrPosition = memopos;
/* Liberation de la memoire */
Board.UnInitBoard();
Route_Layer_TOP = lay_tmp_TOP;
Route_Layer_BOTTOM = lay_tmp_BOTTOM;
pas_route = OldPasRoute;
Module = m_Pcb->m_Modules;
for( ; Module != NULL; Module = (MODULE*)Module->Pnext )
{
Module->Set_Rectangle_Encadrement();
}
/* Recalcul de la liste des pads, detruite par les calculs precedents */
m_Pcb->m_Status_Pcb = 0; build_liste_pads();
DrawPanel->ReDraw(DC, TRUE);
DrawPanel->m_AbortEnable = FALSE;
}
/**********************************************/
void WinEDA_PcbFrame::DrawInfoPlace(wxDC * DC)
/**********************************************/
/* Affiche a l'ecran les infos de placement
*/
{
int color, ii, jj;
int ox, oy, top_state, bottom_state;
GRSetDrawMode(DC, GR_COPY);
for ( ii = 0; ii < Nrows; ii ++ )
{
oy = m_Pcb->m_BoundaryBox.m_Pos.y + (ii * pas_route);
for (jj = 0; jj < Ncols ; jj ++ )
{
ox = m_Pcb->m_BoundaryBox.m_Pos.x + (jj * pas_route);
/* surface de placement : */
color = BLACK;
top_state = GetCell(ii, jj , TOP);
bottom_state = GetCell(ii, jj , BOTTOM);
if( top_state & CELL_is_ZONE ) color = BLUE;
/* obstacles */
if( top_state & (HOLE|CELL_is_MODULE) ) color = LIGHTRED;
else if( bottom_state & (HOLE|CELL_is_MODULE) ) color = LIGHTGREEN;
else /* Affichage du remplissage: Penalites */
{
if( GetDist(ii, jj , TOP ) || GetDist(ii, jj , BOTTOM ) )
color = DARKGRAY;
}
GRPutPixel(&DrawPanel->m_ClipBox, DC, ox, oy, color);
}
}
}
/***************************************/
int WinEDA_PcbFrame::GenPlaceBoard(void)
/***************************************/
/* Routine de generation du board ( cote composant + cote cuivre ) :
Alloue la memoire necessaire pour representer en "bitmap" sur la grille
courante:
- la surface de placement des composant ( le board )
- le bitmap des penalites
et initialise les cellules du board a
- HOLE pour les cellules occupees par un segment EDGE
- CELL_is_ZONE pour les cellules internes au contour EDGE (s'il est ferme)
la surface de placement (board) donne les cellules internes au contour
du pcb, et parmi celle-ci les cellules libres et les cellules deja occupees
le bitmap des penalites donnent les cellules occupes par les modules,
augmentes d'une surface de penalite liee au nombre de pads du module
le bitmap des penalites est mis a 0
l'occupation des cellules est laisse a 0
*/
{
int jj, ii;
int NbCells;
EDA_BaseStruct * PtStruct;
wxString msg;
Board.UnInitBoard();
if( ! SetBoardBoundaryBoxFromEdgesOnly() )
{
DisplayError(this, _("No edge PCB, Unknown board size!"), 30);
return(0);
}
/* The boundary box must have its start point on placing grid: */
m_Pcb->m_BoundaryBox.m_Pos.x -= m_Pcb->m_BoundaryBox.m_Pos.x % pas_route;
m_Pcb->m_BoundaryBox.m_Pos.y -= m_Pcb->m_BoundaryBox.m_Pos.y % pas_route;
/* The boundary box must have its end point on placing grid: */
wxPoint end = m_Pcb->m_BoundaryBox.GetEnd();
end.x -= end.x % pas_route; end.x += pas_route;
end.y -= end.y % pas_route; end.y += pas_route;
m_Pcb->m_BoundaryBox.SetEnd(end);
Nrows = m_Pcb->m_BoundaryBox.GetHeight() / pas_route;
Ncols = m_Pcb->m_BoundaryBox.GetWidth() / pas_route;
/* get a small margin for memory allocation: */
Ncols += 2; Nrows += 2;
NbCells = Ncols * Nrows;
MsgPanel->EraseMsgBox();
msg.Printf( wxT("%d"),Ncols);
Affiche_1_Parametre(this, 1, _("Cols"),msg,GREEN);
msg.Printf( wxT("%d"),Nrows);
Affiche_1_Parametre(this, 7, _("Lines"),msg,GREEN);
msg.Printf( wxT("%d"),NbCells);
Affiche_1_Parametre(this, 14, _("Cells."),msg,YELLOW);
/* Choix du nombre de faces de placement */
Nb_Sides = TWO_SIDES;
Affiche_1_Parametre(this, 22, wxT("S"), ( Nb_Sides == TWO_SIDES ) ? wxT("2") : wxT("1"), WHITE);
/* Creation du mapping du board */
Board.InitBoard();
/* Affichage de la memoire utilisee */
msg.Printf( wxT("%d"), Board.m_MemSize / 1024 );
Affiche_1_Parametre(this, 24, wxT("Mem(Ko)"),msg,CYAN);
Route_Layer_BOTTOM = CMP_N;
if( Nb_Sides == TWO_SIDES ) Route_Layer_BOTTOM = CUIVRE_N;
Route_Layer_TOP = CMP_N;
/* Place the edge layer segments */
PtStruct = m_Pcb->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext )
{
TRACK *TmpSegm;
DRAWSEGMENT * DrawSegm;
switch( PtStruct->m_StructType)
{
case TYPEDRAWSEGMENT:
DrawSegm = (DRAWSEGMENT *) PtStruct;
if(DrawSegm->m_Layer != EDGE_N) continue;
TmpSegm = new TRACK(NULL);
TmpSegm->m_Layer = -1;
TmpSegm->m_Start = DrawSegm->m_Start;
TmpSegm->m_End = DrawSegm->m_End;
TmpSegm->m_Shape = DrawSegm->m_Shape;
TmpSegm->m_Width = DrawSegm->m_Width;
TmpSegm->m_NetCode = -1;
TraceSegmentPcb(m_Pcb, TmpSegm, HOLE, BOTTOM,WRITE_CELL );
delete TmpSegm;
break;
case TYPETEXTE:
default: break;
}
}
/* Init du point d'accrochage de la zone */
OrCell(Nrows/2, Ncols/2, BOTTOM, CELL_is_ZONE);
/* Remplissage des cellules de la couche BOTTOM */
ii = 1, jj = 1;
while( ii )
{
msg.Printf( wxT("%d"), jj++ );
Affiche_1_Parametre(this, 50, _("Loop"),msg,CYAN);
ii = Propagation(this);
}
/* Init de la couche TOP */
if( Board.m_BoardSide[TOP] )
memcpy( Board.m_BoardSide[TOP], Board.m_BoardSide[BOTTOM],NbCells * sizeof(BoardCell));
return(1);
}
/******************************************************/
void WinEDA_PcbFrame::GenModuleOnBoard(MODULE * Module)
/******************************************************/
/* initialise sur le board de placement les cellules correspondantes au
module Module
*/
{
int ox, oy, fx, fy, Penalite;
int marge = pas_route / 2;
int masque_layer;
D_PAD * Pad;
ox = Module->m_RealBoundaryBox.m_Pos.x - marge;
fx = Module->m_RealBoundaryBox.GetRight() + marge;
oy = Module->m_RealBoundaryBox.m_Pos.y - marge;
fy = Module->m_RealBoundaryBox.GetBottom() + marge;
if( ox < m_Pcb->m_BoundaryBox.m_Pos.x)
ox = m_Pcb->m_BoundaryBox.m_Pos.x;
if( ox > m_Pcb->m_BoundaryBox.GetRight())
ox = m_Pcb->m_BoundaryBox.GetRight();
if( fx < m_Pcb->m_BoundaryBox.m_Pos.x) fx = m_Pcb->m_BoundaryBox.m_Pos.x;
if( fx > m_Pcb->m_BoundaryBox.GetRight())
fx = m_Pcb->m_BoundaryBox.GetRight();
if( oy < m_Pcb->m_BoundaryBox.m_Pos.y) oy = m_Pcb->m_BoundaryBox.m_Pos.y;
if( oy > m_Pcb->m_BoundaryBox.GetBottom())
oy = m_Pcb->m_BoundaryBox.GetBottom();
if( fy < m_Pcb->m_BoundaryBox.m_Pos.y) fy = m_Pcb->m_BoundaryBox.m_Pos.y;
if( fy > m_Pcb->m_BoundaryBox.GetBottom())
fy = m_Pcb->m_BoundaryBox.GetBottom();
masque_layer = 0;
if( Module->m_Layer == CMP_N ) masque_layer = CMP_LAYER;
if( Module->m_Layer == CUIVRE_N ) masque_layer = CUIVRE_LAYER;
TraceFilledRectangle(m_Pcb, ox, oy, fx, fy, masque_layer,
CELL_is_MODULE, WRITE_OR_CELL);
/* Trace des pads et leur surface de securite */
marge = g_DesignSettings.m_TrackClearence + g_DesignSettings.m_CurrentTrackWidth;
for(Pad = Module->m_Pads ; Pad != NULL; Pad = (D_PAD *) Pad->Pnext )
{
Place_1_Pad_Board( m_Pcb, Pad, CELL_is_MODULE, marge, WRITE_OR_CELL);
}
/* Trace de la penalite */
marge = (pas_route * Module->m_PadNum ) / GAIN;
Penalite = PENALITE;
TracePenaliteRectangle(m_Pcb, ox, oy, fx, fy, marge, Penalite,
masque_layer);
}
/************************************************************************/
int WinEDA_PcbFrame::RecherchePlacementModule(MODULE * Module, wxDC * DC)
/************************************************************************/
/*
Routine Principale de recherche de la position optimale du module
Entree:
Module pointe la struct MODULE du module a placer.
Retourne:
1 si placement impossible, 0 si OK
et MinCout = variable externe = cout du meilleur placement
*/
{
int cx, cy;
int ox, oy, fx, fy; /* cadre d'occupation du module centre sur le curseur */
int error = 1;
int DisplayChevelu = 0;
wxPoint LastPosOK;
float mincout, cout, Score;
int Penalite;
bool TstOtherSide;
Module->Display_Infos(this);
Build_PlacedPads_List(m_Pcb);
LastPosOK.x = m_Pcb->m_BoundaryBox.m_Pos.x;
LastPosOK.y = m_Pcb->m_BoundaryBox.m_Pos.y;
cx = Module->m_Pos.x; cy = Module->m_Pos.y;
ox = Module->m_RealBoundaryBox.m_Pos.x - cx;
fx = Module->m_RealBoundaryBox.m_Size.x + ox;
oy = Module->m_RealBoundaryBox.m_Pos.y - cy;
fy = Module->m_RealBoundaryBox.m_Size.y + oy;
CurrPosition.x = m_Pcb->m_BoundaryBox.m_Pos.x - ox;
CurrPosition.y = m_Pcb->m_BoundaryBox.m_Pos.y - oy;
/* remise sur la grille de placement: */
CurrPosition.x -= CurrPosition.x % pas_route;
CurrPosition.y -= CurrPosition.y % pas_route;
g_Offset_Module.x = cx - CurrPosition.x;
g_Offset_Module.y = cy - CurrPosition.y;
m_Pcb->m_Status_Pcb &= ~CHEVELU_LOCAL_OK;
/* tst des pastilles traversantes, qui pour un circuit imprime ayant des
composants des 2 cotes, peuvent tomber sur un composant de cote oppose:
s'il y a au moins 1 pastille apparaissant sur l'autre cote, ce cote
est teste */
TstOtherSide = FALSE;
if( Nb_Sides == TWO_SIDES )
{
D_PAD * Pad; int masque_otherlayer;
masque_otherlayer = CUIVRE_LAYER;
if ( Module->m_Layer == CUIVRE_N ) masque_otherlayer = CMP_LAYER;
for(Pad = Module->m_Pads ; Pad != NULL; Pad = (D_PAD *) Pad->Pnext )
{
if( (Pad->m_Masque_Layer & masque_otherlayer) == 0 ) continue;
TstOtherSide = TRUE;
break;
}
}
Dessine_Silouhette_Module(DrawPanel, DC, Module);
mincout = -1.0;
Affiche_Message(wxT("Score ??, pos ??") );
for ( ; CurrPosition.x < m_Pcb->m_BoundaryBox.GetRight() - fx;
CurrPosition.x += pas_route )
{
wxYield();
if ( DrawPanel->m_AbortRequest )
{
if ( IsOK(this, _("Ok to abort ?")) ) return ESC;
else DrawPanel->m_AbortRequest = FALSE;
}
cx = Module->m_Pos.x; cy = Module->m_Pos.y;
Module->m_RealBoundaryBox.m_Pos.x = ox + CurrPosition.x;
Module->m_RealBoundaryBox.m_Pos.y = oy + CurrPosition.y;
Dessine_Silouhette_Module(DrawPanel, DC, Module);
g_Offset_Module.x = cx - CurrPosition.x;
CurrPosition.y = m_Pcb->m_BoundaryBox.m_Pos.y - oy;
/* remise sur la grille de placement: */
CurrPosition.y -= CurrPosition.y % pas_route;
Dessine_Silouhette_Module(DrawPanel, DC, Module);
for ( ; CurrPosition.y < m_Pcb->m_BoundaryBox.GetBottom() - fy;
CurrPosition.y += pas_route )
{
/* effacement des traces */
Dessine_Silouhette_Module(DrawPanel, DC, Module);
if (DisplayChevelu) Compute_Ratsnest_PlaceModule(DC);
DisplayChevelu = 0;
Module->m_RealBoundaryBox.m_Pos.x = ox + CurrPosition.x;
Module->m_RealBoundaryBox.m_Pos.y = oy + CurrPosition.y;
g_Offset_Module.y = cy - CurrPosition.y;
Dessine_Silouhette_Module(DrawPanel, DC, Module);
Penalite = TstModuleOnBoard(m_Pcb, Module, TstOtherSide );
if( Penalite >= 0 ) /* c a d si le module peut etre place */
{
error = 0;
build_ratsnest_module(DC, Module);
cout = Compute_Ratsnest_PlaceModule(DC);
DisplayChevelu = 1;
Score = cout + (float) Penalite;
if( (mincout >= Score ) || (mincout < 0 ) )
{
LastPosOK = CurrPosition;
mincout = Score;
wxString msg;
msg.Printf( wxT("Score %d, pos %3.4f, %3.4f"),
(int)mincout,
(float)LastPosOK.x /10000, (float)LastPosOK.y /10000);
Affiche_Message(msg);
}
}
if( DisplayChevelu ) Compute_Ratsnest_PlaceModule(DC);
DisplayChevelu = 0;
}
}
Dessine_Silouhette_Module(DrawPanel, DC, Module); /* effacement du dernier trace */
if (DisplayChevelu) Compute_Ratsnest_PlaceModule(DC);
/* Regeneration des variables modifiees */
Module->m_RealBoundaryBox.m_Pos.x = ox + cx;
Module->m_RealBoundaryBox.m_Pos.y = oy + cy;
CurrPosition = LastPosOK;
m_Pcb->m_Status_Pcb &= ~(CHEVELU_LOCAL_OK | LISTE_PAD_OK );
MinCout = mincout;
return(error);
}
/**************************************************************************/
int TstRectangle(BOARD * Pcb, int ux0, int uy0, int ux1, int uy1, int side)
/**************************************************************************/
/* tst si la surface rectangulaire (ux,y0 .. ux,y1):
- est sur une zone libre ( retourne OCCUPED_By_MODULE sinon)
- est sur la surface utile du board ( retourne OUT_OF_BOARD sinon)
retourne 0 si OK
*/
{
int row, col;
int row_min, row_max, col_min, col_max;
unsigned int data;
ux0 -= Pcb->m_BoundaryBox.m_Pos.x; uy0 -= Pcb->m_BoundaryBox.m_Pos.y;
ux1 -= Pcb->m_BoundaryBox.m_Pos.x; uy1 -= Pcb->m_BoundaryBox.m_Pos.y;
/* Calcul des coord limites des cellules appartenant au rectangle */
row_max = uy1 / pas_route;
col_max = ux1 / pas_route;
row_min = uy0 / pas_route; if (uy0 > row_min*pas_route ) row_min++;
col_min = ux0 / pas_route; if (ux0 > col_min*pas_route ) col_min++;
if( row_min < 0 ) row_min = 0;
if( row_max >= (Nrows-1)) row_max = Nrows-1;
if( col_min < 0 ) col_min = 0;
if( col_max >= (Ncols-1)) col_max = Ncols-1;
for( row = row_min ;row <= row_max ; row++)
{
for(col = col_min;col <= col_max; col++)
{
data = GetCell(row,col,side);
if( (data & CELL_is_ZONE) == 0 ) /* Cellule non autorisee */
return(OUT_OF_BOARD);
if( data & CELL_is_MODULE ) /* Deja utilisee */
return(OCCUPED_By_MODULE);
}
}
return( 0 );
}
/******************************************************************************/
unsigned int CalculePenaliteRectangle(BOARD * Pcb, int ux0, int uy0,
int ux1, int uy1, int side)
/******************************************************************************/
/* calcule et retourne la penalite de la surface rectangulaire (ux,y0 .. ux,y1):
( somme des valeurs des cellules du plan des Distances )
*/
{
int row, col;
int row_min, row_max, col_min, col_max;
unsigned int Penalite;
ux0 -= Pcb->m_BoundaryBox.m_Pos.x; uy0 -= Pcb->m_BoundaryBox.m_Pos.y;
ux1 -= Pcb->m_BoundaryBox.m_Pos.x; uy1 -= Pcb->m_BoundaryBox.m_Pos.y;
/* Calcul des coord limites des cellules appartenant au rectangle */
row_max = uy1 / pas_route;
col_max = ux1 / pas_route;
row_min = uy0 / pas_route; if (uy0 > row_min*pas_route ) row_min++;
col_min = ux0 / pas_route; if (ux0 > col_min*pas_route ) col_min++;
if( row_min < 0 ) row_min = 0;
if( row_max >= (Nrows-1)) row_max = Nrows-1;
if( col_min < 0 ) col_min = 0;
if( col_max >= (Ncols-1)) col_max = Ncols-1;
Penalite = 0;
for( row = row_min ;row <= row_max ; row++)
{
for(col = col_min;col <= col_max; col++)
{
Penalite += (int) GetDist(row, col, side );
}
}
return( Penalite );
}
/**********************************************************************/
int TstModuleOnBoard(BOARD * Pcb, MODULE * Module, bool TstOtherSide)
/**********************************************************************/
/* Teste si le module peut etre place sur le board.
retourne de diagnostic de TstRectangle().
le module est connu par son rectangle d'encadrement
*/
{
int ox, oy, fx, fy;
int error, Penalite, marge, side, otherside;
side = TOP; otherside = BOTTOM;
if ( Module->m_Layer == CUIVRE_N )
{
side = BOTTOM; otherside = TOP;
}
ox = Module->m_RealBoundaryBox.m_Pos.x;
fx = Module->m_RealBoundaryBox.GetRight();
oy = Module->m_RealBoundaryBox.m_Pos.y;
fy = Module->m_RealBoundaryBox.GetBottom();
error = TstRectangle(Pcb, ox, oy, fx, fy, side );
if( error < 0 ) return (error);
if( TstOtherSide )
{
error = TstRectangle(Pcb, ox, oy, fx, fy, otherside );
if( error < 0 ) return (error);
}
marge = (pas_route * Module->m_PadNum ) / GAIN;
Penalite = CalculePenaliteRectangle(Pcb, ox - marge, oy - marge,
fx + marge, fy + marge, side );
return( Penalite );
}
/************************************************************/
float WinEDA_PcbFrame::Compute_Ratsnest_PlaceModule(wxDC * DC)
/************************************************************/
/* Routine affichant le chevelu du module en cours de deplacement, et
evaluant le "cout" de la position.
Le cout est la longueur des chevelus en distance de manhattan, avec
penalite pour les inclinaisons se rapprochant de 45 degre
*/
{
CHEVELU* pt_local_chevelu ;
int ii;
float cout, icout;
int ox, oy, fx, fy, dx , dy;
if((m_Pcb->m_Status_Pcb & CHEVELU_LOCAL_OK) == 0)
return(-1);
pt_local_chevelu = local_liste_chevelu;
ii = nb_local_chevelu; cout = 0;
while( ii-- > 0 )
{
if(pt_local_chevelu->status & LOCAL_CHEVELU)
{ // Non Affiché
}
else
{
ox = pt_local_chevelu->pad_start->m_Pos.x - g_Offset_Module.x;
oy = pt_local_chevelu->pad_start->m_Pos.y - g_Offset_Module.y;
fx = pt_local_chevelu->pad_end->m_Pos.x;
fy = pt_local_chevelu->pad_end->m_Pos.y;
if ( AutoPlaceShowAll )
{
GRLine(&DrawPanel->m_ClipBox, DC, ox, oy, fx, fy, g_DesignSettings.m_RatsnestColor|GR_XOR) ;
}
/* Evaluation du cout du chevelu: */
dx = fx - ox; dy = fy - oy;
dx = abs(dx); dy = abs( dy );
if( dx < dy ) EXCHG(dx,dy); /* dx >= dy */
/* cout de la distance: */
icout = (float) dx * dx;
/* cout de l'inclinaison */
icout += 3 * (float) dy * dy;
icout = sqrt(icout);
cout += icout; /* cout total = somme des couts de chaque chevelu */
}
pt_local_chevelu++;
}
return (cout);
}
/********************************************/
void Build_PlacedPads_List(BOARD * Pcb)
/********************************************/
/*
construction de la liste ( sous forme d'une liste de stucture )
des caract utiles des pads du PCB pour Placement Automatique )
Cette liste est restreinte a la liste des pads des modules deja places sur
la carte.
parametres:
adresse du buffer de classement = Pcb->ptr_pads;
Variables globales mise a jour:
pointeur ptr_pads (adr de classement de la liste des pads)
nb_pads = nombre utile de pastilles classes
m_Status_Pcb |= LISTE_PAD_OK
*/
{
LISTE_PAD* pt_liste_pad;
MODULE * Module;
D_PAD * PtPad;
if( Pcb->m_Pads ) MyFree( Pcb->m_Pads );
pt_liste_pad = Pcb->m_Pads = NULL;
Pcb->m_NbPads = Pcb->m_NbNodes = 0;
/* Calcul du nombre de pads utiles */
Module = Pcb->m_Modules;
for( ; Module != NULL ; Module = (MODULE*) Module->Pnext)
{
if( Module->m_ModuleStatus & MODULE_to_PLACE ) continue;
PtPad = (D_PAD*) Module->m_Pads;
for(; PtPad != NULL; PtPad = (D_PAD*) PtPad->Pnext )
{
Pcb->m_NbPads++;
}
}
/* Allocation memoire du buffer */
if ( Pcb->m_NbPads > 0)
{
pt_liste_pad = Pcb->m_Pads
= (D_PAD**) MyMalloc(Pcb->m_NbPads * sizeof(D_PAD*) );
}
/* Initialisation du buffer et des variables de travail */
Module = Pcb->m_Modules;
for( ;(Module != NULL) && (pt_liste_pad != NULL); Module = (MODULE*) Module->Pnext)
{
if( Module->m_ModuleStatus & MODULE_to_PLACE ) continue;
PtPad = (D_PAD*) Module->m_Pads;
for(; PtPad != NULL; PtPad = (D_PAD*) PtPad->Pnext )
{
*pt_liste_pad = PtPad;
PtPad->m_physical_connexion = 0;
PtPad->m_logical_connexion = 0;
PtPad->m_Parent = Module;
if(PtPad->m_NetCode) Pcb->m_NbNodes++;
pt_liste_pad++;
}
}
Pcb->m_Status_Pcb |= LISTE_PAD_OK;
Pcb->m_Status_Pcb &= ~(LISTE_CHEVELU_OK | CHEVELU_LOCAL_OK);
adr_lowmem = buf_work;
}
/*****************************************************************/
/* Construction de la zone de penalite ( rectangle ) d'un module */
/*****************************************************************/
/* les cellules ( du plan des Distances ) du rectangle x0,y0 a x1,y1 sont
incrementees de la valeur Penalite
celles qui sont externes au rectangle, mais internes au rectangle
x0,y0 -marge a x1,y1 + marge sont incrementees d'une valeur
(Penalite ... 0) decroissante en fonction de leur eloignement
*/
static void TracePenaliteRectangle(BOARD * Pcb, int ux0, int uy0, int ux1, int uy1 ,
int marge, int Penalite, int masque_layer)
{
int row, col;
int row_min, row_max, col_min, col_max, pmarge;
int trace = 0;
DistCell data, LocalPenalite;
int lgain, cgain;
if(masque_layer & g_TabOneLayerMask[Route_Layer_BOTTOM])
trace = 1; /* Trace sur BOTTOM */
if( (masque_layer & g_TabOneLayerMask[Route_Layer_TOP] ) && Nb_Sides)
trace |= 2; /* Trace sur TOP */
if(trace == 0) return;
ux0 -= Pcb->m_BoundaryBox.m_Pos.x; uy0 -= Pcb->m_BoundaryBox.m_Pos.y;
ux1 -= Pcb->m_BoundaryBox.m_Pos.x; uy1 -= Pcb->m_BoundaryBox.m_Pos.y;
ux0 -= marge; ux1 += marge;
uy0 -= marge; uy1 += marge;
pmarge = marge / pas_route; if (pmarge < 1 ) pmarge = 1;
/* Calcul des coord limites des cellules appartenant au rectangle */
row_max = uy1 / pas_route;
col_max = ux1 / pas_route;
row_min = uy0 / pas_route; if (uy0 > row_min*pas_route ) row_min++;
col_min = ux0 / pas_route; if (ux0 > col_min*pas_route ) col_min++;
if( row_min < 0 ) row_min = 0;
if( row_max >= (Nrows-1)) row_max = Nrows-1;
if( col_min < 0 ) col_min = 0;
if( col_max >= (Ncols-1)) col_max = Ncols-1;
for( row = row_min ;row <= row_max ; row++)
{
lgain = 256;
if ( row < pmarge )
lgain = (256 * row) / pmarge;
else if( row > row_max - pmarge )
lgain = (256 * (row_max - row) ) / pmarge;
for(col = col_min;col <= col_max; col++)
{
cgain = 256;
LocalPenalite = Penalite;
if ( col < pmarge )
cgain = (256 * col) / pmarge;
else if( col > col_max - pmarge )
cgain = (256 * (col_max - col) ) / pmarge;
cgain = (cgain * lgain) / 256;
if( cgain != 256 ) LocalPenalite = (LocalPenalite * cgain) / 256;
if(trace & 1)
{
data = GetDist(row,col,BOTTOM) + LocalPenalite;
SetDist(row,col,BOTTOM, data);
}
if(trace & 2)
{
data = GetDist(row,col,TOP);
data = max( data, LocalPenalite);
SetDist(row,col,TOP, data);
}
}
}
}
/***************************************************/
/* Routines de tri de modules, utilisee par qsort: */
/***************************************************/
static int Tri_PlaceModules(MODULE ** pt_ref, MODULE ** pt_compare)
{
float ff, ff1, ff2 ;
ff1 = (*pt_ref)->m_Surface * (*pt_ref)->m_PadNum ;
ff2 = (*pt_compare)->m_Surface * (*pt_compare)->m_PadNum ;
ff = ff1 - ff2 ;
if( ff < 0 ) return(1) ;
if( ff > 0 ) return(-1) ;
return( 0 );
}
static int Tri_RatsModules(MODULE ** pt_ref, MODULE ** pt_compare)
{
float ff, ff1, ff2 ;
ff1 = (*pt_ref)->m_Surface * (*pt_ref)->flag;
ff2 = (*pt_compare)->m_Surface * (*pt_compare)->flag;
ff = ff1 - ff2 ;
if( ff < 0 ) return(1) ;
if( ff > 0 ) return(-1) ;
return( 0 );
}
/***************************************************************/
static MODULE * PickModule(WinEDA_PcbFrame * pcbframe, wxDC * DC)
/***************************************************************/
/* Recherche le "meilleur" module a placer
les criteres de choix sont:
- maximum de chevelus avec les modules deja places
- taille max, et nombre de pads max
*/
{
MODULE ** BaseListeModules, ** pt_Dmod;
MODULE * Module = NULL, * AltModule = NULL;
CHEVELU* pt_local_chevelu;
int NbModules, ii;
BaseListeModules = GenListeModules(pcbframe->m_Pcb, &NbModules );
if( BaseListeModules == NULL ) return(NULL);
Build_PlacedPads_List(pcbframe->m_Pcb);
/* Tri par surface decroissante des modules
(on place les plus gros en 1er), surface ponderee par le nombre de pads */
qsort(BaseListeModules, NbModules, sizeof(MODULE**),
(int(*)(const void *, const void * ))Tri_PlaceModules);
for(pt_Dmod = BaseListeModules; *pt_Dmod != NULL; pt_Dmod++)
{
(*pt_Dmod)->flag = 0;
if( ! ((*pt_Dmod)->m_ModuleStatus & MODULE_to_PLACE) ) continue;
pcbframe->m_Pcb->m_Status_Pcb &= ~CHEVELU_LOCAL_OK;
adr_lowmem = buf_work;
(*pt_Dmod)->Display_Infos(pcbframe);
pcbframe->build_ratsnest_module(DC, *pt_Dmod);
/* calcul du nombre de chevelus externes */
pt_local_chevelu = local_liste_chevelu;
ii = nb_local_chevelu;
while( ii-- > 0 )
{
if( (pt_local_chevelu->status & LOCAL_CHEVELU) == 0 )
(*pt_Dmod)->flag++;
pt_local_chevelu++;
}
}
pcbframe->m_Pcb->m_Status_Pcb &= ~CHEVELU_LOCAL_OK;
qsort(BaseListeModules, NbModules, sizeof(MODULE**),
(int(*)(const void *, const void * ))Tri_RatsModules);
/* Recherche du "meilleur" module */
Module = NULL;
for(pt_Dmod = BaseListeModules; *pt_Dmod != NULL; pt_Dmod++)
{
if( ! ((*pt_Dmod)->m_ModuleStatus & MODULE_to_PLACE) ) continue;
AltModule = *pt_Dmod;
if( (*pt_Dmod)->flag == 0 ) continue;
Module = *pt_Dmod; break;
}
MyFree(BaseListeModules);
if ( Module ) return(Module);
else return(AltModule);
}
/*******************************************************/
bool WinEDA_PcbFrame::SetBoardBoundaryBoxFromEdgesOnly(void)
/*******************************************************/
/* Determine le rectangle d'encadrement du pcb, selon les contours
(couche EDGE) uniquement
Sortie:
m_Pcb->m_BoundaryBox mis a jour
Retourne FALSE si pas de contour
*/
{
int rayon, cx, cy, d;
int xmax, ymax;
EDA_BaseStruct * PtStruct;
DRAWSEGMENT* ptr;
bool succes = FALSE;
if (m_Pcb == NULL) return FALSE;
m_Pcb->m_BoundaryBox.m_Pos.x = m_Pcb->m_BoundaryBox.m_Pos.y = 0x7FFFFFFFl ;
xmax = ymax = -0x7FFFFFFFl ;
/* Analyse des Contours PCB */
PtStruct = m_Pcb->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext )
{
if( PtStruct->m_StructType != TYPEDRAWSEGMENT ) continue;
succes = TRUE;
ptr = (DRAWSEGMENT*) PtStruct;
d = (ptr->m_Width /2) + 1;
if(ptr->m_Shape == S_CIRCLE)
{
cx = ptr->m_Start.x; cy = ptr->m_Start.y;
rayon = (int)hypot((double)(ptr->m_End.x-cx),(double)(ptr->m_End.y-cy) );
rayon += d;
m_Pcb->m_BoundaryBox.m_Pos.x = min(m_Pcb->m_BoundaryBox.m_Pos.x,cx-rayon);
m_Pcb->m_BoundaryBox.m_Pos.y = min(m_Pcb->m_BoundaryBox.m_Pos.y,cy-rayon);
xmax = max(xmax,cx+rayon);
ymax = max(ymax,cy+rayon);
}
else
{
cx = min(ptr->m_Start.x, ptr->m_End.x );
cy = min(ptr->m_Start.y, ptr->m_End.y);
m_Pcb->m_BoundaryBox.m_Pos.x = min(m_Pcb->m_BoundaryBox.m_Pos.x,cx - d);
m_Pcb->m_BoundaryBox.m_Pos.y = min(m_Pcb->m_BoundaryBox.m_Pos.y,cy - d);
cx = max(ptr->m_Start.x, ptr->m_End.x );
cy = max(ptr->m_Start.y, ptr->m_End.y);
xmax = max(xmax,cx + d);
ymax = max(ymax,cy + d);
}
}
m_Pcb->m_BoundaryBox.SetWidth(xmax - m_Pcb->m_BoundaryBox.m_Pos.x);
m_Pcb->m_BoundaryBox.SetHeight(ymax - m_Pcb->m_BoundaryBox.m_Pos.y);
return(succes);
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
1149
]
]
] |
1c7da2627a675d0ff1bfd169a33195dc73597a25 | 3d20de626d6bd35ecabe770bff36857824ed21ce | /Pacman/Highscore.h | ad94f56700b67ceccacdcfb94adf0bc6c364cca5 | [] | no_license | Flydiverny/Pacman | 4fb688869f0bf1267b05bbe3e0223d6323f5ffde | d9fbc6820a41d46adf40efea87a0162d892f9a4c | refs/heads/master | 2021-03-12T21:28:25.169355 | 2011-05-23T15:49:30 | 2011-05-23T15:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | h | #pragma once
#include "Player.h"
#include <deque>
namespace nadilus {
namespace pacman {
class Highscore {
public:
Highscore(void) {}
Highscore(std::string filename);
~Highscore(void);
std::deque<Player> getList(void);
int addPlayer(Player);
void readHighscore();
void saveHighscore();
private:
std::deque<Player> list;
std::string filename;
};
}
}
| [
"[email protected]"
] | [
[
[
1,
23
]
]
] |
4091b1813e696d234370d3df3ead289cd85540f2 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/ScdTrends.cpp | 97bf4614f8019000ce987dbbf800b49a5ece0186 | [] | 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 | 626 | cpp | // ScdTrends.cpp : Implementation of CScdTrends
#include "stdafx.h"
#include "SysCAD_i.h"
#include "ScdTrends.h"
/////////////////////////////////////////////////////////////////////////////
// CScdTrends
STDMETHODIMP CScdTrends::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdTrends
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
void CScdTrends::FireTheEvent(long Evt, long Data)
{
switch (Evt)
{
case ComCmd_NULL : /*Fire_On...*/ ; break;
};
};
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
3d0b26b2d8cd83675700818c5ceb480f1f15f26c | a9cf0c2a8904e42a206c3575b244f8b0850dd7af | /forms/ReturnForm.cpp | 39fd4d12b462cadf6a266ca87988c1fffce724d9 | [] | no_license | jayrulez/ourlib | 3a38751ccb6a38785d4df6f508daeff35ccfd09f | e4727d638f2d69ea29114dc82b9687ea1fd17a2d | refs/heads/master | 2020-04-22T15:42:00.891099 | 2010-01-06T20:00:17 | 2010-01-06T20:00:17 | 40,554,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,812 | cpp | /*
@Group: BSC2D
@Group Members:
<ul>
<li>Robert Campbell: 0701334</li>
<li>Audley Gordon: 0802218</li>
<li>Dale McFarlane: 0801042</li>
<li>Dyonne Duberry: 0802189</li>
<li>Xavier Lowe: 0802488</li>
</ul>
@
*/
#include"ReturnForm.h"
#include <iostream>
#include <string>
#ifndef DATABASE_FILE
#define DATABASE_FILE "database.sqlite"
#endif
#include "../sqlite3.h"
#include "../Glob_Defs.h"
#include "../RJM_SQLite_Resultset.h"
using namespace std;
ReturnForm::ReturnForm()
{
this->loanPtr = new Loan();
FieldPosition=0;
InputPtr=&input;
ReturnCoord[0][0]=25;
ReturnCoord[0][1]=13;
ReturnCoord[0][2]=18;
ReturnCoord[1][0]=25;
ReturnCoord[1][1]=16;
ReturnCoord[1][2]=11;
ReturnCoord[2][0]=25;
ReturnCoord[2][1]=19;
ReturnCoord[2][2]=6;
}
ReturnForm::~ReturnForm()
{
}
void ReturnForm::browseForm()
{
//char* tempId;
bool read=false;
int KeyType;
consoleObj.xyCoord(ReturnCoord[FieldPosition][0]+ReturnCoord[FieldPosition][2]+
AllInput[FieldPosition].length(),ReturnCoord[FieldPosition][1]);
while(!read)
{
switch(FieldPosition)
{
case 0:
*InputPtr = this->loanPtr->getReferenceNumber();
KeyType=FormInputBuilderObj.FormInput(ALPHANUMERIC,NOSPACING,InputPtr,6,ReturnCoord,FieldPosition,false);
this->loanPtr->setReferenceNumber(*InputPtr);
AllInput[FieldPosition] = *InputPtr;
break;
case 1:
*InputPtr = this->loanPtr->getMemberId();
KeyType=FormInputBuilderObj.FormInput(NUMERIC,NOSPACING,InputPtr,7,ReturnCoord,FieldPosition,false);
this->loanPtr->setMemberId(*InputPtr);
AllInput[FieldPosition] = *InputPtr;
break;
case 2:
*InputPtr = this->loanPtr->getRequestDate();
KeyType=FormInputBuilderObj.FormInput(DATE,SPACING,InputPtr,8,ReturnCoord,FieldPosition,false);
this->loanPtr->setRequestDate(*InputPtr);
AllInput[FieldPosition] = *InputPtr;
break;
}
switch(KeyType)
{
case VK_UP:
if(FieldPosition<=0)
{
FieldPosition=0;
break;
}else{
FieldPosition-=1;
}
break;
case VK_RETURN:
FieldPosition+=1;
break;
case VK_TAB:
FieldPosition+=1;
break;
case VK_DOWN:
FieldPosition+=1;
break;
}
if(FieldPosition>2)
{
FieldPosition = 2;
read=true;
}
consoleObj.xyCoord(ReturnCoord[FieldPosition][0]+
ReturnCoord[FieldPosition][2]+AllInput[FieldPosition].length(),
ReturnCoord[FieldPosition][1]);
}
consoleObj.setCursor(false,3);
}
void ReturnForm::show()
{
consoleObj.xyCoord(ReturnCoord[0][0],ReturnCoord[0][1]);
cout<<"Reference Number: ";
consoleObj.xyCoord(ReturnCoord[1][0],ReturnCoord[1][1]);
cout<<"Id Number: ";
consoleObj.xyCoord(ReturnCoord[2][0]-12,ReturnCoord[2][1]);
cout<<"<dd/mm/yy>";
consoleObj.xyCoord(ReturnCoord[2][0],ReturnCoord[2][1]);
cout<<"Date: ";
}
void ReturnForm::save()
{
string l_filename = DATABASE_FILE;
ostringstream message;
message.str("");
ostringstream l_query;
sqlite3* l_sql_db = NULL;
int rc = sqlite3_open(l_filename.c_str(), &l_sql_db);
if( rc ){
sqlite3_close(l_sql_db);
this->setState(STATE_FAILURE);
this->setError("Error couldn't open SQLite database");
};
RJM_SQLite_Resultset *pRS = NULL;
l_query.str("");
l_query << "SELECT * FROM loan WHERE referencenumber='" << this->loanPtr->getReferenceNumber() << "' AND memberid='" <<this->loanPtr->getMemberId() <<"';";
pRS = SQL_Execute(l_query.str().c_str(), l_sql_db);
if (!pRS->Valid()) {
this->setState(STATE_FAILURE);
message << "Invalid result set returned " << pRS->GetLastError();
this->setError(message.str());
SAFE_DELETE(pRS);
sqlite3_close(l_sql_db);
}else{
rc = pRS->GetRowCount();
SAFE_DELETE(pRS);
if(rc<1)
{
this->setState(STATE_FAILURE);
this->setError("No loan record exists with the details specified.");
}else{
l_query.str("");
l_query << "DELETE FROM loan WHERE referencenumber='" << this->loanPtr->getReferenceNumber() << "' AND memberid='" <<this->loanPtr->getMemberId() <<"';";
pRS = SQL_Execute(l_query.str().c_str(), l_sql_db);
if (!pRS->Valid()) {
this->setState(STATE_FAILURE);
message << "Invalid result set returned " << pRS->GetLastError();
this->setError(message.str());
SAFE_DELETE(pRS);
sqlite3_close(l_sql_db);
}else{
//SAFE_DELETE(pRS);
//rc = pRS->getRowCount();
if(pRS==NULL)
{
this->setState(STATE_FAILURE);
message << "Error trying to complete the RETURN LOAN operation.";
this->setError(message.str());
}else{
this->setState(STATE_SUCCESS);
SAFE_DELETE(pRS);
}
sqlite3_close(l_sql_db);
}
}
}
}
bool ReturnForm::validate()
{
int formSize=3;
int NullCue[3];
bool incomplete=false;
for(int pos=0;pos<formSize;pos++)
{
if(AllInput[pos].empty())
NullCue[pos]=1;
else
NullCue[pos]=0;
if(NullCue[pos]==1)
{
if(pos==2)
{
consoleObj.xyCoord(ReturnCoord[pos][0]-23,ReturnCoord[pos][1]);
}
else
consoleObj.xyCoord(ReturnCoord[pos][0]-15,ReturnCoord[pos][1]);
consoleObj.setColour(12);
cout<<"<Required>";
consoleObj.setColour(15);
incomplete=true;
}
}
return incomplete;
} | [
"[email protected]",
"portmore.leader@2838b242-c2a8-11de-a0e9-83d03c287164"
] | [
[
[
1,
120
],
[
122,
185
]
],
[
[
121,
121
],
[
186,
212
]
]
] |
07048291eb0bdc422a80d5a61d29573662451154 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/SpellHandlers/ShamanSpells.cpp | 3361fef523aa8aafaf75a65bf43258f95cdd6367 | [] | 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 | 3,534 | cpp | /****************************************************************************
*
* SpellHandler Plugin
* Copyright (c) 2007 Team Ascent
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0
* License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons,
* 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU
* ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
* ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
*/
#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Spell Defs */
/************************************************************************/
bool RockbiterWeapon(uint32 i, Spell* pSpell)
{
uint32 enchantment_entry = 0;
switch(pSpell->GetProto()->RankNumber)
{
case 1:
enchantment_entry = 3021;
break;
case 2:
enchantment_entry = 3024;
break;
case 3:
enchantment_entry = 3027;
break;
case 4:
enchantment_entry = 3030;
break;
case 5:
enchantment_entry = 3033;
break;
case 6:
enchantment_entry = 3036;
break;
case 7:
enchantment_entry = 3039;
break;
case 8:
enchantment_entry = 3042;
break;
case 9:
enchantment_entry = 3018;
break;
}
if(!enchantment_entry || !pSpell->p_caster)
return true;
Item * item = NULL;
if(rand()%2 == 0) // Don't know which weapon to enchant, so use random
item = pSpell->p_caster->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_OFFHAND);
if(!item)
item = pSpell->p_caster->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
EnchantEntry * enchant = dbcEnchant.LookupEntry(enchantment_entry);
if(!item || !enchant)
return true;
int32 Slot = item->HasEnchantment(enchant->Id);
if(Slot >= 0)
item->ModifyEnchantmentTime(Slot, 1800);
else
{
//check if enchantment slot 1 is taken. If there was no enchantment there function will quit
item->RemoveEnchantment(1);
//this will also apply bonuses for us
Slot = item->AddEnchantment(enchant, 1800, false, true, false, 1); // 5min
if(Slot < 0) return true;
}
sLog.outDebug("ShamanSpells.cpp :: Rockbiter Weapon Rank %u, enchant %u, slot %u", pSpell->GetProto()->RankNumber,
enchantment_entry, Slot);
return true;
}
void SetupShamanSpells(ScriptMgr * mgr)
{
mgr->register_dummy_spell(8017, &RockbiterWeapon); // rank 1
mgr->register_dummy_spell(8018, &RockbiterWeapon); // rank 2
mgr->register_dummy_spell(8019, &RockbiterWeapon); // rank 3
mgr->register_dummy_spell(10399, &RockbiterWeapon);// rank 4
mgr->register_dummy_spell(16314, &RockbiterWeapon);// rank 5
mgr->register_dummy_spell(16315, &RockbiterWeapon);// rank 6
mgr->register_dummy_spell(16316, &RockbiterWeapon);// rank 7
mgr->register_dummy_spell(25479, &RockbiterWeapon);// rank 8
mgr->register_dummy_spell(25485, &RockbiterWeapon);// rank 9
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
27
],
[
29,
60
],
[
66,
82
],
[
84,
100
]
],
[
[
28,
28
],
[
61,
65
],
[
83,
83
]
]
] |
2ea1c4898ebdc14f55649b07fb83499d4aaf965b | 5fea042a436493f474afaf862ea592fa37c506ab | /Antihack/directx.cpp | 24c51c5d386121dd344aa909bc065f2b21ff1519 | [] | no_license | Danteoriginal/twilight-antihack | 9fde8fbd2f34954752dc2de3927490d657b43739 | 4ccc51c13c33abcb5e370ef1b992436e6a1533c9 | refs/heads/master | 2021-01-13T06:25:31.618338 | 2009-10-25T14:44:34 | 2009-10-25T14:44:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,083 | cpp | #include "directx.h"
CD3DManager::CD3DManager()
{
pDevice = 0;
m_font = 0;
screenWidth = 0;
screenHeight = 0;
printFlags = PF_MESSAGES | PF_CVARS;
AddCvar<int>("FPS", &fps);
AddCvar<int>("Resolution X", &screenWidth);
AddCvar<int>("Resolution Y", &screenHeight);
AddCvar<bool>("Fullscreen", &bFullscreen);
}
CD3DManager::~CD3DManager()
{
std::list<CCvarBase*>::iterator i;
for (i = cvars.begin(); i != cvars.end(); ++i) {
delete (*i);
}
}
void CD3DManager::SetDevice(IDirect3DDevice8* device)
{
pDevice = device;
ReloadFont();
}
int CD3DManager::Update()
{
if (!pDevice) return 0;
ThreadRequestResources();
// ---------------------------------------
// Recalculate FPS
// ---------------------------------------
fps = CalculateFPS();
// ---------------------------------------
// Handle messages
// ---------------------------------------
{
std::list<CMessage> expiredMessages;
std::list<CMessage>::iterator i;
// Draw Current Messages
int yMod = 5;
for (i = messages.begin(); i != messages.end(); ++i) {
if ((*i).HasExpired()) { // Will update the message's alpha value etc asd well
expiredMessages.push_back(*i);
}
TextOut(10, yMod, (*i).msg, (*i).color);
yMod += 20;
}
// kill dead messages
for (i = expiredMessages.begin(); i != expiredMessages.end(); ++i) {
messages.remove(*i);
}
}
// ---------------------------------------
// Handle cvars
// ---------------------------------------
if (printFlags & PF_CVARS) {
std::list<CCvarBase*>::iterator i;
int yMod = screenHeight - cvars.size()*20;
for (i = cvars.begin(); i != cvars.end(); ++i) {
TextOut(10, yMod, (*i)->ToString(), D3DCOLOR_XRGB(240, 150, 50));
yMod += 20;
}
}
ThreadReleaseResources();
return 1;
}
int CD3DManager::OnLostDevice()
{
// call OnLostDevice for all created resources like sprites / fonts
m_font->OnLostDevice();
return 1;
}
int CD3DManager::OnResetDevice()
{
// call OnResetDevice for all created resources like sprites / fonts
m_font->OnResetDevice();
return 1;
}
int CD3DManager::ReloadFont()
{
if (!pDevice) return 0;
if (m_font) {
m_font->Release();
m_font = 0;
}
HFONT m_hfont = CreateFont(18, //height
0, //width
0, //escapment
0, //orientation
FW_NORMAL, //weight dontcare maybe bold etc.
false, //itallic
false, //underline
false, //strikeout
DEFAULT_CHARSET, //charset
OUT_DEFAULT_PRECIS, //output precision
CLIP_DEFAULT_PRECIS, // clip precision
ANTIALIASED_QUALITY, //quality
DEFAULT_PITCH | FF_DONTCARE, //pitch
TEXT("MS Sans Serif"));
D3DXCreateFont(pDevice, m_hfont, &m_font );
DeleteObject(m_hfont);
return 1;
}
int CD3DManager::TakeScreenshot(std::string file_name)
{
// http://www.gamedev.net/reference/articles/article1844.asp
if (!pDevice) return 0;
IDirect3DSurface8* frontbuf;
pDevice->CreateImageSurface(screenWidth, screenHeight, D3DFMT_A8R8G8B8, &frontbuf);
HRESULT hr = pDevice->GetFrontBuffer(frontbuf);
if(hr != D3D_OK)
{
frontbuf->Release();
return 0;
}
D3DXSaveSurfaceToFileA(file_name.c_str(), D3DXIFF_BMP, frontbuf, NULL, NULL);
frontbuf->Release();
return 1;
}
int CD3DManager::PrintMessage(std::string msg, int duration, DWORD color)
{
if (!(printFlags & PF_MESSAGES)) return 0;
srand(GetTickCount());
CMessage message(msg, duration, color);
messages.push_back(message);
return 1;
}
int CD3DManager::TextOut(int x, int y, std::string text, DWORD color)
{
if (!pDevice || !m_font) return 0;
RECT rect_Text = {x, y, x + text.length()*15, y + 25};
pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
pDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
pDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
m_font->DrawTextA(text.c_str(), -1, &rect_Text, 0, color ); //DT_CENTER was 0
return 1;
}
int CD3DManager::PutPixel(int x, int y, D3DCOLOR color)
{
if (!pDevice) return 0;
D3DRECT rect_Clear = {x, y, x+1, y+1};
pDevice->Clear(1, &rect_Clear, D3DCLEAR_TARGET, color, 1.0f, 0);
return 1;
}
int CD3DManager::CalculateFPS()
{
static int oldTime = GetTickCount();
static int frames = 0;
static int result = 0;
++frames;
int dT = GetTickCount() - oldTime;
if (dT >= 200) {
oldTime = GetTickCount();
result = static_cast<int>((double)frames / ((double)dT/1000));
frames = 0;
}
return result;
}
int CD3DManager::SetScreenDimensions(int x, int y, bool fullscreen)
{
screenWidth = x;
screenHeight = y;
bFullscreen = fullscreen;
return 1;
}
int CD3DManager::GetScreenDimension(int* x, int* y, bool* fullscreen)
{
if (x) *x = screenWidth;
if (y) *y = screenHeight;
if (fullscreen) *fullscreen = bFullscreen;
return 1;
}
int CD3DManager::Fullscreen()
{
return static_cast<int>(bFullscreen);
}
int CD3DManager::TogglePrintFlags(int flags)
{
printFlags ^= flags;
return 1;
} | [
"[email protected]"
] | [
[
[
1,
243
]
]
] |
3491aff99bd320c1187a655be65d2f1e8bc208d3 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/ResampleInterpolators/BSplineResampleInterpolatorFloat/elxBSplineResampleInterpolatorFloat.hxx | ded3feea63397c4a7cc49d523f2780a0ba217d26 | [] | 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 | 2,682 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxBSplineResampleInterpolatorFloat_hxx
#define __elxBSplineResampleInterpolatorFloat_hxx
#include "elxBSplineResampleInterpolatorFloat.h"
namespace elastix
{
using namespace itk;
/*
* ******************* BeforeRegistration ***********************
*/
template <class TElastix>
void
BSplineResampleInterpolatorFloat<TElastix>
::BeforeRegistration( void )
{
/** BSplineResampleInterpolator specific.*/
/** Set the SplineOrder, default = 3. */
unsigned int splineOrder = 3;
/** Read the desired splineOrder from the parameterFile. */
this->m_Configuration->ReadParameter( splineOrder,
"FinalBSplineInterpolationOrder", 0 );
/** Set the splineOrder in the superclass. */
this->SetSplineOrder( splineOrder );
} // end BeforeRegistration()
/*
* ******************* ReadFromFile ****************************
*/
template <class TElastix>
void
BSplineResampleInterpolatorFloat<TElastix>
::ReadFromFile( void )
{
/** Call ReadFromFile of the ResamplerBase. */
this->Superclass2::ReadFromFile();
/** BSplineResampleInterpolator specific. */
/** Set the SplineOrder, default = 3. */
unsigned int splineOrder = 3;
/** Read the desired splineOrder from the parameterFile. */
this->m_Configuration->ReadParameter( splineOrder,
"FinalBSplineInterpolationOrder", 0 );
/** Set the splineOrder in the superclass. */
this->SetSplineOrder( splineOrder );
} // end ReadFromFile()
/**
* ******************* WriteToFile ******************************
*/
template <class TElastix>
void
BSplineResampleInterpolatorFloat<TElastix>
::WriteToFile( void ) const
{
/** Call WriteTiFile of the ResamplerBase. */
this->Superclass2::WriteToFile();
/** The BSplineResampleInterpolator adds: */
/** Write the FinalBSplineInterpolationOrder. */
xout["transpar"] << "(FinalBSplineInterpolationOrder " <<
this->GetSplineOrder() << ")" << std::endl;
} // end WriteToFile()
} // end namespace elastix
#endif // end #ifndef __elxBSplineResampleInterpolatorFloat_hxx
| [
"[email protected]"
] | [
[
[
1,
99
]
]
] |
d1f6f1a62a23cb34255a48525ef8e03d9f8c534b | b22c254d7670522ec2caa61c998f8741b1da9388 | /Tools/infoextractor/lba_map_gl.h | cac7e397efe2d6e8542ad6fc5d52caf763dce84c | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | ISO-8859-15 | C++ | false | false | 18,236 | h |
#ifndef LBA_MAP_GL_H
#define LBA_MAP_GL_H
#include "globals.h"
using namespace std;
class LBA_ENTRY
{
public :
int datalenght;
vector<unsigned char> data;
//ENTRY();
LBA_ENTRY(VIRTUAL_FILE_READ_ONLY &pack,int entry)
{
int i;
long file_offset;
long compressed_size;
int compression_type;
int pack_offset=0;
pack.rewind_virtual();
pack_offset=entry*4;
pack.move_cursor(pack_offset);
pack_offset=(long)(pack.read_char()+pack.read_char()*256.+pack.read_char()*65536.+pack.read_char()*16777216.);
pack.move_cursor(pack_offset);
// datalenght=(long)(+pack.read_char()*256.+pack.read_char()*65536.+pack.read_char()*16777216.);
// pack_offset
// pack.rewind_virtual();
datalenght=(long)(pack.read_char()+pack.read_char()*256.+pack.read_char()*65536.+pack.read_char()*16777216.);
compressed_size=(long)(pack.read_char()+pack.read_char()*256.+pack.read_char()*65536.+pack.read_char()*16777216.);
compression_type=(long)(pack.read_char()+pack.read_char()*256.);
data.reserve(datalenght);
if(compression_type>0)
{
int e;
int e2;
unsigned char b,d,f,g;
unsigned char c1,c2;
int data_offset=0;
do
{
b=pack.read_char();
for(d=0;d<8;d++)
{
if((b & (1<<d))!=0)
{
data.push_back(pack.read_char());
data_offset++;
}
else
{
c1=pack.read_char();
c2=pack.read_char();
e=(c1*256+c2)%0x10000;
f=(((e>>8)&0x000f)+compression_type+1)%0x10000;
e2=(((e<<4)&0x0ff0)+((e>>12)&0x000f))%0x10000;
for(g=0;g<f;g++)
{
data.push_back(data[data_offset+1-e2-2]);
data_offset++;
}
}
if(data_offset>=datalenght)break;
}
}
while(data_offset<datalenght);
}
else
{
for(i=0;i<datalenght;i++)
data.push_back(pack.read_char());
}
pack.rewind_virtual();
}
};
class LBA_PALET
{
public :
unsigned char couleur[256][3];
LBA_PALET(VIRTUAL_FILE_READ_ONLY &pack)
{
int i;
int offset_data=0;
LBA_ENTRY *entry=new LBA_ENTRY(pack,0);
for(i=0;i<256;i++)
{
couleur[i][0]=entry->data[offset_data++]; //rouge
couleur[i][1]=entry->data[offset_data++]; //vert
couleur[i][2]=entry->data[offset_data++]; //bleu
}
delete entry;
}
};
class LBA_BRICK
{
public:
int lenght;
int height;
unsigned char pixel[38][48];
LBA_BRICK(VIRTUAL_FILE_READ_ONLY &pack,int n)
{
int data_offset=0;
int i,j,k;
unsigned char c;
int offset;
LBA_ENTRY entry(pack,n);
lenght=48;
height=38;
unsigned char brick_width=entry.data[data_offset++];
unsigned char brick_height=entry.data[data_offset++];
unsigned char brick_offsetx=entry.data[data_offset++];
unsigned char brick_offsety=entry.data[data_offset++];
unsigned char brick_nombre_subline;
unsigned char brick_type_subline;
unsigned char brick_lenght_subline;
for(i=0;i<38;i++)
for(j=0;j<48;j++)
{
pixel[i][j]=0;
}
for(i=0;i<brick_height;i++)
{
c=entry.data[data_offset++];
brick_nombre_subline=c;
offset=0;
for(j=0;j<brick_nombre_subline;j++)
{
c=entry.data[data_offset++];
brick_type_subline=c/64;
brick_lenght_subline=c*4;
brick_lenght_subline/=4;
brick_lenght_subline=brick_lenght_subline+1;
if(brick_type_subline==0)
{
offset+=brick_lenght_subline;
}
if(brick_type_subline==1)
{
for(k=0;k<brick_lenght_subline;k++)
{
c=entry.data[data_offset++];
pixel[i+brick_offsety][brick_offsetx+offset]=c;
offset++;
}
}
if(brick_type_subline==3)
{
for(k=0;k<brick_lenght_subline;k++)
{
c=entry.data[data_offset++];
pixel[i+brick_offsety][brick_offsetx+offset]=c;
offset++;
}
}
if(brick_type_subline==2)
{
c=entry.data[data_offset++];
for(k=0;k<brick_lenght_subline;k++)
{
pixel[i+brick_offsety][brick_offsetx+offset]=c;
offset++;
}
}
}
}
//duplicate borders:
for(int px=0;px<22;px++)
{
pixel[10-px/2][px]=pixel[11-px/2][px],
pixel[27+px/2][px]=pixel[26+px/2][px];
}
for(int px=26;px<48;px++)
{
pixel[0+(px-26)/2][px]=pixel[1+(px-26)/2][px],
pixel[37-(px-26)/2][px]=pixel[36-(px-26)/2][px];
}
/* pixel[0][20]=pixel[1][20];*/
}
};
struct LBA_INFO_BRICK{
int index_brick;
int new_index_brick;
unsigned char shape;
unsigned char material;
unsigned int object;
};
class LBA_OBJECT
{
public:
unsigned char taille_X,taille_Y,taille_Z;
vector <LBA_INFO_BRICK> info_brick;
LBA_OBJECT(int X,int Y,int Z)
{
taille_X=X;
taille_Y=Y;
taille_Z=Z;
info_brick.reserve(X*Y*Z);
}
};
class LBA_LAYOUT
{
public:
int number_objects;
vector<LBA_OBJECT> object;
LBA_LAYOUT(VIRTUAL_FILE_READ_ONLY &pack,int n)
{
int i,j;
int index_data=0;
LBA_ENTRY *entry=new LBA_ENTRY(pack,n);
number_objects=(entry->data[0]+entry->data[1]*256.+entry->data[2]*65536.+entry->data[3]*16777216.)/4;
object.reserve(number_objects);
for(i=0;i<number_objects;i++)//
{
index_data=(entry->data[i*4]+entry->data[i*4+1]*256.+entry->data[i*4+2]*65536.+entry->data[i*4+3]*16777216.);
LBA_OBJECT obj(entry->data[index_data++],entry->data[index_data++],entry->data[index_data++]);
for(j=0;j<obj.taille_X*obj.taille_Y*obj.taille_Z;j++)
{
LBA_INFO_BRICK info;
info.object=i;
info.shape=entry->data[index_data++];
info.material=entry->data[index_data++];
info.index_brick=entry->data[index_data]+(entry->data[index_data+1])*256-1;
obj.info_brick.push_back(info);
index_data+=2;
}
object.push_back(obj);
}
delete entry;
}
};
class LBA_GRID
{
public:
LBA_INFO_BRICK ***info_brick;
LBA_LAYOUT *layout;
LBA_INFO_BRICK *** GetBricks()
{ return info_brick; }
LBA_GRID(VIRTUAL_FILE_READ_ONLY &pack_grid,VIRTUAL_FILE_READ_ONLY &pack_layout,int n,int LBA2)
{
int i,j,k,l;
int index_data=0;
unsigned char flag,number_sub_colomn;
int height_subcolumn,offset_column;
LBA_ENTRY *entry=new LBA_ENTRY(pack_grid,n);
if(LBA2)n=entry->data[0]+180-1;
layout=new LBA_LAYOUT(pack_layout,n);
/*
for(i=0;i<64;i++)
for(j=0;j<64;j++)
{*/
info_brick=new LBA_INFO_BRICK **[64];
for(i=0;i<64;i++)
info_brick[i]=new LBA_INFO_BRICK *[64];
for(i=0;i<64;i++)
for(j=0;j<64;j++)
info_brick[i][j]=new LBA_INFO_BRICK [25];
for(i=0;i<64;i++)
for(j=0;j<64;j++)
for(k=0;k<25;k++)
{
info_brick[i][j][k].index_brick=-1;
info_brick[i][j][k].material=0xF0;
info_brick[i][j][k].shape=0;
}
// }
for(j=0;j<64;j++)
for(i=0;i<64;i++)
{
if(LBA2)index_data=entry->data[2*(j*64+i)+34]+entry->data[2*(j*64+i)+1+34]*256+34;///////////////LBA2 +34 +34 +34
else index_data=entry->data[2*(j*64+i)]+entry->data[2*(j*64+i)+1]*256;
number_sub_colomn=entry->data[index_data++];
offset_column=0;
for(k=0;k<number_sub_colomn;k++)
{
flag=entry->data[index_data]>>6;
height_subcolumn=entry->data[index_data]%0x20+1;
index_data++;
if(flag==0)
{
offset_column+=height_subcolumn;
}
if(flag==1)
{
for(l=0;l<height_subcolumn;l++)
{
if(entry->data[index_data]==0)
{
info_brick[i][j][offset_column].index_brick=-1;
info_brick[i][j][offset_column].material=0xF0;
info_brick[i][j][offset_column].shape=0;
}
else
{
info_brick[i][j][offset_column]=layout->object[entry->data[index_data]-1].info_brick[entry->data[index_data+1]];
}
offset_column++;
index_data+=2;
}
}
if(flag==2)
{
for(l=0;l<height_subcolumn;l++)
{
if(entry->data[index_data]==0)
{
info_brick[i][j][offset_column].index_brick=-1;
info_brick[i][j][offset_column].material=0xF0;
info_brick[i][j][offset_column].shape=0;
}
else
{
info_brick[i][j][offset_column]=layout->object[entry->data[index_data]-1].info_brick[entry->data[index_data+1]];
}
offset_column++;
}
index_data+=2;
}
}
}
delete entry;
}
~LBA_GRID()
{
int i,j,k;
for(i=0;i<64;i++)
for(j=0;j<64;j++)
delete info_brick[i][j];
for(i=0;i<64;i++)
delete [] info_brick[i];
delete [] info_brick;
delete layout;
}
};
class LBA_MAP
{
public:
LBA_PALET *palet;
LBA_GRID *grid;
//vector<LBA_BRICK> brick;
int number_brick;
int brick_list[10000];
LBA_MAP(int n,int LBA2)
{
int i,j,k,l;
number_brick=0;
VIRTUAL_FILE_READ_ONLY *pack_brick;
VIRTUAL_FILE_READ_ONLY *pack_grid;
VIRTUAL_FILE_READ_ONLY *pack_ress;
VIRTUAL_FILE_READ_ONLY *pack_layout;
if(LBA2){
pack_brick=new VIRTUAL_FILE_READ_ONLY("data//map//lba2//LBA_BKG.HQR");
pack_grid=new VIRTUAL_FILE_READ_ONLY("data//map//lba2//LBA_BKG.HQR");
pack_ress=new VIRTUAL_FILE_READ_ONLY("data//map//lba2//RESS2.HQR");
pack_layout=new VIRTUAL_FILE_READ_ONLY("data//map//lba2//LBA_BKG.HQR");
}
else{
pack_brick=new VIRTUAL_FILE_READ_ONLY("data//map//lba1//LBA_BRK.HQR");
pack_grid=new VIRTUAL_FILE_READ_ONLY("data//map//lba1//LBA_GRI.HQR");
pack_ress=new VIRTUAL_FILE_READ_ONLY("data//map//lba1//RESS.HQR");
pack_layout=new VIRTUAL_FILE_READ_ONLY("data//map//lba1//LBA_BLL.HQR");
}
palet=new LBA_PALET(*pack_ress);
grid=new LBA_GRID(*pack_grid,*pack_layout,n,LBA2);
printf(">%d ",number_brick);
for(i=0;i<64;i++)
for(j=0;j<64;j++)
for(k=0;k<25;k++)
{
if(grid->info_brick[i][j][k].index_brick != 0)
{
if(!LBA2)
{
int idx = grid->info_brick[i][j][k].index_brick;
int mat = (grid->info_brick[i][j][k].material >> 4);
int mat2 = grid->info_brick[i][j][k].material & unsigned char(15);
if(mat == 15 && mat2 == 1)
grid->info_brick[i][j][k].shape = 15;
if(idx == 222)
{
if(grid->info_brick[i][j][k].shape == 2)
grid->info_brick[i][j][k].index_brick = 8715;
if(grid->info_brick[i][j][k].shape == 3)
grid->info_brick[i][j][k].index_brick = 8716;
if(grid->info_brick[i][j][k].shape == 4)
grid->info_brick[i][j][k].index_brick = 8717;
if(grid->info_brick[i][j][k].shape == 5)
grid->info_brick[i][j][k].index_brick = 8718;
if(grid->info_brick[i][j][k].shape == 10)
grid->info_brick[i][j][k].index_brick = 8719;
if(grid->info_brick[i][j][k].shape == 12)
grid->info_brick[i][j][k].index_brick = 8720;
if(grid->info_brick[i][j][k].shape == 13)
grid->info_brick[i][j][k].index_brick = 8721;
}
if(idx == 750 || idx == 752 || idx == 760 || idx == 762 ||
idx == 784 || idx == 786 || idx == 2065 || idx == 4219 ||
idx == 4232 || idx == 4233 || idx == 4237 || idx == 4249)
grid->info_brick[i][j][k].shape = 1;
}
else
{
int mat = (grid->info_brick[i][j][k].material >> 4);
if(mat == 1 || mat == 9 || mat == 11 || mat == 13 || mat == 14 || mat == 15)
grid->info_brick[i][j][k].shape = 15;
if(grid->info_brick[i][j][k].index_brick == 126)
{
if(grid->info_brick[i][j][k].shape == 2)
grid->info_brick[i][j][k].index_brick = 8715;
if(grid->info_brick[i][j][k].shape == 3)
grid->info_brick[i][j][k].index_brick = 8716;
if(grid->info_brick[i][j][k].shape == 4)
grid->info_brick[i][j][k].index_brick = 8717;
if(grid->info_brick[i][j][k].shape == 5)
grid->info_brick[i][j][k].index_brick = 8718;
if(grid->info_brick[i][j][k].shape == 10)
grid->info_brick[i][j][k].index_brick = 8719;
if(grid->info_brick[i][j][k].shape == 12)
grid->info_brick[i][j][k].index_brick = 8720;
if(grid->info_brick[i][j][k].shape == 13)
grid->info_brick[i][j][k].index_brick = 8721;
}
else
grid->info_brick[i][j][k].index_brick = grid->info_brick[i][j][k].index_brick + 8722;
}
}
}
for(i=0;i<64;i++)
for(j=0;j<64;j++)
for(k=0;k<25;k++)
{
if(grid->info_brick[i][j][k].index_brick!=-1)
{
for(l=0;l<number_brick;l++)
if(brick_list[l]==grid->info_brick[i][j][k].index_brick)
break;
if(l==number_brick)
{
brick_list[l]=grid->info_brick[i][j][k].index_brick;
number_brick++;
}
}
}
{
std::stringstream filename;
if(LBA2)
filename << "Lba2/";
else
filename << "Lba1/";
filename << "map" << n << ".txt";
std::ofstream file(filename.str().c_str());
file<<64<<" "<<25<<" "<<64<<std::endl;
file<<number_brick<<std::endl;
for(int cc=0;cc<number_brick;++cc)
{
file<<brick_list[cc]-1<<std::endl;
}
file<<std::endl<<std::endl;
for(k=0;k<25;k++)
{
for(i=0;i<64;i++)
{
for(j=0;j<64;j++)
{
if(grid->info_brick[i][j][k].index_brick!=0)
{
l=0;
while(grid->info_brick[i][j][k].index_brick!=brick_list[l])
l++;
file<<l+1<<" ";
}
else
file<<"0 ";
}
file<<std::endl;
}
file<<std::endl;
}
}
//changement dŽindices : on passe de 8000 briques à 600-700 briques
//attention brique 0
//for(i=0;i<64;i++)
//for(j=0;j<64;j++)
//for(k=0;k<25;k++)
//{
// if(grid->info_brick[i][j][k].index_brick!=-1)
// {
// l=0;
// while(grid->info_brick[i][j][k].index_brick!=brick_list[l])l++;
// grid->info_brick[i][j][k].new_index_brick=l;
// }
//}
//getchar();
//brick.reserve(number_brick);
//getchar();
//for(i=0;i<number_brick;i++)
//{
//// printf("%d ",brick_list[i]);
//if(LBA2)brick.push_back(LBA_BRICK(*pack_brick,brick_list[i]-1+198-1+1));//////////////LBA2 +198-1
//else brick.push_back(LBA_BRICK(*pack_brick,brick_list[i]-1+1));
//}
delete pack_brick;
delete pack_grid;
delete pack_layout;
delete pack_ress;
}
~LBA_MAP()
{
int i;
delete palet;
delete grid;
/* for(i=0;i<number_brick;i++)
delete brick[i];
delete brick;*/
}
LBA_GRID * GetGrid()
{return grid;}
};
typedef struct LBA_SHARED_BRICK
{
int id;
int dx;
int dz;
};
typedef struct LBA_FACE
{
double v[9];
double vt[6];
double vn[3];
int dx;
int dz;
};
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
649
]
]
] |
6cc8957ff5238a46bf91e5520c8bb029ed2c5c28 | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkInformationKeyVectorKey.h | 853b24820bef1c7c9a322daa335c34993cab7193 | [] | no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,600 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkInformationKeyVectorKey.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
// .NAME vtkInformationKeyVectorKey - Key for vector-of-keys values.
// .SECTION Description
// vtkInformationKeyVectorKey is used to represent keys for
// vector-of-keys values in vtkInformation.
#ifndef __vtkInformationKeyVectorKey_h
#define __vtkInformationKeyVectorKey_h
#include "vtkInformationKey.h"
#include "vtkCommonInformationKeyManager.h" // Manage instances of this type.
class VTK_COMMON_EXPORT vtkInformationKeyVectorKey : public vtkInformationKey
{
public:
vtkTypeRevisionMacro(vtkInformationKeyVectorKey,vtkInformationKey);
void PrintSelf(ostream& os, vtkIndent indent);
vtkInformationKeyVectorKey(const char* name, const char* location);
~vtkInformationKeyVectorKey();
// Description:
// Get/Set the value associated with this key in the given
// information object.
void Append(vtkInformation* info, vtkInformationKey* value);
void AppendUnique(vtkInformation* info, vtkInformationKey* value);
void Set(vtkInformation* info, vtkInformationKey** value, int length);
void RemoveItem(vtkInformation* info, vtkInformationKey* value);
vtkInformationKey** Get(vtkInformation* info);
vtkInformationKey* Get(vtkInformation* info, int idx);
void Get(vtkInformation* info, vtkInformationKey** value);
int Length(vtkInformation* info);
int Has(vtkInformation* info);
// Description:
// Copy the entry associated with this key from one information
// object to another. If there is no entry in the first information
// object for this key, the value is removed from the second.
virtual void ShallowCopy(vtkInformation* from, vtkInformation* to);
// Description:
// Print the key's value in an information object to a stream.
virtual void Print(ostream& os, vtkInformation* info);
private:
vtkInformationKeyVectorKey(const vtkInformationKeyVectorKey&); // Not implemented.
void operator=(const vtkInformationKeyVectorKey&); // Not implemented.
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
] | [
[
[
1,
64
]
]
] |
afe67e0212759f0864233c46af8f089182bea473 | 30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff | /squirrel/source/ctl.cpp | 4dc3ff21808334bb2fe70dd9e1c8584819676aa3 | [] | no_license | inspirer/history | ed158ef5c04cdf95270821663820cf613b5c8de0 | 6df0145cd28477b23748b1b50e4264a67441daae | refs/heads/master | 2021-01-01T17:22:46.101365 | 2011-06-12T00:58:37 | 2011-06-12T00:58:37 | 1,882,931 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,150 | cpp | // CTL functions
int ValAsInt(char *val)
{
unsigned long nt;
nt=strtoul(val,0,0);
if (strcmp(val,"0")!=0&&nt==0) ErrorExit(78,"Invalid integer format");
//if (cfg.debuginfo) cout << "(" << nt << ") ";
return nt;
}
void DefineVar(char *vr,char *val)
{
strlwr(vr);
//if (cfg.debuginfo) cout << "[" << vr << "," << val << "] ";
if (!strcmp(vr,"modem_irq")) cfg.irq=ValAsInt(val)+8;
else if (!strcmp(vr,"ioport")) cfg.ioport=ValAsInt(val);
else if (!strcmp(vr,"baud")) cfg.baud=ValAsInt(val);
else if (!strcmp(vr,"command_delay")) cfg.cmddelay=ValAsInt(val);
else if (!strcmp(vr,"wait_answer")) cfg.waitans=ValAsInt(val);
else if (!strcmp(vr,"dle")) cfg.dle=ValAsInt(val);
else if (!strcmp(vr,"etx")) cfg.etx=ValAsInt(val);
//modem_irq 4 cfg.irq
//ioport 0x3F8 cfg.ioport
//baud 2 cfg.baud
//command_delay 100 cfg.cmddelay
//wait_answer 4 cfg.waitans
//dle 16 cfg.dle
//etx 3 cfg.etx
else if (!strcmp(vr,"ring")) cfg.ring=ValAsInt(val);
else if (!strcmp(vr,"wait_offhook")) cfg.wallo=ValAsInt(val);
else if (!strcmp(vr,"speaker_freq")) cfg.khz=ValAsInt(val);
else if (!strcmp(vr,"sound_flag")) strcpy(cfg.soundfl,val);
else if (!strcmp(vr,"pause_ring")) cfg.delayring=ValAsInt(val);
else if (!strcmp(vr,"ring_to_line")) cfg.RTL=ValAsInt(val);
else if (!strcmp(vr,"rec_message")) cfg.rec_time=ValAsInt(val);
else if (!strcmp(vr,"wave_output")) cfg.wavout=ValAsInt(val);
else if (!strcmp(vr,"wav_8bit")) cfg.wav8bit=ValAsInt(val);
else if (!strcmp(vr,"hook")) cfg.hook=ValAsInt(val);
//ring 1 cfg.ring
//wait_offhook 500 cfg.wallo
//speaker_freq 440 cfg.khz
//cfg_sound_flag "" cfg.soundfl
//pause_ring 3000 cfg.delayring
//ring_to_line 4 cfg.RTL
//rec_message 30 cfg.rec_time
//WAVE_output 0 cfg.wavout
//WAV_8bit 0 cfg.wav8bit
//cfg_offhook 1 cfg.hook
else if (!strcmp(vr,"detect_num")) cfg.limit=ValAsInt(val);
else if (!strcmp(vr,"frame")) cfg.frame=ValAsInt(val);
else if (!strcmp(vr,"log_level")) cfg.loglev=ValAsInt(val);
else if (!strcmp(vr,"play_device")) cfg.pln=ValAsInt(val);
else if (!strcmp(vr,"show_debug_info")) cfg.debuginfo=ValAsInt(val);
else if (!strcmp(vr,"listen")) cfg.hear=ValAsInt(val);
else if (!strcmp(vr,"use_gsm")) cfg.gsmframe=ValAsInt(val);
else if (!strcmp(vr,"real_close")) cfg.realcl=ValAsInt(val);
else if (!strcmp(vr,"auto_detect")) cfg.auto_detect=ValAsInt(val);
else if (!strcmp(vr,"post_space")) cfg.postspace=ValAsInt(val);
//detect_num 30 cfg.limit
//frame 1000 cfg.frames
//log_level 0 cfg.loglev
//play_device 0 cfg.pln
//show_debug_info 0 cfg.debuginfo
//listen 15 cfg.hear
//use_gsm 1 cfg.gsmframe
//gsm_delay 15 ~
//real_close 1 cfg.realcl
//auto_detect 0 cfg.auto_detect
//cfg_post_space 0 cfg.postspace
else if (!strcmp(vr,"use_aon")) cfg.useaon=ValAsInt(val);
else if (!strcmp(vr,"aon_request")) strcpy(cfg.aonreq.st,val);
else if (!strcmp(vr,"aon_delay_bef")) cfg.delay1=ValAsInt(val);
else if (!strcmp(vr,"aon_delay_after")) cfg.delay2=ValAsInt(val);
else if (!strcmp(vr,"aon_signal")) cfg.minver=ValAsInt(val);
else if (!strcmp(vr,"aon_digits")) cfg.digits=ValAsInt(val);
//Use_AON 1
//AON_request "AT#VTS=[500,500,1]"
//AON_delay_bef 1
//AON_delay_after 0
//aon_signal 2000000 cfg.minver
//AON_digits 7 cfg.digits
else if (!strcmp(vr,"voice_dir")) strcpy(cfg.vdir,val);
else if (!strcmp(vr,"file_allo")) strcpy(cfg.sallo,val);
else if (!strcmp(vr,"file_wait")) strcpy(cfg.swait,val);
else if (!strcmp(vr,"file_auto")) strcpy(cfg.sauto,val);
else if (!strcmp(vr,"mailer_ata")) strcpy(cfg.ata,val);
else if (!strcmp(vr,"logfile")) strcpy(cfg.log,val);
//voice_dir "" cfg.vdir
//file_allo "allo.gsm" cfg.sallo
//file_wait "wait.gsm" cfg.swait
//file_auto "auto.gsm" cfg.sauto
//mailer_ata "ata.sq" cfg.ata
//logfile "squirrel.log" cfg.log
else if (!strcmp(vr,"init_st")) strcpy(cfg.init.st,val);
else if (!strcmp(vr,"deinit_st")) strcpy(cfg.deinit.st,val);
else if (!strcmp(vr,"mailinit_st")) strcpy(cfg.mailinit.st,val);
else if (!strcmp(vr,"offhook_st")) strcpy(cfg.offhook.st,val);
else if (!strcmp(vr,"onhook_st")) strcpy(cfg.onhook.st,val);
else if (!strcmp(vr,"voice_st")) strcpy(cfg.voice.st,val);
else if (!strcmp(vr,"data_st")) strcpy(cfg.data.st,val);
else if (!strcmp(vr,"stplay_st")) strcpy(cfg.stplay.st,val);
else if (!strcmp(vr,"strec_st")) strcpy(cfg.strec.st,val);
else if (!strcmp(vr,"beep_st")) strcpy(cfg.beep.st,val);
else if (!strcmp(vr,"aabeep_st")) strcpy(cfg.abeep.st,val);
else if (!strcmp(vr,"sphone_st")) strcpy(cfg.sphone.st,val);
else if (!strcmp(vr,"mphone_st")) strcpy(cfg.mphone.st,val);
//init_st "ATZQ0E0#VTD=3F,3F,3F"
//deinit_st "ATZ"
//mailinit_st "ATM1"
//offhook_st "ATH1"
//onhook_st "ATH0"
//voice_st "AT#CLS=8#VRA=0#VRN=0#BDR=24#VSD=1#VSS=2#VSP=55"
//data_st "AT#CLS=0"
//stplay_st "~!"
//strec_st "~!"
//beep_st "AT#VTS=[425,425,10]"
//aabeep_st "AT#VTS=[200,200,5]"
//sphone_st "AT#VGR=5#VLS=2"
//mphone_st "AT#VGT=3#VLS=3"
else if (!strcmp(vr,"play_st")) strcpy(cfg.play.st,val);
else if (!strcmp(vr,"rec_st")) strcpy(cfg.rec.st,val);
//play_st "AT#VTX"
//rec_st "AT#VRX"
else { cout<< vr <<": ";ErrorExit(73,"Unknown keyword");}
}
void ReadConfig(char *cname)
{
cout << "reading CTL : " << cname << " : ";
FILE *fp;
int line=1;
fp=fopen(cname,"rb");
if (fp!=NULL){
char b[100],rd,st[200],*keyw,*keyv;st[0]=0;
while((rd=fread(b,1,100,fp))!=0){
for (int cn=0;cn<rd;cn++){
if (b[cn]==13||b[cn]==10){
if (b[cn]==13) line++;
if (strchr(st,';')!=NULL) *strchr(st,';')=0;
keyw=st;
while(strlen(keyw)>0&&keyw[0]==' ') keyw++;
if (*keyw!=0){
keyv=strchr(keyw,' ');
if (keyv==NULL&&strlen(keyw)>0){ cout << "line " << line;ErrorExit(51," : cfg error");}
keyv[0]=0;keyv++;
while(strlen(keyv)>0&&keyv[0]==' ') keyv++;
while(strlen(keyv)>0&&keyv[strlen(keyv)-1]==' ') keyv[strlen(keyv)-1]=0;
if (strlen(keyv)==0){ cout << "line " << line;ErrorExit(58," : cfg error");}
DefineVar(keyw,keyv);
}
st[0]=0;
} else {
st[strlen(st)+1]=0;
st[strlen(st)]=b[cn];
}
}
}
fclose(fp);
} else ErrorExit(92,"FATAL: cfg not found");
cout << "OK" << endl;
}
| [
"[email protected]"
] | [
[
[
1,
185
]
]
] |
4a3dc0a397790c86fbe57b0c33cc443a487d3c9b | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/coordinate_system.hpp | 5835009bb8fcbb442c6603fc4d8aae0c65f0eb7d | [] | 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 | 10,800 | 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 coordinate_system.xsd.
*/
#ifndef AOSLCPP_AOSL__COORDINATE_SYSTEM_HPP
#define AOSLCPP_AOSL__COORDINATE_SYSTEM_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/coordinate_system_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
#include "aosl/axis_x_forward.hpp"
#include "aosl/axis_y_forward.hpp"
#include "aosl/axis_z_forward.hpp"
#undef XSD_DONT_INCLUDE_INLINE
#else
#include "aosl/axis_x_forward.hpp"
#include "aosl/axis_y_forward.hpp"
#include "aosl/axis_z_forward.hpp"
#endif // XSD_DONT_INCLUDE_INLINE
/**
* @brief C++ namespace for the %artofsequence.org/aosl/1.0
* schema namespace.
*/
namespace aosl
{
/**
* @brief Class corresponding to the %coordinate_system schema type.
*
* Coordinate system configuration for graphic space.
*
* @nosubgrouping
*/
class Coordinate_system: public ::xml_schema::Type
{
public:
/**
* @name xaxis
*
* @brief Accessor and modifier functions for the %xaxis
* required element.
*
* Configuration of the horizontal x-axis.
*/
//@{
/**
* @brief Element type.
*/
typedef ::aosl::Axis_x XaxisType;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< XaxisType, char > XaxisTraits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const XaxisType&
xaxis () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
XaxisType&
xaxis ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
xaxis (const XaxisType& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
xaxis (::std::auto_ptr< XaxisType > p);
/**
* @brief Detach the element value from the object model.
*
* @return A pointer to the element value.
*
* Note that this function leaves the required element in
* the original object model uninitialized.
*/
::std::auto_ptr< XaxisType >
detach_xaxis ();
//@}
/**
* @name yaxis
*
* @brief Accessor and modifier functions for the %yaxis
* required element.
*
* Configuration of the vertical y-axis.
*/
//@{
/**
* @brief Element type.
*/
typedef ::aosl::Axis_y YaxisType;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< YaxisType, char > YaxisTraits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const YaxisType&
yaxis () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
YaxisType&
yaxis ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
yaxis (const YaxisType& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
yaxis (::std::auto_ptr< YaxisType > p);
/**
* @brief Detach the element value from the object model.
*
* @return A pointer to the element value.
*
* Note that this function leaves the required element in
* the original object model uninitialized.
*/
::std::auto_ptr< YaxisType >
detach_yaxis ();
//@}
/**
* @name zaxis
*
* @brief Accessor and modifier functions for the %zaxis
* required element.
*
* Configuration of the depth z-axis.
*/
//@{
/**
* @brief Element type.
*/
typedef ::aosl::Axis_z ZaxisType;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ZaxisType, char > ZaxisTraits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ZaxisType&
zaxis () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ZaxisType&
zaxis ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
zaxis (const ZaxisType& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
zaxis (::std::auto_ptr< ZaxisType > p);
/**
* @brief Detach the element value from the object model.
*
* @return A pointer to the element value.
*
* Note that this function leaves the required element in
* the original object model uninitialized.
*/
::std::auto_ptr< ZaxisType >
detach_zaxis ();
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
Coordinate_system (const XaxisType&,
const YaxisType&,
const ZaxisType&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (auto_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
Coordinate_system (::std::auto_ptr< XaxisType >&,
::std::auto_ptr< YaxisType >&,
::std::auto_ptr< ZaxisType >&);
/**
* @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.
*/
Coordinate_system (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.
*/
Coordinate_system (const Coordinate_system& 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 Coordinate_system*
_clone (::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~Coordinate_system ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::Flags);
protected:
::xsd::cxx::tree::one< XaxisType > xaxis_;
::xsd::cxx::tree::one< YaxisType > yaxis_;
::xsd::cxx::tree::one< ZaxisType > zaxis_;
//@endcond
};
bool
operator== (const Coordinate_system&, const Coordinate_system&);
bool
operator!= (const Coordinate_system&, const Coordinate_system&);
}
#ifndef XSD_DONT_INCLUDE_INLINE
#include "aosl/axis_x.hpp"
#include "aosl/axis_x.inl"
#include "aosl/axis_y.hpp"
#include "aosl/axis_y.inl"
#include "aosl/axis_z.hpp"
#include "aosl/axis_z.inl"
#endif // XSD_DONT_INCLUDE_INLINE
#include <iosfwd>
namespace aosl
{
::std::ostream&
operator<< (::std::ostream&, const Coordinate_system&);
}
#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 Coordinate_system&);
}
#ifndef XSD_DONT_INCLUDE_INLINE
#include "aosl/coordinate_system.inl"
#endif // XSD_DONT_INCLUDE_INLINE
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__COORDINATE_SYSTEM_HPP
| [
"klaim@localhost"
] | [
[
[
1,
454
]
]
] |
8e2293c156e9a42e4862ea986ebf5296bfd739ca | fd0221edcf44c190efadd6d8b13763ef5bcbc6f6 | /FER-H264/FER-H264/nal.cpp | b763603b3cb80fc24fb402820fa0751724203ca6 | [] | 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 | UTF-8 | C++ | false | false | 3,902 | cpp | #include "nal.h"
unsigned long findNALstart(FILE *input, unsigned long fPtr)
{
unsigned char buffer[BUFFER_SIZE]; // the buffer for the bytes read
unsigned int bytesRead;
fseek(input, fPtr, SEEK_SET);
// read BUFFER_SIZE bytes from the file:
while (bytesRead = fread(buffer, 1, BUFFER_SIZE, input))
{
bool startPrefixFound = false;
for (unsigned int i = 0; i < bytesRead - 3; i++)
{
if (buffer[i] == 0)
{
if (buffer[i+1] == 0)
{
if (buffer[i+2] == 0)
{
if (buffer[i+3] == 1)
{
// found start code prefix
startPrefixFound = true;
// set the file pointer to after the prefix:
fPtr += i + 4;
fseek(input, fPtr, SEEK_SET);
break;
}
}
}
}
}
if (startPrefixFound) break;
// start code not found in this
// access, set the new fPtr position:
fPtr += BUFFER_SIZE - 3;
fseek(input, fPtr, SEEK_SET);
}
return fPtr;
}
unsigned long findNALend(FILE *input, unsigned long fPtr)
{
unsigned char buffer[BUFFER_SIZE]; // the buffer for the bytes read
unsigned int bytesRead;
fseek(input, fPtr, SEEK_SET);
// read BUFFER_SIZE bytes from the file:
while (bytesRead = fread(buffer, 1, BUFFER_SIZE, input))
{
bool startPrefixFound = false;
for (unsigned int i = 0; i < bytesRead - 2; i++)
{
if (buffer[i] == 0)
{
if (buffer[i+1] == 0)
{
if ((buffer[i+2] == 0) ||
(buffer[i+2] == 1))
{
// found start code prefix
startPrefixFound = true;
// set the file pointer to before the prefix:
fPtr += i;
fseek(input, fPtr, SEEK_SET);
break;
}
}
}
}
if (startPrefixFound) break;
// start code not found in this
// access, set the new fPtr position:
fPtr += BUFFER_SIZE - 2;
fseek(input, fPtr, SEEK_SET);
}
return fPtr;
}
NALunit parseNAL(unsigned char *NALbytes, unsigned int NumBytesInNALunit)
{
NALunit nal_unit;
nal_unit.forbidden_zero_bit = (bool) (NALbytes[0] >> 7);
nal_unit.nal_ref_idc = (NALbytes[0] & 0x7f) >> 5;
nal_unit.nal_unit_type = NALbytes[0] & 0x1f;
nal_unit.NumBytesInRBSP = 0;
unsigned int nalUnitHeaderBytes = 1;
if ((nal_unit.nal_unit_type == 14) ||
(nal_unit.nal_unit_type == 20))
{
perror("NAL unit types 14 and 20 not supported yet.");
exit(1);
}
nal_unit.rbsp_byte = (unsigned char*) malloc(NumBytesInNALunit);
if (nal_unit.rbsp_byte == NULL)
{
perror("Error allocating memory for RBSP.");
exit(1);
}
for (unsigned int i = nalUnitHeaderBytes; i < NumBytesInNALunit; i++)
{
unsigned int next_bits24 = (unsigned int)NALbytes[i] << 16 |
(unsigned int)NALbytes[i+1] << 8 |
(unsigned int)NALbytes[i+2];
if ((i+2 < NumBytesInNALunit) &&
(next_bits24 == 0x03))
{
nal_unit.rbsp_byte[nal_unit.NumBytesInRBSP++] = NALbytes[i];
nal_unit.rbsp_byte[nal_unit.NumBytesInRBSP++] = NALbytes[i+1];
i += 2;
// skip the emulation prevention byte
}
else
{
nal_unit.rbsp_byte[nal_unit.NumBytesInRBSP++] = NALbytes[i];
}
}
return nal_unit;
}
NALunit getNAL(FILE *input, unsigned long *fPtr)
{
unsigned long startPtr = findNALstart(input, *fPtr);
unsigned long endPtr = findNALend(input, startPtr);
unsigned int NumBytesInNALunit = endPtr - startPtr;
printf("NAL start found at %x\n", startPtr);
printf("NAL size = %x\n\n", NumBytesInNALunit);
unsigned char *NALbytes;
NALbytes = (unsigned char*) malloc(NumBytesInNALunit);
if (NALbytes == NULL)
{
perror("Error allocating memory for NAL unit.\n");
exit(1);
}
fseek(input, startPtr, SEEK_SET);
if (fread(NALbytes, 1, NumBytesInNALunit, input) != NumBytesInNALunit)
{
perror("Error reading NAL unit from file.\n");
exit(1);
}
return parseNAL(NALbytes, NumBytesInNALunit);
} | [
"[email protected]@9f3bdf0a-daf3-11de-b590-7f2b5bfbe1fd"
] | [
[
[
1,
156
]
]
] |
a94d13d6651f361c87c7ad135c3b85e8f300a84b | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestnote/src/bctestnotecontainer.cpp | 354a89b8c29c99d9ec18cb7ad997f94bb6f570ef | [] | 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 | 3,807 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Implements test bc for note control container.
*
*/
#include "bctestnotecontainer.h"
#define KAknAtListGray TRgb(0xaaaaaa)
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTestNoteContainer::CBCTestNoteContainer()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestNoteContainer::~CBCTestNoteContainer()
{
ResetControl();
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestNoteContainer::ConstructL( const TRect& aRect )
{
CreateWindowL();
SetRect( aRect );
ActivateL();
}
// ----------------------------------------------------------------------------
// CBCTestNoteContainer::Draw
// Fills the window's rectangle.
// ----------------------------------------------------------------------------
//
void CBCTestNoteContainer::Draw( const TRect& aRect ) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle( CGraphicsContext::ENullPen );
gc.SetBrushColor( KAknAtListGray );
gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
gc.DrawRect( aRect );
}
// ---------------------------------------------------------------------------
// CBCTestNoteContainer::CountComponentControls
// ---------------------------------------------------------------------------
//
TInt CBCTestNoteContainer::CountComponentControls() const
{
if ( iControl )
{
return 1;
}
else
{
return 0;
}
}
// ---------------------------------------------------------------------------
// CBCTestNoteContainer::ComponentControl
// ---------------------------------------------------------------------------
//
CCoeControl* CBCTestNoteContainer::ComponentControl( TInt ) const
{
return iControl;
}
// ---------------------------------------------------------------------------
// CBCTestNoteContainer::SetControlL
// ---------------------------------------------------------------------------
//
void CBCTestNoteContainer::SetControlL( CCoeControl* aControl )
{
iControl = aControl;
if ( iControl )
{
// You can change the position and size
iControl->SetExtent( Rect().iTl, Rect().Size() );
iControl->ActivateL();
DrawNow();
}
}
// ---------------------------------------------------------------------------
// CBCTestNoteContainer::ResetControl
// ---------------------------------------------------------------------------
//
void CBCTestNoteContainer::ResetControl()
{
delete iControl;
iControl = NULL;
}
// ---------------------------------------------------------------------------
// CBCTestNoteContainer::GetCoeEnv
// ---------------------------------------------------------------------------
//
CCoeEnv* CBCTestNoteContainer::GetCoeEnv()
{
return iCoeEnv;
}
| [
"none@none"
] | [
[
[
1,
125
]
]
] |
447d4bd5a7f91e37074421c0354968c00dc72efd | 1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3 | /trunk/libsonetto/include/SonettoScript.h | c6e4d4b64465151ad0347570e007b4391fe3eb16 | [] | no_license | sonetto/legacy | 46bb60ef8641af618d22c08ea198195fd597240b | e94a91950c309fc03f9f52e6bc3293007c3a0bd1 | refs/heads/master | 2021-01-01T16:45:02.531831 | 2009-09-10T21:50:42 | 2009-09-10T21:50:42 | 32,183,635 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,032 | h | /*-----------------------------------------------------------------------------
Copyright (c) 2009, Sonetto Project Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the Sonetto Project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------*/
#ifndef SONETTO_SCRIPT_H
#define SONETTO_SCRIPT_H
// Typedefs and forward declarations
namespace Sonetto {
class Script;
}
#include <vector>
#include "SonettoPrerequisites.h"
#include "SonettoScriptFile.h"
#include "SonettoVariable.h"
namespace Sonetto
{
class SONETTO_API Script
{
public:
Script(ScriptFilePtr file)
: mScriptFile(file), mOffset(0),mLocals(NULL) {}
virtual ~Script() {}
virtual inline void setLocals(VariableMap *locals) { mLocals = locals; }
virtual inline VariableMap *getLocals() { return mLocals; }
virtual inline ScriptFilePtr getScriptFile() { return mScriptFile; }
virtual inline void _setOffset(size_t offset) { mOffset = offset; }
virtual inline size_t _getOffset() const { return mOffset; }
virtual inline void stackPush(const Variable &var) { mVarStack.push(var); }
virtual const Variable &stackPeek();
virtual Variable stackPop();
protected:
/** ScriptFile pointer
Holds opcodes to be used by this script.
*/
ScriptFilePtr mScriptFile;
size_t mOffset;
VariableMap *mLocals;
VariableStack mVarStack;
};
typedef SharedPtr<Script> ScriptPtr;
} // namespace Sonetto
#endif
| [
"[email protected]"
] | [
[
[
1,
86
]
]
] |
350d95b47108354ae4ce94c9000ec12db15a883f | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/LOGINSERVER/StdAfx.h | 736bf558612fea244b3046f5e2fcb81be70abb0a | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,492 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define _WIN32_WINNT 0x0500
#define WINVER 0x0500
#define __MASSIVE
#include <afxwin.h>
#include <mmsystem.h>
#pragma warning(disable:4786)
#include <map>
#include <list>
#include <vector>
using namespace std;
#include "VersionCommon.h"
#include "memtrace.h"
#include "DefineCommon.h"
#include "CmnHdr.h"
#include <afxdisp.h> // MFC Automation classes
#include "DXUtil.h"
#include "Data.h"
#include "file.h"
#include "Scanner.h"
#include "Timer.h"
#include "d3dfont.h"
#include "vutil.h"
//#include "targa.h"
#include "debug.h"
#include "xutil.h"
//#include "exceptionhandler.h"
#include "tickcount.h"
extern CTickCount g_TickCount;
extern char g_lpCoreAddr[16];
extern char g_lpDBAddr[16];
extern char g_szMSG_VER[];
extern BOOL g_bNProtectAuth;
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
62
]
]
] |
fe7744e8ddda95d9d562cacaa91b46c8da58cdda | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADABaseUtils/src/COLLADABUUtils.cpp | e7489552fe8bb337804263c9bc38e2455cbc2132 | [] | no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,915 | cpp | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAStreamWriter.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#include "COLLADABUStableHeaders.h"
#include "COLLADABUUtils.h"
#include "COLLADABUPlatform.h"
#include <string.h>
namespace COLLADABU
{
const String Utils::FILE_PROTOCOL = "file:///";
const String Utils::FILE_DELIMITER = "/";
const char Utils::FILE_DELIMITER_CHAR = '/';
const String Utils::EMPTY_STRING = String();
// defines
#define MAX_FILENAME_LEN 512
// The number of characters at the start of an absolute filename. e.g. in DOS,
// absolute filenames start with "X:\" so this value should be 3, in UNIX they start
// with "\" so this value should be 1. A slash must set to '\\' for DOS or '/' for UNIX.
#if defined(COLLADABU_OS_WIN)
#define ABSOLUTE_NAME_START 3
#define SLASH '\\'
#elif defined(COLLADABU_OS_MAC)
#define ABSOLUTE_NAME_START 1 // TODO Ist das so?
#define SLASH '/' // TODO Ist das so?
#else
#define ABSOLUTE_NAME_START 1
#define SLASH '/'
#endif
//---------------------------------
String Utils::checkNCName ( const String &ncName )
{
String result;
result.reserve ( ncName.length() );
// check if first character is an alpha character
char firstCharacter = ncName[0];
if ( isAsciiAlphaChar ( firstCharacter ) )
result.append ( 1, firstCharacter );
else
result.append ( 1, '_' );
//replace all spaces and colons by underlines
for ( size_t i = 1; i<ncName.length(); ++i )
{
char character = ncName[i];
if ( isIDChar ( character ) )
result.append ( 1, character );
else
result.append ( 1, '_' );
}
return result;
}
//---------------------------------
String Utils::checkID ( const String &id )
{
return checkNCName ( id );
}
//---------------------------------
String Utils::translateToXML ( const String &srcString )
{
String returnString = "";
for ( unsigned int i=0; i<srcString.length(); ++i )
{
switch ( srcString[i])
{
case '\r':
returnString += "
";
break;
case '<':
returnString += "<";
break;
case '>':
returnString += ">";
break;
case '&':
returnString += "&";
break;
case '"':
returnString += """;
break;
case '\'':
returnString += "'";
break;
default :
returnString += srcString[i];
}
}
return returnString;
}
//---------------------------------
String Utils::replaceDot ( const String &text )
{
std::stringstream stream;
for ( size_t i = 0; i < text.length(); ++i )
{
if ( text[i] == '.' )
stream << '_';
else
stream << text[i];
}
return stream.str();
}
//---------------------------------
void Utils::stringFindAndReplace ( String &source, const String searchString, const String replaceString )
{
size_t found = source.find ( searchString );
if ( found != String::npos )
{
size_t searchStrLength = searchString.length();
size_t replaceStrLength = replaceString.length();
do
{
source.replace ( found, searchStrLength, replaceString );
found = source.find (searchString, found + replaceStrLength );
} while ( found != String::npos );
}
}
//---------------------------------
bool Utils::equals ( const String &str1, const String &str2 )
{
return ( strcmp ( str1.c_str(), str2.c_str() ) == 0 );
}
//--------------------------------
bool Utils::equalsIgnoreCase ( const String& s1, const String& s2 )
{
String::const_iterator it1=s1.begin();
String::const_iterator it2=s2.begin();
// has the end of at least one of the strings been reached?
while ( (it1!=s1.end()) && (it2!=s2.end()) )
{
if(::toupper(*it1) != ::toupper(*it2)) //letters differ?
// return -1 to indicate 'smaller than', 1 otherwise
return false;
// proceed to the next character in each string
++it1;
++it2;
}
size_t size1=s1.size(), size2=s2.size();// cache lengths
//return -1,0 or 1 according to strings' lengths
if (size1==size2)
return true;
return false;
}
//--------------------------------
Utils::SystemType Utils::getSystemType()
{
#ifdef COLLADABU_OS_WIN
return WINDOWS;
#else
return POSIX;
#endif
}
//--------------------------------
void Utils::split ( String& text, String& separators, std::vector<String>& words )
{
size_t n = text.length();
size_t start, stop;
start = text.find_first_not_of(separators);
while ((start >= 0) && (start < n))
{
stop = text.find_first_of(separators, start);
if ((stop < 0) || (stop > n)) stop = n;
words.push_back(text.substr(start, stop - start));
start = text.find_first_not_of(separators, stop+1);
}
}
}
| [
"[email protected]"
] | [
[
[
1,
204
]
]
] |
9f4b7dea9c389472cec1cff27b35ad29b68c6568 | 20bf3095aa164d0d3431b73ead8a268684f14976 | /cpp-labs/EXAM.CPP | 44c0b7cb492dc50fb1f52eb7d7c036a4c7ca1249 | [] | no_license | collage-lab/mcalab-cpp | eb5518346f5c3b7c1a96627c621a71cc493de76d | c642f1f009154424f243789014c779b9fc938ce4 | refs/heads/master | 2021-08-31T10:28:59.517333 | 2006-11-10T23:57:09 | 2006-11-10T23:57:21 | 114,954,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | #include<iostream.h>
#include<conio.h>
#include<math.h>
class distance
{
int m,cm;
public:
void getdata()
{
cout<<"\nEnter the distance in metre and centimetre respectively: ";
cin>>m>>cm;
}
void show(distance d3)
{
cout<<"------------------------------------------------";
cout<<"\n HYPOTENUSE CALCULATION OUTPUT";
cout<<"\n-----------------------------------------------";
cout<<"\nThe length of the 3rd side of the right angled triangle is: "<<d3.m<<" metre and "<<d3.cm<<" centimetres";
}
distance calc(distance x,distance y,distance z)
{
x.cm=x.cm+(x.m*100);
y.cm=y.cm+(y.m*100);
z.cm=sqrt(pow(x.cm,2)+pow(y.cm,2));
z.m=0;
while(z.cm>=100)
{
z.m=z.m+1;
z.cm=z.cm-100;
}
return z;
}
};
void main()
{
distance d1,d2,d3;
clrscr();
cout<<"---------------------------------------------";
cout<<"\n HYPOTENUSE CALCULATION";
cout<<"\n---------------------------------------------";
d1.getdata();
d2.getdata();
d3=d3.calc(d1,d2,d3);
d1.show(d3);
getch();
}
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
2e64aabc557ecb1495608b51836e4d2972d1846b | 3182b05c41f13237825f1ee59d7a0eba09632cd5 | /main/main.cpp | 7b7434355bebca9ddeb1f9a2f1ff7dc62a39c0e1 | [] | no_license | adhistac/ee-client-2-0 | 856e8e6ce84bfba32ddd8b790115956a763eec96 | d225fc835fa13cb51c3e0655cb025eba24a8cdac | refs/heads/master | 2021-01-17T17:13:48.618988 | 2010-01-04T17:35:12 | 2010-01-04T17:35:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,642 | cpp | //-----------------------------------------------------------------------------
// Torque 3D
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#ifdef TORQUE_SHARED
#ifdef WIN32
#include <windows.h>
#include <stdio.h>
#include <ExceptionHandler.h>
#pragma comment (lib,"DBGCrash.lib")
extern "C"
{
int (*torque_winmain)( HINSTANCE hInstance, HINSTANCE h, LPSTR lpszCmdLine, int nShow) = NULL;
};
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCommandShow)
{
char filename[4096];
char gameLib[4096];
GetModuleFileNameA(NULL, filename, 4096);
filename[strlen(filename)-4] = 0;
sprintf(gameLib, "%s.dll", filename);
HMODULE hGame = LoadLibraryA(gameLib);
if (hGame)
torque_winmain = (int (*)(HINSTANCE hInstance, HINSTANCE h, LPSTR lpszCmdLine, int nShow))GetProcAddress(hGame, "torque_winmain");
char error[4096];
if (!hGame)
{
sprintf(error, "Unable to load game library: %s. Please make sure it exists and the latest DirectX is installed.", gameLib);
MessageBoxA(NULL, error, "Error", MB_OK|MB_ICONWARNING);
return -1;
}
if (!torque_winmain)
{
sprintf(error, "Missing torque_winmain export in game library: %s. Please make sure that it exists and the latest DirectX is installed.", gameLib);
MessageBoxA(NULL, error, "Error", MB_OK|MB_ICONWARNING);
return -1;
}
int ret = -1;
__try
{
ret = torque_winmain(hInstance, hPrevInstance, lpszCmdLine, nCommandShow );
}
__except(RecordExceptionInfo(GetExceptionInformation(), "main thread"))
{
}
FreeLibrary(hGame);
return ret;
}
#endif // WIN32
#ifdef __MACOSX__
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#include <Carbon/Carbon.h>
extern "C" {
int (*torque_macmain)(int argc, const char **argv) = 0;
}
void GetBasePath(const char** cpath, const char** cname)
{
static char path[2049];
static char name[2049];
ProcessSerialNumber PSN;
ProcessInfoRec pinfo;
FSSpec pspec;
FSRef fsr;
OSStatus err;
path[0] = 0;
name[0] = 0;
*cpath = path;
*cname = name;
// set up process serial number
PSN.highLongOfPSN = 0;
PSN.lowLongOfPSN = kCurrentProcess;
// set up info block
pinfo.processInfoLength = sizeof(pinfo);
pinfo.processName = NULL;
pinfo.processAppSpec = &pspec;
// grab the vrefnum and directory
err = GetProcessInformation(&PSN, &pinfo);
if (! err ) {
FSSpec fss2;
strcpy(name, &pspec.name[1]);
err = FSMakeFSSpec(pspec.vRefNum, pspec.parID, 0, &fss2);
if ( ! err ) {
err = FSpMakeFSRef(&fss2, &fsr);
if ( ! err ) {
err = (OSErr)FSRefMakePath(&fsr, (UInt8*)path, 2048);
}
}
}
}
int main(int argc, const char **argv)
{
void *gameBundle = 0;
char gameBundleFilename[2049];
const char* basePath;
const char* appName;
// Get the path to our app binary and the app name
GetBasePath(&basePath, &appName);
if (!basePath[0] || !appName[0])
return;
char appNameNoDebug[2049];
strcpy(appNameNoDebug, appName);
int i = strlen(appName);
while (i > 0)
{
if (!strcmp(&appName[i], "_DEBUG"))
{
appNameNoDebug[i] = 0;
break;
}
i--;
}
sprintf(gameBundleFilename, "%s.app/Contents/Frameworks/%s Bundle.bundle/Contents/MacOS/%s Bundle", appName, appNameNoDebug, appNameNoDebug);
// first see if the current directory is set properly
gameBundle = dlopen(gameBundleFilename, RTLD_LAZY | RTLD_LOCAL);
if (!gameBundle)
{
// Couldn't load the game bundle... so, using the path to the bundle binary fix up the cwd
if (basePath[0]) {
chdir( basePath );
chdir( "../../../" );
}
// and try again
gameBundle = dlopen( gameBundleFilename, RTLD_LAZY | RTLD_LOCAL);
}
if (!gameBundle)
return -1;
torque_macmain = (int (*)(int argc, const char **argv)) dlsym(gameBundle, "torque_macmain");
if (!torque_macmain)
return -1;
return torque_macmain(argc, argv);
}
#endif // __MACOSX
#ifdef __linux__
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
extern "C"
{
int (*torque_unixmain)(int argc, const char **argv) = NULL;
void(*setExePathName)(const char *exePathName) = NULL;
}
int main(int argc, const char **argv)
{
// assume bin name is in argv[0]
int len = strlen(argv[0]);
char *libName = new char[len+4]; // len + .so + NUL
strcpy(libName, argv[0]);
strcat(libName, ".so");
// try to load the game lib
void *gameLib = dlopen(libName, RTLD_LAZY | RTLD_LOCAL);
delete libName;
if(gameLib == NULL)
{
printf("%s\n", dlerror());
return -1;
}
// set the filename of the exe image
setExePathName = (void(*)(const char *)) dlsym(gameLib, "setExePathName");
if(setExePathName == NULL)
{
printf("%s\n", dlerror());
return -1;
}
setExePathName(argv[0]);
// try to load the lib entry point
torque_unixmain = (int(*)(int argc, const char **argv)) dlsym(gameLib, "torque_unixmain");
if(torque_unixmain == NULL)
{
printf("%s\n", dlerror());
return -1;
}
// Go!
return torque_unixmain(argc, argv);
}
#endif // __linux__
#else //static exe build
#include "platform/platform.h"
#include "app/mainLoop.h"
#include "T3D/gameFunctions.h"
// Entry point for your game.
//
// This is build by default using the "StandardMainLoop" toolkit. Feel free
// to bring code over directly as you need to modify or extend things. You
// will need to merge against future changes to the SML code if you do this.
S32 TorqueMain(S32 argc, const char **argv)
{
// Some handy debugging code:
// if (argc == 1) {
// static const char* argvFake[] = { "dtest.exe", "-jload", "test.jrn" };
// argc = 3;
// argv = argvFake;
// }
// Memory::enableLogging("testMem.log");
// Memory::setBreakAlloc(104717);
// Initialize the subsystems.
StandardMainLoop::init();
// Handle any command line args.
if(!StandardMainLoop::handleCommandLine(argc, argv))
{
Platform::AlertOK("Error", "Failed to initialize game, shutting down.");
return 1;
}
// Main loop
while(StandardMainLoop::doMainLoop());
// Clean everything up.
StandardMainLoop::shutdown();
// Do we need to restart?
if( StandardMainLoop::requiresRestart() )
Platform::restartInstance();
// Return.
return 0;
}
#endif //TORQUE_SHARED
| [
"[email protected]"
] | [
[
[
1,
292
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.