blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f82bc249bf2892788045405fa106a087d82e53d6
|
54cacc105d6bacdcfc37b10d57016bdd67067383
|
/trunk/source/level/physics/PhysicsSystem.cpp
|
26b7ec0a581ae8ae1adcd9c8dca8aab402842f04
|
[] |
no_license
|
galek/hesperus
|
4eb10e05945c6134901cc677c991b74ce6c8ac1e
|
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
|
refs/heads/master
| 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,924 |
cpp
|
/***
* hesperus: PhysicsSystem.cpp
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#include "PhysicsSystem.h"
#include <boost/pointer_cast.hpp>
#include "BroadPhaseCollisionDetector.h"
#include "ContactResolver.h"
#include "ForceGenerator.h"
#include "NarrowPhaseCollisionDetector.h"
#include "NormalPhysicsObject.h"
#include "PhysicsObject.h"
namespace hesp {
//#################### PUBLIC METHODS ####################
PhysicsObjectHandle PhysicsSystem::register_object(const PhysicsObject_Ptr& object)
{
int id = m_idAllocator.allocate();
shared_ptr<int> sid(new int(id));
weak_ptr<int> wid(sid);
object->set_id(id);
m_objects.insert(std::make_pair(id, ObjectData(wid, object)));
m_forceGeneratorRegistry.register_id(id);
return sid;
}
void PhysicsSystem::remove_contact_resolver(PhysicsMaterial material1, PhysicsMaterial material2)
{
m_contactResolverRegistry.remove_resolver(material1, material2);
}
void PhysicsSystem::remove_force_generator(const PhysicsObjectHandle& handle, const std::string& forceName)
{
m_forceGeneratorRegistry.remove_generator(*handle, forceName);
}
void PhysicsSystem::set_contact_resolver(PhysicsMaterial material1, PhysicsMaterial material2,
const ContactResolver_CPtr& resolver)
{
m_contactResolverRegistry.set_resolver(material1, material2, resolver);
}
void PhysicsSystem::set_force_generator(const PhysicsObjectHandle& handle, const std::string& forceName,
const ForceGenerator_CPtr& generator)
{
m_forceGeneratorRegistry.set_generator(*handle, forceName, generator);
}
void PhysicsSystem::update(const BoundsManager_CPtr& boundsManager, const OnionTree_CPtr& tree, int milliseconds)
{
typedef std::vector<Contact_CPtr> ContactSet;
// Step 1: Check for any objects which no longer exist, and deregister them.
check_objects();
// Step 2: Do the physical simulation of the objects.
simulate_objects(milliseconds);
// Step 3: Generate all necessary contacts for them.
ContactSet contacts;
detect_contacts(contacts, boundsManager, tree);
// Step 4: Batch the contacts into groups which might mutually interact.
std::vector<ContactSet> batches = batch_contacts(contacts);
// Step 5: Resolve each batch of contacts in turn.
for(std::vector<ContactSet>::const_iterator it=batches.begin(), iend=batches.end(); it!=iend; ++it)
{
resolve_contacts(*it, tree);
}
}
//#################### PRIVATE METHODS ####################
/**
Group the contacts into batches which might interact with each other.
@param contacts The array of contacts which need resolving
@return The contact batches
*/
std::vector<std::vector<Contact_CPtr> > PhysicsSystem::batch_contacts(const std::vector<Contact_CPtr>& contacts)
{
// TODO: This is the simplest possible batching processor (for test purposes only) - it needs doing properly.
std::vector<std::vector<Contact_CPtr> > batches;
if(!contacts.empty()) batches.push_back(contacts);
return batches;
}
/**
Checks for objects which no longer exist in order to remove them from consideration.
*/
void PhysicsSystem::check_objects()
{
for(std::map<int,ObjectData>::iterator it=m_objects.begin(), iend=m_objects.end(); it!=iend;)
{
shared_ptr<int> sid = it->second.m_wid.lock();
if(!sid)
{
int id = it->first;
m_idAllocator.deallocate(id);
m_forceGeneratorRegistry.deregister_id(id);
it = m_objects.erase(it);
}
else ++it;
}
}
/**
Perform collision detection and generate any necessary contacts.
@param contacts Used to add to the array of contacts which need resolving
@param boundsManager The bounds manager which contains the bounds for all the objects
@param tree The tree representing the world for collision purposes
*/
void PhysicsSystem::detect_contacts(std::vector<Contact_CPtr>& contacts,
const BoundsManager_CPtr& boundsManager, const OnionTree_CPtr& tree)
{
BroadPhaseCollisionDetector broadDetector(boundsManager);
NarrowPhaseCollisionDetector narrowDetector(boundsManager, tree);
// Detect object-object contacts.
for(std::map<int,ObjectData>::const_iterator it=m_objects.begin(), iend=m_objects.end(); it!=iend; ++it)
{
broadDetector.add_object(it->second.m_object);
}
typedef BroadPhaseCollisionDetector::ObjectPairs ObjectPairs;
const ObjectPairs& potentialCollisions = broadDetector.potential_collisions();
for(ObjectPairs::const_iterator it=potentialCollisions.begin(), iend=potentialCollisions.end(); it!=iend; ++it)
{
PhysicsObject& objectA = *it->first;
PhysicsObject& objectB = *it->second;
boost::optional<Contact> contact = narrowDetector.object_vs_object(objectA, objectB);
if(contact) contacts.push_back(Contact_CPtr(new Contact(*contact)));
}
if(tree)
{
// Detect object-world contacts for normal physics objects.
for(std::map<int,ObjectData>::const_iterator it=m_objects.begin(), iend=m_objects.end(); it!=iend; ++it)
{
NormalPhysicsObject_Ptr object = boost::dynamic_pointer_cast<NormalPhysicsObject,PhysicsObject>(it->second.m_object);
if(!object) continue;
boost::optional<Contact> contact = narrowDetector.object_vs_world(*object);
if(contact) contacts.push_back(Contact_CPtr(new Contact(*contact)));
}
}
}
/**
Resolve the contacts using the appropriate contact resolver for each pair of colliding objects.
@param contacts The array of contacts which need resolving
@param tree The tree representing the world for collision purposes
*/
void PhysicsSystem::resolve_contacts(const std::vector<Contact_CPtr>& contacts, const OnionTree_CPtr& tree)
{
// Step 1: Sort the contacts in ascending order of occurrence.
std::vector<Contact_CPtr> sortedContacts(contacts);
std::sort(sortedContacts.begin(), sortedContacts.end(), ContactPred());
// Step 2: Resolve each contact in turn. Note that resolving one contact may affect others,
// which can't be handled completely without abandoning the sequential resolution
// approach. What we do here is simply to recalculate the penetration depth of
// each contact as we come to it, thus allowing e.g. contacts which have become
// irrelevant as a result of another contact being resolved to be skipped.
const double PENETRATION_TOLERANCE = 0;
for(std::vector<Contact_CPtr>::const_iterator it=sortedContacts.begin(), iend=sortedContacts.end(); it!=iend; ++it)
{
const Contact& contact = **it;
double penetrationDepth = contact.penetration_depth();
if(penetrationDepth < PENETRATION_TOLERANCE) continue;
// Look up the appropriate contact resolver in the registry, based on the materials
// of the objects involved.
PhysicsMaterial materialA = contact.objectA().material();
PhysicsMaterial materialB = contact.objectB() ? contact.objectB()->material() : PM_WORLD;
ContactResolver_CPtr resolver = m_contactResolverRegistry.lookup_resolver(materialA, materialB);
// Resolve the contact using this resolver (if any).
if(resolver) resolver->resolve_contact(contact, tree);
}
}
/**
Accumulate the forces on each physics object and update them appropriately.
@param milliseconds The length of the time step (in milliseconds)
*/
void PhysicsSystem::simulate_objects(int milliseconds)
{
for(std::map<int,ObjectData>::const_iterator it=m_objects.begin(), iend=m_objects.end(); it!=iend; ++it)
{
PhysicsObject& object = *it->second.m_object;
object.clear_accumulated_force();
// Apply all the necessary forces to the object.
typedef ForceGeneratorRegistry::ForceGenerators ForceGenerators;
const ForceGenerators& generators = m_forceGeneratorRegistry.generators(object.id());
for(ForceGenerators::const_iterator jt=generators.begin(), jend=generators.end(); jt!=jend; ++jt)
{
jt->second->update_force(object);
}
object.update(milliseconds);
}
}
}
|
[
"[email protected]"
] |
[
[
[
1,
214
]
]
] |
d503f6add7f49a575fbab9451a4738e42f24d1ba
|
af260b99d9f045ac4202745a3c7a65ac74a5e53c
|
/branches/engine/2.4/src/FeatureSet.h
|
66d03a58b8a3063f148e199524f3b4ee290ea01e
|
[] |
no_license
|
BackupTheBerlios/snap-svn
|
560813feabcf5d01f25bc960d474f7e218373da0
|
a99b5c64384cc229e8628b22f3cf6a63a70ed46f
|
refs/heads/master
| 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,582 |
h
|
#ifndef _SeedSearcher_FeatureSet_h
#define _SeedSearcher_FeatureSet_h
//
// File : $RCSfile: $
// $Workfile: FeatureSet.h $
// Version : $Revision: 6 $
// $Author: Aviad $
// $Date: 12/04/05 0:41 $
// Description :
// Concrete class describing a set of features.
// contains algorithms for replacing redundant features
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors apply.
// see http://www.cs.huji.ac.il/labs/compbio/LibB/LICENSE
//
#include "Feature.h"
#include <set>
#include <boost/functional.hpp>
//
// does looks at the value at it1
// does not look at the value at it2
// returns it1 if not found
template <typename _It, typename _Pred>
_It reverse_find_if (_It it1, _It it2, _Pred p)
{
_It current = it2;
for (--current; true ; --current) {
if (p (*current)) {
return current;
}
if (current == it1) {
//
// this is the last seed to compare to
// so if we got here, it means we failed the search
return it1;
}
}
}
class FeatureSet {
public:
//
// comparator for assignments
struct Comparator : public std::binary_function<Feature&, Feature&, bool> {
//
// returns true if a<b
bool operator () (Feature_var a, Feature_var b) const {
return a_better_than_b (*a,*b);
}
//
// compares based on:
// (1) bonfScore
// (2) score
// (3) assignment lexicographical-compare
//
// returns true if a<b
static bool a_better_than_b (const Feature& a, const Feature& b);
};
typedef std::set <Feature_var, Comparator> Features;
typedef Features::iterator iterator;
typedef Features::reverse_iterator reverse_iterator;
typedef Features::const_iterator const_iterator;
typedef IteratorWrapper <Features> Iterator;
typedef CIteratorWrapper <Features> CIterator;
typedef IteratorWrapper <Features, reverse_iterator> RIterator;
public:
~FeatureSet () {
_features.clear ();
}
Feature_var bestFeature() const {
return *_features.begin ();
}
Feature_var worstFeature() const{
return *_features.rbegin ();
}
void removeFeature (iterator it) {
_features.erase(it);
}
bool insertFeature (Feature_var f) {
std::pair <Features::iterator, bool> result = _features.insert(f);
return result.second;
}
void insertFeatures (iterator begin, iterator end) {
_features.insert (begin, end);
}
//
// removes the feature pointed by the iterator from the set
// and insert the feature f instead
void replaceFeature (Features::iterator it, Feature_var f) {
if (it!=_features.end ()) {
removeFeature(it);
}
USELESS (bool result =) insertFeature (f);
USELESS (debug_mustbe (result));
}
int size () {
return _features.size ();
}
iterator begin () {
return _features.begin();
}
iterator end () {
return _features.end ();
}
reverse_iterator rbegin () {
return _features.rbegin();
}
reverse_iterator rend () {
return _features.rend ();
}
Iterator getIterator () {
return Iterator (begin (), end());
}
CIterator getIterator() const {
return CIterator (_features.begin (), _features.end());
}
RIterator getRIterator () {
return RIterator (begin (), end());
}
template <class _BinFunc >
std::pair <Features::iterator, bool>
shouldReplace (Feature_var f, _BinFunc isRedundant)
{
//
// find the BEST-SCORING seed which is redundant with f
Features::iterator best_scoring_redundant =
find_if (
_features.begin (),
_features.end (),
std::bind2nd (isRedundant, f)
);
//
if (best_scoring_redundant == _features.end ()) {
//
// it is not redundant to any seed,
return std::make_pair (_features.end (), true);
}
else {
//
if (Comparator::a_better_than_b (*f, **best_scoring_redundant)) {
//
// f is better than its redundant
debug_mustbe ( f->log2score() <=
(*best_scoring_redundant)->log2score ());
//
// f is better than the best-scoring seeds which it is redundant with.
// so we should insert f into the set.
// but remove the WORST-SCORING seed that f is redundant with
Features::iterator worst_scoring_redundant =
reverse_find_if (
best_scoring_redundant,
_features.end (),
std::bind2nd (isRedundant, f)
);
if (worst_scoring_redundant == _features.end ()) {
//
// the best-scoring-redundant is also the worst-scoring-redundant
worst_scoring_redundant = best_scoring_redundant;
}
# if 0
DLOG << Str ("-------------------") << DLOG.EOL ();
DLOG << Format (f->assignment()) << DLOG.EOL ();
DLOG << Format ((*best_scoring_redundant)->assignment()) << DLOG.EOL ();
DLOG << Format ((*worst_scoring_redundant)->assignment()) << DLOG.EOL ();
DLOG.flush();
# endif
return std::make_pair (worst_scoring_redundant, true);
}
else {
//
// we have a redundant seed which is better than our seed
// we cannot
return std::make_pair (_features.end (), false);
}
}
}
//
// this function replaces a single feature in the set
// with the given feature, if it is helpful.
//
// _BinfFunc should be of the form:
// (1) bool func (const Feature&, const Feature&)
// otherwise if it is a function it should derive from
// (2) std::binary_function <Feature&, Feature&, bool>
template <class _BinFunc >
bool replace1 (Feature_var f, _BinFunc isRedundant) {
Feature& wfeature = *worstFeature();
if (Comparator::a_better_than_b(wfeature, *f)) {
//
// this seed is worse than the worst seed in the set
debug_mustbe (f->log2score() >= wfeature.log2score());
return false;
}
std::pair <Features::iterator, bool> result =
shouldReplace(f, isRedundant);
if (result.second == false) {
//
// it should not be inserted into the set at all
// because a better-scoring, redundant, seed exists
return false;
}
else {
if (result.first == _features.end ()) {
//
// it is not redundant to any seed,
// so drop the worst feature and replace it with this one
replaceFeature (--result.first, f);
return true;
}
else {
//
// we replace the redundant seed with our seed
replaceFeature (result.first, f);
return true;
}
}
}
//
// insert when there is room
// replace if there is chan
template <class _BinFunc>
bool insertOrReplace1 (Feature_var f, _BinFunc isRedundant, int maxElements) {
if (size () < maxElements) {
//
// we insert, unless the seed is redundant to something in the set
std::pair <Features::iterator, bool> result =
shouldReplace(f, isRedundant);
if (result.second) {
replaceFeature(result.first, f);
}
return true;
}
else {
return replace1 (f, isRedundant);
}
}
//
// returns true if (a contains b) or (b contains a)
// length of assignments must be the same
struct SymmetricRedundancyCheck :
public std::binary_function <AssignmentBase, AssignmentBase, bool>
{
bool operator () (const AssignmentBase& a, const AssignmentBase& b) const {
return check (a,b);
}
static bool check (const AssignmentBase& a, const AssignmentBase& b) {
debug_mustbe (a.length () == b.length ());
return a.contains (b) || b.contains (a);
}
};
//
// a = substr (a, 0, length - offset)
// b = substr (b, offset, length - offset)
//
// returns true if (a contains b) or (b contains a)
// length of assignments must be the same
struct ASymmetricOffsetRedundancyCheck :
public std::binary_function <AssignmentBase, AssignmentBase, bool>
{
int _offset;
ASymmetricOffsetRedundancyCheck (int offset) : _offset (offset) {
debug_mustbe (_offset >= 0);
}
bool operator () (const AssignmentBase& a, const AssignmentBase& b) const{
return check (_offset, a,b);
}
static bool check (int offset, const AssignmentBase& a, const AssignmentBase& b);
};
//
// symmetrically looks for ASymmetricOffsetRedundancy
// for all 0<= offset <= max-offset
//
// length of assignments need not be the same
struct SymmetricMaxOffsetRedundancyCheck :
public std::binary_function <AssignmentBase, AssignmentBase, bool>
{
int _maxoffset;
SymmetricMaxOffsetRedundancyCheck (int maxoffset)
: _maxoffset (maxoffset) {
debug_mustbe (_maxoffset >= 0);
}
bool operator () (const AssignmentBase& a, const AssignmentBase& b) const{
return check (_maxoffset, a,b);
}
static bool check (int offset, const AssignmentBase& a, const AssignmentBase& b);
};
template <class _BinFunc>
struct FeatureRedundancyCheck :
public std::binary_function <Feature_var, Feature_var, bool>
{
_BinFunc _f;
FeatureRedundancyCheck (_BinFunc f) :_f (f) {
}
bool operator () (Feature_var a, Feature_var b) const{
return _f(a->assignment(), b->assignment());
}
};
template <class _BinFunc>
static FeatureRedundancyCheck<_BinFunc>
featureRedundancyCheck (_BinFunc f) {
return FeatureRedundancyCheck<_BinFunc> (f);
}
template <class _BinFunc>
struct FeatureReverseRedundancyCheck :
public std::binary_function <Feature_var, Feature_var, bool>
{
_BinFunc _f;
const Langauge& _langauge;
FeatureReverseRedundancyCheck (_BinFunc f, const Langauge& l)
:_f (f), _langauge (l) {
}
bool operator () (Feature_var a, Feature_var b) const {
return _f(a->assignment(), b->assignment()) ||
_f(a->complement(_langauge), b->assignment());
}
};
template <class _BinFunc>
static FeatureReverseRedundancyCheck<_BinFunc>
featureReverseRedundancyCheck (_BinFunc f, const Langauge& l) {
return FeatureReverseRedundancyCheck<_BinFunc> (f, l);
}
private:
Features _features;
};
#endif
|
[
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
] |
[
[
[
1,
361
]
]
] |
cbd6ac6f6d13a47b5034e3af4a4bbbd32cae1f39
|
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
|
/TeCom/src/TdkLayout/Source Files/TdkMapWorld_y1_Property.cpp
|
9df2e4047886cbd84c68dff7a75eab8dce4da4cd
|
[] |
no_license
|
radtek/terra-printer
|
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
|
959241e52562128d196ccb806b51fda17d7342ae
|
refs/heads/master
| 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null |
ISO-8859-2
|
C++
| false | false | 2,659 |
cpp
|
#include<TdkLayoutTypes.h>
#include<TdkMapWorld_y1_Property.h>
///////////////////////////////////////////////////////////////////////////////
//Constructor
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
TdkMapWorld_y1_Property::TdkMapWorld_y1_Property(double *newVal, bool *redraw) : TdkAbstractProperty()
{
_propertyName="MapWorld_y1_Property";
_value=newVal;
_redraw=redraw;
}
///////////////////////////////////////////////////////////////////////////////
//Destructor
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
TdkMapWorld_y1_Property::~TdkMapWorld_y1_Property()
{
_value=0;
}
///////////////////////////////////////////////////////////////////////////////
//SetValue
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
void TdkMapWorld_y1_Property::setValue(const double &newVal)
{
if(_value != 0) *_value=newVal;
if(_redraw != 0) *_redraw=true;
}
///////////////////////////////////////////////////////////////////////////////
//GetValue
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
double TdkMapWorld_y1_Property::getValue()
{
if(_value != 0) return *_value;
return 0;
}
///////////////////////////////////////////////////////////////////////////////
//GetValue by Reference
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
void TdkMapWorld_y1_Property::getValue(double &value)
{
if(_value != 0) value=*_value;
else value=0;
}
///////////////////////////////////////////////////////////////////////////////
//Equal operator
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
TdkMapWorld_y1_Property& TdkMapWorld_y1_Property::operator=(const TdkMapWorld_y1_Property &other)
{
if(_value != 0) *_value=*other._value;
return *this;
}
///////////////////////////////////////////////////////////////////////////////
//Equal Operator
//Author : Rui Mauricio Gregório
//Date : 07/2011
///////////////////////////////////////////////////////////////////////////////
TdkMapWorld_y1_Property& TdkMapWorld_y1_Property::operator=(const TdkAbstractProperty &other)
{
if(_value != 0) *_value=*((TdkMapWorld_y1_Property&)other)._value;
return *this;
}
|
[
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] |
[
[
[
1,
80
]
]
] |
628d09abfff3cca01ff8f8c86d5a9e09073ac85a
|
bc3073755ed70dd63a7c947fec63ccce408e5710
|
/src/Game/Graphics/Particle.h
|
7637e46f60a182b2932e79b354cc1ae7220949a1
|
[] |
no_license
|
ptrefall/ste6274gamedesign
|
9e659f7a8a4801c5eaa060ebe2d7edba9c31e310
|
7d5517aa68910877fe9aa98243f6bb2444d533c7
|
refs/heads/master
| 2016-09-07T18:42:48.012493 | 2011-10-13T23:41:40 | 2011-10-13T23:41:40 | 32,448,466 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,210 |
h
|
/* Ken Mazaika
February 23, 2005
Quagmire Particle Engine
Copyright 2005
http://home.comcast.net/~kjmaz
*/
#pragma once
#include "qd.h"
namespace Graphics
{
class QdParticle
{
protected:
Qd3dPoint m_ptUL; //Upper Left corner to the square
Qd3dPoint m_ptLR; //Lower right corner of the square
QdColor m_clrCurrent; //Current color of the particle
QdColor m_clrFade; //What increment the color by
Qd3dPoint m_ptDirection; //What to increment the object by
Qd3dPoint m_ptGravity; //What to increment the object by
int m_nFrames; //How many times has the particle been displayed
float m_fAge; //How many "seconds" elapsed (for gravity calculations)
float m_fLife; //Determine "life"
float m_fGravityFactor;
float m_fFadeLife;
int m_nParticle;
public:
QdParticle();
void draw();
void advance();
friend class QdParticleEngine;
};
class QdParticleEngine
{
protected:
bool m_bLimit;
QdParticle *m_pParticles;
bool m_bEngineActive;
int m_nParticles;
int m_nAge;
float m_fLimitR;
float m_fLimitL;
float m_fLimitT;
float m_fLimitB;
//char *m_szImgPath;
//char m_szImgPathA[128];
public:
int setLimit(float fLimitL, float fLimitR, float fLimitT, float fLimitB);
int setLimit(bool bLimit);
int setCurrentColor(int nParticle, float fRed, float fGreen, float fBlue, float fAlpha);
int setFadeColor(int nParticle, float fRed, float fGreen, float fBlue, float fAlpha);
int setDirection(int nParticle, float fX, float fY, float fZ);
int setGravity(int nParticle, float fX, float fY, float fZ);
int setLR(int nParticle, float fX, float fY, float fZ);
int setUL(int nParticle, float fX, float fY, float fZ);
int setAge(int nParticle, float fAge);
int setFrame(int nParticle, int nFrame);
int setGravityFactor(int nParticle, float fGravityFactor);
int setLife(int nParticle, float fLife);
int setFadeLife(int nParticle, float fFadeLife);
//int setImgPath(char *szImgPath);
int draw();
QdParticleEngine();
~QdParticleEngine();
int init(int nParticles);
int virtual resetParticles();
//reset a specific particle
virtual int particleDead(int nParticle);
int destroy();
};
}
|
[
"[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79"
] |
[
[
[
1,
83
]
]
] |
12486b7f0a77ee8f1998677f71d2d23bab231a49
|
ce262ae496ab3eeebfcbb337da86d34eb689c07b
|
/SEFoundation/SEDistance/SEDistLine2Ray2.h
|
a4337a4b3cff5667293f152913fff8a9f3153110
|
[] |
no_license
|
pizibing/swingengine
|
d8d9208c00ec2944817e1aab51287a3c38103bea
|
e7109d7b3e28c4421c173712eaf872771550669e
|
refs/heads/master
| 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 2,073 |
h
|
// Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_DistLine2Ray2_H
#define Swing_DistLine2Ray2_H
#include "SEFoundationLIB.h"
#include "SEDistance.h"
#include "SELine2.h"
#include "SERay2.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20090113
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEDistLine2Ray2f : public SEDistance<float,
SEVector2f>
{
public:
SEDistLine2Ray2f(const SELine2f& rLine, const SERay2f& rRay);
// 对象访问.
const SELine2f& GetLine(void) const;
const SERay2f& GetRay(void) const;
// static distance查询.
virtual float Get(void);
virtual float GetSquared(void);
// 用于dynamic distance查询的convex function计算.
virtual float Get(float fT, const SEVector2f& rVelocity0,
const SEVector2f& rVelocity1);
virtual float GetSquared(float fT, const SEVector2f& rVelocity0,
const SEVector2f& rVelocity1);
private:
const SELine2f* m_pLine;
const SERay2f* m_pRay;
};
}
#endif
|
[
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] |
[
[
[
1,
64
]
]
] |
17e92c99356bd4354bf1d121c0fb64b9540643a8
|
a5cbc2c1c12b3df161d9028791c8180838fbf2fb
|
/Heimdall/heimdall/source/ResponsePacket.h
|
ce799b548ffb241fb4a8a1355929ef835669e1da
|
[
"MIT"
] |
permissive
|
atinm/Heimdall
|
e8659fe869172baceb590bc445f383d8bcb72b82
|
692cda38c99834384c4f0c7687c209f432300993
|
refs/heads/master
| 2020-03-27T12:29:58.609089 | 2010-12-03T19:25:19 | 2010-12-03T19:25:19 | 1,136,137 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,143 |
h
|
/* Copyright (c) 2010 Benjamin Dobell, Glass Echidna
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#ifndef RESPONSEPACKET_H
#define RESPONSEPACKET_H
// Heimdall
#include "InboundPacket.h"
namespace Heimdall
{
class ResponsePacket : public InboundPacket
{
public:
enum
{
kResponseTypeSendFilePart = 0x00,
kResponseTypeDeviceInfo = 0x64,
kResponseTypePitFile = 0x65,
kResponseTypeFileTransfer = 0x66,
kResponseTypeRebootDevice = 0x67
};
private:
unsigned int responseType;
protected:
enum
{
kDataSize = 4
};
public:
ResponsePacket(int responseType) : InboundPacket(8)
{
this->responseType = responseType;
}
unsigned int GetResponseType(void) const
{
return (responseType);
}
virtual bool Unpack(void)
{
const unsigned char *data = GetData();
unsigned int receivedResponseType = UnpackInteger(0);
if (receivedResponseType != responseType)
{
responseType = receivedResponseType;
return (false);
}
return (true);
}
};
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
81
]
]
] |
2a9b64e5fb7b0c153a3507b8245908d92fce1fe0
|
299a25ea0e7dc6dfd4a5be0417dc808ee9312bfb
|
/main.cpp
|
2cb9922365ac32b8e749cf06f6384a37bf6c25c9
|
[] |
no_license
|
lucasjcastro/compilador-mepa
|
533914c84f733542df5cc9bf243c19575492cea4
|
b3e4ba52807d6ce3b413b6fd5b1ea43b1048c5a5
|
refs/heads/master
| 2021-01-10T07:37:40.761607 | 2007-06-30T21:33:02 | 2007-06-30T21:33:02 | 46,513,094 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,438 |
cpp
|
//Douglas Schmidt
//este include ja possui as bibliotecas stdio.h, ctype.h e string.h
#include "lexico.h"
#include "TokenListNode.h"
#include <list>
#include <string>
#include <iterator>
#include <iostream>
int main(int argc, char **argv)
{
if (argc <= 1)
{
printf("Erro: Especifique uma entrada.\n");
//system("PAUSE");
return 1;
}
FILE *entrada;
if ((entrada = fopen(argv[1], "r")) == NULL)
{
printf("Erro: Arquivo %s nao pode ser aberto.\n", argv[1]);
//system("PAUSE");
return 2;
}
//fila de tokens
struct Fila *tokens;
inicializarFila(&tokens);
int ntokens = 0;
//lista de tokens
std::list< TokenListNode >
tokenList;
TokenListNode auxTokenListNode;
//analise lexica
if (analiseLexica(entrada, tokens) == ERRO)
{
printf("Erro: Analise mal sucedida.\n");
//system("PAUSE");
//return 1;
}
//esvazia fila de tokens e imprime cada um
struct Token proximo;
do
{
desenfilera(tokens, &proximo);
auxTokenListNode.setTokenValue("\0");
auxTokenListNode.setTokenValue(-99199);
if (proximo.tipo == ERRO)
{
printf("Erro lexico: %d,%d em %s: \n", proximo.linha, proximo.coluna, argv[1]);
//printf("%d\n", proximo.valor);
switch (proximo.valor)
{
case ERRO_ID_INVALIDO:
printf("Identificador invalido.\n");
break;
case ERRO_SIMBOLO_INV:
printf("Simbolo invalido.\n");
}
fclose(entrada);
return 3;
}
else
{
ntokens++;
switch (proximo.tipo)
{
/**
#define INTEIRO 0
#define IDENTIFICADOR 1
#define PAL_RESERVADA 2
#define SIMBOLO 3
#define SIMBOLO_COMP 4
#define BOLEANO 5
#define ERRO 6
#define TERMINO 7
*/
case INTEIRO:
printf("%d,%d:\tInteiro:\t%d\n",
proximo.linha, proximo.coluna, proximo.valor);
/* Construcao da Lista de Tokens */
auxTokenListNode.setTokenType( _NUMERO );
auxTokenListNode.setTokenValue(proximo.valor);
auxTokenListNode.setLine(proximo.linha);
break;
case IDENTIFICADOR:
printf("%d,%d:\tIdentificador:\t%s\n",
proximo.linha, proximo.coluna, proximo.nome);
/* Construcao da Lista de Tokens */
auxTokenListNode.setTokenType( _IDENTIFICADOR );
auxTokenListNode.setTokenValue(proximo.nome);
auxTokenListNode.setLine(proximo.linha);
free(proximo.nome);
break;
case PAL_RESERVADA:
printf("%d,%d:\tPal. reservada:\t%s\n",
proximo.linha, proximo.coluna, reservadas[proximo.valor]);
/* Construcao da Lista de Tokens */
/* Se for or, and ou not, tipo eh op_logico */
if ( (strcmp(reservadas[proximo.valor], reservadas[13]) == 0 ) || // or
(strcmp(reservadas[proximo.valor], reservadas[14]) == 0 ) || // and
(strcmp(reservadas[proximo.valor], reservadas[16]) == 0 ) ) // not
auxTokenListNode.setTokenType( _OP_LOGICO );
/* Se for div eh op_aritmetico */
else if (strcmp(reservadas[proximo.valor], reservadas[15]) == 0 ) // div
auxTokenListNode.setTokenType( _OP_ARITMETICO );
/* Se for integer ou boolean eh _datatype */
else if ( (strcmp(reservadas[proximo.valor], reservadas[17]) == 0) || // integer
(strcmp(reservadas[proximo.valor], reservadas[18]) == 0) ) // boolean
auxTokenListNode.setTokenType( _DATATYPE );
else /* qq outra palavra reservada */
auxTokenListNode.setTokenType( _PAL_RESERVADA );
/* Depois de redefinido o tipo do token, grava os dados */
auxTokenListNode.setTokenValue(reservadas[proximo.valor]);
auxTokenListNode.setLine(proximo.linha);
break;
case SIMBOLO:
printf("%d,%d:\tSimbolo:\t%s\n",
proximo.linha, proximo.coluna, simbolos[proximo.valor]);
/* Construcao da Lista de Tokens */
if ( (strcmp(simbolos[proximo.valor], simbolos[9]) == 0) || // <
(strcmp(simbolos[proximo.valor], simbolos[12]) == 0) ) // >
auxTokenListNode.setTokenType( _OP_RELACIONAL );
else
if ( (strcmp(simbolos[proximo.valor], simbolos[0]) == 0) || // -
(strcmp(simbolos[proximo.valor], simbolos[13]) == 0) || // +
(strcmp(simbolos[proximo.valor], simbolos[14]) == 0) ) // *
auxTokenListNode.setTokenType( _OP_ARITMETICO );
else
if ( (strcmp(simbolos[proximo.valor], simbolos[1]) == 0) || // .
(strcmp(simbolos[proximo.valor], simbolos[2]) == 0) || // ,
(strcmp(simbolos[proximo.valor], simbolos[6]) == 0) || // :
(strcmp(simbolos[proximo.valor], simbolos[3]) == 0) ) // ;
auxTokenListNode.setTokenType( _PONTUACAO );
else
if ( (strcmp(simbolos[proximo.valor], simbolos[4]) == 0) || // (
(strcmp(simbolos[proximo.valor], simbolos[5]) == 0) ) // )
auxTokenListNode.setTokenType( _SIMBOLOS );
auxTokenListNode.setTokenValue(simbolos[proximo.valor]);
auxTokenListNode.setLine(proximo.linha);
break;
case SIMBOLO_COMP:
printf("%d,%d:\tSim. composto:\t%s\n",
proximo.linha, proximo.coluna, simbolos[proximo.valor]);
/* Construcao da Lista de Tokens */
if ( (strcmp(simbolos[proximo.valor], simbolos[8]) == 0) || // <>
(strcmp(simbolos[proximo.valor], simbolos[10]) == 0) || // <=
(strcmp(simbolos[proximo.valor], simbolos[11]) == 0) ) // >=
auxTokenListNode.setTokenType( _OP_RELACIONAL );
else
auxTokenListNode.setTokenType( _SIMBOLOS ); // soh sobrou o :=
auxTokenListNode.setTokenValue(simbolos[proximo.valor]);
auxTokenListNode.setLine(proximo.linha);
break;
case BOLEANO:
printf("%d,%d:\tBooleano:\t%s\n",
proximo.linha, proximo.coluna, reservadas[proximo.valor]);
/* Construcao da Lista de Tokens */
auxTokenListNode.setTokenType( _BOLEANO );
auxTokenListNode.setTokenValue(reservadas[proximo.valor]);
auxTokenListNode.setLine(proximo.linha);
break;
case IGNORA:
ntokens--;
break;
}
/* insere TokenNode na Lista de Tokens */
if ( proximo.tipo != IGNORA)
tokenList.push_back(auxTokenListNode); // <<<< SAIDA DO LEXICO
}
}
while (proximo.tipo != TERMINO);
free(tokens);
fclose(entrada);
printf("\n\tN. Tokens:\t%d\n\n", ntokens);
//CHAMAR SINTATICO AQUI
// Reimprimindo a lista...
// iterador para lista
std::list<TokenListNode>::iterator it;
for ( it = tokenList.begin(); it != tokenList.end(); it++ ) {
std::cout << it->getTokenType();
if ( it->getValueString() != "\0" )
std::cout << "\t" << it->getValueString() << std::endl;
else
std::cout << "\t" << it->getValueInt() << std::endl;
}
std::cout << "Tamanho tokenList: " << tokenList.size() << std::endl;
std::string letra;
//system("PAUSE");
return 0;
}
|
[
"biesdorf@623e42bb-d033-0410-9666-67999694cb3c",
"mefistofiles@623e42bb-d033-0410-9666-67999694cb3c"
] |
[
[
[
1,
206
],
[
219,
227
]
],
[
[
207,
218
]
]
] |
7931bbb447d44107c90a23e393e7662c8c7765eb
|
6bdb3508ed5a220c0d11193df174d8c215eb1fce
|
/Codes/Halak/Color.h
|
7943b2b2dd7e18f54f4332bfb0123ffc8c1c580a
|
[] |
no_license
|
halak/halak-plusplus
|
d09ba78640c36c42c30343fb10572c37197cfa46
|
fea02a5ae52c09ff9da1a491059082a34191cd64
|
refs/heads/master
| 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,012 |
h
|
#pragma once
#ifndef __HALAK_COLOR_H__
#define __HALAK_COLOR_H__
# include <Halak/Foundation.h>
# include <Halak/Vector3.h>
# include <Halak/Vector4.h>
namespace Halak
{
struct Color
{
byte A;
byte R;
byte G;
byte B;
inline Color();
inline Color(int r, int g, int b);
inline Color(int r, int g, int b, int a);
inline Color(unsigned long argb);
inline explicit Color(Vector3 rgb);
inline explicit Color(Vector4 rgba);
inline Color(const Color& original);
inline Vector3 ToVector3() const;
inline Vector4 ToVector4() const;
inline unsigned long ToRGBA() const;
inline unsigned long ToARGB() const;
inline Color& operator = (const Color& original);
inline Color& operator += (Color right);
inline Color& operator -= (Color right);
inline Color& operator *= (Color right);
inline Color& operator *= (float right);
inline Color& operator /= (Color right);
inline Color& operator /= (float right);
inline Color operator + (Color right) const;
inline Color operator - (Color right) const;
inline Color operator * (Color right) const;
inline Color operator * (float right) const;
inline Color operator / (Color right) const;
inline Color operator / (float right) const;
inline bool operator == (Color right) const;
inline bool operator != (Color right) const;
private:
static inline byte Add(byte a, byte b);
static inline byte Subtract(byte a, byte b);
static inline byte Clamp(int value);
static inline byte Clamp(float value);
};
}
# include <Halak/Color.inl>
#endif
|
[
"[email protected]"
] |
[
[
[
1,
59
]
]
] |
7cfcf9e377edb1162c75704cb26e456d0ef22232
|
c58b7487c69d596d08dafba52361aab43ed25ed3
|
/json_test/json_spirit_value_test.cpp
|
9e84848f5d099ed4ed5ad488fda7d8a45316fb75
|
[
"MIT"
] |
permissive
|
deweerdt/JSON-Spirit
|
a2508d6272aa058ff9902c2c6494b7f1d70dec09
|
7dd32ece9c700c3e4a51e6c466cddcefd1054766
|
refs/heads/master
| 2020-04-04T13:14:06.281332 | 2009-12-07T16:13:55 | 2009-12-07T16:13:55 | 403,942 | 4 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,656 |
cpp
|
// Copyright John W. Wilkinson 2007 - 2009.
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.02
#include "json_spirit_value_test.h"
#include "json_spirit_value.h"
#include "utils_test.h"
#include <limits.h>
#include <boost/assign/list_of.hpp>
#include <boost/integer_traits.hpp>
using namespace json_spirit;
using namespace std;
using namespace boost;
using namespace boost::assign;
namespace
{
const int64_t max_int64 = integer_traits< int64_t >::max();
const uint64_t max_uint64 = integer_traits< uint64_t >::max();
void test_obj_value()
{
const Pair p1( "name1", "value1" );
const Pair p3( "name3", "value3" );
Object obj_1; obj_1.push_back( p1 );
Object obj_2; obj_2.push_back( p1 );
Object obj_3; obj_3.push_back( p3 );
Value v1( obj_1 );
Value v2( obj_2 );
Value v3( obj_3 );
assert_eq( v1.type(), obj_type );
assert_eq ( v1, v2 );
assert_neq( v1, v3 );
assert_eq( v1.get_obj(), obj_1 );
assert_eq( v3.get_obj(), obj_3 );
}
void test_array_value()
{
Array array_1; array_1.push_back( 1 ); array_1.push_back( "2" );
Array array_2; array_2.push_back( 1 ); array_2.push_back( "2" );
Array array_3; array_3.push_back( 1 ); array_3.push_back( "X" );
Value v1( array_1 );
Value v2( array_2 );
Value v3( array_3 );
assert_eq( v1.type(), array_type );
assert_eq ( v1, v2 );
assert_neq( v1, v3 );
assert_eq( v1.get_array(), array_1 );
assert_eq( v3.get_array(), array_3 );
}
void test_bool_value()
{
Value v1( true );
Value v2( true );
Value v3( false );
assert_eq( v1.type(), bool_type );
assert_eq ( v1, v2 );
assert_neq( v1, v3 );
assert( v1.get_bool() );
assert( !v3.get_bool() );
}
void test_int_value()
{
Value v1( 1 );
Value v2( 1 );
Value v3( INT_MAX );
assert_eq( v1.type(), int_type );
assert_eq ( v1, v2 );
assert_neq( v1, v3 );
unsigned int uint_max = INT_MAX;
assert_eq( v1.get_int(), 1 );
assert_eq( v1.get_int64(), 1 );
assert_eq( v1.get_uint64(), 1u );
assert_eq( v3.get_int(), INT_MAX );
assert_eq( v3.get_int64(), INT_MAX );
assert_eq( v3.get_uint64(), uint_max );
Value v4( max_int64 );
assert_eq( v4.get_int64(), max_int64 );
assert_eq( v4.get_uint64(), static_cast< uint64_t >( max_int64 ) );
const uint64_t max_int64_plus_1 = max_int64 + uint64_t( 1 );
Value v5( max_int64_plus_1 );
assert_eq( v5.get_uint64(), max_int64_plus_1 );
Value v6( max_uint64 );
assert_eq( v6.get_uint64(), max_uint64 );
Value v7( 0 );
assert_eq( v7.get_int(), 0 );
assert_eq( v7.get_int64(), 0 );
assert_eq( v7.get_uint64(), 0u );
Value v8( -1 );
assert_eq( v8.get_int(), -1 );
assert_eq( v8.get_int64(), -1 );
assert_eq( v8.get_uint64(), max_uint64 );
}
void test_real_value()
{
Value v1( 1.0 );
Value v2( 1.0 );
Value v3( 2.0 );
assert_eq( v1.type(), real_type );
assert_eq ( v1, v2 );
assert_neq( v1, v3 );
assert_eq( v1.get_real(), 1.0 );
assert_eq( v3.get_real(), 2.0 );
}
void test_null_value()
{
Value v1;
Value v2;
assert_eq( v1.type(), null_type );
assert_eq( v1.is_null(), true );
assert_eq( v1, v2 );
assert_eq( v1.is_null(), true );
assert_eq( Value( 1 ).is_null(), false );
}
template< typename T >
void test_get_value( const T& t )
{
assert_eq( Value( t ).get_value< T >(), t );
}
void test_get_value()
{
test_get_value( 123 );
test_get_value( max_int64 );
test_get_value( 1.23 );
test_get_value( true );
test_get_value( false );
test_get_value( string( "test" ) );
Array a; a.push_back( 1 ); a.push_back( "2" );
test_get_value( a );
Object obj; obj.push_back( Pair( "name1", "value1" ) );
test_get_value( obj );
}
void assert_array_eq( const Value& v, const Array& a )
{
assert_eq( v.get_array(), a );
}
void assert_obj_eq( const Value& v, const Object& obj )
{
assert_eq( v.get_obj(), obj );
}
template< typename T >
void check_copy( const T& t )
{
const Value v1( t );
const Value v2( v1 );
Value v3;
v3 = v1;
assert_eq( v1, v2 );
assert_eq( v1, v3 );
assert_eq( v2.get_value< T >(), t );
assert_eq( v3.get_value< T >(), t );
assert_eq( v1.is_uint64(), v2.is_uint64() );
assert_eq( v1.is_uint64(), v3.is_uint64() );
}
void check_copying_null()
{
const Value v1;
const Value v2( v1 );
Value v3;
v3 = v1;
assert_eq( v2.type(), null_type );
assert_eq( v3.type(), null_type );
}
void test_copying()
{
{
const Array array_1 = list_of(1)(2);
Value v1( array_1 );
const Value v2( v1 );
assert_array_eq( v1, array_1 );
assert_array_eq( v2, array_1 );
v1.get_array()[0] = 3;
assert_array_eq( v1, list_of(3)(2) );
assert_array_eq( v2, array_1 );
}
{
const Object obj_1 = list_of( Pair( "a", 1 ) )( Pair( "b", 2 ) );
Value v1( obj_1 );
Value v2;
v2 = v1;
assert_obj_eq( v1, obj_1 );
assert_obj_eq( v2, obj_1 );
v1.get_obj()[0] = Pair( "c", 3 );
assert_obj_eq( v1, list_of( Pair( "c", 3 ) )( Pair( "b", 2 ) ) );
assert_obj_eq( v2, obj_1 );
}
{
check_copy( 1 );
check_copy( 2.0 );
check_copy( max_int64 );
check_copy( max_uint64 );
check_copy( string("test") );
check_copy( true );
check_copy( false );
const Array array_1 = list_of(1)(2);
check_copy( array_1 );
const Object obj_1 = list_of( Pair( "a", 1 ) )( Pair( "b", 2 ) );
check_copy( obj_1 );
check_copying_null();
}
}
template< typename ObjectType > void check_pair_typedefs( ObjectType &object )
{
typename ObjectType::value_type::String_type name = object[0].name_;
typename ObjectType::value_type::Value_type value = object[0].value_;
}
void check_pair_typedefs()
{
Object o;
check_pair_typedefs( o );
#ifndef BOOST_NO_STD_WSTRING
wObject wo;
check_pair_typedefs( wo );
#endif
}
void test_obj_map_implemention()
{
mObject obj;
obj[ "name 1" ] = 1;
obj[ "name 2" ] = "two";
assert_eq( obj.size(), 2u );
assert_eq( obj.find( "name 1" )->second.get_int(), 1 );
assert_eq( obj.find( "name 2" )->second.get_str(), "two" );
}
template< typename Int >
void check_an_int_is_a_real( Int i, bool expected_result )
{
assert_eq( Value( i ).is_uint64(), expected_result );
}
void test_is_uint64()
{
check_an_int_is_a_real( 1, false );
check_an_int_is_a_real( static_cast< int64_t >( 1 ), false );
check_an_int_is_a_real( static_cast< uint64_t >( 1 ), true );
}
template< typename Int >
void check_an_int_is_a_real( Int i, double expected_result )
{
assert_eq( Value( i ).get_real(), expected_result );
}
void test_an_int_is_a_real()
{
check_an_int_is_a_real( -1, -1.0 );
check_an_int_is_a_real( 0, 0.0 );
check_an_int_is_a_real( 1, 1.0 );
check_an_int_is_a_real( max_int64, 9223372036854775800.0 );
check_an_int_is_a_real( max_uint64, 18446744073709552000.0 );
}
}
void json_spirit::test_value()
{
Object obj;
Value value_str ( "value" );
Value value_obj ( obj );
Value value_bool( true );
Value value_str_2 ( string( "value" ) );
Value value_obj_2 ( obj );
Value value_bool_2( false );
const char* str( "value" );
Value value_str_2b ( str );
assert_eq( value_str, value_str );
assert_eq( value_str, value_str_2 );
assert_eq( value_str, value_str_2b );
assert_eq( value_obj, value_obj );
assert_eq( value_obj, value_obj_2 );
assert_neq( value_str, value_obj );
assert_neq( value_str, value_bool );
Object obj_2;
obj_2.push_back( Pair( "name", value_str ) );
Value value_str_3( "xxxxx" );
Value value_obj_3( obj_2 );
assert_neq( value_str, value_str_3 );
assert_neq( value_obj, value_obj_3 );
test_obj_value();
test_array_value();
test_bool_value();
test_int_value();
test_real_value();
test_null_value();
test_get_value();
test_copying();
test_obj_map_implemention();
test_is_uint64();
test_an_int_is_a_real();
}
|
[
"[email protected]"
] |
[
[
[
1,
361
]
]
] |
699ec53a7d6b3fa01dc7c35549f0f075976fc6f7
|
dde32744a06bb6697823975956a757bd6c666e87
|
/bwapi/SCProjects/BTHAIModule/Source/TerranCommander.h
|
b754abddda611f17852ca425d23a68ee6690810c
|
[] |
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 | 1,308 |
h
|
#ifndef __TERRANCOMMANDER_H__
#define __TERRANCOMMANDER_H__
#include "Commander.h"
using namespace BWAPI;
using namespace std;
/** This is the Terran implementation of the Commander class. See
* Commander for more info.
*
* Author: Johan Hagelback ([email protected])
*/
class TerranCommander : public Commander {
private:
public:
TerranCommander();
~TerranCommander();
/** Called each update to issue orders. */
void computeActions();
/** Checks if there are any unfinished buildings that does not have an SCV working on them. Terran only. */
bool checkUnfinishedBuildings();
/** Check if there are any important buildings or units to repair. */
bool checkRepairUnits();
/** Returns true if the unit is important to assist, false if not. All buildings and large expensive units
* such as siege tanks and battlecruisers are considered important, while small units such as marines and
* vultures are not considered important. */
bool isImportantUnit(Unit* unit);
/** Assigns a worker to repair the specified agent. */
void repair(BaseAgent* agent);
/** Assigns a worker to finish constructing an interrupted building. */
void finishBuild(BaseAgent* agent);
void addMainAttackSquad();
void addBunkerSquad();
};
#endif
|
[
"rymdpung@.(none)"
] |
[
[
[
1,
47
]
]
] |
474ca22c6042218e73f563fcbfc60aad1c4bd863
|
90aa2eebb1ab60a2ac2be93215a988e3c51321d7
|
/castor/branches/boost/libs/castor/test/test_family.h
|
e1737a5f1ec8f18c6149b9143cc82dd2cf7e7335
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
roshannaik/castor
|
b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6
|
e86e2bf893719bf3164f9da9590217c107cbd913
|
refs/heads/master
| 2021-04-18T19:24:38.612073 | 2010-08-18T05:10:39 | 2010-08-18T05:10:39 | 126,150,539 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,485 |
h
|
#include <boost/castor.h>
#include <boost/test/minimal.hpp>
using namespace castor;
// (mother1, father1) => (son1 and daughter1)
// (mother2, father2) => (son2 and daughter2)
// (gmother2, gfather2) => (father2)
relation child(lref<std::string> progeny, lref<std::string> mother, lref<std::string> father) {
return eq(progeny, "son1") && eq(mother, "mother1") && eq(father, "father1")
|| eq(progeny, "daughter1") && eq(mother, "mother1") && eq(father, "father1")
|| eq(progeny, "son2") && eq(mother, "mother2") && eq(father, "father2")
|| eq(progeny, "daughter2") && eq(mother, "mother2") && eq(father, "father2")
|| eq(progeny, "father2") && eq(mother, "gmother2") && eq(father, "gfather2");
}
relation mother(lref<std::string> ch, lref<std::string> mom) {
lref<std::string> x;
return child(ch, mom, x);
}
relation father(lref<std::string> ch, lref<std::string> pop) {
lref<std::string> x;
return child(ch, x, pop);
}
relation parent(lref<std::string> par, lref<std::string> kid) {
return father(kid, par) || mother(kid, par);
}
relation ancestor(lref<std::string> ans, lref<std::string> des) {
lref<std::string> X;
return parent(ans, des) || parent(X, des) && recurse(ancestor, ans, X);
}
relation spouse(lref<std::string> husband, lref<std::string> wife) {
lref<std::string> child;
return father(child, husband) && mother(child, wife);
}
|
[
"[email protected]"
] |
[
[
[
1,
41
]
]
] |
17eb1290e023e33862a74815e8ea52e4c7842bec
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Dependencies/Xerces/include/xercesc/framework/XMLGrammarDescription.hpp
|
670968112b9227bf3e68cf2f96d5a1f9c5e0c234
|
[] |
no_license
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,328 |
hpp
|
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: XMLGrammarDescription.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(XMLGRAMMARDESCRIPTION_HPP)
#define XMLGRAMMARDESCRIPTION_HPP
#include <xercesc/util/XMemory.hpp>
#include <xercesc/validators/common/Grammar.hpp>
#include <xercesc/internal/XSerializable.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLPARSER_EXPORT XMLGrammarDescription : public XSerializable, public XMemory
{
public :
// -----------------------------------------------------------------------
/** @name Virtual destructor for derived classes */
// -----------------------------------------------------------------------
//@{
/**
* virtual destructor
*
*/
virtual ~XMLGrammarDescription();
//@}
// -----------------------------------------------------------------------
/** @name The Grammar Description Interface */
// -----------------------------------------------------------------------
//@{
/**
* getGrammarType
*
*/
virtual Grammar::GrammarType getGrammarType() const = 0;
/**
* getGrammarKey
*
*/
virtual const XMLCh* getGrammarKey() const = 0;
//@}
inline MemoryManager* getMemoryManager() const;
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(XMLGrammarDescription)
protected :
// -----------------------------------------------------------------------
/** Hidden Constructors */
// -----------------------------------------------------------------------
//@{
XMLGrammarDescription(MemoryManager* const memMgr = XMLPlatformUtils::fgMemoryManager);
//@}
private :
// -----------------------------------------------------------------------
/** name Unimplemented copy constructor and operator= */
// -----------------------------------------------------------------------
//@{
XMLGrammarDescription(const XMLGrammarDescription& );
XMLGrammarDescription& operator=(const XMLGrammarDescription& );
//@}
// -----------------------------------------------------------------------
//
// fMemMgr: plugged-in (or defaulted-in) memory manager,
// not owned
// no reset after initialization
// allow derivatives to access directly
//
// -----------------------------------------------------------------------
MemoryManager* const fMemMgr;
};
inline MemoryManager* XMLGrammarDescription::getMemoryManager() const
{
return fMemMgr;
}
XERCES_CPP_NAMESPACE_END
#endif
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
104
]
]
] |
93721809d78f7e551ccccc1f7ea7ea01e2e677bb
|
81e051c660949ac0e89d1e9cf286e1ade3eed16a
|
/quake3ce/code/renderer/tr_marks.cpp
|
e50cbc582a18d4d7441d6c207a503bc1fb46f718
|
[] |
no_license
|
crioux/q3ce
|
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
|
5e724f55940ac43cb25440a65f9e9e12220c9ada
|
refs/heads/master
| 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 14,631 |
cpp
|
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// tr_marks.c -- polygon projection on the world polygons
#include"renderer_pch.h"
#define MAX_VERTS_ON_POLY 64
#define MARKER_OFFSET 0 // 1
/*
=============
R_ChopPolyBehindPlane
Out must have space for two more vertexes than in
=============
*/
#define SIDE_FRONT 0
#define SIDE_BACK 1
#define SIDE_ON 2
static void R_ChopPolyBehindPlane( int numInPoints, bvec3_t inPoints[MAX_VERTS_ON_POLY],
int *numOutPoints, bvec3_t outPoints[MAX_VERTS_ON_POLY],
avec3_t normal, bvec_t dist, bvec_t epsilon) {
bfixed dists[MAX_VERTS_ON_POLY+4];
int sides[MAX_VERTS_ON_POLY+4];
int counts[3];
bfixed dot;
int i, j;
bfixed *p1, *p2, *clip;
bfixed d;
// don't clip if it might overflow
if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) {
*numOutPoints = 0;
return;
}
counts[0] = counts[1] = counts[2] = 0;
// determine sides for each point
for ( i = 0 ; i < numInPoints ; i++ ) {
dot = FIXED_VEC3DOT( inPoints[i], normal );
dot -= dist;
dists[i] = dot;
if ( dot > epsilon ) {
sides[i] = SIDE_FRONT;
} else if ( dot < -epsilon ) {
sides[i] = SIDE_BACK;
} else {
sides[i] = SIDE_ON;
}
counts[sides[i]]++;
}
sides[i] = sides[0];
dists[i] = dists[0];
*numOutPoints = 0;
if ( !counts[0] ) {
return;
}
if ( !counts[1] ) {
*numOutPoints = numInPoints;
Com_Memcpy( outPoints, inPoints, numInPoints * sizeof(bvec3_t) );
return;
}
for ( i = 0 ; i < numInPoints ; i++ ) {
p1 = inPoints[i];
clip = outPoints[ *numOutPoints ];
if ( sides[i] == SIDE_ON ) {
VectorCopy( p1, clip );
(*numOutPoints)++;
continue;
}
if ( sides[i] == SIDE_FRONT ) {
VectorCopy( p1, clip );
(*numOutPoints)++;
clip = outPoints[ *numOutPoints ];
}
if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) {
continue;
}
// generate a split point
p2 = inPoints[ (i+1) % numInPoints ];
d = dists[i] - dists[i+1];
if ( d == BFIXED_0 ) {
dot = BFIXED_0;
} else {
dot = dists[i] / d;
}
// clip xyz
for (j=0 ; j<3 ; j++) {
clip[j] = p1[j] + dot * ( p2[j] - p1[j] );
}
(*numOutPoints)++;
}
}
/*
=================
R_BoxSurfaces_r
=================
*/
void R_BoxSurfaces_r(mnode_t *node, bvec3_t mins, bvec3_t maxs, surfaceType_t **list, int listsize, int *listlength, avec3_t dir) {
int s, c;
msurface_t *surf, **mark;
// do the tail recursion in a loop
while ( node->contents == -1 ) {
s = BoxOnPlaneSide( mins, maxs, node->plane );
if (s == 1) {
node = node->children[0];
} else if (s == 2) {
node = node->children[1];
} else {
R_BoxSurfaces_r(node->children[0], mins, maxs, list, listsize, listlength, dir);
node = node->children[1];
}
}
// add the individual surfaces
mark = node->firstmarksurface;
c = node->nummarksurfaces;
while (c--) {
//
if (*listlength >= listsize) break;
//
surf = *mark;
// check if the surface has NOIMPACT or NOMARKS set
if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) )
|| ( surf->shader->contentFlags & CONTENTS_FOG ) ) {
surf->viewCount = tr.viewCount;
}
// extra check for surfaces to avoid list overflows
else if (*(surf->data) == SF_FACE) {
// the face plane should go through the box
s = BoxOnPlaneSide( mins, maxs, &(( srfSurfaceFace_t * ) surf->data)->plane );
if (s == 1 || s == 2) {
surf->viewCount = tr.viewCount;
} else if (FIXED_VEC3DOT((( srfSurfaceFace_t * ) surf->data)->plane.normal, dir) > -AFIXED(0,5)) {
// don't add faces that make sharp angles with the projection direction
surf->viewCount = tr.viewCount;
}
}
else if (*(surfaceType_t *) (surf->data) != SF_GRID) surf->viewCount = tr.viewCount;
// check the viewCount because the surface may have
// already been added if it spans multiple leafs
if (surf->viewCount != tr.viewCount) {
surf->viewCount = tr.viewCount;
list[*listlength] = (surfaceType_t *) surf->data;
(*listlength)++;
}
mark++;
}
}
/*
=================
R_AddMarkFragments
=================
*/
void R_AddMarkFragments(int numClipPoints, bvec3_t clipPoints[2][MAX_VERTS_ON_POLY],
int numPlanes, avec3_t *normals, bfixed *dists,
int maxPoints, bvec3_t pointBuffer,
int maxFragments, markFragment_t *fragmentBuffer,
int *returnedPoints, int *returnedFragments,
bvec3_t mins, bvec3_t maxs) {
int pingPong, i;
markFragment_t *mf;
// chop the surface by all the bounding planes of the to be projected polygon
pingPong = 0;
for ( i = 0 ; i < numPlanes ; i++ ) {
R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong],
&numClipPoints, clipPoints[!pingPong],
normals[i], dists[i], BFIXED(0,5) );
pingPong ^= 1;
if ( numClipPoints == 0 ) {
break;
}
}
// completely clipped away?
if ( numClipPoints == 0 ) {
return;
}
// add this fragment to the returned list
if ( numClipPoints + (*returnedPoints) > maxPoints ) {
return; // not enough space for this polygon
}
/*
// all the clip points should be within the bounding box
for ( i = 0 ; i < numClipPoints ; i++ ) {
int j;
for ( j = 0 ; j < 3 ; j++ ) {
if (clipPoints[pingPong][i][j] < mins[j] - GFIXED(0,5)) break;
if (clipPoints[pingPong][i][j] > maxs[j] + GFIXED(0,5)) break;
}
if (j < 3) break;
}
if (i < numClipPoints) return;
*/
mf = fragmentBuffer + (*returnedFragments);
mf->firstPoint = (*returnedPoints);
mf->numPoints = numClipPoints;
Com_Memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(bvec3_t) );
(*returnedPoints) += numClipPoints;
(*returnedFragments)++;
}
/*
=================
R_MarkFragments
=================
*/
int R_MarkFragments( int numPoints, const bvec3_t *points, const bvec3_t projection,
int maxPoints, bvec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) {
int numsurfaces, numPlanes;
int i, j, k, m, n;
surfaceType_t *surfaces[64];
bvec3_t mins, maxs;
int returnedFragments;
int returnedPoints;
avec3_t normals[MAX_VERTS_ON_POLY+2];
bfixed dists[MAX_VERTS_ON_POLY+2];
bvec3_t clipPoints[2][MAX_VERTS_ON_POLY];
int numClipPoints;
fixed32 *v;
srfSurfaceFace_t *surf;
srfGridMesh_t *cv;
drawVert_t *dv;
bvec3_t normal;
avec3_t projectionDir;
bvec3_t v1, v2;
int *indexes;
//increment view count for lfixed check prevention
tr.viewCount++;
//
VectorNormalizeB2A( projection, projectionDir );
// find all the brushes that are to be considered
ClearBounds( mins, maxs );
for ( i = 0 ; i < numPoints ; i++ ) {
bvec3_t temp;
AddPointToBounds( points[i], mins, maxs );
VectorAdd( points[i], projection, temp );
AddPointToBounds( temp, mins, maxs );
// make sure we get all the leafs (also the one(s) in front of the hit surface)
FIXED_VEC3MA_R( points[i], -BFIXED(20,0), projectionDir, temp );
AddPointToBounds( temp, mins, maxs );
}
if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY;
// create the bounding planes for the to be projected polygon
for ( i = 0 ; i < numPoints ; i++ ) {
VectorSubtract(points[(i+1)%numPoints], points[i], v1);
VectorAdd(points[i], projection, v2);
VectorSubtract(points[i], v2, v2);
bvec3_t tmp;
CrossProduct(v1, v2, tmp);
FIXED_FASTVEC3NORM(tmp);
normals[i][0]=MAKE_AFIXED(tmp[0]);
normals[i][1]=MAKE_AFIXED(tmp[1]);
normals[i][2]=MAKE_AFIXED(tmp[2]);
dists[i] = FIXED_VEC3DOT_R(normals[i], points[i]);
}
// add near and far clipping planes for projection
VectorCopy(projectionDir, normals[numPoints]);
dists[numPoints] = FIXED_VEC3DOT_R(normals[numPoints], points[0]) - BFIXED(32,0);
VectorCopy(projectionDir, normals[numPoints+1]);
VectorInverse(normals[numPoints+1]);
dists[numPoints+1] = FIXED_VEC3DOT_R(normals[numPoints+1], points[0]) - BFIXED(20,0);
numPlanes = numPoints + 2;
numsurfaces = 0;
R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir);
//assert(numsurfaces <= 64);
//assert(numsurfaces != 64);
returnedPoints = 0;
returnedFragments = 0;
for ( i = 0 ; i < numsurfaces ; i++ ) {
if (*surfaces[i] == SF_GRID) {
cv = (srfGridMesh_t *) surfaces[i];
for ( m = 0 ; m < cv->height - 1 ; m++ ) {
for ( n = 0 ; n < cv->width - 1 ; n++ ) {
// We triangulate the grid and chop all triangles within
// the bounding planes of the to be projected polygon.
// LOD is not taken into account, not such a big deal though.
//
// It's probably much nicer to chop the grid itself and deal
// with this grid as a normal SF_GRID surface so LOD will
// be applied. However the LOD of that chopped grid must
// be synced with the LOD of the original curve.
// One way to do this; the chopped grid shares vertices with
// the original curve. When LOD is applied to the original
// curve the unused vertices are flagged. Now the chopped curve
// should skip the flagged vertices. This still leaves the
// problems with the vertices at the chopped grid edges.
//
// To avoid issues when LOD applied to "hollow curves" (like
// the ones around many jump pads) we now just add a 2 unit
// offset to the triangle vertices.
// The offset is added in the vertex normal vector direction
// so all triangles will still fit together.
// The 2 unit offset should avoid pretty much all LOD problems.
numClipPoints = 3;
dv = cv->verts + m * cv->width + n;
VectorCopy(dv[0].xyz, clipPoints[0][0]);
FIXED_VEC3MA_R(clipPoints[0][0], BFIXED(MARKER_OFFSET,0), dv[0].normal, clipPoints[0][0]);
VectorCopy(dv[cv->width].xyz, clipPoints[0][1]);
FIXED_VEC3MA_R(clipPoints[0][1], BFIXED(MARKER_OFFSET,0), dv[cv->width].normal, clipPoints[0][1]);
VectorCopy(dv[1].xyz, clipPoints[0][2]);
FIXED_VEC3MA_R(clipPoints[0][2], BFIXED(MARKER_OFFSET,0), dv[1].normal, clipPoints[0][2]);
// check the normal of this triangle
VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
CrossProduct(v1, v2, normal);
FIXED_FASTVEC3NORM(normal);
if (FIXED_VEC3DOT(normal, projectionDir) < -BFIXED(0,1)) {
// add the fragments of this triangle
R_AddMarkFragments(numClipPoints, clipPoints,
numPlanes, normals, dists,
maxPoints, pointBuffer,
maxFragments, fragmentBuffer,
&returnedPoints, &returnedFragments, mins, maxs);
if ( returnedFragments == maxFragments ) {
return returnedFragments; // not enough space for more fragments
}
}
VectorCopy(dv[1].xyz, clipPoints[0][0]);
FIXED_VEC3MA_R(clipPoints[0][0], BFIXED(MARKER_OFFSET,0), dv[1].normal, clipPoints[0][0]);
VectorCopy(dv[cv->width].xyz, clipPoints[0][1]);
FIXED_VEC3MA_R(clipPoints[0][1], BFIXED(MARKER_OFFSET,0), dv[cv->width].normal, clipPoints[0][1]);
VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]);
FIXED_VEC3MA_R(clipPoints[0][2], BFIXED(MARKER_OFFSET,0), dv[cv->width+1].normal, clipPoints[0][2]);
// check the normal of this triangle
VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
CrossProduct(v1, v2, normal);
FIXED_FASTVEC3NORM(normal);
if (FIXED_VEC3DOT(normal, projectionDir) < -BFIXED(0,05)) {
// add the fragments of this triangle
R_AddMarkFragments(numClipPoints, clipPoints,
numPlanes, normals, dists,
maxPoints, pointBuffer,
maxFragments, fragmentBuffer,
&returnedPoints, &returnedFragments, mins, maxs);
if ( returnedFragments == maxFragments ) {
return returnedFragments; // not enough space for more fragments
}
}
}
}
}
else if (*surfaces[i] == SF_FACE) {
surf = ( srfSurfaceFace_t * ) surfaces[i];
// check the normal of this face
if (FIXED_VEC3DOT(surf->plane.normal, projectionDir) > -AFIXED(0,5)) {
continue;
}
/*
VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
CrossProduct(v1, v2, normal);
VectorNormalize(normal);
if (FIXED_VEC3DOT(normal, projectionDir) > -BFIXED(0,5)) continue;
*/
indexes = (int *)( (byte *)surf + surf->ofsIndices );
for ( k = 0 ; k < surf->numIndices ; k += 3 ) {
for ( j = 0 ; j < 3 ; j++ ) {
v = surf->points[0] + VERTEXSIZE * indexes[k+j];;
FIXED_VEC3MA_R( (const bfixed *)v, BFIXED(MARKER_OFFSET,0), surf->plane.normal, clipPoints[0][j] );
}
// add the fragments of this face
R_AddMarkFragments( 3 , clipPoints,
numPlanes, normals, dists,
maxPoints, pointBuffer,
maxFragments, fragmentBuffer,
&returnedPoints, &returnedFragments, mins, maxs);
if ( returnedFragments == maxFragments ) {
return returnedFragments; // not enough space for more fragments
}
}
continue;
}
else {
// ignore all other world surfaces
// might be cool to also project polygons on a triangle soup
// however this will probably create huge amounts of extra polys
// even more than the projection onto curves
continue;
}
}
return returnedFragments;
}
|
[
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac"
] |
[
[
[
1,
446
]
]
] |
3a85c3e0735f3aca732873691f72ea4ab353777f
|
b9847347f881bf3e599a8572dce35f44412bec69
|
/test/3rdparty/testngppst/src/runner/win32/TestCaseSandboxRunnerMain.cpp
|
4b0030798eb248194e723de5be75ace131ba224c
|
[] |
no_license
|
arthuryuan/TestNG--
|
617c66cd1ec402442bcf39181b33ee453628cf26
|
cf4a3265f7dd258e3c5c1676eac0fc775b712802
|
refs/heads/master
| 2020-05-17T11:53:25.637678 | 2010-02-21T17:03:02 | 2010-02-21T17:03:02 | 500,992 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,810 |
cpp
|
#include <string>
#include <iostream>
#include <windows.h>
#include <testngppst/ExceptionKeywords.h>
#include <testngppst/comm/Win32PipeWrittableChannel.h>
#include <testngppst/runner/TestCaseSandboxResultReporter.h>
#include <testngppst/runner/loaders/ModuleTestSuiteLoaderFactory.h>
#include <testngppst/runner/TestFilter.h>
#include <testngppst/runner/TestFilterFactory.h>
#include <testngppst/runner/TagsFilters.h>
#include <testngppst/runner/TagsParser.h>
#include <testngppst/runner/TestRunnerContext.h>
#include <testngppst/runner/TestSuiteRunner.h>
#include <testngppst/runner/TestFixtureRunner.h>
#include <testngppst/runner/TestFixtureRunnerFactory.h>
#include <testngppst/win32/Win32TestCaseRunnerResultReporter.h>
void usage()
{
std::cerr << "Usage: testngppst-win32-testcase-runner.exe testsuite fixture testcase" << std::endl;
ExitProcess(1);
}
TESTNGPPST_NS::TestCaseRunnerResultReporter*
createCollector(HANDLE hWrite, HANDLE hSemaphore)
{
if(hWrite == 0)
{
hWrite = GetStdHandle(STD_OUTPUT_HANDLE);
if (hWrite == INVALID_HANDLE_VALUE)
{
ExitProcess(1);
}
}
return new TESTNGPPST_NS::TestCaseRunnerResultReporter(hSemaphore,
new TESTNGPPST_NS::TestCaseSandboxResultReporter(
new TESTNGPPST_NS::Win32PipeWrittableChannel(hWrite)));
}
const TESTNGPPST_NS::TestFilter*
createFilter
( const std::string& fixtureName
, const std::string& testcaseName)
{
TESTNGPPST_NS::StringList filterPattern;
filterPattern.add(fixtureName + ":" + testcaseName);
return TESTNGPPST_NS::TestFilterFactory::getFilter(filterPattern);
}
int runTest
( TESTNGPPST_NS::TestCaseRunnerResultReporter* collector
, const std::string& suiteName
, const std::string& fixtureName
, const std::string& testcaseName)
{
std::cout << "testcase name : " << testcaseName << std::endl;
const TESTNGPPST_NS::TestFilter* filter = createFilter(fixtureName, testcaseName);
TESTNGPPST_NS::TagsFilters* tagsFilter = TESTNGPPST_NS::TagsParser::parse("*");
TESTNGPPST_NS::TestFixtureRunner* fixtureRunner = 0;
TESTNGPPST_NS::TestSuiteRunner* suiteRunner = 0;
TESTNGPPST_NS::TestRunnerContext* context = 0;
TESTNGPPST_NS::StringList suites;
suites.add(suiteName);
int result = 0;
__TESTNGPPST_TRY
context = new TESTNGPPST_NS::TestRunnerContext
( suites
, collector
, tagsFilter
, filter);
fixtureRunner = TESTNGPPST_NS::TestFixtureRunnerFactory::createInstance(false, 1);
suiteRunner = new TESTNGPPST_NS::TestSuiteRunner(fixtureRunner, collector);
if(!tagsFilter->startOnNext())
{
std::cerr << "internal error" << std::endl;
}
////////////////////////////////////////////////////
suiteRunner->run(context->getSuite(0), filter);
////////////////////////////////////////////////////
__TESTNGPPST_CATCH_ALL
result = -1;
__TESTNGPPST_FINALLY
if(context != 0)
{
delete context;
}
if(suiteRunner != 0)
{
delete suiteRunner;
}
if(fixtureRunner != 0)
{
delete fixtureRunner;
}
__TESTNGPPST_DONE
delete tagsFilter;
TESTNGPPST_NS::TestFilterFactory::returnFilter(filter);
return result;
}
int main(int argc, char* argv[])
{
if(argc != 6 && argc != 4)
{
usage();
}
std::cout << "start to run " << std::endl;
std::string suite(argv[1]);
std::string fixture(argv[2]);
std::string testcase(argv[3]);
HANDLE hWrite = 0;
HANDLE hSemap = 0;
if(argc == 6)
{
hWrite = (HANDLE)atoi(argv[4]);
hSemap = (HANDLE)atoi(argv[5]);
}
return
runTest(createCollector(hWrite, hSemap), suite, fixture, testcase);
}
|
[
"[email protected]"
] |
[
[
[
1,
143
]
]
] |
abf586969c214ec270427e91aa75a536fdda1e2a
|
869aa4b1261e60a745cf4c7f32c96a9d5d4f1c47
|
/release-5.0.1/plugin/internet_download_manager.cc
|
f18c070fb1974184b5a8805b2c4d8708310e3f57
|
[] |
no_license
|
anmaz/chrome-download-assistant
|
d45dc4f8a8e09f564a5e4eee209b936a67d031d6
|
a4ab1eed1b4e7ef1a905a9988c6cd29d21c6a2bd
|
refs/heads/master
| 2021-01-01T06:38:29.035202 | 2011-06-24T04:25:04 | 2011-06-24T04:25:04 | 34,250,585 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,156 |
cc
|
#include "internet_download_manager.h"
#include <comutil.h>
#include <tchar.h>
#include "log.h"
#include "utils.h"
extern Log g_logger;
NPObject* InternetDownloadManager::Allocate(NPP npp, NPClass *aClass) {
InternetDownloadManager* idm = new InternetDownloadManager;
char logs[256];
sprintf_s(logs, "InternetDownloadManager this=%ld", idm);
g_logger.WriteLog("Allocate", logs);
if (idm != NULL) {
idm->set_plugin((PluginBase*)npp->pdata);
}
return idm;
}
void InternetDownloadManager::Deallocate() {
char logs[256];
sprintf_s(logs, "InternetDownloadManager this=%ld", this);
g_logger.WriteLog("Deallocate", logs);
delete this;
}
void InternetDownloadManager::InitHandler() {
FunctionItem item;
item.function_name = "Download";
item.function_pointer = ON_INVOKEHELPER(&InternetDownloadManager::Download);
AddFunction(item);
item.function_name = "DownloadAll";
item.function_pointer = ON_INVOKEHELPER(&InternetDownloadManager::
DownloadAll);
AddFunction(item);
}
bool InternetDownloadManager::CheckObject() {
TCHAR idm_exe_path[MAX_PATH];
DWORD buffer_len = sizeof(idm_exe_path);
HKEY hkey;
if (RegOpenKey(HKEY_CURRENT_USER, L"Software\\DownloadManager", &hkey))
return false;
if (RegQueryValueEx(hkey, L"ExePath", NULL, NULL, (LPBYTE)idm_exe_path,
&buffer_len)) {
RegCloseKey(hkey);
return false;
}
RegCloseKey(hkey);
if (_taccess(idm_exe_path, 0))
return false;
return true;
}
bool InternetDownloadManager::Download(const NPVariant *args,
uint32_t argCount,
NPVariant *result) {
if (argCount != 1 || !NPVARIANT_IS_STRING(args[0]))
return false;
BOOLEAN_TO_NPVARIANT(FALSE, *result);
HRESULT hr = CoCreateInstance(__uuidof(CIDMLinkTransmitter), NULL,
CLSCTX_SERVER, __uuidof(ICIDMLinkTransmitter2), (LPVOID*)&disp_pointer_);
if (hr != S_OK)
return false;
_bstr_t url = NPVARIANT_TO_STRING(args[0]).UTF8Characters;
MultiByteToWideChar(CP_UTF8, 0, NPVARIANT_TO_STRING(args[0]).UTF8Characters,
-1, url, url.length() + 1);
VARIANT reserved;
reserved.vt=VT_EMPTY;
hr = disp_pointer_->SendLinkToIDM2(url, "", "", "", "", "", "",
"", 0, reserved, reserved);
if (hr == S_OK)
BOOLEAN_TO_NPVARIANT(true, *result);
disp_pointer_->Release();
return true;
}
bool InternetDownloadManager::DownloadAll(const NPVariant *args,
uint32_t argCount,
NPVariant *result) {
if (argCount != 3 || !NPVARIANT_IS_OBJECT(args[0]) ||
!NPVARIANT_IS_OBJECT(args[1]) || !NPVARIANT_IS_STRING(args[2]))
return false;
HRESULT hr = CoCreateInstance(__uuidof(CIDMLinkTransmitter), NULL,
CLSCTX_SERVER, __uuidof(ICIDMLinkTransmitter2), (LPVOID*)&disp_pointer_);
if (hr != S_OK)
return false;
PluginBase* plugin = get_plugin();
NPObject* linkObj = NPVARIANT_TO_OBJECT(args[0]);
NPObject* commentObj = NPVARIANT_TO_OBJECT(args[1]);
NPIdentifier id = NPN_GetStringIdentifier("length");
NPVariant ret;
if (NPN_GetProperty(plugin->get_npp(), linkObj, id, &ret) &&
(NPVARIANT_IS_INT32(ret) || NPVARIANT_IS_DOUBLE(ret))) {
int array_len = NPVARIANT_IS_INT32(ret) ?
NPVARIANT_TO_INT32(ret) : NPVARIANT_TO_DOUBLE(ret);
SAFEARRAY* sa = NULL;
SAFEARRAYBOUND bound[2];
bound[0].lLbound = 0;
bound[0].cElements = array_len;
bound[1].lLbound = 0;
bound[1].cElements = 4;
sa = SafeArrayCreate(VT_BSTR, 2, bound);
if (!sa)
return false;
long index[2];
_bstr_t url, cookie(""), comment, refer;
refer = NPVARIANT_TO_STRING(args[2]).UTF8Characters;
for (int i = 0; i < array_len; i++) {
id = NPN_GetIntIdentifier(i);
NPN_GetProperty(plugin->get_npp(), linkObj, id, &ret);
if (!NPVARIANT_IS_STRING(ret))
continue;
const char* array_item = NPVARIANT_TO_STRING(ret).UTF8Characters;
url = array_item;
MultiByteToWideChar(CP_UTF8, 0, array_item, -1,
url, url.length() + 1);
NPN_GetProperty(plugin->get_npp(), commentObj, id, &ret);
if (!NPVARIANT_IS_STRING(ret))
continue;
array_item = NPVARIANT_TO_STRING(ret).UTF8Characters;
comment = array_item;
MultiByteToWideChar(CP_UTF8, 0, array_item, -1,
comment, comment.length() + 1);
index[0] = i;
index[1] = 0;
SafeArrayPutElement(sa, index, (BSTR)url);
index[1] = 1;
SafeArrayPutElement(sa, index, (BSTR)cookie);
index[1] = 2;
SafeArrayPutElement(sa, index, (BSTR)comment);
index[1] = 3;
SafeArrayPutElement(sa, index, NULL);
}
VARIANT array;
VariantInit(&array);
array.vt = VT_ARRAY | VT_BSTR;
array.parray = sa;
disp_pointer_->SendLinksArray(refer, &array);
SafeArrayDestroy(sa);
}
disp_pointer_->Release();
return true;
}
|
[
"[email protected]@a0d43ee6-04fa-a5ec-bf34-aeaa1c2c5ca5"
] |
[
[
[
1,
158
]
]
] |
b9a8fa227f03d48449464232fe3076b62257137c
|
86bb1666e703b6be9896166d1b192a20f4a1009c
|
/source/bbn/BBN_Given.cpp
|
70150cd91717b57621330c4c436bbe65291fd0f1
|
[] |
no_license
|
aggronerd/Mystery-Game
|
39f366e9b78b7558f5f9b462a45f499060c87d7f
|
dfd8220e03d552dc4e0b0f969e8be03cf67ba048
|
refs/heads/master
| 2021-01-10T21:15:15.318110 | 2010-08-22T09:16:08 | 2010-08-22T09:16:08 | 2,344,888 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,120 |
cpp
|
#include <vector>
#include <exception>
#include "BBN_Given.h"
#include "BBN_Prob.h"
#include "BBN_Exception.h"
#include "BBN_Decision.h"
#include "BBN_Plot.h"
#include "BBN_Option.h"
#include "../misc/logging.h"
BBN_Given::BBN_Given(BBN_Decision* decision)
{
DEBUG_MSG("BBN_Given::BBN_Given(BBN_Decision*) - Called.")
_decision = decision;
}
BBN_Given::~BBN_Given()
{
DEBUG_MSG("BBN_Given::~BBN_Given() - Called.")
// Delete all givens
std::vector<BBN_Given*>::iterator it_gi;
for(it_gi = _givens.begin(); it_gi != _givens.end(); ++it_gi)
delete (*it_gi);
_givens.clear();
// Delete all givens
std::vector<BBN_Prob*>::iterator it_pr;
for(it_pr = _probs.begin(); it_pr != _probs.end(); ++it_pr)
delete (*it_pr);
_probs.clear();
_decision = 0x0;
}
void BBN_Given::load_from_xml(CL_DomElement element)
{
DEBUG_MSG("BBN_Given::load_from_xml(CL_DomElement) - Called.")
//Retrieve attributes
_option = element.get_attribute("option");
DEBUG_MSG("BBN_Given::load_from_xml(CL_DomElement) - Given option = '"+_option+"'.")
//Fetch the first child element
CL_DomNode cur = element.get_first_child();
CL_DomNode curChild;
/*
* Loop through first elements.
*/
while (!cur.is_null())
{
if (cur.get_node_name() == CL_String8("givens"))
{
/*
* <givens></givens>
*/
curChild = cur.get_first_child();
while(!curChild.is_null())
{
if(curChild.get_node_name() == CL_String8("given"))
{
/*
* <given></given>
*/
BBN_Given* given = new BBN_Given(_decision);
CL_DomElement element = curChild.to_element();
given->load_from_xml(element);
add_given(given);
}
curChild = curChild.get_next_sibling();
}
}
if (cur.get_node_name() == CL_String8("probs"))
{
/**
* <probs></probs>
*/
curChild = cur.get_first_child();
while(!curChild.is_null())
{
if(curChild.get_node_name() == CL_String8("prob"))
{
/*
* <prob></prob>
*/
BBN_Prob* prob = new BBN_Prob(_decision);
CL_DomElement element = curChild.to_element();
prob->load_from_xml(element);
add_prob(prob);
}
curChild = curChild.get_next_sibling();
}
}
cur = cur.get_next_sibling();
}
//TODO:Validate
}
void BBN_Given::set_bn_probabilities(dlib::directed_graph<dlib::bayes_node>::kernel_1a_c* bn, dlib::assignment parent_states)
{
//Apply parent states to probability definition for the bayes net.
BBN_Option* option = get_decision()->get_plot()->get_option(_option);
if(option == 0x0)
{
throw(BBN_Exception("Error finding option '" + _option + "' in given for decision " + get_decision()->get_name()));
}
else
{
//Applies given rule to any subsequent recursive calls.
parent_states.add(option->get_decision()->get_id(),option->get_id());
if(_givens.size() > 0)
{
std::vector<BBN_Given*>::iterator it_given;
for(it_given = _givens.begin(); it_given != _givens.end(); ++it_given)
{
(*(it_given))->set_bn_probabilities(get_decision()->get_plot()->get_bn(),parent_states);
}
}
else if(_probs.size() > 0)
{
std::vector<BBN_Prob*>::iterator it_prob;
for(it_prob = _probs.begin(); it_prob != _probs.end(); ++it_prob)
{
(*(it_prob))->set_bn_probability(get_decision()->get_plot()->get_bn(),parent_states);
}
}
else
{
throw(BBN_Exception("No given/prob objects found to extract probabilities from in given for decision '" + get_decision()->get_name() + "' where option = '" + _option + "'."));
}
}
}
BBN_Decision* BBN_Given::get_decision()
{
return(_decision);
}
void BBN_Given::add_given(BBN_Given* given)
{
_givens.push_back(given);
}
void BBN_Given::add_prob(BBN_Prob* prob)
{
_probs.push_back(prob);
}
|
[
"[email protected]"
] |
[
[
[
1,
153
]
]
] |
752236a121158d0c92bf05431149ed15182b5e30
|
8a8873b129313b24341e8fa88a49052e09c3fa51
|
/src/Graphic.cpp
|
043c185c43794fb46116052ce4c2e3d28bc5db5d
|
[] |
no_license
|
flaithbheartaigh/wapbrowser
|
ba09f7aa981d65df810dba2156a3f153df071dcf
|
b0d93ce8517916d23104be608548e93740bace4e
|
refs/heads/master
| 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,160 |
cpp
|
// Canvas.cpp: implementation of the CGraphics class.
//
//////////////////////////////////////////////////////////////////////
#include <bitstd.h>
#include <bitdev.h>
//#include <gdi.h>
#include <aknutils.h>
#include <fontids.hrh>
#include "graphic.h"
#include "CoCoPreDefine.h"
#define ALPHA_COLOR_MASK (0x07E0F81F) //MASK:0000 0,111 11,10 000,0 1111 1,000 00,01 1111
#define KMaxAlpha (0x20)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CGraphic::CGraphic()
{
}
CGraphic::~CGraphic()
{
delete iBmpGc;
delete iBitmapDevice;
delete iBitmap;
}
void CGraphic::ConstructL(const TSize& aSize)
{
iAllSize=aSize;
iFont = AknLayoutUtils::FontFromId(EFontCustom);
iFontHeight = iFont->HeightInPixels();
iBitmap = new (ELeave) CFbsBitmap;
TInt err = iBitmap->Create(aSize,EColor64K);
User::LeaveIfError(err);
iBitmapDevice = CFbsBitmapDevice::NewL(iBitmap);
iBitmapDevice->CreateContext(iBmpGc);
User::LeaveIfError(err);
}
CGraphic* CGraphic::NewL(const TSize& aSize)
{
CGraphic* self = new (ELeave) CGraphic();
CleanupStack::PushL(self);
self->ConstructL(aSize);
CleanupStack::Pop(); // self;
return self;
}
void CGraphic::Clear()
{
iBmpGc->Clear();
}
void CGraphic::Clear(const TRect& aRect)
{
iBmpGc->Clear(aRect);
}
void CGraphic::SetClippingRect(const TRect& aRect)
{
iBmpGc->SetClippingRect(aRect);
}
void CGraphic::SetClippintRegion(const TRegion& aRegion)
{
ASSERT(EFalse);
//iBmpGc->SetClippingRegion(aRegion);
}
void CGraphic::CancelClippingRect()
{
iBmpGc->CancelClipping();
}
void CGraphic::SetPenColor(TRgb aColor)
{
iBmpGc->SetPenColor(aColor);
}
void CGraphic::SetPenStyle(CGraphicsContext::TPenStyle aPenStyle)
{
iBmpGc->SetPenStyle(aPenStyle);
}
void CGraphic::SetBrushColor(TRgb aColor)
{
iBmpGc->SetBrushColor(aColor);
}
void CGraphic::SetBrushStyle(CGraphicsContext::TBrushStyle aPenStyle)
{
iBmpGc->SetBrushStyle(aPenStyle);
}
void CGraphic::DrawText(const TPoint& aPoint,const TDesC& aText )
{
iBmpGc->UseFont(iFont);
TPoint point = aPoint;
point.iY += iFontHeight;
iBmpGc->DrawText(aText,point);
iBmpGc->DiscardFont();
}
void CGraphic::DrawText(const TDesC& aText,const TRect& aBox,CGraphicsContext::TTextAlign aHrz,TInt aMargin)
{
iBmpGc->UseFont(iFont);
TInt baseLine = iFontHeight + ((aBox.Height() - iFontHeight) >> 2);
iBmpGc->DrawText(aText,aBox,baseLine,aHrz,aMargin);
}
void CGraphic::DrawRect(const TRect& aRect )
{
iBmpGc->DrawRect(aRect);
}
void CGraphic::DrawRoundRect(const TRect& aRect)
{
TSize cornerSize(3,3);
iBmpGc->DrawRoundRect(aRect,cornerSize);
}
void CGraphic::BitBlt( const TPoint& aPos,const CFbsBitmap* aBitmap)
{
iBmpGc->BitBlt(aPos,aBitmap);
}
void CGraphic::BitBlt(const TPoint& aPoint,const CFbsBitmap* aBitmap,const TRect& aRect)
{
iBmpGc->BitBlt(aPoint,aBitmap,aRect);
}
void CGraphic::BitBltMasked(const TPoint& aPoint,const CFbsBitmap* aBitmap,const CFbsBitmap* aBitmapMask,TBool aInvertMask)
{
TSize size = aBitmap->SizeInPixels();
iBmpGc->BitBltMasked(aPoint,aBitmap,size,aBitmapMask,aInvertMask);
}
void CGraphic::BitBltMasked(const TPoint& aPoint,const CFbsBitmap* aBitmap,const CFbsBitmap* aBitmapMask,const TRect& aRect,TBool aInvertMask)
{
iBmpGc->BitBltMasked(aPoint,aBitmap,aRect,aBitmapMask,aInvertMask);
}
void CGraphic::DrawLine(TPoint aPos1,TPoint aPos2)
{
iBmpGc->DrawLine(aPos1,aPos2);
}
void CGraphic::DrawText_Bold(TPoint aPos,const TDesC& aText)
{
TRgb argb(0,0,0);
SetPenColor(argb);
iBmpGc->UseFont(iFont);
TInt aFontHeight = iFont->HeightInPixels();
aPos.iY+=aFontHeight;
iBmpGc->DrawText(aText,aPos-TPoint(1,0));
iBmpGc->DrawText(aText,aPos+TPoint(1,0));
iBmpGc->DrawText(aText,aPos-TPoint(0,1));
iBmpGc->DrawText(aText,aPos+TPoint(0,1));
iBmpGc->DrawText(aText,aPos+TPoint(1,1));
iBmpGc->DrawText(aText,aPos+TPoint(1,-1));
iBmpGc->DrawText(aText,aPos+TPoint(-1,1));
iBmpGc->DrawText(aText,aPos+TPoint(-1,1));
TRgb argb1(255,255,255);
SetPenColor(argb1);
iBmpGc->DrawText(aText,aPos);
iBmpGc->DiscardFont();
}
void CGraphic::DrawText_Blue(TPoint aPos,const TDesC& aText)
{
iBmpGc->UseFont(iFont);
TInt aFontHeight = iFont->HeightInPixels();
aPos.iY+=aFontHeight;
TRgb argb(204,204,255);
SetPenColor(argb);
iBmpGc->DrawText(aText,aPos);
TInt width=iFont->MeasureText(aText);
iBmpGc->DrawLine(aPos+TPoint(0,1),aPos+TPoint(width,1));
iBmpGc->DiscardFont();
SetPenColor(KTextColor);
}
void CGraphic::DrawText_Blue(const TDesC& aText,const TRect& aBox,CGraphicsContext::TTextAlign aHrz,TInt aMargin)
{
iBmpGc->UseFont(iFont);
TInt aFontHeight = iFont->HeightInPixels();
TInt baseLine = aFontHeight + ((aBox.Height() - aFontHeight) >> 2);
TRgb argb(204,204,255);
SetPenColor(argb);
iBmpGc->DrawText(aText,aBox,baseLine,aHrz,aMargin);
TPoint point=aBox.iTl;
point.iY+=aBox.Width()-1;
TInt width=iFont->MeasureText(aText);
iBmpGc->DrawLine(point+TPoint(0,1),point+TPoint(width,1));
iBmpGc->DiscardFont();
SetPenColor(KTextColor);
}
void CGraphic::DrawText_Red(const TDesC& aText,const TRect& aBox,CGraphicsContext::TTextAlign aHrz,TInt aMargin)
{
iBmpGc->UseFont(iFont);
TInt aFontHeight = iFont->HeightInPixels();
TInt baseLine = aFontHeight + ((aBox.Height() - aFontHeight) >> 2);
SetPenStyle(CGraphicsContext::ENullPen);
SetBrushColor(TRgb(99,200,255));
SetBrushStyle(CGraphicsContext::ESolidBrush);
iBmpGc->DrawRect(aBox);
SetPenStyle(CGraphicsContext::ESolidPen);
iBmpGc->DrawText(aText,aBox,baseLine,aHrz,aMargin);
TPoint point=aBox.iTl;
point.iY+=aBox.Width()-1;
TInt width=iFont->MeasureText(aText);
iBmpGc->DrawLine(point+TPoint(0,1),point+TPoint(width,1));
iBmpGc->DiscardFont();
SetBrushStyle(CGraphicsContext::ENullBrush);
SetPenColor(KTextColor);
}
void CGraphic::DrawText_Red(TPoint aPos,const TDesC& aText)
{
iBmpGc->UseFont(iFont);
TInt aFontHeight = iFont->HeightInPixels();
aPos.iY+=aFontHeight;
TInt width=iFont->MeasureText(aText);
SetPenStyle(CGraphicsContext::ENullPen);
SetBrushColor(TRgb(99,200,255));
SetBrushStyle(CGraphicsContext::ESolidBrush);
TRect rect(aPos-TPoint(0,iFontHeight), TSize(width,iFontHeight));
iBmpGc->DrawRect(rect);
SetPenStyle(CGraphicsContext::ESolidPen);
iBmpGc->DrawText(aText,aPos);
iBmpGc->DrawLine(aPos+TPoint(0,1),aPos+TPoint(width,1));
iBmpGc->DiscardFont();
SetBrushStyle(CGraphicsContext::ENullBrush);
SetPenColor(KTextColor);
}
void CGraphic::DrawTextWithBlueUnderline( const TPoint& aPoint,const TDesC& aText )
{
iBmpGc->UseFont(iFont);
TPoint point = aPoint;
point.iY += iFont->HeightInPixels();
TRgb argb(204,204,255);
SetPenColor(argb);
iBmpGc->DrawText(aText,point);
TInt i_w= iFont->MeasureText(aText);
iBmpGc->DrawLine(point+TPoint(0,1),point+TPoint(i_w,1));
iBmpGc->DiscardFont();
SetPenColor(KTextColor);
}
TInt CGraphic::MeasureText(const TDesC& aDes) const
{
ASSERT(iFont);
return iFont->MeasureText(aDes);
}
CFbsBitGc& CGraphic::GetBmpGc() const
{
ASSERT(iBmpGc);
return *iBmpGc;
}
const CFont* CGraphic::GetFont() const
{
ASSERT(iFont);
return iFont;
}
const CFbsBitmap* CGraphic::GetOffScreenBitmap() const
{
return iBitmap;
}
TInt CGraphic::FontHeight() const
{
return iFontHeight;
}
TBool CGraphic::AlphaBlend(TPoint pos, CFbsBitmap* image, const TRect& rect, TInt nAlpha)
{
union UColor
{
TUint16 wColor[2];
TUint32 dwColor;
};
TUint16* uSrcBuf = new TUint16[iAllSize.iWidth*2];
TUint8* uSrcBufMask = new TUint8[iAllSize.iWidth*2];
TPtr8 pSrcBuf((TUint8*)(uSrcBuf), sizeof(TUint16)*iAllSize.iWidth*2);
TPtr8 pSrcBufMask(uSrcBufMask, sizeof(TUint8)*iAllSize.iWidth*2);
TUint16* uDesBuf = new TUint16[iAllSize.iWidth*2];
TUint8* uDesBufMask = new TUint8[iAllSize.iWidth*2];
TPtr8 pDesBuf((TUint8*)(uDesBuf), sizeof(TUint16)*iAllSize.iWidth*2);
TPtr8 pDesBufMask(uDesBufMask, sizeof(TUint8)*iAllSize.iWidth*2);
TBool bHasSrcMask =EFalse;// image->HasMask();
TBool bHasDesMask =EFalse;// iBitmap->HasMask();
UColor uSrcColor, uDesColor;
nAlpha = (nAlpha >> 3) & 0x1F;
for (TInt nLine = 0; nLine < rect.Size().iHeight; nLine ++)
{
image->GetScanLine(pSrcBuf, rect.iTl + TPoint(0,nLine), rect.Width(), EColor64K);
//if (bHasSrcMask)
//image->GetScanLineMask(pSrcBufMask, rect.iTl + TPoint(0,nLine), rect.Width(), EColor256);
TUint16* pSrcColor = uSrcBuf;
TUint8* pSrcMask = uSrcBufMask;
GetScanLine(pDesBuf, TPoint(0, pos.iY + nLine), iAllSize.iWidth, EColor64K);
/*if (bHasDesMask)
GetScanLineMask(pDesBufMask, TPoint(0, pos.iY + nLine),iAllSize.iWidth, EColor256);*/
TUint16* pDesColor = &uDesBuf[pos.iX];
TUint8* pDesMask = &uDesBufMask[pos.iX];
for (TInt nCol = 0; nCol < rect.Width(); nCol ++, pSrcColor ++, pDesColor ++, pSrcMask ++, pDesMask++)
{
if (bHasSrcMask && !(*pSrcMask))
continue;
if (bHasDesMask && !(*pDesMask))
continue;
//5:6:5
uSrcColor.wColor[0] = *pSrcColor;
uSrcColor.wColor[1] = *pSrcColor;
uSrcColor.dwColor &= ALPHA_COLOR_MASK;
uDesColor.wColor[0] = *pDesColor;
uDesColor.wColor[1] = *pDesColor;
uDesColor.dwColor &= ALPHA_COLOR_MASK;
uDesColor.dwColor = uDesColor.dwColor * (KMaxAlpha - nAlpha) + uSrcColor.dwColor * nAlpha;
uDesColor.dwColor = (uDesColor.dwColor >> 5) & ALPHA_COLOR_MASK;
*pDesColor = (TUint16)(uDesColor.wColor[0] | uDesColor.wColor[1]);
}
SetScanLine(pDesBuf, pos.iY + nLine);
}
delete [] uSrcBuf;
delete [] uSrcBufMask;
delete [] uDesBuf;
delete [] uDesBufMask;
return ETrue;
}
//*/
/*TBool CGraphic::Shadow(TInt nAlpha, TRect* pRect)
{
union UColor
{
TUint16 wColor[2];
TUint32 dwColor;
};
TUint16 uBuf[iAllSize.iWidth];
TUint8 uBufMask[iAllSize.iWidth];
TPtr8 pBuf((TUint8*)(&uBuf[0]), sizeof(uBuf));
TPtr8 pBufMask(uBufMask, sizeof(uBufMask));
TBool bHasMask = iBitmap->HasMask();
UColor uColor;
TRect rect;
nAlpha = (nAlpha >> 3) & 0x1F;
rect = pRect ? (*pRect) : TRect(TPoint(0,0), iAllSize);
for (TInt nLine = 0; nLine < rect.Size().iHeight; nLine ++)
{
GetScanLine(pBuf, TPoint(0, rect.iTl.iY + nLine), iAllSize.iWidth, EColor64K);
if (bHasMask)
GetScanLineMask(pBufMask, TPoint(0, rect.iTl.iY + nLine), iAllSize.iWidth, EColor256);
TUint16* pColor = &uBuf[rect.iTl.iX];
TUint8* pMask = &uBufMask[rect.iTl.iX];
for (TInt nCol = 0; nCol < rect.Width(); nCol ++, pColor ++, pMask++)
{
if (bHasMask && !(*pMask))
continue;
uColor.wColor[0] = *pColor;
uColor.wColor[1] = *pColor;
uColor.dwColor &= ALPHA_COLOR_MASK;
uColor.dwColor = uColor.dwColor * nAlpha;
uColor.dwColor = (uColor.dwColor >> 5) & ALPHA_COLOR_MASK;
*pColor = (TUint16)(uColor.wColor[0] | uColor.wColor[1]);
}
SetScanLine(pBuf, rect.iTl.iY + nLine);
}
return ETrue;
}*/
|
[
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] |
[
[
[
1,
422
]
]
] |
2a4180db88389079e3364d75844f383da1ebd382
|
110f8081090ba9591d295d617a55a674467d127e
|
/text/LexicalCast.hpp
|
1f3ca5e33c1509c77d8616bda8a0216b245414d7
|
[] |
no_license
|
rayfill/cpplib
|
617bcf04368a2db70aea8b9418a45d7fd187d8c2
|
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
|
refs/heads/master
| 2021-01-25T03:49:26.965162 | 2011-07-17T15:19:11 | 2011-07-17T15:19:11 | 783,979 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,915 |
hpp
|
#ifndef LEXICALCAST_HPP_
#define LEXICALCAST_HPP_
#include <string>
#include <stdexcept>
#include <cassert>
class CastError : public std::runtime_error
{
public:
CastError(const char* reason = "cast error"):
std::runtime_error(reason)
{}
};
template <typename CastType>
CastType lexicalCast(const std::basic_string<char>& source)
{
CastType result = 0;
const bool isMinusSign = source.size() != 0 && source[0] == '-';
for (std::basic_string<char>::const_iterator itor = source.begin();
itor != source.end(); ++itor)
{
result *= 10;
switch (*itor)
{
case '0':
break;
case '1':
result += 1;
break;
case '2':
result += 2;
break;
case '3':
result += 3;
break;
case '4':
result += 4;
break;
case '5':
result += 5;
break;
case '6':
result += 6;
break;
case '7':
result += 7;
break;
case '8':
result += 8;
break;
case '9':
result += 9;
break;
case '-':
if (itor == source.begin())
break;
default:
throw CastError((source + (" string cast failed.")).c_str());
}
}
return isMinusSign ? (-1 * result) : result;
}
template <typename CastType>
CastType hexLexicalCast(const std::basic_string<char>& source)
{
CastType result = 0;
const bool isMinusSign = source.size() != 0 && source[0] == '-';
for (std::basic_string<char>::const_iterator itor = source.begin();
itor != source.end(); ++itor)
{
result *= 16;
switch (*itor)
{
case '0':
break;
case '1':
result += 1;
break;
case '2':
result += 2;
break;
case '3':
result += 3;
break;
case '4':
result += 4;
break;
case '5':
result += 5;
break;
case '6':
result += 6;
break;
case '7':
result += 7;
break;
case '8':
result += 8;
break;
case '9':
result += 9;
break;
case 'A':
case 'a':
result += 10;
break;
case 'B':
case 'b':
result += 11;
break;
case 'C':
case 'c':
result += 12;
break;
case 'D':
case 'd':
result += 13;
break;
case 'E':
case 'e':
result += 14;
break;
case 'F':
case 'f':
result += 15;
break;
case '-':
if (itor == source.begin())
break;
default:
throw CastError((source + (" hexstring cast failed.")).c_str());
}
}
return isMinusSign ? (-1 * result) : result;
}
/**
* とりあえず実数型は無視の形で・・・
* STLPortのstringstream系が怪しいので排除する形に書き換え
*/
template <typename CastType>
std::basic_string<char> stringCast(const CastType& source)
{
std::string result;
const bool isMinusSign = source < 0;
CastType value = isMinusSign ? (-1 * source) : source;
assert(value >= 0);
do
{
switch (value % 10)
{
case 0:
result.append("0");
break;
case 1:
result.append("1");
break;
case 2:
result.append("2");
break;
case 3:
result.append("3");
break;
case 4:
result.append("4");
break;
case 5:
result.append("5");
break;
case 6:
result.append("6");
break;
case 7:
result.append("7");
break;
case 8:
result.append("8");
break;
case 9:
result.append("9");
break;
default:
assert(!"non reached point.");
}
value /= 10;
} while (value != 0);
if (isMinusSign)
result.append("-");
return std::string(result.rbegin(), result.rend());
}
template <typename CastType>
std::basic_string<char> hexStringCast(const CastType& source)
{
std::string result;
const bool isMinusSign = source < 0;
CastType value = isMinusSign ? (-1 * source) : source;
assert(value >= 0);
do
{
switch (value % 16)
{
case 0:
result.append("0");
break;
case 1:
result.append("1");
break;
case 2:
result.append("2");
break;
case 3:
result.append("3");
break;
case 4:
result.append("4");
break;
case 5:
result.append("5");
break;
case 6:
result.append("6");
break;
case 7:
result.append("7");
break;
case 8:
result.append("8");
break;
case 9:
result.append("9");
break;
case 10:
result.append("A");
break;
case 11:
result.append("B");
break;
case 12:
result.append("C");
break;
case 13:
result.append("D");
break;
case 14:
result.append("E");
break;
case 15:
result.append("F");
break;
default:
assert(!"non reached point.");
}
value /= 16;
} while (value != 0);
if (isMinusSign)
result.append("-");
return std::string(result.rbegin(), result.rend());
}
#endif /* LEXICALCAST_HPP_ */
|
[
"bpokazakijr@287b3242-7fab-264f-8401-8509467ab285",
"alfeim@287b3242-7fab-264f-8401-8509467ab285"
] |
[
[
[
1,
4
],
[
15,
18
],
[
34,
34
],
[
38,
38
],
[
42,
42
],
[
77,
78
],
[
176,
176
],
[
178,
178
],
[
229,
230
],
[
304,
304
]
],
[
[
5,
14
],
[
19,
33
],
[
35,
37
],
[
39,
41
],
[
43,
76
],
[
79,
175
],
[
177,
177
],
[
179,
228
],
[
231,
303
]
]
] |
67496f29f2b264d38e33d0269620111ec72343d1
|
d150600f56acd84df1c3226e691f48f100e6c734
|
/RssReader/GUI/thirdparty/htmlLayout/include/htmlayout_dom.hpp
|
90fc036f233c46ba34fc32ec8977527268cfc222
|
[] |
no_license
|
BackupTheBerlios/newsreader-svn
|
64d44ca7d17eff9174a0a5ea529e94be6a171a97
|
8fb6277101099b6c30ac41eac5e803d2628dfcb1
|
refs/heads/master
| 2016-09-05T14:44:52.642415 | 2007-10-28T19:21:10 | 2007-10-28T19:21:10 | 40,802,616 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 33,437 |
hpp
|
/*
* Terra Informatica Lightweight Embeddable HTMLayout control
* http://terrainformatica.com/htmlayout
*
* HTMLayout DOM implementation. C++ wrapper
*
* The code and information provided "as-is" without
* warranty of any kind, either expressed or implied.
*
* (C) 2003-2004, Andrew Fedoniouk ([email protected])
*/
/**\file
* \brief \link htmlayout_dom.h DOM \endlink C++ wrapper
**/
#ifndef __htmlayout_dom_hpp__
#define __htmlayout_dom_hpp__
#include "json-value.h"
#include "htmlayout_dom.h"
#include "htmlayout_aux.h"
#include "htmlayout_queue.h"
#include <assert.h>
#include <stdio.h> // for vsnprintf
#pragma warning(disable:4786) //identifier was truncated...
#pragma warning(disable:4996) //'strcpy' was declared deprecated
#pragma warning(disable:4100) //unreferenced formal parameter
#pragma once
/**htmlayout namespace.*/
namespace htmlayout
{
/**dom namespace.*/
namespace dom
{
/**callback structure.
* Used with #htmlayout::dom::element::select() function.
**/
struct callback
{
/**Is called for every element that match criteria specified when calling to #htmlayout::dom::element::select() function.*/
virtual bool on_element(HELEMENT he) = 0;
};
/**DOM element.*/
class element
{
protected:
HELEMENT he;
void use(HELEMENT h) { he = (HTMLayout_UseElement(h) == HLDOM_OK)? h: 0; }
void unuse() { if(he) HTMLayout_UnuseElement(he); he = 0; }
void set(HELEMENT h) { unuse(); use(h); }
public:
/**Construct \c undefined element .
**/
element(): he(0) { }
/**Construct \c element from existing element handle.
* \param h \b #HELEMENT
**/
element(HELEMENT h) { use(h); }
/**Copy constructor;
* \param e \b #element
**/
element(const element& e) { use(e.he); }
operator HELEMENT() const { return he; }
/**Destructor.*/
~element() { unuse(); }
/**Assign \c element an \c #HELEMENT
* \param h \b #HELEMENT
* \return \b #element&
**/
element& operator = (HELEMENT h) { set(h); return *this; }
/**Assign \c element another \c #element
* \param e \b #element
* \return \b #element&
**/
element& operator = (const element& e) { set(e.he); return *this; }
/**Test equality of this and another \c #element's
* \param rs \b const \b #element
* \return \b bool, true if elements are equal, false otherwise
**/
bool operator == (const element& rs ) const { return he == rs.he; }
bool operator == (HELEMENT rs ) const { return he == rs; }
/**Test equality of this and another \c #element's
* \param rs \b const \b #element
* \return \b bool, true if elements are not equal, false otherwise
**/
bool operator != (const element& rs ) const { return he != rs.he; }
/**Test whether element is valid.
* \return \b bool, true if element is valid, false otherwise
**/
bool is_valid() const { return he != 0; }
/**Get number of child elements.
* \return \b int, number of child elements
**/
unsigned int children_count() const
{
UINT count = 0;
HTMLayoutGetChildrenCount(he, &count);
return count;
}
/**Get Nth child element.
* \param index \b unsigned \b int, number of the child element
* \return \b #HELEMENT, child element handle
**/
HELEMENT child( unsigned int index ) const
{
HELEMENT child = 0;
HTMLayoutGetNthChild(he, index, &child);
return child;
}
/**Get parent element.
* \return \b #HELEMENT, handle of the parent element
**/
HELEMENT parent( ) const
{
HELEMENT hparent = 0;
HTMLayoutGetParentElement(he, &hparent);
return hparent;
}
/**Get index of this element in its parent collection.
* \return \b unsigned \b int, index of this element in its parent collection
**/
unsigned int index( ) const
{
UINT index = 0;
HTMLayoutGetElementIndex(he, &index);
return index;
}
/**Get number of the attributes.
* \return \b unsigned \b int, number of the attributes
**/
unsigned int get_attribute_count( ) const
{
UINT n = 0;
HTMLayoutGetAttributeCount(he, &n);
return n;
}
/**Get attribute value by its index.
* \param n \b unsigned \b int, number of the attribute
* \return \b const \b wchar_t*, value of the n-th attribute
**/
const wchar_t* get_attribute( unsigned int n ) const
{
LPCWSTR lpw = 0;
HTMLayoutGetNthAttribute(he, n, 0, &lpw);
return lpw;
}
/**Get attribute name by its index.
* \param n \b unsigned \b int, number of the attribute
* \return \b const \b char*, name of the n-th attribute
**/
const char* get_attribute_name( unsigned int n ) const
{
LPCSTR lpc = 0;
HTMLayoutGetNthAttribute(he, n, &lpc, 0);
return lpc;
}
/**Get attribute value by name.
* \param name \b const \b char*, name of the attribute
* \return \b const \b wchar_t*, value of the n-th attribute
**/
const wchar_t* get_attribute( const char* name ) const
{
LPCWSTR lpw = 0;
HTMLayoutGetAttributeByName(he, name, &lpw);
return lpw;
}
/**Add or replace attribute.
* \param name \b const \b char*, name of the attribute
* \param value \b const \b wchar_t*, name of the attribute
**/
void set_attribute( const char* name, const wchar_t* value )
{
HTMLayoutSetAttributeByName(he, name, value);
}
/**Get attribute integer value by name.
* \param name \b const \b char*, name of the attribute
* \return \b int , value of the attribute
**/
int get_attribute_int( const char* name, int def_val = 0 ) const
{
const wchar_t* txt = get_attribute(name);
if(!txt) return def_val;
return _wtoi(txt);
}
/**Remove attribute.
* \param name \b const \b char*, name of the attribute
**/
void remove_attribute( const char* name )
{
HTMLayoutSetAttributeByName(he, name, 0);
}
/**Get style attribute of the element by its name.
* \param name \b const \b char*, name of the style attribute, e.g. "background-color"
* \return \b const \b wchar_t*, value of the style attribute
*
* Also all style attributes of the element are available in "style" attribute of the element.
**/
const wchar_t* get_style_attribute( const char* name ) const
{
LPCWSTR lpw = 0;
HTMLayoutGetStyleAttribute(he, name, &lpw);
return lpw;
}
/**Set style attribute.
* \param name \b const \b char*, name of the style attribute
* \param value \b const \b wchar_t*, value of the style attribute
*
* \par Example:
* \code e.set_style_attribute("background-color", L"red"); \endcode
**/
void set_style_attribute( const char* name, const wchar_t* value ) const
{
HTMLayoutSetStyleAttribute(he, name, value);
}
/**Get root DOM element of the HTMLayout document.
* \param hHTMLayoutWnd \b HWND, HTMLayout window
* \return \b #HELEMENT, root element
* \see also \b #root
**/
static HELEMENT root_element(HWND hHTMLayoutWnd)
{
HELEMENT h = 0;
HTMLayoutGetRootElement(hHTMLayoutWnd,&h);
return h;
}
/**Get focus DOM element of the HTMLayout document.
* \param hHTMLayoutWnd \b HWND, HTMLayout window
* \return \b #HELEMENT, focus element
*
* COMMENT: to set focus use: set_state(STATE_FOCUS)
*
**/
static HELEMENT focus_element(HWND hHTMLayoutWnd)
{
HELEMENT h = 0;
HTMLayoutGetFocusElement(hHTMLayoutWnd,&h);
return h;
}
/**Find DOM element of the HTMLayout document by coordinates.
* \param hHTMLayoutWnd \b HWND, HTMLayout window
* \param clientPt \b POINT, coordinates.
* \return \b #HELEMENT, found element handle or zero
**/
static HELEMENT find_element(HWND hHTMLayoutWnd, POINT clientPt)
{
HELEMENT h = 0;
HTMLayoutFindElement(hHTMLayoutWnd, clientPt, &h);
return h;
}
/**Set mouse capture.
* After call to this function all mouse events will be targeted to this element.
* To remove mouse capture call #htmlayout::dom::element::release_capture().
**/
void set_capture() { HTMLayoutSetCapture(he); }
/**Release mouse capture.
* Mouse capture can be set with #element:set_capture()
**/
static void release_capture() { ReleaseCapture(); }
inline static BOOL CALLBACK callback_func( HELEMENT he, LPVOID param )
{
callback *pcall = (callback *)param;
return pcall->on_element(he)? TRUE:FALSE; // TRUE - stop enumeration
}
/**Enumerate all descendant elements.
* \param pcall \b #htmlayout::dom::callback*, callback structure. Its member function #htmlayout::dom::callback::on_element() is called for every enumerated element.
* \param tag_name \b const \b char*, comma separated list of tag names to search, e.g. "div", "p", "div,p" etc. Can be NULL.
* \param attr_name \b const \b char*, name of attribute, can contain wildcard characters, see below. Can be NULL.
* \param attr_value \b const \b char*, name of attribute, can contain wildcard characters, see below. Can be NULL.
* \param depth \b int, depth - depth of search. 0 means all descendants, 1 - direct children only,
* 2 - children and their children and so on.
*
* Wildcard characters in attr_name and attr_value:
* - '*' - any substring
* - '?' - any one char
* - '['char set']' = any one char in set
*
* \par Example:
* - [a-z] - all lowercase letters
* - [a-zA-Z] - all letters
* - [abd-z] - all lowercase letters except of 'c'
* - [-a-z] - all lowercase letters and '-'
*
* \par Example:
* \code document.select(mycallback, "a", "href", "http:*.php"); \endcode
* will call mycallback.on_element() on each <A> element in the document
* having 'href' attribute with value
* starting from "http:" and ending with ".php"
*
* \par Example:
* \code document.select(mycallback); \endcode
* will enumerate ALL elements in the document.
**/
inline void select( callback *pcall,
const char* tag_name = 0,
const char* attr_name = 0,
const wchar_t* attr_value = 0,
int depth = 0) const
{
HTMLayoutVisitElements( he, tag_name, attr_name, attr_value, callback_func, pcall, depth);
}
inline void select_elements( callback *pcall,
const char* selectors // CSS selectors, comma separated list
) const
{
HTMLayoutSelectElements( he, selectors, callback_func, pcall);
}
/**Get element by id.
* \param id \b char*, value of the "id" attribute.
* \return \b #HELEMENT, handle of the first element with the "id" attribute equal to given.
**/
HELEMENT get_element_by_id(const char* id) const
{
find_first_callback cb;
select(&cb,0,"id",aux::a2w(id));
return cb.hfound;
}
HELEMENT get_element_by_id(const wchar_t* id) const
{
find_first_callback cb;
select(&cb,0,"id",id);
return cb.hfound;
}
/**Apply changes and refresh element area in its window.
* \param[in] render_now \b bool, if true element will be redrawn immediately.
**/
void update( bool render_now = false ) const
{
HTMLayoutUpdateElement(he, render_now? TRUE:FALSE);
}
/**Apply changes and refresh element area in its window.
* \param[in] render_now \b bool, if true element will be redrawn immediately.
**/
void update( int mode ) const
{
HTMLayoutUpdateElementEx(he, mode);
}
/**Get next sibling element.
* \return \b #HELEMENT, handle of the next sibling element if it exists or 0 otherwise
**/
HELEMENT next_sibling() const
{
unsigned int idx = index() + 1;
element pel = parent();
if(!pel.is_valid())
return 0;
if( idx >= pel.children_count() )
return 0;
return pel.child(idx);
}
/**Get previous sibling element.
* \return \b #HELEMENT, handle of previous sibling element if it exists or 0 otherwise
**/
HELEMENT prev_sibling() const
{
unsigned int idx = index() - 1;
element pel = parent();
if(!pel.is_valid())
return 0;
if( idx < 0 )
return 0;
return pel.child(idx);
}
/**Get first sibling element.
* \return \b #HELEMENT, handle of the first sibling element if it exists or 0 otherwise
**/
HELEMENT first_sibling() const
{
element pel = parent();
if(!pel.is_valid())
return 0;
return pel.child(0);
}
/**Get last sibling element.
* \return \b #HELEMENT, handle of last sibling element if it exists or 0 otherwise
**/
HELEMENT last_sibling() const
{
element pel = parent();
if(!pel.is_valid())
return 0;
return pel.child(pel.children_count() - 1);
}
/**Get root of the element
* \return \b #HELEMENT, handle of document root element (html)
**/
HELEMENT root() const
{
element pel = parent();
if(pel.is_valid()) return pel.root();
return he;
}
/**Get bounding rectangle of the element.
* \param root_relative \b bool, if true function returns location of the
* element relative to HTMLayout window, otherwise the location is given
* relative to first scrollable container.
* \return \b RECT, bounding rectangle of the element.
**/
RECT get_location(unsigned int area = ROOT_RELATIVE | CONTENT_BOX) const
{
RECT rc = {0,0,0,0};
HTMLayoutGetElementLocation(he,&rc, area);
return rc;
}
/** Test if point is inside shape rectangle of the element.
client_pt - client rect relative point
**/
bool is_inside( POINT client_pt ) const
{
RECT rc = get_location(ROOT_RELATIVE | BORDER_BOX);
return PtInRect(&rc,client_pt) != FALSE;
}
/**Scroll this element to view.
**/
void scroll_to_view(bool toTopOfView = false)
{
HTMLayoutScrollToView(he,toTopOfView?TRUE:FALSE);
}
void get_scroll_info(POINT& scroll_pos, RECT& view_rect, SIZE& content_size)
{
HLDOM_RESULT r = HTMLayoutGetScrollInfo(he, &scroll_pos, &view_rect, &content_size);
assert(r == HLDOM_OK); r;
}
void set_scroll_pos(POINT scroll_pos)
{
HLDOM_RESULT r = HTMLayoutSetScrollPos(he, scroll_pos, TRUE);
assert(r == HLDOM_OK); r;
}
/**Get element's type.
* \return \b const \b char*, name of the elements type
*
* \par Example:
* For <div> tag function will return "div".
**/
const char* get_element_type() const
{
LPCSTR str = 0;
HTMLayoutGetElementType(he,&str);
return str;
}
/**Get HWND of containing window.
* \param root_window \b bool, handle of which window to get:
* - true - HTMLayout window
* - false - nearest parent element having overflow:auto or :scroll
* \return \b HWND
**/
HWND get_element_hwnd(bool root_window)
{
HWND hwnd = 0;
HTMLayoutGetElementHwnd(he,&hwnd, root_window? TRUE : FALSE);
return hwnd;
}
/**Get element UID - identifier suitable for storage.
* \return \b UID
**/
UINT get_element_uid()
{
UINT uid = 0;
HTMLayoutGetElementUID(he,&uid);
return uid;
}
/**Get element handle by its UID.
* \param hHTMLayoutWnd \b HWND, HTMLayout window
* \param uid \b UINT, uid of the element
* \return \b #HELEMENT, handle of element with the given uid or 0 if not found
**/
static HELEMENT element_by_uid(HWND hHTMLayoutWnd, UINT uid)
{
HELEMENT h = 0;
HTMLayoutGetElementByUID(hHTMLayoutWnd, uid,&h);
return h;
}
/**Combine given URL with URL of the document element belongs to.
* \param[in, out] inOutURL \b LPWSTR, at input this buffer contains
* zero-terminated URL to be combined, after function call it contains
* zero-terminated combined URL
* \param bufferSize \b UINT, size of the buffer pointed by \c inOutURL
**/
void combine_url(LPWSTR inOutURL, UINT bufferSize)
{
HTMLayoutCombineURL(he,inOutURL,bufferSize);
}
/**Set inner or outer html of the element.
* \param html \b const \b unsigned \b char*, UTF-8 encoded string containing html text
* \param html_length \b size_t, length in bytes of \c html
* \param where \b int, possible values are:
* - SIH_REPLACE_CONTENT - replace content of the element
* - SIH_INSERT_AT_START - insert html before first child of the element
* - SIH_APPEND_AFTER_LAST - insert html after last child of the element
**/
void set_html( const unsigned char* html, size_t html_length, int where = SIH_REPLACE_CONTENT)
{
if(html == 0 || html_length == 0)
clear();
else
{
HLDOM_RESULT r = HTMLayoutSetElementHtml(he, html, DWORD(html_length), where);
assert(r == HLDOM_OK); r;
}
}
const unsigned char*
get_html( bool outer = true) const
{
unsigned char* utf8bytes = 0;
HLDOM_RESULT r = HTMLayoutGetElementHtml(he, &utf8bytes, outer? TRUE:FALSE);
assert(r == HLDOM_OK); r;
return utf8bytes;
}
// get text as utf8 bytes
const unsigned char* get_text() const
{
unsigned char* utf8bytes = 0;
HLDOM_RESULT r = HTMLayoutGetElementInnerText(he, &utf8bytes);
assert(r == HLDOM_OK); r;
return utf8bytes;
}
// get text as wchar_t words
const wchar_t* text() const
{
wchar_t* utf16words = 0;
HLDOM_RESULT r = HTMLayoutGetElementInnerText16(he, &utf16words);
assert(r == HLDOM_OK); r;
return utf16words;
}
void set_text(const wchar_t* utf16, size_t utf16_length)
{
HLDOM_RESULT r = HTMLayoutSetElementInnerText16(he, utf16, (UINT)utf16_length);
assert(r == HLDOM_OK); r;
}
void set_text(const wchar_t* t)
{
assert(t);
if( t ) set_text( t, wcslen(t) );
}
void clear() // clears content of the element
{
HLDOM_RESULT r = HTMLayoutSetElementInnerText16(he, L"", 0);
assert(r == HLDOM_OK); r;
}
/**Delete element.
* This function removes element from the DOM tree and then deletes it.
**/
void destroy()
{
HTMLayoutDeleteElement(he);
he = 0;
}
HELEMENT find_first( const char* selector, ... ) const
{
char buffer[2049]; buffer[0]=0;
va_list args;
va_start ( args, selector );
_vsnprintf( buffer, 2048, selector, args );
va_end ( args );
find_first_callback find_first;
select_elements( &find_first, buffer); // find first element satisfying given CSS selector
//assert(find_first.hfound);
return find_first.hfound;
}
void find_all( callback* cb, const char* selector, ... ) const
{
char buffer[2049]; buffer[0]=0;
va_list args;
va_start ( args, selector );
_vsnprintf( buffer, 2048, selector, args );
va_end ( args );
select_elements( cb, buffer); // find all elements satisfying given CSS selector
//assert(find_first.hfound);
}
// will find first parent satisfying given css selector(s), will check element itself
HELEMENT find_nearest_parent(const char* selector, ...) const
{
char buffer[2049]; buffer[0]=0;
va_list args;
va_start ( args, selector );
_vsnprintf( buffer, 2048, selector, args );
va_end ( args );
HELEMENT heFound = 0;
HLDOM_RESULT r = HTMLayoutSelectParent(he, buffer, 0, &heFound);
assert(r == HLDOM_OK); r;
return heFound;
}
// test this element against CSS selector(s)
bool test(const char* selector, ...) const
{
char buffer[2049]; buffer[0]=0;
va_list args;
va_start ( args, selector );
_vsnprintf( buffer, 2048, selector, args );
va_end ( args );
HELEMENT heFound = 0;
HLDOM_RESULT r = HTMLayoutSelectParent(he, buffer, 1, &heFound);
assert(r == HLDOM_OK); r;
return heFound != 0;
}
/**Get UI state bits of the element as set of ELEMENT_STATE_BITS
**/
unsigned int get_state() const
{
UINT state = 0;
HLDOM_RESULT r = HTMLayoutGetElementState(he,&state);
assert(r == HLDOM_OK); r;
return (ELEMENT_STATE_BITS) state;
}
/**Checks if particular UI state bits are set in the element.
**/
bool get_state(/*ELEMENT_STATE_BITS*/ unsigned int bits) const
{
UINT state = 0;
HLDOM_RESULT r = HTMLayoutGetElementState(he,&state);
assert(r == HLDOM_OK); r;
return (state & bits) != 0;
}
/**Set UI state of the element with optional view update.
**/
void set_state(
/*ELEMENT_STATE_BITS*/ unsigned int bitsToSet,
/*ELEMENT_STATE_BITS*/ unsigned int bitsToClear = 0, bool update = true )
{
HLDOM_RESULT r = HTMLayoutSetElementState(he,bitsToSet,bitsToClear, update?TRUE:FALSE);
assert(r == HLDOM_OK); r;
}
/** "deeply enabled" **/
bool enabled()
{
BOOL b = FALSE;
HLDOM_RESULT r = HTMLayoutIsElementEnabled(he,&b);
assert(r == HLDOM_OK); r;
return b != 0;
}
/** "deeply visible" **/
bool visible()
{
BOOL b = FALSE;
HLDOM_RESULT r = HTMLayoutIsElementVisible(he,&b);
assert(r == HLDOM_OK); r;
return b != 0;
}
/** create brand new element with text (optional).
Example:
element div = element::create("div");
- will create DIV element,
element opt = element::create("option",L"Europe");
- will create OPTION element with text "Europe" in it.
**/
static element create(const char* tagname, const wchar_t* text = 0)
{
element e(0);
HLDOM_RESULT r = HTMLayoutCreateElement( tagname, text, &e.he ); // don't need 'use' here, as it is already "addrefed"
assert(r == HLDOM_OK); r;
return e;
}
/** create brand new copy of this element. Element will be created disconected.
You need to call insert to inject it in some container.
Example:
element select = ...;
element option1 = ...;
element option2 = option1.clone();
select.insert(option2, option1.index() + 1);
- will create copy of option1 element (option2) and insert it after option1,
**/
element clone()
{
element e(0);
HLDOM_RESULT r = HTMLayoutCloneElement( he, &e.he ); // don't need 'use' here, as it is already "addrefed"
assert(r == HLDOM_OK); r;
return e;
}
/** Insert element e at \i index position of this element.
**/
void insert( const element& e, unsigned int index )
{
HLDOM_RESULT r = HTMLayoutInsertElement( e.he, this->he, index );
assert(r == HLDOM_OK); r;
}
/** Append element e as last child of this element.
**/
void append( const element& e ) { insert(e,0x7FFFFFFF); }
/** detach - remove this element from its parent
**/
void detach()
{
HLDOM_RESULT r = HTMLayoutDetachElement( he );
assert(r == HLDOM_OK); r;
}
/** traverse event - send it by sinking/bubbling on the
* parent/child chain of this element
**/
bool send_event(unsigned int event_code, UINT_PTR reason = 0, HELEMENT heSource = 0)
{
BOOL handled = FALSE;
HLDOM_RESULT r = HTMLayoutSendEvent(he, event_code, heSource? heSource: he, reason, &handled);
assert(r == HLDOM_OK); r;
return handled != 0;
}
/** post event - post it in the queue for later sinking/bubbling on the
* parent/child chain of this element.
* method returns immediately
**/
void post_event(unsigned int event_code, unsigned int reason = 0, HELEMENT heSource = 0)
{
HLDOM_RESULT r = HTMLayoutPostEvent(he, event_code, heSource? heSource: he, reason);
assert(r == HLDOM_OK); r;
}
/** attach event handler to the element
**/
void attach(event_handler* pevth)
{
htmlayout::attach_event_handler(he,pevth);
}
/** remove event handler from the list of event handlers of the element.
**/
void detach(event_handler* pevth)
{
htmlayout::detach_event_handler(he,pevth);
}
/** call method, invokes method in all event handlers attached to the element
**/
bool call_behavior_method(METHOD_PARAMS* p)
{
if(!is_valid())
return false;
return ::HTMLayoutCallBehaviorMethod(he,p) == HLDOM_OK;
}
void load_html(const wchar_t* url, HELEMENT initiator = 0)
{
HLDOM_RESULT r = HTMLayoutRequestElementData(he,url,HLRT_DATA_HTML,initiator);
assert(r == HLDOM_OK); r;
}
struct comparator
{
virtual int compare(const htmlayout::dom::element& e1, const htmlayout::dom::element& e2) = 0;
static INT CALLBACK scmp( HELEMENT he1, HELEMENT he2, LPVOID param )
{
htmlayout::dom::element::comparator* self =
static_cast<htmlayout::dom::element::comparator*>(param);
htmlayout::dom::element e1 = he1;
htmlayout::dom::element e2 = he2;
return self->compare( e1,e2 );
}
};
/** reorders children of the element using sorting order defined by cmp
**/
void sort( comparator& cmp, int start = 0, int end = -1 )
{
if (end == -1)
end = children_count();
HLDOM_RESULT r = HTMLayoutSortElements(he, start, end, &comparator::scmp, &cmp);
assert(r == HLDOM_OK); r;
}
CTL_TYPE get_ctl_type() const
{
UINT t = 0;
HLDOM_RESULT r = ::HTMLayoutControlGetType(he,&t);
assert(r == HLDOM_OK); r;
return CTL_TYPE(t);
}
json::value get_value() const
{
json::value v;
HLDOM_RESULT r = ::HTMLayoutControlGetValue(he,&v);
assert(r == HLDOM_OK); r;
return v;
}
void set_value(const json::value& v)
{
HLDOM_RESULT r = ::HTMLayoutControlSetValue(he,&v);
assert(r == HLDOM_OK); r;
}
private:
struct find_first_callback: callback
{
HELEMENT hfound;
find_first_callback():hfound(0) {}
inline bool on_element(HELEMENT he) { hfound = he; return true; /*stop enumeration*/ }
};
};
#define STD_CTORS(T,PT) \
T() { } \
T(HELEMENT h): PT(h) { } \
T(const element& e): PT(e) { } \
T& operator = (HELEMENT h) { set(h); return *this; } \
T& operator = (const element& e) { set(e); return *this; }
class editbox: public element
{
public:
STD_CTORS(editbox, element)
bool selection( int& start, int& end )
{
TEXT_EDIT_SELECTION_PARAMS sp(false);
if(!call_behavior_method(&sp))
return false;
start = sp.selection_start;
end = sp.selection_end;
return true;
}
bool select( int start = 0, int end = 0xFFFF )
{
TEXT_EDIT_SELECTION_PARAMS sp(true);
sp.selection_start = start;
sp.selection_end = end;
return call_behavior_method(&sp);
}
bool replace(const wchar_t* text, size_t text_length)
{
TEXT_EDIT_REPLACE_SELECTION_PARAMS sp;
sp.text = text;
sp.text_length = UINT(text_length);
return call_behavior_method(&sp);
}
json::string text_value() const
{
TEXT_VALUE_PARAMS sp(false);
if( const_cast<editbox*>(this)->call_behavior_method(&sp) && sp.text && sp.length)
{
return json::string(sp.text, sp.length);
}
return json::string();
}
void text_value(const wchar_t* text, size_t length)
{
TEXT_VALUE_PARAMS sp(true);
sp.text = text;
sp.length = UINT(length);
call_behavior_method(&sp);
update();
}
void text_value(const wchar_t* text)
{
TEXT_VALUE_PARAMS sp(true);
sp.text = text;
sp.length = text? UINT(wcslen(text)):0;
call_behavior_method(&sp);
update();
}
void int_value( int v )
{
wchar_t buf[64]; int n = _snwprintf(buf,63,L"%d", v); buf[63] = 0;
text_value(buf,n);
}
int int_value( ) const
{
return _wtoi( text_value() );
}
};
class scrollbar: public element
{
public:
STD_CTORS(scrollbar, element)
void get_values( int& val, int& min_val, int& max_val, int& page_val, int& step_val )
{
SCROLLBAR_VALUE_PARAMS sbvp;
call_behavior_method(&sbvp);
val = sbvp.value;
min_val = sbvp.min_value;
max_val = sbvp.max_value;
page_val = sbvp.page_value; // page increment
step_val = sbvp.step_value; // step increment (arrow button click)
}
void set_values( int val, int min_val, int max_val, int page_val, int step_val )
{
SCROLLBAR_VALUE_PARAMS sbvp(true);
sbvp.value = val;
sbvp.min_value = min_val;
sbvp.max_value = max_val;
sbvp.page_value = page_val;
sbvp.step_value = step_val;
call_behavior_method(&sbvp);
}
int get_value()
{
SCROLLBAR_VALUE_PARAMS sbvp;
call_behavior_method(&sbvp);
return sbvp.value;
}
void set_value( int v )
{
SCROLLBAR_VALUE_PARAMS sbvp;
call_behavior_method(&sbvp);
sbvp.value = v;
sbvp.methodID = SCROLL_BAR_SET_VALUE;
call_behavior_method(&sbvp);
}
};
struct enumerator
{
enumerator() {}
virtual ~enumerator() {} // to make G++ happy.
void ramble(HELEMENT what, bool forward = true)
{
HLDOM_RESULT r = HTMLayoutEnumerate(what,&_cb,this,forward);
assert(r == HLDOM_OK); r;
}
virtual bool on_element_head( HELEMENT ) { return false; }
virtual bool on_element_tail( HELEMENT ) { return false; }
virtual bool on_char( HELEMENT text, int pos, WCHAR code ) { return false; }
inline static BOOL CALLBACK _cb( LPVOID p, HELEMENT he, int pos, int postype, WCHAR code )
{
enumerator* pe = (enumerator*)p;
switch(postype)
{
case 0: // - he element head position.
return pe->on_element_head( he );
case 1: // - he element tail position.
return pe->on_element_tail( he );
case 2:// - character position.
return pe->on_char( he, pos, code );
}
assert(false);
return false;
}
};
} // dom namespace
} // htmlayout namespace
#endif
|
[
"peacebird@00473811-6f2b-0410-a651-d1448cebbc4e"
] |
[
[
[
1,
1063
]
]
] |
4797ee7fd84303308d9f75a17fe04f0993cafc0d
|
bd89d3607e32d7ebb8898f5e2d3445d524010850
|
/connectivitylayer/isce/isaaccessextension_dll/inc/isakernelapi.h
|
ddd45faf8d228961d3c491299f7501c8aec891b6
|
[] |
no_license
|
wannaphong/symbian-incubation-projects.fcl-modemadaptation
|
9b9c61ba714ca8a786db01afda8f5a066420c0db
|
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
|
refs/heads/master
| 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 17,625 |
h
|
/*
* 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 the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef ISAKERNELAPI_H
#define ISAKERNELAPI_H
// INCLUDES
#include <klib.h> // For DBase
// CONSTANTS
// None
// MACROS
// None
// DATA TYPES
// None
// FUNCTION PROTOTYPES
// None
// FORWARD DECLARATIONS
class DISAKernelWrapperHelper;
// CLASS DECLARATION
/**
* Kernel interface for ISA Access Driver.
*
* @lib IsaKernelAPI
* @since S_CPR81
*/
NONSHARABLE_CLASS( DIsaKernelAPI ) : public DBase
{
public:
/**
* Static constructor. Returns an new instance of the object.
* NOTE! Kern::Fault raised if no free memory left.
*/
static IMPORT_C DIsaKernelAPI* NewF();
/**
* Destructor.
* Cancels any outstanding DFC requests and closes the channel.
*/
IMPORT_C ~DIsaKernelAPI();
/**
* Get a free block for ISI message sending. Block is at least the size
* of the param aSize.
* NOTE! Kern::Fault raised if no free blocks left.
* Preconditions: Channel is succesfully opened.
* Postconditions: Block allocated and reference returned.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aSize, minimum size of the buffer.
* @return TDes8&, reference to allocated block.
*/
IMPORT_C TDes8& AllocateMsgBlock( const TInt aSize );
/**
* Get a free block for data message sending. Block is at least the size
* of the param aSize.
* NOTE! Message allocated with this function must be
* send with DataSend.
* NOTE! Kern::Fault raised if no free blocks left.
* Preconditions: Channel is succesfully opened.
* Postconditions: Block allocated and reference returned.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aSize, minimum size of the buffer.
* @return TDes8&, reference to allocated datablock.
*/
IMPORT_C TDes8& AllocateDataMsgBlock( const TInt aSize );
/**
* Closes the channel. If channel is not open does nothing. Cancels any
* outstanding DFC requests.
* Preconditions: Channel is succesfully opened.
* Postconditions: Channel closed and outstanding requests cancelled.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void Close();
/**
* Receive message. DFC function given as param
* shall be queued to run when message is received.
* NOTE! After Receive DFC completion, client must deallocate block with
* DeAllocateDataMsgBlock and set the pointer to NULL.
* Preconditions: Channel is succesfully opened.
* Parameter aDataMsgBlock must be NULL.
* Postconditions: Receive is pending.
* Kern::Fault will be raised if API can't allocate receive buffer.
* Kern::Fault will be raised if same request is set when it is already pending.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aDataMsgBlock, block where received data message is written.
* @param aDfcStatus, updated when DFC is queued.
* KErrNone, succefull
* KErrCancel, receive was cancelled client no need to deallocate block get from receive.
* @param aDataReceiveDfc, clients DFC function for receiving message.
* @return None
*/
IMPORT_C void DataReceive( TDes8*& aDataMsgBlock,
TInt& aDfcStatus,
const TDfc& aDataReceiveDfc );
/**
* Cancels the pending data receive request.
* Data receive cancellation will cancel pending DataReceive DFC with
* status KErrCancel. If nothing pending does nothing.
* Preconditions: Channel is succesfully opened.
* Postconditions: DataReceive is cancelled.
* Called automatically in destructor.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void DataReceiveCancel();
/**
* Sends a data message and deallocates the block given as parameter.
* Preconditions: Channel is succesfully opened.
* Descriptor was allocated with AllocateDataMsgBlock.
* Postconditions: Data message block is deallocated.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param TDes8& aMsg, reference to message to be send.
* @return TInt, an error code
* KErrNone, send succesfully
* KErrBadDescriptor, descriptor length too small.
* KErrUnderflow, ISI message length either bigger than descriptor
* length or bigger than maximum ISI message length
* or smaller than minimum ISI message length.
* KErrOverFlow, send queue overflow, client must resend.
* KErrNotReady, modem sw down, send failed, start listen state change, when ok, possible to resend.
*/
IMPORT_C TInt DataSend( TDes8& aMsg );
/**
* Deallocates the message block retrieved with Receive.
* NOTE! After deallocation set pointer to NULL.
* Preconditions: Channel is succesfully opened.
* Message was received with Receive.
* Postconditions: Message block is deallocated.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aMsgBlock, reference to block to deallocate.
* @return None
*/
IMPORT_C void DeAllocateMsgBlock( TDes8& aMsgBlock );
/**
* Deallocates the data message block retrieved with DataReceive.
* NOTE! After deallocation set pointer to NULL.
* Preconditions: Channel is succesfully opened.
* Data message was received with DataReceive.
* Postconditions: Data message block is deallocated.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aMsgBlock, reference to data block to deallocate.
* @return None
*/
IMPORT_C void DeAllocateDataMsgBlock( TDes8& aMsgBlock );
/**
* Notifies flow control status change. When flowcontrol status changes
* DFC will be queued and status value updated to parameter.
* Preconditions: Channel is succesfully opened.
* Postconditions: Flowcontrol status notification is pending.
* Kern::Fault will be raised if same request is set when it is already pending.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aNotifyFlowDfc, DFC function for flow status changes.
* @param aDfcStatus, EIscFlowControlOn when datasend not allowed,
* EIscFlowControlOff when datasend allowed,
* EIscTransmissionEnd when datasend connection is removed
* KErrCancel, when cancelled
* @return None
*/
IMPORT_C void NotifyFlowChange( TDfc& aNotifyFlowDfc,
TInt& aDfcStatus );
/**
* Cancels connection status change request.
* Does nothing if request is not pending.
* Preconditions: Channel is succesfully opened.
* Postconditions: Flowcontrol status notification is cancelled.
* Called automatically in destructor.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void NotifyFlowChangeCancel();
/**
* Notifies connection status change. When connection status changes
* DFC will be queued and connection status value updated to parameter.
* Preconditions: Channel is succesfully opened.
* Postconditions: Connection status notification is pending.
* Kern::Fault will be raised if same request is set when it is already pending.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aNotifyStateDfc, DFC function for connection status changes.
* @param aDfcStatus, EIscConnectionOk, EIscConnectionNotOk or KErrCancel
* @return None
*/
IMPORT_C void NotifyStateChange( TDfc& aNotifyStateDfc,
TInt& aDfcStatus );
/**
* Cancels pending connection status notification with KErrCancel.
* Does nothing if request not pending.
* Preconditions: Channel is succesfully opened.
* Postconditions: Connection status notification is cancelled.
* Called automatically in destructor.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void NotifyStateChangeCancel() const;
/**
* Opens a clients channel.
* NOTE! If opened with resource client must give appropriate resource
* as aResource.
* Preconditions: Channel is closed.
* Postconditions: Open is pending.
* Kern::Fault will be raised if same request is set when it is already pending.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aChannelNumber, clients dedicated channel number.
* @param aDfcStatus, updated when DFC queued.
* KErrNone, is succesfully
* KErrAlreadyExist, channel already open
* KErrNotSupported, open with resource failed.
* @param aOpenDfc, ref. to DFC to be queued when channel is opened.
* @param aResource, 32-bit resourceid default value (PN_NO_ROUTING (0xff)).
* @return None
*/
IMPORT_C void Open( const TUint16 aChannelNumber, TInt& aDfcStatus,
TDfc& aOpenDfc, const TUint32 aResource = 0x000000ff );
/**
* Cancels the pending open DFC request with KErrCancel.
* If the open is not pending anymore does nothing.
* Called automatically in destructor.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void OpenCancel();
/**
* Receive message. DFC function given as param
* shall be queued to run when message is received.
* NOTE! After Receive DFC completion, client must deallocate block with
* DeAllocateBlock and set the pointer to NULL.
* Preconditions: Channel is succesfully opened.
* Parameter aMsgBlock must be NULL.
* Postconditions: Receive is pending.
* Kern::Fault will be raised if API can't allocate receive buffer.
* Kern::Fault will be raised if same request is set when it is already pending.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aMsgBlock, block where receive message is stored.
* @param aStatus, updated when DFC is queued.
* KErrNone, succefull
* KErrCancel, receive was cancelled client no need to deallocate block get from receive.
* @param aReceiveDfc, clients DFC function for receiving message.
* @return None
*/
IMPORT_C void Receive( TDes8*& aMsgBlock, TInt& aStatus,
const TDfc& aReceiveDfc );
/**
* Cancels the pending receive DFC request with KErrCancel.
* If the receive is not pending anymore does nothing.
* Preconditions: Channel is succesfully opened.
* Called automatically in destructor.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @return None
*/
IMPORT_C void ReceiveCancel();
/**
* Sends a message and deallocates the block given as parameter.
* Preconditions: Channel is succesfully opened.
* Descriptor was allocated with AllocateMsgBlock.
* Postconditions: Message block is deallocated.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param TDes8& aMsg, reference to message to be send.
* @return TInt, an error code
* KErrNone, send succesfully
* KErrBadDescriptor, descriptor length too small.
* KErrUnderflow, ISI message length either bigger than descriptor
* length or bigger than maximum ISI message length
* or smaller than minimum ISI message length.
* KErrOverFlow, send queue overflow, client must resend.
* KErrNotReady, modem sw down, send failed, start listen state change, when ok, possible to resend.
*/
IMPORT_C TInt Send( TDes8& aMsg );
/**
* Sends an event to CMT. NOTE! Only servers in ISA-sense can do this.
* Preconditions: Channel is succesfully opened with resource.
* Block was allocated with AllocateMsgBlock.
* Postconditions: Indication was send.
* Block was deallocated.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param TDes8& aMsg, reference to indication to be send.
* @return TInt, an error code.
* KErrNone, send succesfully
* KErrBadDescriptor, descriptor length too small.
* KErrUnderflow, ISI message length either bigger than descriptor
* length or bigger than maximum ISI message length
* or smaller than minimum ISI message length.
* KErrOverFlow, send queue overflow, client must resend.
* KErrNotReady, modem sw down, send failed, start listen state change, when ok, possible to resend.
*/
IMPORT_C TInt SendIndication( TDes8& aMsg );
/**
* Subscribe indications. Indications are received with
* Receive.
* NOTE! Don't dellocate the descriptor for indications.
* 8-bit subscribing list item. Must be div. by two.
* byte1:[8bit resourceid]
* byte2:[8bit indicationid]
* 32-bit subscribing list item. Must be div. by five.
* byte1:[32-24 bits of resourceid]
* byte2:[24-16 bits of resourceid]
* byte3:[16-8 bits of resourceid]
* byte4:[8-0 bits of resourceid]
* byte5:[8bit indicationid]
* Preconditions: Channel is succesfully opened.
* Postconditions: Channel is add as indication(s) subscriber.
* Called in kernel thread context.
* Called with no fastmutex held.
* Called with interrupts enabled.
* Called without kernel lock held.
* @param aIndications, indication subscription list.
* @param aThirtyTwoBit, EFalse by default, ETrue when 32-bit subscribing used.
* @return TInt, an error code.
* KErrNone, subscribe succesfully
* KErrBadDescriptor, descriptor length too small or not according to subscribing list items.
* KErrUnderflow, subscribing list item too long.
* KErrOverFlow, send queue overflow, client must resend.
* KErrNotReady, modem sw down, send failed, start listen state change, when ok, possible to resend.
*/
IMPORT_C TInt SubscribeIndications( const TDesC8& aIndications,
const TBool aThirtyTwoBit = EFalse );
private:
/**
* Private constructor.
* One reason class size BC.
*/
DIsaKernelAPI();
private:
// Owned
// Kernel channel dedicated for this.
DISAKernelWrapperHelper* iHelper;
};
#endif // ISAKERNELAPI_H
// End of File.
|
[
"dalarub@localhost",
"mikaruus@localhost"
] |
[
[
[
1,
38
],
[
40,
427
],
[
429,
435
]
],
[
[
39,
39
],
[
428,
428
]
]
] |
3fd59f87f1581c3749612cf383d1092cdc688b9f
|
c0bd82eb640d8594f2d2b76262566288676b8395
|
/src/game/Chat.cpp
|
2c605c9b9d3dbb5efcaea5146b2b562cef6c63e0
|
[
"FSFUL"
] |
permissive
|
vata/solution
|
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
|
774fca057d12a906128f9231831ae2e10a947da6
|
refs/heads/master
| 2021-01-10T02:08:50.032837 | 2007-11-13T22:01:17 | 2007-11-13T22:01:17 | 45,352,930 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 52,121 |
cpp
|
// Copyright (C) 2004 WoW Daemon
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "StdAfx.h"
createFileSingleton( ChatHandler );
ChatHandler::ChatHandler()
{
}
ChatHandler::~ChatHandler()
{
}
ChatCommand * ChatHandler::getCommandTable()
{
// Ignatich
// TODO: change default security levels?
// static bool first_call = true;
static ChatCommand modifyCommandTable[] =
{
{ "hp", 'm', NULL, "Health Points/HP", NULL, UNIT_FIELD_HEALTH, UNIT_FIELD_MAXHEALTH, 1 },
{ "mana", 'm', NULL, "Mana Points/MP", NULL, UNIT_FIELD_POWER1, UNIT_FIELD_MAXPOWER1, 1 },
{ "rage", 'm', NULL, "Rage Points", NULL, UNIT_FIELD_POWER2, UNIT_FIELD_MAXPOWER2, 1 },
{ "energy", 'm', NULL, "Energy Points", NULL, UNIT_FIELD_POWER4, UNIT_FIELD_MAXPOWER4, 1 },
{ "level", 'm', &ChatHandler::HandleModifyLevelCommand,"Level", NULL, 0, 0, 0 },
{ "armor", 'm', NULL, "Armor", NULL, UNIT_FIELD_STAT1, 0, 1 },
{ "holy", 'm', NULL, "Holy Resistance", NULL, UNIT_FIELD_RESISTANCES_01, 0, 1 },
{ "fire", 'm', NULL, "Fire Resistance", NULL, UNIT_FIELD_RESISTANCES_02, 0, 1 },
{ "nature", 'm', NULL, "Nature Resistance", NULL, UNIT_FIELD_RESISTANCES_03, 0, 1 },
{ "frost", 'm', NULL, "Frost Resistance", NULL, UNIT_FIELD_RESISTANCES_04, 0, 1 },
{ "shadow", 'm', NULL, "Shadow Resistance", NULL, UNIT_FIELD_RESISTANCES_05, 0, 1 },
{ "arcane", 'm', NULL, "Arcane Resistance", NULL, UNIT_FIELD_RESISTANCES_06, 0, 1 },
{ "damage", 'm', NULL, "Unit Damage Min/Max", NULL, UNIT_FIELD_MINDAMAGE, UNIT_FIELD_MAXDAMAGE,2 },
{ "scale", 'm', NULL, "Size/Scale", NULL, OBJECT_FIELD_SCALE_X, 0, 2 },
{ "gold", 'm', &ChatHandler::HandleModifyGoldCommand, "Gold/Money/Copper", NULL, 0, 0, 0 },
{ "speed", 'm', &ChatHandler::HandleModifySpeedCommand, "Movement Speed", NULL, 0, 0, 0 },
{ "nativedisplayid", 'm', NULL, "Native Display ID", NULL, UNIT_FIELD_NATIVEDISPLAYID, 0, 1 },
{ "displayid" , 'm', NULL, "Display ID", NULL, UNIT_FIELD_DISPLAYID, 0, 1 },
{ "flags" , 'm', NULL, "Unit Flags", NULL, UNIT_FIELD_FLAGS, 0, 1 },
{ "faction", 'm', NULL, "Faction Template", NULL, UNIT_FIELD_FACTIONTEMPLATE, 0, 1 },
{ "dynamicflags",'m',NULL, "Dynamic Flags", NULL, UNIT_DYNAMIC_FLAGS, 0, 1 },
{ "talentpoints",'m',NULL, "Talent Points", NULL, PLAYER_CHARACTER_POINTS1, 0, 1 },
{ "loyalty", 'm', NULL, "Loyalty", NULL, UNIT_FIELD_POWER5, UNIT_FIELD_MAXPOWER5, 1 },
{ "spirit", 'm', NULL, "Spirit", NULL, UNIT_FIELD_STAT0, 0, 1 },
{ "boundingraidus",'m',NULL, "Bounding Radius", NULL, UNIT_FIELD_BOUNDINGRADIUS, 0, 2 },
{ "combatreach",'m',NULL, "Combat Reach", NULL, UNIT_FIELD_COMBATREACH, 0, 2 },
{ "emotestate",'m', NULL, "NPC Emote State", NULL, UNIT_NPC_EMOTESTATE, 0, 1 },
{ NULL, 0, NULL, "", NULL, 0, 0 }
};
static ChatCommand debugCommandTable[] =
{
{ "infront", 'd', &ChatHandler::HandleDebugInFrontCommand, "", NULL, 0, 0, 0},
{ "showreact", 'd', &ChatHandler::HandleShowReactionCommand, "", NULL, 0, 0, 0},
{ "aimove", 'd', &ChatHandler::HandleAIMoveCommand, "", NULL, 0, 0, 0},
{ "dist", 'd', &ChatHandler::HandleDistanceCommand, "", NULL, 0, 0, 0},
{ "face", 'd', &ChatHandler::HandleFaceCommand, "", NULL, 0, 0, 0},
{ "moveinfo", 'd', &ChatHandler::HandleMoveInfoCommand, "", NULL, 0, 0, 0},
{ "setbytes", 'd', &ChatHandler::HandleSetBytesCommand, "", NULL, 0, 0, 0},
{ "getbytes", 'd', &ChatHandler::HandleGetBytesCommand, "", NULL, 0, 0, 0},
{ "unroot", 'd', &ChatHandler::HandleDebugUnroot, "", NULL, 0, 0, 0},
{ "root", 'd', &ChatHandler::HandleDebugRoot, "", NULL, 0, 0, 0},
{ "landwalk", 'd', &ChatHandler::HandleDebugLandWalk, "", NULL, 0, 0, 0},
{ "waterwalk", 'd', &ChatHandler::HandleDebugWaterWalk, "", NULL, 0, 0, 0},
{ "castspell", 'd', &ChatHandler::HandleCastSpellCommand, ".castspell <spellid> - Casts spell on target.", NULL, 0, 0, 0 },
{ "castspellne", 'd', &ChatHandler::HandleCastSpellNECommand, ".castspellne <spellid> - Casts spell on target (only plays animations, doesnt handle effects or range/facing/etc.", NULL, 0, 0, 0 },
{ "celldelete", 'd', &ChatHandler::HandleCellDeleteCommand, "!USE WITH CAUTION! '.celldelete YES' - Removes everything in current cell from game and database. '.celldelete YES YES' removes everything in a range of 1cell.", NULL, 0, 0, 0},
{ "addrestxp", 'd', &ChatHandler::HandleAddRestXPCommand, ".addrestxp - Adds x rest XP to player.", NULL, 0, 0, 0 },
{ "generatename",'d', &ChatHandler::HandleGenerateNameCommand, ".generatename - Generates name for pet, etc.", NULL, 0, 0, 0 },
{ "attackerinfo",'d', &ChatHandler::HandleAttackerInfoCommand, ".attackerinfo - Shows selected mob/player's attacker's infomation.", NULL, 0, 0, 0 },
{ "showattackers",'d',&ChatHandler::HandleShowAttackersCommand, ".showattackers - Shows selected mob/player's attacker on the minimap.", NULL, 0, 0, 0 },
{ "aggrorange", 'd', &ChatHandler::HandleAggroRangeCommand, ".aggrorange - Shows aggro Range of the selected Creature.", NULL, 0, 0, 0 },
{ "knockback ", 'd', &ChatHandler::HandleKnockBackCommand, ".knockback <value> - Knocks you back.", NULL, 0, 0, 0 },
{ "fade ", 'd', &ChatHandler::HandleFadeCommand, ".fade <value> - calls ModThreatModifyer().", NULL, 0, 0, 0 },
{ "threatMod ", 'd', &ChatHandler::HandleThreatModCommand, ".threatMod <value> - calls ModGeneratedThreatModifyer().", NULL, 0, 0, 0 },
{ "calcThreat ", 'd', &ChatHandler::HandleCalcThreatCommand, ".calcThreat <dmg> <spellId> - calculates threat.", NULL, 0, 0, 0 },
{ "threatList ", 'd', &ChatHandler::HandleThreatListCommand, ".threatList - returns all AI_Targets of the selected Creature.", NULL, 0, 0, 0 },
{ "gettptime", 'd', &ChatHandler::HandleGetTransporterTime, "grabs transporter travel time",NULL, 0, 0, 0 },
{ "itempushresult",'d',&ChatHandler::HandleSendItemPushResult, "sends item push result", NULL, 0, 0, 0 },
{ "weather", 'd', &ChatHandler::HandleWeatherCommand, "", NULL, 0, 0, 0},
{ "setbit", 'd', &ChatHandler::HandleModifyBitCommand, "", NULL, 0, 0, 0},
{ "setvalue", 'd', &ChatHandler::HandleModifyValueCommand, "", NULL, 0, 0, 0},
{ NULL, 0, NULL, "", NULL, 0, 0 }
};
static ChatCommand waypointCommandTable[] =
{
{ "add", 'w', &ChatHandler::HandleWPAddCommand, "Add wp at current pos", NULL, 0, 0, 0},
{ "show", 'w', &ChatHandler::HandleWPShowCommand, "Show wp's for creature", NULL, 0, 0, 0},
{ "hide", 'w', &ChatHandler::HandleWPHideCommand, "Hide wp's for creature", NULL, 0, 0, 0},
{ "delete", 'w', &ChatHandler::HandleWPDeleteCommand, "Delete selected wp", NULL, 0, 0, 0},
{ "movehere", 'w', &ChatHandler::HandleWPMoveHereCommand, "Move to this wp", NULL, 0, 0, 0},
{ "flags", 'w', &ChatHandler::HandleWPFlagsCommand, "Wp flags", NULL, 0, 0, 0},
{ "waittime", 'w', &ChatHandler::HandleWPWaitCommand, "Wait time at this wp", NULL, 0, 0, 0},
{ "emote", 'w', &ChatHandler::HandleWPEmoteCommand, "Emote at this wp", NULL, 0, 0, 0},
{ "skin", 'w', &ChatHandler::HandleWPSkinCommand, "Skin at this wp", NULL, 0, 0, 0},
{ "change", 'w', &ChatHandler::HandleWPChangeNoCommand, "Change at this wp", NULL, 0, 0, 0},
{ "info", 'w', &ChatHandler::HandleWPInfoCommand, "Show info for wp", NULL, 0, 0, 0},
{ "movetype", 'w', &ChatHandler::HandleWPMoveTypeCommand, "Movement type at wp", NULL, 0, 0, 0},
{ NULL, 0, NULL, "", NULL, 0, 0 }
};
static ChatCommand GMTicketCommandTable[] =
{
{ "get", 'g', &ChatHandler::HandleGMTicketGetAllCommand, "Gets GM Ticket", NULL, 0, 0, 0},
{ "getId", 'g', &ChatHandler::HandleGMTicketGetByIdCommand, "Gets GM Ticket by ID", NULL, 0, 0, 0},
{ "delId", 'g', &ChatHandler::HandleGMTicketDelByIdCommand, "Deletes GM Ticket by ID", NULL, 0, 0, 0},
{ NULL, 2, NULL, "", NULL, 0, 0 }
};
static ChatCommand GameObjectCommandTable[] =
{
{ "select", 'o', &ChatHandler::HandleGOSelect, "Selects the nearest GameObject to you", NULL, 0, 0, 0},
{ "delete", 'o', &ChatHandler::HandleGODelete, "Deletes selected GameObject", NULL, 0, 0, 0},
{ "spawn", 'o', &ChatHandler::HandleGOSpawn, "Spawns a GameObject by ID", NULL, 0, 0, 0},
{ "info", 'o', &ChatHandler::HandleGOInfo, "Gives you informations about selected GO", NULL, 0, 0, 0},
{ "activate", 'o', &ChatHandler::HandleGOActivate, "Activates/Opens the selected GO.", NULL, 0, 0, 0},
{ "enable", 'o', &ChatHandler::HandleGOEnable, "Enables the selected GO for use.", NULL, 0, 0, 0},
{ "scale", 'o', &ChatHandler::HandleGOScale, "Sets scale of selected GO", NULL, 0, 0, 0},
{ "animprogress",'o', &ChatHandler::HandleGOAnimProgress, "Sets anim progress", NULL, 0, 0, 0 },
{ "export", 'o', &ChatHandler::HandleGOExport, "Exports the current GO selected", NULL, 0, 0, 0 },
{ NULL, 2, NULL, "", NULL, 0, 0 }
};
static ChatCommand BattlegroundCommandTable[] =
{
{ "setbgscore", 'e', &ChatHandler::HandleSetBGScoreCommand, "<Teamid> <Score> - Sets battleground score. 2 Arguments. ", NULL, 0, 0, 0},
{ "startbg", 'e', &ChatHandler::HandleStartBGCommand, "Starts current battleground match.", NULL, 0, 0, 0},
{ "pausebg", 'e', &ChatHandler::HandlePauseBGCommand, "Pauses current battleground match.", NULL, 0, 0, 0},
{ "bginfo", 'e', &ChatHandler::HandleBGInfoCommnad, "Displays information about current battleground.", NULL, 0, 0, 0},
{ "battleground",'e', &ChatHandler::HandleBattlegroundCommand, "Shows BG Menu", NULL, 0, 0, 0 },
{ "setworldstate",'e',&ChatHandler::HandleSetWorldStateCommand, "<var> <val> - Var can be in hex. WS Value.", NULL, 0, 0, 0 },
{ "playsound", 'e', &ChatHandler::HandlePlaySoundCommand, "<val>. Val can be in hex.", NULL, 0, 0, 0 },
{ "setbfstatus", 'e', &ChatHandler::HandleSetBattlefieldStatusCommand,".setbfstatus - NYI.", NULL, 0, 0, 0 },
{ "leave", 'e', &ChatHandler::HandleBattlegroundExitCommand, "Leaves the current battleground.", NULL, 0, 0, 0 },
{ NULL, 2, NULL, "", NULL, 0, 0 }
};
static ChatCommand NPCCommandTable[] =
{
{ "vendoradditem", 'n', &ChatHandler::HandleItemCommand, "Adds to vendor", NULL, 0, 0, 0},
{ "vendorremoveitem",'n', &ChatHandler::HandleItemRemoveCommand,"Removes from vendor.", NULL, 0, 0, 0},
{ "name", 'n', &ChatHandler::HandleNameCommand, "Changes creature name", NULL, 0, 0, 0},
{ "subname", 'n', &ChatHandler::HandleSubNameCommand, "Changes creature subname", NULL, 0, 0, 0},
{ "flags", 'n', &ChatHandler::HandleNPCFlagCommand, "Changes NPC flags", NULL, 0, 0, 0},
{ "emote", 'n', &ChatHandler::HandleEmoteCommand, ".emote - Sets emote state", NULL, 0, 0, 0 },
{ "run", 'n', &ChatHandler::HandleRunCommand, "", NULL, 0, 0, 0},
{ "addweapon", 'n', &ChatHandler::HandleAddWeaponCommand, "", NULL, 0, 0, 0},
{ "allowmove", 'n', &ChatHandler::HandleAllowMovementCommand, "", NULL, 0, 0, 0},
{ "addgrave", 'n', &ChatHandler::HandleAddGraveCommand, "", NULL, 0, 0, 0},
{ "addsh", 'n', &ChatHandler::HandleAddSHCommand, "", NULL, 0, 0, 0},
{ "addspirit", 'n', &ChatHandler::HandleAddSpiritCommand, "", NULL, 0, 0, 0},
//{ "spawn", 'n', &ChatHandler::HandleSpawnCommand, "<entry> <flags> <faction> <level> <name>", NULL, 0, 0, 0},
{ "spawnentry", 'n', &ChatHandler::HandleSpawnEntryCommand, "<entry>", NULL, 0, 0, 0},
{ "delete", 'n', &ChatHandler::HandleDeleteCommand, "Deletes mob from db and world.", NULL, 0, 0, 0},
{ "info", 'n', &ChatHandler::HandleNpcInfoCommand, "Displays NPC information", NULL, 0, 0, 0},
{ "guid", 'n', &ChatHandler::HandleGUIDCommand, "Shows selected object guid", NULL, 0, 0, 0},
{ "addAgent", 'n', &ChatHandler::HandleAddAIAgentCommand, ".npc addAgent <agent> <procEvent> <procChance> <procCount> <spellId> <spellType> <spelltargetType> <spellCooldown> <floatMisc1> <Misc2>",NULL, 0, 0, 0},
{ "delAgent", 'n', &ChatHandler::HandleDelAIAgentCommand, ".npc delAgent <procEvent> <spellId>",NULL, 0, 0, 0},
{ "listAgent", 'n', &ChatHandler::HandleListAIAgentCommand, ".npc listAgent",NULL, 0, 0, 0},
{ "reset", 'n', &ChatHandler::HandleResetHPCommand, "resets npc health/dmg from temp table.", NULL, 0, 0, 0},
{ "export", 'n', &ChatHandler::HandleNpcExport, "Exports the npc to a sql file", NULL, 0, 0, 0},
{ "say", 'n', &ChatHandler::HandleMonsterSayCommand, ".npc say <text> - Makes selected mob say text <text>.", NULL, 0, 0, 0 },
{ "yell", 'n', &ChatHandler::HandleMonsterYellCommand, ".npc yell <Text> - Makes selected mob yell text <text>.", NULL, 0, 0, 0},
{ "come", 'n', &ChatHandler::HandleNpcComeCommand, ".npc come - Makes npc move to your position", NULL, 0, 0, 0 },
{ "return", 'n', &ChatHandler::HandleNpcReturnCommand, ".npc return - Returns ncp to spawnpoint.", NULL, 0, 0, 0 },
{ NULL, 2, NULL, "", NULL, 0, 0 }
};
static ChatCommand CheatCommandTable[] =
{
{ "status", 'm', &ChatHandler::HandleShowCheatsCommand, "Shows active cheats.", NULL, 0, 0, 0 },
{ "taxi", 'm', &ChatHandler::HandleTaxiCheatCommand, "Enables all taxi nodes.", NULL, 0, 0, 0},
{ "cooldown", 'm', &ChatHandler::HandleCooldownCheatCommand, "Enables no cooldown cheat.", NULL, 0, 0, 0 },
{ "casttime", 'm', &ChatHandler::HandleCastTimeCheatCommand, "Enables no cast time cheat.", NULL, 0, 0, 0 },
{ "power", 'm', &ChatHandler::HandlePowerCheatCommand, "Disables mana consumption etc.", NULL, 0, 0, 0 },
{ "god", 'm', &ChatHandler::HandleGodModeCommand, "Sets god mode, prevents you from taking damage.", NULL, 0, 0, 0 },
{ "fly", 'm', &ChatHandler::HandleFlyCommand, "Sets fly mode", NULL, 0, 0, 0 },
{ "land", 'm', &ChatHandler::HandleLandCommand, "Unsets fly mode", NULL, 0, 0, 0 },
{ "explore", 'm', &ChatHandler::HandleExploreCheatCommand, "Reveals the unexplored parts of the map.", NULL, 0, 0, 0 },
{ "flyspeed", 'm', &ChatHandler::HandleFlySpeedCheatCommand, "Modifies fly speed.", NULL, 0, 0, 0 },
{ "stack", 'm', &ChatHandler::HandleStackCheatCommand, "Enables aura stacking cheat.", NULL, 0, 0, 0 },
{ NULL, 0, NULL, "", NULL, 0, 0, 0 },
};
static ChatCommand honorCommandTable[] =
{
{ "getpvprank", 'm', &ChatHandler::HandleGetRankCommand, "Gets PVP Rank", NULL, 0, 0, 0},
{ "setpvprank", 'm', &ChatHandler::HandleSetRankCommand, "Sets PVP Rank", NULL, 0, 0, 0},
{ "addpoints", 'm', &ChatHandler::HandleAddHonorCommand, "Adds x amount of honor points/currency",NULL,0,0,0},
{ "addkills", 'm', &ChatHandler::HandleAddKillCommand, "Adds x amount of honor kills", NULL, 0, 0, 0 },
{ "globaldailyupdate", 'm', &ChatHandler::HandleGlobalHonorDailyMaintenanceCommand, "Daily honor field moves", NULL, 0, 0, 0},
{ "singledailyupdate", 'm', &ChatHandler::HandleNextDayCommand, "Daily honor field moves for selected player only", NULL,0,0,0},
{ "pvpcredit", 'm', &ChatHandler::HandlePVPCreditCommand, "Sends PVP credit packet, with specified rank and points", NULL,0,0,0},
{ NULL,0,NULL,"",NULL,0,0,0},
};
static ChatCommand petCommandTable[] =
{
{ "createpet",'m',&ChatHandler::HandleCreatePetCommand, "Creates a pet with <entry>.", NULL, 0, 0, 0 },
{ "renamepet",'m',&ChatHandler::HandleRenamePetCommand, "Renames a pet to <name>.", NULL, 0, 0, 0 },
{ "enablerename",'m',&ChatHandler::HandleEnableRenameCommand, "Enables pet rename.", NULL, 0, 0, 0 },
{ "addspell",'m',&ChatHandler::HandleAddPetSpellCommand, "Teaches pet <spell>.", NULL, 0, 0, 0 },
{ "removespell",'m',&ChatHandler::HandleRemovePetSpellCommand, "Removes pet spell <spell>.", NULL, 0, 0, 0 },
{ NULL,0,NULL,"",NULL,0,0,0},
};
static ChatCommand recallCommandTable[] =
{
{ "list", 'q', &ChatHandler::HandleRecallListCommand, "List recall locations", NULL, 0, 0, 0},
{ "port", 'q', &ChatHandler::HandleRecallGoCommand, "Port to recalled location", NULL, 0, 0, 0},
{ "add", 'q', &ChatHandler::HandleRecallAddCommand, "Add recall location", NULL, 0, 0, 0},
{ "del", 'q', &ChatHandler::HandleRecallDelCommand, "Remove a recall location", NULL, 0, 0, 0},
{ NULL, 0, NULL, "", NULL, 0, 0, 0},
};
static ChatCommand commandTable[] = {
{ "commands", 1, &ChatHandler::HandleCommandsCommand, "Shows Commands", NULL, 0, 0, 0},
{ "help", 1, &ChatHandler::HandleHelpCommand, "Shows help for command", NULL, 0, 0, 0},
{ "announce", 'u', &ChatHandler::HandleAnnounceCommand, "Sends Msg To All", NULL, 0, 0, 0},
{ "wannounce", 'u', &ChatHandler::HandleWAnnounceCommand, "Sends Widescreen Msg To All", NULL, 0, 0, 0},
{ "appear", 'v', &ChatHandler::HandleAppearCommand, "Teleports to x's position.", NULL, 0, 0, 0},
{ "summon", 'v', &ChatHandler::HandleSummonCommand, "Summons x to your position", NULL, 0, 0, 0},
{ "banchar", 'b', &ChatHandler::HandleBanCharacterCommand, "Bans character x with or without reason", NULL, 0, 0, 0},
{ "unbanchar", 'b', &ChatHandler::HandleUnBanCharacterCommand,"Unbans character x", NULL, 0, 0, 0},
{ "banreason", 'b', &ChatHandler::HandleBanReasonCharacterCommand, "Shows the reason for ban", NULL, 0, 0, 0},
{ "kick", 'b', &ChatHandler::HandleKickCommand, "Kicks player from server", NULL, 0, 0, 0},
{ "kill", 'r', &ChatHandler::HandleKillCommand, ".kill - Kills selected unit.", NULL, 0, 0, 0},
{ "revive", 'r', &ChatHandler::HandleReviveCommand, "Revives you.", NULL, 0, 0, 0},
{ "reviveplr", 'r', &ChatHandler::HandleReviveStringcommand, "Revives player specified.", NULL, 0, 0, 0},
{ "morph", 'm', &ChatHandler::HandleMorphCommand, "Morphs into model id x.", NULL, 0, 0, 0},
{ "demorph", 'm', &ChatHandler::HandleDeMorphCommand, "Demorphs from morphed model.", NULL, 0, 0, 0},
{ "mount", 'm', &ChatHandler::HandleMountCommand, "Mounts into modelid x.", NULL, 0, 0, 0},
{ "dismount", 1, &ChatHandler::HandleDismountCommand, "Dismounts.", NULL, 0, 0, 0},
{ "gm", 'p', &ChatHandler::HandleGMListCommand, "Shows active GM's", NULL, 0, 0, 0},
{ "gmoff", 't', &ChatHandler::HandleGMOffCommand, "Sets GM tag off", NULL, 0, 0, 0},
{ "gmon", 't', &ChatHandler::HandleGMOnCommand, "Sets GM tag on", NULL, 0, 0, 0},
{ "gps", 'p', &ChatHandler::HandleGPSCommand, "Shows Position", NULL, 0, 0, 0},
{ "info", 'p', &ChatHandler::HandleInfoCommand, "Server info", NULL, 0, 0, 0},
{ "worldport", 'v', &ChatHandler::HandleWorldPortCommand, "", NULL, 0, 0, 0},
{ "save", 's', &ChatHandler::HandleSaveCommand, "Save's your character", NULL, 0, 0, 0},
{ "saveall", 's', &ChatHandler::HandleSaveAllCommand, "Save's all playing characters", NULL, 0, 0, 0},
{ "security", 'z', &ChatHandler::HandleSecurityCommand, "", NULL, 0, 0, 0},
{ "start", 'm', &ChatHandler::HandleStartCommand, "Teleport's you to a starting location", NULL, 0, 0, 0},
{ "levelup", 'm', &ChatHandler::HandleLevelUpCommand, "", NULL, 0, 0, 0},
{ "additem", 'm', &ChatHandler::HandleAddInvItemCommand, "", NULL, 0, 0, 0},
{ "createguild", 'l', &ChatHandler::CreateGuildCommand, "", NULL, 0, 0, 0},
{ "invincible", 'j', &ChatHandler::HandleInvincibleCommand, ".invincible - Toggles INVINCIBILITY (mobs won't attack you)", NULL, 0, 0, 0},
{ "invisible", 'i', &ChatHandler::HandleInvisibleCommand, ".invisible - Toggles INVINCIBILITY and INVISIBILITY (mobs won't attack you and nobody can see you, but they can see your chat messages)", NULL, 0, 0, 0},
{ "resetreputation", 'n',&ChatHandler::HandleResetReputationCommand, ".resetreputation - Resets reputation to start levels. (use on characters that were made before reputation fixes.)", NULL, 0, 0, 0},
{ "resetlevel", 'n', &ChatHandler::HandleResetLevelCommand, ".resetlevel - Resets all stats to level 1 of targeted player. DANGEROUS.", NULL, 0, 0, 0 },
{ "resetspells", 'n', &ChatHandler::HandleResetSpellsCommand, ".resetspells - Resets all spells to starting spells of targeted player. DANGEROUS.", NULL, 0, 0, 0 },
{ "resettalents",'n', &ChatHandler::HandleResetTalentsCommand, ".resettalents - Resets all talents of targeted player to that of their current level. DANGEROUS.", NULL, 0, 0, 0 },
{ "resetskills", 'n', &ChatHandler::HandleResetSkillsCommand , ".resetskills - Resets all skills.", NULL, 0, 0, 0 },
{ "learn", 'm', &ChatHandler::HandleLearnCommand, "Learns spell", NULL, 0, 0, 0},
{ "unlearn", 'm', &ChatHandler::HandleUnlearnCommand, "Unlearns spell", NULL, 0, 0, 0},
{ "learnskill", 'm', &ChatHandler::HandleLearnSkillCommand, ".learnskill <skillid> (optional) <value> <maxvalue> - Learns skill id skillid.", NULL, 0, 0, 0},
{ "advanceskill",'m', &ChatHandler::HandleModifySkillCommand, "advanceskill <skillid> <amount, optional, default = 1> - Advances skill line x times..", NULL, 0, 0, 0},
{ "removeskill", 'm', &ChatHandler::HandleRemoveSkillCommand, ".removeskill <skillid> - Removes skill", NULL, 0, 0, 0 },
{ "increaseweaponskill", 'm', &ChatHandler::HandleIncreaseWeaponSkill, ".increaseweaponskill <count> - Increase eqipped weapon skill x times (defaults to 1).", NULL, 0, 0, 0},
{ "createaccount",'z',&ChatHandler::HandleCreateAccountCommand, ".createaccount - Creates account. Format should be .createaccount username password email", NULL, 0, 0, 0 },
{ "playerinfo", 'z', &ChatHandler::HandlePlayerInfo, ".playerinfo - Displays informations about the selected character (account...)", NULL, 0, 0, 0 },
{ "uptime", 1, &ChatHandler::HandleUptimeCommand, "Shows server uptime", NULL, 0, 0, 0},
{ "modify", 'm', NULL, "", modifyCommandTable, 0, 0, 0},
{ "waypoint", 'w', NULL, "", waypointCommandTable, 0, 0, 0},
{ "debug", 'd', NULL, "", debugCommandTable, 0, 0, 0},
{ "gmTicket", 'g', NULL, "", GMTicketCommandTable, 0, 0, 0},
{ "gobject", 'o', NULL, "", GameObjectCommandTable, 0, 0, 0},
{ "battleground", 'e', NULL, "", BattlegroundCommandTable, 0, 0, 0},
{ "npc" , 'n', NULL, "", NPCCommandTable, 0, 0, 0},
{ "cheat" , 'm', NULL, "", CheatCommandTable, 0, 0, 0},
{ "honor" , 'm', NULL, "", honorCommandTable, 0, 0, 0},
{ "pet", 'm', NULL, "", petCommandTable, 0, 0, 0},
{ "recall", 'q', NULL, "", recallCommandTable, 0, 0, 0},
{ "getpos" , 'd', &ChatHandler::HandleGetPosCommand, "", NULL, 0, 0, 0},
{ "removeauras", 'm', &ChatHandler::HandleRemoveAurasCommand, "Removes all auras from target", NULL, 0, 0, 0},
{ "paralyze", 'b', &ChatHandler::HandleParalyzeCommand, "Roots/Paralyzes the target.", NULL, 0, 0, 0 },
{ "unparalyze", 'b', &ChatHandler::HandleUnParalyzeCommand, "Unroots/Unparalyzes the target.",NULL, 0, 0, 0 },
{ "setmotd", 'm', &ChatHandler::HandleSetMotdCommand, "Sets MOTD", NULL, 0, 0, 0 },
{ "additemset", 'm', &ChatHandler::HandleAddItemSetCommand, "Adds item set to inv.", NULL, 0, 0, 0 },
{ "gotrig", 'v', &ChatHandler::HandleTriggerCommand, "Warps to areatrigger <id>", NULL, 0, 0, 0 },
{ "createinstance",'m', &ChatHandler::HandleCreateInstanceCommand,"Creates instance on map <map>", NULL, 0, 0, 0 },
{ "goinstance", 'm', &ChatHandler::HandleGoInstanceCommand, "Joins instance <instance> <x> <y> <z> <optional mapid>", NULL, 0, 0, 0 },
{ "exitinstance", 'm', &ChatHandler::HandleExitInstanceCommand, "Exits current instance, return to entry point.", NULL, 0, 0, 0 },
{ "dbreload", 'm', &ChatHandler::HandleDBReloadCommand, "Reloads some of the database tables", NULL, 0, 0, 0 },
{ "spawnspiritguide",'m', &ChatHandler::HandleSpawnSpiritGuideCommand, "Spawns a spirit guide (params: 1 = horde, 0 = alliance", NULL, 0, 0, 0 },
{ "servershutdown", 'z', &ChatHandler::HandleShutdownCommand, "Initiates server shutdown in <x> seconds.", NULL, 0, 0, 0 },
{ "serverrestart", 'z', &ChatHandler::HandleShutdownRestartCommand, "Initiates server restart in <x> seconds.", NULL, 0, 0, 0 },
{ "allowwhispers", 'c', &ChatHandler::HandleAllowWhispersCommand, "Allows whispers from player <s> while in gmon mode.", NULL, 0, 0, 0 },
{ "blockwhispers", 'c', &ChatHandler::HandleBlockWhispersCommand, "Blocks whispers from player <s> while in gmon mode.", NULL, 0, 0, 0 },
{ "advanceallskills", 'm', &ChatHandler::HandleAdvanceAllSkillsCommand, "Advances all skills <x> points.", NULL, 0, 0, 0 },
{ "killbyplayer", 'f', &ChatHandler::HandleKillByPlayerCommand, "Disconnects the player with name <s>.", NULL, 0, 0, 0 },
{ "killbyaccount", 'f', &ChatHandler::HandleKillBySessionCommand, "Disconnects the session with account name <s>.", NULL, 0, 0, 0 },
{ "unlockmovement", 'm',&ChatHandler::HandleUnlockMovementCommand, "Unlocks movement for player.", NULL, 0, 0, 0},
{ "castall", 'z', &ChatHandler::HandleCastAllCommand, "Makes all players online cast spell <x>.", NULL, 0, 0, 0},
{ "getrate", 'f', &ChatHandler::HandleGetRateCommand, "Gets rate <x>.", NULL, 0, 0, 0 },
{ "setrate", 'f', &ChatHandler::HandleSetRateCommand, "Sets rate <x>.", NULL, 0, 0, 0 },
{ "modperiod" , 'm', &ChatHandler::HandleModPeriodCommand, "Changes period of current transporter.", NULL, 0, 0, 0 },
{ "npcfollow", 'm', &ChatHandler::HandleNpcFollowCommand, "Sets npc to follow you", NULL, 0, 0, 0 },
{ "nullfollow", 'm', &ChatHandler::HandleNullFollowCommand, "Sets npc to not follow anything", NULL, 0, 0, 0 },
{ "formationlink1", 'm', &ChatHandler::HandleFormationLink1Command, "Sets formation master.", NULL, 0, 0, 0 },
{ "formationlink2", 'm', &ChatHandler::HandleFormationLink2Command, "Sets formation slave with distance and angle", NULL, 0, 0, 0 },
{ "formationclear", 'm', &ChatHandler::HandleFormationClearCommand, "Removes formation from creature", NULL, 0, 0, 0 },
{ NULL, 0, NULL, "", NULL, 0, 0 }
};
return commandTable;
}
bool ChatHandler::hasStringAbbr(const char* s1, const char* s2)
{
for(;;)
{
if( !*s2 )
return true;
else if( !*s1 )
return false;
else if( tolower( *s1 ) != tolower( *s2 ) )
return false;
s1++; s2++;
}
}
void ChatHandler::SendMultilineMessage(WorldSession *m_session, const char *str)
{
char buf[256];
const char* line = str;
const char* pos = line;
while((pos = strchr(line, '\n')) != NULL)
{
strncpy(buf, line, pos-line);
buf[pos-line]=0;
SystemMessage(m_session, buf);
line = pos+1;
}
SystemMessage(m_session, line);
}
bool ChatHandler::ExecuteCommandInTable(ChatCommand *table, const char* text, WorldSession *m_session)
{
std::string cmd = "";
// get command
while (*text != ' ' && *text != '\0')
{
cmd += *text;
text++;
}
while (*text == ' ') text++; // skip whitespace
if(!cmd.length())
return false;
for(uint32 i = 0; table[i].Name != NULL; i++)
{
if(!hasStringAbbr(table[i].Name, cmd.c_str()))
continue;
if(!m_session->CanUseCommand(table[i].CommandGroup))
continue;
if(table[i].ChildCommands != NULL)
{
if(!ExecuteCommandInTable(table[i].ChildCommands, text, m_session))
{
if(table[i].Help != "")
SendMultilineMessage(m_session, table[i].Help.c_str());
else
{
GreenSystemMessage(m_session, "Available Subcommands:");
for(uint32 k=0; table[i].ChildCommands[k].Name;k++)
{
if(m_session->CanUseCommand(table[i].ChildCommands[k].CommandGroup))
BlueSystemMessage(m_session, " %s - %s", table[i].ChildCommands[k].Name, table[i].ChildCommands[k].Help.size() ? table[i].ChildCommands[k].Help.c_str() : "No Help Available");
}
}
}
return true;
}
// Check for field-based commands
if(table[i].Handler == NULL && (table[i].MaxValueField || table[i].NormalValueField))
{
bool result = false;
if(strlen(text) == 0)
{
RedSystemMessage(m_session, "No values specified.");
}
if(table[i].ValueType == 2)
result = CmdSetFloatField(m_session, table[i].NormalValueField, table[i].MaxValueField, table[i].Name, text);
else
result = CmdSetValueField(m_session, table[i].NormalValueField, table[i].MaxValueField, table[i].Name, text);
if(!result)
RedSystemMessage(m_session, "Must be in the form of (command) <value>, or, (command) <value> <maxvalue>");
}
else
{
if(!(this->*(table[i].Handler))(text, m_session))
{
if(table[i].Help != "")
SendMultilineMessage(m_session, table[i].Help.c_str());
else
{
RedSystemMessage(m_session, "Incorrect syntax specified. Try .help %s for the correct syntax.", table[i].Name);
}
}
}
return true;
}
return false;
}
int ChatHandler::ParseCommands(const char* text, WorldSession *session)
{
if (!session)
return 0;
ASSERT(text);
ASSERT(*text);
if(session->GetPermissionCount() == 0)
return 0;
if(text[0] != '!' && text[0] != '.') // let's not confuse users
return 0;
text++;
if(!ExecuteCommandInTable(getCommandTable(), text, session))
{
SystemMessage(session, "There is no such command, or you do not have access to it.");
}
return 1;
}
WorldPacket * ChatHandler::FillMessageData( uint32 type, uint32 language, const char *message,uint64 guid , uint8 flag) const
{
//Packet structure
//uint8 type;
//uint32 language;
//uint64 guid;
//uint64 guid;
//uint32 len_of_text;
//char text[]; // not sure ? i think is null terminated .. not null terminated
//uint8 afk_state;
ASSERT(type != CHAT_MSG_CHANNEL);
//channels are handled in channel handler and so on
uint32 messageLength = strlen((char*)message) + 1;
WorldPacket *data = new WorldPacket(SMSG_MESSAGECHAT, messageLength + 30);
data->Initialize(SMSG_MESSAGECHAT);
*data << (uint8)type;
*data << language;
/*if (type == CHAT_MSG_CHANNEL)
{
ASSERT(channelName);
*data << channelName;
}*/
*data << guid;
// crashfix
if (type == CHAT_MSG_SAY || type == CHAT_MSG_YELL || type == CHAT_MSG_PARTY || type == 0x53)
*data << guid;
*data << messageLength;
*data << message;
//*data << uint8(0); // afk
*data << uint8(flag);
return data;
}
WorldPacket* ChatHandler::FillSystemMessageData(const char *message) const
{
uint32 messageLength = strlen((char*)message) + 1;
WorldPacket * data = new WorldPacket(SMSG_MESSAGECHAT, 20 + messageLength);
data->Initialize(SMSG_MESSAGECHAT);
*data << (uint8)CHAT_MSG_SYSTEM;
*data << (uint32)LANG_UNIVERSAL;
*data << (uint64)0; // Who cares about guid when there's no nickname displayed heh ?
*data << messageLength;
*data << message;
*data << uint8(0);
return data;
}
void ChatHandler::SpawnCreature(WorldSession *session, const char* name, uint32 displayId, uint32 npcFlags, uint32 factionId, uint32 level)
{
// Create the requested monster
Player *chr = session->GetPlayer();
float x = chr->GetPositionX();
float y = chr->GetPositionY();
float z = chr->GetPositionZ();
float o = chr->GetOrientation();
Creature* pCreature = sObjHolder.Create<Creature>();
pCreature->SetInstanceID(session->GetPlayer()->GetInstanceID());
pCreature->Create(name, chr->GetMapId(), x, y, z, o);
pCreature->SetZoneId(chr->GetZoneId());
pCreature->SetUInt32Value(OBJECT_FIELD_ENTRY, objmgr.AddCreatureName(pCreature->GetName(), displayId));
pCreature->SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
pCreature->SetUInt32Value(UNIT_FIELD_DISPLAYID, displayId);
pCreature->SetUInt32Value(UNIT_NPC_FLAGS , npcFlags);
pCreature->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE , factionId);
pCreature->SetUInt32Value(UNIT_FIELD_HEALTH, 28 + 30*level);
pCreature->SetUInt32Value(UNIT_FIELD_MAXHEALTH, 28 + 30*level);
pCreature->SetUInt32Value(UNIT_FIELD_LEVEL , level);
pCreature->SetFloatValue(UNIT_FIELD_COMBATREACH , 1.5f);
pCreature->SetFloatValue(UNIT_FIELD_MAXDAMAGE , 5.0f);
pCreature->SetFloatValue(UNIT_FIELD_MINDAMAGE , 8.0f);
pCreature->SetUInt32Value(UNIT_FIELD_BASEATTACKTIME, 1900);
pCreature->SetUInt32Value(UNIT_FIELD_BASEATTACKTIME+1, 2000);
pCreature->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 2.0f);
//sLog.outError("AddObject at Chat.cpp");
pCreature->_setFaction();
pCreature->AddToWorld();
CreatureTemplate *t = new CreatureTemplate;
t->Create(pCreature);
pCreature->GetMapMgr()->GetBaseMap()->GetTemplate()->AddIndex<Creature>(pCreature, t);
pCreature->SaveToDB();
}
Player * ChatHandler::getSelectedChar(WorldSession *m_session, bool showerror)
{
uint64 guid;
Player *chr;
guid = m_session->GetPlayer()->GetSelection();
if (guid == 0)
{
if(showerror)
GreenSystemMessage(m_session, "Auto-targeting self.");
chr = m_session->GetPlayer(); // autoselect
}
else
chr = World::GetPlayer(guid);
if(chr == NULL)
{
if(showerror)
RedSystemMessage(m_session, "This command requires that you select a player.");
return NULL;
}
return chr;
}
Creature * ChatHandler::getSelectedCreature(WorldSession *m_session, bool showerror)
{
uint64 guid;
Creature *creature;
guid = m_session->GetPlayer()->GetSelection();
creature = World::GetCreature(guid);
if(creature != NULL)
return creature;
else
{
if(showerror)
RedSystemMessage(m_session, "This command requires that you select a creature.");
return NULL;
}
}
void ChatHandler::SystemMessage(WorldSession *m_session, const char* message, ...)
{
if( !message ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
WorldPacket * data = FillSystemMessageData(msg1);
if(m_session != NULL)
m_session->SendPacket(data);
delete data;
}
void ChatHandler::ColorSystemMessage(WorldSession *m_session, const char* colorcode, const char *message, ...)
{
if( !message ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
char msg[1024];
sprintf(msg, "%s%s|r", colorcode, msg1);
WorldPacket * data = FillSystemMessageData(msg);
if(m_session != NULL)
m_session->SendPacket(data);
delete data;
}
void ChatHandler::RedSystemMessage(WorldSession *m_session, const char *message, ...)
{
if( !message ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
char msg[1024];
sprintf(msg, "%s%s|r", MSG_COLOR_LIGHTRED/*MSG_COLOR_RED*/, msg1);
WorldPacket * data = FillSystemMessageData(msg);
if(m_session != NULL)
m_session->SendPacket(data);
delete data;
}
void ChatHandler::GreenSystemMessage(WorldSession *m_session, const char *message, ...)
{
if( !message ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
char msg[1024];
sprintf(msg, "%s%s|r", MSG_COLOR_GREEN, msg1);
WorldPacket * data = FillSystemMessageData(msg);
if(m_session != NULL)
m_session->SendPacket(data);
delete data;
}
void ChatHandler::BlueSystemMessage(WorldSession *m_session, const char *message, ...)
{
if( !message ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
char msg[1024];
sprintf(msg, "%s%s|r", MSG_COLOR_LIGHTBLUE, msg1);
WorldPacket * data = FillSystemMessageData(msg);
if(m_session != NULL)
m_session->SendPacket(data);
delete data;
}
void ChatHandler::RedSystemMessageToPlr(Player* plr, const char *message, ...)
{
if( !message || !plr->GetSession() ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
RedSystemMessage(plr->GetSession(), (const char*)msg1);
}
void ChatHandler::GreenSystemMessageToPlr(Player* plr, const char *message, ...)
{
if( !message || !plr->GetSession() ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
GreenSystemMessage(plr->GetSession(), (const char*)msg1);
}
void ChatHandler::BlueSystemMessageToPlr(Player* plr, const char *message, ...)
{
if( !message || !plr->GetSession() ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
BlueSystemMessage(plr->GetSession(), (const char*)msg1);
}
void ChatHandler::SystemMessageToPlr(Player *plr, const char* message, ...)
{
if( !message || !plr->GetSession() ) return;
va_list ap;
va_start(ap, message);
char msg1[1024];
vsprintf(msg1,message,ap);
SystemMessage(plr->GetSession(), msg1);
}
bool ChatHandler::CmdSetValueField(WorldSession *m_session, uint32 field, uint32 fieldmax, const char *fieldname, const char *args)
{
if(!args) return false;
char* pvalue = strtok((char*)args, " ");
uint32 mv, av;
if (!pvalue)
return false;
else
av = atol(pvalue);
if(fieldmax)
{
char* pvaluemax = strtok(NULL, " ");
if (!pvaluemax)
return false;
else
mv = atol(pvaluemax);
}
else
{
mv = 0;
}
if (av <= 0 && mv > 0)
{
RedSystemMessage(m_session, "Values are invalid. Value must be < max (if max exists), and both must be > 0.");
return true;
}
if(fieldmax)
{
if(mv < av || mv <= 0)
{
RedSystemMessage(m_session, "Values are invalid. Value must be < max (if max exists), and both must be > 0.");
return true;
}
}
Player *plr = getSelectedChar(m_session, false);
if(plr)
{
sGMLog.writefromsession(m_session, "used modify field value: %s, %u on %s", fieldname, av, plr->GetName());
if(fieldmax)
{
BlueSystemMessage(m_session, "You set the %s of %s to %d/%d.", fieldname, plr->GetName(), av, mv);
GreenSystemMessageToPlr(plr, "%s set your %s to %d/%d.", m_session->GetPlayer()->GetName(), fieldname, av, mv);
}
else
{
BlueSystemMessage(m_session, "You set the %s of %s to %d.", fieldname, plr->GetName(), av);
GreenSystemMessageToPlr(plr, "%s set your %s to %d.", m_session->GetPlayer()->GetName(), fieldname, av);
}
if(field == UNIT_FIELD_STAT1) av /= 2;
if(field == UNIT_FIELD_BASE_HEALTH)
{
plr->SetUInt32Value(UNIT_FIELD_HEALTH, av);
plr->SetBaseUInt32Value(UNIT_FIELD_HEALTH,av);
}
plr->SetUInt32Value(field, av);
plr->SetBaseUInt32Value(field,av);
if(fieldmax) {
plr->SetUInt32Value(fieldmax, mv);
plr->SetBaseUInt32Value(fieldmax,mv);
}
}
else
{
Creature *cr = getSelectedCreature(m_session, false);
if(cr)
{
if(!(field < UNIT_END && fieldmax < UNIT_END)) return false;
std::string creaturename = "Unknown Being";
if(cr->GetCreatureName())
creaturename = cr->GetCreatureName()->Name;
if(fieldmax)
BlueSystemMessage(m_session, "Setting %s of %s to %d/%d.", fieldname, creaturename.c_str(), av, mv);
else
BlueSystemMessage(m_session, "Setting %s of %s to %d.", fieldname, creaturename.c_str(), av);
sGMLog.writefromsession(m_session, "used modify field value: [creature]%s, %u on %s", fieldname, av, creaturename.c_str());
if(field == UNIT_FIELD_STAT1) av /= 2;
if(field == UNIT_FIELD_BASE_HEALTH)
{
cr->SetUInt32Value(UNIT_FIELD_HEALTH, av);
cr->SetBaseUInt32Value(UNIT_FIELD_HEALTH,av);
}
cr->SetUInt32Value(field, av);
cr->SetBaseUInt32Value(field,av);
if(fieldmax) {
cr->SetUInt32Value(fieldmax, mv);
cr->SetBaseUInt32Value(fieldmax,mv);
}
// reset faction
if(field == UNIT_FIELD_FACTIONTEMPLATE)
cr->_setFaction();
cr->SaveToDB();
}
else
{
RedSystemMessage(m_session, "Invalid Selection.");
}
}
return true;
}
bool ChatHandler::CmdSetFloatField(WorldSession *m_session, uint32 field, uint32 fieldmax, const char *fieldname, const char *args)
{
char* pvalue = strtok((char*)args, " ");
float mv, av;
if (!pvalue)
return false;
else
av = (float)atof(pvalue);
if(fieldmax)
{
char* pvaluemax = strtok(NULL, " ");
if (!pvaluemax)
return false;
else
mv = (float)atof(pvaluemax);
}
else
{
mv = 0;
}
if (av <= 0)
{
RedSystemMessage(m_session, "Values are invalid. Value must be < max (if max exists), and both must be > 0.");
return true;
}
if(fieldmax)
{
if(mv < av || mv <= 0)
{
RedSystemMessage(m_session, "Values are invalid. Value must be < max (if max exists), and both must be > 0.");
return true;
}
}
Player *plr = getSelectedChar(m_session, false);
if(plr)
{
sGMLog.writefromsession(m_session, "used modify field value: %s, %f on %s", fieldname, av, plr->GetName());
if(fieldmax)
{
BlueSystemMessage(m_session, "You set the %s of %s to %.1f/%.1f.", fieldname, plr->GetName(), av, mv);
GreenSystemMessageToPlr(plr, "%s set your %s to %.1f/%.1f.", m_session->GetPlayer()->GetName(), fieldname, av, mv);
}
else
{
BlueSystemMessage(m_session, "You set the %s of %s to %.1f.", fieldname, plr->GetName(), av);
GreenSystemMessageToPlr(plr, "%s set your %s to %.1f.", m_session->GetPlayer()->GetName(), fieldname, av);
}
plr->SetFloatValue(field, av);
if(fieldmax) plr->SetFloatValue(fieldmax, mv);
}
else
{
Creature *cr = getSelectedCreature(m_session, false);
if(cr)
{
if(!(field < UNIT_END && fieldmax < UNIT_END)) return false;
std::string creaturename = "Unknown Being";
if(cr->GetCreatureName())
creaturename = cr->GetCreatureName()->Name;
if(fieldmax)
BlueSystemMessage(m_session, "Setting %s of %s to %.1f/%.1f.", fieldname, creaturename.c_str(), av, mv);
else
BlueSystemMessage(m_session, "Setting %s of %s to %.1f.", fieldname, creaturename.c_str(), av);
cr->SetFloatValue(field, av);
cr->SetBaseFloatValue(field,mv);
sGMLog.writefromsession(m_session, "used modify field value: [creature]%s, %f on %s", fieldname, av, creaturename.c_str());
if(fieldmax) {
cr->SetFloatValue(fieldmax, mv);
cr->SetBaseFloatValue(fieldmax,mv);
}
//cr->SaveToDB();
}
else
{
RedSystemMessage(m_session, "Invalid Selection.");
}
}
return true;
}
bool ChatHandler::HandleGetPosCommand(const char* args, WorldSession *m_session)
{
/*if(m_session->GetPlayer()->GetSelection() == 0) return false;
Creature *creature = objmgr.GetCreature(m_session->GetPlayer()->GetSelection());
if(!creature) return false;
BlueSystemMessage(m_session, "Creature Position: \nX: %f\nY: %f\nZ: %f\n", creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ());
return true;*/
uint32 spell = atol(args);
SpellEntry *se = sSpellStore.LookupEntry(spell);
if(se)
BlueSystemMessage(m_session, "SpellIcon for %d is %d", se->Id, se->field114);
return true;
}
|
[
"[email protected]"
] |
[
[
[
1,
943
]
]
] |
9bcf7ab36d0643787ecb7a47c097ffa0fcca3619
|
6f1b053deb725638eb80930dd633e965a1c8beb3
|
/Server/RessourceManager.cpp
|
ccda9c10ff869516ede06d1e6c87b2aabedb6b27
|
[] |
no_license
|
ArrowU/112simulator
|
ddf2e27bf95be2be5799b53474fab787527d2290
|
7b355cb12fb2955d3d1d0fb165a566eba4fad89d
|
refs/heads/master
| 2016-09-01T10:53:27.235941 | 2009-12-14T05:54:05 | 2009-12-14T05:54:05 | 48,593,696 | 0 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 8,874 |
cpp
|
#include "RessourceManager.h"
#include "Ressource.h"
#include "Call.h"
#include <stdio.h>
RessourceManager::RessourceManager()
{
// initialisation des buffers
waitingListPrio0 = new MSBuffer<Call>(10); // prio absolue
waitingListPrio1 = new MSBuffer<Call>(10);
waitingListPrio2 = new MSBuffer<Call>(10);
waitingListPrio3 = new MSBuffer<Call>(10);
choppers = new MSBuffer<Ressource>(1);
ambulances = new MSBuffer<Ressource>(5);
medics = new MSBuffer<Ressource>(3);
teams = new MSBuffer<Ressource>(5);
// initialisation des ressources
for (int i = 0; i < choppers->getMaxSize(); i++)
{
choppers->addElement(new Ressource(Ressource::CHOPPER, i));
}
for (int i = 0; i < ambulances->getMaxSize(); i++)
{
ambulances->addElement(new Ressource(Ressource::AMBULANCE, i));
}
for (int i = 0; i < medics->getMaxSize(); i++)
{
medics->addElement(new Ressource(Ressource::MEDIC, i));
}
for (int i = 0; i < teams->getMaxSize(); i++)
{
teams->addElement(new Ressource(Ressource::TEAM, i));
}
// initialisation des mutex et des balises
threadSafeLock1 = new MSMutex(MSMutex::START_UNLOCKED);
threadSafeLock2 = new MSMutex(MSMutex::START_UNLOCKED);
threadSafeLock3 = new MSMutex(MSMutex::START_UNLOCKED);
threadSafeLock0 = new MSMutex(MSMutex::START_UNLOCKED);
threadSafeLockChopper = new MSMutex(MSMutex::START_UNLOCKED);
MSMutex *threadSafeLockAmbulance = new MSMutex(MSMutex::START_UNLOCKED);
MSMutex *threadSafeLockMedic = new MSMutex(MSMutex::START_UNLOCKED);
MSMutex *threadSafeLockTeam = new MSMutex(MSMutex::START_UNLOCKED);
newCall1 = false;
newCall2 = false;
newCall3 = false;
newCall0 = false;
hasNewRessource = false;
printf("RessourceManager created... \n");
}
void RessourceManager::start()
{
printf("RessourceManager launched... \n");
while (true)
{
threadSafeLock0->waitForUnlock(MSMutex::WAIT_INFINITE);
checkList(waitingListPrio0);
newCall0 = false;
threadSafeLock0->unlock();
hasNewRessource = false;
if (!newCall0 && !hasNewRessource)
{
threadSafeLock1->waitForUnlock(MSMutex::WAIT_INFINITE);
checkList(waitingListPrio1);
newCall1 = false;
threadSafeLock1->unlock();
}
if (!newCall0 && !newCall1 && !hasNewRessource)
{
threadSafeLock2->waitForUnlock(MSMutex::WAIT_INFINITE);
checkList(waitingListPrio2);
newCall2 = false;
threadSafeLock2->unlock();
}
if (!newCall0 && !newCall1 && !newCall2 && !hasNewRessource)
{
threadSafeLock3->waitForUnlock(MSMutex::WAIT_INFINITE);
checkList(waitingListPrio3);
newCall3 = false;
threadSafeLock3->unlock();
}
//incrementation du temps
timeControl();
}
}
void RessourceManager::addCallToWaitingList(Call* call)
{
//test de possibilite de l'appel
int requiredChoppers = call->getRequiredChoppers();
int requiredAmbulances = call->getRequiredAmbulances();
int requiredMedics = call->getRequiredMedics();
int requiredTeams = call->getRequiredTeams();
if (requiredChoppers > choppers->getMaxSize() || requiredAmbulances > ambulances->getMaxSize() || requiredMedics > medics->getMaxSize() || requiredTeams > teams->getMaxSize())
{
call->abort();
}
// si possible, encodage dans les listes d'attente
else
{
switch (call->getSource())
{
case Call::NURSING_HOME:
threadSafeLock1->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio1->addElement(call);
newCall1 = true;
threadSafeLock1->unlock();
break;
case Call::SCHOOL:
threadSafeLock2->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio2->addElement(call);
newCall2 = true;
threadSafeLock2->unlock();
break;
case Call::PRIVATE_INDIVIDUAL:
threadSafeLock3->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio3->addElement(call);
newCall3 = true;
threadSafeLock3->unlock();
break;
}
}
call->setWaitedTime(0);
//printf("Call checked... \n");
}
void RessourceManager::releaseRessources(Call *call)
{
while (call->hasRessources())
{
Ressource *ressource = call->freeRessources();
switch(ressource->getType())
{
case Ressource::CHOPPER:
//threadSafeLockChopper->waitForUnlock(MSMutex::WAIT_INFINITE);
choppers->addElement(ressource);
//threadSafeLockChopper->unlock();
break;
case Ressource::AMBULANCE:
//threadSafeLockAmbulance->waitForUnlock(MSMutex::WAIT_INFINITE);
ambulances->addElement(ressource);
//threadSafeLockAmbulance->unlock();
break;
case Ressource::MEDIC:
//threadSafeLockMedic->waitForUnlock(MSMutex::WAIT_INFINITE);
medics->addElement(ressource);
//threadSafeLockMedic->unlock();
break;
case Ressource::TEAM:
//threadSafeLockTeam->waitForUnlock(MSMutex::WAIT_INFINITE);
teams->addElement(ressource);
//threadSafeLockTeam->unlock();
break;
default:
printf("Error in RessourceManager while trying to free Ressources \n");
system("pause");
}
}
hasNewRessource = true;
}
bool RessourceManager::possibleMission(Call* call)
{
if (call->getRequiredChoppers() > choppers->getCurrentSize() || call->getRequiredAmbulances() > ambulances->getCurrentSize() || call->getRequiredMedics() > medics->getCurrentSize() || call->getRequiredTeams() > teams->getCurrentSize())
return false;
else
return true;
}
void RessourceManager::checkList(MSBuffer<Call>* waitingList)
{
for (int i = 0; i < waitingList->getCurrentSize(); i++)
{
Call* waiting = waitingList->getElement(MSBuffer<Call>::RETURN_NULL_IF_EMPTY);
if(waiting==NULL) system("pause");
if (possibleMission(waiting))
{
// on ajoute les ressources
//threadSafeLockChopper->waitForUnlock(MSMutex::WAIT_INFINITE);
for (int i = 0; i < waiting->getRequiredChoppers(); i++)
{
waiting->addRessource(choppers->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT));
}
//threadSafeLockChopper->unlock();
//threadSafeLockAmbulance->waitForUnlock(MSMutex::WAIT_INFINITE);
for (int i = 0; i < waiting->getRequiredAmbulances(); i++)
{
waiting->addRessource(ambulances->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT));
}
//threadSafeLockAmbulance->unlock();
//threadSafeLockMedic->waitForUnlock(MSMutex::WAIT_INFINITE);
for (int i = 0; i < waiting->getRequiredMedics(); i++)
{
waiting->addRessource(medics->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT));
}
//threadSafeLockMedic->unlock();
//threadSafeLockTeam->waitForUnlock(MSMutex::WAIT_INFINITE);
for (int i = 0; i < waiting->getRequiredTeams(); i++)
{
waiting->addRessource(teams->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT));
}
//threadSafeLockTeam->unlock();
//on lance la mission
waiting->readyToStart();
// Le call va alors prévenir l'opérateur, qui va créer les threads correspondant, qui font le sleep(rand)
// puis libèrent les ressources, puis vont Logger l'appel;
}
else
{
// on remet l'appel dans la liste...
waitingList->addElement(waiting);
}
}
}
void RessourceManager::timeControl()
{
Call* call;
//liste 1
for (int i = 0; i < waitingListPrio1->getCurrentSize(); i++)
{
call = waitingListPrio1->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT);
call->setWaitedTime(call->getWaitedTime());
if (call->getWaitedTime() > waitingTime)
{
threadSafeLock0->waitForUnlock(MSMutex::WAIT_INFINITE);
call->setWaitedTime(0);
waitingListPrio0->addElement(call);
threadSafeLock0->unlock();
}
else
{
threadSafeLock1->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio1->addElement(call);
threadSafeLock1->unlock();
}
}
//liste 2
for (int i = 0; i < waitingListPrio2->getCurrentSize(); i++)
{
call = waitingListPrio2->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT);
call->setWaitedTime(call->getWaitedTime());
if (call->getWaitedTime() > waitingTime)
{
threadSafeLock1->waitForUnlock(MSMutex::WAIT_INFINITE);
call->setWaitedTime(0);
waitingListPrio1->addElement(call);
threadSafeLock1->unlock();
}
else
{
threadSafeLock2->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio2->addElement(call);
threadSafeLock2->unlock();
}
}
//liste 3
for (int i = 0; i < waitingListPrio3->getCurrentSize(); i++)
{
call = waitingListPrio3->getElement(MSBuffer<Ressource>::WAIT_FOR_ELEMENT);
call->setWaitedTime(call->getWaitedTime());
if (call->getWaitedTime() > waitingTime)
{
threadSafeLock2->waitForUnlock(MSMutex::WAIT_INFINITE);
call->setWaitedTime(0);
waitingListPrio2->addElement(call);
threadSafeLock2->unlock();
}
else
{
threadSafeLock3->waitForUnlock(MSMutex::WAIT_INFINITE);
waitingListPrio3->addElement(call);
threadSafeLock3->unlock();
}
}
}
|
[
"overbanck@0974c598-c7c7-11de-ba9a-9db95b2bc6c5",
"Snowangelic@0974c598-c7c7-11de-ba9a-9db95b2bc6c5"
] |
[
[
[
1,
1
],
[
6,
11
],
[
13,
21
],
[
23,
23
],
[
25,
25
],
[
27,
27
],
[
29,
29
],
[
31,
31
],
[
33,
33
],
[
35,
35
],
[
37,
51
],
[
53,
64
],
[
67,
72
],
[
74,
79
],
[
81,
91
],
[
93,
94
],
[
99,
99
],
[
101,
101
],
[
103,
106
],
[
108,
108
],
[
112,
112
],
[
114,
115
],
[
119,
119
],
[
121,
122
],
[
126,
126
],
[
128,
131
],
[
133,
134
],
[
136,
138
],
[
141,
142
],
[
144,
144
],
[
146,
147
],
[
149,
149
],
[
151,
152
],
[
154,
154
],
[
156,
157
],
[
159,
159
],
[
161,
170
],
[
172,
172
],
[
174,
178
],
[
180,
180
],
[
182,
182
],
[
185,
187
],
[
190,
190
],
[
192,
192
],
[
196,
196
],
[
198,
198
],
[
202,
202
],
[
204,
204
],
[
208,
208
],
[
210,
210
],
[
212,
213
],
[
216,
219
],
[
221,
226
],
[
228,
230
],
[
232,
232
],
[
234,
250
],
[
252,
252
],
[
254,
270
],
[
272,
272
],
[
274,
287
]
],
[
[
2,
5
],
[
12,
12
],
[
22,
22
],
[
24,
24
],
[
26,
26
],
[
28,
28
],
[
30,
30
],
[
32,
32
],
[
34,
34
],
[
36,
36
],
[
52,
52
],
[
65,
66
],
[
73,
73
],
[
80,
80
],
[
92,
92
],
[
95,
98
],
[
100,
100
],
[
102,
102
],
[
107,
107
],
[
109,
111
],
[
113,
113
],
[
116,
118
],
[
120,
120
],
[
123,
125
],
[
127,
127
],
[
132,
132
],
[
135,
135
],
[
139,
140
],
[
143,
143
],
[
145,
145
],
[
148,
148
],
[
150,
150
],
[
153,
153
],
[
155,
155
],
[
158,
158
],
[
160,
160
],
[
171,
171
],
[
173,
173
],
[
179,
179
],
[
181,
181
],
[
183,
184
],
[
188,
189
],
[
191,
191
],
[
193,
195
],
[
197,
197
],
[
199,
201
],
[
203,
203
],
[
205,
207
],
[
209,
209
],
[
211,
211
],
[
214,
215
],
[
220,
220
],
[
227,
227
],
[
231,
231
],
[
233,
233
],
[
251,
251
],
[
253,
253
],
[
271,
271
],
[
273,
273
]
]
] |
4d09db4e039032c9892497231a8b6dc58cd9ced8
|
36fea6c98ecabcd5e932f2b7854b3282cdb571ee
|
/debug/plugins/moc_qteditorfactory.cpp
|
071b889512233aa1c0c1fd2fc9b632acdb88e60a
|
[] |
no_license
|
doomfrawen/visualcommand
|
976adaae69303d8b4ffc228106a1db9504e4a4e4
|
f7bc1d590444ff6811f84232f5c6480449228e19
|
refs/heads/master
| 2016-09-06T17:40:57.775379 | 2009-07-28T22:48:23 | 2009-07-28T22:48:23 | 32,345,504 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 34,453 |
cpp
|
/****************************************************************************
** Meta object code from reading C++ file 'qteditorfactory.h'
**
** Created: Fri Jun 19 11:29:23 2009
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../src/qteditorfactory.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qteditorfactory.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QtSpinBoxFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
5, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
20, 18, 17, 17, 0x08,
60, 57, 17, 17, 0x08,
98, 18, 17, 17, 0x08,
137, 17, 17, 17, 0x08,
155, 17, 17, 17, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtSpinBoxFactory[] = {
"QtSpinBoxFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,int)\0"
",,\0slotRangeChanged(QtProperty*,int,int)\0"
"slotSingleStepChanged(QtProperty*,int)\0"
"slotSetValue(int)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtSpinBoxFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtIntPropertyManager>::staticMetaObject, qt_meta_stringdata_QtSpinBoxFactory,
qt_meta_data_QtSpinBoxFactory, 0 }
};
const QMetaObject *QtSpinBoxFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtSpinBoxFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtSpinBoxFactory))
return static_cast<void*>(const_cast< QtSpinBoxFactory*>(this));
return QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacast(_clname);
}
int QtSpinBoxFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 1: d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 2: d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 3: d_func()->slotSetValue((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 5;
}
return _id;
}
static const uint qt_meta_data_QtSliderFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
5, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
19, 17, 16, 16, 0x08,
59, 56, 16, 16, 0x08,
97, 17, 16, 16, 0x08,
136, 16, 16, 16, 0x08,
154, 16, 16, 16, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtSliderFactory[] = {
"QtSliderFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,int)\0"
",,\0slotRangeChanged(QtProperty*,int,int)\0"
"slotSingleStepChanged(QtProperty*,int)\0"
"slotSetValue(int)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtSliderFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtIntPropertyManager>::staticMetaObject, qt_meta_stringdata_QtSliderFactory,
qt_meta_data_QtSliderFactory, 0 }
};
const QMetaObject *QtSliderFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtSliderFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtSliderFactory))
return static_cast<void*>(const_cast< QtSliderFactory*>(this));
return QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacast(_clname);
}
int QtSliderFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 1: d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 2: d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 3: d_func()->slotSetValue((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 5;
}
return _id;
}
static const uint qt_meta_data_QtScrollBarFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
5, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
22, 20, 19, 19, 0x08,
62, 59, 19, 19, 0x08,
100, 20, 19, 19, 0x08,
139, 19, 19, 19, 0x08,
157, 19, 19, 19, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtScrollBarFactory[] = {
"QtScrollBarFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,int)\0"
",,\0slotRangeChanged(QtProperty*,int,int)\0"
"slotSingleStepChanged(QtProperty*,int)\0"
"slotSetValue(int)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtScrollBarFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtIntPropertyManager>::staticMetaObject, qt_meta_stringdata_QtScrollBarFactory,
qt_meta_data_QtScrollBarFactory, 0 }
};
const QMetaObject *QtScrollBarFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtScrollBarFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtScrollBarFactory))
return static_cast<void*>(const_cast< QtScrollBarFactory*>(this));
return QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacast(_clname);
}
int QtScrollBarFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtIntPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 1: d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 2: d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 3: d_func()->slotSetValue((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 5;
}
return _id;
}
static const uint qt_meta_data_QtCheckBoxFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
21, 19, 18, 18, 0x08,
59, 18, 18, 18, 0x08,
78, 18, 18, 18, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtCheckBoxFactory[] = {
"QtCheckBoxFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,bool)\0"
"slotSetValue(bool)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtCheckBoxFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtBoolPropertyManager>::staticMetaObject, qt_meta_stringdata_QtCheckBoxFactory,
qt_meta_data_QtCheckBoxFactory, 0 }
};
const QMetaObject *QtCheckBoxFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtCheckBoxFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtCheckBoxFactory))
return static_cast<void*>(const_cast< QtCheckBoxFactory*>(this));
return QtAbstractEditorFactory<QtBoolPropertyManager>::qt_metacast(_clname);
}
int QtCheckBoxFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtBoolPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
case 1: d_func()->slotSetValue((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtDoubleSpinBoxFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
6, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
26, 24, 23, 23, 0x08,
69, 66, 23, 23, 0x08,
113, 24, 23, 23, 0x08,
155, 24, 23, 23, 0x08,
192, 23, 23, 23, 0x08,
213, 23, 23, 23, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtDoubleSpinBoxFactory[] = {
"QtDoubleSpinBoxFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,double)\0"
",,\0slotRangeChanged(QtProperty*,double,double)\0"
"slotSingleStepChanged(QtProperty*,double)\0"
"slotDecimalsChanged(QtProperty*,int)\0"
"slotSetValue(double)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtDoubleSpinBoxFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtDoublePropertyManager>::staticMetaObject, qt_meta_stringdata_QtDoubleSpinBoxFactory,
qt_meta_data_QtDoubleSpinBoxFactory, 0 }
};
const QMetaObject *QtDoubleSpinBoxFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtDoubleSpinBoxFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtDoubleSpinBoxFactory))
return static_cast<void*>(const_cast< QtDoubleSpinBoxFactory*>(this));
return QtAbstractEditorFactory<QtDoublePropertyManager>::qt_metacast(_clname);
}
int QtDoubleSpinBoxFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtDoublePropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2]))); break;
case 1: d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2])),(*reinterpret_cast< double(*)>(_a[3]))); break;
case 2: d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2]))); break;
case 3: d_func()->slotDecimalsChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 4: d_func()->slotSetValue((*reinterpret_cast< double(*)>(_a[1]))); break;
case 5: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 6;
}
return _id;
}
static const uint qt_meta_data_QtLineEditFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
4, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
21, 19, 18, 18, 0x08,
62, 19, 18, 18, 0x08,
101, 18, 18, 18, 0x08,
123, 18, 18, 18, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtLineEditFactory[] = {
"QtLineEditFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QString)\0"
"slotRegExpChanged(QtProperty*,QRegExp)\0"
"slotSetValue(QString)\0"
"slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtLineEditFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtStringPropertyManager>::staticMetaObject, qt_meta_stringdata_QtLineEditFactory,
qt_meta_data_QtLineEditFactory, 0 }
};
const QMetaObject *QtLineEditFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtLineEditFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtLineEditFactory))
return static_cast<void*>(const_cast< QtLineEditFactory*>(this));
return QtAbstractEditorFactory<QtStringPropertyManager>::qt_metacast(_clname);
}
int QtLineEditFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtStringPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break;
case 1: d_func()->slotRegExpChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRegExp(*)>(_a[2]))); break;
case 2: d_func()->slotSetValue((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 3: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 4;
}
return _id;
}
static const uint qt_meta_data_QtDateEditFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
4, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
21, 19, 18, 18, 0x08,
63, 60, 18, 18, 0x08,
105, 18, 18, 18, 0x08,
125, 18, 18, 18, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtDateEditFactory[] = {
"QtDateEditFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QDate)\0"
",,\0slotRangeChanged(QtProperty*,QDate,QDate)\0"
"slotSetValue(QDate)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtDateEditFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtDatePropertyManager>::staticMetaObject, qt_meta_stringdata_QtDateEditFactory,
qt_meta_data_QtDateEditFactory, 0 }
};
const QMetaObject *QtDateEditFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtDateEditFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtDateEditFactory))
return static_cast<void*>(const_cast< QtDateEditFactory*>(this));
return QtAbstractEditorFactory<QtDatePropertyManager>::qt_metacast(_clname);
}
int QtDateEditFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtDatePropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDate(*)>(_a[2]))); break;
case 1: d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDate(*)>(_a[2])),(*reinterpret_cast< const QDate(*)>(_a[3]))); break;
case 2: d_func()->slotSetValue((*reinterpret_cast< const QDate(*)>(_a[1]))); break;
case 3: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 4;
}
return _id;
}
static const uint qt_meta_data_QtTimeEditFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
21, 19, 18, 18, 0x08,
60, 18, 18, 18, 0x08,
80, 18, 18, 18, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtTimeEditFactory[] = {
"QtTimeEditFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QTime)\0"
"slotSetValue(QTime)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtTimeEditFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtTimePropertyManager>::staticMetaObject, qt_meta_stringdata_QtTimeEditFactory,
qt_meta_data_QtTimeEditFactory, 0 }
};
const QMetaObject *QtTimeEditFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtTimeEditFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtTimeEditFactory))
return static_cast<void*>(const_cast< QtTimeEditFactory*>(this));
return QtAbstractEditorFactory<QtTimePropertyManager>::qt_metacast(_clname);
}
int QtTimeEditFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtTimePropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QTime(*)>(_a[2]))); break;
case 1: d_func()->slotSetValue((*reinterpret_cast< const QTime(*)>(_a[1]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtDateTimeEditFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
25, 23, 22, 22, 0x08,
68, 22, 22, 22, 0x08,
92, 22, 22, 22, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtDateTimeEditFactory[] = {
"QtDateTimeEditFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QDateTime)\0"
"slotSetValue(QDateTime)\0"
"slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtDateTimeEditFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtDateTimePropertyManager>::staticMetaObject, qt_meta_stringdata_QtDateTimeEditFactory,
qt_meta_data_QtDateTimeEditFactory, 0 }
};
const QMetaObject *QtDateTimeEditFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtDateTimeEditFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtDateTimeEditFactory))
return static_cast<void*>(const_cast< QtDateTimeEditFactory*>(this));
return QtAbstractEditorFactory<QtDateTimePropertyManager>::qt_metacast(_clname);
}
int QtDateTimeEditFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtDateTimePropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDateTime(*)>(_a[2]))); break;
case 1: d_func()->slotSetValue((*reinterpret_cast< const QDateTime(*)>(_a[1]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtKeySequenceEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
30, 28, 27, 27, 0x08,
76, 27, 27, 27, 0x08,
103, 27, 27, 27, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtKeySequenceEditorFactory[] = {
"QtKeySequenceEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QKeySequence)\0"
"slotSetValue(QKeySequence)\0"
"slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtKeySequenceEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtKeySequencePropertyManager>::staticMetaObject, qt_meta_stringdata_QtKeySequenceEditorFactory,
qt_meta_data_QtKeySequenceEditorFactory, 0 }
};
const QMetaObject *QtKeySequenceEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtKeySequenceEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtKeySequenceEditorFactory))
return static_cast<void*>(const_cast< QtKeySequenceEditorFactory*>(this));
return QtAbstractEditorFactory<QtKeySequencePropertyManager>::qt_metacast(_clname);
}
int QtKeySequenceEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtKeySequencePropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QKeySequence(*)>(_a[2]))); break;
case 1: d_func()->slotSetValue((*reinterpret_cast< const QKeySequence(*)>(_a[1]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtCharEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
23, 21, 20, 20, 0x08,
62, 20, 20, 20, 0x08,
82, 20, 20, 20, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtCharEditorFactory[] = {
"QtCharEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QChar)\0"
"slotSetValue(QChar)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtCharEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtCharPropertyManager>::staticMetaObject, qt_meta_stringdata_QtCharEditorFactory,
qt_meta_data_QtCharEditorFactory, 0 }
};
const QMetaObject *QtCharEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtCharEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtCharEditorFactory))
return static_cast<void*>(const_cast< QtCharEditorFactory*>(this));
return QtAbstractEditorFactory<QtCharPropertyManager>::qt_metacast(_clname);
}
int QtCharEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtCharPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QChar(*)>(_a[2]))); break;
case 1: d_func()->slotSetValue((*reinterpret_cast< const QChar(*)>(_a[1]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtEnumEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
5, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
23, 21, 20, 20, 0x08,
60, 21, 20, 20, 0x08,
106, 21, 20, 20, 0x08,
156, 20, 20, 20, 0x08,
174, 20, 20, 20, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtEnumEditorFactory[] = {
"QtEnumEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,int)\0"
"slotEnumNamesChanged(QtProperty*,QStringList)\0"
"slotEnumIconsChanged(QtProperty*,QMap<int,QIcon>)\0"
"slotSetValue(int)\0slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtEnumEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtEnumPropertyManager>::staticMetaObject, qt_meta_stringdata_QtEnumEditorFactory,
qt_meta_data_QtEnumEditorFactory, 0 }
};
const QMetaObject *QtEnumEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtEnumEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtEnumEditorFactory))
return static_cast<void*>(const_cast< QtEnumEditorFactory*>(this));
return QtAbstractEditorFactory<QtEnumPropertyManager>::qt_metacast(_clname);
}
int QtEnumEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtEnumPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 1: d_func()->slotEnumNamesChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QStringList(*)>(_a[2]))); break;
case 2: d_func()->slotEnumIconsChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QMap<int,QIcon>(*)>(_a[2]))); break;
case 3: d_func()->slotSetValue((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 5;
}
return _id;
}
static const uint qt_meta_data_QtCursorEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
25, 23, 22, 22, 0x08,
66, 23, 22, 22, 0x08,
99, 22, 22, 22, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtCursorEditorFactory[] = {
"QtCursorEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QCursor)\0"
"slotEnumChanged(QtProperty*,int)\0"
"slotEditorDestroyed(QObject*)\0"
};
const QMetaObject QtCursorEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtCursorPropertyManager>::staticMetaObject, qt_meta_stringdata_QtCursorEditorFactory,
qt_meta_data_QtCursorEditorFactory, 0 }
};
const QMetaObject *QtCursorEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtCursorEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtCursorEditorFactory))
return static_cast<void*>(const_cast< QtCursorEditorFactory*>(this));
return QtAbstractEditorFactory<QtCursorPropertyManager>::qt_metacast(_clname);
}
int QtCursorEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtCursorPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QCursor(*)>(_a[2]))); break;
case 1: d_func()->slotEnumChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtColorEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
24, 22, 21, 21, 0x08,
64, 21, 21, 21, 0x08,
94, 21, 21, 21, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtColorEditorFactory[] = {
"QtColorEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QColor)\0"
"slotEditorDestroyed(QObject*)\0"
"slotSetValue(QColor)\0"
};
const QMetaObject QtColorEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtColorPropertyManager>::staticMetaObject, qt_meta_stringdata_QtColorEditorFactory,
qt_meta_data_QtColorEditorFactory, 0 }
};
const QMetaObject *QtColorEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtColorEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtColorEditorFactory))
return static_cast<void*>(const_cast< QtColorEditorFactory*>(this));
return QtAbstractEditorFactory<QtColorPropertyManager>::qt_metacast(_clname);
}
int QtColorEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtColorPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QColor(*)>(_a[2]))); break;
case 1: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
case 2: d_func()->slotSetValue((*reinterpret_cast< const QColor(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
static const uint qt_meta_data_QtFontEditorFactory[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
23, 21, 20, 20, 0x08,
62, 20, 20, 20, 0x08,
92, 20, 20, 20, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QtFontEditorFactory[] = {
"QtFontEditorFactory\0\0,\0"
"slotPropertyChanged(QtProperty*,QFont)\0"
"slotEditorDestroyed(QObject*)\0"
"slotSetValue(QFont)\0"
};
const QMetaObject QtFontEditorFactory::staticMetaObject = {
{ &QtAbstractEditorFactory<QtFontPropertyManager>::staticMetaObject, qt_meta_stringdata_QtFontEditorFactory,
qt_meta_data_QtFontEditorFactory, 0 }
};
const QMetaObject *QtFontEditorFactory::metaObject() const
{
return &staticMetaObject;
}
void *QtFontEditorFactory::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtFontEditorFactory))
return static_cast<void*>(const_cast< QtFontEditorFactory*>(this));
return QtAbstractEditorFactory<QtFontPropertyManager>::qt_metacast(_clname);
}
int QtFontEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QtAbstractEditorFactory<QtFontPropertyManager>::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: d_func()->slotPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QFont(*)>(_a[2]))); break;
case 1: d_func()->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
case 2: d_func()->slotSetValue((*reinterpret_cast< const QFont(*)>(_a[1]))); break;
default: ;
}
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
[
"flouger@13a168e0-7ae3-11de-a146-1f7e517e55b8"
] |
[
[
[
1,
950
]
]
] |
462430cf67f5ae483c5865f62497f13b8e284792
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemgetvalue/src/tsemgetvaluecases.cpp
|
7f3f11b477109a1525585bb43239df703ecd3a3c
|
[] |
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 | 28,000 |
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:
*
*/
#include "tsemgetvalue.h"
#include <e32svr.h>
int (*fp)(void* arg);
int func(void* arg);
int func1(void* arg);
int func2(void* arg);
int func3(void* arg);
int func4(void* arg);
TInt SemInit(ThreadData* aThreadData)
{
TInt retval=0;
semParam_t* semParam =NULL;
if(semParam)
{
retval = sem_init(aThreadData->iTestSemaphore,semParam->pshared,semParam->value);
}
else
{
retval = sem_init(aThreadData->iTestSemaphore,0,0);
}
return retval;
}
TInt SemGetValue(ThreadData* aThreadData)
{
int retval=0;
retval = sem_getvalue(aThreadData->iTestSemaphore,&(aThreadData->iValue));
return retval;
}
TInt CheckValue(ThreadData* aThreadData,int expectedResult)
{
int retval=0;
if ( (expectedResult == aThreadData->iValue) )
{
retval = 0;
}
else
{
retval = KValueMismatch;
}
return retval;
}
int SemDestroy(ThreadData* aThreadData)
{
int retval=0;
retval = sem_destroy(aThreadData->iTestSemaphore);
return retval;
}
int SemWait(ThreadData* aThreadData)
{
int retval=0;
aThreadData->iSuspending = true;
sem_post(aThreadData->iSuspendSemaphore);
retval = sem_wait(aThreadData->iTestSemaphore);
aThreadData->iSuspending = false;
return retval;
}
void StopThread(ThreadData* aThreadData)
{
if(aThreadData->iSelf != EThreadMain)
{
aThreadData->iStopped = true;
sem_post(aThreadData->iSuspendSemaphore);
#ifdef USE_RTHREAD
User::Exit(KErrNone);
#endif
}
}
int SemPost(ThreadData* aThreadData)
{
int retval=0;
retval = sem_post(aThreadData->iTestSemaphore);
return retval;
}
int WaitForSignal(ThreadData* aThreadData)
{
int retval;
retval = sem_wait(aThreadData->iSignalSemaphore);
return retval;
}
int PostSignal(ThreadData* aThreadData)
{
int retval=0;
retval = sem_post(aThreadData->iSignalSemaphore);
return retval;
}
int ThreadCreate(ThreadData* aThreadData, void* aThreadId)
{
HarnessThread threadId;
int retval=0;
if(aThreadData->iSelf != EThreadMain)
{
retval = KNoPermission;
}
else
{
threadId = (HarnessThread)(int) aThreadId;
retval = NewThread(aThreadData,threadId);
}
return retval;
}
int NewThread(ThreadData* aThreadData, HarnessThread aThreadId)
{
ThreadData* newData = new ThreadData;
if(!newData)
{
return KNoMemory;
}
if(aThreadId < EThreadMain && aThreadId >= 0)
{
aThreadData->iTDArr[aThreadId] = newData;
}
else
{
return KNoArgument;
}
newData->iSignalSemaphore = aThreadData->iSignalSemaphore;
newData->iSuspendSemaphore = aThreadData->iSuspendSemaphore;
newData->iTestSemaphore = aThreadData->iTestSemaphore;
newData->iTestMutex = aThreadData->iTestMutex;
newData->iTestCondVar = aThreadData->iTestCondVar;
newData->iDefaultAttr = aThreadData->iDefaultAttr;
newData->iErrorcheckAttr = aThreadData->iErrorcheckAttr;
newData->iRecursiveAttr = aThreadData->iRecursiveAttr;
newData->iCondAttr = aThreadData->iCondAttr;
newData->iSuspending = false;
newData->iSpinCounter = 0;
newData->iCurrentCommand = -1;
newData->iSelf = aThreadId;
newData->iValue = 0;
newData->iRetValue = 0;
newData->ierrno = 0;
newData->iValue = 0;
newData->iExpectederrno = 0;
newData->iTimes = 0;
newData->iStopped = false;
newData->iCommonData = aThreadData->iCommonData;
#ifdef USE_RTHREAD
TBuf<10> threadName;
threadName.NumFixedWidth(TUint(aThreadId), EDecimal, 10);
RThread lNewThread;
lNewThread.Create(
(const TDesC &)threadName, // Thread Name
_mrtEntryPtFun, // Entry pt function
KDefaultStackSize, // Stack Size
NULL, // Use common heap
(TAny*)newData); // Args to entry pt function
lNewThread.Resume();
lNewThread.Close();
#else
pthread_create(&aThreadData->iIdArr[aThreadId],NULL,StartFn,(void*)newData);
#endif
return 0;
}
int ThreadDestroy(ThreadData* aThreadData,void* aThreadId)
{
int retval=0;
HarnessThread threadId;
if(aThreadData->iSelf != EThreadMain)
{
retval = KNoPermission;
}
else
{
threadId = (HarnessThread)(int) aThreadId;
retval = DeleteThread(aThreadData,threadId);
}
return retval;
}
int DeleteThread(ThreadData* aThreadData, HarnessThread aThreadId)
{
#ifndef USE_RTHREAD
pthread_join(aThreadData->iIdArr[aThreadId],NULL);
#else
int signalsEaten = 0;
sem_wait(aThreadData->iSuspendSemaphore);
while(aThreadData->iTDArr[aThreadId]->iStopped == false)
{
signalsEaten++;
sem_wait(aThreadData->iSuspendSemaphore);
}
for(int i=0; i<signalsEaten; i++)
{
sem_post(aThreadData->iSuspendSemaphore);
}
#endif
if(aThreadData->iTDArr[aThreadId]->iRetValue != 0)
{
printf("Thread %d errvalue %d\n",aThreadId,aThreadData->iTDArr[aThreadId]->iRetValue);
}
delete aThreadData->iTDArr[aThreadId];
aThreadData->iTDArr[aThreadId] = NULL;
return 0;
}
void WaitTillSuspended(ThreadData* aThreadData,void* aThreadId)
{
HarnessThread threadId;
ThreadData* lTarget;
int signalsEaten =0;
int i=0;
threadId = (HarnessThread) (int) aThreadId;
lTarget = NULL;
if(threadId >=0 && threadId < EThreadMain)
{
lTarget = aThreadData->iTDArr[threadId];
}
if(lTarget)
{
sem_wait(lTarget->iSuspendSemaphore);
while(lTarget->iSuspending == false)
{
signalsEaten++;
sem_wait(lTarget->iSuspendSemaphore);
}
for(i=0; i <signalsEaten; i++)
{
sem_post(lTarget->iSuspendSemaphore);
}
}
}
void* StartFn(void* arg)
{
int retval=0;
retval = (*fp)(arg);
return (void *)retval;
}
int func(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = SemWait(pData);
retval = CheckValue(pData,0);
retval = PostSignal(pData);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
int func1(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = SemWait(pData);
retval = CheckValue(pData,0);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
int func2(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = SemWait(pData);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
int func3(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = SemWait(pData);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
int func4(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = SemWait(pData);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
//sem_getvalue on an uninitialized semaphore
TInt CTestSemgetvalue::TestSem313()
{
/*
TRACE("+TestSem313\n");
HarnessCommand lCommandArr[255] =
{
{EThreadMain, ESemInit},
{EThreadMain, ESemDestroy},
{EThreadMain, ESemGetValue},
{EThreadMain, EVerifyErrno, (void*) EINVAL},
{EThreadMain, EStop},
{ENoThread, ELastCommand},
};
TRACE("-TestSem313\n");
return LoadHarness(lCommandArr);*/
return 0;
}
//sem_getvalue on a newly initialized semaphore
TInt CTestSemgetvalue::TestSem314( )
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
retval = SemInit(&lThreadData);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,0);
retval = SemDestroy(&lThreadData);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//sem_getvalue on a semaphore posted once
TInt CTestSemgetvalue::TestSem315( )
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
retval = SemInit(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,1);
retval = SemDestroy(&lThreadData);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//sem_getvalue on a semaphore posted n times
TInt CTestSemgetvalue::TestSem316( )
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
retval = SemInit(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemWait(&lThreadData);
retval = SemWait(&lThreadData);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,2);
retval = SemDestroy(&lThreadData);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//sem_getvalue on a semaphore waited on once
TInt CTestSemgetvalue::TestSem317( )
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
fp=func;
retval = SemInit(&lThreadData);
retval = ThreadCreate(&lThreadData, (void*) EThread1);
WaitTillSuspended(&lThreadData, (void*) EThread1);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,0);
retval = SemPost(&lThreadData);
retval = WaitForSignal(&lThreadData);
retval = ThreadDestroy(&lThreadData, (void*) EThread1);
retval = SemDestroy(&lThreadData);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//sem_getvalue on a semaphore waited on n times
TInt CTestSemgetvalue::TestSem318( )
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
retval = SemInit(&lThreadData);
fp=func1;
retval = ThreadCreate(&lThreadData, (void*) EThread1);
fp=func2;
retval = ThreadCreate(&lThreadData, (void*) EThread2);
fp=func3;
retval = ThreadCreate(&lThreadData, (void*) EThread3);
fp=func4;
retval = ThreadCreate(&lThreadData, (void*) EThread4);
WaitTillSuspended(&lThreadData, (void*) EThread1);
WaitTillSuspended(&lThreadData, (void*) EThread2);
WaitTillSuspended(&lThreadData, (void*) EThread3);
WaitTillSuspended(&lThreadData, (void*) EThread4);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,-4);
retval = SemPost(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemGetValue(&lThreadData);
retval = CheckValue(&lThreadData,-2);
retval = SemPost(&lThreadData);
retval = SemPost(&lThreadData);
retval = SemGetValue(&lThreadData);
retval = ThreadDestroy(&lThreadData, (void*) EThread1);
retval = ThreadDestroy(&lThreadData, (void*) EThread2);
retval = ThreadDestroy(&lThreadData, (void*) EThread3);
retval = ThreadDestroy(&lThreadData, (void*) EThread4);
retval = SemDestroy(&lThreadData);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//sem_getvalue on a semaphore before, during and after a timedwait times out
TInt CTestSemgetvalue::TestSem319( )
{
/*
TRACE("+TestSem319\n");
HarnessCommand lCommandArr[255] =
{
{EThreadMain, ESemInit, (void*) NULL},
{EThreadMain, ESemGetValue},
{EThreadMain, ECheckValue, (void*) 0},
{EThreadMain, EThreadCreate, (void*) (int) EThread1},
{EThread1, ESemTimedWait,NULL},
{EThreadMain, EWaitTillSuspended, (void*) (int) EThread1},
{EThreadMain, ESemGetValue},
{EThreadMain, ECheckValue, (void*) -1},
{EThreadMain, EWaitForSignal},
{EThread1, EVerifyResult, (void*) ETIMEDOUT},
{EThread1, EPostSignal},
{EThread1, EStop},
{EThreadMain, ESemGetValue},
{EThreadMain, ECheckValue, (void*) 0},
{EThreadMain, EThreadDestroy, (void*) (int) EThread1},
{EThreadMain, ESemDestroy},
{EThreadMain, EStop},
{ENoThread, ELastCommand},
};
TRACE("-TestSem319\n");
return LoadHarness(lCommandArr);
*/
return KErrNone;
}
|
[
"none@none"
] |
[
[
[
1,
1120
]
]
] |
0eff3a8cb238a3d0a1e4dc0638388a807e754b6c
|
c54f5a7cf6de3ed02d2e02cf867470ea48bd9258
|
/pyobjc/PyOpenGL-2.0.2.01/src/interface/GL.EXT._compiled_vertex_array.0103.inc
|
437a556f829101a4ee0cd7f919ac65fbf226f25c
|
[] |
no_license
|
orestis/pyobjc
|
01ad0e731fbbe0413c2f5ac2f3e91016749146c6
|
c30bf50ba29cb562d530e71a9d6c3d8ad75aa230
|
refs/heads/master
| 2021-01-22T06:54:35.401551 | 2009-09-01T09:24:47 | 2009-09-01T09:24:47 | 16,895 | 8 | 5 | null | null | null | null |
UTF-8
|
C++
| false | false | 53,382 |
inc
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.23
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGPYTHON
#ifndef SWIG_TEMPLATE_DISAMBIGUATOR
# if defined(__SUNPRO_CC)
# define SWIG_TEMPLATE_DISAMBIGUATOR template
# else
# define SWIG_TEMPLATE_DISAMBIGUATOR
# endif
#endif
#include <Python.h>
/***********************************************************************
* common.swg
*
* This file contains generic SWIG runtime support for pointer
* type checking as well as a few commonly used macros to control
* external linkage.
*
* Author : David Beazley ([email protected])
*
* Copyright (c) 1999-2000, The University of Chicago
*
* This file may be freely redistributed without license or fee provided
* this copyright message remains intact.
************************************************************************/
#include <string.h>
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if !defined(STATIC_LINKED)
# define SWIGEXPORT(a) __declspec(dllexport) a
# else
# define SWIGEXPORT(a) a
# endif
#else
# define SWIGEXPORT(a) a
#endif
#define SWIGRUNTIME(x) static x
#ifndef SWIGINLINE
#if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
#else
# define SWIGINLINE
#endif
#endif
/* This should only be incremented when either the layout of swig_type_info changes,
or for whatever reason, the runtime changes incompatibly */
#define SWIG_RUNTIME_VERSION "1"
/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
#ifdef SWIG_TYPE_TABLE
#define SWIG_QUOTE_STRING(x) #x
#define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
#define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
#else
#define SWIG_TYPE_TABLE_NAME
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*swig_converter_func)(void *);
typedef struct swig_type_info *(*swig_dycast_func)(void **);
typedef struct swig_type_info {
const char *name;
swig_converter_func converter;
const char *str;
void *clientdata;
swig_dycast_func dcast;
struct swig_type_info *next;
struct swig_type_info *prev;
} swig_type_info;
static swig_type_info *swig_type_list = 0;
static swig_type_info **swig_type_list_handle = &swig_type_list;
/*
Compare two type names skipping the space characters, therefore
"char*" == "char *" and "Class<int>" == "Class<int >", etc.
Return 0 when the two name types are equivalent, as in
strncmp, but skipping ' '.
*/
static int
SWIG_TypeNameComp(const char *f1, const char *l1,
const char *f2, const char *l2) {
for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
while ((*f1 == ' ') && (f1 != l1)) ++f1;
while ((*f2 == ' ') && (f2 != l2)) ++f2;
if (*f1 != *f2) return *f1 - *f2;
}
return (l1 - f1) - (l2 - f2);
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
*/
static int
SWIG_TypeEquiv(const char *nb, const char *tb) {
int equiv = 0;
const char* te = tb + strlen(tb);
const char* ne = nb;
while (!equiv && *ne) {
for (nb = ne; *ne; ++ne) {
if (*ne == '|') break;
}
equiv = SWIG_TypeNameComp(nb, ne, tb, te) == 0;
if (*ne) ++ne;
}
return equiv;
}
/* Register a type mapping with the type-checking */
static swig_type_info *
SWIG_TypeRegister(swig_type_info *ti) {
swig_type_info *tc, *head, *ret, *next;
/* Check to see if this type has already been registered */
tc = *swig_type_list_handle;
while (tc) {
/* check simple type equivalence */
int typeequiv = (strcmp(tc->name, ti->name) == 0);
/* check full type equivalence, resolving typedefs */
if (!typeequiv) {
/* only if tc is not a typedef (no '|' on it) */
if (tc->str && ti->str && !strstr(tc->str,"|")) {
typeequiv = SWIG_TypeEquiv(ti->str,tc->str);
}
}
if (typeequiv) {
/* Already exists in the table. Just add additional types to the list */
if (ti->clientdata) tc->clientdata = ti->clientdata;
head = tc;
next = tc->next;
goto l1;
}
tc = tc->prev;
}
head = ti;
next = 0;
/* Place in list */
ti->prev = *swig_type_list_handle;
*swig_type_list_handle = ti;
/* Build linked lists */
l1:
ret = head;
tc = ti + 1;
/* Patch up the rest of the links */
while (tc->name) {
head->next = tc;
tc->prev = head;
head = tc;
tc++;
}
if (next) next->prev = head;
head->next = next;
return ret;
}
/* Check the typename */
static swig_type_info *
SWIG_TypeCheck(char *c, swig_type_info *ty) {
swig_type_info *s;
if (!ty) return 0; /* Void pointer */
s = ty->next; /* First element always just a name */
do {
if (strcmp(s->name,c) == 0) {
if (s == ty->next) return s;
/* Move s to the top of the linked list */
s->prev->next = s->next;
if (s->next) {
s->next->prev = s->prev;
}
/* Insert s as second element in the list */
s->next = ty->next;
if (ty->next) ty->next->prev = s;
ty->next = s;
s->prev = ty;
return s;
}
s = s->next;
} while (s && (s != ty->next));
return 0;
}
/* Cast a pointer up an inheritance hierarchy */
static SWIGINLINE void *
SWIG_TypeCast(swig_type_info *ty, void *ptr) {
if ((!ty) || (!ty->converter)) return ptr;
return (*ty->converter)(ptr);
}
/* Dynamic pointer casting. Down an inheritance hierarchy */
static swig_type_info *
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
swig_type_info *lastty = ty;
if (!ty || !ty->dcast) return ty;
while (ty && (ty->dcast)) {
ty = (*ty->dcast)(ptr);
if (ty) lastty = ty;
}
return lastty;
}
/* Return the name associated with this type */
static SWIGINLINE const char *
SWIG_TypeName(const swig_type_info *ty) {
return ty->name;
}
/* Return the pretty name associated with this type,
that is an unmangled type name in a form presentable to the user.
*/
static const char *
SWIG_TypePrettyName(const swig_type_info *type) {
/* The "str" field contains the equivalent pretty names of the
type, separated by vertical-bar characters. We choose
to print the last name, as it is often (?) the most
specific. */
if (type->str != NULL) {
const char *last_name = type->str;
const char *s;
for (s = type->str; *s; s++)
if (*s == '|') last_name = s+1;
return last_name;
}
else
return type->name;
}
/* Search for a swig_type_info structure */
static swig_type_info *
SWIG_TypeQuery(const char *name) {
swig_type_info *ty = *swig_type_list_handle;
while (ty) {
if (ty->str && (SWIG_TypeEquiv(ty->str,name))) return ty;
if (ty->name && (strcmp(name,ty->name) == 0)) return ty;
ty = ty->prev;
}
return 0;
}
/* Set the clientdata field for a type */
static void
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
swig_type_info *tc, *equiv;
if (ti->clientdata) return;
/* if (ti->clientdata == clientdata) return; */
ti->clientdata = clientdata;
equiv = ti->next;
while (equiv) {
if (!equiv->converter) {
tc = *swig_type_list_handle;
while (tc) {
if ((strcmp(tc->name, equiv->name) == 0))
SWIG_TypeClientData(tc,clientdata);
tc = tc->prev;
}
}
equiv = equiv->next;
}
}
/* Pack binary data into a string */
static char *
SWIG_PackData(char *c, void *ptr, size_t sz) {
static char hex[17] = "0123456789abcdef";
unsigned char *u = (unsigned char *) ptr;
const unsigned char *eu = u + sz;
register unsigned char uu;
for (; u != eu; ++u) {
uu = *u;
*(c++) = hex[(uu & 0xf0) >> 4];
*(c++) = hex[uu & 0xf];
}
return c;
}
/* Unpack binary data from a string */
static char *
SWIG_UnpackData(char *c, void *ptr, size_t sz) {
register unsigned char uu = 0;
register int d;
unsigned char *u = (unsigned char *) ptr;
const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu = ((d - '0') << 4);
else if ((d >= 'a') && (d <= 'f'))
uu = ((d - ('a'-10)) << 4);
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu |= (d - '0');
else if ((d >= 'a') && (d <= 'f'))
uu |= (d - ('a'-10));
*u = uu;
}
return c;
}
/* This function will propagate the clientdata field of type to
* any new swig_type_info structures that have been added into the list
* of equivalent types. It is like calling
* SWIG_TypeClientData(type, clientdata) a second time.
*/
static void
SWIG_PropagateClientData(swig_type_info *type) {
swig_type_info *equiv = type->next;
swig_type_info *tc;
if (!type->clientdata) return;
while (equiv) {
if (!equiv->converter) {
tc = *swig_type_list_handle;
while (tc) {
if ((strcmp(tc->name, equiv->name) == 0) && !tc->clientdata)
SWIG_TypeClientData(tc, type->clientdata);
tc = tc->prev;
}
}
equiv = equiv->next;
}
}
#ifdef __cplusplus
}
#endif
/* -----------------------------------------------------------------------------
* SWIG API. Portion that goes into the runtime
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C" {
#endif
/* -----------------------------------------------------------------------------
* for internal method declarations
* ----------------------------------------------------------------------------- */
#ifndef SWIGINTERN
#define SWIGINTERN static
#endif
#ifndef SWIGINTERNSHORT
#ifdef __cplusplus
#define SWIGINTERNSHORT static inline
#else /* C case */
#define SWIGINTERNSHORT static
#endif /* __cplusplus */
#endif
/* Common SWIG API */
#define SWIG_ConvertPtr(obj, pp, type, flags) SWIG_Python_ConvertPtr(obj, pp, type, flags)
#define SWIG_NewPointerObj(p, type, flags) SWIG_Python_NewPointerObj(p, type, flags)
#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags)
/* Python-specific SWIG API */
#define SWIG_newvarlink() SWIG_Python_newvarlink()
#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr)
#define SWIG_ConvertPacked(obj, ptr, sz, ty, flags) SWIG_Python_ConvertPacked(obj, ptr, sz, ty, flags)
#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type)
#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants)
/*
Exception handling in wrappers
*/
#define SWIG_fail goto fail
#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg)
#define SWIG_append_errmsg(msg) SWIG_Python_AddErrMesg(msg,0)
#define SWIG_preppend_errmsg(msg) SWIG_Python_AddErrMesg(msg,1)
#define SWIG_type_error(type,obj) SWIG_Python_TypeError(type,obj)
#define SWIG_null_ref(type) SWIG_Python_NullRef(type)
/*
Contract support
*/
#define SWIG_contract_assert(expr, msg) \
if (!(expr)) { PyErr_SetString(PyExc_RuntimeError, (char *) msg ); goto fail; } else
/* -----------------------------------------------------------------------------
* Constant declarations
* ----------------------------------------------------------------------------- */
/* Constant Types */
#define SWIG_PY_INT 1
#define SWIG_PY_FLOAT 2
#define SWIG_PY_STRING 3
#define SWIG_PY_POINTER 4
#define SWIG_PY_BINARY 5
/* Constant information structure */
typedef struct swig_const_info {
int type;
char *name;
long lvalue;
double dvalue;
void *pvalue;
swig_type_info **ptype;
} swig_const_info;
/* -----------------------------------------------------------------------------
* Pointer declarations
* ----------------------------------------------------------------------------- */
/*
Use SWIG_NO_COBJECT_TYPES to force the use of strings to represent
C/C++ pointers in the python side. Very useful for debugging, but
not always safe.
*/
#if !defined(SWIG_NO_COBJECT_TYPES) && !defined(SWIG_COBJECT_TYPES)
# define SWIG_COBJECT_TYPES
#endif
/* Flags for pointer conversion */
#define SWIG_POINTER_EXCEPTION 0x1
#define SWIG_POINTER_DISOWN 0x2
/* -----------------------------------------------------------------------------
* Alloc. memory flags
* ----------------------------------------------------------------------------- */
#define SWIG_OLDOBJ 1
#define SWIG_NEWOBJ SWIG_OLDOBJ + 1
#define SWIG_PYSTR SWIG_NEWOBJ + 1
#ifdef __cplusplus
}
#endif
/***********************************************************************
* pyrun.swg
*
* This file contains the runtime support for Python modules
* and includes code for managing global variables and pointer
* type checking.
*
* Author : David Beazley ([email protected])
************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
/* -----------------------------------------------------------------------------
* global variable support code.
* ----------------------------------------------------------------------------- */
typedef struct swig_globalvar {
char *name; /* Name of global variable */
PyObject *(*get_attr)(); /* Return the current value */
int (*set_attr)(PyObject *); /* Set the value */
struct swig_globalvar *next;
} swig_globalvar;
typedef struct swig_varlinkobject {
PyObject_HEAD
swig_globalvar *vars;
} swig_varlinkobject;
static PyObject *
swig_varlink_repr(swig_varlinkobject *v) {
v = v;
return PyString_FromString("<Global variables>");
}
static int
swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) {
swig_globalvar *var;
flags = flags;
fprintf(fp,"Global variables { ");
for (var = v->vars; var; var=var->next) {
fprintf(fp,"%s", var->name);
if (var->next) fprintf(fp,", ");
}
fprintf(fp," }\n");
return 0;
}
static PyObject *
swig_varlink_getattr(swig_varlinkobject *v, char *n) {
swig_globalvar *var = v->vars;
while (var) {
if (strcmp(var->name,n) == 0) {
return (*var->get_attr)();
}
var = var->next;
}
PyErr_SetString(PyExc_NameError,"Unknown C global variable");
return NULL;
}
static int
swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
swig_globalvar *var = v->vars;
while (var) {
if (strcmp(var->name,n) == 0) {
return (*var->set_attr)(p);
}
var = var->next;
}
PyErr_SetString(PyExc_NameError,"Unknown C global variable");
return 1;
}
static PyTypeObject varlinktype = {
PyObject_HEAD_INIT(0)
0, /* Number of items in variable part (ob_size) */
(char *)"swigvarlink", /* Type name (tp_name) */
sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */
0, /* Itemsize (tp_itemsize) */
0, /* Deallocator (tp_dealloc) */
(printfunc) swig_varlink_print, /* Print (tp_print) */
(getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */
(setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */
0, /* tp_compare */
(reprfunc) swig_varlink_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
#if PY_VERSION_HEX >= 0x02020000
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
#endif
#if PY_VERSION_HEX >= 0x02030000
0, /* tp_del */
#endif
#ifdef COUNT_ALLOCS
/* these must be last */
0, /* tp_alloc */
0, /* tp_free */
0, /* tp_maxalloc */
0, /* tp_next */
#endif
};
/* Create a variable linking object for use later */
static PyObject *
SWIG_Python_newvarlink(void) {
swig_varlinkobject *result = 0;
result = PyMem_NEW(swig_varlinkobject,1);
varlinktype.ob_type = &PyType_Type; /* Patch varlinktype into a PyType */
result->ob_type = &varlinktype;
result->vars = 0;
result->ob_refcnt = 0;
Py_XINCREF((PyObject *) result);
return ((PyObject*) result);
}
static void
SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
swig_varlinkobject *v;
swig_globalvar *gv;
v= (swig_varlinkobject *) p;
gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
gv->name = (char *) malloc(strlen(name)+1);
strcpy(gv->name,name);
gv->get_attr = get_attr;
gv->set_attr = set_attr;
gv->next = v->vars;
v->vars = gv;
}
/* -----------------------------------------------------------------------------
* errors manipulation
* ----------------------------------------------------------------------------- */
static void
SWIG_Python_TypeError(const char *type, PyObject *obj)
{
if (type) {
if (!PyCObject_Check(obj)) {
const char *otype = (obj ? obj->ob_type->tp_name : 0);
if (otype) {
PyObject *str = PyObject_Str(obj);
const char *cstr = str ? PyString_AsString(str) : 0;
if (cstr) {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
type, otype, cstr);
} else {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
type, otype);
}
Py_DECREF(str);
return;
}
} else {
const char *otype = (char *) PyCObject_GetDesc(obj);
if (otype) {
PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PyCObject(%s)' is received",
type, otype);
return;
}
}
PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
} else {
PyErr_Format(PyExc_TypeError, "unexpected type is received");
}
}
static SWIGINLINE void
SWIG_Python_NullRef(const char *type)
{
if (type) {
PyErr_Format(PyExc_TypeError, "null reference of type '%s' was received",type);
} else {
PyErr_Format(PyExc_TypeError, "null reference was received");
}
}
static int
SWIG_Python_AddErrMesg(const char* mesg, int infront)
{
if (PyErr_Occurred()) {
PyObject *type = 0;
PyObject *value = 0;
PyObject *traceback = 0;
PyErr_Fetch(&type, &value, &traceback);
if (value) {
PyObject *old_str = PyObject_Str(value);
Py_XINCREF(type);
PyErr_Clear();
if (infront) {
PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
} else {
PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
}
Py_DECREF(old_str);
}
return 1;
} else {
return 0;
}
}
static int
SWIG_Python_ArgFail(int argnum)
{
if (PyErr_Occurred()) {
/* add information about failing argument */
char mesg[256];
sprintf(mesg, "argument number %d:", argnum);
return SWIG_Python_AddErrMesg(mesg, 1);
} else {
return 0;
}
}
/* -----------------------------------------------------------------------------
* pointers/data manipulation
* ----------------------------------------------------------------------------- */
/* Convert a pointer value */
static int
SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
swig_type_info *tc;
char *c = 0;
static PyObject *SWIG_this = 0;
int newref = 0;
PyObject *pyobj = 0;
void *vptr;
if (!obj) return 0;
if (obj == Py_None) {
*ptr = 0;
return 0;
}
#ifdef SWIG_COBJECT_TYPES
if (!(PyCObject_Check(obj))) {
if (!SWIG_this)
SWIG_this = PyString_FromString("this");
pyobj = obj;
obj = PyObject_GetAttr(obj,SWIG_this);
newref = 1;
if (!obj) goto type_error;
if (!PyCObject_Check(obj)) {
Py_DECREF(obj);
goto type_error;
}
}
vptr = PyCObject_AsVoidPtr(obj);
c = (char *) PyCObject_GetDesc(obj);
if (newref) Py_DECREF(obj);
goto type_check;
#else
if (!(PyString_Check(obj))) {
if (!SWIG_this)
SWIG_this = PyString_FromString("this");
pyobj = obj;
obj = PyObject_GetAttr(obj,SWIG_this);
newref = 1;
if (!obj) goto type_error;
if (!PyString_Check(obj)) {
Py_DECREF(obj);
goto type_error;
}
}
c = PyString_AS_STRING(obj);
/* Pointer values must start with leading underscore */
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
if (newref) { Py_DECREF(obj); }
*ptr = (void *) 0;
return 0;
} else {
if (newref) { Py_DECREF(obj); }
goto type_error;
}
}
c++;
c = SWIG_UnpackData(c,&vptr,sizeof(void *));
if (newref) { Py_DECREF(obj); }
#endif
type_check:
if (ty) {
tc = SWIG_TypeCheck(c,ty);
if (!tc) goto type_error;
*ptr = SWIG_TypeCast(tc,vptr);
}
if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
PyObject_SetAttrString(pyobj,(char*)"thisown",Py_False);
}
return 0;
type_error:
PyErr_Clear();
if (pyobj && !obj) {
obj = pyobj;
if (PyCFunction_Check(obj)) {
/* here we get the method pointer for callbacks */
char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
c = doc ? strstr(doc, "swig_ptr: ") : 0;
if (c) {
c += 10;
if (*c == '_') {
c++;
c = SWIG_UnpackData(c,&vptr,sizeof(void *));
goto type_check;
}
}
}
}
if (flags & SWIG_POINTER_EXCEPTION) {
if (ty) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
} else {
SWIG_Python_TypeError("C/C++ pointer", obj);
}
}
return -1;
}
/* Convert a pointer value, signal an exception on a type mismatch */
static void *
SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
void *result;
if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
PyErr_Clear();
if (flags & SWIG_POINTER_EXCEPTION) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
SWIG_Python_ArgFail(argnum);
}
}
return result;
}
/* Convert a packed value value */
static int
SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty, int flags) {
swig_type_info *tc;
char *c = 0;
if ((!obj) || (!PyString_Check(obj))) goto type_error;
c = PyString_AS_STRING(obj);
/* Pointer values must start with leading underscore */
if (*c != '_') goto type_error;
c++;
c = SWIG_UnpackData(c,ptr,sz);
if (ty) {
tc = SWIG_TypeCheck(c,ty);
if (!tc) goto type_error;
}
return 0;
type_error:
PyErr_Clear();
if (flags & SWIG_POINTER_EXCEPTION) {
if (ty) {
SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
} else {
SWIG_Python_TypeError("C/C++ packed data", obj);
}
}
return -1;
}
/* Create a new pointer string */
static char *
SWIG_Python_PointerStr(char *buff, void *ptr, const char *name, size_t bsz) {
char *r = buff;
if ((2*sizeof(void *) + 2) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,&ptr,sizeof(void *));
if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
strcpy(r,name);
return buff;
}
/* Create a new pointer object */
static PyObject *
SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int own) {
PyObject *robj;
if (!ptr) {
Py_INCREF(Py_None);
return Py_None;
}
#ifdef SWIG_COBJECT_TYPES
robj = PyCObject_FromVoidPtrAndDesc((void *) ptr, (char *) type->name, NULL);
#else
{
char result[1024];
SWIG_Python_PointerStr(result, ptr, type->name, 1024);
robj = PyString_FromString(result);
}
#endif
if (!robj || (robj == Py_None)) return robj;
if (type->clientdata) {
PyObject *inst;
PyObject *args = Py_BuildValue((char*)"(O)", robj);
Py_DECREF(robj);
inst = PyObject_CallObject((PyObject *) type->clientdata, args);
Py_DECREF(args);
if (inst) {
if (own) {
PyObject_SetAttrString(inst,(char*)"thisown",Py_True);
}
robj = inst;
}
}
return robj;
}
static PyObject *
SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
char result[1024];
char *r = result;
if ((2*sz + 2 + strlen(type->name)) > 1024) return 0;
*(r++) = '_';
r = SWIG_PackData(r,ptr,sz);
strcpy(r,type->name);
return PyString_FromString(result);
}
/* -----------------------------------------------------------------------------
* constants/methods manipulation
* ----------------------------------------------------------------------------- */
/* Install Constants */
static void
SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
int i;
PyObject *obj;
for (i = 0; constants[i].type; i++) {
switch(constants[i].type) {
case SWIG_PY_INT:
obj = PyInt_FromLong(constants[i].lvalue);
break;
case SWIG_PY_FLOAT:
obj = PyFloat_FromDouble(constants[i].dvalue);
break;
case SWIG_PY_STRING:
if (constants[i].pvalue) {
obj = PyString_FromString((char *) constants[i].pvalue);
} else {
Py_INCREF(Py_None);
obj = Py_None;
}
break;
case SWIG_PY_POINTER:
obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
break;
case SWIG_PY_BINARY:
obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
break;
default:
obj = 0;
break;
}
if (obj) {
PyDict_SetItemString(d,constants[i].name,obj);
Py_DECREF(obj);
}
}
}
/* Fix SwigMethods to carry the callback ptrs when needed */
static void
SWIG_Python_FixMethods(PyMethodDef *methods,
swig_const_info *const_table,
swig_type_info **types,
swig_type_info **types_initial) {
int i;
for (i = 0; methods[i].ml_name; ++i) {
char *c = methods[i].ml_doc;
if (c && (c = strstr(c, "swig_ptr: "))) {
int j;
swig_const_info *ci = 0;
char *name = c + 10;
for (j = 0; const_table[j].type; j++) {
if (strncmp(const_table[j].name, name,
strlen(const_table[j].name)) == 0) {
ci = &(const_table[j]);
break;
}
}
if (ci) {
size_t shift = (ci->ptype) - types;
swig_type_info *ty = types_initial[shift];
size_t ldoc = (c - methods[i].ml_doc);
size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
char *ndoc = (char*)malloc(ldoc + lptr + 10);
char *buff = ndoc;
void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue: (void *)(ci->lvalue);
strncpy(buff, methods[i].ml_doc, ldoc);
buff += ldoc;
strncpy(buff, "swig_ptr: ", 10);
buff += 10;
SWIG_Python_PointerStr(buff, ptr, ty->name, lptr);
methods[i].ml_doc = ndoc;
}
}
}
}
/* -----------------------------------------------------------------------------
* Lookup type pointer
* ----------------------------------------------------------------------------- */
#if PY_MAJOR_VERSION < 2
/* PyModule_AddObject function was introduced in Python 2.0. The following function
is copied out of Python/modsupport.c in python version 2.3.4 */
static int
PyModule_AddObject(PyObject *m, char *name, PyObject *o)
{
PyObject *dict;
if (!PyModule_Check(m)) {
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs module as first arg");
return -1;
}
if (!o) {
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs non-NULL value");
return -1;
}
dict = PyModule_GetDict(m);
if (dict == NULL) {
/* Internal error -- modules must have a dict! */
PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
PyModule_GetName(m));
return -1;
}
if (PyDict_SetItemString(dict, name, o))
return -1;
Py_DECREF(o);
return 0;
}
#endif
static PyMethodDef swig_empty_runtime_method_table[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
static void
SWIG_Python_LookupTypePointer(swig_type_info ***type_list_handle) {
PyObject *module, *pointer;
void *type_pointer;
/* first check if module already created */
type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
if (type_pointer) {
*type_list_handle = (swig_type_info **) type_pointer;
} else {
PyErr_Clear();
/* create a new module and variable */
module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table);
pointer = PyCObject_FromVoidPtr((void *) (*type_list_handle), NULL);
if (pointer && module) {
PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
}
}
}
#ifdef __cplusplus
}
#endif
/* -------- TYPES TABLE (BEGIN) -------- */
#define SWIGTYPE_p_GLsizei swig_types[0]
#define SWIGTYPE_p_GLshort swig_types[1]
#define SWIGTYPE_p_GLboolean swig_types[2]
#define SWIGTYPE_size_t swig_types[3]
#define SWIGTYPE_p_GLushort swig_types[4]
#define SWIGTYPE_p_GLenum swig_types[5]
#define SWIGTYPE_p_GLvoid swig_types[6]
#define SWIGTYPE_p_GLint swig_types[7]
#define SWIGTYPE_p_char swig_types[8]
#define SWIGTYPE_p_GLclampd swig_types[9]
#define SWIGTYPE_p_GLclampf swig_types[10]
#define SWIGTYPE_p_GLuint swig_types[11]
#define SWIGTYPE_ptrdiff_t swig_types[12]
#define SWIGTYPE_p_GLbyte swig_types[13]
#define SWIGTYPE_p_GLbitfield swig_types[14]
#define SWIGTYPE_p_GLfloat swig_types[15]
#define SWIGTYPE_p_GLubyte swig_types[16]
#define SWIGTYPE_p_GLdouble swig_types[17]
static swig_type_info *swig_types[19];
/* -------- TYPES TABLE (END) -------- */
/*-----------------------------------------------
@(target):= _compiled_vertex_array.so
------------------------------------------------*/
#define SWIG_init init_compiled_vertex_array
#define SWIG_name "_compiled_vertex_array"
SWIGINTERN PyObject *
SWIG_FromCharPtr(const char* cptr)
{
if (cptr) {
size_t size = strlen(cptr);
if (size > INT_MAX) {
return SWIG_NewPointerObj((char*)(cptr),
SWIG_TypeQuery("char *"), 0);
} else {
if (size != 0) {
return PyString_FromStringAndSize(cptr, size);
} else {
return PyString_FromString(cptr);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
/*@C:\\bin\\SWIG-1.3.23\\Lib\\python\\pymacros.swg,66,SWIG_define@*/
#define SWIG_From_int PyInt_FromLong
/*@@*/
/**
*
* GL.EXT.compiled_vertex_array Module for PyOpenGL
*
* Date: May 2001
*
* Authors: Tarn Weisner Burton <[email protected]>
*
***/
GLint PyOpenGL_round(double x) {
if (x >= 0) {
return (GLint) (x+0.5);
} else {
return (GLint) (x-0.5);
}
}
int __PyObject_AsArray_Size(PyObject* x);
#ifdef NUMERIC
#define _PyObject_AsArray_Size(x) ((x == Py_None) ? 0 : ((PyArray_Check(x)) ? PyArray_Size(x) : __PyObject_AsArray_Size(x)))
#else /* NUMERIC */
#define _PyObject_AsArray_Size(x) ((x == Py_None) ? 0 : __PyObject_AsArray_Size(x))
#endif /* NUMERIC */
#define _PyObject_As(NAME, BASE) BASE* _PyObject_As##NAME(PyObject* source, PyObject** temp, int* len);
#define _PyObject_AsArray_Cleanup(target, temp) if (temp) Py_XDECREF(temp); else PyMem_Del(target)
_PyObject_As(FloatArray, float)
_PyObject_As(DoubleArray, double)
_PyObject_As(CharArray, signed char)
_PyObject_As(UnsignedCharArray, unsigned char)
_PyObject_As(ShortArray, short)
_PyObject_As(UnsignedShortArray, unsigned short)
_PyObject_As(IntArray, int)
_PyObject_As(UnsignedIntArray, unsigned int)
void* _PyObject_AsArray(GLenum type, PyObject* source, PyObject** temp, int* len);
#define PyErr_XPrint() if (PyErr_Occurred()) PyErr_Print()
#if HAS_DYNAMIC_EXT
#define DECLARE_EXT(PROC_NAME, RET, ERROR_RET, PROTO, CALL)\
RET PROC_NAME PROTO\
{\
typedef RET (APIENTRY *proc_##PROC_NAME) PROTO;\
proc_##PROC_NAME proc = (proc_##PROC_NAME)GL_GetProcAddress(#PROC_NAME);\
if (proc) return proc CALL;\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
return ERROR_RET;\
}
#define DECLARE_VOID_EXT(PROC_NAME, PROTO, CALL)\
void PROC_NAME PROTO\
{\
typedef void (APIENTRY *proc_##PROC_NAME) PROTO;\
proc_##PROC_NAME proc = (proc_##PROC_NAME)GL_GetProcAddress(#PROC_NAME);\
if (proc) proc CALL;\
else {\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
}\
}
#else
#define DECLARE_EXT(PROC_NAME, RET, ERROR_RET, PROTO, CALL)\
RET PROC_NAME PROTO\
{\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
return ERROR_RET;\
}
#define DECLARE_VOID_EXT(PROC_NAME, PROTO, CALL)\
void PROC_NAME PROTO\
{\
PyErr_SetGLErrorMessage( GL_INVALID_OPERATION, "Dynamic function loading not implemented/supported on this platform" );\
}
#endif
#define _PyTuple_From(NAME, BASE) PyObject* _PyTuple_From##NAME(int len, BASE* data);
_PyTuple_From(UnsignedCharArray, unsigned char)
_PyTuple_From(CharArray, signed char)
_PyTuple_From(UnsignedShortArray, unsigned short)
_PyTuple_From(ShortArray, short)
_PyTuple_From(UnsignedIntArray, unsigned int)
_PyTuple_From(IntArray, int)
_PyTuple_From(FloatArray, float)
_PyTuple_From(DoubleArray, double)
#define _PyObject_From(NAME, BASE) PyObject* _PyObject_From##NAME(int nd, int* dims, BASE* data, int own);
_PyObject_From(UnsignedCharArray, unsigned char)
_PyObject_From(CharArray, signed char)
_PyObject_From(UnsignedShortArray, unsigned short)
_PyObject_From(ShortArray, short)
_PyObject_From(UnsignedIntArray, unsigned int)
_PyObject_From(IntArray, int)
_PyObject_From(FloatArray, float)
_PyObject_From(DoubleArray, double)
PyObject* _PyObject_FromArray(GLenum type, int nd, int *dims, void* data, int own);
void* SetupPixelRead(int rank, GLenum format, GLenum type, int *dims);
void SetupPixelWrite(int rank);
void* SetupRawPixelRead(GLenum format, GLenum type, int n, const int *dims, int* size);
void* _PyObject_AsPointer(PyObject* x);
/* The following line causes a warning on linux and cygwin
The function is defined in interface_utils.c, which is
linked to each extension module. For some reason, though,
this declaration doesn't get recognised as a declaration
prototype for that function.
*/
void init_util();
typedef void *PTR;
typedef struct
{
void (*_decrement)(void* pointer);
void (*_decrementPointer)(GLenum pname);
int (*_incrementLock)(void *pointer);
int (*_incrementPointerLock)(GLenum pname);
void (*_acquire)(void* pointer);
void (*_acquirePointer)(GLenum pname);
#if HAS_DYNAMIC_EXT
PTR (*GL_GetProcAddress)(const char* name);
#endif
int (*InitExtension)(const char *name, const char** procs);
PyObject *_GLerror;
PyObject *_GLUerror;
} util_API;
static util_API *_util_API = NULL;
#define decrementLock(x) (*_util_API)._decrement(x)
#define decrementPointerLock(x) (*_util_API)._decrementPointer(x)
#define incrementLock(x) (*_util_API)._incrementLock(x)
#define incrementPointerLock(x) (*_util_API)._incrementPointerLock(x)
#define acquire(x) (*_util_API)._acquire(x)
#define acquirePointer(x) (*_util_API)._acquirePointer(x)
#define GLerror (*_util_API)._GLerror
#define GLUerror (*_util_API)._GLUerror
#if HAS_DYNAMIC_EXT
#define GL_GetProcAddress(x) (*_util_API).GL_GetProcAddress(x)
#endif
#define InitExtension(x, y) (*_util_API).InitExtension(x, (const char**)y)
#define PyErr_SetGLerror(code) PyErr_SetObject(GLerror, Py_BuildValue("is", code, gluErrorString(code)));
#define PyErr_SetGLUerror(code) PyErr_SetObject(GLUerror, Py_BuildValue("is", code, gluErrorString(code)));
int _PyObject_Dimension(PyObject* x, int rank);
#define ERROR_MSG_SEP ", "
#define ERROR_MSG_SEP_LEN 2
int GLErrOccurred()
{
if (PyErr_Occurred()) return 1;
if (CurrentContextIsValid())
{
GLenum error, *errors = NULL;
char *msg = NULL;
const char *this_msg;
int count = 0;
error = glGetError();
while (error != GL_NO_ERROR)
{
this_msg = gluErrorString(error);
if (count)
{
msg = realloc(msg, (strlen(msg) + strlen(this_msg) + ERROR_MSG_SEP_LEN + 1)*sizeof(char));
strcat(msg, ERROR_MSG_SEP);
strcat(msg, this_msg);
errors = realloc(errors, (count + 1)*sizeof(GLenum));
}
else
{
msg = malloc((strlen(this_msg) + 1)*sizeof(char));
strcpy(msg, this_msg);
errors = malloc(sizeof(GLenum));
}
errors[count++] = error;
error = glGetError();
}
if (count)
{
PyErr_SetObject(GLerror, Py_BuildValue("Os", _PyTuple_FromIntArray(count, (int*)errors), msg));
free(errors);
free(msg);
return 1;
}
}
return 0;
}
void PyErr_SetGLErrorMessage( int id, char * message ) {
/* set a GLerror with an ID and string message
This tries pretty hard to look just like a regular
error as produced by GLErrOccurred()'s formatter,
save that there's only the single error being reported.
Using id 0 is probably best for any future use where
there isn't a good match for the exception description
in the error-enumeration set.
*/
PyObject * args = NULL;
args = Py_BuildValue( "(i)s", id, message );
if (args) {
PyErr_SetObject( GLerror, args );
Py_XDECREF( args );
} else {
PyErr_SetGLerror(id);
}
}
#if !EXT_DEFINES_PROTO || !defined(GL_EXT_compiled_vertex_array)
DECLARE_VOID_EXT(glLockArraysEXT, (GLint first, GLsizei count), (first, count))
DECLARE_VOID_EXT(glUnlockArraysEXT, (), ())
#endif
#include <limits.h>
SWIGINTERN int
SWIG_CheckLongInRange(long value, long min_value, long max_value,
const char *errmsg)
{
if (value < min_value) {
if (errmsg) {
PyErr_Format(PyExc_OverflowError,
"value %ld is less than '%s' minimum %ld",
value, errmsg, min_value);
}
return 0;
} else if (value > max_value) {
if (errmsg) {
PyErr_Format(PyExc_OverflowError,
"value %ld is greater than '%s' maximum %ld",
value, errmsg, max_value);
}
return 0;
}
return 1;
}
SWIGINTERN int
SWIG_AsVal_long(PyObject * obj, long* val)
{
if (PyInt_Check(obj)) {
if (val) *val = PyInt_AS_LONG(obj);
return 1;
}
if (PyLong_Check(obj)) {
long v = PyLong_AsLong(obj);
if (!PyErr_Occurred()) {
if (val) *val = v;
return 1;
} else {
if (!val) PyErr_Clear();
return 0;
}
}
if (val) {
SWIG_type_error("long", obj);
}
return 0;
}
#if INT_MAX != LONG_MAX
SWIGINTERN int
SWIG_AsVal_int(PyObject *obj, int *val)
{
const char* errmsg = val ? "int" : (char*)0;
long v;
if (SWIG_AsVal_long(obj, &v)) {
if (SWIG_CheckLongInRange(v, INT_MIN,INT_MAX, errmsg)) {
if (val) *val = (int)(v);
return 1;
} else {
return 0;
}
} else {
PyErr_Clear();
}
if (val) {
SWIG_type_error(errmsg, obj);
}
return 0;
}
#else
SWIGINTERNSHORT int
SWIG_AsVal_int(PyObject *obj, int *val)
{
return SWIG_AsVal_long(obj,(long*)val);
}
#endif
SWIGINTERNSHORT int
SWIG_As_int(PyObject* obj)
{
int v;
if (!SWIG_AsVal_int(obj, &v)) {
/*
this is needed to make valgrind/purify happier.
*/
memset((void*)&v, 0, sizeof(int));
}
return v;
}
SWIGINTERNSHORT int
SWIG_Check_int(PyObject* obj)
{
return SWIG_AsVal_int(obj, (int*)0);
}
static char _doc_glLockArraysEXT[] = "glLockArraysEXT(first, count) -> None";
static char _doc_glUnlockArraysEXT[] = "glUnlockArraysEXT() -> None";
static char *proc_names[] =
{
#if !EXT_DEFINES_PROTO || !defined(GL_EXT_compiled_vertex_array)
"glLockArraysEXT",
"glUnlockArraysEXT",
#endif
NULL
};
#define glInitCompiledVertexArrayEXT() InitExtension("GL_EXT_compiled_vertex_array", proc_names)
static char _doc_glInitCompiledVertexArrayEXT[] = "glInitCompiledVertexArrayEXT() -> bool";
PyObject *__info()
{
if (glInitCompiledVertexArrayEXT())
{
PyObject *info = PyList_New(0);
return info;
}
Py_INCREF(Py_None);
return Py_None;
}
#ifdef __cplusplus
extern "C" {
#endif
static PyObject *_wrap_glLockArraysEXT(PyObject *self, PyObject *args) {
PyObject *resultobj;
GLint arg1 ;
GLsizei arg2 ;
PyObject * obj0 = 0 ;
PyObject * obj1 = 0 ;
if(!PyArg_ParseTuple(args,(char *)"OO:glLockArraysEXT",&obj0,&obj1)) goto fail;
{
arg1 = (GLint)(SWIG_As_int(obj0));
if (SWIG_arg_fail(1)) SWIG_fail;
}
{
if (PyInt_Check(obj1) || PyLong_Check(obj1)) {
arg2= (GLsizei)(PyInt_AsLong( obj1 ));
} else if (PyFloat_Check(obj1)) {
double arg2_temp_float;
arg2_temp_float = PyFloat_AsDouble(obj1);
if (arg2_temp_float >= (INT_MAX-0.5)) {
PyErr_SetString(PyExc_ValueError, "Value too large to be converted to a size measurement");
return NULL;
} else if (arg2_temp_float <= -0.5) {
PyErr_SetString(PyExc_ValueError, "Value less than 0, cannot be converted to a size measurement");
return NULL;
}
arg2 = (GLsizei) PyOpenGL_round( arg2_temp_float );
}
}
{
glLockArraysEXT(arg1,arg2);
if (GLErrOccurred()) {
return NULL;
}
}
Py_INCREF(Py_None); resultobj = Py_None;
return resultobj;
fail:
return NULL;
}
static PyObject *_wrap_glUnlockArraysEXT(PyObject *self, PyObject *args) {
PyObject *resultobj;
if(!PyArg_ParseTuple(args,(char *)":glUnlockArraysEXT")) goto fail;
{
glUnlockArraysEXT();
if (GLErrOccurred()) {
return NULL;
}
}
Py_INCREF(Py_None); resultobj = Py_None;
return resultobj;
fail:
return NULL;
}
static PyObject *_wrap_glInitCompiledVertexArrayEXT(PyObject *self, PyObject *args) {
PyObject *resultobj;
int result;
if(!PyArg_ParseTuple(args,(char *)":glInitCompiledVertexArrayEXT")) goto fail;
{
result = (int)glInitCompiledVertexArrayEXT();
if (GLErrOccurred()) {
return NULL;
}
}
{
resultobj = SWIG_From_int((int)(result));
}
return resultobj;
fail:
return NULL;
}
static PyObject *_wrap___info(PyObject *self, PyObject *args) {
PyObject *resultobj;
PyObject *result;
if(!PyArg_ParseTuple(args,(char *)":__info")) goto fail;
{
result = (PyObject *)__info();
if (GLErrOccurred()) {
return NULL;
}
}
{
resultobj= result;
}
return resultobj;
fail:
return NULL;
}
static PyMethodDef SwigMethods[] = {
{ (char *)"glLockArraysEXT", _wrap_glLockArraysEXT, METH_VARARGS, NULL},
{ (char *)"glUnlockArraysEXT", _wrap_glUnlockArraysEXT, METH_VARARGS, NULL},
{ (char *)"glInitCompiledVertexArrayEXT", _wrap_glInitCompiledVertexArrayEXT, METH_VARARGS, NULL},
{ (char *)"__info", _wrap___info, METH_VARARGS, NULL},
{ NULL, NULL, 0, NULL }
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
static swig_type_info _swigt__p_GLsizei[] = {{"_p_GLsizei", 0, "int *|GLsizei *", 0, 0, 0, 0},{"_p_GLint", 0, 0, 0, 0, 0, 0},{"_p_GLsizei", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLshort[] = {{"_p_GLshort", 0, "short *|GLshort *", 0, 0, 0, 0},{"_p_GLshort", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLboolean[] = {{"_p_GLboolean", 0, "unsigned char *|GLboolean *", 0, 0, 0, 0},{"_p_GLboolean", 0, 0, 0, 0, 0, 0},{"_p_GLubyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__size_t[] = {{"_size_t", 0, "size_t", 0, 0, 0, 0},{"_size_t", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLushort[] = {{"_p_GLushort", 0, "unsigned short *|GLushort *", 0, 0, 0, 0},{"_p_GLushort", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLenum[] = {{"_p_GLenum", 0, "unsigned int *|GLenum *", 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLvoid[] = {{"_p_GLvoid", 0, "void *|GLvoid *", 0, 0, 0, 0},{"_p_GLvoid", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLint[] = {{"_p_GLint", 0, "int *|GLint *", 0, 0, 0, 0},{"_p_GLint", 0, 0, 0, 0, 0, 0},{"_p_GLsizei", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_char[] = {{"_p_char", 0, "char *", 0, 0, 0, 0},{"_p_char", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLclampd[] = {{"_p_GLclampd", 0, "double *|GLclampd *", 0, 0, 0, 0},{"_p_GLclampd", 0, 0, 0, 0, 0, 0},{"_p_GLdouble", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLclampf[] = {{"_p_GLclampf", 0, "float *|GLclampf *", 0, 0, 0, 0},{"_p_GLfloat", 0, 0, 0, 0, 0, 0},{"_p_GLclampf", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLuint[] = {{"_p_GLuint", 0, "unsigned int *|GLuint *", 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__ptrdiff_t[] = {{"_ptrdiff_t", 0, "ptrdiff_t", 0, 0, 0, 0},{"_ptrdiff_t", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLbyte[] = {{"_p_GLbyte", 0, "signed char *|GLbyte *", 0, 0, 0, 0},{"_p_GLbyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLbitfield[] = {{"_p_GLbitfield", 0, "unsigned int *|GLbitfield *", 0, 0, 0, 0},{"_p_GLuint", 0, 0, 0, 0, 0, 0},{"_p_GLbitfield", 0, 0, 0, 0, 0, 0},{"_p_GLenum", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLfloat[] = {{"_p_GLfloat", 0, "float *|GLfloat *", 0, 0, 0, 0},{"_p_GLfloat", 0, 0, 0, 0, 0, 0},{"_p_GLclampf", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLubyte[] = {{"_p_GLubyte", 0, "unsigned char *|GLubyte *", 0, 0, 0, 0},{"_p_GLboolean", 0, 0, 0, 0, 0, 0},{"_p_GLubyte", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info _swigt__p_GLdouble[] = {{"_p_GLdouble", 0, "double *|GLdouble *", 0, 0, 0, 0},{"_p_GLclampd", 0, 0, 0, 0, 0, 0},{"_p_GLdouble", 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0}};
static swig_type_info *swig_types_initial[] = {
_swigt__p_GLsizei,
_swigt__p_GLshort,
_swigt__p_GLboolean,
_swigt__size_t,
_swigt__p_GLushort,
_swigt__p_GLenum,
_swigt__p_GLvoid,
_swigt__p_GLint,
_swigt__p_char,
_swigt__p_GLclampd,
_swigt__p_GLclampf,
_swigt__p_GLuint,
_swigt__ptrdiff_t,
_swigt__p_GLbyte,
_swigt__p_GLbitfield,
_swigt__p_GLfloat,
_swigt__p_GLubyte,
_swigt__p_GLdouble,
0
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
static swig_const_info swig_const_table[] = {
{ SWIG_PY_POINTER, (char*)"__version__", 0, 0, (void *)"1.33.6.1", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__date__", 0, 0, (void *)"2004/11/14 23:19:04", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__author__", 0, 0, (void *)"Tarn Weisner Burton <[email protected]>", &SWIGTYPE_p_char},
{ SWIG_PY_POINTER, (char*)"__doc__", 0, 0, (void *)"http://oss.sgi.com/projects/ogl-sample/registry/EXT/compiled_vertex_array.txt", &SWIGTYPE_p_char},
{0, 0, 0, 0.0, 0, 0}};
#ifdef __cplusplus
}
#endif
#ifdef SWIG_LINK_RUNTIME
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(_MSC_VER) || defined(__GNUC__)
# define SWIGIMPORT(a) extern a
# else
# if defined(__BORLANDC__)
# define SWIGIMPORT(a) a _export
# else
# define SWIGIMPORT(a) a
# endif
# endif
#else
# define SWIGIMPORT(a) a
#endif
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT(void *) SWIG_ReturnGlobalTypeList(void *);
#endif
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT(void) SWIG_init(void) {
static PyObject *SWIG_globals = 0;
static int typeinit = 0;
PyObject *m, *d;
int i;
if (!SWIG_globals) SWIG_globals = SWIG_newvarlink();
/* Fix SwigMethods to carry the callback ptrs when needed */
SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_types_initial);
m = Py_InitModule((char *) SWIG_name, SwigMethods);
d = PyModule_GetDict(m);
if (!typeinit) {
#ifdef SWIG_LINK_RUNTIME
swig_type_list_handle = (swig_type_info **) SWIG_ReturnGlobalTypeList(swig_type_list_handle);
#else
# ifndef SWIG_STATIC_RUNTIME
SWIG_Python_LookupTypePointer(&swig_type_list_handle);
# endif
#endif
for (i = 0; swig_types_initial[i]; i++) {
swig_types[i] = SWIG_TypeRegister(swig_types_initial[i]);
}
typeinit = 1;
}
SWIG_InstallConstants(d,swig_const_table);
PyDict_SetItemString(d,"__version__", SWIG_FromCharPtr("1.33.6.1"));
PyDict_SetItemString(d,"__date__", SWIG_FromCharPtr("2004/11/14 23:19:04"));
{
PyDict_SetItemString(d,"__api_version__", SWIG_From_int((int)(259)));
}
PyDict_SetItemString(d,"__author__", SWIG_FromCharPtr("Tarn Weisner Burton <[email protected]>"));
PyDict_SetItemString(d,"__doc__", SWIG_FromCharPtr("http://oss.sgi.com/projects/ogl-sample/registry/EXT/compiled_vertex_array.txt"));
#ifdef NUMERIC
PyArray_API = NULL;
import_array();
init_util();
PyErr_Clear();
#endif
{
PyObject *util = PyImport_ImportModule("OpenGL.GL._GL__init__");
if (util)
{
PyObject *api_object = PyDict_GetItemString(PyModule_GetDict(util), "_util_API");
if (PyCObject_Check(api_object)) _util_API = (util_API*)PyCObject_AsVoidPtr(api_object);
}
}
{
PyDict_SetItemString(d,"GL_ARRAY_ELEMENT_LOCK_FIRST_EXT", SWIG_From_int((int)(0x81A8)));
}
{
PyDict_SetItemString(d,"GL_ARRAY_ELEMENT_LOCK_COUNT_EXT", SWIG_From_int((int)(0x81A9)));
}
}
|
[
"ronaldoussoren@f55f28a5-9edb-0310-a011-a803cfcd5d25"
] |
[
[
[
1,
1784
]
]
] |
4c3e8cd0ed28fa7aa861282122eade3a244ed992
|
b83c990328347a0a2130716fd99788c49c29621e
|
/include/boost/foreach.hpp
|
b0a641f9c2d7882db0aa1ebd52b2222273747c90
|
[] |
no_license
|
SpliFF/mingwlibs
|
c6249fbb13abd74ee9c16e0a049c88b27bd357cf
|
12d1369c9c1c2cc342f66c51d045b95c811ff90c
|
refs/heads/master
| 2021-01-18T03:51:51.198506 | 2010-06-13T15:13:20 | 2010-06-13T15:13:41 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 44,293 |
hpp
|
///////////////////////////////////////////////////////////////////////////////
// foreach.hpp header file
//
// Copyright 2004 Eric Niebler.
// 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/foreach for documentation
//
// Credits:
// Anson Tsao - for the initial inspiration and several good suggestions.
// Thorsten Ottosen - for Boost.Range, and for suggesting a way to detect
// const-qualified rvalues at compile time on VC7.1+
// Russell Hind - For help porting to Borland
// Alisdair Meredith - For help porting to Borland
// Stefan Slapeta - For help porting to Intel
// David Jenkins - For help finding a Microsoft Code Analysis bug
#ifndef BOOST_FOREACH
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <cstddef>
#include <utility> // for std::pair
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
// Some compilers let us detect even const-qualified rvalues at compile-time
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1310) && !defined(_PREFAST_) \
|| (BOOST_WORKAROUND(__GNUC__, >= 4) && !defined(BOOST_INTEL)) \
|| (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ >= 4) && !defined(BOOST_INTEL))
# define BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION
#else
// Some compilers allow temporaries to be bound to non-const references.
// These compilers make it impossible to for BOOST_FOREACH to detect
// temporaries and avoid reevaluation of the collection expression.
# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
|| BOOST_WORKAROUND(__BORLANDC__, < 0x593) \
|| (BOOST_WORKAROUND(BOOST_INTEL_CXX_VERSION, <= 700) && defined(_MSC_VER)) \
|| BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x570)) \
|| BOOST_WORKAROUND(__DECCXX_VER, <= 60590042)
# define BOOST_FOREACH_NO_RVALUE_DETECTION
# endif
// Some compilers do not correctly implement the lvalue/rvalue conversion
// rules of the ternary conditional operator.
# if defined(BOOST_FOREACH_NO_RVALUE_DETECTION) \
|| defined(BOOST_NO_SFINAE) \
|| BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \
|| BOOST_WORKAROUND(BOOST_INTEL_WIN, BOOST_TESTED_AT(1400)) \
|| BOOST_WORKAROUND(__GNUC__, < 3) \
|| (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ <= 2)) \
|| (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ <= 3) && defined(__APPLE_CC__)) \
|| BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) \
|| BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206)) \
|| BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x590))
# define BOOST_FOREACH_NO_CONST_RVALUE_DETECTION
# else
# define BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
# endif
#endif
#include <boost/mpl/if.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/noncopyable.hpp>
#include <boost/range/end.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/rend.hpp>
#include <boost/range/rbegin.hpp>
#include <boost/range/iterator.hpp>
#include <boost/range/reverse_iterator.hpp>
#include <boost/type_traits/is_array.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/is_abstract.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/utility/addressof.hpp>
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
# include <new>
# include <boost/aligned_storage.hpp>
# include <boost/utility/enable_if.hpp>
# include <boost/type_traits/remove_const.hpp>
#endif
// This must be at global scope, hence the uglified name
enum boost_foreach_argument_dependent_lookup_hack
{
boost_foreach_argument_dependent_lookup_hack_value
};
namespace boost
{
// forward declarations for iterator_range
template<typename T>
class iterator_range;
// forward declarations for sub_range
template<typename T>
class sub_range;
namespace foreach
{
///////////////////////////////////////////////////////////////////////////////
// in_range
//
template<typename T>
inline std::pair<T, T> in_range(T begin, T end)
{
return std::make_pair(begin, end);
}
///////////////////////////////////////////////////////////////////////////////
// boost::foreach::tag
//
typedef boost_foreach_argument_dependent_lookup_hack tag;
///////////////////////////////////////////////////////////////////////////////
// boost::foreach::is_lightweight_proxy
// Specialize this for user-defined collection types if they are inexpensive to copy.
// This tells BOOST_FOREACH it can avoid the rvalue/lvalue detection stuff.
template<typename T>
struct is_lightweight_proxy
: boost::mpl::false_
{
};
///////////////////////////////////////////////////////////////////////////////
// boost::foreach::is_noncopyable
// Specialize this for user-defined collection types if they cannot be copied.
// This also tells BOOST_FOREACH to avoid the rvalue/lvalue detection stuff.
template<typename T>
struct is_noncopyable
#if !defined(BOOST_BROKEN_IS_BASE_AND_DERIVED) && !defined(BOOST_NO_IS_ABSTRACT)
: boost::mpl::or_<
boost::is_abstract<T>
, boost::is_base_and_derived<boost::noncopyable, T>
>
#elif !defined(BOOST_BROKEN_IS_BASE_AND_DERIVED)
: boost::is_base_and_derived<boost::noncopyable, T>
#elif !defined(BOOST_NO_IS_ABSTRACT)
: boost::is_abstract<T>
#else
: boost::mpl::false_
#endif
{
};
} // namespace foreach
} // namespace boost
// vc6/7 needs help ordering the following overloads
#ifdef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
# define BOOST_FOREACH_TAG_DEFAULT ...
#else
# define BOOST_FOREACH_TAG_DEFAULT boost::foreach::tag
#endif
///////////////////////////////////////////////////////////////////////////////
// boost_foreach_is_lightweight_proxy
// Another customization point for the is_lightweight_proxy optimization,
// this one works on legacy compilers. Overload boost_foreach_is_lightweight_proxy
// at the global namespace for your type.
template<typename T>
inline boost::foreach::is_lightweight_proxy<T> *
boost_foreach_is_lightweight_proxy(T *&, BOOST_FOREACH_TAG_DEFAULT) { return 0; }
template<typename T>
inline boost::mpl::true_ *
boost_foreach_is_lightweight_proxy(std::pair<T, T> *&, boost::foreach::tag) { return 0; }
template<typename T>
inline boost::mpl::true_ *
boost_foreach_is_lightweight_proxy(boost::iterator_range<T> *&, boost::foreach::tag) { return 0; }
template<typename T>
inline boost::mpl::true_ *
boost_foreach_is_lightweight_proxy(boost::sub_range<T> *&, boost::foreach::tag) { return 0; }
template<typename T>
inline boost::mpl::true_ *
boost_foreach_is_lightweight_proxy(T **&, boost::foreach::tag) { return 0; }
///////////////////////////////////////////////////////////////////////////////
// boost_foreach_is_noncopyable
// Another customization point for the is_noncopyable trait,
// this one works on legacy compilers. Overload boost_foreach_is_noncopyable
// at the global namespace for your type.
template<typename T>
inline boost::foreach::is_noncopyable<T> *
boost_foreach_is_noncopyable(T *&, BOOST_FOREACH_TAG_DEFAULT) { return 0; }
namespace boost
{
namespace foreach_detail_
{
///////////////////////////////////////////////////////////////////////////////
// Define some utilities for assessing the properties of expressions
//
template<typename Bool1, typename Bool2>
inline boost::mpl::and_<Bool1, Bool2> *and_(Bool1 *, Bool2 *) { return 0; }
template<typename Bool1, typename Bool2, typename Bool3>
inline boost::mpl::and_<Bool1, Bool2, Bool3> *and_(Bool1 *, Bool2 *, Bool3 *) { return 0; }
template<typename Bool1, typename Bool2>
inline boost::mpl::or_<Bool1, Bool2> *or_(Bool1 *, Bool2 *) { return 0; }
template<typename Bool1, typename Bool2, typename Bool3>
inline boost::mpl::or_<Bool1, Bool2, Bool3> *or_(Bool1 *, Bool2 *, Bool3 *) { return 0; }
template<typename Bool>
inline boost::mpl::not_<Bool> *not_(Bool *) { return 0; }
template<typename T>
inline boost::mpl::false_ *is_rvalue_(T &, int) { return 0; }
template<typename T>
inline boost::mpl::true_ *is_rvalue_(T const &, ...) { return 0; }
template<typename T>
inline boost::is_array<T> *is_array_(T const &) { return 0; }
template<typename T>
inline boost::is_const<T> *is_const_(T &) { return 0; }
#ifndef BOOST_FOREACH_NO_RVALUE_DETECTION
template<typename T>
inline boost::mpl::true_ *is_const_(T const &) { return 0; }
#endif
///////////////////////////////////////////////////////////////////////////////
// auto_any_t/auto_any
// General utility for putting an object of any type into automatic storage
struct auto_any_base
{
// auto_any_base must evaluate to false in boolean context so that
// they can be declared in if() statements.
operator bool() const
{
return false;
}
};
template<typename T>
struct auto_any : auto_any_base
{
auto_any(T const &t)
: item(t)
{
}
// temporaries of type auto_any will be bound to const auto_any_base
// references, but we still want to be able to mutate the stored
// data, so declare it as mutable.
mutable T item;
};
typedef auto_any_base const &auto_any_t;
template<typename T, typename C>
inline BOOST_DEDUCED_TYPENAME boost::mpl::if_<C, T const, T>::type &auto_any_cast(auto_any_t a)
{
return static_cast<auto_any<T> const &>(a).item;
}
typedef boost::mpl::true_ const_;
///////////////////////////////////////////////////////////////////////////////
// type2type
//
template<typename T, typename C = boost::mpl::false_>
struct type2type
: boost::mpl::if_<C, T const, T>
{
};
template<typename T>
struct wrap_cstr
{
typedef T type;
};
template<>
struct wrap_cstr<char *>
{
typedef wrap_cstr<char *> type;
typedef char *iterator;
typedef char *const_iterator;
};
template<>
struct wrap_cstr<char const *>
{
typedef wrap_cstr<char const *> type;
typedef char const *iterator;
typedef char const *const_iterator;
};
template<>
struct wrap_cstr<wchar_t *>
{
typedef wrap_cstr<wchar_t *> type;
typedef wchar_t *iterator;
typedef wchar_t *const_iterator;
};
template<>
struct wrap_cstr<wchar_t const *>
{
typedef wrap_cstr<wchar_t const *> type;
typedef wchar_t const *iterator;
typedef wchar_t const *const_iterator;
};
template<typename T>
struct is_char_array
: mpl::and_<
is_array<T>
, mpl::or_<
is_convertible<T, char const *>
, is_convertible<T, wchar_t const *>
>
>
{};
template<typename T, typename C = boost::mpl::false_>
struct foreach_iterator
{
// **** READ THIS IF YOUR COMPILE BREAKS HERE ****
//
// There is an ambiguity about how to iterate over arrays of char and wchar_t.
// Should the last array element be treated as a null terminator to be skipped, or
// is it just like any other element in the array? To fix the problem, you must
// say which behavior you want.
//
// To treat the container as a null-terminated string, merely cast it to a
// char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ...
//
// To treat the container as an array, use boost::as_array() in <boost/range/as_array.hpp>,
// as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ...
#if !defined(BOOST_MSVC) || BOOST_MSVC > 1300
BOOST_MPL_ASSERT_MSG( (!is_char_array<T>::value), IS_THIS_AN_ARRAY_OR_A_NULL_TERMINATED_STRING, (T&) );
#endif
// If the type is a pointer to a null terminated string (as opposed
// to an array type), there is no ambiguity.
typedef BOOST_DEDUCED_TYPENAME wrap_cstr<T>::type container;
typedef BOOST_DEDUCED_TYPENAME boost::mpl::eval_if<
C
, range_const_iterator<container>
, range_mutable_iterator<container>
>::type type;
};
template<typename T, typename C = boost::mpl::false_>
struct foreach_reverse_iterator
{
// **** READ THIS IF YOUR COMPILE BREAKS HERE ****
//
// There is an ambiguity about how to iterate over arrays of char and wchar_t.
// Should the last array element be treated as a null terminator to be skipped, or
// is it just like any other element in the array? To fix the problem, you must
// say which behavior you want.
//
// To treat the container as a null-terminated string, merely cast it to a
// char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ...
//
// To treat the container as an array, use boost::as_array() in <boost/range/as_array.hpp>,
// as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ...
#if !defined(BOOST_MSVC) || BOOST_MSVC > 1300
BOOST_MPL_ASSERT_MSG( (!is_char_array<T>::value), IS_THIS_AN_ARRAY_OR_A_NULL_TERMINATED_STRING, (T&) );
#endif
// If the type is a pointer to a null terminated string (as opposed
// to an array type), there is no ambiguity.
typedef BOOST_DEDUCED_TYPENAME wrap_cstr<T>::type container;
typedef BOOST_DEDUCED_TYPENAME boost::mpl::eval_if<
C
, range_reverse_iterator<container const>
, range_reverse_iterator<container>
>::type type;
};
template<typename T, typename C = boost::mpl::false_>
struct foreach_reference
: iterator_reference<BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type>
{
};
///////////////////////////////////////////////////////////////////////////////
// encode_type
//
template<typename T>
inline type2type<T> *encode_type(T &, boost::mpl::false_ *) { return 0; }
template<typename T>
inline type2type<T, const_> *encode_type(T const &, boost::mpl::true_ *) { return 0; }
///////////////////////////////////////////////////////////////////////////////
// set_false
//
inline bool set_false(bool &b)
{
b = false;
return false;
}
///////////////////////////////////////////////////////////////////////////////
// to_ptr
//
template<typename T>
inline T *&to_ptr(T const &)
{
static T *t = 0;
return t;
}
// Borland needs a little extra help with arrays
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
template<typename T,std::size_t N>
inline T (*&to_ptr(T (&)[N]))[N]
{
static T (*t)[N] = 0;
return t;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// derefof
//
template<typename T>
inline T &derefof(T *t)
{
// This is a work-around for a compiler bug in Borland. If T* is a pointer to array type U(*)[N],
// then dereferencing it results in a U* instead of U(&)[N]. The cast forces the issue.
return reinterpret_cast<T &>(
*const_cast<char *>(
reinterpret_cast<char const volatile *>(t)
)
);
}
#ifdef BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION
///////////////////////////////////////////////////////////////////////////////
// Detect at compile-time whether an expression yields an rvalue or
// an lvalue. This is rather non-standard, but some popular compilers
// accept it.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// rvalue_probe
//
template<typename T>
struct rvalue_probe
{
struct private_type_ {};
// can't ever return an array by value
typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_<
boost::mpl::or_<boost::is_abstract<T>, boost::is_array<T> >, private_type_, T
>::type value_type;
operator value_type() { return *reinterpret_cast<value_type *>(this); } // never called
operator T &() const { return *reinterpret_cast<T *>(const_cast<rvalue_probe *>(this)); } // never called
};
template<typename T>
rvalue_probe<T> const make_probe(T const &)
{
return rvalue_probe<T>();
}
# define BOOST_FOREACH_IS_RVALUE(COL) \
boost::foreach_detail_::and_( \
boost::foreach_detail_::not_(boost::foreach_detail_::is_array_(COL)) \
, (true ? 0 : boost::foreach_detail_::is_rvalue_( \
(true ? boost::foreach_detail_::make_probe(COL) : (COL)), 0)))
#elif defined(BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION)
///////////////////////////////////////////////////////////////////////////////
// Detect at run-time whether an expression yields an rvalue
// or an lvalue. This is 100% standard C++, but not all compilers
// accept it. Also, it causes FOREACH to break when used with non-
// copyable collection types.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// rvalue_probe
//
template<typename T>
struct rvalue_probe
{
rvalue_probe(T &t, bool &b)
: value(t)
, is_rvalue(b)
{
}
struct private_type_ {};
// can't ever return an array or an abstract type by value
#ifdef BOOST_NO_IS_ABSTRACT
typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_<
boost::is_array<T>, private_type_, T
>::type value_type;
#else
typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_<
boost::mpl::or_<boost::is_abstract<T>, boost::is_array<T> >, private_type_, T
>::type value_type;
#endif
operator value_type()
{
this->is_rvalue = true;
return this->value;
}
operator T &() const
{
return this->value;
}
private:
T &value;
bool &is_rvalue;
};
template<typename T>
rvalue_probe<T> make_probe(T &t, bool &b) { return rvalue_probe<T>(t, b); }
template<typename T>
rvalue_probe<T const> make_probe(T const &t, bool &b) { return rvalue_probe<T const>(t, b); }
///////////////////////////////////////////////////////////////////////////////
// simple_variant
// holds either a T or a T const*
template<typename T>
struct simple_variant
{
simple_variant(T const *t)
: is_rvalue(false)
{
*static_cast<T const **>(this->data.address()) = t;
}
simple_variant(T const &t)
: is_rvalue(true)
{
::new(this->data.address()) T(t);
}
simple_variant(simple_variant const &that)
: is_rvalue(that.is_rvalue)
{
if(this->is_rvalue)
::new(this->data.address()) T(*that.get());
else
*static_cast<T const **>(this->data.address()) = that.get();
}
~simple_variant()
{
if(this->is_rvalue)
this->get()->~T();
}
T const *get() const
{
if(this->is_rvalue)
return static_cast<T const *>(this->data.address());
else
return *static_cast<T const * const *>(this->data.address());
}
private:
enum size_type { size = sizeof(T) > sizeof(T*) ? sizeof(T) : sizeof(T*) };
simple_variant &operator =(simple_variant const &);
bool const is_rvalue;
aligned_storage<size> data;
};
// If the collection is an array or is noncopyable, it must be an lvalue.
// If the collection is a lightweight proxy, treat it as an rvalue
// BUGBUG what about a noncopyable proxy?
template<typename LValue, typename IsProxy>
inline BOOST_DEDUCED_TYPENAME boost::enable_if<boost::mpl::or_<LValue, IsProxy>, IsProxy>::type *
should_copy_impl(LValue *, IsProxy *, bool *)
{
return 0;
}
// Otherwise, we must determine at runtime whether it's an lvalue or rvalue
inline bool *
should_copy_impl(boost::mpl::false_ *, boost::mpl::false_ *, bool *is_rvalue)
{
return is_rvalue;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// contain
//
template<typename T>
inline auto_any<T> contain(T const &t, boost::mpl::true_ *) // rvalue
{
return t;
}
template<typename T>
inline auto_any<T *> contain(T &t, boost::mpl::false_ *) // lvalue
{
// Cannot seem to get sunpro to handle addressof() with array types.
#if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x570))
return &t;
#else
return boost::addressof(t);
#endif
}
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
template<typename T>
auto_any<simple_variant<T> >
contain(T const &t, bool *rvalue)
{
return *rvalue ? simple_variant<T>(t) : simple_variant<T>(&t);
}
#endif
/////////////////////////////////////////////////////////////////////////////
// begin
//
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type>
begin(auto_any_t col, type2type<T, C> *, boost::mpl::true_ *) // rvalue
{
return boost::begin(auto_any_cast<T, C>(col));
}
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type>
begin(auto_any_t col, type2type<T, C> *, boost::mpl::false_ *) // lvalue
{
typedef BOOST_DEDUCED_TYPENAME type2type<T, C>::type type;
typedef BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type iterator;
return iterator(boost::begin(derefof(auto_any_cast<type *, boost::mpl::false_>(col))));
}
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
template<typename T>
auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, const_>::type>
begin(auto_any_t col, type2type<T, const_> *, bool *)
{
return boost::begin(*auto_any_cast<simple_variant<T>, boost::mpl::false_>(col).get());
}
#endif
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<typename T, typename C>
inline auto_any<T *>
begin(auto_any_t col, type2type<T *, C> *, boost::mpl::true_ *) // null-terminated C-style strings
{
return auto_any_cast<T *, boost::mpl::false_>(col);
}
#endif
///////////////////////////////////////////////////////////////////////////////
// end
//
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type>
end(auto_any_t col, type2type<T, C> *, boost::mpl::true_ *) // rvalue
{
return boost::end(auto_any_cast<T, C>(col));
}
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type>
end(auto_any_t col, type2type<T, C> *, boost::mpl::false_ *) // lvalue
{
typedef BOOST_DEDUCED_TYPENAME type2type<T, C>::type type;
typedef BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type iterator;
return iterator(boost::end(derefof(auto_any_cast<type *, boost::mpl::false_>(col))));
}
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
template<typename T>
auto_any<BOOST_DEDUCED_TYPENAME foreach_iterator<T, const_>::type>
end(auto_any_t col, type2type<T, const_> *, bool *)
{
return boost::end(*auto_any_cast<simple_variant<T>, boost::mpl::false_>(col).get());
}
#endif
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<typename T, typename C>
inline auto_any<int>
end(auto_any_t col, type2type<T *, C> *, boost::mpl::true_ *) // null-terminated C-style strings
{
return 0; // not used
}
#endif
///////////////////////////////////////////////////////////////////////////////
// done
//
template<typename T, typename C>
inline bool done(auto_any_t cur, auto_any_t end, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type iter_t;
return auto_any_cast<iter_t, boost::mpl::false_>(cur) == auto_any_cast<iter_t, boost::mpl::false_>(end);
}
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<typename T, typename C>
inline bool done(auto_any_t cur, auto_any_t, type2type<T *, C> *) // null-terminated C-style strings
{
return ! *auto_any_cast<T *, boost::mpl::false_>(cur);
}
#endif
///////////////////////////////////////////////////////////////////////////////
// next
//
template<typename T, typename C>
inline void next(auto_any_t cur, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type iter_t;
++auto_any_cast<iter_t, boost::mpl::false_>(cur);
}
///////////////////////////////////////////////////////////////////////////////
// deref
//
template<typename T, typename C>
inline BOOST_DEDUCED_TYPENAME foreach_reference<T, C>::type
deref(auto_any_t cur, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_iterator<T, C>::type iter_t;
return *auto_any_cast<iter_t, boost::mpl::false_>(cur);
}
/////////////////////////////////////////////////////////////////////////////
// rbegin
//
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type>
rbegin(auto_any_t col, type2type<T, C> *, boost::mpl::true_ *) // rvalue
{
return boost::rbegin(auto_any_cast<T, C>(col));
}
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type>
rbegin(auto_any_t col, type2type<T, C> *, boost::mpl::false_ *) // lvalue
{
typedef BOOST_DEDUCED_TYPENAME type2type<T, C>::type type;
typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type iterator;
return iterator(boost::rbegin(derefof(auto_any_cast<type *, boost::mpl::false_>(col))));
}
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
template<typename T>
auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, const_>::type>
rbegin(auto_any_t col, type2type<T, const_> *, bool *)
{
return boost::rbegin(*auto_any_cast<simple_variant<T>, boost::mpl::false_>(col).get());
}
#endif
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<typename T, typename C>
inline auto_any<reverse_iterator<T *> >
rbegin(auto_any_t col, type2type<T *, C> *, boost::mpl::true_ *) // null-terminated C-style strings
{
T *p = auto_any_cast<T *, boost::mpl::false_>(col);
while(0 != *p)
++p;
return reverse_iterator<T *>(p);
}
#endif
///////////////////////////////////////////////////////////////////////////////
// rend
//
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type>
rend(auto_any_t col, type2type<T, C> *, boost::mpl::true_ *) // rvalue
{
return boost::rend(auto_any_cast<T, C>(col));
}
template<typename T, typename C>
inline auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type>
rend(auto_any_t col, type2type<T, C> *, boost::mpl::false_ *) // lvalue
{
typedef BOOST_DEDUCED_TYPENAME type2type<T, C>::type type;
typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type iterator;
return iterator(boost::rend(derefof(auto_any_cast<type *, boost::mpl::false_>(col))));
}
#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION
template<typename T>
auto_any<BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, const_>::type>
rend(auto_any_t col, type2type<T, const_> *, bool *)
{
return boost::rend(*auto_any_cast<simple_variant<T>, boost::mpl::false_>(col).get());
}
#endif
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<typename T, typename C>
inline auto_any<reverse_iterator<T *> >
rend(auto_any_t col, type2type<T *, C> *, boost::mpl::true_ *) // null-terminated C-style strings
{
return reverse_iterator<T *>(auto_any_cast<T *, boost::mpl::false_>(col));
}
#endif
///////////////////////////////////////////////////////////////////////////////
// rdone
//
template<typename T, typename C>
inline bool rdone(auto_any_t cur, auto_any_t end, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type iter_t;
return auto_any_cast<iter_t, boost::mpl::false_>(cur) == auto_any_cast<iter_t, boost::mpl::false_>(end);
}
///////////////////////////////////////////////////////////////////////////////
// rnext
//
template<typename T, typename C>
inline void rnext(auto_any_t cur, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type iter_t;
++auto_any_cast<iter_t, boost::mpl::false_>(cur);
}
///////////////////////////////////////////////////////////////////////////////
// rderef
//
template<typename T, typename C>
inline BOOST_DEDUCED_TYPENAME foreach_reference<T, C>::type
rderef(auto_any_t cur, type2type<T, C> *)
{
typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator<T, C>::type iter_t;
return *auto_any_cast<iter_t, boost::mpl::false_>(cur);
}
} // namespace foreach_detail_
} // namespace boost
// Suppress a bogus code analysis warning on vc8+
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# define BOOST_FOREACH_SUPPRESS_WARNINGS() __pragma(warning(suppress:6001))
#else
# define BOOST_FOREACH_SUPPRESS_WARNINGS()
#endif
///////////////////////////////////////////////////////////////////////////////
// Define a macro for giving hidden variables a unique name. Not strictly
// needed, but eliminates some warnings on some compilers.
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1500))
// With some versions of MSVC, use of __LINE__ to create unique identifiers
// can fail when the Edit-and-Continue debug flag is used.
# define BOOST_FOREACH_ID(x) x
#else
# define BOOST_FOREACH_ID(x) BOOST_PP_CAT(x, __LINE__)
#endif
// A sneaky way to get the type of the collection without evaluating the expression
#define BOOST_FOREACH_TYPEOF(COL) \
(true ? 0 : boost::foreach_detail_::encode_type(COL, boost::foreach_detail_::is_const_(COL)))
// returns true_* if the type is noncopyable
#define BOOST_FOREACH_IS_NONCOPYABLE(COL) \
boost_foreach_is_noncopyable( \
boost::foreach_detail_::to_ptr(COL) \
, boost_foreach_argument_dependent_lookup_hack_value)
// returns true_* if the type is a lightweight proxy (and is not noncopyable)
#define BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL) \
boost::foreach_detail_::and_( \
boost::foreach_detail_::not_(BOOST_FOREACH_IS_NONCOPYABLE(COL)) \
, boost_foreach_is_lightweight_proxy( \
boost::foreach_detail_::to_ptr(COL) \
, boost_foreach_argument_dependent_lookup_hack_value))
#ifdef BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION
///////////////////////////////////////////////////////////////////////////////
// R-values and const R-values supported here with zero runtime overhead
///////////////////////////////////////////////////////////////////////////////
// No variable is needed to track the rvalue-ness of the collection expression
# define BOOST_FOREACH_PREAMBLE() \
BOOST_FOREACH_SUPPRESS_WARNINGS()
// Evaluate the collection expression
# define BOOST_FOREACH_EVALUATE(COL) \
(COL)
# define BOOST_FOREACH_SHOULD_COPY(COL) \
(true ? 0 : boost::foreach_detail_::or_( \
BOOST_FOREACH_IS_RVALUE(COL) \
, BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL)))
#elif defined(BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION)
///////////////////////////////////////////////////////////////////////////////
// R-values and const R-values supported here
///////////////////////////////////////////////////////////////////////////////
// Declare a variable to track the rvalue-ness of the collection expression
# define BOOST_FOREACH_PREAMBLE() \
BOOST_FOREACH_SUPPRESS_WARNINGS() \
if (bool BOOST_FOREACH_ID(_foreach_is_rvalue) = false) {} else
// Evaluate the collection expression, and detect if it is an lvalue or and rvalue
# define BOOST_FOREACH_EVALUATE(COL) \
(true ? boost::foreach_detail_::make_probe((COL), BOOST_FOREACH_ID(_foreach_is_rvalue)) : (COL))
// The rvalue/lvalue-ness of the collection expression is determined dynamically, unless
// type type is an array or is noncopyable or is non-const, in which case we know it's an lvalue.
// If the type happens to be a lightweight proxy, always make a copy.
# define BOOST_FOREACH_SHOULD_COPY(COL) \
(boost::foreach_detail_::should_copy_impl( \
true ? 0 : boost::foreach_detail_::or_( \
boost::foreach_detail_::is_array_(COL) \
, BOOST_FOREACH_IS_NONCOPYABLE(COL) \
, boost::foreach_detail_::not_(boost::foreach_detail_::is_const_(COL))) \
, true ? 0 : BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL) \
, &BOOST_FOREACH_ID(_foreach_is_rvalue)))
#elif !defined(BOOST_FOREACH_NO_RVALUE_DETECTION)
///////////////////////////////////////////////////////////////////////////////
// R-values supported here, const R-values NOT supported here
///////////////////////////////////////////////////////////////////////////////
// No variable is needed to track the rvalue-ness of the collection expression
# define BOOST_FOREACH_PREAMBLE() \
BOOST_FOREACH_SUPPRESS_WARNINGS()
// Evaluate the collection expression
# define BOOST_FOREACH_EVALUATE(COL) \
(COL)
// Determine whether the collection expression is an lvalue or an rvalue.
// NOTE: this gets the answer wrong for const rvalues.
# define BOOST_FOREACH_SHOULD_COPY(COL) \
(true ? 0 : boost::foreach_detail_::or_( \
boost::foreach_detail_::is_rvalue_((COL), 0) \
, BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL)))
#else
///////////////////////////////////////////////////////////////////////////////
// R-values NOT supported here
///////////////////////////////////////////////////////////////////////////////
// No variable is needed to track the rvalue-ness of the collection expression
# define BOOST_FOREACH_PREAMBLE() \
BOOST_FOREACH_SUPPRESS_WARNINGS()
// Evaluate the collection expression
# define BOOST_FOREACH_EVALUATE(COL) \
(COL)
// Can't use rvalues with BOOST_FOREACH (unless they are lightweight proxies)
# define BOOST_FOREACH_SHOULD_COPY(COL) \
(true ? 0 : BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL))
#endif
#define BOOST_FOREACH_CONTAIN(COL) \
boost::foreach_detail_::contain( \
BOOST_FOREACH_EVALUATE(COL) \
, BOOST_FOREACH_SHOULD_COPY(COL))
#define BOOST_FOREACH_BEGIN(COL) \
boost::foreach_detail_::begin( \
BOOST_FOREACH_ID(_foreach_col) \
, BOOST_FOREACH_TYPEOF(COL) \
, BOOST_FOREACH_SHOULD_COPY(COL))
#define BOOST_FOREACH_END(COL) \
boost::foreach_detail_::end( \
BOOST_FOREACH_ID(_foreach_col) \
, BOOST_FOREACH_TYPEOF(COL) \
, BOOST_FOREACH_SHOULD_COPY(COL))
#define BOOST_FOREACH_DONE(COL) \
boost::foreach_detail_::done( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_ID(_foreach_end) \
, BOOST_FOREACH_TYPEOF(COL))
#define BOOST_FOREACH_NEXT(COL) \
boost::foreach_detail_::next( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_TYPEOF(COL))
#define BOOST_FOREACH_DEREF(COL) \
boost::foreach_detail_::deref( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_TYPEOF(COL))
#define BOOST_FOREACH_RBEGIN(COL) \
boost::foreach_detail_::rbegin( \
BOOST_FOREACH_ID(_foreach_col) \
, BOOST_FOREACH_TYPEOF(COL) \
, BOOST_FOREACH_SHOULD_COPY(COL))
#define BOOST_FOREACH_REND(COL) \
boost::foreach_detail_::rend( \
BOOST_FOREACH_ID(_foreach_col) \
, BOOST_FOREACH_TYPEOF(COL) \
, BOOST_FOREACH_SHOULD_COPY(COL))
#define BOOST_FOREACH_RDONE(COL) \
boost::foreach_detail_::rdone( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_ID(_foreach_end) \
, BOOST_FOREACH_TYPEOF(COL))
#define BOOST_FOREACH_RNEXT(COL) \
boost::foreach_detail_::rnext( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_TYPEOF(COL))
#define BOOST_FOREACH_RDEREF(COL) \
boost::foreach_detail_::rderef( \
BOOST_FOREACH_ID(_foreach_cur) \
, BOOST_FOREACH_TYPEOF(COL))
///////////////////////////////////////////////////////////////////////////////
// BOOST_FOREACH
//
// For iterating over collections. Collections can be
// arrays, null-terminated strings, or STL containers.
// The loop variable can be a value or reference. For
// example:
//
// std::list<int> int_list(/*stuff*/);
// BOOST_FOREACH(int &i, int_list)
// {
// /*
// * loop body goes here.
// * i is a reference to the int in int_list.
// */
// }
//
// Alternately, you can declare the loop variable first,
// so you can access it after the loop finishes. Obviously,
// if you do it this way, then the loop variable cannot be
// a reference.
//
// int i;
// BOOST_FOREACH(i, int_list)
// { ... }
//
#define BOOST_FOREACH(VAR, COL) \
BOOST_FOREACH_PREAMBLE() \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_col) = BOOST_FOREACH_CONTAIN(COL)) {} else \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_cur) = BOOST_FOREACH_BEGIN(COL)) {} else \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_end) = BOOST_FOREACH_END(COL)) {} else \
for (bool BOOST_FOREACH_ID(_foreach_continue) = true; \
BOOST_FOREACH_ID(_foreach_continue) && !BOOST_FOREACH_DONE(COL); \
BOOST_FOREACH_ID(_foreach_continue) ? BOOST_FOREACH_NEXT(COL) : (void)0) \
if (boost::foreach_detail_::set_false(BOOST_FOREACH_ID(_foreach_continue))) {} else \
for (VAR = BOOST_FOREACH_DEREF(COL); !BOOST_FOREACH_ID(_foreach_continue); BOOST_FOREACH_ID(_foreach_continue) = true)
///////////////////////////////////////////////////////////////////////////////
// BOOST_REVERSE_FOREACH
//
// For iterating over collections in reverse order. In
// all other respects, BOOST_REVERSE_FOREACH is like
// BOOST_FOREACH.
//
#define BOOST_REVERSE_FOREACH(VAR, COL) \
BOOST_FOREACH_PREAMBLE() \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_col) = BOOST_FOREACH_CONTAIN(COL)) {} else \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_cur) = BOOST_FOREACH_RBEGIN(COL)) {} else \
if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_end) = BOOST_FOREACH_REND(COL)) {} else \
for (bool BOOST_FOREACH_ID(_foreach_continue) = true; \
BOOST_FOREACH_ID(_foreach_continue) && !BOOST_FOREACH_RDONE(COL); \
BOOST_FOREACH_ID(_foreach_continue) ? BOOST_FOREACH_RNEXT(COL) : (void)0) \
if (boost::foreach_detail_::set_false(BOOST_FOREACH_ID(_foreach_continue))) {} else \
for (VAR = BOOST_FOREACH_RDEREF(COL); !BOOST_FOREACH_ID(_foreach_continue); BOOST_FOREACH_ID(_foreach_continue) = true)
#endif
|
[
"[email protected]"
] |
[
[
[
1,
1099
]
]
] |
f66f4cbf9fe2f93df71a6245999dce0efda6e4ca
|
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
|
/GameServer/MapGroupKernel/Team.cpp
|
cf02cec9563e7b6e589f394630d528c9e8f38235
|
[] |
no_license
|
cronoszeu/revresyksgpr
|
78fa60d375718ef789042c452cca1c77c8fa098e
|
5a8f637e78f7d9e3e52acdd7abee63404de27e78
|
refs/heads/master
| 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null |
GB18030
|
C++
| false | false | 20,553 |
cpp
|
#include "allmsg.h"
#include "Team.h"
#include "mapgroup.h"
#define GUIDING_TIME 60*60 //一个小时
MYHEAP_IMPLEMENTATION(CTeam,s_heap)
CTeam::CTeam(PROCESS_ID idProcess)
{
m_idProcess = idProcess;
this->m_tGuidingTime.Startup(GUIDING_TIME);
}
CTeam::~CTeam()
{
}
CTeam* CTeam::CreateNew(PROCESS_ID idProcess, OBJID m_idTeam, OBJID idLeader)
{
CTeam* pTeam = new CTeam(idProcess);
if (!pTeam)
return NULL;
if (!pTeam->Create(idLeader))
{
delete pTeam;
return NULL;
}
pTeam->m_id = m_idTeam;
return pTeam;
}
CTeam* CTeam::CreateNew(PROCESS_ID idProcess, TeamInfoStruct* pInfo)
{
CTeam* pTeam = new CTeam(idProcess);
IF_NOT(pTeam)
return NULL;
IF_NOT(pTeam->Create(pInfo->idLeader))
{
delete pTeam;
return NULL;
}
pTeam->m_id = pInfo->id;
for(int i = 0; i < _MAX_TEAMAMOUNT; i++)
{
if(pInfo->setMember[i] != ID_NONE && pInfo->setMember[i] != pInfo->idLeader)
pTeam->AddMemberOnly(pInfo->setMember[i]);
}
pTeam->m_bCloseMoney = pInfo->bCloseMoney;
pTeam->m_bCloseItem = pInfo->bCloseItem;
return pTeam;
}
bool CTeam::Create(OBJID idLeader)
{
this->Init();
m_idLeader = idLeader;
this->AddMemberOnly(idLeader);
CUser* pPlayer = UserManager()->GetUser(idLeader);
if (pPlayer) // may be not current mapgroup
pPlayer->SetStatus(STATUS_TEAMLEADER);
return true;
}
BOOL CTeam::AddMember(OBJID idMember)
{
if (m_fClosed)
return false;
int nOldAmount = this->GetMemberAmount();
if (nOldAmount >= _MAX_TEAMAMOUNT)
return false;
if (this->IsTeamMember(idMember))
return false;
CUser* pMember = UserManager()->GetUser(idMember);
if (!pMember)
return false;
int nSize = m_setIdUser.size();
for(int i = 0; i < nSize; i++)
{
CUser* pPlayer = UserManager()->GetUser(m_setIdUser[i]);
if(pPlayer)
{
IF_OK(pPlayer->GetTeam())
pPlayer->GetTeam()->AddMemberOnly(idMember);
}
else
{
MapGroup(PID)->QueryIntraMsg()->ChangeTeam(CHANGETEAM_ADD, GetID(), idMember);
}
}
int nNewAmount = this->GetMemberAmount();
if (nOldAmount != nNewAmount
&& (nOldAmount >= TEAM_STATUS_REQ_ROLES || nNewAmount >= TEAM_STATUS_REQ_ROLES))
{
AdjustMemberStatus(nOldAmount, nNewAmount);
}
pMember->SetTeam(this->CloneNew()); //? 只会在本地
return true;
}
BOOL CTeam::DelMember(OBJID idMember)
{// 从队伍里删除队员ID,不需要检验ID的有效性。
int nOldAmount = this->GetMemberAmount();
int nSize = nOldAmount; //this->GetMemberAmount();
for (int i=nSize-1; i>=0; i--)
{// 倒序,删除
CUser* pPlayer = UserManager()->GetUser(m_setIdUser[i]);
if (pPlayer)
{
IF_OK(pPlayer->GetTeam())
{
pPlayer->GetTeam()->DelMemberOnly(idMember);
}
}
else
{
MapGroup(PID)->QueryIntraMsg()->ChangeTeam(CHANGETEAM_DEL, GetID(), idMember);
}
}
int nNewAmount = this->GetMemberAmount();
if (nOldAmount != nNewAmount
&& (nOldAmount >= TEAM_STATUS_REQ_ROLES || nNewAmount >= TEAM_STATUS_REQ_ROLES))
{
AdjustMemberStatus(nOldAmount, nNewAmount);
}
return true;
}
void CTeam::Dismiss(OBJID idLeader)
{
CUser* pLeader = UserManager()->GetUser(idLeader);
if (pLeader)
{
for (int i=STATUS_TEAM_BEGIN; i<=STATUS_TEAM_END; i++)
{
if (pLeader->QueryStatus(i))
{
CMsgTalk msg;
if (msg.Create(SYSTEM_NAME, ALLUSERS_NAME, STR_TEAM_STATUS_DISAPPEAR, NULL, 0xff0000, _TXTATR_SYSTEM))
this->BroadcastTeamMsg(&msg);
break;
}
}
}
int nSize = this->GetMemberAmount();
for (int i=nSize-1; i>=0; i--)
{// 倒序,删除
CUser* pPlayer = UserManager()->GetUser(m_setIdUser[i]);
if (pPlayer)
{
IF_OK(pPlayer->GetTeam())
{
if(pPlayer->GetID() != idLeader) // owner在外面删除
pPlayer->ClrTeam(); //? 可能在远程,CUser::DelTeamMember()中会删除
}
}
else
{
MapGroup(PID)->QueryIntraMsg()->ChangeTeam(CHANGETEAM_DISMISS, GetID(), idLeader);
}
}
}
OBJID CTeam::GetMemberByIndex(int nIndex)
{
if (nIndex >= m_setIdUser.size() || nIndex < 0)
return ID_NONE;
return m_setIdUser[nIndex];
}
void CTeam::Destroy()
{
this->Init();
}
void CTeam::Init()
{
m_setIdUser.clear();
m_fClosed = false;
m_bCloseMoney = false;
m_bCloseItem = true;
m_bCloseGemAccess = true;
m_idLeader = ID_NONE;
}
void CTeam::SetLeader(OBJID idLeader)
{
if (m_idLeader != ID_NONE) // 已经设置过队长了。
return;
CUser* pPlayer = UserManager()->GetUser(idLeader);
if (!pPlayer)
return;
m_idLeader = idLeader;
}
OBJID CTeam::GetLeader()
{
return m_idLeader;
}
int CTeam::GetMemberAmount()
{
return __min(_MAX_TEAMAMOUNT, m_setIdUser.size());
}
void CTeam::BroadcastTeamMsg(Msg* pMsg, CUser* pSender/*=NULL*/)
{
if (!pMsg)
return;
for (int i=0; i<this->GetMemberAmount(); i++)
{
CUser* pUser = NULL;
OBJID idUser = this->GetMemberByIndex(i);
pUser = UserManager()->GetUser(idUser);
if (pUser)
{
if (pUser != pSender)
pUser->SendMsg(pMsg);
}
else // 跨进程组
{
MapGroup(PID)->QueryIntraMsg()->TransmitWorldMsgByUserID(pMsg, idUser);
}
}
}
void CTeam::Open()
{
m_fClosed = false;
}
void CTeam::Close()
{
m_fClosed = true;
}
BOOL CTeam::IsClosed()
{
return m_fClosed;
}
void CTeam::OpenMoney()
{
m_bCloseMoney = false;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_MONEY_s, STR_OPEN);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseMoney(false);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_MONEY;
pInfo->IntParam[0] = false;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
void CTeam::CloseMoney()
{
m_bCloseMoney = true;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_MONEY_s, STR_CLOSE);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseMoney(true);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_MONEY;
pInfo->IntParam[0] = true;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
void CTeam::OpenItem()
{
m_bCloseItem = false;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_ITEM_s, STR_OPEN);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseItem(false);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_ITEM;
pInfo->IntParam[0] = false;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
void CTeam::CloseItem()
{
m_bCloseItem = true;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_ITEM_s, STR_CLOSE);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseItem(true);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_ITEM;
pInfo->IntParam[0] = true;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
void CTeam::OpenGemAccess()
{
m_bCloseGemAccess = false;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_GEM_s, STR_OPEN);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseGemAccess(false);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_GEM_ACCESS;
pInfo->IntParam[0] = false;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
void CTeam::CloseGemAccess()
{
m_bCloseGemAccess = true;
char szBuf[1024];
sprintf(szBuf, STR_TEAM_GEM_s, STR_CLOSE);
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idTarget = this->GetMemberByIndex(i);
CUser* pTarget = UserManager()->GetUser(idTarget);
if (pTarget) //? may be another mapgroup
{
CTeam* pTeam = pTarget->GetTeam();
IF_OK(pTeam)
{
pTeam->SetCloseGemAccess(true);
pTarget->SendSysMsg(_TXTATR_TEAM, szBuf);
}
}
else
{
// remote call
char buf[1024];
REMOTE_CALL0* pInfo = (REMOTE_CALL0*)&buf;
pInfo->idUser = idTarget;
pInfo->ucFuncType = REMOTE_CALL_TEAM_CLOSE_GEM_ACCESS;
pInfo->IntParam[0] = true;
pInfo->nSize = sizeof(REMOTE_CALL0) + sizeof(int);
MapGroup(PID)->QueryIntraMsg()->RemoteCall(pInfo);
}
}
}
BOOL CTeam::IsTeamWithNewbie(OBJID idKiller, IRole* pTarget)
{
CHECKF (pTarget);
BOOL bNewbieBonus = false;
int nMonsterLev = pTarget->GetLev();
for (int i=0; i<this->GetMemberAmount(); i++)
{
CUser* pUser = UserManager()->GetUser(this->GetMemberByIndex(i));
if (pUser) //? may be another mapgroup
{
if (!pUser->IsAlive())
continue;
if (pUser->GetMapID() != pTarget->GetMap()->GetID())
continue;
if (abs(pUser->GetPosX()-pTarget->GetPosX()) > _RANGE_EXPSHARE ||
abs(pUser->GetPosY()-pTarget->GetPosY()) > _RANGE_EXPSHARE)
continue; // out of share range
if (pUser->GetLev()+20 < nMonsterLev)
{
bNewbieBonus = true;
break;
}
}
}
return bNewbieBonus;
}
BOOL CTeam::IsTeamWithTutor(OBJID idKiller, IRole* pTarget)
{
CHECKF (pTarget);
bool bWithTutor = false;
for (int i=0; i<this->GetMemberAmount(); i++)
{
CUser* pUser = UserManager()->GetUser(this->GetMemberByIndex(i));
if (pUser) //? may be another mapgroup
{
if (!pUser->IsAlive())
continue;
if (pUser->GetMapID() != pTarget->GetMap()->GetID())
continue;
if (abs(pUser->GetPosX()-pTarget->GetPosX()) > _RANGE_EXPSHARE ||
abs(pUser->GetPosY()-pTarget->GetPosY()) > _RANGE_EXPSHARE)
continue; // out of share range
if (pUser->GetStudent(idKiller))
{
bWithTutor = true;
break;
}
}
}
return bWithTutor;
}
void CTeam::AwardMemberExp(OBJID idKiller, IRole* pTarget, int nExp)
{
// 1. idKiller代表杀死怪物的玩家ID,这个玩家不加组队经验了。
// 2. nAddExp代表杀死怪物玩家获取的奖励经验
CHECK (pTarget);
CUser* pKiller = UserManager()->GetUser(idKiller);
IF_NOT (pKiller)
return;
int nMonsterLev = pTarget->GetLev();
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idUser = this->GetMemberByIndex(i);
CUser* pUser = UserManager()->GetUser(idUser);
if (!pUser) //? may be in another mapgroup.
continue;
// map, no self
if (pUser->GetMapID() != pTarget->GetMap()->GetID() || pUser->GetID() == idKiller)
continue;
// chk all eudemons exclude killer's
for (int i=0; i<pUser->GetEudemonAmount(); i++)
{
CMonster* pEudemon = pUser->QueryEudemonByIndex(i);
if (pEudemon && pEudemon->IsAlive() &&
(abs(pEudemon->GetPosX()-pTarget->GetPosX()) <= _RANGE_EXPSHARE
|| abs(pEudemon->GetPosY()-pTarget->GetPosY()) <= _RANGE_EXPSHARE))
{
int nAwardExp = CBattleSystem::AdjustExp(nExp, pEudemon->GetLev(), pTarget->GetLev());
bool bIncludeOwner = false;
pEudemon->AwardBattleExp(nExp, true, bIncludeOwner);
}
}
// no self
if (!(pUser->IsAlive() && pUser->GetID() != idKiller))
continue;
// distance
if (abs(pUser->GetPosX()-pTarget->GetPosX()) > _RANGE_EXPSHARE ||
abs(pUser->GetPosY()-pTarget->GetPosY()) > _RANGE_EXPSHARE)
continue; // out of share range
int nAddExp = pUser->AdjustExp(pTarget, nExp);
// 下面这几行如果可能最好并入AdjustExp
CLevupexpData* pLevupexp = LevupexpSet()->GetObj(EXP_TYPE_USER * _EXP_TYPE + pUser->GetLev());
if (!pLevupexp)
return;
int nMaxStuExp = pLevupexp->GetInt(LEVUPEXPDATA_STU_EXP);
nAddExp = __min(nAddExp, nMaxStuExp);
if (!pKiller->IsNewbie() && pUser->IsNewbie())
{
// 老玩家带新玩家练级,可以得到导师经验
int nTutorExp = nAddExp*10/nMaxStuExp;
if (pKiller->GetStudent(pUser->GetID())) // 如果新玩家是自己的学徒,导师经验翻倍
nTutorExp *= 2;
// award tutor exp
pKiller->AwardTutorExp(nTutorExp);
// msg
pKiller->SendSysMsg(STR_TEACHER_EXP, nTutorExp);
}
// max exp
if(nAddExp > pUser->GetLev() * MAX_TEAM_EXP_TIMES)
nAddExp = pUser->GetLev() * MAX_TEAM_EXP_TIMES;
// double exp
if (pUser->IsMasterPrentice(pKiller) || pUser->IsMate(pKiller))
nAddExp *= 2;
// award exp now
pUser->AwardBattleExp(nAddExp);
// msg
pUser->SendSysMsg(STR_TEAM_EXPERIENCE, nAddExp);
}
}
void CTeam::BroadcastMemberLife(CUser* pMember, bool bMaxLife)
{
if (!pMember)
return;
for (int i=0; i<this->GetMemberAmount(); i++)
{
CUser* pUser = NULL;
OBJID idUser = this->GetMemberByIndex(i);
DEBUG_TRY
pUser = UserManager()->GetUser(idUser);
DEBUG_CATCH("Team broadcast member life get user by id crash.")
if (pUser && pUser->GetID() != pMember->GetID())
{
MsgUserAttrib msg;
if (msg.Create(pMember->GetID(), _USERATTRIB_LIFE, pMember->GetLife()))
{
if(bMaxLife)
msg.Append(_USERATTRIB_MAXLIFE, pMember->GetMaxLife());
pUser->SendMsg(&msg);
}
}
}
}
BOOL CTeam::IsTeamMember(OBJID idMember)
{
for(int i = 0; i < GetMemberAmount(); i++)
{
if(GetMemberByIndex(i) == idMember)
return TRUE;
}
return FALSE;
}
CTeam* CTeam::CloneNew()
{
CTeam* pTeam = new CTeam(m_idProcess);
CHECKF(pTeam);
*pTeam = *this;
return pTeam;
}
void CTeam::GetInfo(TeamInfoStruct* pInfo)
{
memset(pInfo, 0, sizeof(TeamInfoStruct));
pInfo->id = m_id;
pInfo->idLeader = m_idLeader;
for(int i = 0; i < m_setIdUser.size() && i < _MAX_TEAMAMOUNT; i++)
{
pInfo->setMember[i] = m_setIdUser[i];
}
pInfo->bCloseMoney = m_bCloseMoney;
pInfo->bCloseItem = m_bCloseItem;
}
//
void CTeam::AddMemberOnly (OBJID idMember)
{
m_setIdUser.push_back(idMember);
}
void CTeam::DelMemberOnly (OBJID idMember)
{
USERIDSET::iterator iter = find(m_setIdUser.begin(), m_setIdUser.end(), idMember);
if(iter != m_setIdUser.end())
m_setIdUser.erase(iter);
}
void CTeam::AttachMemberStatus(int nStatus, int nPower, int nSecs, int nTimes, OBJID idExclude)
{
CUser* pLeader = UserManager()->GetUser(this->GetLeader());
if (!pLeader || !pLeader->IsAlive())
return ; // 队长不存在或者死了
for (int i=0; i<this->GetMemberAmount(); i++)
{
CUser* pUser = UserManager()->GetUser(this->GetMemberByIndex(i));
if (pUser) //? may be another mapgroup
{
// 给幻兽加状态
for (int i=0; i<pUser->GetEudemonAmount(); i++)
{
CMonster* pEudemon = pUser->QueryEudemonByIndex(i);
if (pEudemon
&& pEudemon->GetMap()->GetID() == pLeader->GetMapID()
&& (pEudemon->GetDistance(pLeader->QueryMapThing()) <= _RANGE_TEAM_STATUS || STATUS_ADD_EXP == nStatus))
{
if (!pEudemon->QueryStatus(nStatus))
CRole::AttachStatus(pEudemon->QueryRole(), nStatus, nPower, nSecs, nTimes);
}
}
// 给玩家加状态
if (pUser->GetID() != idExclude)
{
if (pUser->IsAlive()
&& pUser->GetMapID() == pLeader->GetMapID()
&& (pUser->GetDistance(pLeader->QueryMapThing()) <= _RANGE_TEAM_STATUS || STATUS_ADD_EXP == nStatus))
{
if (!pUser->QueryStatus(nStatus))
CRole::AttachStatus(pUser->QueryRole(), nStatus, nPower, nSecs, nTimes);
}
}
}
}
}
void CTeam::AdjustMemberStatus(int nOldAmount, int nNewAmount)
{
USERIDSET::iterator it=m_setIdUser.begin();
for (; it!=m_setIdUser.end(); it++)
{
CUser* pUser = UserManager()->GetUser(*it);
if (pUser)
{
// 只有速度需要通知客户端,其他界结状态的影响效果都是即时计算的无需通知客户端
if (pUser->QueryStatus(STATUS_TEAMSPEED))
{
MsgUserAttrib msg;
IF_OK (msg.Create(pUser->GetID(), _USERATTRIB_SPEED, pUser->AdjustSpeed(pUser->GetSpeed())))
pUser->BroadcastRoomMsg(&msg, INCLUDE_SELF);
}
}
}
CUser* pLeader = UserManager()->GetUser(this->GetLeader());
if (pLeader)
{
for (int i=STATUS_TEAM_BEGIN; i<=STATUS_TEAM_END; i++)
{
if (pLeader->QueryStatus(i))
{
char szMsg[256] = "";
if (nNewAmount < TEAM_STATUS_REQ_ROLES)
::SafeCopy(szMsg, STR_TEAM_STATUS_DISAPPEAR, 256);
else
{
if (nOldAmount < nNewAmount)
sprintf(szMsg, STR_TEAM_STATUS_POWER_INC, 10*(nNewAmount-nOldAmount));
else
sprintf(szMsg, STR_TEAM_STATUS_POWER_DEC, 10*(nOldAmount-nNewAmount));
}
CMsgTalk msg;
if (msg.Create(SYSTEM_NAME, ALLUSERS_NAME, szMsg, NULL, 0xff0000, _TXTATR_SYSTEM))
this->BroadcastTeamMsg(&msg);
break;
}
}
}
}
// 平分伤害,返回修改后的实际伤害
int CTeam::ShareDamage(int nDamage, OBJID idExclude)
{
typedef std::vector<IRole*> ROLE_SET;
ROLE_SET setMember;
for (int i=0; i<this->GetMemberAmount(); i++)
{
OBJID idMember = this->GetMemberByIndex(i);
CUser* pMember = UserManager()->GetUser(idMember);
// 与带有心灵结界的其他队伍成员(包括幻兽)平分伤害 -- 只考虑当前地图组
if (pMember)
{
for (int i=0; i<pMember->GetEudemonAmount(); i++)
{
CMonster* pEudemon = pMember->QueryEudemonByIndex(i);
if (pEudemon && pEudemon->GetLife()>1 && pEudemon->QueryStatus(STATUS_TEAMSPIRIT))
setMember.push_back(pEudemon->QueryRole());
}
if (pMember->GetID() != idExclude && pMember->GetLife()>1 && pMember->QueryStatus(STATUS_TEAMSPIRIT))
setMember.push_back(pMember->QueryRole());
}
}
nDamage = __max(1, nDamage/(setMember.size()+1)); // 平均伤害值
for (ROLE_SET::iterator it=setMember.begin(); it!=setMember.end(); it++)
{
IRole* pRole = *it;
ASSERT(pRole);
// TODO:
// ?? 幻兽的生命是灵力,所以这里恐怕针对幻兽得做修改 -- zlong 2004.11.26
int nLifeLost = __min(pRole->GetLife()-1, nDamage);
pRole->AddAttrib(_USERATTRIB_LIFE, -1*nLifeLost, SYNCHRO_TRUE);
}
setMember.clear();
return nDamage;
}
//带其他玩家练级,每带其他玩家练级一个小时,军团声望增加100点。
//void CTeam::DealTeamLeaderInfo()
//{
// DEBUG_TRY
//
// if(this->m_tGuidingTime.ToNextTime())
// {
// CUser * pLeader = UserManager()->GetUser(this->GetLeader());
// if(pLeader)
// {
// CSyndicate * pSyn = pLeader->GetSyndicate();
// if(pSyn)
// {
// pSyn->QueryModify()->AddData(SYNDATA_REPUTE, TEAMLEADER_WITHNEWBIE_REPUTEINC, true);
// //添加声望增量
// // pLeader->QuerySynAttr()->AddReputeInc(TEAMLEADER_WITHNEWBIE_REPUTEINC);
// }
// }
// }
//
// DEBUG_CATCH("void CTeam::DealTeamLeaderInfo()")
//}
|
[
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
] |
[
[
[
1,
827
]
]
] |
3e62d1c966758651b5e9d976de8427eb47a8d440
|
27d5670a7739a866c3ad97a71c0fc9334f6875f2
|
/CPP/Targets/SupportWFLib/symbian/RectTools.h
|
dec40f70798ec290d249bc3992bfdbaff921e877
|
[
"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 | 19,964 |
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 TRECTTOOLS_H
#define TRECTTOOLS_H
#include <e32std.h>
namespace {
enum TRectPanic {
ERectBadPercent = 0,
ERectNot100Percent = 1,
};
void RectPanic(enum TRectPanic aPanic)
{
_LIT(KRectPanic, "RectTools");
User::Panic(KRectPanic, aPanic);
}
///Sets the width to half of the original width. The top left corner
///of the rect stays in the same place.
///@param aRect original TRect to work with.
///@return a Rect with half the width of aRect.
inline class TRect HalfWidth(class TRect aRect)
{
aRect.Normalize();
aRect.SetWidth(aRect.Width() / 2);
return aRect;
}
///Sets the height to half of the original height. The topleft corner
///of the rect stays in the same place.
///@param aRect original TRect to work with.
///@return a TRect with half the height of aRect.
inline class TRect HalfHeight(class TRect aRect)
{
aRect.Normalize();
aRect.SetHeight(aRect.Height() / 2);
return aRect;
}
///Flips the rect around it's right edge. This is the same as moving
///the rect the rects width pixels right.
///@param aRect the original TRect.
///@return a Rect with the same size as aRect, but with it's top left
/// corner in the same spot as aRect's top right corner.
inline class TRect FlipRight(class TRect aRect)
{
aRect.Normalize();
aRect.Move(aRect.Width(), 0);
return aRect;
}
///Sets the width to half of the original width. The bottom right corner
///of the rect stays in the same place.
///@param aRect original TRect to work with.
///@return a Rect with half the width of aRect.
inline class TRect RightHalf(const class TRect& aRect)
{
return FlipRight(HalfWidth(aRect));
}
///Flips the rect around it's lower edge. This is the same as moving
///the rect the rects height pixels down.
///@param aRect the original TRect.
///@return a Rect with the same size as aRect, but with it's top left
/// corner in the same spot as aRect's lower left corner.
inline class TRect FlipDown(class TRect aRect)
{
aRect.Normalize();
aRect.Move(0, aRect.Height());
return aRect;
}
///Moves the right edge of the rect inwards by the specified number of
///pixels.
///@param aRect the original TRect.
///@param aPixels the number of pixels to move the right edge. If
/// aPixels is negative the edge will be moved outward
/// instead.
///@return a TRect with the same position as aRect, but aPixels thinner.
inline class TRect ShrinkRight(class TRect aRect, TInt aPixels)
{
aRect.Normalize();
aRect.iBr.iX -= aPixels;
return aRect;
}
///Moves the left edge of the rect inwards by the specified number of
///pixels.
///@param aRect the original TRect.
///@param aPixels the number of pixels to move the left edge. If
/// aPixels is negative the edge will be moved outward
/// instead.
///@return a TRect with the same bottom right corner as aRect, but
/// aPixels thinner.
inline class TRect ShrinkLeft(class TRect aRect, TInt aPixels)
{
aRect.Normalize();
aRect.iTl.iX += aPixels;
return aRect;
}
///Moves the top edge of the rect inwards by the specified number of
///pixels.
///@param aRect the original TRect.
///@param aPixels the number of pixels to move the top edge. If
/// aPixels is negative the edge will be moved outward
/// instead.
///@return a TRect with the same bottom right corner as aRect, but
/// aPixels lower.
inline class TRect ShrinkTop(class TRect aRect, TInt aPixels)
{
aRect.Normalize();
aRect.iTl.iY += aPixels;
return aRect;
}
///Moves the bottom edge of the rect inwards by the specified number of
///pixels.
///@param aRect the original TRect.
///@param aPixels the number of pixels to move the bottom edge. If
/// aPixels is negative the edge will be moved outward
/// instead.
///@return a TRect with the same top left corner as aRect, but
/// aPixels smaller height.
inline class TRect ShrinkBottom(class TRect aRect, TInt aPixels)
{
aRect.Normalize();
aRect.iBr.iY -= aPixels;
return aRect;
}
///Moves the top and left edges inwards by the number of pixels
///specified in aPixelPair.iY and aPixelPair.iX respectively.
///@param aRect the original TRect.
///@param aPixelPair the value to subtract from aRect.iTl. If any of
/// the values in aPixelPair is negative, that edge
/// will be moved outwards instead.
///@return a TRect with the same bottom right corner as aRect, but
/// with the top left corner moved aPixelPair pixels.
inline class TRect ShrinkTopLeft(class TRect aRect, TPoint aPixelPair)
{
aRect.Normalize();
aRect.iTl -= aPixelPair;
return aRect;
}
///Moves the top and left edges inwards by the number of pixels
///specified in aPixels
///@param aRect the original TRect.
///@param aPixelPair the value to move the top left corner inwards.
/// If the aPixels value is negative, the edges
/// will be moved outwards instead.
///@return a TRect with the same bottom right corner as aRect, but
/// with the top left corner moved aPixels pixels inwards.
inline class TRect ShrinkTopLeft(class TRect aRect, TInt aPixels)
{
return ShrinkTopLeft(aRect, TPoint(aPixels, aPixels));
}
///Shrinks a rectangle using a specified TSize offset. The rectangle
///shrinks by twice the value of the height and width specified in the
///TSize. The co-ordinates of the centre of the rectangle remain
///unchanged. If either value is negative, the rectangle expands in
///the corresponding direction.
///@param aRect the orignal TRect that will be shrunk.
///@param aSize the shrink offset.
///@return the shrunk rectangle.
inline class TRect Shrink(class TRect aRect, class TSize aSize)
{
aRect.Normalize();
aRect.Shrink(aSize);
return aRect;
}
///Shrinks a rectangle using a specified offset. The rectangles
///height and width shrinks by twice the offset. The co-ordinates of
///the centre of the rectangle remain unchanged. If the value is
///negative, the rectangle expands with this offset.
///@param aRect the orignal TRect that will be shrunk.
///@param aSize the shrink offset.
///@return the shrunk rectangle.
inline class TRect Shrink(const class TRect& aRect, TInt aSize)
{
return Shrink(aRect, TSize(aSize, aSize));
}
///Divides both the iHeight and iWidth members of a TSize object by
///the specified divisor.
///@param aTop the original TSize object.
///@param aDivisor the divisor.
///@return the resulting TSize object.
inline const class TSize operator/(class TSize aTop, TInt aDivisor)
{
aTop.iWidth /= aDivisor;
aTop.iHeight /= aDivisor;
return aTop;
}
///Finds the center point of a rectangle.
///@param aRect the rectangle which's center point we want to find.
///@return a TPoint object representing the center point of aRect.
inline class TPoint GetCenter(class TRect aRect)
{
aRect.Normalize();
return aRect.iTl + (aRect.Size() / 2);
}
///Sets the center point of a rectngle.
///@param aRect the rectangle to move.
///@param aNewCenter the new center point.
///@return the moved rectangle.
inline class TRect SetCenter(class TRect aRect, class TPoint aNewCenter)
{
aRect.Normalize();
TPoint offset = aNewCenter - GetCenter(aRect);
aRect.Move(offset);
return aRect;
}
///Sets the Height of a rectangle without moving it's top left corner.
///@param aRect the original rectangle.
///@param aHeight the new height.
///@return the modified rectangle.
inline class TRect SetHeight(class TRect aRect, TInt aHeight)
{
aRect.Normalize();
aRect.SetHeight(aHeight);
return aRect;
}
///Sets the width of a rectangle without moving it's top left corner.
///@param aRect the original rectangle.
///@param aWidth the new width.
///@return the modified rectangle.
inline class TRect SetWidth(class TRect aRect, TInt aWidth)
{
aRect.Normalize();
aRect.SetWidth(aWidth);
return aRect;
}
///Move one rectangle so that its center position is the same as that
///of another rectangle
///@param aCenterIn the reference rectangle.
///@param aOrigin the rectangle that should be moved.
///@return the moved rectangle.
inline class TRect Center(const class TRect& aCenterIn, class TRect aOrigin)
{
return SetCenter(aOrigin, GetCenter(aCenterIn));
// TSize offset = (aCenterIn.Size() - aOrigin.Size()) / 2;
// aOrigin.SetRect(aCenterIn.iTl, aOrigin.Size());
// aOrigin.Move(offset.iWidth, offset.iHeight);
// return aOrigin;
}
///Reduces the size of a TRect object by the amount contained in a
///TSize object, whitout changing the top left position of the TRect.
///@param aRect a reference to the object to be changed.
///@param aSize the amount to change the size with.
///@return a copy of the changed TRect object.
inline const class TRect operator-=(class TRect& aRect, TSize aSize)
{
aRect.Normalize();
aRect.iBr -= aSize;
return aRect;
}
///Creates a new TRect object with the same top left corner as aRect,
///and its size being aRect.Size() - aSize.
///@param aRect the orignal TRect object.
///@param aSize the size to reduce with.
///@return a new TRect object with reduced size.
inline const class TRect operator-(class TRect aRect, class TSize aSize)
{
aRect.Normalize();
return aRect -= aSize;
}
///Splits a TRect horizontally so that the top half will be a
///specified percentage of the height. The original TRect that is fed
///as an argument to this funtion will be modified to be the lower
///half while the upper part will be retuned as a normal return value.
///@param aRect the orignal rectangle. Also used as the return value
/// for the lower TRect.
///@param percent specifies how many percent of aRect's original
/// height that will make up the top rectangle. Values less than
/// 0 or greater than 100 will cause a RectTools panic 0.
///@return the top rectangle that will be the top aPercent percent of
/// the original aRect rectangle
inline class TRect SplitHeight(class TRect& aRect, TInt aPercent)
{
if(aPercent > 100 || aPercent < 0){
RectPanic(ERectBadPercent);
}
TRect ret = aRect - TSize(0, (aRect.Height() * (100 - aPercent)) / 100);
aRect.iTl.iY = ret.iBr.iY + 1;
return ret;
}
///Splits a TRect vertically so that the left half will be a specified
///percentage of the original width. The original TRect that is fed as
///an argument to this funtion will be modified to be the right half
///while the left part will be retuned as a normal return value.
///@param aRect the orignal rectangle. Also used as the return value
/// for the right TRect.
///@param percent specifies how many percent of ARect's original
/// width that will make up the left rectangle. Values less than
/// 0 or greater than 100 will cause a RectTools 0 panic.
///@return the left rectangle that will be the left aPercent percent of
/// the original aRect rectangle
inline class TRect SplitWidth(class TRect& aRect, TInt percent)
{
if(percent > 100 || percent < 0){
RectPanic(ERectBadPercent);
}
TRect ret = aRect - TSize((aRect.Width() * (100 - percent)) / 100, 0);
aRect.iTl.iX = ret.iBr.iX + 1;
return ret;
}
///Support template class for SplitHeight. Used as return type.
template<TInt N>
struct TRectArray{
///An array of N TRects.
TRect iRects[N];
///Allows indexing in const TRectArray objects.
///@param aIndex index into array. Note that no check is made
/// whether the index is in range.
const TRect& operator[](TInt aIndex) const {
return iRects[aIndex];
}
///Allows indexing in non-const TRectArray objects.
///@param aIndex index into array. Note that no check is made
/// whether the index is in range.
TRect& operator[](TInt aIndex){
return iRects[aIndex];
}
void fill(TRect aRect)
{
for(TInt n = 0; n < N; ++n){
iRects[n] = aRect;
}
}
};
///Support template class for SplitHeight. Used as parameter type.
template<TInt N>
struct TIntArray{
///An array of TInts.
TInt iInts[N];
///Allows indexing in const TIntArray objects.
///@param aIndex index into array. Note that no check is made
/// whether the index is in range.
const TInt& operator[](TInt aIndex) const {
return iInts[aIndex];
}
///Allows indexing in non-const TIntArray objects.
///@param aIndex index into array. Note that no check is made
/// whether the index is in range.
TInt& operator[](TInt aIndex) {
return iInts[aIndex];
}
};
template<typename T, TInt N>
struct TTypeArray{
T iArray[N];
const T& operator[](TInt aIndex) const {
return iArray[aIndex];
}
T& operator[](TInt aIndex){
return iArray[aIndex];
}
void Fill(const T& aValue){
for(TInt n = 0; n < N; ++n){
iArray[n] = aValue;
}
}
};
///This template function splits a TRect N-ways. All parts have equal
///width, but the height is split according to the aParts TIntArray
///object. If the sum of all values in the aParts array isn't 100, a
///ERectNot100percent panic is raised.
///@param aRect the original TRect.
///@param aParts a TIntArray object holding the percent values.
///@return a TRectArray object with each held TRect matching a percent
/// value in aParts.
template<TInt N>
TRectArray<N> SplitHeight(const class TRect& aRect, const TIntArray<N>& aParts)
{
TInt sumOfParts = 0;
TIntArray<N> heights;
TInt sum = 0;
for(TInt a = 0; a < N; ++a){
sumOfParts += aParts[a];
heights[a] = (aRect.Height() * aParts[a])/100;
sum += heights[a];
}
if(sumOfParts != 100){
RectPanic(ERectNot100Percent);
}
TInt leftover = aRect.Height() - sum;
for(TInt j = 0; j < leftover; ++j){
heights[(leftover*j)%N] += 1;
}
TRectArray<N> results;
results.fill(aRect);
results[0].iBr.iY = aRect.iTl.iY + heights[0];
for(TInt k = 1; k < N; ++k){
results[k].iTl.iY = results[k-1].iBr.iY + 1;
results[k].iBr.iY = results[k].iTl.iY + heights[k];
}
return results;
}
///Returns a squale rectangle with width and height equal to the
///height of aRect. The returned TRect will have the same center
///position as aRect.
///@param aRect the original TRect.
///@return a Square.
inline class TRect SquareOnHeight(const class TRect& aRect)
{
TRect ret = aRect;
ret.SetWidth(aRect.Height());
return Center(aRect, ret);
}
///Returns a TRect with size aSize and the same top right corner as aRect.
///@param aRect the TRect from which the top right corner shall be taken.
///@param aSize the size of the returned rectangle.
///@return the new rectangle
inline class TRect TopRight(const class TRect& aRect, const class TSize& aSize)
{
return TRect(TPoint(aRect.iBr.iX - aSize.iWidth, aRect.iTl.iY), aSize);
}
///Returns a TRect with size aSize and the same lower right corner as aRect.
///@param aRect the TRect from which the lower right corner shall be taken.
///@param aSize the size of the returned rectangle.
///@return the new rectangle
inline class TRect LowerRight(const class TRect& aRect,
const class TSize& aSize)
{
return TRect(TPoint(aRect.iBr.iX - aSize.iWidth - 1,
aRect.iBr.iY - aSize.iHeight - 1), aSize);
}
///Returns a TRect with size aSize and the same bottom left corner as aRect.
///@param aRect the TRect from which the bottom left corner shall be taken.
///@param aSize the size of the returned rectangle.
///@return the new rectangle
inline class TRect LowerLeft(const class TRect& aRect,const class TSize& aSize)
{
return TRect(TPoint(aRect.iTl.iX, aRect.iBr.iY - aSize.iHeight - 1), aSize);
}
///Returns aRect moved by the specified amount.
///@param aRect the original rectangle.
///@param aDx the amount to move sideways. A positive amount moves
/// right, a negative left.
///@param aDy the amount to move up or down. A positive amount moves
/// down, a negative up.
///@return the moved rect.
inline class TRect Move(class TRect aRect, TInt aDx, TInt aDy)
{
aRect.Move(aDx, aDy);
return aRect;
}
///Returns aRect moved horizontally by the specified amount.
///@param aRect the original rectangle.
///@param aDx the amount to move sideways. A positive amount moves
/// right, a negative left.
///@return the moved rect.
inline class TRect MoveX(const class TRect& aRect, TInt aDx)
{
return Move(aRect, aDx, 0);
}
///Returns aRect moved vertically by the specified amount.
///@param aRect the original rectangle.
///@param aDy the amount to move. A positive amount moves down, a
/// negative up.
///@return the moved rect.
inline class TRect MoveY(const class TRect& aRect, TInt aDy)
{
return Move(aRect, 0, aDy);
}
///Tests whether one rectangle is totally contained whithin another rectangle.
///@param aContainer the containing TRect.
///@param aContainee the contained TRect.
///@param ETrue if both the bottom right corner and upper left corner
/// of aContainee are contained whithin the aContainer
/// rectangle.
inline TBool Contains(const class TRect& aContainer,
const class TRect& aContainee)
{
return aContainer.Contains(aContainee.iTl) &&
aContainer.Contains(aContainee.iBr);
}
}//namespace
///Tests if the control pointer is NULL. If not it will call the
///SetRect function with the TRect argument.
///@param aControl the control that will be affectef. If the pointer
/// is NULL the function is a no-op.
///@param aRect the new extent of the control.
inline void SetRect(class CCoeControl* aControl, const class TRect& aRect)
{
if(aControl){
aControl->SetRect(aRect);
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
547
]
]
] |
4cd741d7a4aa4f9c2863e3d3bd15f0bad4b2cb08
|
36bf908bb8423598bda91bd63c4bcbc02db67a9d
|
/WallPaperSFX/WallPaperSFX.cpp
|
97f7368e4eed17ae4b7bf49327f34c44d2200c18
|
[
"BSD-3-Clause"
] |
permissive
|
code4bones/crawlpaper
|
edbae18a8b099814a1eed5453607a2d66142b496
|
f218be1947a9791b2438b438362bc66c0a505f99
|
refs/heads/master
| 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 19,226 |
cpp
|
/*
WallPaperSFX.cpp
Eseguibile sfx per installazione WallPaper (SDK).
Luca Piergentili, 24/08/00
[email protected]
WallPaper (alias crawlpaper) - the hardcore of Windows desktop
http://www.crawlpaper.com/
copyright © 1998-2004 Luca Piergentili, all rights reserved
crawlpaper is a registered name, all rights reserved
This is a free software, released under the terms of the BSD license. Do not
attempt to use it in any form which violates the license or you will be persecuted
and charged for this.
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 "crawlpaper" 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.
*/
#include "env.h"
#include "pragma.h"
#include "macro.h"
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <direct.h>
#include <string.h>
#include "strings.h"
#define STRICT 1
#include <windows.h>
#include <windowsx.h>
#include "win32api.h"
#include <commctrl.h>
#include <shlobj.h>
#include "resource.h"
#include "gzwhdr.h"
#include "CProgressBar.h"
#include "CFindFile.h"
#include "CDirDialog.h"
#include "CSEFileInfo.h"
#include "CSelfExtractor.h"
#include "WallBrowserVersion.h"
#include "WallPaperVersion.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
#if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL))
#ifdef PRAGMA_MESSAGE_VERBOSE
#pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro")
#endif
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// macro
#define WALLPAPERSFX_DEFAULT_INSTALL_FOLDER WALLPAPER_PROGRAM_NAME
#define WALLPAPERSFX_PROGRAM_TITLE " "WALLPAPER_PROGRAM_NAME" Self Extractor Installer "
// prototipi
int WINAPI WinMain(HINSTANCE,HINSTANCE,LPSTR,int);
/*
CDialog
Classe base per il dialogo.
*/
class CDialog
{
public:
CDialog( HINSTANCE hInstance = NULL,
UINT nTemplateID = (UINT)-1,
UINT nIconID = (UINT)-1,
LPCSTR lpcszTitle = NULL
);
virtual ~CDialog() {}
UINT DoModal(void);
// inizializza, se ritorna FALSE il dialogo non viene visualizzato
virtual BOOL OnInitDialog(void) {return(TRUE);}
// gestori comandi
virtual void OnCommand(int nID,HWND hWndCtrl,UINT uiNotify) = 0;
// ricava l'handle del controllo
HWND GetDlgItem(UINT nID) {return(::GetDlgItem(m_hWnd,nID));}
// chiude il dialogo
void EndDialog(UINT nRet) {::EndDialog(m_hWnd,nRet);}
protected:
// per il passaggio dei parametri
typedef struct Param {
HWND hWnd;
UINT uMsg;
WPARAM wParam;
LPARAM lParam;
};
HINSTANCE m_hInstance; // handle dell'istanza
HWND m_hWnd; // handle del dialogo
UINT m_nTemplateID; // id del dialogo (resource)
UINT m_nIconID; // id dell'icona (resource)
LPCSTR m_lpcszTitle; // titolo del dialogo
private:
// inizializza il dialogo e chiama la virtuale
BOOL OnInitDialog(HWND hwndFocus,LPARAM lParam);
// per processare i messaggi di sistema (WM_...), chiama il membro non statico
// chiama il gestore OnCommand() per i messaggi (deve essere definito nella classe derivata)
static BOOL CALLBACK __stdcall DialogProcedure(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
BOOL DialogProcedure(Param* p);
};
/*
CDialog()
*/
CDialog::CDialog(HINSTANCE hInstance,UINT nTemplateID,UINT nIconID,LPCSTR lpcszTitle)
{
m_hInstance = hInstance;
m_hWnd = NULL;
m_nTemplateID = nTemplateID;
m_nIconID = nIconID;
m_lpcszTitle = lpcszTitle;
}
/*
DoModal()
*/
UINT CDialog::DoModal(void)
{
// da inizializzare col costruttore
if(m_hInstance==NULL || m_nTemplateID==(UINT)-1 || m_nIconID==(UINT)-1)
return(IDCANCEL);
// chiama la DialogBoxParam(), non la DialogBox(), per gestire la callback C++
return(::DialogBoxParam(m_hInstance,MAKEINTRESOURCE(m_nTemplateID),(HWND)NULL,this->DialogProcedure,(LPARAM)this));
}
/*
DialogProcedure()
Callback per la gestione dei messaggi (come WndProc() per le finestre).
Con la chiamata a DialogBoxParam() riceve il puntatore alla classe, ottenendo l'accesso ai membri.
*/
BOOL CALLBACK __stdcall CDialog::DialogProcedure(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
static CDialog* This = (CDialog*)NULL;
static Param p;
switch(uMsg)
{
// in lParam il puntatore alla classe
case WM_INITDIALOG:
{
p.hWnd = hWnd;
p.uMsg = uMsg;
p.wParam = wParam;
p.lParam = lParam;
This = (CDialog*)lParam;
return(This->DialogProcedure(&p));
break;
}
// messaggi, chiama la callback reale
default:
{
if(This!=(CDialog*)NULL)
{
p.hWnd = hWnd;
p.uMsg = uMsg;
p.wParam = wParam;
p.lParam = lParam;
return(This->DialogProcedure(&p));
}
else
return(FALSE);
break;
}
}
}
/*
DialogProcedure()
Callback per la gestione dei messaggi (chiamata dal membro di cui sopra).
*/
BOOL CDialog::DialogProcedure(Param* p)
{
switch(p->uMsg)
{
// se restituisce FALSE termina
case WM_INITDIALOG:
{
m_hWnd = p->hWnd;
if(!this->OnInitDialog((HWND)p->wParam,p->lParam))
::PostMessage(p->hWnd,WM_QUIT,0,0);
return(TRUE);
}
// comandi
case WM_COMMAND:
{
this->OnCommand((int)LOWORD(p->wParam),(HWND)p->lParam,(UINT)HIWORD(p->wParam));
return(TRUE);
}
default:
return(FALSE);
}
}
/*
OnInitDialog()
Inizializza il dialogo e chiama il membro virtuale (deve essere definito nella classe derivata).
Se il membro della classe derivata restituisce FALSE il dialogo viene chiuso.
*/
BOOL CDialog::OnInitDialog(HWND hwndFocus,LPARAM lParam)
{
if(m_hInstance==NULL || m_hWnd==NULL || m_nTemplateID==(UINT)-1 || m_nIconID==(UINT)-1)
return(FALSE);
// icona
::SetClassLong(m_hWnd,GCL_HICON,(LONG)::LoadIcon((HINSTANCE)::GetWindowLong(m_hWnd,GWL_HINSTANCE),MAKEINTRESOURCE(m_nIconID)));
// titolo
if(m_lpcszTitle)
::SetWindowText(m_hWnd,m_lpcszTitle);
return(this->OnInitDialog());
}
/*
CLicenseDialog
Classe derivata per il dialogo per la licenza.
*/
class CLicenseDialog : public CDialog
{
public:
// ctor/dtor
CLicenseDialog(HINSTANCE hInstance = NULL,UINT nTemplateID = (UINT)-1,UINT nIconID = (UINT)-1,LPCSTR lpcszTitle = NULL) : CDialog(hInstance,nTemplateID,nIconID,lpcszTitle)
{
memset(m_szLicense,'\0',sizeof(m_szLicense));
}
virtual ~CLicenseDialog() {}
// da definire
BOOL OnInitDialog(void);
void OnCommand(int,HWND,UINT);
// gestori
void OnButtonAccept(void);
void OnButtonDecline(void);
private:
char m_szLicense[8192];
};
/*
OnInitDialog()
*/
BOOL CLicenseDialog::OnInitDialog(void)
{
ExtractResourceIntoBuffer(IDR_LICENSE,"TXT",m_szLicense,sizeof(m_szLicense)-1);
// visualizza l'about
Edit_SetText(GetDlgItem(IDC_EDIT_LICENSE),m_szLicense);
return(TRUE);
}
/*
OnCommand()
*/
void CLicenseDialog::OnCommand(int nID,HWND hWndCtrl,UINT uiNotify)
{
// processa i comandi ricevuti dai controli del dialogo
switch(nID)
{
case IDOK:
{
OnButtonAccept();
break;
}
case IDCANCEL:
{
if(uiNotify==BN_CLICKED)
OnButtonDecline();
break;
}
}
}
/*
OnButtonAccept()
*/
void CLicenseDialog::OnButtonAccept(void)
{
EndDialog(IDOK);
}
/*
OnButtonDecline()
*/
void CLicenseDialog::OnButtonDecline(void)
{
EndDialog(IDCANCEL);
}
/*
CSelfExtractDialog
Classe derivata per il dialogo per l'installatore.
*/
class CSelfExtractDialog : public CDialog
{
public:
// ctor/dtor
CSelfExtractDialog(HINSTANCE hInstance = NULL,UINT nTemplateID = (UINT)-1,UINT nIconID = (UINT)-1,LPCSTR lpcszTitle = NULL) : CDialog(hInstance,nTemplateID,nIconID,lpcszTitle)
{
memset(m_szInstallFolder,'\0',sizeof(m_szInstallFolder));
memset(m_szStatus,'\0',sizeof(m_szStatus));
}
virtual ~CSelfExtractDialog() {}
// da definire
BOOL OnInitDialog(void);
void OnCommand(int,HWND,UINT);
// gestori
void OnEditPath(void);
void OnButtonInstall(void);
void OnButtonBrowse(void);
void OnButtonAbout(void);
void OnButtonExit(void);
// callback per la barra di progresso
static UINT ExtractCallBack(LPVOID,LPVOID);
private:
char m_szInstallFolder[_MAX_FILEPATH+1];
char m_szStatus[_MAX_PATH+1];
CProgressBar m_wndProgressBar;
};
/*
OnInitDialog()
*/
BOOL CSelfExtractDialog::OnInitDialog(void)
{
char szBuffer[1024];
// barra di progresso
m_wndProgressBar.Attach(m_hWnd,IDC_PROGRESS);
m_wndProgressBar.SetStep(1);
m_wndProgressBar.Hide();
// visualizza/nasconde i controlli
::ShowWindow(GetDlgItem(IDC_INSTALL),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_STATUS),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_PROGRESS),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_PATH),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_BROWSE),SW_SHOW);
// visualizza l'about
Edit_SetText(GetDlgItem(IDC_EDIT_ABOUT),g_lpcszCredits);
// imposta la directory per l'installazione
_snprintf(szBuffer,
sizeof(szBuffer)-1,
"%s will be installed into the following folder.\nClick on the Install button when ready.",
WALLPAPER_PROGRAM_NAME);
Edit_SetText(GetDlgItem(IDC_INSTALL),szBuffer);
// ricava la Program Files sucaminchia
ITEMIDLIST *id = NULL;
BOOL bSuccess = FALSE;
if(::SHGetSpecialFolderLocation(NULL,CSIDL_PROGRAM_FILES,&id)==NOERROR)
{
char szProgramFiles[_MAX_FILEPATH+1] = {0};
if(::SHGetPathFromIDList(id,&szProgramFiles[0]))
{
bSuccess = TRUE;
_snprintf(m_szInstallFolder,sizeof(m_szInstallFolder)-1,"%s\\%s",szProgramFiles,WALLPAPERSFX_DEFAULT_INSTALL_FOLDER);
}
}
if(!bSuccess)
_snprintf(m_szInstallFolder,sizeof(m_szInstallFolder)-1,"C:\\%s",WALLPAPERSFX_DEFAULT_INSTALL_FOLDER);
Edit_SetText(GetDlgItem(IDC_PATH),m_szInstallFolder);
return(TRUE);
}
/*
OnCommand()
*/
void CSelfExtractDialog::OnCommand(int nID,HWND hWndCtrl,UINT uiNotify)
{
// processa i comandi ricevuti dai controli del dialogo
switch(nID)
{
case IDC_PATH:
{
if(uiNotify==EN_CHANGE)
OnEditPath();
break;
}
case IDC_EXTRACT:
{
if(uiNotify==BN_CLICKED)
OnButtonInstall();
break;
}
case IDC_BROWSE:
{
if(uiNotify==BN_CLICKED)
OnButtonBrowse();
break;
}
case IDC_ABOUT:
{
if(uiNotify==BN_CLICKED)
OnButtonAbout();
break;
}
case IDCANCEL:
{
if(uiNotify==BN_CLICKED)
OnButtonExit();
break;
}
}
}
/*
OnEditPath()
*/
void CSelfExtractDialog::OnEditPath(void)
{
// dal controllo al buffer interno
Edit_GetText(GetDlgItem(IDC_PATH),m_szInstallFolder,sizeof(m_szInstallFolder)-1);
::RemoveBackslash(m_szInstallFolder);
}
/*
OnButtonInstall()
*/
void CSelfExtractDialog::OnButtonInstall(void)
{
int nRet = 0;
char szBuffer[2048];
// directory di output
if(strempty(m_szInstallFolder))
{
::MessageBox(m_hWnd,"No kidding please, select a valid folder as destination.",WALLPAPERSFX_PROGRAM_TITLE,MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONWARNING);
::MessageBeep(MB_ICONEXCLAMATION);
return;
}
CFindFile findfile;
if(!findfile.CreatePathName(m_szInstallFolder))
{
_snprintf(szBuffer,sizeof(szBuffer)-1,"Unable to create %s.",m_szInstallFolder);
::MessageBox(m_hWnd,szBuffer,WALLPAPERSFX_PROGRAM_TITLE,MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONERROR);
::MessageBeep(MB_ICONEXCLAMATION);
return;
}
// estrae i files
CSelfExtractor m_Extractor;
char szThisModule[_MAX_FILEPATH+1];
::GetThisModuleFileName(szThisModule,sizeof(szThisModule));
// visualizza/nasconde i controlli
::ShowWindow(GetDlgItem(IDC_INSTALL),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_STATUS),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_PROGRESS),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_PATH),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_BROWSE),SW_HIDE);
::EnableWindow(GetDlgItem(IDC_EXTRACT),FALSE);
::EnableWindow(GetDlgItem(IDC_ABOUT),FALSE);
::EnableWindow(GetDlgItem(IDCANCEL),FALSE);
#ifdef _DEBUG
nRet = SFX_SUCCESS;
#else
if((nRet = m_Extractor.ReadTOC(szThisModule))!=SFX_SUCCESS)
goto return_code;
#endif
// status bar
#ifdef _DEBUG
m_wndProgressBar.SetRange(0,100);
#else
m_wndProgressBar.SetRange(0,m_Extractor.GetFileCount());
#endif
m_wndProgressBar.Show();
Edit_SetText(GetDlgItem(IDC_STATUS),"");
#ifdef _DEBUG
strcpy(m_szStatus,"Extracting ...");
Edit_SetText(GetDlgItem(IDC_STATUS),m_szStatus);
for(int i=0; i < 100; i++)
{
m_wndProgressBar.StepIt();
::Sleep(50L);
}
nRet = SFX_SUCCESS;
#else
nRet = m_Extractor.ExtractAll(m_szInstallFolder,sizeof(m_szInstallFolder),CSelfExtractDialog::ExtractCallBack,this);
#endif
// status bar
m_wndProgressBar.Hide();
Edit_SetText(GetDlgItem(IDC_STATUS),"");
return_code:
::ShowWindow(GetDlgItem(IDC_INSTALL),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_STATUS),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_PROGRESS),SW_HIDE);
::ShowWindow(GetDlgItem(IDC_PATH),SW_SHOW);
::ShowWindow(GetDlgItem(IDC_BROWSE),SW_SHOW);
::EnableWindow(GetDlgItem(IDC_EXTRACT),TRUE);
::EnableWindow(GetDlgItem(IDC_ABOUT),TRUE);
::EnableWindow(GetDlgItem(IDCANCEL),TRUE);
::SetFocus(GetDlgItem(IDCANCEL));
switch(nRet)
{
case SFX_SUCCESS:
{
_snprintf(szBuffer,
sizeof(szBuffer)-1,
"%s has been installed successful.\n\n"
"For general notes about the program, see the readme.txt file.\n"
"For a list of changes of the current version (%s%s), see the\nchangelog.txt file.\n"
"License terms into the license.txt file, credits available into the\ncredits.txt file.\n"
"\nDo not miss to visit the web site (%s)\t\n"
"\nThat's all, crawl everything and have fun...\n",
WALLPAPER_PROGRAM_NAME,
WALLPAPER_VERSION_NUMBER,
WALLPAPER_VERSION_TYPE,
WALLPAPER_WEB_SITE
);
::MessageBeep(MB_OK);
::MessageBox(m_hWnd,szBuffer,WALLPAPERSFX_PROGRAM_TITLE,MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONINFORMATION);
// esegue quanto installato
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
::RemoveBackslash(m_szInstallFolder);
_snprintf(szBuffer,sizeof(szBuffer)-1,"%s\\%s.exe /i%s\\%s.exe",m_szInstallFolder,WALLPAPER_PROGRAM_NAME,m_szInstallFolder,WALLPAPER_PROGRAM_NAME);
memset(&si,'\0',sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
memset(&pi,'\0',sizeof(PROCESS_INFORMATION));
#ifdef _DEBUG
::MessageBox(m_hWnd,szBuffer,"Now executing...",MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONINFORMATION);
#else
if(::CreateProcess(NULL,szBuffer,NULL,NULL,FALSE,0L,NULL,NULL,&si,&pi))
::CloseHandle(pi.hProcess);
::Sleep(500L);
#endif
EndDialog(IDOK);
break;
}
case SFX_NO_SOURCE:
case SFX_INVALID_SIG:
case SFX_COPY_FAILED:
case SFX_NOTHING_TO_DO:
case SFX_OUTPUT_FILE_ERROR:
case SFX_INPUT_FILE_ERROR:
case SFX_RESOURCE_ERROR:
case SFX_COMPRESS_ERROR:
case SFX_UNCOMPRESS_ERROR:
case SFX_UNKNOWN_ERROR:
case SFX_SAME_FILES:
default:
{
_snprintf(szBuffer,sizeof(szBuffer)-1,"Extraction error: %s.",m_Extractor.GetLastErrorString());
::MessageBox(m_hWnd,szBuffer,WALLPAPERSFX_PROGRAM_TITLE,MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONWARNING);
::MessageBeep(MB_ICONEXCLAMATION);
break;
}
}
}
/*
OnButtonBrowse()
*/
void CSelfExtractDialog::OnButtonBrowse(void)
{
CDirDialog dlg(m_szInstallFolder,"Select the output directory");
if(dlg.DoModal(m_hWnd)==IDOK)
{
strcpyn(m_szInstallFolder,dlg.GetPathName(),sizeof(m_szInstallFolder));
Edit_SetText(GetDlgItem(IDC_PATH),m_szInstallFolder);
}
}
/*
OnButtonAbout()
*/
void CSelfExtractDialog::OnButtonAbout(void)
{
char szAuthorCopyright[256];
_snprintf(szAuthorCopyright,
sizeof(szAuthorCopyright)-1,
WALLPAPER_AUTHOR_COPYRIGHT,
WALLPAPER_AUTHOR_EMAIL
);
char szAbout[512];
_snprintf(szAbout,
sizeof(szAbout)-1,
"GZW Self Extractor Installer\n\n"
"%s.\n\n"
"The GZW API uses a modified version of the zLib library.\n"
"The self-extract portion of this code uses a modified version of the work of James Spibey.\n\n",
szAuthorCopyright
);
::MessageBeep(MB_OK);
::MessageBox(m_hWnd,szAbout," About ",MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONINFORMATION);
}
/*
OnButtonExit()
*/
void CSelfExtractDialog::OnButtonExit(void)
{
EndDialog(IDOK);
}
/*
ExtractCallBack()
*/
UINT CSelfExtractDialog::ExtractCallBack(void *ExtractData,void* userData)
{
CSEFileInfo* pData = (CSEFileInfo*)ExtractData;
CSelfExtractDialog* pDlg = (CSelfExtractDialog*)userData;
_snprintf(pDlg->m_szStatus,_MAX_PATH-4,"Extracting %s...",pData->GetFileName());
char* p = strstr(pDlg->m_szStatus,GZW_EXTENSION);
if(p)
*p = '\0';
strcat(pDlg->m_szStatus,"...");
Edit_SetText(pDlg->GetDlgItem(IDC_STATUS),pDlg->m_szStatus);
pDlg->m_wndProgressBar.StepIt();
return(0L);
}
/*
WinMain()
*/
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdLine,int nCmdShow)
{
if(::FindWindow((LPCSTR)NULL,WALLPAPERSFX_PROGRAM_TITLE)==(HWND)NULL)
{
CLicenseDialog dlgLicense(hInstance,IDD_LICENSE_DIALOG,IDI_GZW_EXTRACTOR,WALLPAPERSFX_PROGRAM_TITLE);
if(dlgLicense.DoModal()==IDOK)
{
CSelfExtractDialog dlgInstall(hInstance,IDD_EXTRACTOR_DIALOG,IDI_GZW_EXTRACTOR,WALLPAPERSFX_PROGRAM_TITLE);
dlgInstall.DoModal();
}
}
else
::MessageBox((HWND)NULL,"No kidding please, only one instance at time.",WALLPAPERSFX_PROGRAM_TITLE,MB_APPLMODAL|MB_SETFOREGROUND|MB_TOPMOST|MB_OK|MB_ICONERROR);
return(0);
}
|
[
"[email protected]"
] |
[
[
[
1,
711
]
]
] |
9991ba1346cb9d0c5f45e7ec664d61f7dbe5b1b1
|
b6bad03a59ec436b60c30fc793bdcf687a21cf31
|
/som2416/wince5/sdmemdiskio.cpp
|
890a680d79c0caa47485fe62e254603be8374d99
|
[] |
no_license
|
blackfa1con/openembed
|
9697f99b12df16b1c5135e962890e8a3935be877
|
3029d7d8c181449723bb16d0a73ee87f63860864
|
refs/heads/master
| 2021-01-10T14:14:39.694809 | 2010-12-16T03:20:27 | 2010-12-16T03:20:27 | 52,422,065 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 37,313 |
cpp
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
// Copyright (c) 2002 BSQUARE Corporation. All rights reserved.
// DO NOT REMOVE --- BEGIN EXTERNALLY DEVELOPED SOURCE CODE ID 40973--- DO NOT REMOVE
// SD Memory Card driver disk IO implementation
#include "SDMemory.h"
///////////////////////////////////////////////////////////////////////////////
// SDMemCalcDataAccessClocks - Calculate the data access clocks
// Input: pMemCard - the memcard
// Output: pReadAccessClocks - Pointer to ULONG for read access clocks
// pWriteAccessClocks - Pointer to ULONG for write access clocks
// Return: TRUE or FALSE to indicate function success/failure
// Notes: Calculate data access times for memory devices. This calculation
// is to fine tune the data delay time
///////////////////////////////////////////////////////////////////////////////
BOOL SDMemCalcDataAccessClocks(PSD_MEMCARD_INFO pMemCard,
PULONG pReadAccessClocks,
PULONG pWriteAccessClocks)
{
SD_CARD_INTERFACE cardInterface; // current card interface
SD_API_STATUS status; // intermediate status
DOUBLE clockPeriodNs; // clock period in nano seconds
ULONG asyncClocks; // clocks required for the async portion
// fetch the card clock rate
status = SDCardInfoQuery(pMemCard->hDevice,
SD_INFO_CARD_INTERFACE,
&cardInterface,
sizeof(cardInterface));
if(!SD_API_SUCCESS(status)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCalcDataAccessClocks: Can't get card interface info\r\n")));
return FALSE;
}
if(0 == cardInterface.ClockRate) {
DEBUGCHK(FALSE);
return FALSE;
}
// if the clock rate is greater than 1 Ghz, this won't work
if(cardInterface.ClockRate > 1000000000) {
DEBUGCHK(FALSE);
return FALSE;
}
// calculate the clock period in nano seconds, clock rate is in Hz
clockPeriodNs = 1000000000 / cardInterface.ClockRate;
// calculate the async portion now that we know the clock rate
// make asyncClock an integer
asyncClocks = (ULONG)(pMemCard->CSDRegister.DataAccessTime.TAAC / clockPeriodNs);
// add the async and synchronous portions together for the read access
*pReadAccessClocks = asyncClocks + pMemCard->CSDRegister.DataAccessTime.NSAC;
// for the write access the clocks area multiple of the read clocks
*pWriteAccessClocks = (*pReadAccessClocks) * pMemCard->CSDRegister.WriteSpeedFactor;
DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemCalcDataAccessClocks: Tpd:%f ns, Asynch: %f ns, AsyncClocks:%d , SyncClocks: %d, ReadTotal: %d, Write Factor: %d WriteTotal: %d \n"),
clockPeriodNs,
pMemCard->CSDRegister.DataAccessTime.TAAC,
asyncClocks,
pMemCard->CSDRegister.DataAccessTime.NSAC,
*pReadAccessClocks,
pMemCard->CSDRegister.WriteSpeedFactor,
*pWriteAccessClocks));
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// SDMemCardConfig - Initialise the memcard structure and card itself
// Input: pMemCard - SD memory card structure
// Output:
// Return: win32 status code
// Notes:
///////////////////////////////////////////////////////////////////////////////
DWORD SDMemCardConfig( PSD_MEMCARD_INFO pMemCard )
{
DWORD status = ERROR_SUCCESS; // intermediate win32 status
DWORD dwSDHC; // high capacity value
SD_API_STATUS apiStatus; // intermediate SD API status
SD_CARD_INTERFACE cardInterface; // card interface
SD_DATA_TRANSFER_CLOCKS dataTransferClocks; // data transfer clocks
// retrieve CID Register contents
apiStatus = SDCardInfoQuery( pMemCard->hDevice,
SD_INFO_REGISTER_CID,
&(pMemCard->CIDRegister),
sizeof(SD_PARSED_REGISTER_CID) );
if(!SD_API_SUCCESS(apiStatus)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCardConfig: Can't read CID Register\r\n")));
return ERROR_GEN_FAILURE;
}
// Retrieve CSD Register contents
apiStatus = SDCardInfoQuery( pMemCard->hDevice,
SD_INFO_REGISTER_CSD,
&(pMemCard->CSDRegister),
sizeof(SD_PARSED_REGISTER_CSD) );
if(!SD_API_SUCCESS(apiStatus)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCardConfig: Can't read CSD Register\r\n")));
return ERROR_GEN_FAILURE;
}
// retreive the card's RCA
apiStatus = SDCardInfoQuery(pMemCard->hDevice,
SD_INFO_REGISTER_RCA,
&(pMemCard->RCA),
sizeof(pMemCard->RCA));
if(!SD_API_SUCCESS(apiStatus)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCardConfig: Can't read RCA \r\n")));
return ERROR_GEN_FAILURE;
}
// get write protect state
apiStatus = SDCardInfoQuery( pMemCard->hDevice,
SD_INFO_CARD_INTERFACE,
&cardInterface,
sizeof(cardInterface));
if(!SD_API_SUCCESS(apiStatus)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCardConfig: Can't read Card Interface\r\n")));
return ERROR_GEN_FAILURE;
}
// Get write protect state from Card Interface structure
pMemCard->WriteProtected = cardInterface.WriteProtected;
if( pMemCard->WriteProtected ) {
DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemCardConfig: Card is write protected\r\n")));
}
// get capacity information
apiStatus = SDCardInfoQuery( pMemCard->hDevice,
SD_INFO_HIGH_CAPACITY_SUPPORT,
&dwSDHC,
sizeof(dwSDHC));
if(!SD_API_SUCCESS(apiStatus)) {
pMemCard->HighCapacity = FALSE;
}
else {
pMemCard->HighCapacity = dwSDHC != 0;
}
if( pMemCard->HighCapacity ) {
DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemCardConfig: Card is high capacity (2.0+)\r\n")));
}
// If the card doesn't support block reads, then fail
if (!(pMemCard->CSDRegister.CardCommandClasses & SD_CSD_CCC_BLOCK_READ)) {
DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemCardConfig: Card does not support block read\r\n")));
return ERROR_BAD_DEVICE;
}
// If the card doesn't support block writes, then mark the card as
// write protected
if (!(pMemCard->CSDRegister.CardCommandClasses & SD_CSD_CCC_BLOCK_WRITE)) {
DEBUGMSG(SDCARD_ZONE_INIT || SDCARD_ZONE_WARN, (TEXT("SDMemCardConfig: Card does not support block write; mark as WP\r\n")));
pMemCard->WriteProtected = TRUE;
}
// Calculate read and write data access clocks to fine tune access times
if( !SDMemCalcDataAccessClocks( pMemCard, &dataTransferClocks.ReadClocks, &dataTransferClocks.WriteClocks) ) {
DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemCardConfig: Unable to calculate data access clocks\r\n")));
return ERROR_GEN_FAILURE;
}
// Call API to set the read and write data access clocks
apiStatus = SDSetCardFeature( pMemCard->hDevice,
SD_SET_DATA_TRANSFER_CLOCKS,
&dataTransferClocks,
sizeof(dataTransferClocks));
if(!SD_API_SUCCESS(apiStatus)) {
DEBUGMSG(SDCARD_ZONE_ERROR,(TEXT("SDMemCardConfig: Can't set data access clocks\r\n")));
return ERROR_GEN_FAILURE;
}
// FATFS only supports 512 bytes per sector so set that
pMemCard->DiskInfo.di_bytes_per_sect = SD_BLOCK_SIZE;
// indicate that we aren't using Cylinder/Head/Sector addressing,
// and that reads and writes are synchronous.
pMemCard->DiskInfo.di_flags = DISK_INFO_FLAG_CHS_UNCERTAIN |
DISK_INFO_FLAG_PAGEABLE;
// since we aren't using C/H/S addressing we can set the counts of these
// items to zero
pMemCard->DiskInfo.di_cylinders = 0;
pMemCard->DiskInfo.di_heads = 0;
pMemCard->DiskInfo.di_sectors = 0;
// Work out whether we have a Master Boot Record
switch( pMemCard->CSDRegister.FileSystem ) {
case SD_FS_FAT_PARTITION_TABLE:
// yes, we have a MBR
pMemCard->DiskInfo.di_flags |= DISK_INFO_FLAG_MBR;
break;
case SD_FS_FAT_NO_PARTITION_TABLE:
// no, we don't have a MBR
break;
default:
// ee don't do "Other" file systems
DEBUGMSG( SDCARD_ZONE_ERROR, (TEXT("SDMemCardConfig: Card indicates unsupported file system (non FAT)\r\n")));
return ERROR_GEN_FAILURE;
}
// calculate total number of sectors on the card
//
// NOTE:The bus is only using BLOCK units instead of BYTE units if
// the device type is SD (not MMC) and if the CSDVersion is SD_CSD_VERSION_CODE_2_0.
// Since we don't have access to the device type, we are checking to see if it is
// a high definition card. This should work for most cases.
//
if( pMemCard->CSDRegister.CSDVersion == SD_CSD_VERSION_CODE_2_0 &&
pMemCard->HighCapacity ) {
pMemCard->DiskInfo.di_total_sectors = pMemCard->CSDRegister.DeviceSize;
#ifdef _MMC_SPEC_42_
/*************************************************************************/
/****** Date : 07.05.14 ******/
/****** Developer : HS.JANG ******/
/****** Description : If MMC card is on SPEC42 ******/
/*************************************************************************/
} else if (pMemCard->CSDRegister.SpecVersion >= HSMMC_CSD_SPEC_VERSION_CODE_SUPPORTED )
{
#ifdef FOR_MOVI_NAND
/*************************************************************************/
/****** Date : 07.05.28 ******/
/****** Developer : HS.JANG ******/
/****** Description : There is no way to distinguish between HSMMC ******/
/****** and moviNAND. So, We assume that All HSMMC ******/
/****** card is the moviNAND ******/
/*************************************************************************/
pMemCard->IsHSMMC = TRUE;
/*************************************************************************/
#endif
if( (signed)(pMemCard->CSDRegister.SectorCount) > 0)
{
RETAILMSG(1,(TEXT("[HSMMC] This MMC card is on SPEC 4.2\n")));
pMemCard->DiskInfo.di_total_sectors = pMemCard->CSDRegister.SectorCount;
pMemCard->HighCapacity = TRUE;
}
else
{
pMemCard->DiskInfo.di_total_sectors = pMemCard->CSDRegister.DeviceSize/SD_BLOCK_SIZE;
}
/*************************************************************************/
#endif
} else {
pMemCard->DiskInfo.di_total_sectors = pMemCard->CSDRegister.DeviceSize/SD_BLOCK_SIZE;
}
// FATFS and the SD Memory file spec only supports 512 byte sectors. An SD Memory
// card will ALWAYS allow us to read and write in 512 byte blocks - but it might
// be configured for a larger size initially. We set the size to 512 bytes here if needed.
if( pMemCard->CSDRegister.MaxReadBlockLength != SD_BLOCK_SIZE ) {
// Set block length to 512 bytes
status = SDMemSetBlockLen( pMemCard, SD_BLOCK_SIZE );
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
// SDMemRead - Read data from card into pSG scatter gather buffers
// Input: pMemCard - SD memory card structure
// pSG - Scatter Gather buffer structure from FATFS
// Output:
// Return: Status - windows status code
// Notes: Reads from the card are split into groups of size TransferBlockSize
// This is controlled by a registry entry for the driver.
///////////////////////////////////////////////////////////////////////////////
DWORD SDMemRead(PSD_MEMCARD_INFO pMemCard, PSG_REQ pSG)
{
DWORD NumBlocks;
DWORD StartBlock;
PUCHAR pBlockBuffer = NULL, pCardDataPtr = NULL;
PUCHAR pSGBuffer = NULL;
DWORD status = ERROR_SUCCESS;
DWORD SGBufNum, SGBufLen, SGBufRemaining;
DWORD PartialStartBlock;
DWORD CardDataRemaining;
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +SDMemRead\r\n")));
PREFAST_DEBUGCHK(pSG);
// pSG is a sterile SG_REQ copy of the callers's SG_REQ; we can map the
// embedded pointers back into it
// validate the embedded sb_bufs
for (ULONG ul = 0; ul < pSG->sr_num_sg; ul += 1) {
if (
(NULL == pSG->sr_sglist[ul].sb_buf) ||
(0 == pSG->sr_sglist[ul].sb_buf)
) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
pSG->sr_sglist[ul].sb_buf = (PUCHAR)MapCallerPtr(
(LPVOID)pSG->sr_sglist[ul].sb_buf,
pSG->sr_sglist[ul].sb_len);
if (pSG->sr_sglist[ul].sb_buf == NULL) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
}
// validate the I/O request
if ((pSG->sr_start > pSG->sr_start + pSG->sr_num_sec)
||(pSG->sr_start + pSG->sr_num_sec) > pMemCard->DiskInfo.di_total_sectors) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
// get number of sectors
StartBlock = pSG->sr_start;
NumBlocks = pSG->sr_num_sec;
DEBUGMSG(SDMEM_ZONE_DISK_IO, (TEXT("SDMemRead: Reading blocks %d-%d\r\n"),
StartBlock,
StartBlock+NumBlocks-1));
SGBufLen = 0;
// calculate total buffer space of scatter gather buffers
for (SGBufNum = 0; SGBufNum < pSG->sr_num_sg; SGBufNum++) {
SGBufLen += pSG->sr_sglist[SGBufNum].sb_len;
}
// check total SG buffer space is enough for reqeusted transfer size
if (SGBufLen < (NumBlocks * SD_BLOCK_SIZE)) {
DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemRead: SG Buffer space %d bytes less than block read size %d bytes\r\n"),
SGBufLen,
NumBlocks*SD_BLOCK_SIZE));
status = ERROR_GEN_FAILURE;
goto statusReturn;
}
// get block transfer buffer
pBlockBuffer = (PUCHAR)SDAllocateFromMemList(pMemCard->hBufferList);
// initialize some variables used in data copy
SGBufNum = 0;
SGBufRemaining = pSG->sr_sglist[SGBufNum].sb_len;
pSGBuffer = pSG->sr_sglist[SGBufNum].sb_buf;
// split the reads into groups of TransferBlockSize in size to avoid
// hogging the SD Bus with large reads
for (PartialStartBlock = StartBlock; PartialStartBlock < StartBlock+NumBlocks; PartialStartBlock += pMemCard->BlockTransferSize) {
// some variables just used for copying
DWORD PartialTransferSize;
DWORD CopySize;
pCardDataPtr = pBlockBuffer;
PartialTransferSize = MIN(
pMemCard->BlockTransferSize,
StartBlock+NumBlocks-PartialStartBlock);
// read the data from SD Card
status = SDMemReadMultiple(
pMemCard,
PartialStartBlock,
PartialTransferSize,
pBlockBuffer);
if (status != ERROR_SUCCESS) {
break;
}
// copy from pBlockArray to pSG buffers
CardDataRemaining = PartialTransferSize*SD_BLOCK_SIZE;
while (CardDataRemaining) {
// get minimum of remaining size in SG buf and data left in pBlockBuffer
CopySize = MIN(SGBufRemaining, CardDataRemaining);
// copy that much data to SG buffer
if (0 == CeSafeCopyMemory(pSGBuffer, pCardDataPtr, CopySize)) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
// update pointers and counts
pSGBuffer += CopySize;
pCardDataPtr += CopySize;
CardDataRemaining -= CopySize;
SGBufRemaining -= CopySize;
// fet the next SG Buffer if needed
if (!SGBufRemaining && CardDataRemaining) {
SGBufNum++;
SGBufRemaining = pSG->sr_sglist[SGBufNum].sb_len;
pSGBuffer = pSG->sr_sglist[SGBufNum].sb_buf;
}
}
}
statusReturn:
// free the allocated block buffer
if(pBlockBuffer) {
SDFreeToMemList(pMemCard->hBufferList, pBlockBuffer);
}
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: -SDMemRead\r\n")));
// FATFS wants the status returned in the SG buffers also
pSG->sr_status = status;
return status;
}
///////////////////////////////////////////////////////////////////////////////
// SDMemWrite - Write data to card from pSG scatter gather buffers
// Input: pMemCard - SD memory card structure
// pSG - Scatter Gather buffer structure from FATFS
// Output:
// Return: Status - windows status code
// Notes: Writes to the card are split into groups of size TransferBlockSize
// This is controlled by a registry entry for the driver.
///////////////////////////////////////////////////////////////////////////////
DWORD SDMemWrite( PSD_MEMCARD_INFO pMemCard, PSG_REQ pSG )
{
DWORD NumBlocks;
DWORD StartBlock;
PUCHAR pBlockBuffer = NULL, pCardDataPtr = NULL;
PUCHAR pSGBuffer = NULL;
DWORD status = ERROR_SUCCESS;
DWORD SGBufNum, SGBufLen, SGBufRemaining;
DWORD PartialStartBlock;
DWORD CardDataRemaining;
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +SDMemWrite\r\n")));
PREFAST_DEBUGCHK(pSG);
// pSG is a sterile SG_REQ copy of the callers's SG_REQ; we can map the
// embedded pointers back into it
// validate the embedded sb_bufs
for (ULONG ul = 0; ul < pSG->sr_num_sg; ul += 1) {
if (
(NULL == pSG->sr_sglist[ul].sb_buf) ||
(0 == pSG->sr_sglist[ul].sb_buf)
) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
pSG->sr_sglist[ul].sb_buf = (PUCHAR)MapCallerPtr(
(LPVOID)pSG->sr_sglist[ul].sb_buf,
pSG->sr_sglist[ul].sb_len);
if (pSG->sr_sglist[ul].sb_buf == NULL) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
}
// validate the I/O request
if ((pSG->sr_start > pSG->sr_start + pSG->sr_num_sec)
||(pSG->sr_start + pSG->sr_num_sec) > pMemCard->DiskInfo.di_total_sectors) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
// check card write protect status
if (pMemCard->WriteProtected) {
DEBUGMSG(SDMEM_ZONE_DISK_IO, (TEXT("SDMemWrite: Card is write protected\r\n")));
status = ERROR_WRITE_PROTECT;
goto statusReturn;
}
// get number of sectors
StartBlock = pSG->sr_start;
NumBlocks = pSG->sr_num_sec;
DEBUGMSG(SDMEM_ZONE_DISK_IO, (TEXT("SDMemWrite: Writing blocks %d-%d\r\n"),
StartBlock,
StartBlock+NumBlocks-1));
// calculate total buffer space of scatter gather buffers
SGBufLen = 0;
for (SGBufNum = 0; SGBufNum < pSG->sr_num_sg; SGBufNum++) {
SGBufLen += pSG->sr_sglist[SGBufNum].sb_len;
}
// check total SG buffer space is enough for reqeusted transfer size
if(SGBufLen < NumBlocks * SD_BLOCK_SIZE) {
DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemWrite: SG Buffer space %d bytes less than block write size %d bytes\r\n"),
SGBufLen,
NumBlocks * SD_BLOCK_SIZE));
status = ERROR_GEN_FAILURE;
goto statusReturn;
}
// get block transfer buffer
pBlockBuffer = (PUCHAR)SDAllocateFromMemList(pMemCard->hBufferList);
// initialize some variables used in data copy
SGBufNum = 0;
SGBufRemaining = pSG->sr_sglist[SGBufNum].sb_len;
pSGBuffer = pSG->sr_sglist[SGBufNum].sb_buf;
// split the writes into groups of TransferBlockSize in size to avoid
// hogging the SD Bus with large writes
for(PartialStartBlock = StartBlock; PartialStartBlock < StartBlock+NumBlocks; PartialStartBlock += pMemCard->BlockTransferSize) {
// some variables just used for copying
DWORD PartialTransferSize;
DWORD CopySize;
pCardDataPtr = pBlockBuffer;
PartialTransferSize = MIN(
pMemCard->BlockTransferSize,
StartBlock+NumBlocks-PartialStartBlock);
// copy from pSG buffers to pBlockArray
CardDataRemaining = PartialTransferSize*SD_BLOCK_SIZE;
while (CardDataRemaining) {
// get minimum of remaining size in SG buf and data left in pBlockBuffer
CopySize = MIN(SGBufRemaining, CardDataRemaining);
// copy that much data to block buffer
if (0 == CeSafeCopyMemory(pCardDataPtr, pSGBuffer, CopySize)) {
status = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
// update pointers and counts
pSGBuffer += CopySize;
pCardDataPtr += CopySize;
CardDataRemaining -= CopySize;
SGBufRemaining -= CopySize;
// get the next SG Buffer if needed
if (!SGBufRemaining && CardDataRemaining) {
SGBufNum++;
SGBufRemaining = pSG->sr_sglist[SGBufNum].sb_len;
pSGBuffer = pSG->sr_sglist[SGBufNum].sb_buf;
}
}
// write the data to the SD Card
status = SDMemWriteMultiple(
pMemCard,
PartialStartBlock,
PartialTransferSize,
pBlockBuffer);
if (status != ERROR_SUCCESS) {
break;
}
}
statusReturn:
// free the allocated block buffer
if (pBlockBuffer) {
SDFreeToMemList(pMemCard->hBufferList, pBlockBuffer);
}
// FATFS wants the status returned in the SG buffers also
pSG->sr_status = status;
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: -SDMemWrite\r\n")));
return status;
}
///////////////////////////////////////////////////////////////////////////////
// SDMemErase - Erase a contiguous set of blocks
// Input: pMemCard - SD memory card structure
// pDSI - structure describing the range of sectors to erase
// Output:
// Return: Status - windows status code
// Notes:
///////////////////////////////////////////////////////////////////////////////
DWORD SDMemErase( PSD_MEMCARD_INFO pMemCard, PDELETE_SECTOR_INFO pDSI )
{
DWORD dwStatus = ERROR_SUCCESS;
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +SDMemErase\n")));
PREFAST_DEBUGCHK(pMemCard);
PREFAST_DEBUGCHK(pDSI);
// Validate Gather request
if ((pDSI->startsector + pDSI->numsectors) > pMemCard->DiskInfo.di_total_sectors) {
dwStatus = ERROR_INVALID_PARAMETER;
goto statusReturn;
}
/*
dwStatus = SDMemDoErase(
pMemCard,
(LONG) pDSI->startsector,
(LONG) pDSI->numsectors
);
*/
statusReturn:
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: -SDMemErase\n")));
return dwStatus;
}
#if 0
///////////////////////////////////////////////////////////////////////////////
// SDMemEraseAll - Erase all blocks
// Input: pMemCard - SD memory card structure
// Output:
// Return: Status - windows status code
// Notes:
///////////////////////////////////////////////////////////////////////////////
DWORD SDMemEraseAll( PSD_MEMCARD_INFO pMemCard )
{
DWORD dwStatus = ERROR_SUCCESS;
DELETE_SECTOR_INFO DSI;
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +SDMemEraseAll\n")));
PREFAST_DEBUGCHK(pMemCard);
DSI.cbSize = sizeof(DSI);
DSI.startsector = 0;
DSI.numsectors = pMemCard->DiskInfo.di_total_sectors;
dwStatus = SDMemErase(pMemCard, &DSI);
DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: -SDMemEraseAll\n")));
return dwStatus;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// RequestPrologue - pre-tasks before handling the ioctl
// Input: pMemCard - memory card instance
// DeviceIoControl - device iocontrol to filter
// Output:
// Return: SD_API_STATUS code
// Notes:
// This function should be called from the Ioctl dispatch function
///////////////////////////////////////////////////////////////////////////////
SD_API_STATUS RequestPrologue(PSD_MEMCARD_INFO pMemCard, DWORD DeviceIoControl)
{
SD_API_STATUS status = SD_API_STATUS_SUCCESS; // intermediate status
if (pMemCard->CardEjected) {
return SD_API_STATUS_DEVICE_REMOVED;
}
// check and see if we need to do power management tasks
if (!pMemCard->EnablePowerManagement) {
return SD_API_STATUS_SUCCESS;
}
// pass power Ioctls through without issuing card re-select
if ((IOCTL_POWER_CAPABILITIES == DeviceIoControl) ||
(IOCTL_POWER_QUERY == DeviceIoControl) ||
(IOCTL_POWER_SET == DeviceIoControl)) {
return SD_API_STATUS_SUCCESS;
}
// for all other ioctls, re-select the card
AcquireLock(pMemCard);
// cancel the idle timer
pMemCard->CancelIdleTimeout= TRUE;
// check to see if the card was deselected due to power
// management
if (pMemCard->CardDeSelected) {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Re-Selecting Card \n")));
status = IssueCardSelectDeSelect(pMemCard, TRUE);
if (SD_API_SUCCESS(status)) {
pMemCard->CardDeSelected = FALSE;
}
}
ReleaseLock(pMemCard);
return status;
}
///////////////////////////////////////////////////////////////////////////////
// RequestEnd - post-tasks before handling the ioctl
// Input: pMemCard - memory card instance
// Output:
// Return:
// Notes:
// this function should be called from the Ioctl dispatch function
///////////////////////////////////////////////////////////////////////////////
void RequestEnd(PSD_MEMCARD_INFO pMemCard)
{
AcquireLock(pMemCard);
// clear the idle timer cancel flag after ioctl request is end
pMemCard->CancelIdleTimeout= FALSE;
ReleaseLock(pMemCard);
}
///////////////////////////////////////////////////////////////////////////////
// IssueCardSelectDeSelect - issue card select
// Input: pMemCard - memory card instance
// Select - select the card
// Output:
// Return: SD_API_STATUS code
// Notes:
///////////////////////////////////////////////////////////////////////////////
SD_API_STATUS IssueCardSelectDeSelect(PSD_MEMCARD_INFO pMemCard, BOOL Select)
{
USHORT relativeAddress; // relative address
SD_RESPONSE_TYPE responseType; // expected response
SD_API_STATUS status; // intermediate status
int retryCount; // retryCount;
SD_CARD_STATUS cardStatus; // card status
if (Select) {
// using the cards original address selects the card again
relativeAddress = pMemCard->RCA;
DEBUG_CHECK((relativeAddress != 0), (TEXT("IssueCardSelectDeSelect - Relative address is zero! \n")));
// the selected card should return a response
responseType = ResponseR1b;
} else {
// address of zero deselects the card
relativeAddress = 0;
// according to the spec no response will be returned
responseType = NoResponse;
}
retryCount = DEFAULT_DESELECT_RETRY_COUNT;
while (retryCount) {
status = SDSynchronousBusRequest(pMemCard->hDevice,
SD_CMD_SELECT_DESELECT_CARD,
((DWORD)relativeAddress) << 16,
SD_COMMAND,
responseType,
NULL,
0,
0,
NULL,
0);
if (!SD_API_SUCCESS(status)) {
break;
}
if (!Select) {
// if we deselected, get the card status and check for
// standby state
status = SDCardInfoQuery(pMemCard->hDevice,
SD_INFO_CARD_STATUS,
&cardStatus,
sizeof(SD_CARD_STATUS));
if (!SD_API_SUCCESS(status)){
break;
}
if (SD_STATUS_CURRENT_STATE(cardStatus) ==
SD_STATUS_CURRENT_STATE_STDBY) {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Card now in Standby \n")));
break;
} else {
DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Card not in standby! Card Status: 0x%08X \n")
, cardStatus));
// set unusuccessful for retry
status = SD_API_STATUS_UNSUCCESSFUL;
}
retryCount--;
} else {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Card now in Transfer state \n")));
break;
}
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
// IdleThread - idle thread
// Input: pMemCard - memory card instance
// Output:
// Return: thread exit code
// Notes:
// This thread is created if power management is enabled.
// Normally the thread lays dormant until signalled to perform
// the idle timeout. When an idle timeout occurs, if the
// timer was not cancelled, the thread deselects the memory card
// to reduce power consumption.
///////////////////////////////////////////////////////////////////////////////
DWORD IdleThread(PSD_MEMCARD_INFO pMemCard)
{
while(1) {
// wait for event
WaitForSingleObject(pMemCard->hWakeUpIdleThread, INFINITE);
if (pMemCard->ShutDownIdleThread) {
return 0;
}
// while low power polling is enabled
while (pMemCard->EnableLowPower) {
// wait with a timeout
WaitForSingleObject(pMemCard->hWakeUpIdleThread, pMemCard->IdleTimeout);
if (pMemCard->EnableLowPower) {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Idle Timeout Wakeup after %d MS \n"),pMemCard->IdleTimeout));
AcquireLock(pMemCard);
// check for cancel
if (!pMemCard->CancelIdleTimeout){
// make sure we haven't already deselected the card
if (!pMemCard->CardDeSelected) {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Idle Timout, De-Selecting Card \n")));
// we haven't been canceled, so issue the card de-select
if (SD_API_SUCCESS(IssueCardSelectDeSelect(pMemCard, FALSE))) {
pMemCard->CardDeSelected = TRUE;
}
}
} else {
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: Idle Timout, Cancelled! \n")));
}
// clear the cancel flag
// SMC_IOControl() will clear pMemCard->CancelIdleTimeout once ioctl request is end
ReleaseLock(pMemCard);
}
}
if (pMemCard->ShutDownIdleThread) {
return 0;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// HandleIoctlPowerSet
// Input: pMemCard - SD memory card structure
// pDevicePowerState - device power state
// Output:
// Return:
// Notes:
///////////////////////////////////////////////////////////////////////////////
VOID HandleIoctlPowerSet(PSD_MEMCARD_INFO pMemCard,
PCEDEVICE_POWER_STATE pDevicePowerState)
{
AcquireLock(pMemCard);
DEBUGMSG(SDMEM_ZONE_POWER, (TEXT("SDMemory: IOCTL_POWER_SET %d \n"),*pDevicePowerState));
if (*pDevicePowerState < pMemCard->PowerStateForIdle) {
// everything above the power state for idle is treated as D0
*pDevicePowerState = D0;
pMemCard->CurrentPowerState = D0;
// disable low power operation
pMemCard->EnableLowPower = FALSE;
} else {
// everything above the IDLE power state is set to IDLE
*pDevicePowerState = pMemCard->PowerStateForIdle;
pMemCard->CurrentPowerState = pMemCard->PowerStateForIdle;
// enable low power operation
pMemCard->EnableLowPower = TRUE;
// wake up the idle thread to go into power idle polling
SetEvent(pMemCard->hWakeUpIdleThread);
}
ReleaseLock(pMemCard);
}
///////////////////////////////////////////////////////////////////////////////
// InitializePowerManagement - initialize power management feature
// Input: pMemCard - SD memory card structure
// Output:
// Return:
// Notes:
///////////////////////////////////////////////////////////////////////////////
VOID InitializePowerManagement(PSD_MEMCARD_INFO pMemCard)
{
DWORD threadID; // idle thread ID
if (!pMemCard->EnablePowerManagement) {
DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Power Management Disabled\n")));
return;
}
pMemCard->EnableLowPower = FALSE;
pMemCard->CurrentPowerState = D0;
pMemCard->ShutDownIdleThread = FALSE;
pMemCard->CancelIdleTimeout = FALSE;
pMemCard->CardDeSelected = FALSE;
// create the wake up event
pMemCard->hWakeUpIdleThread = CreateEvent(NULL, FALSE, FALSE, NULL);
if (NULL == pMemCard->hWakeUpIdleThread) {
pMemCard->EnablePowerManagement = FALSE;
return;
}
// create the thread
pMemCard->hIdleThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)IdleThread,
pMemCard,
0,
&threadID);
if (NULL == pMemCard->hIdleThread) {
pMemCard->EnablePowerManagement = FALSE;
return;
}
DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Power Management Setup complete \n")));
}
///////////////////////////////////////////////////////////////////////////////
// DeinitializePowerManagent - clean up power management feature
// Input: pMemCard - SD memory card structure
// Output:
// Return:
// Notes:
///////////////////////////////////////////////////////////////////////////////
VOID DeinitializePowerManagement(PSD_MEMCARD_INFO pMemCard)
{
pMemCard->ShutDownIdleThread = TRUE;
pMemCard->EnableLowPower = FALSE;
pMemCard->CancelIdleTimeout = TRUE;
if (NULL != pMemCard->hIdleThread) {
SetEvent(pMemCard->hWakeUpIdleThread);
WaitForSingleObject(pMemCard->hIdleThread, INFINITE);
CloseHandle(pMemCard->hIdleThread);
pMemCard->hIdleThread = NULL;
}
if (NULL != pMemCard->hWakeUpIdleThread) {
CloseHandle(pMemCard->hWakeUpIdleThread);
pMemCard->hWakeUpIdleThread = NULL;
}
}
// DO NOT REMOVE --- END EXTERNALLY DEVELOPED SOURCE CODE ID --- DO NOT REMOVE
|
[
"[email protected]"
] |
[
[
[
1,
992
]
]
] |
6fe38b40b7daa84dd50392549ccc3120ce45f227
|
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
|
/Common/Scd/ScdLib/DATATYPE.CPP
|
eb9fde07fdc6a76b801af14ca2331dc08622f932
|
[] |
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 | 87,910 |
cpp
|
//================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "sc_defs.h"
#define __DATATYPE_CPP
#include "datacnvs.h"
#include "datatype.h"
//#include "errorlog.h"
#include "dbgmngr.h"
//#include "optoff.h"
//========================================================================
//
//
//
//========================================================================
#define DoFlags 01
#define DoStrings 01
#define DoCharArrays 01
//========================================================================
//
//
//
//========================================================================
const int ExpOff=6;
const int ExpMax=15;
const int ExpMin=0;
flt16 flt16::operator=(double v)
{
if (_isnan(v))
v = 0.0;
Sgn=(v<0.0);
v=fabs(v);
int e;
double m = frexp(v, &e);
if (e%2!=0)
{
m/=2.0;
e++;
}
e=e/2+ExpOff;
if (e > 15)
{
e=15;
m=1.0;
//iStatus=ds_OverFlow;
}
else if (e < 0)
{
e=0;
m=0.25;
//iStatus=ds_UnderFlow;
}
//else
//iStatus=ds_OK;
Exp=e;
Mant=((word)floor(m*2048.0));
return *this;
};
//------------------------------------------------------------------------
flt16::operator double() const
{
int e=Exp-ExpOff;
double v=(Mant+0.5)/2048.0;
if (e>0)
v*=(1 << 2*e);
else if (e<0)
v/=(1 << 2*abs(e));
if (Sgn)
return -v;
return v;
};
//========================================================================
void flt16::Test()
{
flt16 f;//DataUnionCom DU;
int kk;
/*
double x[]= {1.0, 1.1111111, 2.0, 2.222222, 3.0, 3.3333333, 4, 4.44444, 5, 5.555555, 6, 6.6666666, 7, 7.777777, 8, 8.88888888, 9, 9.9999999};
for (double ii=-7; ii<6; ii++)
for (int jj=0; jj<sizeof(x)/sizeof(x[0]); jj++)
for (int kk=0; kk<2; kk++)
{
double X=x[jj]* (ii==-7 ? 0.0 : pow(10.0, ii)) * (kk==0 ? 1.0 : -1.0);
DU.SetFlt16(X);
dbgp("%14g > %14g ", X, DU.GetFlt16());
switch (DU.Status())
{
case ds_OK : dbgp(" %8.4f", 100.0*(DU.GetFlt16()-X)/NZ(X)); break;
case ds_OverFlow : dbgp(" Hi"); break;
case ds_UnderFlow: dbgp(" Lo "); break;
case ds_NAN : dbgp(" NAN "); break;
}
dbgpln("");
}
for (int kk=0; kk<2000; kk++)
{
double X=0.9+(0.1*kk/1000);
DU.SetFlt16(X);
dbgp("%14g > %14g ", X, DU.GetFlt16());
switch (DU.Status())
{
case ds_OK : dbgp(" %8.4f", 100.0*(DU.GetFlt16()-X)/NZ(X)); break;
case ds_OverFlow : dbgp(" Hi"); break;
case ds_UnderFlow : dbgp(" Lo "); break;
case ds_NAN : dbgp(" NAN "); break;
}
dbgpln("");
}
*/
double MeanError=0.0;
double MeanAbsError=0.0;
double MaxError=0.0, MaxX=1.0;
const int nn=100000;
for (kk=0; kk<nn; kk++)
{
double X=1.0+(0.1*kk/1000);
// flt16 f;
f=X;
//DU.Set(f);
double e=(double(f)-X)/X;
MeanError+=e;
MeanAbsError+=fabs(e);
if (e>MaxError)
{
MaxError=e;
MaxX=X;
}
if (fabs(100.0*(double(f)-X)/NZ(X)) > 0.1)
{
dbgp("%14g > %14g ", X, f);
dbgp(" %8.4f", 100.0*(f-X)/NZ(X));
dbgpln(" <<<< ");
}
/*
dbgp("%14g > %14g ", X, DU.GetFlt16());
switch (DU.Status())
{
case ds_OK : dbgp(" %8.4f", 100.0*(DU.GetFlt16()-X)/NZ(X)); break;
case ds_OverFlow : dbgp(" Hi"); break;
case ds_UnderFlow : dbgp(" Lo "); break;
case ds_NAN : dbgp(" NAN "); break;
}
dbgpln("");
*/
}
dbgpln("Mean Error over %i values = %g%%", nn, 100.0*MeanError/nn);
dbgpln("Mean Abs Error over %i values = %g%%", nn, 100.0*MeanAbsError/nn);
f=MaxX;
dbgpln("Max Error @ %14g > %14g %14g%%", MaxX, f, 100.0*(f-MaxX)/NZ(MaxX));
}
//========================================================================
//
//
//
//========================================================================
//===========================================================================
//
//
//
//===========================================================================
DDBValueLst DDBOnOff[] = {{False, "Off", MDD_Default}, {True, "On"}, {0}};
DDBValueLst DDBOnBlank[] = {{False, " " }, {True, "On"}, {0}};
DDBValueLst DDBYesNo[] = {{False, "No" , MDD_Default}, {True, "Yes"}, {0}};
DDBValueLst DDBYesBlank[] = {{False, " " }, {True, "Yes"}, {0}};
DDBValueLst DDBNAN_NotSpecd[] = {{0, "Undefined"}, {1, "0.0 : A Value"}, {0}};
DDBValueLst DDBNAN_Floating[] = {{0, "Floating"}, {1, "0.0 : A Value"}, {0}};
DDBValueLst DDBNAN_Ignore[] = {{0, "Ignore"}, {1, "0.0 : A Value"}, {0}};
DDBValueLst DDBNAN_Off[] = {{0, "Off"}, {1, "0.0 : A Value"}, {0}};
DDBValueLst DDBNAN_AtmosP[] = {{0, "Atmospheric"}, {1, "101.35 : A Value"},{0}};
DDBValueLst DDBNAN_BlkPass[] = {{0, "Block"}, {1, "Pass" },{0}};
int DDBAltArrayAddress=0;
//===========================================================================
DDBValueLstMem & DDBValueLstMem::operator=(const DDBValueLstMem & VL)
{
Str.Clear();
Lst.SetSize(VL.Lst.GetSize());
for (int i=0; i<VL.Lst.GetSize(); i++)
{
Lst[i]=VL.Lst[i];
if (VL.Lst[i].m_pStr)
{
Str.Append(VL.Lst[i].m_pStr);
Lst[i].m_pStr=Str.Last()->Str();
}
}
Len=VL.Len;
return *this;
};
DDBValueLstMem & DDBValueLstMem::operator=(const DDBValueLst & VL)
{
const DDBValueLst *pVL=&VL;
int Len;
for (Len=0; pVL[Len].m_pStr; Len++)
{ };
// Len--;
Str.Clear();
Lst.SetSize(Len+1);
for (int i=0; i<Len; i++)
{
Lst[i]=pVL[i];
if (pVL[i].m_pStr)
{
Str.Append(pVL[i].m_pStr);
Lst[i].m_pStr=Str.Last()->Str();
}
}
return *this;
};
void DDBValueLstMem::LoadFromCSV(Strng &S)
{
Strng Buff(S);
CSVColArray f;
int Quote,nParms;
nParms = ParseCSVTokens(Buff(), f, Quote);
int Index=0;
for (int i=0; i<nParms; i++)
{
if (f[i] && strlen(f[i])>0)
{
char * p=strchr(f[i], '=');
if (p)
{
*p=0;
Index=SafeAtoL(p+1, Index);
Add(Index, f[i]);
}
else
{
Add(Index, f[i]);
}
}
else
Add(Index, "");
Index++;
}
};
void DDBValueLstMem::SaveToCSV(Strng &S, bool QuoteBlanks)
{;
char Buff[2048];
for (int v=0; v<Length(); v++)
{
char * pS=Item(v)->m_pStr;
if (pS==NULL || strlen(pS)<1)
pS="''";
sprintf(Buff, v>0?", %s=%i":"%s=%i", pS, Item(v)->m_lVal);
S+= Buff;
}
};
//===========================================================================
//
//
//
//===========================================================================
word DataUnionCom::Size() const
{
switch (iType)
{
case tt_NULL : return 0+sizeof(byte);
case tt_Char : return sizeof(char)+sizeof(byte);
case tt_Bool :
case tt_Bit :
case tt_Byte : return sizeof(byte)+sizeof(byte);
case tt_Word : return sizeof(word)+sizeof(byte);
case tt_DWord : return sizeof(dword)+sizeof(byte);
case tt_Int : return sizeof(int)+sizeof(byte);
case tt_Short : return sizeof(short)+sizeof(byte);
case tt_Long : return sizeof(long)+sizeof(byte);
case tt_Flt16 : return sizeof(flt16)+sizeof(byte);
case tt_Float : return sizeof(float)+sizeof(byte);
case tt_Double : return sizeof(double)+sizeof(byte);
default : break;
};
VERIFY(0);
return 0;
};
//------------------------------------------------------------------------
word DataUnionCom::TypeSize() const
{
switch (iType)
{
case tt_NULL : return 0;
case tt_Bool :
case tt_Bit :
case tt_Byte : return sizeof(byte);
case tt_Word : return sizeof(word);
case tt_DWord : return sizeof(dword);
case tt_Int : return sizeof(int);
case tt_Char : return sizeof(char);
case tt_Short : return sizeof(short);
case tt_Long : return sizeof(long);
case tt_Flt16 : return sizeof(flt16);
case tt_Float : return sizeof(float);
case tt_Double : return sizeof(double);
};
//VERIFY(0);
return 0;
};
//------------------------------------------------------------------------
flag DataUnionCom::IsNAN() const
{
switch (iType)
{
case tt_Flt16 : return (Status()==ds_NAN);
case tt_Float : return !Valid(Float);
case tt_Double : return !Valid(Double);
default : return 0;
}
return 0;
}
//------------------------------------------------------------------------
void DataUnionCom::Set(DataUnionCom &V)
{
switch (V.iType)
{
case tt_NULL: /* Do Nothing */ break;
case tt_Char: Char =V.Char; break;
case tt_Bool:
case tt_Bit:
case tt_Byte: Byte =V.Byte; break;
case tt_Word: Word =V.Word; break;
case tt_DWord: DWord =V.DWord; break;
case tt_Int: Int =V.Int; break;
case tt_Short: Short =V.Short; break;
case tt_Long: Long =V.Long; break;
case tt_Flt16: Flt16 =V.Flt16; break;
case tt_Float: Float =V.Float; break;
case tt_Double: Double =V.Double; break;
default: VERIFY(0); break;
}
iType=V.iType;
iStatus=V.iStatus;
//lt16Neg=V.bFlt16Neg;
};
//------------------------------------------------------------------------
flag DataUnionCom::IsZero() const
{
switch (iType)
{
case tt_NULL: return true;
case tt_Char: return Char == 0;
case tt_Bool:
case tt_Bit:
case tt_Byte: return Byte == 0;
case tt_Word: return Word == 0;
case tt_DWord: return DWord == 0;
case tt_Int: return Int == 0;
case tt_Short: return Short == 0;
case tt_Long: return Long == 0;
case tt_Flt16: return Flt16 == 0;
case tt_Float: return Valid(Float) ? (Float == 0.0f) : false;
case tt_Double: return Valid(Double) ? (Double == 0.0) : false;
default: return false;
}
};
////------------------------------------------------------------------------
//
//void DataUnionCom::Set(PkDataUnion &V)
// {
// switch (V.iType)
// {
// case tt_Char: Char =V.Char; break;
// case tt_Bool:
// case tt_Bit:
// case tt_Byte: Byte =V.Byte; break;
// case tt_Word: Word =V.Word; break;
// case tt_DWord: DWord =V.DWord; break;
// case tt_Int: Int =V.Int; break;
// case tt_Short: Short =V.Short; break;
// case tt_Long: Long =V.Long; break;
// case tt_Flt16: Flt16 =V.Flt16; break;
// case tt_Float: Float =V.Float; break;
// case tt_Double: Double =V.Double; break;
// default: VERIFY(0); break;
// }
// iType=V.iType;
// iStatus=V.iStatus;
// //lt16Neg=V.bFlt16Neg;
// };
//------------------------------------------------------------------------
flag DataUnionCom::Equal(DataUnionCom &V)
{
if (iType!=V.iType)
return false;
switch (iType)
{
case tt_NULL : return true;
case tt_Char : return Char==V.Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte==V.Byte;
case tt_Word : return Word==V.Word;
case tt_DWord : return DWord==V.DWord;
case tt_Int : return Int==V.Int;
case tt_Short : return Short==V.Short;
case tt_Long : return Long==V.Long;
case tt_Flt16 : return Flt16==V.Flt16;
case tt_Float : return Float==V.Float;
case tt_Double : return Double==V.Double;
default : VERIFY(0); return 0;
}
return false;
}
//------------------------------------------------------------------------
flag DataUnionCom::EqualNANOK(DataUnionCom &V)
{
if (iType!=V.iType)
return false;
switch (iType)
{
case tt_NULL : return true;
case tt_Char : return Char==V.Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte==V.Byte;
case tt_Word : return Word==V.Word;
case tt_DWord : return DWord==V.DWord;
case tt_Int : return Int==V.Int;
case tt_Short : return Short==V.Short;
case tt_Long : return Long==V.Long;
case tt_Flt16 : return Flt16==V.Flt16;
case tt_Float : return Valid(Float)&&Valid(V.Float) ? Float==V.Float : Valid(Float)==Valid(V.Float);
case tt_Double : return Valid(Double)&&Valid(V.Double) ? Double==V.Double : Valid(Double)==Valid(V.Double);
default : VERIFY(0); return 0;
}
return false;
}
//------------------------------------------------------------------------
long DataUnionCom::GetLong() const
{
switch (iType)
{
case tt_NULL : return 0;
case tt_Char : return Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte;
case tt_Word : return Word;
case tt_DWord : return DWord;
case tt_Int : return Int;
case tt_Short : return Short;
case tt_Long : return Long;
//case tt_Flt16 : return (long)(iCnv==0 ? Flt16 : Cnvs[iCnv]->Human(Flt16, pCnvTxt));
case tt_Flt16 : return (long)Flt16;
case tt_Float : return (long)Float;
case tt_Double : return (long)Double;
default : VERIFY(0); return 0;
}
}
//------------------------------------------------------------------------
long DataUnionCom::GetLong(CCnvIndex iCnv, char*pCnvTxt) const
{
switch (iType)
{
case tt_NULL : return 0;
case tt_Char : return Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte;
case tt_Word : return Word;
case tt_DWord : return DWord;
case tt_Int : return Int;
case tt_Short : return Short;
case tt_Long : return Long;
//case tt_Flt16 : return (long)(iCnv==0 ? Flt16 : Cnvs[iCnv]->Human(Flt16, pCnvTxt));
case tt_Flt16 : return (long)Cnvs[iCnv]->Human(Flt16, pCnvTxt);
case tt_Float : return (long)Cnvs[iCnv]->Human(Float, pCnvTxt);
case tt_Double : return (long)Cnvs[iCnv]->Human(Double, pCnvTxt);
default : VERIFY(0); return 0;
}
}
//------------------------------------------------------------------------
void DataUnionCom::PutLong(long L)
{
iStatus=ds_OK;
switch (iType)
{
case tt_NULL : break;
case tt_Char : Char=(char)L; break;
case tt_Bool :
case tt_Bit :
case tt_Byte : Byte=(byte)L; break;
case tt_Word : Word=(word)L; break;
case tt_DWord : DWord=(dword)L; break;
case tt_Int : Int=(int)L; break;
case tt_Short : Short=(short)L; break;
case tt_Long : Long=(long)L; break;
case tt_Flt16 : Flt16=(double)L; break;
case tt_Float : Float=(float)L; break;
case tt_Double : Double=(double)L; break;
default : VERIFY(0); break;
}
};
//------------------------------------------------------------------------
void DataUnionCom::PutLong(long L, CCnvIndex iCnv, char*pCnvTxt)
{
iStatus=ds_OK;
switch (iType)
{
case tt_NULL : break;
case tt_Char : Char=(char)L; break;
case tt_Bool :
case tt_Bit :
case tt_Byte : Byte=(byte)L; break;
case tt_Word : Word=(word)L; break;
case tt_DWord : DWord=(dword)L; break;
case tt_Int : Int=(int)L; break;
case tt_Short : Short=(short)L; break;
case tt_Long : Long=(long)L; break;
case tt_Flt16 : Flt16=Cnvs[iCnv]->Normal(L, pCnvTxt); break;
case tt_Float : Float=(float)Cnvs[iCnv]->Normal(L, pCnvTxt); break;
case tt_Double : Double=Cnvs[iCnv]->Normal(L, pCnvTxt); break;
default : VERIFY(0); break;
}
};
//------------------------------------------------------------------------
double DataUnionCom::GetDouble() const
{
switch (iType)
{
case tt_NULL : return 0;
case tt_Char : return Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte;
case tt_Word : return Word;
case tt_DWord : return DWord;
case tt_Int : return Int;
case tt_Short : return Short;
case tt_Long : return Long;
case tt_Flt16 : return Flt16;
case tt_Float : return Float;
case tt_Double : return Double;
default : VERIFY(0); return dNAN;
}
}
//------------------------------------------------------------------------
double DataUnionCom::GetDouble(CCnvIndex iCnv, char*pCnvTxt) const
{
switch (iType)
{
case tt_NULL : return 0;
case tt_Char : return Char;
case tt_Bool :
case tt_Bit :
case tt_Byte : return Byte;
case tt_Word : return Word;
case tt_DWord : return DWord;
case tt_Int : return Int;
case tt_Short : return Short;
case tt_Long : return Long;
case tt_Flt16 : return Cnvs[iCnv]->Human(Flt16, pCnvTxt);
case tt_Float : return Cnvs[iCnv]->Human(Float, pCnvTxt);
case tt_Double : return Cnvs[iCnv]->Human(Double, pCnvTxt);
default : VERIFY(0); return dNAN;
}
}
//------------------------------------------------------------------------
void DataUnionCom::PutDouble(double D)
{
iStatus=ds_OK;
switch (iType)
{
case tt_NULL : ; break;
case tt_Char : Char=(char)D; break;
case tt_Bool :
case tt_Bit :
case tt_Byte : Byte=(byte)D; break;
case tt_Word : Word=(word)D; break;
case tt_DWord : DWord=(dword)D; break;
case tt_Int : Int=(int)D; break;
case tt_Short : Short=(short)D; break;
case tt_Long : Long=(long)D; break;
case tt_Flt16 : Flt16=D; break;
case tt_Float : Float=(float)D; break;
case tt_Double : Double=D; break;
default : VERIFY(0); break;
}
};
//------------------------------------------------------------------------
void DataUnionCom::PutDouble(double D, CCnvIndex iCnv, char*pCnvTxt)
{
iStatus=ds_OK;
switch (iType)
{
case tt_NULL : ; break;
case tt_Char : Char=(char)D; break;
case tt_Bool :
case tt_Bit :
case tt_Byte : Byte=(byte)D; break;
case tt_Word : Word=(word)D; break;
case tt_DWord : DWord=(dword)D; break;
case tt_Int : Int=(int)D; break;
case tt_Short : Short=(short)D; break;
case tt_Long : Long=(long)D; break;
case tt_Flt16 : Flt16=(iCnv ? Cnvs[iCnv]->Normal(D, pCnvTxt) : D); break;
case tt_Float : Float=(float)(iCnv ? Cnvs[iCnv]->Normal(D, pCnvTxt) : D); break;
case tt_Double : Double=(iCnv ? Cnvs[iCnv]->Normal(D, pCnvTxt) : D); break;
default : VERIFY(0); break;
}
};
//------------------------------------------------------------------------
char GetStringBuffer[2048];
int GetStringBufferPos=0;
char* DataUnionCom::GetString(char*IFmt/*="%i"*/, char*FFmt/*="%g"*/, CCnvIndex iCnv/*=0*/, char*pCnvTxt/*=NULL*/) const
{
char*p = &GetStringBuffer[GetStringBufferPos];
switch (iType)
{
case tt_NULL : sprintf(p, ""); break;
case tt_Char : sprintf(p, IFmt, Char); break;
case tt_Bool :
case tt_Bit :
case tt_Byte : sprintf(p, IFmt, Byte); break;
case tt_Word : sprintf(p, IFmt, Word); break;
case tt_DWord : sprintf(p, IFmt, DWord); break;
case tt_Int : sprintf(p, IFmt, Int); break;
case tt_Short : sprintf(p, IFmt, Short); break;
case tt_Long : sprintf(p, IFmt, Long); break;
case tt_Flt16 : if (Status()!=ds_NAN)
sprintf(p, FFmt, Cnvs[iCnv]->Human(Flt16, pCnvTxt));
else
strcpy(p, "*");
break;
case tt_Float : if (Valid(Float))
sprintf(p, FFmt, Cnvs[iCnv]->Human(Float, pCnvTxt));
else
strcpy(p, "*");
break;
case tt_Double : if (Valid(Double))
sprintf(p, FFmt, Cnvs[iCnv]->Human(Double, pCnvTxt));
else if (HasNANFlag(Double, NF_Free))
strcpy(p, "*Free");
else if (HasNANFlag(Double, NF_Hold))
strcpy(p, "*Hold");
else if (HasNANFlag(Double, NF_Pulse))
strcpy(p, "*Pulse");
else if (HasNANFlag(Double, NF_Ignore))
strcpy(p, "*Ignore");
else if (HasNANFlag(Double, NF_Block))
strcpy(p, "*Block");
else if (HasNANFlag(Double, NF_Plus))
strcpy(p, "*+");
else if (HasNANFlag(Double, NF_Minus))
strcpy(p, "*-");
else if (HasNANFlag(Double, NF_Star))
strcpy(p, "**");
else if (HasNANFlag(Double, NF_Pass))
strcpy(p, "*Pass");
else
strcpy(p, "*");
break;
default :
VERIFY(0);
break;
}
GetStringBufferPos+=strlen(p)+1;
if (GetStringBufferPos>(2048-512))
GetStringBufferPos=0;
return p;
}
//------------------------------------------------------------------------
flag DataUnionCom::SetTypeString(byte iTypeRqd, char*pStrData, CCnvIndex iCnv/*=0*/, char*pCnvTxt/*=NULL*/)
{
iStatus=ds_OK;
switch (iTypeRqd)
{
case tt_NULL : break;
case tt_Char : Char=(char)atol(pStrData); break;
case tt_Bool :
case tt_Bit :
case tt_Byte : Byte=(byte)atol(pStrData); break;
case tt_Word : Word=(word)atol(pStrData); break;
case tt_DWord : DWord=(dword)atol(pStrData); break;
case tt_Int : Int=(int)atol(pStrData); break;
case tt_Short : Short=(short)atol(pStrData); break;
case tt_Long : Long=(long)atol(pStrData); break;
case tt_Flt16 :
while (*pStrData==' ') pStrData++;
if (*pStrData=='*')
SetStatus(ds_NAN);
else
Flt16=Cnvs[iCnv]->Normal(atof(pStrData), pCnvTxt);
break;
case tt_Float :
while (*pStrData==' ') pStrData++;
if (*pStrData=='*')
Float=fNAN;
else
Float=(float)Cnvs[iCnv]->Normal(atof(pStrData), pCnvTxt);
break;
case tt_Double :
while (*pStrData==' ') pStrData++;
if (*pStrData=='*')
Double =ParseNANFlag(pStrData);
else
Double=Cnvs[iCnv]->Normal(atof(pStrData), pCnvTxt);
break;
default : VERIFY(0); break;
}
iType=iTypeRqd;
return True;
}
//========================================================================
//
//
//
//========================================================================
void DataUnion::CopyTo(void* p)
{
switch (iType)
{
case tt_NULL : break;
case tt_Bool :
case tt_Bit :
case tt_Byte : *((byte*)p) = Byte; break;
case tt_Word : *((word*)p) = Word; break;
case tt_DWord : *((dword*)p) = DWord; break;
case tt_Int : *((int*)p) = Int; break;
case tt_Char : *((char*)p) = Char; break;
case tt_Short : *((short*)p) = Short; break;
case tt_Long : *((long*)p) = Long; break;
case tt_Flt16 : *((flt16*)p) = Flt16; break;
case tt_Float : *((float*)p) = Float; break;
case tt_Double : *((double*)p) = Double; break;
case tt_pChar :
case tt_Strng : strcpy((char*)p, pChar); break;
default : ASSERT(0);
}
};
//========================================================================
//
//
//
//========================================================================
#pragma pack(push, 1)
class CPkDataItem8 : public CPkDataItem { char m_BuffExt[8 ]; public:CPkDataItem8 () { m_wMaxSize=8 ;}; virtual ~CPkDataItem8 () {}; DEFINE_SPARES(CPkDataBuff8 ); };
class CPkDataItem16 : public CPkDataItem { char m_BuffExt[16 ]; public:CPkDataItem16 () { m_wMaxSize=16 ;}; virtual ~CPkDataItem16 () {}; DEFINE_SPARES(CPkDataBuff16 ); };
class CPkDataItem24 : public CPkDataItem { char m_BuffExt[24 ]; public:CPkDataItem24 () { m_wMaxSize=24 ;}; virtual ~CPkDataItem24 () {}; DEFINE_SPARES(CPkDataBuff24 ); };
class CPkDataItem32 : public CPkDataItem { char m_BuffExt[32 ]; public:CPkDataItem32 () { m_wMaxSize=32 ;}; virtual ~CPkDataItem32 () {}; DEFINE_SPARES(CPkDataBuff32 ); };
class CPkDataItem40 : public CPkDataItem { char m_BuffExt[40 ]; public:CPkDataItem40 () { m_wMaxSize=40 ;}; virtual ~CPkDataItem40 () {}; DEFINE_SPARES(CPkDataBuff40 ); };
class CPkDataItem48 : public CPkDataItem { char m_BuffExt[48 ]; public:CPkDataItem48 () { m_wMaxSize=48 ;}; virtual ~CPkDataItem48 () {}; DEFINE_SPARES(CPkDataBuff48 ); };
class CPkDataItem56 : public CPkDataItem { char m_BuffExt[56 ]; public:CPkDataItem56 () { m_wMaxSize=56 ;}; virtual ~CPkDataItem56 () {}; DEFINE_SPARES(CPkDataBuff56 ); };
class CPkDataItem64 : public CPkDataItem { char m_BuffExt[64 ]; public:CPkDataItem64 () { m_wMaxSize=64 ;}; virtual ~CPkDataItem64 () {}; DEFINE_SPARES(CPkDataBuff64 ); };
class CPkDataItem96 : public CPkDataItem { char m_BuffExt[96 ]; public:CPkDataItem96 () { m_wMaxSize=96 ;}; virtual ~CPkDataItem96 () {}; DEFINE_SPARES(CPkDataBuff96 ); };
class CPkDataItem128 : public CPkDataItem { char m_BuffExt[128 ]; public:CPkDataItem128 () { m_wMaxSize=128 ;}; virtual ~CPkDataItem128 () {}; DEFINE_SPARES(CPkDataBuff128 ); };
class CPkDataItem160 : public CPkDataItem { char m_BuffExt[160 ]; public:CPkDataItem160 () { m_wMaxSize=160 ;}; virtual ~CPkDataItem160 () {}; DEFINE_SPARES(CPkDataBuff160 ); };
class CPkDataItem192 : public CPkDataItem { char m_BuffExt[192 ]; public:CPkDataItem192 () { m_wMaxSize=192 ;}; virtual ~CPkDataItem192 () {}; DEFINE_SPARES(CPkDataBuff192 ); };
class CPkDataItem224 : public CPkDataItem { char m_BuffExt[224 ]; public:CPkDataItem224 () { m_wMaxSize=224 ;}; virtual ~CPkDataItem224 () {}; DEFINE_SPARES(CPkDataBuff224 ); };
class CPkDataItem256 : public CPkDataItem { char m_BuffExt[256 ]; public:CPkDataItem256 () { m_wMaxSize=256 ;}; virtual ~CPkDataItem256 () {}; DEFINE_SPARES(CPkDataBuff256 ); };
class CPkDataItem384 : public CPkDataItem { char m_BuffExt[384 ]; public:CPkDataItem384 () { m_wMaxSize=384 ;}; virtual ~CPkDataItem384 () {}; DEFINE_SPARES(CPkDataBuff384 ); };
class CPkDataItem512 : public CPkDataItem { char m_BuffExt[512 ]; public:CPkDataItem512 () { m_wMaxSize=512 ;}; virtual ~CPkDataItem512 () {}; DEFINE_SPARES(CPkDataBuff512 ); };
class CPkDataItem640 : public CPkDataItem { char m_BuffExt[640 ]; public:CPkDataItem640 () { m_wMaxSize=640 ;}; virtual ~CPkDataItem640 () {}; DEFINE_SPARES(CPkDataBuff640 ); };
class CPkDataItem768 : public CPkDataItem { char m_BuffExt[768 ]; public:CPkDataItem768 () { m_wMaxSize=768 ;}; virtual ~CPkDataItem768 () {}; DEFINE_SPARES(CPkDataBuff768 ); };
class CPkDataItem896 : public CPkDataItem { char m_BuffExt[896 ]; public:CPkDataItem896 () { m_wMaxSize=896 ;}; virtual ~CPkDataItem896 () {}; DEFINE_SPARES(CPkDataBuff896 ); };
class CPkDataItem1024 : public CPkDataItem { char m_BuffExt[1024]; public:CPkDataItem1024() { m_wMaxSize=1024;}; virtual ~CPkDataItem1024() {}; DEFINE_SPARES(CPkDataBuff1024 ); };
class CPkDataItem1152 : public CPkDataItem { char m_BuffExt[1152]; public:CPkDataItem1152() { m_wMaxSize=1152;}; virtual ~CPkDataItem1152() {}; DEFINE_SPARES(CPkDataBuff1152 ); };
class CPkDataItem1280 : public CPkDataItem { char m_BuffExt[1280]; public:CPkDataItem1280() { m_wMaxSize=1280;}; virtual ~CPkDataItem1280() {}; DEFINE_SPARES(CPkDataBuff1280 ); };
class CPkDataItem1408 : public CPkDataItem { char m_BuffExt[1408]; public:CPkDataItem1408() { m_wMaxSize=1408;}; virtual ~CPkDataItem1408() {}; DEFINE_SPARES(CPkDataBuff1408 ); };
class CPkDataItem1536 : public CPkDataItem { char m_BuffExt[1536]; public:CPkDataItem1536() { m_wMaxSize=1536;}; virtual ~CPkDataItem1536() {}; DEFINE_SPARES(CPkDataBuff1536 ); };
class CPkDataItem1664 : public CPkDataItem { char m_BuffExt[1664]; public:CPkDataItem1664() { m_wMaxSize=1664;}; virtual ~CPkDataItem1664() {}; DEFINE_SPARES(CPkDataBuff1664 ); };
class CPkDataItem1792 : public CPkDataItem { char m_BuffExt[1792]; public:CPkDataItem1792() { m_wMaxSize=1792;}; virtual ~CPkDataItem1792() {}; DEFINE_SPARES(CPkDataBuff1792 ); };
class CPkDataItem1920 : public CPkDataItem { char m_BuffExt[1920]; public:CPkDataItem1920() { m_wMaxSize=1920;}; virtual ~CPkDataItem1920() {}; DEFINE_SPARES(CPkDataBuff1920 ); };
class CPkDataItem2048 : public CPkDataItem { char m_BuffExt[2048]; public:CPkDataItem2048() { m_wMaxSize=2048;}; virtual ~CPkDataItem2048() {}; DEFINE_SPARES(CPkDataBuff2048 ); };
class CPkDataItem2176 : public CPkDataItem { char m_BuffExt[2176]; public:CPkDataItem2176() { m_wMaxSize=2176;}; virtual ~CPkDataItem2176() {}; DEFINE_SPARES(CPkDataBuff2176 ); };
class CPkDataItem2304 : public CPkDataItem { char m_BuffExt[2304]; public:CPkDataItem2304() { m_wMaxSize=2304;}; virtual ~CPkDataItem2304() {}; DEFINE_SPARES(CPkDataBuff2304 ); };
class CPkDataItem2432 : public CPkDataItem { char m_BuffExt[2432]; public:CPkDataItem2432() { m_wMaxSize=2432;}; virtual ~CPkDataItem2432() {}; DEFINE_SPARES(CPkDataBuff2432 ); };
class CPkDataItem2560 : public CPkDataItem { char m_BuffExt[2560]; public:CPkDataItem2560() { m_wMaxSize=2560;}; virtual ~CPkDataItem2560() {}; DEFINE_SPARES(CPkDataBuff2560 ); };
class CPkDataItem2688 : public CPkDataItem { char m_BuffExt[2688]; public:CPkDataItem2688() { m_wMaxSize=2688;}; virtual ~CPkDataItem2688() {}; DEFINE_SPARES(CPkDataBuff2688 ); };
class CPkDataItem2816 : public CPkDataItem { char m_BuffExt[2816]; public:CPkDataItem2816() { m_wMaxSize=2816;}; virtual ~CPkDataItem2816() {}; DEFINE_SPARES(CPkDataBuff2816 ); };
class CPkDataItem2944 : public CPkDataItem { char m_BuffExt[2944]; public:CPkDataItem2944() { m_wMaxSize=2944;}; virtual ~CPkDataItem2944() {}; DEFINE_SPARES(CPkDataBuff2944 ); };
class CPkDataItem3072 : public CPkDataItem { char m_BuffExt[3072]; public:CPkDataItem3072() { m_wMaxSize=3072;}; virtual ~CPkDataItem3072() {}; DEFINE_SPARES(CPkDataBuff3072 ); };
class CPkDataItem3200 : public CPkDataItem { char m_BuffExt[3200]; public:CPkDataItem3200() { m_wMaxSize=3200;}; virtual ~CPkDataItem3200() {}; DEFINE_SPARES(CPkDataBuff3200 ); };
class CPkDataItem3328 : public CPkDataItem { char m_BuffExt[3328]; public:CPkDataItem3328() { m_wMaxSize=3328;}; virtual ~CPkDataItem3328() {}; DEFINE_SPARES(CPkDataBuff3328 ); };
class CPkDataItem3456 : public CPkDataItem { char m_BuffExt[3456]; public:CPkDataItem3456() { m_wMaxSize=3456;}; virtual ~CPkDataItem3456() {}; DEFINE_SPARES(CPkDataBuff3456 ); };
class CPkDataItem3584 : public CPkDataItem { char m_BuffExt[3584]; public:CPkDataItem3584() { m_wMaxSize=3584;}; virtual ~CPkDataItem3584() {}; DEFINE_SPARES(CPkDataBuff3584 ); };
class CPkDataItem3712 : public CPkDataItem { char m_BuffExt[3712]; public:CPkDataItem3712() { m_wMaxSize=3712;}; virtual ~CPkDataItem3712() {}; DEFINE_SPARES(CPkDataBuff3712 ); };
class CPkDataItem3840 : public CPkDataItem { char m_BuffExt[3840]; public:CPkDataItem3840() { m_wMaxSize=3840;}; virtual ~CPkDataItem3840() {}; DEFINE_SPARES(CPkDataBuff3840 ); };
class CPkDataItem3968 : public CPkDataItem { char m_BuffExt[3968]; public:CPkDataItem3968() { m_wMaxSize=3968;}; virtual ~CPkDataItem3968() {}; DEFINE_SPARES(CPkDataBuff3968 ); };
class CPkDataItem4096 : public CPkDataItem { char m_BuffExt[4096]; public:CPkDataItem4096() { m_wMaxSize=4096;}; virtual ~CPkDataItem4096() {}; DEFINE_SPARES(CPkDataBuff4096 ); };
class CPkDataItem4224 : public CPkDataItem { char m_BuffExt[4224]; public:CPkDataItem4224() { m_wMaxSize=4224;}; virtual ~CPkDataItem4224() {}; DEFINE_SPARES(CPkDataBuff4224 ); };
const long BiggestBuffer=4224;
//------------------------------------------------------------------------
IMPLEMENT_SPARES(CPkDataItem8 ,10000);
IMPLEMENT_SPARES(CPkDataItem16 ,10000);
IMPLEMENT_SPARES(CPkDataItem24 ,1000);
IMPLEMENT_SPARES(CPkDataItem32 ,1000);
IMPLEMENT_SPARES(CPkDataItem40 ,1000);
IMPLEMENT_SPARES(CPkDataItem48 ,1000);
IMPLEMENT_SPARES(CPkDataItem56 ,1000);
IMPLEMENT_SPARES(CPkDataItem64 ,500);
IMPLEMENT_SPARES(CPkDataItem96 ,500);
IMPLEMENT_SPARES(CPkDataItem128 ,500);
IMPLEMENT_SPARES(CPkDataItem160 ,100);
IMPLEMENT_SPARES(CPkDataItem192 ,100);
IMPLEMENT_SPARES(CPkDataItem224 ,100);
IMPLEMENT_SPARES(CPkDataItem256 ,100);
IMPLEMENT_SPARES(CPkDataItem384 ,100);
IMPLEMENT_SPARES(CPkDataItem512 ,100);
IMPLEMENT_SPARES(CPkDataItem640 ,100);
IMPLEMENT_SPARES(CPkDataItem768 ,100);
IMPLEMENT_SPARES(CPkDataItem896 ,100);
IMPLEMENT_SPARES(CPkDataItem1024 ,10);
IMPLEMENT_SPARES(CPkDataItem1152 ,10);
IMPLEMENT_SPARES(CPkDataItem1280 ,10);
IMPLEMENT_SPARES(CPkDataItem1408 ,10);
IMPLEMENT_SPARES(CPkDataItem1536 ,10);
IMPLEMENT_SPARES(CPkDataItem1664 ,10);
IMPLEMENT_SPARES(CPkDataItem1792 ,10);
IMPLEMENT_SPARES(CPkDataItem1920 ,10);
IMPLEMENT_SPARES(CPkDataItem2048 ,10);
IMPLEMENT_SPARES(CPkDataItem2176 ,10);
IMPLEMENT_SPARES(CPkDataItem2304 ,10);
IMPLEMENT_SPARES(CPkDataItem2432 ,10);
IMPLEMENT_SPARES(CPkDataItem2560 ,10);
IMPLEMENT_SPARES(CPkDataItem2688 ,10);
IMPLEMENT_SPARES(CPkDataItem2816 ,10);
IMPLEMENT_SPARES(CPkDataItem2944 ,10);
IMPLEMENT_SPARES(CPkDataItem3072 ,10);
IMPLEMENT_SPARES(CPkDataItem3200 ,10);
IMPLEMENT_SPARES(CPkDataItem3328 ,10);
IMPLEMENT_SPARES(CPkDataItem3456 ,10);
IMPLEMENT_SPARES(CPkDataItem3584 ,10);
IMPLEMENT_SPARES(CPkDataItem3712 ,10);
IMPLEMENT_SPARES(CPkDataItem3840 ,10);
IMPLEMENT_SPARES(CPkDataItem3968 ,10);
IMPLEMENT_SPARES(CPkDataItem4096 ,10);
IMPLEMENT_SPARES(CPkDataItem4224 ,10);
#pragma pack(pop)
//========================================================================
//
//
//
//========================================================================
CPkDataItem::CPkDataItem()
{
//m_pData=NULL;
Clear();//NULL);
};
//------------------------------------------------------------------------
//
CPkDataItem * CPkDataItem::Create(long Sz)
{
CPkDataItem *p=NULL;
Sz=Sz-1;
Sz=Max(0L, Sz);
switch (Sz/8)
{
case 0: p = new CPkDataItem8; break;
case 1: p = new CPkDataItem16; break;
case 2: p = new CPkDataItem24; break;
case 3: p = new CPkDataItem32; break;
case 4: p = new CPkDataItem40; break;
case 5: p = new CPkDataItem48; break;
case 6: p = new CPkDataItem56; break;
case 7: p = new CPkDataItem64; break;
default:
switch (Sz/32)
{
case 0: p = new CPkDataItem32; break; // wont happen
case 1: p = new CPkDataItem64; break; // wont happen
case 2: p = new CPkDataItem96; break;
case 3: p = new CPkDataItem128; break;
case 4: p = new CPkDataItem160; break;
case 5: p = new CPkDataItem192; break;
case 6: p = new CPkDataItem224; break;
case 7: p = new CPkDataItem256; break;
default:
switch (Sz/128)
{
case 0 : p = new CPkDataItem128; break; // wont happen
case 1 : p = new CPkDataItem256; break; // wont happen
case 2 : p = new CPkDataItem384; break;
case 3 : p = new CPkDataItem512; break;
case 4 : p = new CPkDataItem640; break;
case 5 : p = new CPkDataItem768; break;
case 6 : p = new CPkDataItem896; break;
case 7 : p = new CPkDataItem1024; break;
case 8 : p = new CPkDataItem1152; break;
case 9 : p = new CPkDataItem1280; break;
case 10: p = new CPkDataItem1408; break;
case 11: p = new CPkDataItem1536; break;
case 12: p = new CPkDataItem1664; break;
case 13: p = new CPkDataItem1792; break;
case 14: p = new CPkDataItem1920; break;
case 15: p = new CPkDataItem2048; break;
case 16: p = new CPkDataItem2176; break;
case 17: p = new CPkDataItem2304; break;
case 18: p = new CPkDataItem2432; break;
case 19: p = new CPkDataItem2560; break;
case 20: p = new CPkDataItem2688; break;
case 21: p = new CPkDataItem2816; break;
case 22: p = new CPkDataItem2944; break;
case 23: p = new CPkDataItem3072; break;
case 24: p = new CPkDataItem3200; break;
case 25: p = new CPkDataItem3328; break;
case 26: p = new CPkDataItem3456; break;
case 27: p = new CPkDataItem3584; break;
case 28: p = new CPkDataItem3712; break;
case 29: p = new CPkDataItem3840; break;
case 30: p = new CPkDataItem3968; break;
case 31: p = new CPkDataItem4096; break;
case 32: p = new CPkDataItem4224; break;
default:
ASSERT_ALWAYS(FALSE, "CPkDataItem Buffer overflow", __FILE__, __LINE__);
}
}
}
ASSERT(p->MaxDataSize()>=Sz);
p->Clear();
return p;
};
//------------------------------------------------------------------------
//
CPkDataItem * CPkDataItem::Create(const CPkDataItem &C)
{
CPkDataItem *p=NULL;
long Sz=C.DataSize()-1;
Sz=Max(0L, Sz);
switch (Sz/8)
{
case 0: p = new CPkDataItem8; break;
case 1: p = new CPkDataItem16; break;
case 2: p = new CPkDataItem24; break;
case 3: p = new CPkDataItem32; break;
case 4: p = new CPkDataItem40; break;
case 5: p = new CPkDataItem48; break;
case 6: p = new CPkDataItem56; break;
case 7: p = new CPkDataItem64; break;
default:
switch (Sz/32)
{
case 0: p = new CPkDataItem32; break; // wont happen
case 1: p = new CPkDataItem64; break; // wont happen
case 2: p = new CPkDataItem96; break;
case 3: p = new CPkDataItem128; break;
case 4: p = new CPkDataItem160; break;
case 5: p = new CPkDataItem192; break;
case 6: p = new CPkDataItem224; break;
case 7: p = new CPkDataItem256; break;
default:
switch (Sz/128)
{
case 0 : p = new CPkDataItem128; break; // wont happen
case 1 : p = new CPkDataItem256; break; // wont happen
case 2 : p = new CPkDataItem384; break;
case 3 : p = new CPkDataItem512; break;
case 4 : p = new CPkDataItem640; break;
case 5 : p = new CPkDataItem768; break;
case 6 : p = new CPkDataItem896; break;
case 7 : p = new CPkDataItem1024; break;
case 8 : p = new CPkDataItem1152; break;
case 9 : p = new CPkDataItem1280; break;
case 10: p = new CPkDataItem1408; break;
case 11: p = new CPkDataItem1536; break;
case 12: p = new CPkDataItem1664; break;
case 13: p = new CPkDataItem1792; break;
case 14: p = new CPkDataItem1920; break;
case 15: p = new CPkDataItem2048; break;
case 16: p = new CPkDataItem2176; break;
case 17: p = new CPkDataItem2304; break;
case 18: p = new CPkDataItem2432; break;
case 19: p = new CPkDataItem2560; break;
case 20: p = new CPkDataItem2688; break;
case 21: p = new CPkDataItem2816; break;
case 22: p = new CPkDataItem2944; break;
case 23: p = new CPkDataItem3072; break;
case 24: p = new CPkDataItem3200; break;
case 25: p = new CPkDataItem3328; break;
case 26: p = new CPkDataItem3456; break;
case 27: p = new CPkDataItem3584; break;
case 28: p = new CPkDataItem3712; break;
case 29: p = new CPkDataItem3840; break;
case 30: p = new CPkDataItem3968; break;
case 31: p = new CPkDataItem4096; break;
case 32: p = new CPkDataItem4224; break;
default:
ASSERT_ALWAYS(FALSE, "CPkDataItem Buffer overflow", __FILE__, __LINE__);
}
}
}
ASSERT(p->MaxDataSize()>=C.DataSize());
p->m_wContents=C.m_wContents;
p->m_wSize=C.m_wSize;
memcpy(p->Buffer(), C.Buffer(), C.DataSize());
return p;
};
//------------------------------------------------------------------------
//
CPkDataItem * CPkDataItem::Create(const CPkDataItemOld &C)
{
CPkDataItem *p=NULL;
long Sz=C.m_wSize-1;
Sz=Max(0L, Sz);
switch (Sz/8)
{
case 0: p = new CPkDataItem8; break;
case 1: p = new CPkDataItem16; break;
case 2: p = new CPkDataItem24; break;
case 3: p = new CPkDataItem32; break;
case 4: p = new CPkDataItem40; break;
case 5: p = new CPkDataItem48; break;
case 6: p = new CPkDataItem56; break;
case 7: p = new CPkDataItem64; break;
default:
switch (Sz/32)
{
case 0: p = new CPkDataItem32; break; // wont happen
case 1: p = new CPkDataItem64; break; // wont happen
case 2: p = new CPkDataItem96; break;
case 3: p = new CPkDataItem128; break;
case 4: p = new CPkDataItem160; break;
case 5: p = new CPkDataItem192; break;
case 6: p = new CPkDataItem224; break;
case 7: p = new CPkDataItem256; break;
default:
switch (Sz/128)
{
case 0 : p = new CPkDataItem128; break; // wont happen
case 1 : p = new CPkDataItem256; break; // wont happen
case 2 : p = new CPkDataItem384; break;
case 3 : p = new CPkDataItem512; break;
case 4 : p = new CPkDataItem640; break;
case 5 : p = new CPkDataItem768; break;
case 6 : p = new CPkDataItem896; break;
case 7 : p = new CPkDataItem1024; break;
case 8 : p = new CPkDataItem1152; break;
case 9 : p = new CPkDataItem1280; break;
case 10: p = new CPkDataItem1408; break;
case 11: p = new CPkDataItem1536; break;
case 12: p = new CPkDataItem1664; break;
case 13: p = new CPkDataItem1792; break;
case 14: p = new CPkDataItem1920; break;
case 15: p = new CPkDataItem2048; break;
case 16: p = new CPkDataItem2176; break;
case 17: p = new CPkDataItem2304; break;
case 18: p = new CPkDataItem2432; break;
case 19: p = new CPkDataItem2560; break;
case 20: p = new CPkDataItem2688; break;
case 21: p = new CPkDataItem2816; break;
case 22: p = new CPkDataItem2944; break;
case 23: p = new CPkDataItem3072; break;
case 24: p = new CPkDataItem3200; break;
case 25: p = new CPkDataItem3328; break;
case 26: p = new CPkDataItem3456; break;
case 27: p = new CPkDataItem3584; break;
case 28: p = new CPkDataItem3712; break;
case 29: p = new CPkDataItem3840; break;
case 30: p = new CPkDataItem3968; break;
case 31: p = new CPkDataItem4096; break;
case 32: p = new CPkDataItem4224; break;
default:
ASSERT_ALWAYS(FALSE, "CPkDataItem Buffer overflow", __FILE__, __LINE__);
}
}
}
p->m_wContents=C.m_wContents;
p->m_wSize=C.m_wSize;
memcpy(p->Buffer(), &C.m_cData[0], C.m_wSize);
return p;
};
//------------------------------------------------------------------------
CPkDataItem::~CPkDataItem()
{
};
//------------------------------------------------------------------------
void CPkDataItem::Clear()
{
m_wContents=0;
m_wSize=0;
};
//------------------------------------------------------------------------
bool CPkDataItem::operator==(const CPkDataItem &C)
{
return (C.m_wContents==m_wContents) && (C.m_wSize==m_wSize) && (memcmp(&C.m_Data[0], &m_Data[0], m_wSize)==0);
};
bool CPkDataItem::operator!=(const CPkDataItem &C)
{
return (C.m_wContents!=m_wContents) || (C.m_wSize!=m_wSize) || (memcmp(&C.m_Data[0], &m_Data[0], m_wSize)!=0);
};
CPkDataItem & CPkDataItem::operator=(const CPkDataItem &C)
{
m_wContents=C.m_wContents;
m_wSize=C.m_wSize;
memcpy(&m_Data[0], &C.m_Data[0], m_wSize);
return *this;
};
//------------------------------------------------------------------------
inline int CPkDataItem::CompactAStr(LPSTR pStr)
{
{
strcpy(CurrentPtr(), pStr);
//if (pInfo)
// pInfo->AddStr(CurrentPtr());
m_wSize+=strlen(pStr)+1;
return 0;
}
}
//------------------------------------------------------------------------
LPSTR CPkDataItem::SkipAStr(LPSTR p)
{
p+=strlen(p)+1;
return p;
};
//------------------------------------------------------------------------
LPSTR CPkDataItem::ExtractAStr(LPSTR p)
{
return p;
};
//------------------------------------------------------------------------
static flag TstContentsClear(dword m_wContents, dword i)
{
dword tst=m_wContents;
while (i<0x8000)
{
if ((i & tst)!=0)
return 0;
i=i<<1;
}
return 1;
}
#ifdef _RELEASE
#define TSTCONTENTSCLEAR(a,b)
#else
#define TSTCONTENTSCLEAR(a,b) {if (!TstContentsClear(a,b)) DoBreak();}
#endif
//------------------------------------------------------------------------
void CPkDataItem::AppendValue(DDEF_Flags iFlags, PkDataUnion &PData)
{
TSTCONTENTSCLEAR(m_wContents, PDI_Value);
if (iFlags)
{
m_wContents|=PDI_Flags|PDI_Flags64;
memcpy(CurrentPtr(), &iFlags, sizeof(iFlags));
m_wSize+=sizeof(iFlags);
}
m_wContents|=PDI_Value;
char * pStart=CurrentPtr();
word sz=PData.Size();
VERIFY(sz>0);
memcpy(CurrentPtr(), (char*)&PData, sz);
m_wSize+=sz;
char * pEnd=CurrentPtr();
}
//------------------------------------------------------------------------
void CPkDataItem::AppendTag(pchar pTag, pchar pSym)
{
TSTCONTENTSCLEAR(m_wContents, PDI_Tag);
m_wContents|=PDI_Tag;
CompactAStr(pSym);
CompactAStr(pTag);
};
//------------------------------------------------------------------------
void CPkDataItem::AppendTagOfParent(char * pTag)
{
if (pTag && (strlen(pTag)>0))
{
TSTCONTENTSCLEAR(m_wContents, PDI_TagOfParent);
m_wContents|=PDI_TagOfParent;
strcpy(CurrentPtr(), pTag);
m_wSize+=strlen(pTag)+1;
}
};
//------------------------------------------------------------------------
void CPkDataItem::AppendDescription(char * pDesc)
{
if (pDesc && (strlen(pDesc)>0))
{
TSTCONTENTSCLEAR(m_wContents, PDI_Description);
m_wContents|=PDI_Description;
CompactAStr(pDesc);
//strcpy(CurrentPtr(), pDesc);
//m_wSize+=strlen(pDesc)+1;
}
};
//------------------------------------------------------------------------
void CPkDataItem::AppendTagComment(char * pTagComment)
{
if (pTagComment && (strlen(pTagComment)>0))
{
TSTCONTENTSCLEAR(m_wContents, PDI_TagComment);
m_wContents|=PDI_TagComment;
CompactAStr(pTagComment);
//m_wSize+=strlen(pTagComment)+1;
}
};
//------------------------------------------------------------------------
void CPkDataItem::AppendSubClass(char * pSubClass)
{
if (pSubClass && (strlen(pSubClass)>0))
{
TSTCONTENTSCLEAR(m_wContents, PDI_SubClass);
m_wContents|=PDI_SubClass;
strcpy(CurrentPtr(), pSubClass);
m_wSize+=strlen(pSubClass)+1;
}
};
//------------------------------------------------------------------------
void CPkDataItem::AppendPrimaryCfg(char * pPrimaryCfg)
{
if (pPrimaryCfg && (strlen(pPrimaryCfg)>0))
{
TSTCONTENTSCLEAR(m_wContents, PDI_PrimaryCfg);
m_wContents|=PDI_PrimaryCfg;
strcpy(CurrentPtr(), pPrimaryCfg);
m_wSize+=strlen(pPrimaryCfg)+1;
}
};
//------------------------------------------------------------------------
void CPkDataItem::AppendNElements(DDEF_NElements nElems)
{
TSTCONTENTSCLEAR(m_wContents, PDI_NElements);
m_wContents|=PDI_NElements;
memcpy(CurrentPtr(), &nElems, sizeof(nElems));
m_wSize+=sizeof(nElems);
};
//------------------------------------------------------------------------
#if WITHEQUIPSPECS
void CPkDataItem::AppendItemStatus(CTagRefStatus S, CTagValueStatus V)
#else
void CPkDataItem::AppendItemStatus(CTagRefStatus S)
#endif
{
TSTCONTENTSCLEAR(m_wContents, PDI_XRefStatus);
m_wContents|=PDI_XRefStatus;
memcpy(CurrentPtr(), &S, sizeof(S));
m_wSize+=sizeof(S);
#if WITHEQUIPSPECS
memcpy(CurrentPtr(), &V, sizeof(V));
m_wSize+=sizeof(V);
#endif
};
//------------------------------------------------------------------------
void CPkDataItem::AppendRange(DataUnion &DMin, DataUnion &DMax)
{
PkDataUnion PMin, PMax;
TSTCONTENTSCLEAR(m_wContents, PDI_Range);
m_wContents|=PDI_Range;
char * pStart=CurrentPtr();
PMin.Set(DMin);
memcpy(CurrentPtr(), &PMin, PMin.Size());
m_wSize+=PMin.Size();
PMax.Set(DMax);
memcpy(CurrentPtr(), &PMax, PMax.Size());
m_wSize+=PMax.Size();
};
//------------------------------------------------------------------------
void CPkDataItem::AppendCnvInfo(CCnvIndex iCnv, char * pCnvTxt, char * pCnvFam)
{
TSTCONTENTSCLEAR(m_wContents, PDI_CnvInfo);
m_wContents|=PDI_CnvInfo;
char * pStart=CurrentPtr();
*((CCnvIndex*)(CurrentPtr()/*+m_wSize*/))=iCnv;
strcpy(CurrentPtr()+sizeof(CCnvIndex), pCnvTxt);
m_wSize+=sizeof(CCnvIndex)+strlen(pCnvTxt)+1;
strcpy(CurrentPtr(), pCnvFam);
m_wSize+=strlen(pCnvFam)+1;
};
//------------------------------------------------------------------------
void CPkDataItem::AppendStrListItem(char * pStr, long Index, flag Indexed, pword & pStrLstLen)
{
char*p=CurrentPtr();
if (pStrLstLen==NULL)
{
TSTCONTENTSCLEAR(m_wContents, PDI_StrList);
m_wContents|=PDI_StrList;
word n=1;// One Item
pStrLstLen=(word*)p;
*pStrLstLen=n;
m_wSize+=sizeof(n);
p+=sizeof(n);
*((flag*)p)=Indexed;
m_wSize+=sizeof(Indexed);
p+=sizeof(Indexed);
}
else
*pStrLstLen=*pStrLstLen+1;
if (Indexed)
{
*((long*)p)=Index;
m_wSize+=sizeof(long);
p+=sizeof(long);
}
strcpy(p, pStr);
int Len=strlen(pStr);
p+=Len+1;
m_wSize+=Len+1;
};
//------------------------------------------------------------------------
//void CPkDataItem::AppendNextStrListItem(char *pStr, long Index, flag Indexed, pword pStrLstLen)
// {
// //TCONTENTSCLEAR(m_wContents, PDI_StrList);
// //ontents|=PDI_StrList;
//
// *pStrLstLen=*pStrLstLen+1;
// char*p=CurrentPtr();
//
// if (Indexed)
// {
// *((long*)p)=Index;
// wSize+=sizeof(long);
// p+=sizeof(long);
// }
// strcpy(p, pStr);
// int Len=strlen(pStr);
// p+=Len+1;
// wSize+=Len+1;
// };
//------------------------------------------------------------------------
void* CPkDataItem::AddressOf(word what)
{
// NBNB
// this arithmetic must be in the order of the PDI_ constants
char* p=Buffer();//m_pData->Start();
if (what == PDI_Flags) return (char*)p;
if (m_wContents & PDI_Flags) p += (m_wContents & PDI_Flags64) ? sizeof(DDEF_Flags64) : sizeof(DDEF_Flags32);
if (what == PDI_Value) return (char*)p;
if (m_wContents & PDI_Value) p+=((PkDataUnion*)p)->Size();
if (what == PDI_Tag) return (char*)p;
if (m_wContents & PDI_Tag)
{ // Skip Sym
p=SkipAStr(p);
// Skip Tag
p=SkipAStr(p);
}
if (what == PDI_TagOfParent) return (char*)p;
if (m_wContents & PDI_TagOfParent) p+=strlen(p)+1;
if (what == PDI_CnvInfo) {
return (char*)p;
}
if (m_wContents & PDI_CnvInfo) {
p+=sizeof(CCnvIndex); // Skip CnvIndex
p+=strlen(p)+1; // Skip CnvStr
p+=strlen(p)+1; // Skip CnvFam
}
if (what == PDI_NElements) return (char*)p;
if (m_wContents & PDI_NElements) p+=sizeof(DDEF_NElements);
if (what == PDI_XRefStatus) return (char*)p;
if (m_wContents & PDI_XRefStatus) {
p+=sizeof(CTagRefStatus);
#if WITHEQUIPSPECS
p+=sizeof(CTagValueStatus);
#endif
}
if (what == PDI_Range) return (char*)p;
if (m_wContents & PDI_Range) {
PkDataUnion* pUn=(PkDataUnion*)p;
p+=pUn->Size();
PkDataUnion* pUx=(PkDataUnion*)p;
p+=pUx->Size();
}
if (what == PDI_StrList) return (char*)p;
if (m_wContents & PDI_StrList) {
word n=*((word*)p);
p+=sizeof(word);
flag Indexed=*((flag*)p);
p+=sizeof(flag);
for(word i=0; i<n; i++)
{
if (Indexed)
p+=sizeof(long);
p+=strlen(p)+1;
}
}
if (what == PDI_Description) return (char*)p;
if (m_wContents & PDI_Description) p=SkipAStr(p);
if (what == PDI_TagComment) return (char*)p;
if (m_wContents & PDI_TagComment) p=SkipAStr(p);
if (what == PDI_SubClass) return (char*)p;
if (m_wContents & PDI_SubClass) p+=strlen(p)+1;
if (what == PDI_PrimaryCfg) return (char*)p;
if (m_wContents & PDI_PrimaryCfg) p+=strlen(p)+1;
//if (what == PDI_Blob) return (char*)p;
//if (m_wContents & PDI_Blob) { ASSERT(0); word l=*((word*)p); p+=sizeof(word)+l+1; }
VERIFY(0);
return NULL;
}
//------------------------------------------------------------------------
/*
void* CPkDataItem::AddressOf(word what)
{
// NBNB
// this arithmetic must be in the order of the PDI_ constants
#if WITHCOMPACT
char* p=(m_wContents & PDI_Compact) ? m_cDataCompact : cData;
#else
char* p=cData;
#endif
if (what == PDI_Flags) return (char*)p;
if (m_wContents & PDI_Flags)
{
if (m_wContents & PDI_Flags64)
{
#if WITHCOMPACT
if (m_FlgRL && (m_wContents & PDI_Compact))
p+=m_FlgRL;//1+*p;
else
#endif
p+=sizeof(DDEF_Flags64);
}
else
p+=sizeof(DDEF_Flags32);
};
if (what == PDI_Value) {
#if WITHCOMPACT
if (m_ValRL && (m_wContents & PDI_Compact))
{
long i=0;
memcpy(&i, p, m_ValRL);
p-=i;
}
#endif
return (char*)p;
}
if (m_wContents & PDI_Value) {
#if WITHCOMPACT
if (m_ValRL && (m_wContents & PDI_Compact))
p+=m_ValRL;//1+*p;
else
#endif
p+=((PkDataUnion*)p)->Size();
}
if (what == PDI_Tag) return (char*)p;
if (m_wContents & PDI_Tag)
{ // Skip Sym
p=SkipAStr(p, m_SymRL);
// Skip Tag
p=SkipAStr(p, m_TagRL);
}
if (what == PDI_TagOfParent) return (char*)p;
if (m_wContents & PDI_TagOfParent) p+=strlen(p)+1;
if (what == PDI_CnvInfo) {
#if WITHCOMPACT
if (m_CnvRL && (m_wContents & PDI_Compact))
{
long i=0;
memcpy(&i, p, m_CnvRL);
p-=i;
}
#endif
return (char*)p;
}
if (m_wContents & PDI_CnvInfo) {
#if WITHCOMPACT
if (m_CnvRL && (m_wContents & PDI_Compact))
p+=m_CnvRL;//1+*p;
else
#endif
{
p+=sizeof(CCnvIndex); // Skip CnvIndex
p+=strlen(p)+1; // Skip CnvStr
p+=strlen(p)+1; // Skip CnvFam
}
}
if (what == PDI_NElements) return (char*)p;
if (m_wContents & PDI_NElements) p+=sizeof(DDEF_NElements);
if (what == PDI_XRefStatus) return (char*)p;
if (m_wContents & PDI_XRefStatus) p+=sizeof(CTagRefStatusWord);
if (what == PDI_Range) {
#if WITHCOMPACT
if (m_RngRL && (m_wContents & PDI_Compact))
{
long i=0;
memcpy(&i, p, m_RngRL);
p-=i;
}
#endif
return (char*)p;
}
if (m_wContents & PDI_Range) {
#if WITHCOMPACT
if (m_RngRL && (m_wContents & PDI_Compact))
p+=m_RngRL;//1+*p;
else
#endif
{
PkDataUnion* pUn=(PkDataUnion*)p;
p+=pUn->Size();
PkDataUnion* pUx=(PkDataUnion*)p;
p+=pUx->Size();
}
}
if (what == PDI_StrList) {
#if WITHCOMPACT
if (m_LstRL && (m_wContents & PDI_Compact))
{
long i=0;
memcpy(&i, p, m_LstRL);
p-=i;
}
#endif
return (char*)p;
}
if (m_wContents & PDI_StrList) {
#if WITHCOMPACT
if (m_LstRL && (m_wContents & PDI_Compact))
p+=m_LstRL;//1+*p;
else
#endif
{
word n=*((word*)p);
p+=sizeof(word);
flag Indexed=*((flag*)p);
p+=sizeof(flag);
for(word i=0; i<n; i++)
{
if (Indexed)
p+=sizeof(long);
p+=strlen(p)+1;
}
}
}
if (what == PDI_Description) return (char*)p;
if (m_wContents & PDI_Description) p=SkipAStr(p, m_DscRL);
if (what == PDI_TagComment) return (char*)p;
if (m_wContents & PDI_TagComment) p=SkipAStr(p, m_ComRL);
if (what == PDI_SubClass) return (char*)p;
if (m_wContents & PDI_SubClass) p+=strlen(p)+1;
if (what == PDI_PrimaryCfg) return (char*)p;
if (m_wContents & PDI_PrimaryCfg) p+=strlen(p)+1;
//if (what == PDI_Blob) return (char*)p;
//if (m_wContents & PDI_Blob) { ASSERT(0); word l=*((word*)p); p+=sizeof(word)+l+1; }
VERIFY(0);
return NULL;
}
**/
//------------------------------------------------------------------------
byte CPkDataItem::Type()
{
if ((m_wContents & PDI_Value)==0) return tt_NULL;
PkDataUnion *p=(PkDataUnion *)AddressOf(PDI_Value);
return p->Type();
};
//------------------------------------------------------------------------
PkDataUnion *CPkDataItem::Value()
{
if ((m_wContents & PDI_Value)==0) return NULL;
PkDataUnion *p=(PkDataUnion *)AddressOf(PDI_Value);
return p;
};
//------------------------------------------------------------------------
char *CPkDataItem::Class()
{
if ((m_wContents & PDI_Value)==0) return NULL;
PkDataUnion *p=(PkDataUnion *)AddressOf(PDI_Value);
return p->String();
};
//------------------------------------------------------------------------
char* CPkDataItem::SymStr()
{
if ((m_wContents & PDI_Tag)==0) return "";
char*p=(char*)AddressOf(PDI_Tag);
return ExtractAStr(p);
//long i=0;
//if (*p>=1 && *p<=4)
// {
// memcpy(&i, p+1, *p);
// p-=i;
// //dbgpln("SymStr='%s'", p);
// }
//return p;
};
//------------------------------------------------------------------------
char* CPkDataItem::TagStr()
{
if ((m_wContents & PDI_Tag)==0) return "";
char*p=(char*)AddressOf(PDI_Tag);
p=SkipAStr(p);
return ExtractAStr(p);
};
//------------------------------------------------------------------------
char* CPkDataItem::SymOrTag()
{
if ((m_wContents & PDI_Tag)==0) return "";
LPSTR p=(LPSTR)AddressOf(PDI_Tag);
if (*p==0)
p+=strlen(p)+1; // Skip Zero len Sym
return p;
};
//------------------------------------------------------------------------
DDEF_Flags CPkDataItem::Flags()
{
if ((m_wContents & PDI_Flags)==0)
return 0;
if (m_wContents & PDI_Flags64)
{
return *((DDEF_Flags64*)AddressOf(PDI_Flags));
}
else
return *((DDEF_Flags32*)AddressOf(PDI_Flags));
};
//------------------------------------------------------------------------
char* CPkDataItem::TagOfParent()
{
if ((m_wContents & PDI_TagOfParent)==0) return "";
char*p=(char*)AddressOf(PDI_TagOfParent);
return p;
};
//------------------------------------------------------------------------
char* CPkDataItem::Description()
{
if ((m_wContents & PDI_Description)==0) return "";
char*p=(char*)AddressOf(PDI_Description);
return ExtractAStr(p);
};
//------------------------------------------------------------------------
char* CPkDataItem::TagComment()
{
if ((m_wContents & PDI_TagComment)==0) return "";
char*p=(char*)AddressOf(PDI_TagComment);
return ExtractAStr(p);
};
//------------------------------------------------------------------------
char* CPkDataItem::SubClass()
{
if ((m_wContents & PDI_SubClass)==0) return "";
char*p=(char*)AddressOf(PDI_SubClass);
return p;
};
//------------------------------------------------------------------------
char* CPkDataItem::PrimaryCfg()
{
if ((m_wContents & PDI_PrimaryCfg)==0) return "";
char*p=(char*)AddressOf(PDI_PrimaryCfg);
return p;
};
//------------------------------------------------------------------------
DDEF_NElements CPkDataItem::NElements()
{
if ((m_wContents & PDI_NElements)==0) return 0;
DDEF_NElements*p=(DDEF_NElements*)AddressOf(PDI_NElements);
return *p;
};
//------------------------------------------------------------------------
CTagRefStatus CPkDataItem::GetTagRefStatus()
{
if ((m_wContents & PDI_XRefStatus)==0)
return 0;
char*p=(char*)AddressOf(PDI_XRefStatus);
CTagRefStatus Status=*((CTagRefStatus*)p);
return Status;
};
//------------------------------------------------------------------------
#if WITHEQUIPSPECS
CTagValueStatus CPkDataItem::GetTagValueStatus()
{
if ((m_wContents & PDI_XRefStatus)==0)
return 0;
char*p=(char*)AddressOf(PDI_XRefStatus);
p+=sizeof(CTagRefStatus);
CTagValueStatus Status=*((CTagValueStatus*)p);
return Status;
};
#endif
//------------------------------------------------------------------------
flag CPkDataItem::GetRange(DataUnion &DMin, DataUnion &DMax)
{
if ((m_wContents & PDI_Range)==0) return 0;
pPkDataUnion pDU;
char*p=(char*)AddressOf(PDI_Range);
pDU=(pPkDataUnion)p;
DMin.Set(*pDU);
p+=pDU->Size();
pDU=(pPkDataUnion)p;
DMax.Set(*pDU);
return 1;
};
//------------------------------------------------------------------------
flag CPkDataItem::GetRange(pPkDataUnion &pDMin, pPkDataUnion &pDMax)
{
if ((m_wContents & PDI_Range)==0)
{
pDMin=NULL;
pDMax=NULL;
return 0;
}
char*p=(char*)AddressOf(PDI_Range);
pDMin=(pPkDataUnion)p;
p+=pDMin->Size();
pDMax=(pPkDataUnion)p;
return 1;
};
//------------------------------------------------------------------------
CCnvIndex CPkDataItem::CnvIndex()
{
if ((m_wContents & PDI_CnvInfo)==0) return 0;
CCnvIndex* p=(CCnvIndex*)AddressOf(PDI_CnvInfo);
return *p;
};
//------------------------------------------------------------------------
char* CPkDataItem::CnvTxt()
{
if ((m_wContents & PDI_CnvInfo)==0) return 0;
char*p=(((char*)AddressOf(PDI_CnvInfo))+sizeof(CCnvIndex));
return p;
};
//------------------------------------------------------------------------
char* CPkDataItem::CnvFam()
{
if ((m_wContents & PDI_CnvInfo)==0) return 0;
char*p=(((char*)AddressOf(PDI_CnvInfo))+sizeof(CCnvIndex));
p+=strlen(p)+1;
return p;
};
//------------------------------------------------------------------------
flag CPkDataItem::IndexedStrList()
{
if ((m_wContents & PDI_StrList)==0) return False;
char*p=(char*)AddressOf(PDI_StrList);
word n=*((word*)p);
p+=sizeof(word);
return *((flag*)p);
};
//------------------------------------------------------------------------
flag CPkDataItem::GetStrList(Strng_List & Values, flag & Indexed)
{
Values.Clear();
if ((m_wContents & PDI_StrList)==0) return False;
char*p=(char*)AddressOf(PDI_StrList);
word n=*((word*)p);
p+=sizeof(word);
Indexed=*((flag*)p);
p+=sizeof(flag);
for(word i=0; i<n; i++)
{
long Inx=i;
if (Indexed)
{
Inx=*((long*)p);
p+=sizeof(long);
}
pStrng pS=new Strng(p);
pS->SetIndex(Inx);
Values.Append(pS);
p+=pS->Length()+1;
}
return True;
};
//------------------------------------------------------------------------
void CPkDataItem::AppendLayout(byte iType, pchar pTag, DDEF_Flags iFlags)
{
Clear();//pInfo);
PkDataUnion PData;
PData.iType=iType;
PData.StringSet(pTag);
AppendValue(iFlags, PData);
//pendDefFlags(iFlags);
};
//------------------------------------------------------------------------
void CPkDataItem::AppendStructureS(byte iType, pchar pTag, pchar pClass, pchar pSubClass, pchar pPrimaryCfg, DDEF_Flags iFlags, pchar pTagOfParent, pchar pDescription, pchar pTagComment, int nElem)
{
Clear();//pInfo);
PkDataUnion PData;
PData.iType=iType;
PData.StringSet(pClass);
AppendValue(iFlags, PData);
AppendTag(pTag, "");
//AppendDefFlags(iFlags);
if (pTagOfParent && (strlen(pTagOfParent)>0))
AppendTagOfParent(pTagOfParent);
if (iType==tt_Array)
AppendNElements(nElem);
if (pDescription && (strlen(pDescription)>0))
AppendDescription(pDescription);
if (pTagComment && (strlen(pTagComment)>0))
AppendTagComment(pTagComment);
if (pSubClass && (strlen(pSubClass)>0))
AppendSubClass(pSubClass);
if (pPrimaryCfg && (strlen(pPrimaryCfg)>0))
AppendPrimaryCfg(pPrimaryCfg);
};
//------------------------------------------------------------------------
void CPkDataItem::AppendStructureE(byte iType, pchar pTag, DDEF_Flags iFlags)
{
Clear();//pInfo);;
PkDataUnion PData;
PData.iType=iType;
PData.StringSet("");
AppendValue(iFlags, PData);
if (pTag && (strlen(pTag)>0))
AppendTag(pTag, "");
};
//------------------------------------------------------------------------
void CPkDataItem::AppendDataValue(TABOptions Opts, pchar pTag, pchar pSym, DDEF_Flags iFlags, PkDataUnion &PData, CCnvIndex iCnv, char *pCnvTxt, char *pCnvFam)
{
Clear();//pInfo);;
AppendValue(iFlags, PData);
if ((Opts & (TABOpt_ForScenario|TABOpt_ForSnapShot|TABOpt_AllInfo)) &&
((pTag!=NULL && pTag[0]>0) || (pSym!=NULL && pSym[0]>0)))
AppendTag(pTag, pSym);
//AppendDefFlags(iFlags);
if ((Opts & (TABOpt_ValCnvs|TABOpt_AllInfo)) && ((iCnv)>0) && pCnvTxt && (strlen(pCnvTxt)>0))
AppendCnvInfo(iCnv, pCnvTxt, pCnvFam);
};
//------------------------------------------------------------------------
void CPkDataItem::AppendBlob(pchar pTag, void * pBlob, short iBlobLen)
{
Clear();//pInfo);;
//AppendTag(pTag);
PkDataUnion PData;
PData.iType=tt_Blob;
PData.BlobSet(pBlob, iBlobLen);
AppendValue(0, PData);
AppendTag(pTag, "");
};
//------------------------------------------------------------------------
void CPkDataItem::AppendValueLst(DDBValueLst *pValueLst, flag Indexed)
{
if (pValueLst && pValueLst->m_pStr)
{
char * pStart=CurrentPtr();
pword pStrLstLen=NULL;
for ( ; pValueLst->m_pStr; pValueLst++)
if ((pValueLst->m_dwFlags & MDD_Hidden)==0)
AppendStrListItem(pValueLst->m_pStr, pValueLst->m_lVal, Indexed, pStrLstLen);
}
}
//========================================================================
//
//
//
//========================================================================
CPkDataList::CPkDataList() :
m_WorkItem(*(new CPkDataItem4224))
{
Clear();
};
CPkDataList::~CPkDataList()
{
delete &m_WorkItem;
};
inline void CPkDataList::AdvanceWrite()//CPkDataItem* &pPItem)
{
//Do New etc
ASSERT(m_WorkItem.ItemSize()<BiggestBuffer);
CPkDataItem* pItem=CPkDataItem::Create(m_WorkItem);
AddTail(pItem);
};
//------------------------------------------------------------------------
void CPkDataList::SetStructureS(byte iType, pchar pTag, pchar pClass, pchar pSubClass, pchar pPrimaryCfg, DDEF_Flags iFlags, pchar pTagOfParent, pchar pDescription, pchar pTagComment, int nElem)
{
Item.Clear();
PkDataUnion PData;
PData.iType=iType;
PData.StringSet(pClass);
Item.AppendValue(iFlags, PData);
Item.AppendTag(pTag, "");
if (pTagOfParent && (strlen(pTagOfParent)>0))
Item.AppendTagOfParent(pTagOfParent);
if (iType==tt_Array)
Item.AppendNElements(nElem);
if (pDescription && (strlen(pDescription)>0))
Item.AppendDescription(pDescription);
if (pTagComment && (strlen(pTagComment)>0))
Item.AppendTagComment(pTagComment);
if (pSubClass && (strlen(pSubClass)>0))
Item.AppendSubClass(pSubClass);
if (pPrimaryCfg && (strlen(pPrimaryCfg)>0))
Item.AppendPrimaryCfg(pPrimaryCfg);
AdvanceWrite();//pPItem);
};
//------------------------------------------------------------------------
void CPkDataList::SetStructureE(byte iType, pchar pTag, DDEF_Flags iFlags)
{
Item.Clear();
PkDataUnion PData;
PData.iType=iType;
PData.StringSet("");
Item.AppendValue(iFlags, PData);
if (pTag && (strlen(pTag)>0))
Item.AppendTag(pTag, "");
AdvanceWrite();
};
//------------------------------------------------------------------------
void CPkDataList::SetDataValue(pchar pTag, DDEF_Flags iFlags, PkDataUnion &PData)
{
Item.Clear();
Item.AppendValue(iFlags, PData);
if (pTag!=NULL && pTag[0]>0)
Item.AppendTag(pTag, "");
//AppendDefFlags(iFlags);
AdvanceWrite();
};
//------------------------------------------------------------------------
void CPkDataList::SetDataValueAll(pchar pTag, pchar pTagComment, PkDataUnion &PData, DDEF_Flags iFlags,
DataUnion &DataMin, DataUnion &DataMax, CCnvIndex iCnv, pchar pCnvTxt, pchar pCnvFam,
pStrng_List pValueList, flag bIndexedStr, pchar pDesc)
{
Item.Clear();
Item.AppendValue(iFlags, PData);
Item.AppendTag(pTag, "");
if ((iCnv)>0 && strlen(pCnvTxt) > 0)
Item.AppendCnvInfo(iCnv, pCnvTxt, pCnvFam);
if (DataMin.iType!=tt_NULL)
Item.AppendRange(DataMin, DataMax);
if (pValueList)
{
word *pStrLstLen=NULL;
pStrng pS=pValueList->First();
for (int i=0; pS; i++, pS=pS->Next())
Item.AppendStrListItem(pS->Str(), pS->Index(), bIndexedStr, pStrLstLen);
}
if (pDesc && (strlen(pDesc)>0))
Item.AppendDescription(pDesc);
if (pTagComment && (strlen(pTagComment)>0))
Item.AppendTagComment(pTagComment);
AdvanceWrite();
};
//------------------------------------------------------------------------
void CPkDataList::dbgDump(flag Full, char* pWhere)
{
dbgp("CPkDataList[] : %s", /*Size()*//*wSize*/ pWhere);
flag MultiLine=0;
CPkDataIter Iter;
CPkDataItem * pFirstItem=FirstItem(Iter);
if (pFirstItem)
{
CPkDataItem* pPItem=pFirstItem;
MultiLine=(!IsData(pPItem->Type()) && Full);
pPItem=NextItem(Iter);//AdvanceReadItem();
if (!pPItem)
MultiLine=0;
}
if (MultiLine)
dbgpln("");
int n=0;
int iItem=0;
int CompactStart=0;
int CompactStartZ=0;
int Size=0;
for (CPkDataItem* pPItem=FirstItem(Iter); pPItem && (Full || n++<10); pPItem=NextItem(Iter)) //AdvanceReadItem())
{
if (Full)
{
char * pC=(char*)pPItem;
word C=0, Cm=1;
for (int ii=0; ii<16; ii++, Cm=Cm<<1)
if (pPItem->Contains(Cm))
C|=Cm;
dbgp("%5i)", iItem++);
dbgp("%3i:", pPItem->DataSize());
//dbgp("%5i[%3i]:", (char*)pPItem-(char*)pFirstItem, pPItem->Size());
dbgp("%04x ", C);
dbgp("%08x ", pPItem->Buffer());
if (0)
{
dbgp("%5i", CompactStart);
dbgp("|%5i", CompactStartZ);
dbgp(pPItem->Contains(PDI_Value) ?"(%3i) ":"( )", pPItem->Value()->Size());
// Contents Data XRef Index
int DataSz=0;
bool IsZero=false;
if (pPItem->Contains(PDI_Value ))
{
DataSz=pPItem->Value()->Size();
switch (pPItem->Value()->Type())
{
case tt_Double: IsZero = pPItem->Value()->GetDouble()==0; break;
}
}
dbgp(IsZero?"=0 ":" ");
CompactStart+=2+DataSz+1+4;
CompactStartZ+=2+(IsZero?0:DataSz)+1+4;
}
dbgp("'", C);
dbgp("%c", pPItem->Contains(PDI_Flags ) ? 'F':' ');
dbgp("%c", pPItem->Contains(PDI_Value ) ? 'V':' ');
dbgp("%c", pPItem->Contains(PDI_Tag ) ? 'T':' ');
dbgp("%c", pPItem->Contains(PDI_TagOfParent) ? 'P':' ');
dbgp("%c", pPItem->Contains(PDI_CnvInfo ) ? 'C':' ');
dbgp("%c", pPItem->Contains(PDI_NElements ) ? 'N':' ');
dbgp("%c", pPItem->Contains(PDI_CnvInfo2 ) ? '2':' ');
dbgp("%c", pPItem->Contains(PDI_XRefStatus ) ? 'X':' ');
dbgp("%c", pPItem->Contains(PDI_Range ) ? 'R':' ');
dbgp("%c", pPItem->Contains(PDI_StrList ) ? 'L':' ');
dbgp("%c", pPItem->Contains(PDI_Description) ? 'D':' ');
dbgp("%c", pPItem->Contains(PDI_TagComment ) ? 'c':' ');
dbgp("%c", pPItem->Contains(PDI_SubClass ) ? 'S':' ');
dbgp("%c", pPItem->Contains(PDI_PrimaryCfg ) ? 'g':' ');
//dbgp("%c", pPItem->Contains(PDI_Flags64 ) ? '6':' ');
dbgp("' %4i%4i:", pPItem->DataSize(), pPItem->Value()->TypeSize());
}
if (pPItem->Empty())
{
if (Full)
dbgpln("");
break;
}
if (!MultiLine && pPItem!=pFirstItem)
dbgp(", ");
dbgp(Full ? " %-8.8s:" : "%s",tt_TypeString(pPItem->Type()));
if (pPItem->Contains(PDI_Flags))
{
DDEF_Flags F=pPItem->Flags();
/**/
Strng S;
if ((F&DDEF_PARAM )!=0) S+="P";
if ((F&DDEF_NOFILE )==0) S+="f";
if ((F&DDEF_NOVIEW )==0) S+="v";
if ((F&DDEF_NOSNAPSHOT )==0) S+="s";
if ((F&DDEF_NOSCENARIO )==0) S+="c";
if ((F&DDEF_WRITEPROTECT )!=0) S+="W";
if ((F&DDEF_HIDDEN )!=0) S+="H";
if ((F&DDEF_AFFECTSSTRUCT )!=0) S+="S";
if ((F&DDEF_KEEPHISTORY )!=0) S+="K";
if ((F&DDEF_TREENODE )!=0) S+="n";
if ((F&DDEF_NAN_OK )!=0) S+="N";
if ((F&DDEF_BUTTON )!=0) S+="B";
if ((F&DDEF_CHECKBOX )!=0) S+="C";
if ((F&DDEF_DUPHANDLES_OK )!=0) S+="x";
if ((F&DDEF_MULTILINESTR )!=0) S+="M";
if ((F&DDEF_PARAMSTOPPED )!=0) S+="p";
if ((F&DDEF_INERROR )!=0) S+="E";
if ((F&DDEF_DRIVERTAG )!=0) S+="D";
if ((F&DDEF_HIDEIFZERO )!=0) S+="Z";
if ((F&DDEF_CHILDMASK )!=0) S+="+";
//if ((F&DDEF_STARTMATRIX )!=0) S+="#";
//if ((F&DDEF_STARTROW )!=0) S+="[";
//if ((F&DDEF_ENDMATRIX )!=0) S+="]";
dbgp(" <%-8s>",S.Buffer());
/**/
//dbgp(" <%8x>",F);
}
else
dbgp(" < >");
dbgp(pPItem->Value()->IsZero() ? "Z":" ");
#if WITHEQUIPSPECS
if (pPItem->Contains(PDI_XRefStatus))
dbgp("{%02x.%02x}", pPItem->GetTagRefStatus(), pPItem->GetTagValueStatus());
else
dbgp(" ");
#else
if (pPItem->Contains(PDI_XRefStatus))
dbgp("{%02x}", pPItem->GetTagRefStatus());
else
dbgp(" ");
#endif
if (pPItem->Contains(PDI_Tag))
if (strlen(pPItem->SymStr())>0)
dbgp(" '%s' ('%s')",pPItem->SymOrTag(), pPItem->TagStr());
else
dbgp(" '%s'",pPItem->TagStr());
if (pPItem->Contains(PDI_TagOfParent))
dbgp(" Parent:%s",pPItem->TagOfParent());
if (pPItem->Contains(PDI_Value))
if (pPItem->Type()!=tt_Blob)
dbgp(" = '%s'", pPItem->Value()->GetString());
if (pPItem->Contains(PDI_SubClass))
dbgp(" [%s]",pPItem->SubClass());
if (pPItem->Contains(PDI_PrimaryCfg))
dbgp(" /%s/",pPItem->PrimaryCfg());
if (pPItem->Contains(PDI_CnvInfo))
{
dbgp(" Cnv:'%s",pPItem->CnvTxt());
dbgp(pPItem->CnvFam() && strlen(pPItem->CnvFam())>0 ? "(%s)":"",pPItem->CnvFam());
dbgp("'[%i]",pPItem->CnvIndex());
}
if (pPItem->Contains(PDI_NElements))
dbgp(" [%i]",pPItem->NElements());
if (pPItem->Contains(PDI_Range))
dbgp(" Range");
if (pPItem->Contains(PDI_StrList))
{
flag Inxd=pPItem->IndexedStrList();
dbgp(" StrList[");
//PkValueLst ValueList;
//pPItem->GetStrList(ValueList);
//for (pStrng pS=ValueList.Values.First(); pS; pS=pS->Next())
// {
// if (pS!=ValueList.Values.First())
// dbgp(",");
// if (Inxd)
// dbgp(" %i %s",pS->Index(), pS->Str());
// else
// dbgp(" %s",pS->Str());
// }
Strng_List ValueList;
pPItem->GetStrList(ValueList);
for (pStrng pS=ValueList.First(); pS; pS=pS->Next())
{
if (pS!=ValueList.First())
dbgp(",");
if (Inxd)
dbgp(" %i %s",pS->Index(), pS->Str());
else
dbgp(" %s",pS->Str());
}
dbgp("]");
}
if (pPItem->Contains(PDI_Description))
dbgp(" \"%s\"",pPItem->Description());
if (pPItem->Contains(PDI_TagComment))
dbgp(" (%s)",pPItem->TagComment());
//dbgp(" TagComment:%s",pPItem->TagComment());
if (MultiLine)
dbgpln("");
}
if (!MultiLine)
dbgpln("");
};
//=========================================================================
//
//
//
//=========================================================================
MTagIOValue::MTagIOValue()
{
m_TIOType = MTagType_Null;
};
MTagIOValue::MTagIOValue(long L)
{
m_TIOType = MTagType_Long;
m_Long = L;
};
MTagIOValue::MTagIOValue(double D)
{
m_TIOType = MTagType_Double;
m_Double = D;
};
MTagIOValue::MTagIOValue(LPCSTR S)
{
m_TIOType = MTagType_String;
m_String = S;
};
MTagIOValue::MTagIOValue(const MTagIOValue & V)
{
m_TIOType = V.m_TIOType;
switch (m_TIOType)
{
case MTagType_Long: m_Long = V.m_Long; break;
case MTagType_Double: m_Double = V.m_Double; break;
case MTagType_String: m_String = V.m_String; break;
}
};
MTagIOValue::~MTagIOValue() { };
MTagIOValue & MTagIOValue::operator=(const MTagIOValue & V)
{
m_TIOType = V.m_TIOType;
switch (m_TIOType)
{
case MTagType_Long: m_Long = V.m_Long; break;
case MTagType_Double: m_Double = V.m_Double; break;
case MTagType_String: m_String = V.m_String; break;
}
return *this;
};
MTagIOValue & MTagIOValue::operator=(const PkDataUnion & V)
{
m_TIOType = V.TagType();
switch (m_TIOType)
{
case MTagType_Long: m_Long = V.GetLong(); break;
case MTagType_Double: m_Double = V.GetDouble(); break;
case MTagType_String: m_String = V.GetString(); break;
}
return *this;
};
bool MTagIOValue::operator==(const MTagIOValue & V)
{
if (m_TIOType != V.m_TIOType)
return false;
switch (m_TIOType)
{
case MTagType_Long: return m_Long == V.m_Long;
case MTagType_Double:
{
bool Valid1=Valid(m_Double);
bool Valid2=Valid(V.m_Double);
return (Valid1 && Valid2 && (m_Double==V.m_Double)) || (Valid1==Valid2);
}
case MTagType_String: return m_String == V.m_String;
}
return false;
};
bool MTagIOValue::operator!=(const MTagIOValue & V)
{
if (m_TIOType != V.m_TIOType)
return true;
switch (m_TIOType)
{
case MTagType_Long: return m_Long != V.m_Long;
case MTagType_Double:
{
bool Valid1=Valid(m_Double);
bool Valid2=Valid(V.m_Double);
return (Valid1 && Valid2 && (m_Double!=V.m_Double)) || (Valid1!=Valid2);
}
case MTagType_String: return m_String != V.m_String;
}
return true;
};
MTagIOType MTagIOValue::getTIOType() const { return m_TIOType; };
void MTagIOValue::putTIOType(MTagIOType T) { m_TIOType=T; };
long MTagIOValue::getLong() const
{
switch (m_TIOType)
{
case MTagType_Long: return m_Long;
case MTagType_Double: return (long)Range(double(LONG_MIN), m_Double, double(LONG_MAX));
case MTagType_String: return SafeAtoL(m_String, 0);
};
return 0;
}
void MTagIOValue::putLong(long L)
{
m_TIOType=MTagType_Long;
m_Long=L;
};
double MTagIOValue::getDoubleSI() const
{
double d=0.0;
switch (m_TIOType)
{
case MTagType_Long: d=m_Long; break;
case MTagType_Double: d=m_Double; break;
case MTagType_String: d=SafeAtoF(m_String, 0); break;
};
return d;
}
void MTagIOValue::putDoubleSI(double D)
{
m_TIOType=MTagType_Double;
m_Double=D;
};
double MTagIOValue::getDoubleCnv(const MCnv * pCnv) const
{
double d=0.0;
switch (m_TIOType)
{
case MTagType_Long: d=m_Long; break;
case MTagType_Double: d=m_Double; break;
case MTagType_String: d=SafeAtoF(m_String, 0); break;
};
if (pCnv)
d= Cnvs[pCnv->Index]->Human(d, (LPSTR)pCnv->Text);
return d;
}
void MTagIOValue::putDoubleCnv(const MCnv * pCnv, double D)
{
if (pCnv)
D= Cnvs[pCnv->Index]->Normal(D, (LPSTR)pCnv->Text);
m_TIOType=MTagType_Double;
m_Double=D;
};
LPCSTR MTagIOValue::getString() const
{
switch (m_TIOType)
{
case MTagType_Long:
//return m_Long;
case MTagType_Double: //return m_Double;
_asm int 3;
return "???";
case MTagType_String: return m_String;
};
return 0;
}
void MTagIOValue::putString(LPCSTR S)
{
m_TIOType=MTagType_String;
m_String=S;
};
void MTagIOValue::Reset()
{
switch (m_TIOType)
{
case MTagType_Long: m_Long = 0; break;
case MTagType_Double: m_Double = 0.0; break;
case MTagType_String: m_String = ""; break;
}
};
CString MTagIOValue::AsString() const
{
CString S;
switch (m_TIOType)
{
case MTagType_Long: S.Format("%i", m_Long); break;
case MTagType_Double: S.Format("%.5f", m_Double); break;
case MTagType_String: S=m_String; break;
}
return S;
};
//=========================================================================
//
// //
//=========================================================================
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
9
],
[
11,
74
],
[
76,
183
],
[
186,
186
],
[
188,
188
],
[
195,
287
],
[
289,
312
],
[
314,
336
],
[
338,
376
],
[
378,
391
],
[
394,
476
],
[
478,
500
],
[
502,
572
],
[
574,
595
],
[
597,
669
],
[
671,
712
],
[
715,
985
],
[
987,
1063
],
[
1065,
1143
],
[
1145,
1345
],
[
1351,
1355
],
[
1360,
1480
],
[
1482,
1490
],
[
1497,
1497
],
[
1499,
1834
],
[
1851,
1855
],
[
1859,
1861
],
[
1863,
2285
],
[
2289,
2299
],
[
2306,
2309
],
[
2312,
2387
],
[
2584,
2584
]
],
[
[
10,
10
],
[
75,
75
],
[
184,
185
],
[
187,
187
],
[
189,
194
],
[
288,
288
],
[
313,
313
],
[
337,
337
],
[
377,
377
],
[
392,
393
],
[
477,
477
],
[
501,
501
],
[
573,
573
],
[
596,
596
],
[
670,
670
],
[
713,
714
],
[
986,
986
],
[
1064,
1064
],
[
1144,
1144
],
[
1346,
1350
],
[
1356,
1359
],
[
1481,
1481
],
[
1491,
1496
],
[
1498,
1498
],
[
1835,
1850
],
[
1856,
1858
],
[
1862,
1862
],
[
2286,
2288
],
[
2300,
2305
],
[
2310,
2311
],
[
2388,
2583
]
]
] |
31fb84ea66ab0d1d74ac3ea67ae1bb2c4ab19c5c
|
1db5ea1580dfa95512b8bfa211c63bafd3928ec5
|
/MicroManager.cpp
|
bb6e50a07b20a1e481ad5508397fbef4ec801ec3
|
[] |
no_license
|
armontoubman/scbatbot
|
3b9dd4532fbb78406b41dd0d8f08926bd710ad7b
|
bee2b0bf0281b8c2bd6edc4c10a597041ea4be9b
|
refs/heads/master
| 2023-04-18T12:08:13.655631 | 2010-09-17T23:03:26 | 2010-09-17T23:03:26 | 361,411,133 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 56,526 |
cpp
|
#pragma once
#include "MicroManager.h"
#include <BWAPI.h>
#include <set>
#include <map>
#include <UnitGroup.h>
#include <BuildOrderManager.h>
#include "EnemyUnitDataManager.h"
#include "EnemyUnitData.h"
#include "TaskManager.h"
#include "Task.h"
#include "HighCommand.h"
#include "EigenUnitDataManager.h"
#include "Util.h"
#include <sstream>
#include "WantBuildManager.h"
MicroManager::MicroManager()
{
}
MicroManager::MicroManager(EnemyUnitDataManager* e, TaskManager* t, HighCommand* h, EigenUnitDataManager* ei, WantBuildManager* w)
{
this->eudm = e;
this->tm = t;
this->hc = h;
this->eiudm = ei;
this->wbm = w;
}
BWAPI::Position MicroManager::moveAway(BWAPI::Unit* unit, double radius)
{
// huidige positie van de unit die gaat moven
BWAPI::Position current = unit->getPosition();
// alle enemies in de gekozen radius
BWAPI::Position enemiescenter = this->eudm->getUG().inRadius(radius, unit->getPosition()).getCenter();
int newx = current.x() - (enemiescenter.x() - current.x());
int newy = current.y() - (enemiescenter.y() - current.y());
// mogelijk een verdere afstand als de onderlinge afstand klein is. Maar wellicht vuurt dit vaak genoeg.
return BWAPI::Position(newx, newy).makeValid();
}
BWAPI::Position MicroManager::moveAway(BWAPI::Unit* unit)
{
return moveAway(unit, dist(13));
}
void MicroManager::moveAway(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator it=units.begin(); it!=units.end(); it++)
{
(*it)->move(moveAway((*it)));
}
}
BWAPI::Position MicroManager::splitUp(BWAPI::Unit* unit)
{
// huidige positie van de unit die gaat moven
BWAPI::Position current = unit->getPosition();
// alle enemies in de gekozen radius
UnitGroup allies = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(dist(3), current);
allies.erase(unit);
BWAPI::Position alliescenter = allies.getCenter();
int newx = current.x() - (alliescenter.x() - current.x());
int newy = current.y() - (alliescenter.y() - current.y());
// mogelijk een verdere afstand als de onderlinge afstand klein is. Maar wellicht vuurt dit vaak genoeg.
return BWAPI::Position(newx, newy).makeValid();
}
void MicroManager::splitUp(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator it=units.begin(); it!=units.end(); it++)
{
(*it)->move(splitUp(*it));
}
}
std::set<BWAPI::Position> MicroManager::getAdjacentPositions(BWAPI::Position p)
{
std::set<BWAPI::Position> result;
int factor = dist(10); // was 1
result.insert(BWAPI::Position(p.x()-factor, p.y()+factor));
result.insert(BWAPI::Position(p.x(), p.y()+factor));
result.insert(BWAPI::Position(p.x()+factor, p.y()+factor));
result.insert(BWAPI::Position(p.x()-factor, p.y()));
result.insert(BWAPI::Position(p.x()+factor, p.y()));
result.insert(BWAPI::Position(p.x()-factor, p.y()-factor));
result.insert(BWAPI::Position(p.x(), p.y()-1));
result.insert(BWAPI::Position(p.x()+factor, p.y()-factor));
return result;
}
std::set<BWAPI::Position> MicroManager::sanitizePositions(std::set<BWAPI::Position> ps)
{
std::set<BWAPI::Position> result;
for(std::set<BWAPI::Position>::iterator it = ps.begin(); it != ps.end(); it++)
{
if(
BWAPI::Broodwar->isWalkable(it->x(), it->y()) &&
BWAPI::Broodwar->unitsOnTile(it->x(), it->y()).empty() == true
)
{
result.insert(BWAPI::Position(it->x(), it->y()));
}
}
return result;
}
bool MicroManager::overlordSupplyProvidedSoon()
{
return
BWAPI::Broodwar->self()->supplyUsed() < BWAPI::Broodwar->self()->supplyTotal() - BWAPI::UnitTypes::Zerg_Overlord.supplyProvided() ||
(this->wbm->countEggsMorphingInto(BWAPI::UnitTypes::Zerg_Overlord)+this->wbm->buildList.count(BWAPI::UnitTypes::Zerg_Overlord)) > 0;
}
bool MicroManager::enemyInRange(BWAPI::Position p, double radius, int type)
{
return enemiesInRange(p, radius, type).size() > 0;
}
bool MicroManager::enemyInRange(BWAPI::Position p)
{
return enemyInRange(p, dist(13), 0);
}
UnitGroup MicroManager::enemiesInRange(BWAPI::Position p, double radius, int type) // 0 beide, 1 ground, 2 flyer
{
std::map<BWAPI::Unit*, EnemyUnitData> enemies = this->eudm->getEnemyUnitsInRadius(radius, p);
UnitGroup result;
for each(std::pair<BWAPI::Unit*, EnemyUnitData> enemy in enemies)
{
if(type == 0)
{
result.insert(enemy.first);
}
if(type == 1)
{
if(!enemy.second.unitType.isFlyer())
{
result.insert(enemy.first);
}
}
if(type == 2)
{
if(enemy.second.unitType.isFlyer())
{
result.insert(enemy.first);
}
}
}
return result;
}
bool MicroManager::containsDetector(UnitGroup ug)
{
if(
ug(Observer).size() > 0 ||
ug(Photon_Cannon).size() > 0 ||
ug(Missile_Turret).size() > 0 ||
ug(Science_Vessel).size() > 0 ||
ug(Overlord).size() > 0 ||
ug(Spore_Colony).size() > 0
)
{
return true;
}
else {
return false;
}
}
int MicroManager::compareArmySize(UnitGroup x, UnitGroup y)
{
return x.size() - y.size();
}
BWAPI::Unit* MicroManager::nearestUnit(BWAPI::Position pos, UnitGroup ug)
{
double besteAfstand = -1;
BWAPI::Unit* besteUnit = NULL;
for(std::set<BWAPI::Unit*>::iterator it = ug.begin(); it != ug.end(); it++)
{
if(besteAfstand == -1)
{
besteAfstand = (*it)->getDistance(pos);
besteUnit = (*it);
}
else
{
if((*it)->getDistance(pos) < besteAfstand)
{
besteAfstand = (*it)->getDistance(pos);
besteUnit = (*it);
}
}
}
return besteUnit;
}
UnitGroup MicroManager::enemiesInSeekRange(BWAPI::Position p, double radius, int type) // 0 beide, 1 ground, 2 flyer
{
UnitGroup ug = UnitGroup();
std::map<BWAPI::Unit*, EnemyUnitData> databank = this->eudm->getData();
for(std::map<BWAPI::Unit*, EnemyUnitData>::iterator it = databank.begin(); it != databank.end(); it++)
{
if(p.getDistance(it->second.position) < radius)
{
if(type == 0)
{
ug.insert(it->first);
}
if(type == 1 && !it->first->getType().isFlyer())
{
ug.insert(it->first);
}
if(type == 2 && it->first->getType().isFlyer())
{
ug.insert(it->first);
}
}
}
return ug;
}
bool MicroManager::alliesCanAttack(BWAPI::Position p, UnitGroup enemies)
{
UnitGroup allies = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(dist(9), p);
if(allies.size() == 0) return false;
bool alliesGroundWeapons = false;
bool alliesAirWeapons = false;
bool enemiesAir = false;
bool enemiesGround = false;
if(enemies(isFlyer).size() > 0) enemiesAir = true;
if((enemies - enemies(isFlyer)).size() > 0) enemiesGround = true;
for(std::set<BWAPI::Unit*>::iterator it = allies.begin(); it != allies.end(); it++)
{
if((*it)->getType().groundWeapon().targetsGround())
{
alliesGroundWeapons = true;
}
if((*it)->getType().airWeapon().targetsAir())
{
alliesAirWeapons = true;
}
}
if(enemiesAir && alliesAirWeapons) return true;
if(enemiesGround && alliesGroundWeapons) return true;
return false;
}
/*
BWAPI::Unit* MicroManager::harvest(BWAPI::Unit* unit) // returnt een unit terug waarop rechtermuisgeklikt mag worden
{
UnitGroup mineralDrones = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(isGatheringMinerals);
UnitGroup gasDrones = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(MoveToGas, WaitForGas, HarvestGas, ReturnGas); // has Order gather gas moet er nog bij of juist ipv
UnitGroup extractors = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Extractor)(isCompleted);
if (gasDrones.size() < extractors.size()*3)
{
if (mineralDrones.size()<5)
{
if (mineralDrones.size()<3 || gasDrones.size() >= extractors.size()*2)
{
return mineWhere(unit);
}
else
{
return gasWhere(unit);
}
}
else
{
return gasWhere(unit);
}
}
else
{
if (gasDrones.size() > extractors.size()*3) // teveel gas enzo
{
if (unit->isCarryingGas())
{
return this->hc->getNearestHatchery(unit->getPosition());
}
else
{
return mineWhere(unit);
}
// return de gas terug enzo, rechtermuisklik op nearest hatchery
// mogelijke probleem hierbij is dat ze allemaal teruggaan, als carryinggas == returngas/gatheringGas
}
}
return mineWhere(unit);
}
*/
void MicroManager::mineWhere(BWAPI::Unit* unit)
{
if (unit->isGatheringMinerals())
{
// unit->getTarget(); // vraag is, beweegt het dan telkens juist weer terug naar de patch of blijft het lekker gatheren? als het telkens terug gaat, is het mogelijk return null te doen? en anders wordt het complexer
}
else
{
UnitGroup minerals = getUnusedMineralsNearHatcheries(); // pak alle unused minerals die in de nabijheid van een hatchery bevinden
if(minerals.empty()) // voor als het vol is enzo
{
unit->move(this->hc->getNearestHatchery(unit->getPosition())->getPosition());
}
unit->gather(nearestUnitInGroup(unit, minerals));
}
}
void MicroManager::gasWhere(BWAPI::Unit* unit)
{
if (unit->isGatheringGas())
{
//return unit->getTarget();
}
else
{
UnitGroup extractors = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Extractor)(isCompleted);
UnitGroup result = extractors;
for(std::set<BWAPI::Unit*>::iterator it=extractors.begin(); it!=extractors.end(); it++)
{
if (UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone).inRadius(dist(6), (*it)->getPosition()).size()<3)
{
result.erase(*it); // ug met een unit ehh
}
}
if (result.empty())
{
unit->move(this->hc->getNearestHatchery(unit->getPosition())->getPosition());
}
unit->gather(nearestUnitInGroup(unit, result));
}
}
void MicroManager::gatherWhere(BWAPI::Unit* unit)
{
if ((unit->isGatheringGas()) || (unit->isConstructing()) || ((unit->isMoving()) && (!unit->isCarryingMinerals())) )
{
if (unit->isGatheringGas())
{
if (UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone)(isGatheringGas).inRadius(dist(5), unit->getPosition()).size()>3)
{
unit->stop();
}
}
}
else
{
UnitGroup extractors = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Extractor)(isCompleted);
UnitGroup result = extractors;
logc("(result = extractors) aantal extractors: ");
logc(this->hc->wantBuildManager->intToString(result.size()).c_str());
logc("\n");
if (UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone).size()>5)
{
for(std::set<BWAPI::Unit*>::iterator it=extractors.begin(); it!=extractors.end(); it++)
{
if(((UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone)(isGatheringGas).inRadius(dist(10), (*it)->getPosition()).size()+UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone)(GetTarget, *it).size()) > 2))
{
logc("erase extractor\n");
result.erase(*it); // ug met een unit ehh
}
}
if (!result.empty())
{
logc("!result.empty() gaat gas\n");
logc("!result.empty() aantal extractors: ");
logc(this->hc->wantBuildManager->intToString(result.size()).c_str());
logc("\n");
unit->gather(nearestUnitInGroup(unit, result)); // ga eerst naar extractor
return;
}
}
if (!unit->isGatheringMinerals())
{
result = getUnusedMineralsNearHatcheries();
if (result.empty())
{
unit->gather(nearestUnitInGroup(unit, UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals())));
return;
}
else
{
unit->gather(nearestUnitInGroup(unit, result));
return;
}
}
}
logc("einde gatherwhere\n");
}
UnitGroup MicroManager::getHatcheriesWithMinerals()
{
UnitGroup hatcheries = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Hatchery, Lair, Hive);
UnitGroup result = UnitGroup();
UnitGroup minerals = UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals());
for(std::set<BWAPI::Unit*>::iterator it=hatcheries.begin(); it!=hatcheries.end(); it++)
{
for(std::set<BWAPI::Unit*>::iterator mit=minerals.begin(); mit!=minerals.end(); mit++) // stond eerst it!=minerals.end(), lijkt me beetje raar als de rest mit staat? ***
{
if((*it)->getDistance(*mit) <= dist(8))
{
result.insert(*it);
break;
}
}
}
return result;
}
UnitGroup MicroManager::getUnusedMineralsNearHatcheries()
{
UnitGroup hatcheries = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Hatchery, Lair, Hive)(isCompleted);
UnitGroup result = UnitGroup();
UnitGroup minerals = UnitGroup::getUnitGroup(BWAPI::Broodwar->getMinerals());
for(std::set<BWAPI::Unit*>::iterator mit=minerals.begin(); mit!=minerals.end(); mit++)
{
for(std::set<BWAPI::Unit*>::iterator it=hatcheries.begin(); it!=hatcheries.end(); it++)
{
UnitGroup allies = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(dist(15), (*it)->getPosition()).not(Drone).not(Overlord).not(isBuilding);
UnitGroup effectivemining = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(dist(7), (*it)->getPosition())(Drone)(isGatheringMinerals);
UnitGroup mineralsnearby = minerals.inRadius(dist(10), (*it)->getPosition());
// idee is: per mineral check of er een hatchery in de buurt is, zo ja, check voor die hatchery of het wel een geldige basis is (i.e. geen enemies in de buurt of allies nearby) EN of er niet al genoeg drones in de buurt aant minen zijn.
if (((amountCanAttackGround(enemiesInRange((*it)->getPosition(), dist(10), 0)) < 5) || (allies.size()>4)) && effectivemining.size()<=mineralsnearby.size())
{
// als er niet al genoeg drones zijn voor de minerals && de basis is veilig && slechts per 1 hatchery checken of de mineral in de buurt van een hatchery bevindt.
// het wordt erg dubbelop.. maar op deze manier weet ik zeker dat een mineral niet 10x erin komt te staan, dat niet alle drones gewoon naar de dichtsbijzijnde gaat, etc.
//if((*it)->getDistance(*mit) <= dist(13) && !(*mit)->isBeingGathered())
if((*it)->getDistance(*mit) <= dist(13) && UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits())(Drone)(GetTarget, *mit).size() < 1)
{
result.insert(*mit);
break;
}
}
else
{
break;
}
}
}
return result;
}
UnitGroup* MicroManager::inRadiusUnitGroup(double radius, UnitGroup* ug)
{
UnitGroup* result= new UnitGroup();
for(std::set<BWAPI::Unit*>::iterator it=ug->begin(); it!=ug->end(); it++)
{
UnitGroup newunits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(radius, (*it)->getPosition());
result->insert(newunits.begin(), newunits.end());
}
return result;
}
UnitGroup* MicroManager::inRadiusUnitGroupUnitType(double radius, UnitGroup* ug, BWAPI::UnitType ut)
{
// return a unitgroup of the specified unittype that is in radius of a unit of a unit group;
UnitGroup* result= new UnitGroup();
for(std::set<BWAPI::Unit*>::iterator it=ug->begin(); it!=ug->end(); it++)
{
UnitGroup newunits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(radius, (*it)->getPosition())(GetType, ut);
result->insert(newunits.begin(), newunits.end()); // kan meerdere keren tot dezelfde UG worden toegevoegd?
}
return result;
}
bool MicroManager::tooSplitUp(double radius, UnitGroup* ug)
{
BWAPI::Position ugcenter = ug->getCenter();
int amount = 0;
for(std::set<BWAPI::Unit*>::iterator it=ug->begin(); it!=ug->end(); it++)
{
if ((*it)->getDistance(ugcenter) > radius && (*it)->getType() != BWAPI::UnitTypes::Zerg_Overlord)
{
amount++;
}
}
if (ug->size()/2 < amount)
{
return true;
}
return false;
}
void MicroManager::doMicro(std::set<UnitGroup*> listUG)
{
logc("\n\ndoMicro\n\n");
UnitGroup allSelfUnits = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits());
UnitGroup allEnemyUnits = this->eudm->getUG();
for(std::set<UnitGroup*>::iterator it=listUG.begin(); it!=listUG.end(); it++)
{
/* SCOURGE */
if((**it)(Scourge).size() > 0)
{
BWAPI::Unit* eerste = *((**it)(Scourge).begin());
UnitGroup airenemies = enemiesInRange(eerste->getPosition(), dist(7), 2);
UnitGroup allenemies = enemiesInRange(eerste->getPosition(), dist(7), 0);
if(eerste->isUnderStorm() || canAttackAir(allenemies) && airenemies.size() == 0)
{
(*it)->move(this->hc->getNearestHatchery(eerste->getPosition())->getPosition()); // move
}
else
{
if(airenemies.size() > 0)
{
if(canAttackAir(allenemies) || airenemies.size() > 2*(*it)->size()) // nakijken
{
moveAway(**it);
}
else
{
(*it)->attackUnit(*airenemies.begin());
}
}
else {
if(eerste->getDistance(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position) < dist(9))
{
for(std::set<BWAPI::Unit*>::iterator scourgeit=(*it)->begin(); scourgeit!=(*it)->end(); scourgeit++)
{
(*scourgeit)->move(splitUp(*scourgeit)); // kijk dit ff na aub
}
}
else
{
(*it)->attackMove(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position);
}
}
}
}
/* EINDE SCOURGE */
/* MUTALISK */
else if((**it)(Mutalisk).size() > 0)
{
BWAPI::Unit* eerste = nearestUnit(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position, (**it)(Mutalisk));
logx(eerste, " begin micro\n");
bool onderstorm = false;
// check of allemaal uit storm zijn, als er 1tje onder storm is, move to nearest base
for(std::set<BWAPI::Unit*>::iterator unitit=(*it)->begin(); unitit!=(*it)->end(); unitit++)
{
if ((*unitit)->isUnderStorm() || (((*unitit) != eerste) && canAttackAir(enemiesInRange((*unitit)->getPosition(), dist(6), 0)) && eerste->getDistance((*unitit)->getPosition()) > dist(4)) )
onderstorm = true;
}
if(onderstorm)
{
logx(eerste, " is under storm\n");
moveToNearestBase(**it);
}
else
{
if(eerste->getGroundWeaponCooldown() >= 15 || eerste->getAirWeaponCooldown() >= 15) // er staat op internet 30 is cooldown, en idee is dat ze niet pas terugkomen als cooldown ready is, maar gewoon simpel heen en weer enzo.
{
logx(eerste, " groundweap cd\n");
if(canAttackAir(enemiesInRange(eerste->getPosition(), dist(8), 0)))
{
logx(eerste, " enemies, moveaway\n");
moveAway(**it);
}
else
{
if(eerste->getDistance(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position) < dist(5))
{
logx(eerste, " vlakbij task, terug naar base\n");
moveToNearestBase(**it);
}
else
{
if (tooSplitUp(dist(3), (*it)))
{
(*it)->attackMove(nearestUnit((*it)->getCenter(), (**it))->getPosition());
}
else
{
logx(eerste, " gogo naar task\n");
(*it)->attackMove(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position); // move
}
}
}
}
else
{
logx(eerste, " groundweap klaar\n");
logx(eerste, " bij task\n");
UnitGroup enemies = enemiesInRange(eerste->getPosition(), dist(7), 0);
UnitGroup enemiesMilitary = enemiesInRange(eerste->getPosition(), dist(7), 0).not(isBuilding);
if (enemiesMilitary.size()>0)
{
BWAPI::Unit* nearestt = nearestUnit(eerste->getPosition(), enemiesMilitary);
if (nearestt->getDistance(eerste->getPosition()) < dist(4))
{
(*it)->attackUnit(nearestt);
}
else
{
(*it)->attackMove(nearestt->getPosition());
}
}
else
{
if (enemies.size()>0)
{
BWAPI::Unit* nearestt = nearestUnit(eerste->getPosition(), enemies);
if (nearestt->getDistance(eerste->getPosition()) < dist(4))
{
(*it)->attackUnit(nearestt);
}
else
{
(*it)->attackMove(nearestt->getPosition());
}
}
else
{
if(eerste->getDistance(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position) <= dist(1))
{
logx(eerste, " vlakbij task, terug naar base\n");
moveToNearestBase(**it);
}
else
{
if (tooSplitUp(dist(6), (*it)))
{
(*it)->attackMove(nearestUnit((*it)->getCenter(), (**it))->getPosition());
}
else
{
logx(eerste, " move naar task\n");
(*it)->attackMove(this->hc->planAssigner->vindTask(this->hc->hcplan, (*it)).position);
}
}
}
}
}
}
}
/* EINDE MUTALISK */
else
{
Task currentTask = this->hc->planAssigner->vindTask(this->hc->hcplan, *it);
for(std::set<BWAPI::Unit*>::iterator unitit=(*it)->begin(); unitit!=(*it)->end(); unitit++)
{
logc("doMicro for unit iterator ");
logc((*unitit)->getType().getName().c_str());
logc("\n");
//Task currentTask = this->hc->planAssigner->vindTask(this->hc->hcplan, this->hc->eigenUnitGroupManager->findUnitGroupWithUnit(*unitit));
logc("doMicro selecteer unittype\n");
/* NEW ZERGLING */
if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Zergling)
{
UnitGroup allies = UnitGroup::getUnitGroup(BWAPI::Broodwar->self()->getUnits()).inRadius(dist(12), (*unitit)->getPosition());
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(10), 1);
UnitGroup enemiesair = enemiesInRange((*unitit)->getPosition(), dist(7), 2);
if (MicroManager::amountCanAttackGround(enemiesair)>0 && MicroManager::amountCanAttackAir(allies)==0)
{
logx((*unitit), "moveaway van air enemies, geen support in de buurt\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
if (currentTask.type == 1)
{
logx((*unitit), "scout task\n");
if (enemiesInRange((*unitit)->getPosition(), dist(4), 0).not(isBuilding).size()>0)
{
logx((*unitit), "moveaway van enemies\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), "geen enemies\n");
if ((*unitit)->getDistance(currentTask.position) < dist(4) && BWAPI::Broodwar->isVisible(currentTask.position))
//if(BWTA::getGroundDistance((*unitit)->getTilePosition(), BWAPI::TilePosition(currentTask.position)) < dist(4))
{
logx((*unitit), "dichtbij task\n");
if (!(*unitit)->isMoving())
{
logx((*unitit), "staat stil, random lopen\n");
int x = (*unitit)->getPosition().x();
int y = (*unitit)->getPosition().y();
int factor = dist(10);
int newx = x + (((rand() % 30)-15)*factor);
int newy = y + (((rand() % 30)-15)*factor);
(*unitit)->move(BWAPI::Position(newx, newy).makeValid());
}
}
else
{
logx((*unitit), "move naar task\n");
(*unitit)->move(currentTask.position);
}
}
}
else
{
logx((*unitit), "geen scout task\n");
BWAPI::Unit* swarm = nearestSwarm((*unitit));
if(swarm != NULL && swarm->getPosition().getDistance((*unitit)->getPosition()) < dist(9))
{
logx((*unitit), " swarm in de buurt\n");
if(!isUnderDarkSwarm((*unitit)) && !(*unitit)->isAttacking())
{
logx((*unitit), " naar swarm\n");
(*unitit)->attackMove(swarm->getPosition()); // move
}
else
{
logx((*unitit), " onder swarm, attack enemy\n"); // wat als geen enemy? nullpointer!
UnitGroup enemiesonderswarm = enemiesInRange((*unitit)->getPosition(), dist(6), 1);
if (!(*unitit)->isAttacking() && enemiesonderswarm.size()>0)
{
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), enemiesonderswarm));
}
}
}
else
{
logx((*unitit), "outnumbered!\n");
if ((allies.size())<amountCanAttackGround(enemies.not(isWorker)))
{
logx((*unitit), "moveaway!\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), "niet outnumbered\n");
if (enemiesInRange((*unitit)->getPosition(), dist(3), 1).size()>0)
{
logx((*unitit), "ground enemy in range 3, nothing AI enzo\n");
// nothing AI enzo
}
else
{
logx((*unitit), "geen enemy in range 3\n");
if (enemies.size()>0)
{
logx((*unitit), "wel in range 10, attackmove\n");
BWAPI::Unit* nearest = nearestUnit((*unitit)->getPosition(), enemies);
(*unitit)->attackMove(nearest->getPosition());
}
else
{
logx((*unitit), "geen enemies\n");
if (tooSplitUp(dist(7), *it))
{
logx((*unitit), "groep is tooSplitUp, move naar center unit\n");
(*unitit)->attackMove(nearestUnit((*it)->getCenter(), (**it))->getPosition());
}
else
{
logx((*unitit), "groep is bij elkaar, move naar task\n");
(*unitit)->attackMove(currentTask.position);
}
}
}
}
}
}
}
}
else
{
/* ULTRALISK */
if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Ultralisk)
{
if((*unitit)->isIrradiated())
{
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(30), 1);
if(enemies.size()>0)
{
(*unitit)->attackMove(nearestUnit((*unitit)->getPosition(), enemies)->getPosition());
}
}
else
{
if((*unitit)->isUnderStorm())
{
(*unitit)->attackMove(moveAway(*unitit));
}
else
{
UnitGroup swarms = UnitGroup::getUnitGroup(BWAPI::Broodwar->getAllUnits())(Dark_Swarm).inRadius(dist(9), (*unitit)->getPosition());
if(swarms.size() > 0)
{
if(isUnderDarkSwarm(*unitit))
{
// doe niks Game AI lost zelf op
}
else
{
BWAPI::Unit* swarm = nearestSwarm(*unitit);
if(swarm != NULL)
{
(*unitit)->move(swarm->getPosition());
}
}
}
else
{
if(currentTask.type != -1 && (*unitit)->getDistance(currentTask.position) < dist(6) && BWAPI::Broodwar->isVisible(currentTask.position) )
{
if(enemiesInRange((*unitit)->getPosition(), dist(6), 0).size() > 0)
{
(*unitit)->attackUnit(*enemiesInRange((*unitit)->getPosition(), dist(6), 0).begin());
}
else
{
(*unitit)->attackMove(currentTask.position);
}
}
else
{
(*unitit)->attackMove(currentTask.position);
}
}
}
}
}
/* EINDE ULTRALISK */
/* LURKER */
else if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Lurker)
{
if(!(*unitit)->isBurrowed())
{
logc("lurker unburrowed\n");
if((*unitit)->isUnderStorm())
{
logc("lurker storm\n");
moveToNearestBase(*unitit);
}
else
{
if((*unitit)->getPosition().getDistance(currentTask.position) > dist(6) && enemiesInRange((*unitit)->getPosition(), dist(8), 0).size() == 0)
{
logc("lurker movetask\n");
(*unitit)->move(currentTask.position);
}
else
{
logc("burrow\n");
(*unitit)->burrow();
}
}
}
else
{
if((*unitit)->isUnderStorm())
{
logc("lurker stormunburrow\n");
(*unitit)->unburrow();
}
else
{
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(6), 0);
if(enemiesInRange((*unitit)->getPosition(), dist(8), 0).size() > 0)
{
logc("lurker predetectie\n");
if(!this->eiudm->unitIsSeen(*unitit))
{
logc("lurker notdetec\n");
if(enemies.size() > 3)
{
if(enemies(Marine).size() > 0 || enemies(isWorker).size() > 0 || enemies(Zealot).size() > 0 || enemies(Medic).size() > 0 || enemies(Zergling).size() > 0)
{
if(nearestUnit((*unitit)->getPosition(), enemies)->getPosition().getDistance((*unitit)->getPosition()) < dist(3))
{
logc("lurker attackinseen\n");
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), enemies)); // mogelijke changen
}
else
{
// hold lurker
std::set<BWAPI::Unit*> holdset;
holdset.insert(*unitit);
UnitGroup olords = allSelfUnits(Overlord)(isIdle);
logc("lurker preholdpos\n");
if(olords.size() > 0)
{
logc("lurker holdposdone\n");
holdset.insert(*olords.begin());
UnitGroup holdgroup = UnitGroup::getUnitGroup(holdset);
holdgroup.holdPosition();
}
}
}
else
{
logc("lurker attackgewoon\n");
(*unitit)->attackUnit(*enemies.begin());
}
}
else
{
logc("lurker structureattack\n");
UnitGroup structures = allEnemyUnits(isBuilding);
if(structures.size() > 0)
{
BWAPI::Unit* neareststructure = nearestUnit((*unitit)->getPosition(), structures);
if((*it)->getCenter().getDistance(neareststructure->getPosition()) < dist(10))
{
(*unitit)->attackUnit(neareststructure);
}
}
}
}
else
{
logc("lurker detected\n");
//(*unitit)->stop(); // mogelijk moet dit anders als de micro zo vaak hier langs komt dat hij gewoon niet eens aanvalt
// hold lurker
std::set<BWAPI::Unit*> holdset;
holdset.insert(*unitit);
UnitGroup olords = allSelfUnits(Overlord)(isIdle);
logc("lurker preholdpos\n");
if(olords.size() > 0)
{
logc("lurker holdposdone\n");
holdset.insert(*olords.begin());
UnitGroup holdgroup = UnitGroup::getUnitGroup(holdset);
holdgroup.holdPosition();
}
}
}
else
{
if((*unitit)->getPosition().getDistance(currentTask.position) > dist(6))
{
logc("lurker unburrowmoven\n");
(*unitit)->unburrow();
}
else
{
// hold lurker
std::set<BWAPI::Unit*> holdset;
holdset.insert(*unitit);
UnitGroup olords = allSelfUnits(Overlord)(isIdle);
logc("lurker andereprehold\n");
if(olords.size() > 0)
{
holdset.insert(*olords.begin());
UnitGroup holdgroup = UnitGroup::getUnitGroup(holdset);
holdgroup.holdPosition();
logc("lurker anderehold\n");
}
}
}
}
}
logc("lurker einde\n");
}
/* EINDE LURKER */
/* DEFILER */
else if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Defiler)
{
if((*unitit)->isUnderStorm())
{
moveToNearestBase(*unitit);
}
else
{
if(allSelfUnits.inRadius(dist(10), (*unitit)->getPosition()).not(Defiler).size() > 3)
{
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(9), 0);
bool atleastoneunderswarm = false;
for(std::set<BWAPI::Unit*>::iterator swarmit=enemies.begin(); swarmit!=enemies.end(); swarmit++)
{
if(isUnderDarkSwarm(*swarmit))
{
atleastoneunderswarm = true;
}
}
if(!atleastoneunderswarm)
{
int energy = (*unitit)->getEnergy();
int energynodig = BWAPI::TechTypes::Dark_Swarm.energyUsed();
if(energy < energynodig)
{
UnitGroup zerglings = allSelfUnits(Zergling);
if(zerglings.size() > 0)
{
BWAPI::Unit* slachtoffer = nearestUnitInGroup((*unitit), zerglings);
(*unitit)->useTech(BWAPI::TechTypes::Consume, slachtoffer);
}
else
{
(*unitit)->move(nearestSwarm(*unitit)->getPosition());
}
}
else
{
BWAPI::Unit* nenuds = nearestEnemyNotUnderDarkSwarm(*unitit);
BWAPI::Unit* swarm = nearestSwarm(nenuds);
if(nenuds != NULL && swarm != NULL)
{
if(nenuds->getPosition().getDistance(swarm->getPosition()) > dist(5))
{
int x = abs(nenuds->getPosition().x() - swarm->getPosition().x());
int y = abs(nenuds->getPosition().y() - swarm->getPosition().y());
BWAPI::Position pos = BWAPI::Position(x, y);
(*unitit)->useTech(BWAPI::TechTypes::Dark_Swarm, pos);
}
else
{
(*unitit)->useTech(BWAPI::TechTypes::Dark_Swarm, nenuds);
}
}
}
}
else
{
// niks
}
}
else
{
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(9), 0);
if(enemies.size() > 0)
{
UnitGroup buildings = allSelfUnits(isBuilding).inRadius(dist(5), (*unitit)->getPosition());
if(buildings.size() > 0)
{
(*unitit)->useTech(BWAPI::TechTypes::Dark_Swarm, (*unitit));
}
else
{
moveToNearestBase(*unitit);
}
}
else
{
(*unitit)->move(currentTask.position);
}
}
}
}
/* EINDE DEFILER */
/* OVERLORD */
else if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Overlord)
{
logx((*unitit), "\n");
if((*unitit)->isUnderStorm())
{
logx((*unitit), " under storm moveAway\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), std::string(" task.type=").append(intToString(currentTask.type)).append("\n").c_str());
if(currentTask.type == 1 || currentTask.type == 4 || currentTask.type == 2)
{
logx((*unitit), " type=1||4\n");
BWAPI::Unit* nearAir = nearestEnemyThatCanAttackAir(*unitit);
logx((*unitit), "nearAir ok\n");
// de volgende if heeft geen else, hij gaat er niet in, maar is dan klaar met de micro
if(nearAir != NULL && canAttackAir(enemiesInRange((*unitit)->getPosition(), dist(10), 0)))
{
logx((*unitit), " moveAway\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), "check stealths\n");
UnitGroup stealths = allEnemyUnits(isCloaked);
BWAPI::Unit* neareststealth = nearestUnit((*unitit)->getPosition(), stealths);
logx((*unitit), "check stealths ok\n");
if(neareststealth != NULL)
{
logx((*unitit), " stealth gezien\n");
(*unitit)->move(neareststealth->getPosition());
}
else
{
logx((*unitit), "check dropships\n");
UnitGroup dropships = allEnemyUnits(Dropship) + allEnemyUnits(Shuttle);
dropships = dropships.inRadius(dist(10), (*unitit)->getPosition());
if(dropships.size() > 0)
{
logx((*unitit), " dropship gezien\n");
(*unitit)->move(nearestUnit((*unitit)->getPosition(), dropships)->getPosition());
}
else
{
if ((*unitit)->getPosition().getDistance(currentTask.position) < dist(6))
{
if (!(*unitit)->isMoving())
{
int x = (*unitit)->getPosition().x();
int y = (*unitit)->getPosition().y();
int factor = dist(10);
int newx = x + (((rand() % 30)-15)*factor);
int newy = y + (((rand() % 30)-15)*factor);
(*unitit)->move(BWAPI::Position(newx, newy));
}
}
else
{
logx((*unitit), " geen dropship, move naar task\n");
(*unitit)->move(currentTask.position);
}
}
}
}
}
else
{
{
UnitGroup overlordsnearby = allSelfUnits(Overlord).inRadius(dist(10), (*unitit)->getPosition());
if(overlordsnearby.size() > 1)
{
logx((*unitit), " andere overlord\n");
if(canAttackAir(enemiesInRange((*unitit)->getPosition(), dist(8), 0)))
{
logx((*unitit), " canAttackAir moveAway\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
if (!(*unitit)->isMoving())
{
logx((*unitit), " splitUp\n");
(*unitit)->move(splitUp(*unitit));
}
}
}
else
{
UnitGroup buildings = allSelfUnits(isBuilding).inRadius(dist(15), (*unitit)->getPosition());
if(buildings.size() > 0)
{
if (!(*unitit)->isMoving())
{
logx((*unitit), " building random\n");
// als dit elk frame gebeurt, krijgt hij elk frame een nieuwe positie -> stuiterbal
int x = (*unitit)->getPosition().x();
int y = (*unitit)->getPosition().y();
int factor = dist(10);
int newx = x + (((rand() % 30)-15)*factor);
int newy = y + (((rand() % 30)-15)*factor);
(*unitit)->move(BWAPI::Position(newx, newy));
}
}
else
{
logx((*unitit), " eigen building\n");
BWAPI::Unit* nearestbuilding = nearestUnit((*unitit)->getPosition(), allSelfUnits(isBuilding));
(*unitit)->move(nearestbuilding->getPosition());
}
}
}
}
}
}
/* EINDE OVERLORD */
/* DRONE */
else if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Drone)
{
/*logx("\n\ndoMicro drone ", (*unitit), "\n");
if(this->wbm->bouwdrones.count(*unitit) > 0)
{
logx((*unitit), " drone is aan het bouwen, skip\n");
continue;
}*/
if((*unitit)->isUnderStorm())
{
logx((*unitit), " under storm moveAway\n");
moveToNearestBase(*unitit);
}
else
{
if(currentTask.type != 1)
{
logx((*unitit), " task.type != 1\n");
if(canAttackGround(enemiesInRange((*unitit)->getPosition(), dist(5), 0)) || this->eiudm->lostHealthThisFrame(*unitit))
{
logx((*unitit), " ground enemies of geraakt\n");
UnitGroup allyAirInRange = allSelfUnits(isFlyer).inRadius(dist(7), (*unitit)->getPosition());
UnitGroup dronesInRange = allSelfUnits(Drone).inRadius(dist(7), (*unitit)->getPosition());
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(7), 0);
if(!canAttackGround(allyAirInRange) && enemies.size()*2 <= dronesInRange.size())
{
logx((*unitit), " drone rage\n");
BWAPI::Unit* target = getVisibleUnit(enemies);
if(target != NULL)
{
(*unitit)->attackUnit(target);
}
else
{
(*unitit)->move(moveAway(*unitit));
}
}
else
{
UnitGroup detectorsInRange = enemiesInRange((*unitit)->getPosition(), dist(10), 0)(isDetector);
if(BWAPI::Broodwar->self()->hasResearched(BWAPI::TechTypes::Burrowing) && detectorsInRange.size() == 0)
{
logx((*unitit), " geen detectors, wel burrow\n");
(*unitit)->burrow();
}
else
{
UnitGroup militaryInRange = allSelfUnits.inRadius(dist(8), (*unitit)->getPosition()).not(isWorker)(canAttack);
if(militaryInRange.size() > 0)
{
logx((*unitit), " military \n");
(*unitit)->rightClick(nearestUnit((*unitit)->getPosition(), militaryInRange)->getPosition());
}
else
{
logx((*unitit), " geen military moveAway\n");
(*unitit)->move(moveAway(*unitit));
}
}
}
}
else
{
logx((*unitit), " harvestcheck\n");
gatherWhere(*unitit);
logx((*unitit), " harvestdone\n");
}
}
else
{
logx((*unitit), " task.type = 1\n");
if(canAttackGround(enemiesInRange((*unitit)->getPosition(), dist(7), 0)))
{
logx((*unitit), " enemies moveAway\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
if((*unitit)->getPosition().getDistance(currentTask.position) < dist(7))
{
logx((*unitit), " moveToNearestBase\n");
moveToNearestBase(*unitit);
}
else
{
logx((*unitit), " naar task\n");
(*unitit)->move(currentTask.position);
}
}
}
}
if((*unitit)->isIdle()==true || (*unitit)->getOrder() == BWAPI::Orders::None || (*unitit)->getOrder() == BWAPI::Orders::Nothing)
{
logx((*unitit), " harvestcheckidle\n");
gatherWhere(*unitit);
logx((*unitit), " harvestdonewasidle\n");
}
}
/* EINDE DRONE */
/* HYDRALISK */
else if((*unitit)->getType() == BWAPI::UnitTypes::Zerg_Hydralisk)
{
logx((*unitit), " start\n");
if((*unitit)->isUnderStorm())
{
logx((*unitit), " storm\n");
(*unitit)->move(moveAway(*unitit, dist(10)));
}
else
{
UnitGroup allEnemies = allEnemyUnits;
UnitGroup allMelee = allEnemies(Drone) + allEnemies(Zealot) + allEnemies(Zergling) + allEnemies(SCV) + allEnemies(Probe) + allEnemies(Ultralisk);
allMelee = allMelee.inRadius(dist(3), (*unitit)->getPosition());
BWAPI::Unit* swarm = nearestSwarm(*unitit);
logx((*unitit), " prenullswarm\n");
if(swarm != NULL && swarm->getPosition().getDistance((*unitit)->getPosition()) < dist(10) && allMelee.size() == 0)
{
BWAPI::Unit* swarm = nearestSwarm(*unitit);
if(!isUnderDarkSwarm(*unitit) && swarm != NULL)
{
logx((*unitit), " darkswarm nearby\n");
(*unitit)->attackMove(swarm->getPosition());
}
else
{
UnitGroup enemies = enemiesInRange((*unitit)->getPosition(), dist(10), 0);
BWAPI::Unit* target = NULL;
for(std::set<BWAPI::Unit*>::iterator enit=enemies.begin(); enit!=enemies.end(); enit++)
{
if(!isUnderDarkSwarm(*enit))
{
target = *enit;
break;
}
}
if(target != NULL)
{
(*unitit)->attackUnit(target);
}
}
}
else
{
logx((*unitit), " Pre samen eerst\n");
if(allSelfUnits(Hydralisk).inRadius(dist(6), (*unitit)->getPosition()).size() > 1)
{
logx((*unitit), " zijnsamen\n");
int allies = allSelfUnits.inRadius(dist(9), (*unitit)->getPosition()).size();
int enemies = allEnemyUnits.inRadius(dist(8), (*unitit)->getPosition()).not(isBuilding).not(isWorker).size();
logx((*unitit), " samenpreif\n");
if(enemies * 1.5 > allies)
{
if((*unitit)->getGroundWeaponCooldown() != 0)
{
logx((*unitit), " groundweapon niet ready\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), " val aan\n");
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), allEnemyUnits.inRadius(dist(15), (*unitit)->getPosition())));
}
}
else
{
if((*unitit)->getPosition().getDistance(currentTask.position) > dist(5))
{
logx((*unitit), " distancecheck\n");
if(enemiesInRange((*unitit)->getPosition(), dist(6), 0).size() > 0)
{
logx((*unitit), " er zijn enemies\n");
BWAPI::Unit* nearesttarget = nearestUnit((*unitit)->getPosition(), allEnemyUnits.inRadius(dist(6), (*unitit)->getPosition()));
if(nearesttarget != NULL && nearesttarget->getPosition().getDistance((*unitit)->getPosition()) <= dist(6))
{
/*logx((*unitit), " nearest check\n");
if(allSelfUnits(Hydralisk).inRadius(dist(9), nearesttarget->getPosition()).size() > 0)
{
logx((*unitit), " moveaway ofzo\n");
(*unitit)->move(moveAway(*unitit));
}
else
{*/
if((*unitit)->getGroundWeaponCooldown() != 0)
{
logx((*unitit), " moveaway not rdy\n");
(*unitit)->move(currentTask.position);
}
else
{
logx((*unitit), " val nogmaals aan\n");
(*unitit)->attackUnit(nearesttarget);
}
//}
}
else
{
if((*unitit)->getGroundWeaponCooldown() != 0)
{
logx((*unitit), " move to task not ready\n");
(*unitit)->move(currentTask.position);
}
else
{
logx((*unitit), " attack 3\n");
BWAPI::Unit* attack3nearest = nearestUnit((*unitit)->getPosition(), allEnemyUnits);
if(attack3nearest != NULL)
{
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), allEnemyUnits));
}
else
{
(*unitit)->move(currentTask.position);
}
}
}
}
else
{
logx((*unitit), " attackmove task1\n");
(*unitit)->attackMove(currentTask.position);
}
}
else
{
if(enemiesInRange((*unitit)->getPosition(), dist(6), 0).size() > 0)
{
logx((*unitit), " anderedistance\n");
BWAPI::Unit* nearesttarget = nearestUnit((*unitit)->getPosition(), allEnemyUnits.inRadius(dist(6), (*unitit)->getPosition()));
if(nearesttarget->getPosition().getDistance((*unitit)->getPosition()) <= dist(6))
{
if((*unitit)->getGroundWeaponCooldown() != 0)
{
logx((*unitit), " notrdy2\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), " attack 3\n");
(*unitit)->attackUnit(nearesttarget);
}
}
else
{
if((*unitit)->getGroundWeaponCooldown() != 0)
{
logx((*unitit), " notrdy3\n");
(*unitit)->move(moveAway(*unitit));
}
else
{
logx((*unitit), " attack 4\n");
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), allEnemyUnits));
}
}
}
else
{
logx((*unitit), " moveway4\n");
(*unitit)->move(moveAway(*unitit));
}
}
}
}
else
{
logx((*unitit), " met weinig\n");
UnitGroup nearEnemies = enemiesInRange((*unitit)->getPosition(), dist(9), 0);
if(nearEnemies.size() > 0 && canAttackGround(nearEnemies))
{
logx((*unitit), " weinig en enemy\n");
(*unitit)->attackUnit(nearestUnit((*unitit)->getPosition(), nearEnemies));
}
else
{
if (tooSplitUp(dist(8), (*it)))
{
logc("split up\n");
(*unitit)->attackMove(nearestUnit((*it)->getCenter(), (**it))->getPosition());
}
else
{
logx((*unitit), " gogotask\n");
(*unitit)->attackMove(currentTask.position);
}
}
}
}
}
logx((*unitit), " eind\n ");
}
/* EINDE HYDRALISK */
}
}
}
}
}
void MicroManager::moveToNearestBase(BWAPI::Unit* unit)
{
BWAPI::Unit* nearest = hc->getNearestHatchery(unit->getPosition());
if (unit->getPosition().getDistance(nearest->getPosition()) > dist(5)) // voorkomt dat ze buggen
{
unit->move(nearest->getPosition());
}
}
void MicroManager::moveToNearestBase(std::set<BWAPI::Unit*> units)
{
BWAPI::Unit* nearest = hc->getNearestHatchery(UnitGroup::getUnitGroup(units).getCenter());
if (UnitGroup::getUnitGroup(units).getCenter().getDistance(nearest->getPosition()) > dist(5))
{
UnitGroup::getUnitGroup(units).move(nearest->getPosition()); // move
}
}
bool MicroManager::isUnderDarkSwarm(BWAPI::Unit* unit)
{
UnitGroup darkSwarms = UnitGroup::getUnitGroup(BWAPI::Broodwar->getAllUnits())(Dark_Swarm);
return darkSwarms.inRadius(dist(5), unit->getPosition()).size() > 0;
}
bool MicroManager::canAttackAir(BWAPI::Unit* unit)
{
return unit->getType().airWeapon().targetsAir();
}
bool MicroManager::canAttackGround(BWAPI::Unit* unit)
{
return unit->getType().groundWeapon().targetsGround();
}
bool MicroManager::canAttackAir(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
if(canAttackAir(*it))
{
return true;
}
}
return false;
}
bool MicroManager::canAttackGround(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
if(canAttackGround(*it))
{
return true;
}
}
return false;
}
int MicroManager::amountCanAttackAir(std::set<BWAPI::Unit*> units)
{
int amount = 0;
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
if(canAttackAir(*it))
{
amount++;
}
}
return amount;
}
int MicroManager::amountCanAttackGround(std::set<BWAPI::Unit*> units)
{
int amount = 0;
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
if(canAttackGround(*it))
{
amount++;
}
}
return amount;
}
double MicroManager::minimalDistanceToGroup(BWAPI::Unit* unit, std::set<BWAPI::Unit*> units)
{
double minimalDistance = -1;
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
double currentDistance = unit->getPosition().getDistance((*it)->getPosition());
if(minimalDistance == -1)
{
minimalDistance = currentDistance;
}
else if(currentDistance < minimalDistance)
{
minimalDistance = currentDistance;
}
}
return minimalDistance;
}
BWAPI::Unit* MicroManager::nearestUnitInGroup(BWAPI::Unit* unit, std::set<BWAPI::Unit*> units)
{
double minimalDistance = -1;
BWAPI::Unit* nearest = NULL;
for(std::set<BWAPI::Unit*>::iterator it = units.begin(); it != units.end(); it++)
{
double currentDistance = unit->getPosition().getDistance((*it)->getPosition());
if(minimalDistance == -1)
{
minimalDistance = currentDistance;
nearest = *it;
}
else if(currentDistance < minimalDistance)
{
minimalDistance = currentDistance;
nearest = *it;
}
}
return nearest;
}
BWAPI::Unit* MicroManager::nearestEnemyThatCanAttackAir(BWAPI::Unit* unit)
{
BWAPI::Unit* enemy = NULL;
double distance = -1;
std::map<BWAPI::Unit*, EnemyUnitData> enemies = this->eudm->getData();
for(std::map<BWAPI::Unit*, EnemyUnitData>::iterator it=enemies.begin(); it!=enemies.end(); it++)
{
double currentDistance = unit->getPosition().getDistance(it->second.lastKnownPosition);
if(it->second.unitType.airWeapon().targetsAir() || it->second.unitType.groundWeapon().targetsAir())
{
if(distance == -1)
{
enemy = it->first;
distance = currentDistance;
}
else if(currentDistance < distance)
{
enemy = it->first;
distance = currentDistance;
}
}
}
return enemy;
}
BWAPI::Unit* MicroManager::nearestNonBuildingEnemy(BWAPI::Unit* unit)
{
BWAPI::Unit* enemy = NULL;
double distance = -1;
std::map<BWAPI::Unit*, EnemyUnitData> enemies = this->eudm->getData();
for(std::map<BWAPI::Unit*, EnemyUnitData>::iterator it=enemies.begin(); it!=enemies.end(); it++)
{
double currentDistance = unit->getPosition().getDistance(it->second.lastKnownPosition);
if(!it->second.unitType.isBuilding())
{
if(distance == -1)
{
enemy = it->first;
distance = currentDistance;
}
else if(currentDistance < distance)
{
enemy = it->first;
distance = currentDistance;
}
}
}
return enemy;
}
BWAPI::Unit* MicroManager::nearestSwarm(BWAPI::Unit* unit)
{
UnitGroup darkSwarms = UnitGroup::getUnitGroup(BWAPI::Broodwar->getAllUnits())(Dark_Swarm);
BWAPI::Unit* nearest = NULL;
double distance = -1;
for(std::set<BWAPI::Unit*>::iterator it=darkSwarms.begin(); it!=darkSwarms.end(); it++)
{
double currentDistance = unit->getPosition().getDistance((*it)->getPosition());
if(distance == -1)
{
nearest = *it;
distance = currentDistance;
}
else if(currentDistance < distance)
{
nearest = *it;
distance = currentDistance;
}
}
return nearest;
}
BWAPI::Unit* MicroManager::nearestEnemyNotUnderDarkSwarm(BWAPI::Unit* unit)
{
UnitGroup enemies = this->eudm->getUG();
std::set<BWAPI::Unit*> underswarm;
for(std::set<BWAPI::Unit*>::iterator it=enemies.begin(); it!=enemies.end(); it++)
{
if(isUnderDarkSwarm(*it))
{
underswarm.insert(*it);
}
}
UnitGroup notunderswarm = enemies - UnitGroup::getUnitGroup(underswarm);
return nearestUnit(unit->getPosition(), notunderswarm);
}
std::string MicroManager::intToString(int i) {
std::ostringstream buffer;
buffer << i;
return buffer.str();
}
void MicroManager::logx(BWAPI::Unit* unit, std::string msg)
{
if(unit->getType() == BWAPI::UnitTypes::Zerg_Drone) return;
if(unit->getType() == BWAPI::UnitTypes::Zerg_Zergling) return;
logc(std::string("MM ").append(unit->getType().getName()).append(" ").append(intToString(unit->getID())).append(std::string(msg)).c_str());
// geeft spam aan berichten
// werkt wel als logx alleen in het laagste if/else niveau van doMicro staat
//BWAPI::Broodwar->drawTextMap(unit->getPosition().x(), unit->getPosition().y(), msg.c_str());
}
void MicroManager::logc(const char* msg)
{
if(false)
{
log(msg);
}
}
double MicroManager::dist(int d)
{
return d*32;
}
BWAPI::Position MicroManager::getCenterPositionFromEnemyMap(std::map<BWAPI::Unit*, EnemyUnitData> data)
{
int result_x;
int result_y;
int cur_x;
int cur_y;
double avg_x = 0.0;
double avg_y = 0.0;
int aantal = 0;
for(std::map<BWAPI::Unit*, EnemyUnitData>::iterator i=data.begin();i!=data.end();i++)
{
cur_x = i->second.lastKnownPosition.x();
cur_y = i->second.lastKnownPosition.y();
avg_x = cur_x + aantal * avg_x / aantal + 1;
aantal++;
}
result_x = int(avg_x);
result_y = int(avg_y);
return BWAPI::Position(result_x, result_y);
}
BWAPI::Unit* MicroManager::getVisibleUnit(std::set<BWAPI::Unit*> units)
{
for each(BWAPI::Unit* unit in units)
{
if(unit->isVisible())
{
return unit;
}
}
return NULL;
}
|
[
"armontoubman@a850bb65-3c1a-43af-a1ba-18f3eb5da290",
"kof@a850bb65-3c1a-43af-a1ba-18f3eb5da290"
] |
[
[
[
1,
34
],
[
36,
36
],
[
43,
46
],
[
48,
53
],
[
55,
57
],
[
66,
66
],
[
82,
133
],
[
135,
244
],
[
246,
271
],
[
273,
274
],
[
301,
301
],
[
319,
319
],
[
326,
326
],
[
328,
328
],
[
336,
336
],
[
342,
342
],
[
346,
346
],
[
348,
348
],
[
351,
351
],
[
353,
353
],
[
357,
358
],
[
361,
361
],
[
364,
364
],
[
373,
373
],
[
375,
377
],
[
414,
414
],
[
417,
425
],
[
427,
440
],
[
442,
442
],
[
444,
444
],
[
450,
450
],
[
453,
453
],
[
459,
459
],
[
464,
466
],
[
472,
472
],
[
474,
475
],
[
484,
484
],
[
486,
486
],
[
490,
491
],
[
494,
494
],
[
503,
503
],
[
510,
522
],
[
525,
546
],
[
548,
562
],
[
564,
564
],
[
573,
576
],
[
578,
578
],
[
580,
581
],
[
584,
585
],
[
591,
592
],
[
607,
607
],
[
609,
610
],
[
615,
615
],
[
618,
618
],
[
620,
620
],
[
622,
622
],
[
624,
624
],
[
629,
629
],
[
635,
636
],
[
638,
641
],
[
648,
648
],
[
658,
677
],
[
680,
680
],
[
685,
686
],
[
692,
693
],
[
695,
696
],
[
698,
701
],
[
703,
703
],
[
705,
705
],
[
708,
708
],
[
714,
714
],
[
719,
719
],
[
722,
726
],
[
729,
729
],
[
732,
732
],
[
735,
737
],
[
744,
751
],
[
753,
756
],
[
759,
759
],
[
764,
764
],
[
767,
767
],
[
773,
774
],
[
776,
777
],
[
781,
781
],
[
786,
790
],
[
792,
792
],
[
795,
795
],
[
797,
797
],
[
803,
805
],
[
807,
807
],
[
809,
811
],
[
821,
825
],
[
832,
839
],
[
846,
848
],
[
853,
853
],
[
855,
855
],
[
875,
877
],
[
879,
879
],
[
887,
887
],
[
890,
890
],
[
893,
893
],
[
895,
895
],
[
916,
918
],
[
921,
924
],
[
926,
927
],
[
929,
933
],
[
935,
938
],
[
940,
956
],
[
958,
958
],
[
976,
979
],
[
981,
981
],
[
983,
983
],
[
986,
986
],
[
988,
988
],
[
994,
994
],
[
998,
998
],
[
1000,
1000
],
[
1002,
1003
],
[
1005,
1005
],
[
1009,
1009
],
[
1012,
1012
],
[
1015,
1017
],
[
1019,
1020
],
[
1044,
1047
],
[
1050,
1050
],
[
1060,
1062
],
[
1064,
1067
],
[
1069,
1069
],
[
1072,
1072
],
[
1075,
1075
],
[
1083,
1083
],
[
1086,
1086
],
[
1089,
1089
],
[
1095,
1095
],
[
1098,
1098
],
[
1100,
1100
],
[
1102,
1102
],
[
1106,
1106
],
[
1110,
1110
],
[
1112,
1115
],
[
1133,
1139
],
[
1142,
1142
],
[
1146,
1146
],
[
1150,
1150
],
[
1159,
1161
],
[
1179,
1179
],
[
1184,
1188
],
[
1190,
1190
],
[
1193,
1193
],
[
1196,
1196
],
[
1208,
1208
],
[
1211,
1211
],
[
1217,
1217
],
[
1228,
1230
],
[
1233,
1233
],
[
1236,
1236
],
[
1251,
1252
],
[
1259,
1261
],
[
1264,
1264
],
[
1267,
1269
],
[
1280,
1282
],
[
1289,
1289
],
[
1291,
1291
],
[
1294,
1295
],
[
1298,
1298
],
[
1302,
1302
],
[
1306,
1307
],
[
1309,
1309
],
[
1312,
1313
],
[
1315,
1315
],
[
1317,
1317
],
[
1332,
1333
],
[
1335,
1336
],
[
1338,
1339
],
[
1342,
1342
],
[
1344,
1344
],
[
1347,
1347
],
[
1352,
1352
],
[
1355,
1357
],
[
1359,
1360
],
[
1362,
1363
],
[
1366,
1366
],
[
1370,
1370
],
[
1377,
1377
],
[
1382,
1382
],
[
1386,
1391
],
[
1393,
1411
],
[
1413,
1416
],
[
1418,
1419
],
[
1422,
1422
],
[
1433,
1438
],
[
1440,
1443
],
[
1445,
1450
],
[
1452,
1458
],
[
1462,
1462
],
[
1474,
1474
],
[
1478,
1482
],
[
1484,
1492
],
[
1495,
1495
],
[
1497,
1501
],
[
1504,
1504
],
[
1506,
1510
],
[
1512,
1547
],
[
1574,
1770
]
],
[
[
35,
35
],
[
37,
42
],
[
47,
47
],
[
54,
54
],
[
58,
65
],
[
67,
81
],
[
134,
134
],
[
245,
245
],
[
272,
272
],
[
275,
300
],
[
302,
318
],
[
320,
325
],
[
327,
327
],
[
329,
335
],
[
337,
341
],
[
343,
345
],
[
347,
347
],
[
349,
350
],
[
352,
352
],
[
354,
356
],
[
359,
360
],
[
362,
363
],
[
365,
372
],
[
374,
374
],
[
378,
413
],
[
415,
416
],
[
426,
426
],
[
441,
441
],
[
443,
443
],
[
445,
449
],
[
451,
452
],
[
454,
458
],
[
460,
463
],
[
467,
471
],
[
473,
473
],
[
476,
483
],
[
485,
485
],
[
487,
489
],
[
492,
493
],
[
495,
502
],
[
504,
509
],
[
523,
524
],
[
547,
547
],
[
563,
563
],
[
565,
572
],
[
577,
577
],
[
579,
579
],
[
582,
583
],
[
586,
590
],
[
593,
606
],
[
608,
608
],
[
611,
614
],
[
616,
617
],
[
619,
619
],
[
621,
621
],
[
623,
623
],
[
625,
628
],
[
630,
634
],
[
637,
637
],
[
642,
647
],
[
649,
657
],
[
678,
679
],
[
681,
684
],
[
687,
691
],
[
694,
694
],
[
697,
697
],
[
702,
702
],
[
704,
704
],
[
706,
707
],
[
709,
713
],
[
715,
718
],
[
720,
721
],
[
727,
728
],
[
730,
731
],
[
733,
734
],
[
738,
743
],
[
752,
752
],
[
757,
758
],
[
760,
763
],
[
765,
766
],
[
768,
772
],
[
775,
775
],
[
778,
780
],
[
782,
785
],
[
791,
791
],
[
793,
794
],
[
796,
796
],
[
798,
802
],
[
806,
806
],
[
808,
808
],
[
812,
820
],
[
826,
831
],
[
840,
845
],
[
849,
852
],
[
854,
854
],
[
856,
874
],
[
878,
878
],
[
880,
886
],
[
888,
889
],
[
891,
892
],
[
894,
894
],
[
896,
915
],
[
919,
920
],
[
925,
925
],
[
928,
928
],
[
934,
934
],
[
939,
939
],
[
957,
957
],
[
959,
975
],
[
980,
980
],
[
982,
982
],
[
984,
985
],
[
987,
987
],
[
989,
993
],
[
995,
997
],
[
999,
999
],
[
1001,
1001
],
[
1004,
1004
],
[
1006,
1008
],
[
1010,
1011
],
[
1013,
1014
],
[
1018,
1018
],
[
1021,
1043
],
[
1048,
1049
],
[
1051,
1059
],
[
1063,
1063
],
[
1068,
1068
],
[
1070,
1071
],
[
1073,
1074
],
[
1076,
1082
],
[
1084,
1085
],
[
1087,
1088
],
[
1090,
1094
],
[
1096,
1097
],
[
1099,
1099
],
[
1101,
1101
],
[
1103,
1105
],
[
1107,
1109
],
[
1111,
1111
],
[
1116,
1132
],
[
1140,
1141
],
[
1143,
1145
],
[
1147,
1149
],
[
1151,
1158
],
[
1162,
1178
],
[
1180,
1183
],
[
1189,
1189
],
[
1191,
1192
],
[
1194,
1195
],
[
1197,
1207
],
[
1209,
1210
],
[
1212,
1216
],
[
1218,
1227
],
[
1231,
1232
],
[
1234,
1235
],
[
1237,
1250
],
[
1253,
1258
],
[
1262,
1263
],
[
1265,
1266
],
[
1270,
1279
],
[
1283,
1288
],
[
1290,
1290
],
[
1292,
1293
],
[
1296,
1297
],
[
1299,
1301
],
[
1303,
1305
],
[
1308,
1308
],
[
1310,
1311
],
[
1314,
1314
],
[
1316,
1316
],
[
1318,
1331
],
[
1334,
1334
],
[
1337,
1337
],
[
1340,
1341
],
[
1343,
1343
],
[
1345,
1346
],
[
1348,
1351
],
[
1353,
1354
],
[
1358,
1358
],
[
1361,
1361
],
[
1364,
1365
],
[
1367,
1369
],
[
1371,
1376
],
[
1378,
1381
],
[
1383,
1385
],
[
1392,
1392
],
[
1412,
1412
],
[
1417,
1417
],
[
1420,
1421
],
[
1423,
1432
],
[
1439,
1439
],
[
1444,
1444
],
[
1451,
1451
],
[
1459,
1461
],
[
1463,
1473
],
[
1475,
1477
],
[
1483,
1483
],
[
1493,
1494
],
[
1496,
1496
],
[
1502,
1503
],
[
1505,
1505
],
[
1511,
1511
],
[
1548,
1573
]
]
] |
10b832d138d648cd122ba6deb94f29ad35163a81
|
a0253037fb4d15a9f087c4415da58253998b453e
|
/lib/t_map/map.cpp
|
2b9378cc8601c6594e242f041bf43268505bf8de
|
[] |
no_license
|
thomas41546/Spario
|
a792746ca3e12c7c3fb2deb57ceb05196f5156a0
|
4aca33f9679515abce208eb1ee28d8bc6987cba0
|
refs/heads/master
| 2021-01-25T06:36:40.111835 | 2010-07-03T04:16:45 | 2010-07-03T04:16:45 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,521 |
cpp
|
#include "map.h"
Map::Map(){
Map::W = XMAP_W;
Map::H = XMAP_H;
data = new unsigned int[Map::W*Map::H];
}
void Map::load(char *fbasepath,char *name){
unsigned char *buff;
unsigned long int blen = 0;
char fname[512];
if(fbasepath != NULL){
sprintf(fname,"%s%s",fbasepath,name);
}
else{
sprintf(fname,"%s",name);
}
readfile(&buff,&blen, fname);
if(blen == Map::W*Map::H*sizeof(unsigned int)){
memcpy((unsigned char *)data, buff, blen);
}
else{
Debug("Error Looading Map: ");
Debug((const char *)fname);
}
delete buff;
}
void Map::writeFlag(Vector Loc,int bit,bool state){//map[loc] set upper flag bit to state;
if(Loc.x< Map::W && Loc.y < Map::H && Loc.x >= 0 && Loc.y >= 0 && bit < 16 && bit >= 0){
data[(int)Loc.x+((int)Loc.y*Map::W)] = (data[(int)Loc.x+((int)Loc.y*Map::W)] & ~(1<<(bit+16)))|((int)state<<(bit+16));
}
}
bool Map::readFlag(Vector Loc,int bit){
if(Loc.x< Map::W && Loc.y < Map::H && Loc.x >= 0 && Loc.y >= 0 && bit < 16 && bit >= 0){
return (bool)((data[(int)Loc.x+((int)Loc.y*Map::W)] >> (bit+16)) & 1);
}
}
int Map::read(Vector Loc){ //excludes flags
if(Loc.x< Map::W && Loc.y < Map::H && Loc.x >= 0 && Loc.y >= 0){
return data[(int)Loc.x+((int)Loc.y*Map::W)] & 0xFFFF;
}
}
int Map::getWidth(){
return Map::W;
}
int Map::getHeight(){
return Map::H;
}
|
[
"[email protected]"
] |
[
[
[
1,
55
]
]
] |
5439b70a420eaca905dd55de226914d09a385b75
|
b2d46af9c6152323ce240374afc998c1574db71f
|
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_mem_tem_pnts_pass.cpp
|
3dd5286339d5bdba1c0f3ebf73f9b7c950630536
|
[] |
no_license
|
bugbit/cipsaoscar
|
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
|
52aa8b4b67d48f59e46cb43527480f8b3552e96d
|
refs/heads/master
| 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,319 |
cpp
|
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS
// This file should compile, if it does not then
// BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS needs to be defined.
// see boost_no_mem_tem_pnts.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_mem_tem_pnts.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS
#include "boost_no_mem_tem_pnts.ipp"
#else
namespace boost_no_pointer_to_member_template_parameters = empty_boost;
#endif
int main( int, char *[] )
{
return boost_no_pointer_to_member_template_parameters::test();
}
|
[
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] |
[
[
[
1,
39
]
]
] |
8671db451fc4dd7731b2971854eab4589767217b
|
cd69369374074a7b4c4f42e970ee95847558e9f0
|
/Nova Versao, em Visual Studio 2010/Medico.h
|
03ecd8ded35c0316cbf6deff9ef2617d196d23a6
|
[] |
no_license
|
miaosun/aeda-trab1
|
4e6b8ce3de8bb7e85e13670595012a5977258a2a
|
1ec5e2edec383572c452545ed52e45fb26df6097
|
refs/heads/master
| 2021-01-25T03:40:21.146657 | 2010-12-25T03:35:28 | 2010-12-25T03:35:28 | 33,734,306 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,381 |
h
|
///////////////////////////////////////////////////////////
// Medico.h
// Implementation of the Class Medico
// Created on: 24-Out-2010 20:04:14
///////////////////////////////////////////////////////////
#if !defined(EA_FC464729_C72D_4115_B003_E0DAD8DDC9B3__INCLUDED_)
#define EA_FC464729_C72D_4115_B003_E0DAD8DDC9B3__INCLUDED_
#include "Pessoa.h"
#include "Funcionario.h"
#include "Doente.h"
class Medico : public Pessoa
{
public:
Medico();
virtual ~Medico();
Funcionario *f_Funcionario;
Doente *m_Doente;
Medico(string nome, string dataNascimento, string tipo, string especialidade, string horario, double vencimento);
string getEspecialidade();
void setEspecialidade(string especialidade);
string getHorario();
void setHorario(string horario);
double getVencimento();
void setVencimento(double vencimento);
Funcionario *getFuncionario();
void setFuncionario(Funcionario *func);
vector<string> imprime();
vector<string> editPessoa();
string toString();
//funcoes abstradas para objecto da superclasse consegue acessar os metodos das classes derivadas
void setMorada(string morada);
void setCargo(string cargo);
string getCargo();
private:
string especialidade;
string horario;
double vencimento;
Funcionario *func;
};
#endif // !defined(EA_FC464729_C72D_4115_B003_E0DAD8DDC9B3__INCLUDED_)
|
[
"miaosun88@9ca0f86a-2074-76d8-43a5-19cf18205b40"
] |
[
[
[
1,
48
]
]
] |
511fae062f68397054c761669bc04960c7bb4689
|
f3efbdc560277c0d0b5da2fc07c6b9574f5aadd4
|
/ lxyppc-oled/oled/HidLoader/HidLoaderDlg.h
|
8903f1c33950b61c996a225ff5a48f2e8ba042e5
|
[] |
no_license
|
lxyppc/lxyppc-oled
|
9a686820ff6bbfa3af11d2c058c9c9144da6ecf1
|
706201693896abae91cdcce616ad7366b9fc9efa
|
refs/heads/master
| 2016-09-05T23:21:47.259439 | 2010-04-26T09:27:31 | 2010-04-26T09:27:31 | 32,801,575 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,635 |
h
|
// HidLoaderDlg.h : header file
//
#pragma once
#include "..\hexedit\hexeditctrl.h"
#include "..\PICData\hexfileline.h"
#include "..\AppSetting\AppSetting.h"
#include "HidDialog.h"
#include <list>
using std::list;
#pragma pack(push,1)
#include "..\..\STM32\oledLoader\inc\Bootloader.h"
#pragma pack(pop)
#include "afxwin.h"
#include "afxcmn.h"
#ifndef FLASH_BASE
#define FLASH_BASE (0x08000000)
#endif
#ifndef FLASH_MAX
#define FLASH_MAX (512*1024) // 512KB
#endif
#define WM_LOADER WM_USER + 101
#define WML_DISABLE_ITEMS 1 /// Disable items
#define WML_ENABLE_ITEMS 2 /// Enable items
#define WML_UPDATE_STATUS 3 /// Update status
struct CROMImage
{
CROMImage():flashBaseAddress(FLASH_BASE),startAddress(0)
,endAddress(0),crc32(0xFFFFFFFF),flash(NULL),flashMaxSize(FLASH_MAX){
flash = new BYTE[FLASH_MAX];
}
~CROMImage(){
delete [] flash;
}
BOOL LoadHexFile(LPCTSTR path);
BYTE* flash;
DWORD startAddress;
const DWORD flashBaseAddress;
const DWORD flashMaxSize;
DWORD endAddress;
DWORD crc32; // crc32 value
int size()const{ return endAddress - startAddress + 1; }
BYTE* data(){
if( startAddress>=flashBaseAddress && size() <= (int)flashMaxSize){
return flash + (startAddress - flashBaseAddress);
}
return flash;
}
};
#define LOG_OUT
#define LOG(_X_)
// CHidLoaderDlg dialog
class CHidLoaderDlg : public CHidDialog
{
// Construction
public:
CHidLoaderDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_HIDLOADER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CHexEditor m_hexView;
public:
afx_msg void OnDropFiles(HDROP hDropInfo);
virtual void OnConnect(LPCTSTR path);
virtual void OnDisconnect(LPCTSTR path);
virtual void OnHidData(void* pData, size_t dataLen);
public:
afx_msg void OnBnClickedLoadFile();
public:
BOOL LoadFile(const CString & path);
public:
BOOL m_fileValid;
BOOL m_bDeviceOpen;
public:
CROMImage m_romImage;
public:
CComboBox m_hexPath;
public:
DeviceFeature m_curDeviceFeature;
public:
void UpdateFeature(void);
public:
CProgressCtrl m_progress;
public:
afx_msg void OnBnClickedUpdateFw();
public:
BOOL EnterBootMode(void);
public:
DWORD Program(void);
static DWORD CALLBACK ProgramCallback(LPVOID pVoid){
::SendMessage(((CHidLoaderDlg*)pVoid)->m_hParent,WM_LOADER,WML_DISABLE_ITEMS,0);
DWORD res = ((CHidLoaderDlg*)pVoid)->Program();
::SendMessage(((CHidLoaderDlg*)pVoid)->m_hParent,WM_LOADER,WML_ENABLE_ITEMS,res);
return res;
}
public:
void ResetRxBuffer(void);
public:
HANDLE m_hEvent;
BYTE m_buffer[64];
CComboBox m_logCombo;
protected:
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
public:
void EnableItems(bool bEnable);
afx_msg void OnBnClickedRunApp();
FILETIME m_fileTime;
CAppSetting m_settings;
list<CString> m_fileList;
public:
void UpdateRecentFileList(const CString& path);
public:
afx_msg void OnCbnSelchangeFilePath();
};
|
[
"lxyppc@2b92f6c6-00d0-11df-bce7-934f6fdf4811"
] |
[
[
[
1,
138
]
]
] |
12df5d5b04a76b191a678397ba536230d8e3d74a
|
ef23e388061a637f82b815d32f7af8cb60c5bb1f
|
/src/mame/includes/gottlieb.h
|
a34e99f7e27c63f6ad4961ce3ced8b8658c0445c
|
[] |
no_license
|
marcellodash/psmame
|
76fd877a210d50d34f23e50d338e65a17deff066
|
09f52313bd3b06311b910ed67a0e7c70c2dd2535
|
refs/heads/master
| 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,273 |
h
|
/***************************************************************************
Gottlieb hardware
***************************************************************************/
#include "machine/6532riot.h"
#define GOTTLIEB_VIDEO_HCOUNT 318
#define GOTTLIEB_VIDEO_HBLANK 256
#define GOTTLIEB_VIDEO_VCOUNT 256
#define GOTTLIEB_VIDEO_VBLANK 240
class gottlieb_state : public driver_device
{
public:
gottlieb_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 *m_videoram;
UINT8 m_votrax_queue[100];
UINT8 m_votrax_queuepos;
emu_timer *m_nmi_timer;
UINT8 m_nmi_rate;
UINT8 m_nmi_state;
UINT8 m_speech_control;
UINT8 m_last_command;
UINT8 *m_dac_data;
UINT8 *m_psg_latch;
UINT8 *m_sp0250_latch;
int m_score_sample;
int m_random_offset;
int m_last;
UINT8 m_joystick_select;
UINT8 m_track[2];
device_t *m_laserdisc;
emu_timer *m_laserdisc_bit_timer;
emu_timer *m_laserdisc_philips_timer;
UINT8 m_laserdisc_select;
UINT8 m_laserdisc_status;
UINT16 m_laserdisc_philips_code;
UINT8 *m_laserdisc_audio_buffer;
UINT16 m_laserdisc_audio_address;
INT16 m_laserdisc_last_samples[2];
attotime m_laserdisc_last_time;
attotime m_laserdisc_last_clock;
UINT8 m_laserdisc_zero_seen;
UINT8 m_laserdisc_audio_bits;
UINT8 m_laserdisc_audio_bit_count;
UINT8 m_gfxcharlo;
UINT8 m_gfxcharhi;
UINT8 *m_charram;
UINT8 m_background_priority;
UINT8 m_spritebank;
UINT8 m_transparent0;
tilemap_t *m_bg_tilemap;
double m_weights[4];
UINT8 *m_spriteram;
};
/*----------- defined in audio/gottlieb.c -----------*/
WRITE8_HANDLER( gottlieb_sh_w );
MACHINE_CONFIG_EXTERN( gottlieb_soundrev1 );
MACHINE_CONFIG_EXTERN( gottlieb_soundrev2 );
INPUT_PORTS_EXTERN( gottlieb1_sound );
INPUT_PORTS_EXTERN( gottlieb2_sound );
/*----------- defined in video/gottlieb.c -----------*/
extern WRITE8_HANDLER( gottlieb_videoram_w );
extern WRITE8_HANDLER( gottlieb_charram_w );
extern WRITE8_HANDLER( gottlieb_video_control_w );
extern WRITE8_HANDLER( gottlieb_laserdisc_video_control_w );
extern WRITE8_HANDLER( gottlieb_paletteram_w );
VIDEO_START( gottlieb );
VIDEO_START( screwloo );
SCREEN_UPDATE( gottlieb );
|
[
"Mike@localhost"
] |
[
[
[
1,
85
]
]
] |
470b1d5eda8979464b762fc1e1d96be41f9d8615
|
968aa9bac548662b49af4e2b873b61873ba6f680
|
/deprecated/etouch/etouch.cpp
|
6db7abb16640c093540ba0a15ba7abff68f2fc34
|
[] |
no_license
|
anagovitsyn/oss.FCL.sftools.dev.build
|
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
|
f458a4ce83f74d603362fe6b71eaa647ccc62fee
|
refs/heads/master
| 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,174 |
cpp
|
// Copyright (c) 1996-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:
//
#if defined(__MSVCDOTNET__) || defined (__TOOLS2__)
#include <iostream>
using namespace std;
#else //!__MSVCDOTNET__
#include <iostream.h>
#endif //__MSVCDOTNET__
#if defined(__VC32__) || defined(__TOOLS2__)
#include <sys/utime.h>
#else
#include <utime.h>
#endif
#if defined(__VC32__) && !defined(__MSVCDOTNET__)
#pragma warning( disable : 4710 ) // 'fn': function not inlined
#endif // old MSVC
int main(int argc,char *argv[])
//
// Collect the filename from the command line
// and change its date/time stamp to the current date/time
//
{
if (argc!=2)
{
cout << "Syntax: etouch filename" << endl;
return(1);
}
return(utime(argv[1],NULL)==(-1) ? 1 : 0);
}
|
[
"none@none"
] |
[
[
[
1,
46
]
]
] |
f21c1eac2137ad9807b06c695be99dff0a80e7d8
|
252e638cde99ab2aa84922a2e230511f8f0c84be
|
/toollib/src/SimpleTourDataSetViewForm.cpp
|
9f17401d08a902b466b459796623e599fafb6558
|
[] |
no_license
|
openlab-vn-ua/tour
|
abbd8be4f3f2fe4d787e9054385dea2f926f2287
|
d467a300bb31a0e82c54004e26e47f7139bd728d
|
refs/heads/master
| 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,160 |
cpp
|
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "SimpleTourDataSetViewForm.h"
#include "TourTool.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SimpleDataSetViewForm"
#pragma link "VStringStorage"
#pragma link "Placemnt"
#pragma resource "*.dfm"
TTourSimpleTourDataSetViewForm *TourSimpleTourDataSetViewForm;
#define GetTranslatedStr(Index) VStringStorage->Lines->Strings[Index]
//---------------------------------------------------------------------------
__fastcall TTourSimpleTourDataSetViewForm::TTourSimpleTourDataSetViewForm(TComponent* Owner)
: TTourSimpleDataSetViewForm(Owner)
{
ColumnToSort = 2;
}
//---------------------------------------------------------------------------
void __fastcall TTourSimpleTourDataSetViewForm::ListViewColumnClick(
TObject *Sender, TListColumn *Column)
{
if (abs(ColumnToSort) - 1 != Column->Index)
{
ColumnToSort = Column->Index + 1;
}
else
{
ColumnToSort *= -1;
}
// ((TCustomListView *)Sender)->CustomSort(NULL,TourListViewColumnToSort);
((TCustomListView *)Sender)->AlphaSort();
}
//---------------------------------------------------------------------------
void __fastcall TTourSimpleTourDataSetViewForm::ListViewCompare(
TObject *Sender, TListItem *Item1, TListItem *Item2, int Data,
int &Compare)
{
bool InvertFlag;
InvertFlag = false;
if (abs(ColumnToSort) <= 1)
{
Compare = CompareText(Item1->Caption,Item2->Caption);
if (ColumnToSort < 0 && !Item1->Caption.IsEmpty() && !Item2->Caption.IsEmpty())
{
InvertFlag = true;
}
}
else
{
int SubItemIndex;
SubItemIndex = abs(ColumnToSort) - 2;
if ((Item1->SubItems->Count >= SubItemIndex + 1) &&
(Item2->SubItems->Count >= SubItemIndex + 1))
{
if (SubItemIndex == 0)
{
Compare = CompareText(Item1->SubItems->Strings[SubItemIndex],
Item2->SubItems->Strings[SubItemIndex]);
if (ColumnToSort < 0)
{
InvertFlag = true;
}
}
/*
else if (SubItemIndex == 1)
{
Compare = TripDiagramCompareDouble(Item1->SubItems->Strings[SubItemIndex],
Item2->SubItems->Strings[SubItemIndex]);
if (TourListViewColumnToSort < 0)
{
InvertFlag = true;
}
}
else
{
Compare = TripDiagramCompareTime(Item1->SubItems->Strings[SubItemIndex],
Item2->SubItems->Strings[SubItemIndex]);
if (TourListViewColumnToSort < 0 &&
!Item1->SubItems->Strings[SubItemIndex].IsEmpty() &&
!Item2->SubItems->Strings[SubItemIndex].IsEmpty())
{
InvertFlag = true;
}
}
*/
}
}
if (InvertFlag)
{
Compare *= (-1);
}
}
//---------------------------------------------------------------------------
void __fastcall TTourSimpleTourDataSetViewForm::FormCloseQuery(
TObject *Sender, bool &CanClose)
{
if (ModalResult == mrOk)
{
if (ListView->Selected == NULL)
{
CanClose = false;
TourShowDialogError
(GetTranslatedStr(TourSimpleTourDataSetViewChooseTourMessageStr).c_str());
ListView->SetFocus();
}
else
{
CanClose = true;
}
}
else
{
CanClose = true;
}
}
//---------------------------------------------------------------------------
void __fastcall TTourSimpleTourDataSetViewForm::PanelResize(
TObject *Sender)
{
CancelButton->Left = Panel->Width - CancelButton->Width - Panel->Tag;
OkButton->Left = CancelButton->Left - OkButton->Width - Panel->Tag;
}
//---------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
144
]
]
] |
881410f800a18c2a6112a60577b638f550763d19
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/statechart/example/Performance/Performance.cpp
|
f2f7c53f95b6e695958d21b2bd9b10c07c463e76
|
[
"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 | 15,108 |
cpp
|
//////////////////////////////////////////////////////////////////////////////
// Copyright 2005-2006 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// #define CUSTOMIZE_MEMORY_MANAGEMENT
// #define BOOST_STATECHART_USE_NATIVE_RTTI
//////////////////////////////////////////////////////////////////////////////
// This program measures event processing performance of the BitMachine
// (see BitMachine example for more information) with a varying number of
// states. Also, a varying number of transitions are replaced with in-state
// reactions. This allows us to calculate how much time is spent for state-
// entry and state-exit during a transition. All measurements are written to
// comma-separated-values files, one file for each individual BitMachine.
//////////////////////////////////////////////////////////////////////////////
#include <boost/statechart/event.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/in_state_reaction.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/front_inserter.hpp>
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/shift_left.hpp>
#include <boost/mpl/bitxor.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/less.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/config.hpp>
#include <boost/assert.hpp>
#ifdef CUSTOMIZE_MEMORY_MANAGEMENT
# ifdef BOOST_MSVC
# pragma warning( push )
# pragma warning( disable: 4127 ) // conditional expression is constant
# pragma warning( disable: 4800 ) // forcing value to bool 'true' or 'false'
# endif
# define BOOST_NO_MT
# include <boost/pool/pool_alloc.hpp>
# ifdef BOOST_MSVC
# pragma warning( pop )
# endif
#endif
#include <vector>
#include <ctime>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <algorithm>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std
{
using ::clock_t;
using ::clock;
}
#endif
#ifdef BOOST_INTEL
# pragma warning( disable: 304 ) // access control not specified
# pragma warning( disable: 444 ) // destructor for base is not virtual
# pragma warning( disable: 981 ) // operands are evaluated in unspecified order
#endif
namespace sc = boost::statechart;
namespace mpl = boost::mpl;
//////////////////////////////////////////////////////////////////////////////
typedef mpl::integral_c< unsigned int, 0 > uint0;
typedef mpl::integral_c< unsigned int, 1 > uint1;
typedef mpl::integral_c< unsigned int, 2 > uint2;
typedef mpl::integral_c< unsigned int, 3 > uint3;
typedef mpl::integral_c< unsigned int, 4 > uint4;
typedef mpl::integral_c< unsigned int, 5 > uint5;
typedef mpl::integral_c< unsigned int, 6 > uint6;
typedef mpl::integral_c< unsigned int, 7 > uint7;
typedef mpl::integral_c< unsigned int, 8 > uint8;
typedef mpl::integral_c< unsigned int, 9 > uint9;
//////////////////////////////////////////////////////////////////////////////
template< class BitNo >
struct EvFlipBit : sc::event< EvFlipBit< BitNo > > {};
boost::intrusive_ptr< const sc::event_base > pFlipBitEvents[] =
{
new EvFlipBit< uint0 >,
new EvFlipBit< uint1 >,
new EvFlipBit< uint2 >,
new EvFlipBit< uint3 >,
new EvFlipBit< uint4 >,
new EvFlipBit< uint5 >,
new EvFlipBit< uint6 >,
new EvFlipBit< uint7 >,
new EvFlipBit< uint8 >,
new EvFlipBit< uint9 >
};
//////////////////////////////////////////////////////////////////////////////
template<
class StateNo,
class NoOfBits,
class FirstTransitionBit >
struct BitState;
template< class NoOfBits, class FirstTransitionBit >
struct BitMachine : sc::state_machine<
BitMachine< NoOfBits, FirstTransitionBit >,
BitState< uint0, NoOfBits, FirstTransitionBit >
#ifdef CUSTOMIZE_MEMORY_MANAGEMENT
, boost::fast_pool_allocator< int >
#endif
>
{
public:
BitMachine() : inStateReactions_( 0 ), transitions_( 0 ) {}
// GCC 3.4.2 doesn't seem to instantiate a function template despite the
// fact that an address of the instantiation is passed as a non-type
// template argument. This leads to linker errors when a function template
// is defined instead of the overloads below.
void InStateReaction( const EvFlipBit< uint0 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint1 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint2 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint3 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint4 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint5 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint6 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint7 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint8 > & )
{
++inStateReactions_;
}
void InStateReaction( const EvFlipBit< uint9 > & )
{
++inStateReactions_;
}
void Transition( const EvFlipBit< uint0 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint1 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint2 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint3 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint4 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint5 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint6 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint7 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint8 > & )
{
++transitions_;
}
void Transition( const EvFlipBit< uint9 > & )
{
++transitions_;
}
unsigned int GetNoOfInStateReactions() const
{
return inStateReactions_;
}
unsigned int GetNoOfTransitions() const
{
return transitions_;
}
private:
unsigned int inStateReactions_;
unsigned int transitions_;
};
//////////////////////////////////////////////////////////////////////////////
template<
class BitNo, class StateNo, class NoOfBits, class FirstTransitionBit >
struct FlipTransition
{
private:
typedef typename mpl::bitxor_<
StateNo,
mpl::shift_left< uint1, BitNo >
>::type NextStateNo;
public:
typedef typename mpl::if_<
mpl::less< BitNo, FirstTransitionBit >,
sc::in_state_reaction<
EvFlipBit< BitNo >,
BitMachine< NoOfBits, FirstTransitionBit >,
&BitMachine< NoOfBits, FirstTransitionBit >::InStateReaction >,
sc::transition<
EvFlipBit< BitNo >,
BitState< NextStateNo, NoOfBits, FirstTransitionBit >,
BitMachine< NoOfBits, FirstTransitionBit >,
&BitMachine< NoOfBits, FirstTransitionBit >::Transition >
>::type type;
BOOST_MPL_AUX_LAMBDA_SUPPORT(
3, FlipTransition, (BitNo, StateNo, FirstTransitionBit) );
};
//////////////////////////////////////////////////////////////////////////////
template<
class StateNo,
class NoOfBits,
class FirstTransitionBit >
struct BitState : sc::simple_state<
BitState< StateNo, NoOfBits, FirstTransitionBit >,
BitMachine< NoOfBits, FirstTransitionBit > >
{
typedef typename mpl::copy<
typename mpl::transform_view<
mpl::range_c< unsigned int, 0, NoOfBits::value >,
FlipTransition<
mpl::placeholders::_, StateNo, NoOfBits, FirstTransitionBit >
>::type,
mpl::front_inserter< mpl::list<> >
>::type reactions;
};
// GCC 3.4.2 doesn't seem to instantiate a class template member function
// despite the fact that an address of the function is passed as a non-type
// template argument. This leads to linker errors when the class template
// defining the functions is not explicitly instantiated.
template struct BitMachine< uint1, uint0 >;
template struct BitMachine< uint1, uint1 >;
template struct BitMachine< uint2, uint0 >;
template struct BitMachine< uint2, uint1 >;
template struct BitMachine< uint2, uint2 >;
template struct BitMachine< uint3, uint0 >;
template struct BitMachine< uint3, uint1 >;
template struct BitMachine< uint3, uint2 >;
template struct BitMachine< uint3, uint3 >;
template struct BitMachine< uint4, uint0 >;
template struct BitMachine< uint4, uint1 >;
template struct BitMachine< uint4, uint2 >;
template struct BitMachine< uint4, uint3 >;
template struct BitMachine< uint4, uint4 >;
template struct BitMachine< uint5, uint0 >;
template struct BitMachine< uint5, uint1 >;
template struct BitMachine< uint5, uint2 >;
template struct BitMachine< uint5, uint3 >;
template struct BitMachine< uint5, uint4 >;
template struct BitMachine< uint5, uint5 >;
template struct BitMachine< uint6, uint0 >;
template struct BitMachine< uint6, uint1 >;
template struct BitMachine< uint6, uint2 >;
template struct BitMachine< uint6, uint3 >;
template struct BitMachine< uint6, uint4 >;
template struct BitMachine< uint6, uint5 >;
template struct BitMachine< uint6, uint6 >;
template struct BitMachine< uint7, uint0 >;
template struct BitMachine< uint7, uint1 >;
template struct BitMachine< uint7, uint2 >;
template struct BitMachine< uint7, uint3 >;
template struct BitMachine< uint7, uint4 >;
template struct BitMachine< uint7, uint5 >;
template struct BitMachine< uint7, uint6 >;
template struct BitMachine< uint7, uint7 >;
////////////////////////////////////////////////////////////////////////////
struct PerfResult
{
PerfResult( double inStateRatio, double nanoSecondsPerReaction ) :
inStateRatio_( inStateRatio ),
nanoSecondsPerReaction_( nanoSecondsPerReaction )
{
}
double inStateRatio_;
double nanoSecondsPerReaction_;
};
template< class NoOfBits, class FirstTransitionBit >
class PerformanceTester
{
public:
////////////////////////////////////////////////////////////////////////
static PerfResult Test()
{
eventsSent_ = 0;
BitMachine< NoOfBits, FirstTransitionBit > machine;
machine.initiate();
const std::clock_t startTime = std::clock();
const unsigned int laps = eventsToSend_ / ( GetNoOfStates() - 1 );
for ( unsigned int lap = 0; lap < laps; ++lap )
{
VisitAllStatesImpl( machine, NoOfBits::value - 1 );
}
const std::clock_t elapsedTime = std::clock() - startTime;
BOOST_ASSERT( eventsSent_ == eventsToSend_ );
BOOST_ASSERT(
machine.GetNoOfInStateReactions() +
machine.GetNoOfTransitions() == eventsSent_ );
return PerfResult(
static_cast< double >( machine.GetNoOfInStateReactions() ) /
eventsSent_,
static_cast< double >( elapsedTime ) /
CLOCKS_PER_SEC * 1000.0 * 1000.0 * 1000.0 / eventsSent_ );
}
static unsigned int GetNoOfStates()
{
return 1 << NoOfBits::value;
}
static unsigned int GetNoOfReactions()
{
return GetNoOfStates() * NoOfBits::value;
}
private:
////////////////////////////////////////////////////////////////////////
static void VisitAllStatesImpl(
BitMachine< NoOfBits, FirstTransitionBit > & machine,
unsigned int bit )
{
if ( bit > 0 )
{
PerformanceTester< NoOfBits, FirstTransitionBit >::
VisitAllStatesImpl( machine, bit - 1 );
}
machine.process_event( *pFlipBitEvents[ bit ] );
++PerformanceTester< NoOfBits, FirstTransitionBit >::eventsSent_;
if ( bit > 0 )
{
PerformanceTester< NoOfBits, FirstTransitionBit >::
VisitAllStatesImpl( machine, bit - 1 );
}
}
// common prime factors of 2^n-1 for n in [1,8]
static const unsigned int eventsToSend_ = 3 * 3 * 5 * 7 * 17 * 31 * 127;
static unsigned int eventsSent_;
};
template< class NoOfBits, class FirstTransitionBit >
unsigned int PerformanceTester< NoOfBits, FirstTransitionBit >::eventsSent_;
//////////////////////////////////////////////////////////////////////////////
typedef std::vector< PerfResult > PerfResultList;
template< class NoOfBits >
struct PerfResultBackInserter
{
PerfResultBackInserter( PerfResultList & perfResultList ) :
perfResultList_( perfResultList )
{
}
template< class FirstTransitionBit >
void operator()( const FirstTransitionBit & )
{
perfResultList_.push_back(
PerformanceTester< NoOfBits, FirstTransitionBit >::Test() );
}
PerfResultList & perfResultList_;
};
template< class NoOfBits >
std::vector< PerfResult > TestMachine()
{
PerfResultList result;
mpl::for_each< mpl::range_c< unsigned int, 0, NoOfBits::value + 1 > >(
PerfResultBackInserter< NoOfBits >( result ) );
return result;
}
template< class NoOfBits >
void TestAndWriteResults()
{
PerfResultList results = TestMachine< NoOfBits >();
std::fstream output;
output.exceptions(
std::ios_base::badbit | std::ios_base::eofbit | std::ios_base::failbit );
std::string prefix = std::string( BOOST_COMPILER ) + "__";
std::replace( prefix.begin(), prefix.end(), ' ', '_' );
output.open(
( prefix + std::string( 1, '0' + static_cast< char >( NoOfBits::value ) )
+ ".txt" ).c_str(),
std::ios_base::out );
for ( PerfResultList::const_iterator pResult = results.begin();
pResult != results.end(); ++pResult )
{
output << std::fixed << std::setprecision( 0 ) <<
std::setw( 8 ) << pResult->inStateRatio_ * 100 << ',' <<
std::setw( 8 ) << pResult->nanoSecondsPerReaction_ << "\n";
}
}
//////////////////////////////////////////////////////////////////////////////
int main()
{
std::cout <<
"Boost.Statechart in-state reaction vs. transition performance test\n\n";
std::cout << "Press <CR> to start the test: ";
{
std::string input;
std::getline( std::cin, input );
}
TestAndWriteResults< uint1 >();
TestAndWriteResults< uint2 >();
TestAndWriteResults< uint3 >();
return 0;
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
516
]
]
] |
3a07b6aade03b2788d66b8f128f7b2c2ba53083e
|
b4d726a0321649f907923cc57323942a1e45915b
|
/CODE/ImpED/wing_editor.cpp
|
aed2785723920d54cead4e8959f41e06c00fdd54
|
[] |
no_license
|
chief1983/Imperial-Alliance
|
f1aa664d91f32c9e244867aaac43fffdf42199dc
|
6db0102a8897deac845a8bd2a7aa2e1b25086448
|
refs/heads/master
| 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 44,477 |
cpp
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/fred2/wing_editor.cpp $
* $Revision: 1.4 $
* $Date: 2004/03/15 12:14:46 $
* $Author: randomtiger $
*
* Wing editor dialog box handler code
*
* $Log: wing_editor.cpp,v $
* Revision 1.4 2004/03/15 12:14:46 randomtiger
* Fixed a whole heap of problems with Fred introduced by changes to global vars.
*
* Revision 1.3 2003/01/06 20:49:15 Goober5000
* FRED2 support for wing squad logos - look in the wing editor
* --Goober5000
*
* Revision 1.2 2002/08/15 01:06:34 penguin
* Include filename reorg (to coordinate w/ fs2_open)
*
* Revision 1.1.1.1 2002/07/15 03:11:04 inquisitor
* Initial FRED2 Checking
*
*
* 3 8/16/99 10:52p Andsager
* Allow closer ship positioning for NEAR_SHIP ship and wing arrivals.
*
* 2 10/07/98 6:28p Dave
* Initial checkin. Renamed all relevant stuff to be Fred2 instead of
* Fred. Globalized mission and campaign file extensions. Removed Silent
* Threat specific code.
*
* 1 10/07/98 3:02p Dave
*
* 1 10/07/98 3:00p Dave
*
* 83 9/14/98 3:31p Allender
* don't allow alpha, beta, and gamma to get > 1 wave when editing a
* multiplayer missions
*
* 82 6/17/98 4:50p Hoffoss
* Added error checking for arrival delays used on wing player is in.
*
* 81 5/22/98 10:10a Hoffoss
* Fixed bug with hide cue button not working correctly.
*
* 80 3/24/98 12:30p Allender
* arrival/departure target boxes were getting initialized incorrectly
*
* 79 3/21/98 7:36p Lawrance
* Move jump nodes to own lib.
*
* 78 3/16/98 8:27p Allender
* Fred support for two new AI flags -- kamikaze and no dynamic goals.
*
* 77 3/10/98 6:11p Hoffoss
* Added jump node renaming abilities to Fred.
*
* 76 2/23/98 9:48p Allender
* added no arrival/departure warps to wings
*
* 75 12/31/97 3:56p Hoffoss
* Forced alpha wing to always have a true arrival cue.
*
* 74 12/29/97 4:55p Johnson
* Added some fixes.
*
* 73 12/18/97 10:40a Hoffoss
* Fixed bug with a few of the checkboxes not initializing properly.
*
* 72 11/25/97 10:03a Allender
* added no arrival message checkbox to wing editor
*
* 71 11/25/97 9:42a Hoffoss
* Removed starting wing checkbox from wing editor.
*
* 70 11/13/97 4:14p Allender
* automatic assignment of hotkeys for starting wings. Appripriate
* warnings when they are incorrectly used. hotkeys correctly assigned to
* ships/wing arriving after mission start
*
* 69 11/11/97 2:13p Allender
* docking bay support for Fred and Freespace. Added hook to ai code for
* arrival/departure from dock bays. Fred support now sufficient.
*
* 68 11/10/97 10:13p Allender
* added departure anchor to Fred and Freespace in preparation for using
* docking bays. Functional in Fred, not in FreeSpace.
*
* 67 10/28/97 3:33p Hoffoss
* Fixed bug where <1 num_waves was being allowed to be entered into Fred.
*
* 66 10/14/97 5:33p Hoffoss
* Added Fred support (and fsm support) for the no_arrival_music flags in
* ships and wings.
*
* 65 10/01/97 12:37p Hoffoss
* Changed Fred (and FreeSpace) to utilize alpha, beta and gamma as player
* starting wing names.
*
* 64 9/04/97 5:35p Hoffoss
* Fixed arrival distance stuff.
*
* 63 9/04/97 5:04p Johnson
* Fixed bug with arrival target distance checking.
*
* 62 9/04/97 4:30p Hoffoss
* Removed sexp tree info from grayed trees.
*
* 61 8/30/97 9:52p Hoffoss
* Implemented arrival location, distance, and anchor in Fred.
*
* 60 8/22/97 4:16p Hoffoss
* added support for arrival and departure info in ship editor using
* wing's info if editing marked ships in a wing instead of using ship's.
*
* 59 8/21/97 3:20p Duncan
* Fixed bug in wing renaming when a player is in the wing.
*
* 58 8/19/97 1:44p Hoffoss
* Fixed bug with updating too quickly (i.e. via prev and next buttons).
*
* 57 8/15/97 5:14p Hoffoss
* Completely changed around how initial orders dialog worked. It's
* pretty awesome now.
*
* 56 8/15/97 11:24a Hoffoss
* Changed order of events.
*
* 55 8/13/97 11:31p Hoffoss
* Added bound checking on min/max wave delay.
*
* 54 8/13/97 11:22p Hoffoss
* Implemented wave delay min and max in Fred.
*
* 53 8/12/97 7:17p Hoffoss
* Added previous button to ship and wing editors.
*
* 52 8/12/97 6:32p Hoffoss
* Added code to allow hiding of arrival and departure cues in editors.
*
* 51 8/12/97 3:33p Hoffoss
* Fixed the "press cancel to go to reference" code to work properly.
*
* 50 8/12/97 1:55a Hoffoss
* Made extensive changes to object reference checking and handling for
* object deletion call.
*
* 49 8/10/97 4:22p Hoffoss
* Made main display update when ships or wings are renamed.
*
* 48 8/08/97 10:00a Hoffoss
* Added protection from threshold being equal or higher than the number
* of ships in a wing.
*
* 47 8/01/97 2:45p Hoffoss
* Fixed bug with no new item in MFC CTreeCtrl selection changed message.
* Throught it shouldn't happen, but Whiteside made it happen.
*
* 46 7/30/97 5:23p Hoffoss
* Removed Sexp tree verification code, since it duplicates normal sexp
* verification, and is just another set of code to keep maintained.
*
* 45 7/30/97 12:31p Hoffoss
* Made improvements to ship goals editor (initial orders) to disallow
* illegal orders.
*
* 44 7/28/97 2:28p Hoffoss
* Added bypasses to MFC integer validation routines.
*
* 43 7/25/97 2:40p Hoffoss
* Fixed bug in sexp tree selection updating handling.
*
* 42 7/24/97 4:44p Hoffoss
* Added sexp help to more dialogs, and changed made some changes to make
* it work correctly for ship and wing editors.
*
* 41 7/18/97 2:05p Hoffoss
* Fixed some bugs BoundsChecker turned up.
*
* 40 7/16/97 6:30p Hoffoss
* Added icons to sexp trees, mainly because I think they will be required
* for drag n drop.
*
* 39 7/09/97 2:38p Allender
* organized ship/wing editor dialogs. Added protect ship and ignore
* count checkboxes to those dialogs. Changed flag code for
* parse_objects. Added unprotect sexpressions
*
* 38 7/08/97 10:15a Allender
* making ships/wings reinforcements now do not set the arrival cue to
* false. A reinforcement may only be available after it's arrival cue is
* true
*
* 37 7/02/97 3:30p Hoffoss
* Put in code to validate and bash if necessary the wing wave threshold.
*
* 36 6/18/97 3:07p Hoffoss
* Wing ship names are 1 indexes instead of 0 indexed now.
*
* 35 6/05/97 6:10p Hoffoss
* Added features: Autosaving, object hiding. Also fixed some minor bugs.
*
* 34 5/30/97 11:33a Allender
* more hotkey combo box stuff
*
* 33 5/23/97 1:53p Hoffoss
* Fixed problems with modeless dialog updating. It won't get caught in
* an infinate loop anymore, but still gives an error warning 3 times when
* using cancel and trying to switch window focus to main window. Don't
* know if I can fix that, but it's not too critical right now.
*
* 32 5/01/97 4:15p Hoffoss
* Fixed bugs.
*
* 31 4/28/97 2:37p Hoffoss
* Added hotkey editing to Fred for ships and wings.
*
* 30 4/23/97 11:55a Hoffoss
* Fixed many bugs uncovered while trying to create Mission 6.
*
* 29 4/07/97 1:53p Hoffoss
* Fixed a few bugs, and added sexp chain duplicating for object
* duplicating.
*
* 28 4/03/97 11:35a Hoffoss
* Fixed bugs: viewpoint didn't reset, initial orders not updated when
* referenced ship is renamed or deleted.
*
* 27 4/01/97 5:15p Hoffoss
* Fixed errors in max length checks, renaming a wing now renames the
* ships in the wing as well, as it should.
*
* 26 3/20/97 3:55p Hoffoss
* Major changes to how dialog boxes initialize (load) and update (save)
* their internal data. This should simplify things and create less
* problems.
*
* 25 3/17/97 4:29p Hoffoss
* Automated player's wing flaging as a starting player wing.
*
* 24 3/05/97 10:54a Hoffoss
* removed special arrival/departure cue token usage in wing editor.
*
* 23 2/28/97 11:31a Hoffoss
* Implemented modeless dialog saving and restoring, and changed some
* variables names.
*
* 22 2/27/97 3:16p Allender
* major wing structure enhancement. simplified wing code. All around
* better wing support
*
* 21 2/24/97 5:38p Hoffoss
* Added dialog box to name a wing at creation, code to change ship names
* to match wing name, and code to maintain these ship names.
*
* 20 2/21/97 5:34p Hoffoss
* Added extensive modification detection and fixed a bug in initial
* orders editor.
*
* 19 2/20/97 4:03p Hoffoss
* Several ToDo items: new reinforcement clears arrival cue, reinforcement
* control from ship and wing dialogs, show grid toggle.
*
* 18 2/17/97 5:28p Hoffoss
* Checked RCS headers, added them were missing, changing description to
* something better, etc where needed.
*
* $NoKeywords: $
*/
#include "stdafx.h"
#include "MainFrm.h"
#include "FRED.h"
#include "FREDDoc.h"
#include "Management.h"
#include "wing.h"
#include "globalincs/linklist.h"
#include "ship/aigoals.h"
#include "FREDView.h"
#include "starfield/starfield.h"
#include "jumpnode/jumpnode.h"
#include "cfile/cfile.h"
#define ID_WING_MENU 9000
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// wing_editor dialog
wing_editor::wing_editor(CWnd* pParent /*=NULL*/)
: CDialog(wing_editor::IDD, pParent)
{
//{{AFX_DATA_INIT(wing_editor)
m_wing_name = _T("");
m_wing_squad_filename = _T("");
m_special_ship = -1;
m_waves = 0;
m_threshold = 0;
m_arrival_location = -1;
m_departure_location = -1;
m_arrival_delay = 0;
m_departure_delay = 0;
m_reinforcement = FALSE;
m_hotkey = -1;
m_ignore_count = FALSE;
m_arrival_delay_max = 0;
m_arrival_delay_min = 0;
m_arrival_dist = 0;
m_arrival_target = -1;
m_no_arrival_music = FALSE;
m_departure_target = -1;
m_no_arrival_message = FALSE;
m_no_arrival_warp = FALSE;
m_no_departure_warp = FALSE;
m_no_dynamic = FALSE;
//}}AFX_DATA_INIT
modified = 0;
select_sexp_node = -1;
bypass_errors = 0;
}
void wing_editor::DoDataExchange(CDataExchange* pDX)
{
CString str;
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(wing_editor)
DDX_Control(pDX, IDC_DEPARTURE_DELAY_SPIN, m_departure_delay_spin);
DDX_Control(pDX, IDC_ARRIVAL_DELAY_SPIN, m_arrival_delay_spin);
DDX_Control(pDX, IDC_DEPARTURE_TREE, m_departure_tree);
DDX_Control(pDX, IDC_ARRIVAL_TREE, m_arrival_tree);
DDX_Control(pDX, IDC_SPIN_WAVE_THRESHOLD, m_threshold_spin);
DDX_Control(pDX, IDC_SPIN_WAVES, m_waves_spin);
DDX_Text(pDX, IDC_WING_NAME, m_wing_name);
DDX_Text(pDX, IDC_WING_SQUAD_LOGO, m_wing_squad_filename);
DDX_CBIndex(pDX, IDC_WING_SPECIAL_SHIP, m_special_ship);
DDX_CBIndex(pDX, IDC_ARRIVAL_LOCATION, m_arrival_location);
DDX_CBIndex(pDX, IDC_DEPARTURE_LOCATION, m_departure_location);
DDX_Check(pDX, IDC_REINFORCEMENT, m_reinforcement);
//DDX_Check(pDX, IDC_PLAYER_EDIT, m_player_edit);
DDX_CBIndex(pDX, IDC_HOTKEY, m_hotkey);
DDX_Check(pDX, IDC_IGNORE_COUNT, m_ignore_count);
DDX_Text(pDX, IDC_ARRIVAL_DISTANCE, m_arrival_dist);
DDX_CBIndex(pDX, IDC_ARRIVAL_TARGET, m_arrival_target);
DDX_Check(pDX, IDC_NO_ARRIVAL_MUSIC, m_no_arrival_music);
DDX_CBIndex(pDX, IDC_DEPARTURE_TARGET, m_departure_target);
DDX_Check(pDX, IDC_NO_ARRIVAL_MESSAGE, m_no_arrival_message);
DDX_Check(pDX, IDC_NO_ARRIVAL_WARP, m_no_arrival_warp);
DDX_Check(pDX, IDC_NO_DEPARTURE_WARP, m_no_departure_warp);
DDX_Check(pDX, IDC_NO_DYNAMIC, m_no_dynamic);
//}}AFX_DATA_MAP
if (pDX->m_bSaveAndValidate) { // get dialog control values
GetDlgItem(IDC_ARRIVAL_DELAY)->GetWindowText(str);
m_arrival_delay = atoi(str);
if (m_arrival_delay < 0)
m_arrival_delay = 0;
GetDlgItem(IDC_DEPARTURE_DELAY)->GetWindowText(str);
m_departure_delay = atoi(str);
if (m_departure_delay < 0)
m_departure_delay = 0;
GetDlgItem(IDC_WING_WAVES)->GetWindowText(str);
m_waves = atoi(str);
if (m_waves < 0)
m_waves = 0;
GetDlgItem(IDC_WING_WAVE_THRESHOLD)->GetWindowText(str);
m_threshold = atoi(str);
if (m_threshold < 0)
m_threshold = 0;
GetDlgItem(IDC_ARRIVAL_DELAY_MIN)->GetWindowText(str);
m_arrival_delay_min = atoi(str);
if (m_arrival_delay_min < 0)
m_arrival_delay_min = 0;
GetDlgItem(IDC_ARRIVAL_DELAY_MAX)->GetWindowText(str);
m_arrival_delay_max = atoi(str);
if (m_arrival_delay_max < 0)
m_arrival_delay_max = 0;
} else {
DDX_Text(pDX, IDC_ARRIVAL_DELAY, m_arrival_delay);
DDX_Text(pDX, IDC_DEPARTURE_DELAY, m_departure_delay);
DDX_Text(pDX, IDC_WING_WAVES, m_waves);
DDX_Text(pDX, IDC_WING_WAVE_THRESHOLD, m_threshold);
DDX_Text(pDX, IDC_ARRIVAL_DELAY_MIN, m_arrival_delay_min);
DDX_Text(pDX, IDC_ARRIVAL_DELAY_MAX, m_arrival_delay_max);
}
}
BEGIN_MESSAGE_MAP(wing_editor, CDialog)
//{{AFX_MSG_MAP(wing_editor)
ON_WM_INITMENU()
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_WAVES, OnDeltaposSpinWaves)
ON_NOTIFY(NM_RCLICK, IDC_ARRIVAL_TREE, OnRclickArrivalTree)
ON_NOTIFY(NM_RCLICK, IDC_DEPARTURE_TREE, OnRclickDepartureTree)
ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_ARRIVAL_TREE, OnBeginlabeleditArrivalTree)
ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_DEPARTURE_TREE, OnBeginlabeleditDepartureTree)
ON_NOTIFY(TVN_ENDLABELEDIT, IDC_ARRIVAL_TREE, OnEndlabeleditArrivalTree)
ON_NOTIFY(TVN_ENDLABELEDIT, IDC_DEPARTURE_TREE, OnEndlabeleditDepartureTree)
ON_BN_CLICKED(IDC_DELETE_WING, OnDeleteWing)
ON_BN_CLICKED(IDC_DISBAND_WING, OnDisbandWing)
ON_WM_CLOSE()
ON_BN_CLICKED(IDC_GOALS2, OnGoals2)
ON_BN_CLICKED(IDC_REINFORCEMENT, OnReinforcement)
ON_BN_CLICKED(IDC_NEXT, OnNext)
ON_NOTIFY(TVN_SELCHANGED, IDC_ARRIVAL_TREE, OnSelchangedArrivalTree)
ON_NOTIFY(TVN_SELCHANGED, IDC_DEPARTURE_TREE, OnSelchangedDepartureTree)
ON_BN_CLICKED(IDC_HIDE_CUES, OnHideCues)
ON_BN_CLICKED(IDC_PREV, OnPrev)
ON_CBN_SELCHANGE(IDC_ARRIVAL_LOCATION, OnSelchangeArrivalLocation)
ON_CBN_SELCHANGE(IDC_DEPARTURE_LOCATION, OnSelchangeDepartureLocation)
ON_CBN_SELCHANGE(IDC_HOTKEY, OnSelchangeHotkey)
ON_BN_CLICKED(IDC_WING_SQUAD_LOGO_BUTTON, OnSquadLogo)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// wing_editor message handlers
BOOL wing_editor::Create()
{
BOOL r;
int i;
CComboBox *box;
r = CDialog::Create(IDD, Fred_main_wnd);
box = (CComboBox *) GetDlgItem(IDC_ARRIVAL_LOCATION);
box->ResetContent();
for (i=0; i<MAX_ARRIVAL_NAMES; i++)
box->AddString(Arrival_location_names[i]);
box = (CComboBox *) GetDlgItem(IDC_DEPARTURE_LOCATION);
box->ResetContent();
for (i=0; i<MAX_DEPARTURE_NAMES; i++)
box->AddString(Departure_location_names[i]);
m_hotkey = 0;
m_waves_spin.SetRange(1, 99);
m_arrival_tree.link_modified(&modified); // provide way to indicate trees are modified in dialog
m_arrival_tree.setup((CEdit *) GetDlgItem(IDC_HELP_BOX));
m_departure_tree.link_modified(&modified);
m_departure_tree.setup();
m_arrival_delay_spin.SetRange(0, 999);
m_departure_delay_spin.SetRange(0, 999);
initialize_data(1);
return r;
}
void wing_editor::OnInitMenu(CMenu* pMenu)
{
CMenu *m;
m = pMenu->GetSubMenu(0);
clear_menu(m);
generate_wing_popup_menu(m, ID_WING_MENU, MF_ENABLED);
if (cur_wing != -1)
m->CheckMenuItem(ID_WING_MENU + cur_wing, MF_BYCOMMAND | MF_CHECKED);
CDialog::OnInitMenu(pMenu);
}
void wing_editor::OnOK()
{
HWND h;
CWnd *w;
w = GetFocus();
if (w) {
h = w->m_hWnd;
GetDlgItem(IDC_ARRIVAL_TREE)->SetFocus();
::SetFocus(h);
}
}
void wing_editor::OnClose()
{
if (verify() && (!bypass_errors)) {
SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
bypass_errors = 0;
return;
}
if (update_data()) {
SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
bypass_errors = 0;
return;
}
SetWindowPos(Fred_main_wnd, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW);
Fred_main_wnd->SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
// initialize everything that update_data_safe() saves.
void wing_editor::initialize_data_safe(int full_update)
{
int i, enable = TRUE, player_wing = 0, player_enabled = 1;
CComboBox *arrival_box, *departure_box;
nprintf(("Fred routing", "Wing dialog load safe\n"));
if (!GetSafeHwnd())
return;
arrival_box = (CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET);
departure_box = (CComboBox *)GetDlgItem(IDC_DEPARTURE_TARGET);
m_ignore_count = 0;
if (cur_wing < 0) {
m_wing_squad_filename = _T("");
m_special_ship = -1;
m_arrival_location = -1;
m_departure_location = -1;
m_arrival_delay = 0;
m_arrival_delay_min = 0;
m_arrival_delay_max = 0;
m_arrival_dist = 0;
m_arrival_target = -1;
m_departure_target = -1;
m_departure_delay = 0;
m_arrival_tree.clear_tree();
m_departure_tree.clear_tree();
m_arrival_tree.DeleteAllItems();
m_departure_tree.DeleteAllItems();
m_reinforcement = FALSE;
m_hotkey = 0;
m_ignore_count = 0;
m_no_arrival_music = 0;
m_no_arrival_message = 0;
m_no_arrival_warp = 0;
m_no_departure_warp = 0;
m_no_dynamic = 0;
player_enabled = enable = FALSE;
} else {
CComboBox *ptr;
/*if (cur_wing == wing_name_lookup("alpha", 1))
player_enabled = 0;
if ((The_mission.game_type & MISSION_TYPE_MULTI_TEAMS) && (cur_wing == wing_name_lookup("zeta", 1)))
player_enabled = 0;
// in multiplayer coop missions, alpha, beta, and gamma are both off limits.
if ( The_mission.game_type & MISSION_TYPE_MULTI_COOP ) {
if ( (cur_wing == wing_name_lookup("alpha", 1)) || (cur_wing == wing_name_lookup("beta", 1)) || (cur_wing == wing_name_lookup("gamma", 1)) ) {
player_enabled = 0;
}
}*/
if ((Player_start_shipnum >= 0) && (Player_start_shipnum < MAX_SHIPS) && (Ships[Player_start_shipnum].objnum >= 0))
if (Ships[Player_start_shipnum].wingnum == cur_wing)
player_wing = 1;
m_wing_squad_filename = _T(Wings[cur_wing].wing_squad_filename);
m_special_ship = Wings[cur_wing].special_ship;
m_waves = Wings[cur_wing].num_waves;
m_threshold = Wings[cur_wing].threshold;
m_arrival_location = Wings[cur_wing].arrival_location;
m_departure_location = Wings[cur_wing].departure_location;
m_arrival_delay = Wings[cur_wing].arrival_delay;
m_arrival_delay_min = Wings[cur_wing].wave_delay_min;
m_arrival_delay_max = Wings[cur_wing].wave_delay_max;
m_arrival_dist = Wings[cur_wing].arrival_distance;
m_arrival_target = Wings[cur_wing].arrival_anchor;
if (m_departure_location == DEPART_AT_DOCK_BAY)
m_departure_target = Wings[cur_wing].departure_anchor;
else
m_departure_target = Wings[cur_wing].jump_anchor;
m_no_dynamic = (Wings[cur_wing].flags & WF_NO_DYNAMIC)?1:0;
// Add the ships/special items to the combo box here before data is updated
if ( m_arrival_location == ARRIVE_FROM_DOCK_BAY ) {
management_add_ships_to_combo( arrival_box, SHIPS_2_COMBO_DOCKING_BAY_ONLY );
} else {
management_add_ships_to_combo( arrival_box, SHIPS_2_COMBO_SPECIAL | SHIPS_2_COMBO_ALL_SHIPS );
}
if (m_arrival_target >= SPECIAL_ARRIVAL_ANCHORS_OFFSET)
m_arrival_target -= SPECIAL_ARRIVAL_ANCHORS_OFFSET;
else if (m_arrival_target >= 0)
m_arrival_target = arrival_box->FindStringExact(-1, Ships[m_arrival_target].ship_name);
// add the ships to the departure target combo box
if ( m_departure_location == DEPART_AT_DOCK_BAY ) {
management_add_ships_to_combo( departure_box, SHIPS_2_COMBO_DOCKING_BAY_ONLY );
if ( m_departure_target >= 0 )
m_departure_target = departure_box->FindStringExact(-1, Ships[m_departure_target].ship_name);
} else {
departure_box->ResetContent();
char list[MAX_JUMPPOINT_LISTS+1][NAME_LENGTH];
strcpy(list[0], "None");
departure_box->AddString("None");
for (i=0; i<Num_jump_nodes; i++) {
departure_box->AddString(Jumppoint_lists[i].name);
strcpy(list[i+1], Jumppoint_lists[i].name);
}
if (m_departure_target >= 0) {
m_departure_target = departure_box->FindStringExact(-1, list[m_departure_target]);
} else
m_departure_target = 0;
}
m_departure_delay = Wings[cur_wing].departure_delay;
if (player_wing)
m_arrival_tree.load_tree(Locked_sexp_true);
else
m_arrival_tree.load_tree(Wings[cur_wing].arrival_cue);
m_departure_tree.load_tree(Wings[cur_wing].departure_cue, "false");
m_hotkey = Wings[cur_wing].hotkey+1;
if (Wings[cur_wing].flags & WF_IGNORE_COUNT)
m_ignore_count = 1;
else
m_ignore_count = 0;
if (Wings[cur_wing].flags & WF_NO_ARRIVAL_MUSIC)
m_no_arrival_music = 1;
else
m_no_arrival_music = 0;
if ( Wings[cur_wing].flags & WF_NO_ARRIVAL_MESSAGE )
m_no_arrival_message = 1;
else
m_no_arrival_message = 0;
if ( Wings[cur_wing].flags & WF_NO_ARRIVAL_WARP )
m_no_arrival_warp = 1;
else
m_no_arrival_warp = 0;
if ( Wings[cur_wing].flags & WF_NO_DEPARTURE_WARP )
m_no_departure_warp = 1;
else
m_no_departure_warp = 0;
ptr = (CComboBox *) GetDlgItem(IDC_WING_SPECIAL_SHIP);
ptr->ResetContent();
for (i=0; i<Wings[cur_wing].wave_count; i++)
ptr->AddString(Ships[Wings[cur_wing].ship_index[i]].ship_name);
m_threshold_spin.SetRange(0, Wings[cur_wing].wave_count - 1);
for (i=0; i<Num_reinforcements; i++)
if (!stricmp(Reinforcements[i].name, Wings[cur_wing].name))
break;
if (i < Num_reinforcements)
m_reinforcement = TRUE;
else
m_reinforcement = FALSE;
}
if (full_update)
UpdateData(FALSE);
GetDlgItem(IDC_WING_NAME)->EnableWindow(enable);
GetDlgItem(IDC_WING_SQUAD_LOGO_BUTTON)->EnableWindow(enable);
GetDlgItem(IDC_WING_SPECIAL_SHIP)->EnableWindow(enable);
GetDlgItem(IDC_WING_WAVES)->EnableWindow(player_enabled);
GetDlgItem(IDC_WING_WAVE_THRESHOLD)->EnableWindow(player_enabled);
GetDlgItem(IDC_DISBAND_WING)->EnableWindow(enable);
GetDlgItem(IDC_SPIN_WAVES)->EnableWindow(player_enabled);
GetDlgItem(IDC_SPIN_WAVE_THRESHOLD)->EnableWindow(player_enabled);
GetDlgItem(IDC_ARRIVAL_LOCATION)->EnableWindow(enable);
GetDlgItem(IDC_ARRIVAL_DELAY)->EnableWindow(player_enabled);
GetDlgItem(IDC_ARRIVAL_DELAY_MIN)->EnableWindow(player_enabled);
GetDlgItem(IDC_ARRIVAL_DELAY_MAX)->EnableWindow(player_enabled);
GetDlgItem(IDC_ARRIVAL_DELAY_SPIN)->EnableWindow(player_enabled);
if (m_arrival_location) {
GetDlgItem(IDC_ARRIVAL_DISTANCE)->EnableWindow(enable);
GetDlgItem(IDC_ARRIVAL_TARGET)->EnableWindow(enable);
} else {
GetDlgItem(IDC_ARRIVAL_DISTANCE)->EnableWindow(FALSE);
GetDlgItem(IDC_ARRIVAL_TARGET)->EnableWindow(FALSE);
}
GetDlgItem(IDC_NO_DYNAMIC)->EnableWindow(enable);
//if ( m_departure_location ) {
GetDlgItem(IDC_DEPARTURE_TARGET)->EnableWindow(enable);
//} else {
// GetDlgItem(IDC_DEPARTURE_TARGET)->EnableWindow(FALSE);
//}
if (player_wing)
GetDlgItem(IDC_ARRIVAL_TREE)->EnableWindow(0);
else
GetDlgItem(IDC_ARRIVAL_TREE)->EnableWindow(enable);
GetDlgItem(IDC_DEPARTURE_LOCATION)->EnableWindow(enable);
GetDlgItem(IDC_DEPARTURE_DELAY)->EnableWindow(enable);
GetDlgItem(IDC_DEPARTURE_DELAY_SPIN)->EnableWindow(enable);
GetDlgItem(IDC_DEPARTURE_TREE)->EnableWindow(enable);
GetDlgItem(IDC_GOALS2)->EnableWindow(enable);
GetDlgItem(IDC_DELETE_WING)->EnableWindow(enable);
GetDlgItem(IDC_REINFORCEMENT)->EnableWindow(enable);
GetDlgItem(IDC_HOTKEY)->EnableWindow(enable);
GetDlgItem(IDC_IGNORE_COUNT)->EnableWindow(enable);
GetDlgItem(IDC_NO_ARRIVAL_MUSIC)->EnableWindow(enable);
GetDlgItem(IDC_NO_ARRIVAL_MESSAGE)->EnableWindow(enable);
GetDlgItem(IDC_NO_ARRIVAL_WARP)->EnableWindow(enable);
GetDlgItem(IDC_NO_DEPARTURE_WARP)->EnableWindow(enable);
if (cur_wing >= 0) {
enable = TRUE;
// check to see if the wing has a ship which is not a fighter/bomber type. If so, then disable
// the wing_waves and wing_threshold stuff
for (i = 0; i < Wings[cur_wing].wave_count; i++ ) {
int sflag;
sflag = Ship_info[Ships[Wings[cur_wing].ship_index[i]].ship_info_index].flags;
if ( !(sflag & SIF_FIGHTER) && !(sflag & SIF_BOMBER) )
enable = FALSE;
}
} else
enable = FALSE;
}
void wing_editor::initialize_data(int full_update)
{
int i;
CWnd *w = NULL;
nprintf(("Fred routing", "Wing dialog load\n"));
if (!GetSafeHwnd())
return;
m_arrival_tree.select_sexp_node = m_departure_tree.select_sexp_node = select_sexp_node;
select_sexp_node = -1;
if (cur_wing == -1)
m_wing_name = _T("");
else
m_wing_name = _T(Wings[cur_wing].name);
initialize_data_safe(full_update);
modified = 0;
if (w)
w -> SetFocus();
i = m_arrival_tree.select_sexp_node;
if (i != -1) {
w = GetDlgItem(IDC_ARRIVAL_TREE);
m_arrival_tree.hilite_item(i);
} else {
i = m_departure_tree.select_sexp_node;
if (i != -1) {
w = GetDlgItem(IDC_DEPARTURE_TREE);
m_departure_tree.hilite_item(i);
}
}
}
// update wing structure(s) with dialog data. The data is first checked for errors. If
// no errors occur, returns 0. If an error occurs, returns -1. If the update is bypassed,
// returns 1. Bypass is necessary to avoid an infinite loop, and it doesn't actually
// update the data. Bypass only occurs if bypass mode is active and we still get an error.
// Once the error no longer occurs, bypass mode is cleared and data is updated.
int wing_editor::update_data(int redraw)
{
char *str, old_name[255], buf[512];
int i, z;
object *ptr;
nprintf(("Fred routing", "Wing dialog save\n"));
if (!GetSafeHwnd())
return 0;
UpdateData(TRUE);
UpdateData(TRUE);
if (cur_wing >= 0) {
if (!strnicmp(m_wing_name, "player ", 7)) {
if (bypass_errors)
return 1;
bypass_errors = 1;
z = MessageBox("Wing names can't start with the word 'player'\n"
"Press OK to restore old name", "Error", MB_ICONEXCLAMATION | MB_OKCANCEL);
if (z == IDCANCEL)
return -1;
m_wing_name = _T(Wings[cur_wing].name);
UpdateData(FALSE);
}
for (i=0; i<MAX_WINGS; i++)
if (Wings[i].wave_count && !stricmp(Wings[i].name, m_wing_name) && (i != cur_wing)) {
if (bypass_errors)
return 1;
bypass_errors = 1;
z = MessageBox("This wing name is already being used by another wing\n"
"Press OK to restore old name", "Error", MB_ICONEXCLAMATION | MB_OKCANCEL);
if (z == IDCANCEL)
return -1;
m_wing_name = _T(Wings[cur_wing].name);
UpdateData(FALSE);
}
ptr = GET_FIRST(&obj_used_list);
while (ptr != END_OF_LIST(&obj_used_list)) {
if (ptr->type == OBJ_SHIP) {
if (!stricmp(m_wing_name, Ships[ptr->instance].ship_name)) {
if (bypass_errors)
return 1;
bypass_errors = 1;
z = MessageBox("This wing name is already being used by a ship\n"
"Press OK to restore old name", "Error", MB_ICONEXCLAMATION | MB_OKCANCEL);
if (z == IDCANCEL)
return -1;
m_wing_name = _T(Wings[cur_wing].name);
UpdateData(FALSE);
}
}
ptr = GET_NEXT(ptr);
}
for (i=0; i<MAX_WAYPOINT_LISTS; i++)
if (Waypoint_lists[i].count && !stricmp(Waypoint_lists[i].name, m_wing_name)) {
if (bypass_errors)
return 1;
bypass_errors = 1;
z = MessageBox("This wing name is already being used by a waypoint path\n"
"Press OK to restore old name", "Error", MB_ICONEXCLAMATION | MB_OKCANCEL);
if (z == IDCANCEL)
return -1;
m_wing_name = _T(Wings[cur_wing].name);
UpdateData(FALSE);
}
for (i=0; i<Num_jump_nodes; i++)
if (!stricmp(Jump_nodes[i].name, m_wing_name)) {
if (bypass_errors)
return 1;
bypass_errors = 1;
z = MessageBox("This wing name is already being used by a hyper buoy\n"
"Press OK to restore old name", "Error", MB_ICONEXCLAMATION | MB_OKCANCEL);
if (z == IDCANCEL)
return -1;
m_wing_name = _T(Wings[cur_wing].name);
UpdateData(FALSE);
}
strcpy(old_name, Wings[cur_wing].name);
string_copy(Wings[cur_wing].name, m_wing_name, NAME_LENGTH, 1);
update_data_safe();
bypass_errors = 0;
modified = 0;
str = Wings[cur_wing].name;
if (stricmp(old_name, str)) {
update_sexp_references(old_name, str);
ai_update_goal_references(REF_TYPE_WING, old_name, str);
for (i=0; i<Num_reinforcements; i++)
if (!stricmp(old_name, Reinforcements[i].name)) {
Assert(strlen(str) < NAME_LENGTH);
strcpy(Reinforcements[i].name, str);
}
for (i=0; i<Wings[cur_wing].wave_count; i++) {
if ((Objects[wing_objects[cur_wing][i]].type == OBJ_SHIP) || (Objects[wing_objects[cur_wing][i]].type == OBJ_START)) {
sprintf(buf, "%s %d", str, i + 1);
rename_ship(Wings[cur_wing].ship_index[i], buf);
}
}
Update_window = 1;
}
if (set_reinforcement(str, m_reinforcement) == 1) {
free_sexp2(Wings[cur_wing].arrival_cue);
Wings[cur_wing].arrival_cue = Locked_sexp_false;
}
}
if (redraw)
update_map_window();
return 0;
}
// update parts of wing that can't fail. This is useful if for when you need to change
// something in a wing that this updates elsewhere in Fred. Normally when auto-update
// kicks in, the changes you make will be wiped out by the auto=update, so instead you
// would call this function to update the wing, make your changes, and then call the
// initialize_data_safe() function to show your changes in the dialog
void wing_editor::update_data_safe()
{
char buf[512];
int i, d, hotkey = -1;
nprintf(("Fred routing", "Wing dialog save safe\n"));
if (!GetSafeHwnd())
return;
UpdateData(TRUE);
UpdateData(TRUE);
if (cur_wing < 0)
return;
if (m_threshold >= Wings[cur_wing].wave_count) {
m_threshold = Wings[cur_wing].wave_count - 1;
if (!bypass_errors)
sprintf(buf, "Wave threshold is set too high. Value has been lowered to %d", (int) m_threshold);
MessageBox(buf);
}
if (m_threshold + Wings[cur_wing].wave_count > MAX_SHIPS_PER_WING) {
m_threshold = MAX_SHIPS_PER_WING - Wings[cur_wing].wave_count;
if (!bypass_errors)
sprintf(buf, "Wave threshold is set too high. Value has been lowered to %d", (int) m_threshold);
MessageBox(buf);
}
if (m_waves < 1) {
m_waves = 1;
if (!bypass_errors)
sprintf(buf, "Number of waves illegal. Has been set to 1.", (int) m_waves);
MessageBox(buf);
}
MODIFY(Wings[cur_wing].special_ship, m_special_ship);
MODIFY(Wings[cur_wing].num_waves, m_waves);
MODIFY(Wings[cur_wing].threshold, m_threshold);
MODIFY(Wings[cur_wing].arrival_location, m_arrival_location);
MODIFY(Wings[cur_wing].departure_location, m_departure_location);
MODIFY(Wings[cur_wing].arrival_delay, m_arrival_delay);
if (m_arrival_delay_min > m_arrival_delay_max) {
if (!bypass_errors)
sprintf(buf, "Arrival delay minimum greater than maximum. Value lowered to %d", m_arrival_delay_max);
MessageBox(buf);
m_arrival_delay_min = m_arrival_delay_max;
}
MODIFY(Wings[cur_wing].wave_delay_min, m_arrival_delay_min);
MODIFY(Wings[cur_wing].wave_delay_max, m_arrival_delay_max);
MODIFY(Wings[cur_wing].arrival_distance, m_arrival_dist);
if (m_arrival_target >= 0) {
i = ((CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET)) -> GetItemData(m_arrival_target);
MODIFY(Wings[cur_wing].arrival_anchor, i);
// when arriving near or in front of a ship, be sure that we are far enough away from it!!!
if (((m_arrival_location != ARRIVE_AT_LOCATION) && (m_arrival_location != ARRIVE_FROM_DOCK_BAY)) && (i >= 0) && (i < SPECIAL_ARRIVAL_ANCHORS_OFFSET)) {
d = int(min(500, 2.0f * Objects[Ships[i].objnum].radius));
if ((Wings[cur_wing].arrival_distance < d) && (Wings[cur_wing].arrival_distance > -d)) {
if (!bypass_errors)
sprintf(buf, "Ship must arrive at least %d meters away from target.\n"
"Value has been reset to this. Use with caution!\r\n"
"Reccomended distance is %d meters.\r\n", d, (int)(2.0f * Objects[Ships[i].objnum].radius) );
MessageBox(buf);
if (Wings[cur_wing].arrival_distance < 0)
Wings[cur_wing].arrival_distance = -d;
else
Wings[cur_wing].arrival_distance = d;
m_arrival_dist = Wings[cur_wing].arrival_distance;
}
}
}
i = ((CComboBox*)GetDlgItem(IDC_DEPARTURE_TARGET))->GetItemData(m_departure_target);
if (m_departure_location == DEPART_AT_DOCK_BAY)
MODIFY(Wings[cur_wing].departure_anchor, i);
else
MODIFY(Wings[cur_wing].jump_anchor, m_departure_target);
MODIFY(Wings[cur_wing].departure_delay, m_departure_delay);
hotkey = m_hotkey - 1;
MODIFY(Wings[cur_wing].hotkey, hotkey);
if ( m_ignore_count ) {
if ( !(Wings[cur_wing].flags & WF_IGNORE_COUNT) )
set_modified();
Wings[cur_wing].flags |= WF_IGNORE_COUNT;
} else {
if ( Wings[cur_wing].flags & WF_IGNORE_COUNT )
set_modified();
Wings[cur_wing].flags &= ~WF_IGNORE_COUNT;
}
if ( m_no_arrival_music ) {
if ( !(Wings[cur_wing].flags & WF_NO_ARRIVAL_MUSIC) )
set_modified();
Wings[cur_wing].flags |= WF_NO_ARRIVAL_MUSIC;
} else {
if ( Wings[cur_wing].flags & WF_NO_ARRIVAL_MUSIC )
set_modified();
Wings[cur_wing].flags &= ~WF_NO_ARRIVAL_MUSIC;
}
// check the no message flag
if ( m_no_arrival_message ) {
if ( !(Wings[cur_wing].flags & WF_NO_ARRIVAL_MESSAGE) )
set_modified();
Wings[cur_wing].flags |= WF_NO_ARRIVAL_MESSAGE;
} else {
if ( Wings[cur_wing].flags & WF_NO_ARRIVAL_MESSAGE )
set_modified();
Wings[cur_wing].flags &= ~WF_NO_ARRIVAL_MESSAGE;
}
// set the no warp effect for wings flag
if ( m_no_arrival_warp ) {
if ( !(Wings[cur_wing].flags & WF_NO_ARRIVAL_WARP) )
set_modified();
Wings[cur_wing].flags |= WF_NO_ARRIVAL_WARP;
} else {
if ( Wings[cur_wing].flags & WF_NO_ARRIVAL_WARP )
set_modified();
Wings[cur_wing].flags &= ~WF_NO_ARRIVAL_WARP;
}
// set the no warp effect for wings flag
if ( m_no_departure_warp ) {
if ( !(Wings[cur_wing].flags & WF_NO_DEPARTURE_WARP) )
set_modified();
Wings[cur_wing].flags |= WF_NO_DEPARTURE_WARP;
} else {
if ( Wings[cur_wing].flags & WF_NO_DEPARTURE_WARP )
set_modified();
Wings[cur_wing].flags &= ~WF_NO_DEPARTURE_WARP;
}
if ( m_no_dynamic ) {
if ( !(Wings[cur_wing].flags & WF_NO_DYNAMIC) )
set_modified();
Wings[cur_wing].flags |= WF_NO_DYNAMIC;
} else {
if ( Wings[cur_wing].flags & WF_NO_DYNAMIC )
set_modified();
Wings[cur_wing].flags &= ~WF_NO_DYNAMIC;
}
if (Wings[cur_wing].arrival_cue >= 0)
free_sexp2(Wings[cur_wing].arrival_cue);
Wings[cur_wing].arrival_cue = m_arrival_tree.save_tree();
if (Wings[cur_wing].departure_cue >= 0)
free_sexp2(Wings[cur_wing].departure_cue);
Wings[cur_wing].departure_cue = m_departure_tree.save_tree();
// copy squad stuff
if(stricmp(m_wing_squad_filename, Wings[cur_wing].wing_squad_filename))
{
string_copy(Wings[cur_wing].wing_squad_filename, m_wing_squad_filename, MAX_FILENAME_LEN);
set_modified();
}
if (modified)
set_modified();
}
BOOL wing_editor::OnCommand(WPARAM wParam, LPARAM lParam)
{
int id, wing;
id = LOWORD(wParam);
if (id >= ID_WING_MENU && id < ID_WING_MENU + MAX_WINGS) {
if (!update_data()) {
wing = id - ID_WING_MENU;
mark_wing(wing);
return 1;
}
}
return CDialog::OnCommand(wParam, lParam);
}
void wing_editor::OnDeltaposSpinWaves(NMHDR* pNMHDR, LRESULT* pResult)
{
int new_pos;
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
new_pos = pNMUpDown->iPos + pNMUpDown->iDelta;
if (new_pos > 0 && new_pos < 100) {
*pResult = 0;
modified = 1;
} else
*pResult = 1;
}
void wing_editor::OnRclickArrivalTree(NMHDR* pNMHDR, LRESULT* pResult)
{
m_arrival_tree.right_clicked();
*pResult = 0;
}
void wing_editor::OnRclickDepartureTree(NMHDR* pNMHDR, LRESULT* pResult)
{
m_departure_tree.right_clicked();
*pResult = 0;
}
void wing_editor::OnBeginlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
if (m_arrival_tree.edit_label(pTVDispInfo->item.hItem) == 1) {
*pResult = 0;
modified = 1;
} else
*pResult = 1;
}
void wing_editor::OnBeginlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
if (m_departure_tree.edit_label(pTVDispInfo->item.hItem) == 1) {
*pResult = 0;
modified = 1;
} else
*pResult = 1;
}
void wing_editor::OnEndlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
*pResult = m_arrival_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText);
}
void wing_editor::OnEndlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
*pResult = m_departure_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText);
}
int wing_editor::verify()
{
nprintf(("Fred routing", "Wing dialog verify\n"));
if (!GetSafeHwnd() || !modified)
return 0;
if (bypass_errors)
return 1;
return 0;
}
// delete wing and all ships that are part of the wing
void wing_editor::OnDeleteWing()
{
modified = 0; // no need to run update checks, since wing will be gone shortly anyway.
delete_wing(cur_wing);
}
// delete wing, but leave ships intact and wingless
void wing_editor::OnDisbandWing()
{
modified = 0; // no need to run update checks, since wing will be gone shortly anyway.
remove_wing(cur_wing);
}
void wing_editor::OnGoals2()
{
ShipGoalsDlg dlg_goals;
Assert(cur_wing != -1);
dlg_goals.self_wing = cur_wing;
dlg_goals.DoModal();
if (query_initial_orders_conflict(cur_wing))
MessageBox("One or more ships of this flight group also has initial orders",
"Possible conflict");
}
void wing_editor::OnReinforcement()
{
UpdateData(TRUE);
UpdateData(TRUE);
//if (m_reinforcement)
// m_arrival_tree.clear_tree("false");
}
void wing_editor::OnPrev()
{
int wing, count = 0;
if (!update_data() && num_wings) {
wing = cur_wing - 1;
if (wing < 0)
wing = MAX_WINGS - 1;
while (!Wings[wing].wave_count) {
wing--;
if (count++ > MAX_WINGS)
return;
if (wing < 0)
wing = MAX_WINGS - 1;
}
mark_wing(wing);
Wing_editor_dialog.initialize_data(1);
Update_wing = 0;
}
return;
}
void wing_editor::OnNext()
{
int wing, count = 0;
if (!update_data() && num_wings) {
wing = cur_wing + 1;
if (wing >= MAX_WINGS)
wing = 0;
while (!Wings[wing].wave_count) {
wing++;
if (count++ > MAX_WINGS)
return;
if (wing >= MAX_WINGS)
wing = 0;
}
mark_wing(wing);
Wing_editor_dialog.initialize_data(1);
Update_wing = 0;
}
return;
}
void wing_editor::OnSelchangedArrivalTree(NMHDR* pNMHDR, LRESULT* pResult)
{
HTREEITEM h;
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
h = pNMTreeView->itemNew.hItem;
if (h)
m_arrival_tree.update_help(h);
*pResult = 0;
}
void wing_editor::OnSelchangedDepartureTree(NMHDR* pNMHDR, LRESULT* pResult)
{
HTREEITEM h;
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
h = pNMTreeView->itemNew.hItem;
if (h)
m_departure_tree.update_help(h);
*pResult = 0;
}
void wing_editor::calc_cue_height()
{
CRect cue;
GetDlgItem(IDC_CUE_FRAME)->GetWindowRect(cue);
cue_height = cue.bottom - cue.top + 10;
if (Show_sexp_help)
cue_height += SEXP_HELP_BOX_SIZE;
if (Hide_wing_cues) {
((CButton *) GetDlgItem(IDC_HIDE_CUES)) -> SetCheck(1);
OnHideCues();
}
}
void wing_editor::show_hide_sexp_help()
{
CRect rect;
if (Show_sexp_help)
cue_height += SEXP_HELP_BOX_SIZE;
else
cue_height -= SEXP_HELP_BOX_SIZE;
if (((CButton *) GetDlgItem(IDC_HIDE_CUES)) -> GetCheck())
return;
GetWindowRect(rect);
if (Show_sexp_help)
rect.bottom += SEXP_HELP_BOX_SIZE;
else
rect.bottom -= SEXP_HELP_BOX_SIZE;
MoveWindow(rect);
}
void wing_editor::OnHideCues()
{
CRect rect;
GetWindowRect(rect);
if (((CButton *) GetDlgItem(IDC_HIDE_CUES)) -> GetCheck()) {
rect.bottom -= cue_height;
Hide_wing_cues = 1;
} else {
rect.bottom += cue_height;
Hide_wing_cues = 0;
}
MoveWindow(rect);
}
void wing_editor::OnSelchangeArrivalLocation()
{
CComboBox *box;
box = (CComboBox *)GetDlgItem(IDC_ARRIVAL_TARGET);
UpdateData();
if (m_arrival_location) {
GetDlgItem(IDC_ARRIVAL_DISTANCE)->EnableWindow(TRUE);
GetDlgItem(IDC_ARRIVAL_TARGET)->EnableWindow(TRUE);
if (m_arrival_target < 0) {
m_arrival_target = 0;
}
// determine which items we should put into the arrival target combo box
if ( m_arrival_location == ARRIVE_FROM_DOCK_BAY ) {
management_add_ships_to_combo( box, SHIPS_2_COMBO_DOCKING_BAY_ONLY );
} else {
management_add_ships_to_combo( box, SHIPS_2_COMBO_SPECIAL | SHIPS_2_COMBO_ALL_SHIPS );
}
} else {
m_arrival_target = -1;
GetDlgItem(IDC_ARRIVAL_DISTANCE)->EnableWindow(FALSE);
GetDlgItem(IDC_ARRIVAL_TARGET)->EnableWindow(FALSE);
}
UpdateData(FALSE);
}
void wing_editor::OnSelchangeDepartureLocation()
{
CComboBox *box;
box = (CComboBox *)GetDlgItem(IDC_DEPARTURE_TARGET);
UpdateData();
if (m_departure_location) {
GetDlgItem(IDC_DEPARTURE_TARGET)->EnableWindow(TRUE);
if (m_departure_target < 0) {
m_departure_target = 0;
}
// we need to build up the list box content based on the departure type. When
// from a docking bay, only show ships in the list which have them. Show all ships otherwise
if ( m_departure_location == DEPART_AT_DOCK_BAY ) {
management_add_ships_to_combo( box, SHIPS_2_COMBO_DOCKING_BAY_ONLY );
} else {
// I think that this section is currently illegal
Int3();
}
} else {
box->ResetContent();
box->EnableWindow(TRUE);
if ( m_departure_target < 0 )
m_departure_target = -1;
m_departure_target = 0;
box->AddString("None");
for (int i=0; i<Num_jump_nodes; i++)
box->AddString(Jumppoint_lists[i].name);
//GetDlgItem(IDC_DEPARTURE_TARGET)->EnableWindow(FALSE);
}
UpdateData(FALSE);
}
// see if hotkey should possibly be reserved for player starting wing
void wing_editor::OnSelchangeHotkey()
{
char buf[256];
int set_num, i;
UpdateData(TRUE);
set_num = m_hotkey - 1; // hotkey sets are 1 index based
// first, determine if we are currently working with a starting wing
for ( i = 0; i < MAX_STARTING_WINGS; i++ ) {
if ( !stricmp( Wings[cur_wing].name, Starting_wing_names[i]) )
break;
}
if ( i == MAX_STARTING_WINGS )
return;
// we have a player starting wing. See if we assigned a non-standard hotkey
if ( (set_num >= MAX_STARTING_WINGS) || (set_num != i) ) {
sprintf(buf, "Assigning nonstandard hotkey to flight group %s (default is F%d)", Wings[cur_wing].name, 5+i);
MessageBox(buf, NULL, MB_OK | MB_ICONEXCLAMATION );
}
}
void wing_editor::OnSquadLogo()
{
CString pcx_filename;
int z;
// get list of squad images
z = cfile_push_chdir(CF_TYPE_SQUAD_IMAGES_MAIN);
CFileDialog dlg(TRUE, "pcx", pcx_filename, OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Pcx Files (*.pcx)|*.pcx");
// if we have a result
if (dlg.DoModal() == IDOK) {
m_wing_squad_filename = dlg.GetFileName();
} else {
m_wing_squad_filename = _T("");
}
UpdateData(FALSE);
// restore directory
if (!z){
cfile_pop_dir();
}
}
|
[
"[email protected]"
] |
[
[
[
1,
1461
]
]
] |
3dd93e0dbbddc690953b61bd13bdb961fb610334
|
26b6f15c144c2f7a26ab415c3997597fa98ba30a
|
/sdp/inc/RtpAvpConstants.h
|
e6e620c7afaca11d19572b50644f43eb76f801f8
|
[] |
no_license
|
wangscript007/rtspsdk
|
fb0b52e63ad1671e8b2ded1d8f10ef6c3c63fddf
|
f5b095f0491e5823f50a83352945acb88f0b8aa0
|
refs/heads/master
| 2022-03-09T09:25:23.988183 | 2008-12-27T17:23:31 | 2008-12-27T17:23:31 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,422 |
h
|
/*****************************************************************************
// SDP Parser Classes
//
// RTP/AVP Constants
//
// description:
// defines some constants that can be used when creating
// MediaFields with the RTP/AVP transport protocol
//
// revision of last commit:
// $Rev$
// author of last commit:
// $Author$
// date of last commit:
// $Date$
//
// created by Argenet {[email protected]}
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
******************************************************************************/
#ifndef __RTP_AVP_CONSTANTS__H__
#define __RTP_AVP_CONSTANTS__H__
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Includes
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include "sdp_parser.h"
#include "common.h"
namespace SDP {
typedef struct SDP_PARSER_API _RtpAvpConstants
/// This class defines some constants that can be used when creating MediaFields with the RTP/AVP
/// transport protocol.
{
static const std::string RESERVED;
/// An int greater than or equal to 0 and less than AVP_DEFINED_STATIC_MAX,
/// but has not been assigned a value.
static const std::string UNASSIGNED;
/// Unassigned Payload type.
/// An int greater than or equal to AVP_DEFINED_STATIC_MAX and less than
/// AVP_DYNAMIC_MIN - currently unassigned.
static const std::string DYNAMIC;
/// Dynamic Payload type.
/// Any int less than 0 or greater than or equal to AVP_DYNAMIC_MIN
static const std::string RTP_AVP;
/// RTP/AVP Protocol
static const std::string RTPMAP;
/// RTP mapping attribute.
///
/// SDP is case-sensitive; RFC2327 specifies 'rtpmap' (all smallcap)
static const std::string FMTP;
/// RTP mapping attribute.
static const std::string CONTROL;
/// RTP attribute.
static const int PCMU = 0;
/// Static RTP/AVP payload type for the PCMU audio codec.
static const int TENSIXTEEN = 1;
/// Static RTP/AVP payload type for the TENSIXTEEN audio codec.
static const int G726_32 = 2;
/// Static RTP/AVP payload type for the G726_32 audio codec.
static const int GSM = 3;
/// Static RTP/AVP payload type for the GSM audio codec.
static const int G723 = 4;
/// Static RTP/AVP payload type for the G723 audio codec.
static const int DVI4_8000 = 5;
/// Static RTP/AVP payload type for the DVI4_8000 audio codec.
static const int DVI4_16000 = 6;
/// Static RTP/AVP payload type for the DVI4_16000 audio codec.
static const int LPC = 7;
/// Static RTP/AVP payload type for the LPC audio codec.
static const int PCMA = 8;
/// Static RTP/AVP payload type for the PCMA audio codec.
static const int G722 = 9;
/// Static RTP/AVP payload type for the G722 audio codec.
static const int L16_2CH = 10;
/// Static RTP/AVP payload type for the L16_2CH audio codec.
static const int L16_1CH = 11;
/// Static RTP/AVP payload type for the L16_1CH audio codec.
static const int QCELP = 12;
/// Static RTP/AVP payload type for QCELP audio codec.
static const int CN = 13;
/// Static RTP/AVP payload type for the CN audio codec.
static const int MPA = 14;
/// Static RTP/AVP payload type for the MPA audio codec.
static const int G728 = 15;
/// Static RTP/AVP payload type for the G728 audio codec.
static const int DVI4_11025 = 16;
/// Static RTP/AVP payload type for the DVI4_11025 audio codec
static const int DVI4_22050 = 17;
/// Static RTP/AVP payload type for the DVI4_22050 audio codec.
static const int G729 = 18;
/// Static RTP/AVP payload type for the G729 audio codec.
static const int CN_DEPRECATED = 19;
/// Static RTP/AVP payload type for the CN audio codec.
static const int CELB = 25;
/// Static RTP/AVP payload type for the CELB video codec.
static const int JPEG = 26;
/// Static RTP/AVP payload type for the JPEG video codec.
static const int NV = 28;
/// Static RTP/AVP payload type for the NV video codec.
static const int H261 = 31;
/// Static RTP/AVP payload type for the H261 video codec.
static const int MPV = 32;
/// Static RTP/AVP payload type for the MPV video codec.
static const int MP2T = 33;
/// Static RTP/AVP payload type for the MP2T video codec.
static const int H263 = 34;
/// Static RTP/AVP payload type for the H263 video codec.
static const int AVP_DEFINED_STATIC_MAX = 35;
/// Highest defined static payload type. This is (currently) 35.
static const int AVP_DYNAMIC_MIN = -35;
/// The minimum defined dynamic format value
static const std::string avpTypeNames[AVP_DEFINED_STATIC_MAX];
/// Names of AVP (Audio-Video Profile) payload types indexed on their static payload types.
static const int avpClockRates[AVP_DEFINED_STATIC_MAX];
/// Clock rates for various AVP payload types indexed by their static payload types.
static const int avpChannels[AVP_DEFINED_STATIC_MAX];
/// Channels per static type.
} RtpAvpConstants;
} // namespace SDP
#endif // __RTP_AVP_CONSTANTS__H__
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
185
]
],
[
[
186,
187
]
]
] |
9b3104480f27dbb52397d7ef6afa706b27ceb302
|
59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02
|
/publish/skinctrlex/skinbuttonex.h
|
15560c5c2d9b8192ee759d420cf6e5ab81616b56
|
[] |
no_license
|
fingomajom/skinengine
|
444a89955046a6f2c7be49012ff501dc465f019e
|
6bb26a46a7edac88b613ea9a124abeb8a1694868
|
refs/heads/master
| 2021-01-10T11:30:51.541442 | 2008-07-30T07:13:11 | 2008-07-30T07:13:11 | 47,892,418 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 8,337 |
h
|
/* -------------------------------------------------------------------------
// 文件名 : ksgui/skinctrlex/skinbuttonex.h
// 创建人 : 冰峰
// 创建时间 : 2008-4-28 16:24:25
// 功能描述 : 增强自由的Button
//
// $Id: $
// -----------------------------------------------------------------------*/
#ifndef __KSGUI_SKINCTRLEX_SKINBUTTONEX_H__
#define __KSGUI_SKINCTRLEX_SKINBUTTONEX_H__
#include "../ksguicommon/drawer/KFormatDrawer.h"
namespace KSGUI{
#define _INNER_SPACE_AFTER_PREFIX 4
//////////////////////////////////////////////////////////////////////////
// 增强自由的ButtonEx
class CSkinButtonEx : public SkinWindowImpl<CSkinButtonEx, CButton>,
public WTL::COwnerDraw<CSkinButtonEx>
{
public:
typedef SkinWindowImpl<CSkinButtonEx, CButton> _Base;
typedef CSkinButtonEx _Self;
private:
KSingleLineHTMLControl m_Drawer;
CImageList m_imPrefixState; //单选框/复选框的状态
CToolTipCtrl m_ToolTip;
WTL::CString m_strToolTip; //Tooltip String
UINT m_nCustomStyle; //自定义样式
// Internal states
unsigned m_nChecked:4;
unsigned m_bMouseOver:1;
unsigned m_bFocus:1;
unsigned m_bPressed:1;
//////////////////////////////////////////////////////////////////////////
// Init
public:
CSkinButtonEx()
{
m_bMouseOver = 0;
m_bPressed = 0;
}
~CSkinButtonEx()
{
}
BOOL SubclassWindow(HWND hWnd)
{
ATLASSERT(m_hWnd == NULL);
ATLASSERT(::IsWindow(hWnd));
BOOL bRet = _Base::SubclassWindow(hWnd);
if(bRet)
_Init();
return bRet;
}
//////////////////////////////////////////////////////////////////////////
// 导出函数
public:
void SetCustomStyle(UINT nStyle)
{
m_nCustomStyle = nStyle;
}
BOOL SetRichText(LPCTSTR szRichText, int nAlignType = AT_DEFAULT, int nIndent = 0)
{
//Setting
CRect rc;
GetClientRect(&rc);
m_Drawer.SetPageSize(rc.Width() - _GetLeftInnerWidth(), rc.Height());
m_Drawer.SetAlignStyle(nAlignType);
m_Drawer.SetIndent(nIndent);
m_Drawer.SetRichText(szRichText);
return TRUE;
}
BOOL SetPrefixState(HBITMAP hBitmap, COLORREF rMask, int cx = -1, int cy = -1)
{
CBitmapHandle bitmap(hBitmap);
CSize size;
bitmap.GetSize(size);
if (cx == -1)
cx = size.cx;
if (cy == -1)
cy = size.cy;
m_imPrefixState.Create(cx, cy, ILC_COLOR16 | ILC_MASK, 0, 0);
m_imPrefixState.Add(hBitmap, rMask);
return TRUE;
}
BOOL SetImage(LPCTSTR szName, HIMAGELIST hImageList)
{
return KImageListManager::Instance()->AddImageList(szName, hImageList);
}
BOOL SetToolTipText(LPCTSTR szToolTipText)
{
if (szToolTipText == NULL) //清掉
{
m_ToolTip.Activate(FALSE);
return TRUE;
}
//
if(!m_ToolTip.IsWindow())
{
m_strToolTip = szToolTipText;
if(m_ToolTip.Create(m_hWnd))
{
CRect rc;
GetClientRect(&rc);
if(m_ToolTip.AddTool(m_hWnd, (LPCTSTR)m_strToolTip), &rc)
{
m_ToolTip.Activate(TRUE);
}
}
}
else
{
m_ToolTip.UpdateTipText(szToolTipText, m_hWnd);
}
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
// 消息
public:
BEGIN_MSG_MAP(CSkinButtonEx)
MESSAGE_HANDLER(WM_CREATE , OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(BM_SETCHECK, OnSetCheck)
MESSAGE_HANDLER(BM_GETCHECK, OnGetCheck)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
MESSAGE_HANDLER(WM_MOUSELEAVE, OnMouseLeave)
CHAIN_MSG_MAP_ALT(COwnerDraw<_Self>, 1)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
_Init();
return 1L;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
//放掉数据
m_imPrefixState.Destroy();
if (m_ToolTip.IsWindow())
m_ToolTip.DestroyWindow();
bHandled = FALSE;
return 1L;
}
LRESULT OnSetCheck(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
m_nChecked = wParam;
// 组中其它项都清掉
HWND hwndParent = GetParent();
ASSERT(hwndParent);
HWND hwndNext = m_hWnd;
for ( ; wParam == BST_CHECKED; )
{
hwndNext = ::GetNextDlgGroupItem(hwndParent, hwndNext, FALSE);
if (hwndNext == m_hWnd)
break;
::SendMessage(hwndNext, BM_SETCHECK, BST_UNCHECKED, 0);
}
if (m_nChecked == BST_UNCHECKED)
Invalidate();
return 1L;
}
LRESULT OnGetCheck(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return m_nChecked;
}
LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MSG msg = { m_hWnd, uMsg, wParam, lParam };
if(m_ToolTip.IsWindow())
m_ToolTip.RelayEvent(&msg);
bHandled = FALSE;
return 1L;
}
LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
m_bPressed = TRUE;
Invalidate();
UpdateWindow();
return lRet;
}
LRESULT OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
if(m_bPressed)
{
m_bPressed = FALSE;
::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
}
_Base::SetCheck(BST_CHECKED);
m_ToolTip.Activate(TRUE);
return lRet;
}
LRESULT OnEnable(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
Invalidate();
UpdateWindow();
bHandled = FALSE;
return 1;
}
LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
if(m_bMouseOver == 0)
{
m_bMouseOver = 1;
Invalidate();
UpdateWindow();
StartTrackMouseLeave();
}
bHandled = FALSE;
return 1;
}
LRESULT OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
if(m_bMouseOver == 1)
{
m_bMouseOver = 0;
Invalidate();
UpdateWindow();
}
bHandled = FALSE;
return 1;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1; // no background needed
}
void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
CDCHandle dc(lpDrawItemStruct->hDC);
CRect rc(lpDrawItemStruct->rcItem);
if (_HasPrefixState())
{
int nImageIndex;
SIZE size;
m_imPrefixState.GetIconSize(size);
int nOffsetY = (rc.Height() - size.cy) / 2;
if (m_nChecked == BST_CHECKED /*&& !m_bPressed*/)
nImageIndex = 3;
else
nImageIndex = 0;
if (m_bMouseOver)
nImageIndex += 1;
// if (m_bPressed)
// nImageIndex += 2;
m_imPrefixState.Draw(dc, nImageIndex, 0, nOffsetY, ILD_TRANSPARENT);
rc.left += _GetLeftInnerWidth();
}
dc.SetBkMode(TRANSPARENT);
m_Drawer.Draw(dc, &rc);
}
//////////////////////////////////////////////////////////////////////////
// Helper
private:
void _Init()
{
ModifyStyle(0, BS_OWNERDRAW);
}
inline BOOL _IsRadioButton()
{
DWORD dwStyle = GetStyle();
return dwStyle & BS_RADIOBUTTON || dwStyle & BS_AUTORADIOBUTTON;
}
inline BOOL _IsCheckBoxButton()
{
DWORD dwStyle = GetStyle();
return dwStyle & BS_CHECKBOX || dwStyle & BS_AUTOCHECKBOX;
}
inline BOOL _HasPrefixState()
{
return _IsRadioButton() || _IsCheckBoxButton();
}
inline int _GetLeftInnerWidth()
{
CSize size;
if (_IsRadioButton() || _IsCheckBoxButton())
{
m_imPrefixState.GetIconSize(size);
return size.cx + _INNER_SPACE_AFTER_PREFIX;
}
else
{
return 0;
}
}
BOOL StartTrackMouseLeave()
{
TRACKMOUSEEVENT tme = { 0 };
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = m_hWnd;
return _TrackMouseEvent(&tme);
}
};
};
// -------------------------------------------------------------------------
// $Log: $
#endif /* __KSGUI_SKINCTRLEX_SKINBUTTONEX_H__ */
|
[
"[email protected]"
] |
[
[
[
1,
356
]
]
] |
25bf558b4a885a47de5ff9db85150b2871cd225d
|
6629f18d84dc8d5a310b95fedbf5be178b00da92
|
/SDK-2008-05-27/foobar2000/SDK/commandline.h
|
7237c347487978afba992bb3a203e3c3c6b1c0a8
|
[] |
no_license
|
thenfour/WMircP
|
317f7b36526ebf8061753469b10f164838a0a045
|
ad6f4d1599fade2ae4e25656a95211e1ca70db31
|
refs/heads/master
| 2021-01-01T17:42:20.670266 | 2008-07-11T03:10:48 | 2008-07-11T03:10:48 | 16,931,152 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,374 |
h
|
#ifndef _FOOBAR2000_SDK_COMMANDLINE_H_
#define _FOOBAR2000_SDK_COMMANDLINE_H_
#include "service.h"
class NOVTABLE commandline_handler : public service_base
{
public:
enum result
{
RESULT_NOT_OURS,//not our command
RESULT_PROCESSED,//command processed
RESULT_PROCESSED_EXPECT_FILES,//command processed, we want to takeover file urls after this command
};
virtual result on_token(const char * token)=0;
virtual void on_file(const char * url) {};//optional
virtual void on_files_done() {};//optional
virtual bool want_directories() {return false;}
FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(commandline_handler);
};
class commandline_handler_metadb_handle : public commandline_handler//helper
{
protected:
virtual void on_file(const char * url);
virtual bool want_directories() {return true;}
public:
virtual result on_token(const char * token)=0;
virtual void on_files_done() {};
virtual void on_file(const metadb_handle_ptr & ptr)=0;
};
/*
how commandline_handler is used:
scenario #1:
creation => on_token() => deletion
scenario #2:
creation => on_token() returning RESULT_PROCESSED_EXPECT_FILES => on_file(), on_file().... => on_files_done() => deletion
*/
template<typename T>
class commandline_handler_factory_t : public service_factory_t<T> {};
#endif //_FOOBAR2000_SDK_COMMANDLINE_H_
|
[
"carl@72871cd9-16e1-0310-933f-800000000000"
] |
[
[
[
1,
50
]
]
] |
a7be313157836a6ba37531769584e9612048a22a
|
15f5ea95f75eebb643a9fa4d31592b2537a33030
|
/src/re167/BasicMath.h
|
8445737c96ea49a0e3bd15be046d4c04ccbcd64c
|
[] |
no_license
|
festus-onboard/graphics
|
90aaf323e188b205661889db2c9ac59ed43bfaa7
|
fdd195cd758ef95147d2d02160062d2014e50e04
|
refs/heads/master
| 2021-05-26T14:38:54.088062 | 2009-05-10T16:59:28 | 2009-05-10T16:59:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 831 |
h
|
#ifndef __BasicMath_h__
#define __BasicMath_h__
#include "RE167_global.h"
#include <math.h>
namespace RE167
{
/** Basic math utility class.
@remarks
Implements some basic math utilities and defines useful constants,
such as PI.
*/
class RE167_EXPORT BasicMath
{
public:
static const float PI;
static const float TWO_PI;
static float radian(float a) { return a*PI/180.f; };
static float degrees(float radians) { return radians * 180.f / PI; }
static bool AlmostEqual2sComplement(float A, float B, int maxUlps);
static bool approxEqual (float A, float B);
static float clamp(const float val, const float min, const float max);
static float randBetween(const float min, const float max);
private:
static const int MAX_NUM_DIGITS_DIFFERENCE = 1;
};
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
37
]
]
] |
cae1dba3168b378adad103ea9c2854df25cd9701
|
160e08f968425ae7b8e83f7381c617906b4e9f18
|
/TimeServices.Engine.Cpu/Core/SliceFractions.h
|
07da5904d96507bcdb73641d14d354183639e48b
|
[] |
no_license
|
m3skine/timeservices
|
0f6a938a25a49a0cad884e2ae9fb1fff4a8a08fe
|
1efca945a2121cd7f45c05387503ea8ef66541e6
|
refs/heads/master
| 2020-04-10T20:06:24.326180 | 2010-04-21T01:12:44 | 2010-04-21T01:12:44 | 33,272,683 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 455 |
h
|
#pragma once
#include "SliceNode.h"
using namespace System::Collections::Generic;
namespace TimeServices { namespace Engine { namespace Core {
struct SliceFractions //: SortedDictionary<unsigned long, Slice>
{
public:
bool TryGetValue(unsigned long fraction, SliceNode* node)
{
return false;
}
void Add(unsigned long fraction, LinkKind* value)
{
}
void Add(unsigned long fraction, ListKind* value)
{
}
};
}}}
|
[
"Moreys@localhost"
] |
[
[
[
1,
20
]
]
] |
71bb37f772e5cbea504f43e71e8e6fe365f57128
|
b236da3776ea1085448f6d8669e1f36189ad3a3b
|
/public-ro/mlc/h/dutables.h
|
b80924cd6b206c1924f3583261128f4e81b0ffd8
|
[] |
no_license
|
jirihelmich/mlaskal
|
f79a9461b9bbf00d0c9c8682ac52811e397a0c5d
|
702cb0e1e81dc3524719d361ba48e7ec9e68cf91
|
refs/heads/master
| 2021-01-13T01:40:09.443603 | 2010-12-14T18:33:02 | 2010-12-14T18:33:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 41,533 |
h
|
/*
DUTABLES.H
DB
Mlaskal's semantic tables
*/
#ifndef __DUTABLES_H
#define __DUTABLES_H
#include "common_types.hpp"
#include "literal_storage.hpp"
#include "flat_icblock.hpp"
#include "labeled_icblock.hpp"
#include "uid_gen.hpp"
#include <vector>
#include <map>
#include <limits>
namespace mlc {
// literal storages
/// integer literal storage type
typedef mlaskal::lit_storage<int> ls_int_type;
/// real literal storage type
typedef mlaskal::lit_storage<double> ls_real_type;
/// string literal storage type
typedef mlaskal::lit_storage<std::string> ls_str_type;
/// identifier storage type
typedef mlaskal::lit_storage<std::string> ls_id_type;
/*
/// integer literal storage
extern ls_int_type ls_int;
/// real literal storage
extern ls_real_type ls_real;
/// string literal storage
extern ls_str_type ls_str;
/// identifier storage
extern ls_id_type ls_id;
*/
/*************************************************************************/
/// stack offset type
/** this type is used to store addresses of global and local variables **/
typedef mlaskal::ICRELNUM stack_address;
/// integer literal index
typedef ls_int_type::const_iterator ls_int_index;
/// real literal index
typedef ls_real_type::const_iterator ls_real_index;
/// string literal index
typedef ls_str_type::const_iterator ls_str_index;
/// identifier index
typedef ls_id_type::const_iterator ls_id_index;
/*************************************************************************/
/// intermediate code label
typedef mlaskal::labeled_icblock::label_type ic_label;
/// intermediate code block
typedef mlaskal::labeled_icblock * icblock_pointer;
/// creates empty icblock
inline icblock_pointer icblock_create()
{
return new mlaskal::labeled_icblock;
}
/// merges two icblocks
/** appends sicb to dicb, kills sicb **/
inline void icblock_append_delete( icblock_pointer dicb, icblock_pointer sicb)
{
dicb->append_clear_block( * sicb);
delete sicb;
}
/// intermediate code label
typedef mlaskal::abstract_functions::iterator ic_function_pointer;
/*************************************************************************/
class symbol_tables;
/* symbol entries */
/// function or procedure parameter modes
enum parameter_mode {
PMODE_UNDEF,
PMODE_BY_VALUE,
PMODE_BY_REFERENCE
};
/*************************************************************************/
class abstract_type;
/// pointer to representation of a type
typedef mlaskal::dumb_pointer< abstract_type> type_pointer;
/*************************************************************************/
class type_entry;
/// \internal vector of type entries
typedef std::list< type_entry> type_vector;
/*************************************************************************/
/// category of a type
enum type_category {
TCAT_UNDEF,
TCAT_ARRAY,
TCAT_RECORD,
TCAT_BOOL,
TCAT_RANGE,
TCAT_INT,
TCAT_REAL,
TCAT_STR
};
/// \internal type_category dumper
std::ostream &operator<<(std::ostream &os, type_category typecat);
class array_type;
class record_type;
class int_type;
class range_type;
class bool_type;
class real_type;
class str_type;
/// pointer to an array_type entry
typedef mlaskal::dumb_pointer< array_type> array_type_pointer;
/// pointer to a record_type entry
typedef mlaskal::dumb_pointer< record_type> record_type_pointer;
/// pointer to an int_type entry
typedef mlaskal::dumb_pointer< int_type> int_type_pointer;
/// pointer to an range_type entry
typedef mlaskal::dumb_pointer< range_type> range_type_pointer;
/// pointer to an bool_type entry
typedef mlaskal::dumb_pointer< bool_type> bool_type_pointer;
/// pointer to an real_type entry
typedef mlaskal::dumb_pointer< real_type> real_type_pointer;
/// pointer to an str_type entry
typedef mlaskal::dumb_pointer< str_type> str_type_pointer;
class DumpUniquizer;
/// abstract entry for a type
class abstract_type {
public:
/// \internal
virtual ~abstract_type() {}
/// returns the category of the type
type_category cat() const { return this ? cat_() : TCAT_UNDEF; }
/// accesses array_type entry if applicable
array_type_pointer access_array() { return this ? arrayType_() : array_type_pointer(); }
/// accesses record_type entry if applicable
record_type_pointer access_record() { return this ? recordType_() : record_type_pointer(); }
/// accesses int_type entry if applicable
int_type_pointer access_int() { return this ? integerType_() : int_type_pointer(); }
/// accesses range_type entry if applicable
range_type_pointer access_range() { return this ? rangeType_() : range_type_pointer(); }
/// accesses bool_type entry if applicable
bool_type_pointer access_bool() { return this ? booleanType_() : bool_type_pointer(); }
/// accesses real_type entry if applicable
real_type_pointer access_real() { return this ? realType_() : real_type_pointer(); }
/// accesses str_type entry if applicable
str_type_pointer access_str() { return this ? stringType_() : str_type_pointer(); }
/// compute the size of the type
/** the size is returned in stack units **/
stack_address compute_size() { return this ? compute_size_() : 0; }
/// compute intermediate code physical type
/** returns the innermost element type for arrays
returns integer for range types
**/
mlaskal::physical_type compute_final_ptype() { return this ? compute_final_ptype_() : mlaskal::PTYPE_UNDEF; }
private:
size_t get_idx() const { return this ? get_idx_() : std::numeric_limits< size_t>::max(); }
virtual type_category cat_() const = 0;
virtual array_type_pointer arrayType_() = 0;
virtual record_type_pointer recordType_() = 0;
virtual int_type_pointer integerType_() = 0;
virtual range_type_pointer rangeType_() = 0;
virtual bool_type_pointer booleanType_() = 0;
virtual real_type_pointer realType_() = 0;
virtual str_type_pointer stringType_() = 0;
virtual stack_address compute_size_() = 0;
virtual mlaskal::physical_type compute_final_ptype_() = 0;
virtual size_t get_idx_() const = 0;
virtual const type_entry * access_entry() const = 0;
friend std::ostream & operator<<( std::ostream & o, type_pointer e);
friend bool identical_type( type_pointer a, type_pointer b);
friend class DumpUniquizer;
friend class type_entry;
};
/// entry for an (one-dimensional) array type
class array_type : public virtual abstract_type {
public:
virtual ~array_type() {}
/// type of the array element
type_pointer element_type() const { return this ? elementType_() : type_pointer(); }
/// type of the index
type_pointer index_type() const { return this ? indexType_() : type_pointer(); }
private:
virtual type_pointer elementType_() const = 0;
virtual type_pointer indexType_() const = 0;
};
class field_entry;
/// pointer to an field_entry
typedef mlaskal::dumb_pointer< const field_entry> field_pointer;
/// \internal parameter entry vector
typedef std::vector< field_entry> field_vector;
/// entry for a record type
class record_type : public virtual abstract_type {
public:
virtual ~record_type() {}
field_pointer find( ls_id_index idx) const { return this ? record_find_( idx) : field_pointer(); }
/// iterator type
typedef field_vector::const_iterator const_iterator;
/// first element
const_iterator begin() const { return record_begin_(); }
/// behind-the-last element
const_iterator end() const { return record_end_(); }
private:
virtual field_pointer record_find_( ls_id_index idx) const = 0;
virtual field_vector::const_iterator record_begin_() const = 0;
virtual field_vector::const_iterator record_end_() const = 0;
};
/// common base for integer and range type entries
class integral_type : public virtual abstract_type {
public:
virtual ~integral_type() {}
};
/// entry for the 'integer' type (singleton)
class int_type : public virtual integral_type {
public:
virtual ~int_type() {}
};
/// entry for a range type
class range_type : public virtual integral_type {
public:
virtual ~range_type() {}
// lower bound (inclusive)
ls_int_index lowerBound() const { return this ? lowerBound_() : ls_int_index(); }
// upper bound (inclusive)
ls_int_index upperBound() const { return this ? upperBound_() : ls_int_index(); }
private:
virtual ls_int_index lowerBound_() const = 0;
virtual ls_int_index upperBound_() const = 0;
};
/// entry for the 'boolean' type (singleton)
class bool_type : public virtual abstract_type {
public:
virtual ~bool_type() {}
};
/// entry for the 'real' type (singleton)
class real_type : public virtual abstract_type {
public:
virtual ~real_type() {}
};
/// entry for the 'string' type (singleton)
class str_type : public virtual abstract_type {
public:
virtual ~str_type() {}
};
class field_list;
/// \internal ordering functor on literal table indexes
template< typename T>
class ls_index_comparator {
public:
bool operator() (
typename mlaskal::lit_storage< T>::const_iterator a,
typename mlaskal::lit_storage< T>::const_iterator b) const
{
return * a < * b;
}
};
/// \internal record field index
typedef std::map< ls_id_index, const field_entry *, ls_index_comparator< std::string> > record_cache_type;
/// \internal implementation of a type entry
class type_entry :
public virtual array_type,
public virtual record_type,
public virtual int_type,
public virtual range_type,
public virtual bool_type,
public virtual real_type,
public virtual str_type
{
private:
type_entry();
type_entry( size_t idx, type_category p);
type_entry( size_t idx, type_category p, field_list * fldlist);
type_entry( size_t idx, type_category p, type_pointer t1, type_pointer t2);
type_entry( size_t idx, type_category p, type_pointer t1, type_pointer t2, ls_int_index s1, ls_int_index s2);
size_t idx_;
type_category typecat;
type_pointer ltype1;
type_pointer ltype2;
ls_int_index idx1;
ls_int_index idx2;
field_list * fldlist;
record_cache_type record_cache;
virtual type_category cat_() const;
virtual array_type_pointer arrayType_();
virtual record_type_pointer recordType_();
virtual int_type_pointer integerType_();
virtual range_type_pointer rangeType_();
virtual bool_type_pointer booleanType_();
virtual real_type_pointer realType_();
virtual str_type_pointer stringType_();
virtual type_pointer elementType_() const;
virtual type_pointer indexType_() const;
virtual ls_int_index lowerBound_() const;
virtual ls_int_index upperBound_() const;
virtual size_t get_idx_() const;
virtual const type_entry * access_entry() const;
virtual stack_address compute_size_();
virtual mlaskal::physical_type compute_final_ptype_();
virtual field_pointer record_find_( ls_id_index idx) const;
virtual field_vector::const_iterator record_begin_() const;
virtual field_vector::const_iterator record_end_() const;
virtual void fill_record_cache( int line);
friend class symbol_tables;
friend class DumpUniquizer;
std::string operator()( std::string & name, std::ostream & oo, DumpUniquizer & uniq) const;
friend std::ostream & operator<<( std::ostream & o, const type_entry & e);
};
/// \internal type_entry dumper
std::ostream & operator<<( std::ostream & o, const type_entry & e);
/*************************************************************************/
/// record field
/** represents a field '\p idx : \p ltype'
**/
class field_entry {
public:
type_pointer type() const
{
return this ? ltype : type_pointer();
}
stack_address offset() const
{
return this ? offset_ : 0;
}
private:
/// constructor
field_entry( ls_id_index i, type_pointer p);
/// identifier index
ls_id_index idx;
/// type
type_pointer ltype;
/// offset
stack_address offset_;
std::string operator()( std::ostream & oo, DumpUniquizer & uniq) const;
friend class type_entry;
friend class field_list;
friend struct flftr;
friend std::ostream & operator<<( std::ostream & o, const field_entry & e);
};
/// \internal parameter entry dumper
std::ostream & operator<<( std::ostream & o, const field_entry & e);
/// \internal parameter entry vector
typedef std::vector< field_entry> field_vector;
/// list of record fields
class field_list {
public:
/// iterator type
typedef field_vector::const_iterator const_iterator;
/// first element
const_iterator begin() const;
/// behind-the-last element
const_iterator end() const;
/// appends a field
void append_field( ls_id_index idx, type_pointer ltype);
/// appends another list of fields
/** kills the list \p ll2 **/
void append_and_kill( field_list * ll2);
/// number of field entries
field_vector::size_type size() const;
private:
void push_back( const field_entry & v);
void append( const field_list & l2);
void assign_offsets();
std::string operator()( std::ostream & oo, DumpUniquizer & uniq) const;
field_vector v_;
stack_address total_size_;
friend std::ostream & operator<<( std::ostream & o, const field_list & e);
friend class symbol_tables;
friend class type_entry;
};
/*************************************************************************/
/// function or procedure parameter entry
/** represents a parameter '\p idx : \p ltype'
'var' parameters are distinguished by \p partype
**/
struct parameter_entry {
/// constructor
parameter_entry( parameter_mode s, ls_id_index i, type_pointer p);
/// by-value or by-reference ('var') parameter
parameter_mode partype;
/// identifier index
ls_id_index idx;
/// type
type_pointer ltype;
std::string operator()( std::ostream & oo, DumpUniquizer & uniq) const;
};
/// \internal parameter entry dumper
std::ostream & operator<<( std::ostream & o, const parameter_entry & e);
/// \internal parameter entry vector
typedef std::vector< parameter_entry> parameter_vector;
class symbol_entry;
/// list of function or procedure parameters
class parameter_list {
public:
/// iterator type
typedef parameter_vector::const_iterator const_iterator;
/// first element
const_iterator begin() const;
/// behind-the-last element
const_iterator end() const;
/// appends a parameter passed by value
void append_parameter_by_value( ls_id_index idx, type_pointer ltype);
/// appends a parameter passed by reference
void append_parameter_by_reference( ls_id_index idx, type_pointer ltype);
/// appends another list of parameters
/** kills the list \p ll2 **/
void append_and_kill( parameter_list * ll2);
/// number of parameter entries
parameter_vector::size_type size() const;
private:
void push_back( const parameter_entry & v);
void append( const parameter_list & l2);
std::string operator()( std::ostream & oo, DumpUniquizer & uniq) const;
parameter_vector v_;
friend std::ostream & operator<<( std::ostream & o, const parameter_list & e);
friend class symbol_entry;
};
/// \internal parameter list dumper
std::ostream & operator<<( std::ostream & o, const parameter_list & e);
/*************************************************************************/
/// symbol kind
enum symbol_kind {
SKIND_UNDEF,
SKIND_PROCEDURE,
SKIND_FUNCTION,
SKIND_GLOBAL_VARIABLE,
SKIND_LOCAL_VARIABLE,
SKIND_PARAMETER_BY_REFERENCE,
SKIND_TYPE,
SKIND_CONST
};
class typed_symbol;
class variable_symbol;
class subprogram_symbol;
class procedure_symbol;
class function_symbol;
class global_variable_symbol;
class local_variable_symbol;
class parameter_by_reference_symbol;
class type_symbol;
class const_symbol;
/// pointer to typed_symbol entry
typedef mlaskal::dumb_pointer< typed_symbol> typed_symbol_pointer;
/// pointer to variable_symbol entry
typedef mlaskal::dumb_pointer< variable_symbol> variable_symbol_pointer;
/// pointer to subprogram_symbol entry
typedef mlaskal::dumb_pointer< subprogram_symbol> subprogram_symbol_pointer;
/// pointer to procedure_symbol entry
typedef mlaskal::dumb_pointer< procedure_symbol> procedure_symbol_pointer;
/// pointer to function_symbol entry
typedef mlaskal::dumb_pointer< function_symbol> function_symbol_pointer;
/// pointer to global_variable_symbol entry
typedef mlaskal::dumb_pointer< global_variable_symbol> global_variable_symbol_pointer;
/// pointer to local_variable_symbol entry
typedef mlaskal::dumb_pointer< local_variable_symbol> local_variable_symbol_pointer;
/// pointer to parameter_by_reference_symbol entry
typedef mlaskal::dumb_pointer< parameter_by_reference_symbol> parameter_by_reference_symbol_pointer;
/// pointer to type_symbol entry
typedef mlaskal::dumb_pointer< type_symbol> type_symbol_reference;
/// pointer to const_symbol entry
typedef mlaskal::dumb_pointer< const_symbol> const_symbol_reference;
/// abstract symbol representation
class abstract_symbol
{
public:
virtual ~abstract_symbol() {}
/// returns the kind of the symbol
symbol_kind kind() const { return this ? kind_() : SKIND_UNDEF; }
/// accesses typed_symbol entry if applicable
typed_symbol_pointer access_typed() { return this ? typedSymbol_() : typed_symbol_pointer(); }
/// accesses variable_symbol entry if applicable
variable_symbol_pointer access_variable() { return this ? variableSymbol_() : variable_symbol_pointer(); }
/// accesses subprogram_symbol entry if applicable
subprogram_symbol_pointer access_subprogram() { return this ? subprogramSymbol_() : subprogram_symbol_pointer(); }
/// accesses procedure_symbol entry if applicable
procedure_symbol_pointer access_procedure() { return this ? procSymbol_() : procedure_symbol_pointer(); }
/// accesses function_symbol entry if applicable
function_symbol_pointer access_function() { return this ? fncSymbol_() : function_symbol_pointer(); }
/// accesses global_variable_symbol entry if applicable
global_variable_symbol_pointer access_global_variable() { return this ? gVarSymbol_() : global_variable_symbol_pointer(); }
/// accesses local_variable_symbol entry if applicable
local_variable_symbol_pointer access_local_variable() { return this ? lVarSymbol_() : local_variable_symbol_pointer(); }
/// accesses parameter_by_reference_symbol entry if applicable
parameter_by_reference_symbol_pointer access_parameter_by_reference() { return this ? varParSymbol_() : parameter_by_reference_symbol_pointer(); }
/// accesses type_symbol entry if applicable
type_symbol_reference access_type() { return this ? typeSymbol_() : type_symbol_reference(); }
/// accesses const_symbol entry if applicable
const_symbol_reference access_const() { return this ? constSymbol_() : const_symbol_reference(); }
private:
virtual symbol_kind kind_() const = 0;
virtual typed_symbol_pointer typedSymbol_() = 0;
virtual variable_symbol_pointer variableSymbol_() = 0;
virtual subprogram_symbol_pointer subprogramSymbol_() = 0;
virtual procedure_symbol_pointer procSymbol_() = 0;
virtual function_symbol_pointer fncSymbol_() = 0;
virtual global_variable_symbol_pointer gVarSymbol_() = 0;
virtual local_variable_symbol_pointer lVarSymbol_() = 0;
virtual parameter_by_reference_symbol_pointer varParSymbol_() = 0;
virtual type_symbol_reference typeSymbol_() = 0;
virtual const_symbol_reference constSymbol_() = 0;
};
/// pointer to abstract symbol entry
typedef mlaskal::dumb_pointer< abstract_symbol> symbol_pointer;
/// common base of procedure and function entries
class subprogram_symbol
: public virtual abstract_symbol
{
public:
virtual ~subprogram_symbol() {}
/// list of parameters
const parameter_list * parameters() const { return this ? parList_() : 0; }
/// intermediate code representation
ic_function_pointer code() const { return this ? label_() : ic_function_pointer(); }
private:
virtual const parameter_list * parList_() const = 0;
virtual ic_function_pointer label_() const = 0;
};
/// common base of all symbol entries that have a type
class typed_symbol
: public virtual abstract_symbol
{
public:
virtual ~typed_symbol() {}
/// the type of the symbol
type_pointer type() const { return this ? type_() : type_pointer(); }
private:
virtual type_pointer type_() const = 0;
};
/// representation of a procedure
class procedure_symbol
: public virtual subprogram_symbol
{
public:
virtual ~procedure_symbol() {}
};
/// representation of a function
class function_symbol
: public virtual subprogram_symbol,
public virtual typed_symbol
{
public:
virtual ~function_symbol() {}
};
/// common base of all variable representations
class variable_symbol
: public virtual typed_symbol
{
public:
virtual ~variable_symbol() {}
/// address of the variable in intermediate code stack units
virtual stack_address address() const { return this ? varOffset_() : 0; }
private:
virtual stack_address varOffset_() const = 0;
};
/// global variable representation
class global_variable_symbol
: public virtual variable_symbol
{
public:
virtual ~global_variable_symbol() {}
};
/// local variable representation
/** also used for parameters passed by value **/
class local_variable_symbol
: public virtual variable_symbol
{
public:
virtual ~local_variable_symbol() {}
};
/// representation of a parameter passed by reference ('var')
class parameter_by_reference_symbol
: public virtual variable_symbol
{
public:
virtual ~parameter_by_reference_symbol() {}
};
/// representation of a named type
class type_symbol
: public virtual typed_symbol
{
public:
virtual ~type_symbol() {}
};
class bool_const_symbol;
class int_const_symbol;
class real_const_symbol;
class str_const_symbol;
/// pointer to a representation of a named boolean constant
typedef mlaskal::dumb_pointer< bool_const_symbol> bool_const_symbol_pointer;
/// pointer to a representation of a named integer constant
typedef mlaskal::dumb_pointer< int_const_symbol> int_const_symbol_pointer;
/// pointer to a representation of a named real constant
typedef mlaskal::dumb_pointer< real_const_symbol> real_const_symbol_pointer;
/// pointer to a representation of a named string constant
typedef mlaskal::dumb_pointer< str_const_symbol> str_const_symbol_pointer;
/// common base of all named constant representations
class const_symbol
: public virtual typed_symbol
{
public:
virtual ~const_symbol() {}
/// accesses bool_const_symbol entry if applicable
bool_const_symbol_pointer access_bool_const() { return this ? boolConstSymbol_() : bool_const_symbol_pointer(); }
/// accesses int_const_symbol entry if applicable
int_const_symbol_pointer access_int_const() { return this ? integerConstSymbol_() : int_const_symbol_pointer(); }
/// accesses real_const_symbol entry if applicable
real_const_symbol_pointer access_real_const() { return this ? realConstSymbol_() : real_const_symbol_pointer(); }
/// accesses str_const_symbol entry if applicable
str_const_symbol_pointer access_str_const() { return this ? stringConstSymbol_() : str_const_symbol_pointer(); }
private:
virtual bool_const_symbol_pointer boolConstSymbol_() = 0;
virtual int_const_symbol_pointer integerConstSymbol_() = 0;
virtual real_const_symbol_pointer realConstSymbol_() = 0;
virtual str_const_symbol_pointer stringConstSymbol_() = 0;
};
/// representation of a named boolean constant
/** created automatically during initialization for 'false' and 'true' **/
class bool_const_symbol
: public virtual const_symbol
{
public:
virtual ~bool_const_symbol() {}
bool bool_value() const { return this ? boolValue_() : false; }
private:
virtual bool boolValue_() const = 0;
};
/// representation of a named integer constant
class int_const_symbol
: public virtual const_symbol
{
public:
virtual ~int_const_symbol() {}
ls_int_index int_value() const { return this ? integerValue_() : ls_int_index(); }
private:
virtual ls_int_index integerValue_() const = 0;
};
/// representation of a named real constant
class real_const_symbol
: public virtual const_symbol
{
public:
virtual ~real_const_symbol() {}
ls_real_index real_value() const { return this ? realValue_() : ls_real_index(); }
private:
virtual ls_real_index realValue_() const = 0;
};
/// representation of a named string constant
class str_const_symbol
: public virtual const_symbol
{
public:
virtual ~str_const_symbol() {}
ls_str_index str_value() const { return this ? stringValue_() : ls_str_index(); }
private:
virtual ls_str_index stringValue_() const = 0;
};
/*************************************************************************/
class local_symbol_tables;
class symbol_entry;
class label_entry;
/// \internal symbol map
typedef std::map< ls_id_index, symbol_entry, ls_index_comparator< std::string> > symbol_map;
/// \internal label map
typedef std::map< ls_int_index, label_entry, ls_index_comparator< int> > label_map;
/// \internal implementation of a symbol
class symbol_entry
: public virtual procedure_symbol,
public virtual function_symbol,
public virtual global_variable_symbol,
public virtual local_variable_symbol,
public virtual parameter_by_reference_symbol,
public virtual type_symbol,
public virtual bool_const_symbol,
public virtual int_const_symbol,
public virtual real_const_symbol,
public virtual str_const_symbol
{
private:
symbol_entry( symbol_kind s, stack_address i, type_pointer p, const ic_function_pointer & m, local_symbol_tables * lt)
: symtype( s), value( false), relnum_( i), ltype( p), parlist( 0), magic( m), epilogue_( icblock_create()), local_tables_( lt)
{
}
symbol_entry( symbol_kind s, stack_address i, type_pointer p, ic_label bl, ic_label el)
: symtype( s), value( false), relnum_( i), ltype( p), parlist( 0), magic(), epilogue_( 0), local_tables_( 0),
icip_begin_label( bl), icip_end_label( el)
{
}
symbol_entry( symbol_kind s, bool i, type_pointer p)
: symtype( s), value( i), relnum_( -1), ltype( p), parlist( 0), magic(), epilogue_( 0), local_tables_( 0)
{
}
symbol_entry( symbol_kind s, ls_int_index i, type_pointer p)
: symtype( s), value( false), intidx( i), relnum_( -1), ltype( p), parlist( 0), magic(), epilogue_( 0), local_tables_( 0)
{
}
symbol_entry( symbol_kind s, ls_real_index i, type_pointer p)
: symtype( s), value( false), realidx( i), relnum_( -1), ltype( p), parlist( 0), magic(), epilogue_( 0), local_tables_( 0)
{
}
symbol_entry( symbol_kind s, ls_str_index i, type_pointer p)
: symtype( s), value( false), stridx( i), relnum_( -1), ltype( p), parlist( 0), magic(), epilogue_( 0), local_tables_( 0)
{
}
symbol_kind symtype;
bool value;
ls_int_index intidx;
ls_real_index realidx;
ls_str_index stridx;
stack_address relnum_;
type_pointer ltype;
parameter_list * parlist;
ic_function_pointer magic;
mlaskal::abstract_function_vars local_vars_;
icblock_pointer epilogue_;
local_symbol_tables * local_tables_;
ic_label icip_begin_label;
ic_label icip_end_label;
virtual symbol_kind kind_() const;
virtual typed_symbol_pointer typedSymbol_();
virtual variable_symbol_pointer variableSymbol_();
virtual subprogram_symbol_pointer subprogramSymbol_();
virtual procedure_symbol_pointer procSymbol_();
virtual function_symbol_pointer fncSymbol_();
virtual global_variable_symbol_pointer gVarSymbol_();
virtual local_variable_symbol_pointer lVarSymbol_();
virtual parameter_by_reference_symbol_pointer varParSymbol_();
virtual type_symbol_reference typeSymbol_();
virtual const_symbol_reference constSymbol_();
virtual const parameter_list * parList_() const;
virtual type_pointer type_() const;
virtual stack_address varOffset_() const;
virtual bool_const_symbol_pointer boolConstSymbol_();
virtual int_const_symbol_pointer integerConstSymbol_();
virtual real_const_symbol_pointer realConstSymbol_();
virtual str_const_symbol_pointer stringConstSymbol_();
virtual bool boolValue_() const;
virtual ls_int_index integerValue_() const;
virtual ls_real_index realValue_() const;
virtual ls_str_index stringValue_() const;
virtual ic_function_pointer label_() const;
std::string operator()( const std::string & indent, const std::string & name, std::ostream & o, DumpUniquizer & uniq) const;
void kill();
friend void kill_symbol( symbol_map::value_type & e);
friend class symbol_tables;
friend class local_symbol_tables;
friend std::ostream & operator<<( std::ostream & o, const symbol_entry & e);
};
/*************************************************************************/
/// label entry
class label_symbol {
public:
virtual ~label_symbol() {}
/// assigned intermediate code label
virtual ic_label label() const = 0;
/// encountered a goto statement
virtual void goto_found( int line) = 0;
/// encountered a label:
virtual bool label_found( int line) = 0;
};
/// pointer to a label entry
typedef mlaskal::dumb_pointer< label_symbol> label_symbol_pointer;
/*************************************************************************/
struct check_label;
/// \internal implementation of label entry
class label_entry
: public virtual label_symbol
{
private:
label_entry( int ln, const ls_int_index & i, const ic_label & l)
: id( i), magic( l), have_goto( false), have_label( false), decl_line( ln), goto_line( 0), label_line( 0) {}
ls_int_index id;
ic_label magic;
bool have_goto, have_label;
int decl_line, goto_line, label_line;
virtual ic_label label() const;
virtual void goto_found( int line);
virtual bool label_found( int line);
void check();
friend class symbol_tables;
friend struct check_label;
};
/*************************************************************************/
class local_symbol_tables {
private:
local_symbol_tables();
~local_symbol_tables();
std::string dump_locals( std::ostream & oo, DumpUniquizer & uniq) const;
std::ostream & dump_llabel( std::ostream & o, const label_map::const_iterator & lit, std::ostream & oo, DumpUniquizer & uniq) const;
std::ostream & dump_local( std::ostream & o, const symbol_map::const_iterator & sit, std::ostream & oo, DumpUniquizer & uniq) const;
label_map llabels;
symbol_map locals;
stack_address lvarsize;
stack_address retval_;
friend class symbol_tables;
friend class symbol_entry;
};
/*************************************************************************/
struct MlaskalCtx;
/// all symbol tables together
class symbol_tables {
public:
//ls_id_index translate_id( ls_id_index idx);
/// integer literal storage
ls_int_type & ls_int() { return aic_->get_ls_int(); }
/// real literal storage
ls_real_type & ls_real() { return aic_->get_ls_real(); }
/// string literal storage
ls_str_type & ls_str() { return aic_->get_ls_string(); }
/// identifier storage
ls_id_type & ls_id() { return aic_->get_ls_id(); }
/// creates an array type representation
/** creates an array_type entry for 'array [ \p index_type ] of \p element_type' **/
type_pointer create_array_type( type_pointer index_type, type_pointer element_type);
/// creates a record type representation
/** creates a record_type entry for 'record field_list end' **/
type_pointer create_record_type( field_list * fldlist, int line = 0);
/// creates a range type representation
/** creates a range_type entry for '\p i1 .. \p i2' **/
type_pointer create_range_type( ls_int_index i1, ls_int_index i2);
/// finds a label
/** finds a label entry identified by integer literal \p idx **/
label_symbol_pointer find_label( ls_int_index idx);
/// creates a variable representation
/** creates a global_variable_symbol or local_variable_symbol entry for 'var \p idx : \p ltype' (based on symbol_tables::nested())
\p line is a line number
**/
variable_symbol_pointer add_var( int line, ls_id_index idx, type_pointer ltype);
/// creates a representation of boolean constant
/** creates a bool_const_symbol entry for 'const \p idx = \p val'
\p line is a line number
**/
bool_const_symbol_pointer add_const_bool( int line, ls_id_index idx, bool val);
/// creates a representation of integer constant
/** creates a int_const_symbol entry for 'const \p idx = \p val'
\p line is a line number
**/
int_const_symbol_pointer add_const_int( int line, ls_id_index idx, ls_int_index symidx);
/// creates a representation of real constant
/** creates a real_const_symbol entry for 'const \p idx = \p symidx'
\p line is a line number
**/
real_const_symbol_pointer add_const_real( int line, ls_id_index idx, ls_real_index symidx);
/// creates a representation of string constant
/** creates a str_const_symbol entry for 'const \p idx = \p symidx'
\p line is a line number
**/
str_const_symbol_pointer add_const_str( int line, ls_id_index idx, ls_str_index symidx);
/// creates a representation of named type
/** creates a type_symbol entry for 'type \p idx = \p symidx'
\p line is a line number
**/
type_symbol_reference add_type( int line, ls_id_index idx, type_pointer ltype);
/// creates a representation of label
/** creates a label_symbol entry for 'label \p idx'
label is identified by an integer literal \p idx
\p lbl should be an unique intermediate code label (created by ::new_label())
\p line is a line number
**/
label_symbol_pointer add_label_entry( int line, ls_int_index idx, ic_label lbl);
/// creates a representation of function
/** creates a function_symbol entry for 'function \p idx ( \p parlist ) : \p ltype'
\p line is a line number
**/
function_symbol_pointer add_fnc( int line, ls_id_index idx, type_pointer ltype, parameter_list * parlist);
/// creates a representation of procedure
/** creates a procedure_symbol entry for 'procedure \p idx ( \p parlist )'
\p line is a line number
**/
procedure_symbol_pointer add_proc( int line, ls_id_index idx, parameter_list * parlist);
/// assign code to a function
/** defines the code of a function/procedure named \p idx using icblock \p icb
icblock \p icb is inserted between prologue and epilogue code (including RET)
automatically generated from local variable declarations
**/
bool set_subprogram_code( ls_id_index idx, icblock_pointer icb);
/// assign code to the main block
/** defines the code of the main block of a program named \p idx using icblock \p icb
icblock \p icb is inserted between prologue and epilogue code (including HALT)
automatically generated from global variable declarations
**/
bool set_main_code( ls_id_index idx, icblock_pointer icb);
/// opens a block of a procedure or function
/** \p idx must be an identifier of a procedure or a function that already has its entry
\li opens the block (nested() becomes true)
\li creates local_variable_symbol or parameter_by_reference_symbol entries for parameters (as defined by the procedure or function entry)
\p line is a line number
**/
bool enter( int line, ls_id_index idx);
/// closes a block of a procedure or function
/** \li discards all symbol and label entries inside the block
\li closes the block (nested() becomes false)
\p line is a line number
**/
void leave( int line);
/// current function
/** returns the identifier of the current function (as defined by enter())
**/
ls_id_index my_function_name() const;
/// integer literal 1
/** returns the integer literal '1'
**/
mlc::ls_int_type::const_iterator one();
/// place for the returned value
/** returns the stack offset of the returned value
**/
stack_address my_return_address();
/// undefined type
/** returns an abstract_type representation of undefined type
**/
type_pointer logical_undef();
/// boolean type
/** returns a BoolType representation of 'boolean' type
**/
type_pointer logical_bool();
/// integer type
/** returns an int_type representation of 'integer' type
**/
type_pointer logical_integer();
/// real type
/** returns a real_type representation of 'real' type
**/
type_pointer logical_real();
/// string type
/** returns a str_type representation of 'string' type
**/
type_pointer logical_string();
/// checks enter/leave status
/** returns true if inside a procedure or function block
**/
bool nested() const;
/// finds a symbol
/** returns an abstract_symbol representation assigned to the identifier \p symidx
\li if nested(), searches among local declarations
\li if not found, searches among global declarations
\li if not found anywhere, returns undefined (SKIND_UNDEFINED) symbol representation
**/
symbol_pointer find_symbol( ls_id_index symidx);
private:
label_map & llabels() { if ( nested_ ) return my_function_entry()->local_tables_->llabels; return glabels; }
const label_map & llabels() const { if ( nested_ ) return my_function_entry()->local_tables_->llabels; return glabels; }
symbol_map & locals() { if ( nested_ ) return my_function_entry()->local_tables_->locals; return globals; }
const symbol_map & locals() const { if ( nested_ ) return my_function_entry()->local_tables_->locals; return globals; }
stack_address & lvarsize() { if ( nested_ ) return my_function_entry()->local_tables_->lvarsize; return gvarsize; }
const stack_address & lvarsize() const { if ( nested_ ) return my_function_entry()->local_tables_->lvarsize; return gvarsize; }
stack_address & retval_() { return my_function_entry()->local_tables_->retval_; }
const stack_address & retval_() const { return my_function_entry()->local_tables_->retval_; }
const symbol_entry * my_function_entry() const;
symbol_entry * my_function_entry();
type_vector types;
label_map glabels;
symbol_map globals;
bool nested_;
stack_address gvarsize;
ls_id_index myfncname_;
mlc::ls_int_type::const_iterator one_;
type_pointer bool_;
type_pointer integer_;
type_pointer real_;
type_pointer string_;
type_pointer undef_;
bool debug_;
mlaskal::abstract_ic * aic_;
mlaskal::abstract_function_vars global_vars_;
mlaskal::tr1::shared_ptr< mlaskal::labeled_icblock> global_block_;
icblock_pointer global_epilogue_;
type_pointer create_atomic_type( type_category ptype);
ic_function_pointer my_function_code();
symbol_tables( bool debug, mlaskal::abstract_ic * aic);
void dump_enter( ls_id_index idx) const;
void dump_leave() const;
void dump_builtins() const;
void dump_main() const;
void dump_type( const type_vector::const_iterator & tit) const;
void dump_glabel( const label_map::const_iterator & lit) const;
void dump_global( const symbol_map::const_iterator & sit) const;
void dump_llabel( const label_map::const_iterator & lit) const;
void dump_local( const symbol_map::const_iterator & sit) const;
std::ostream & dump_type( std::ostream & o, const type_vector::const_iterator & tit) const;
std::ostream & dump_glabel( std::ostream & o, const label_map::const_iterator & lit) const;
std::ostream & dump_glabel( std::ostream & o, const label_map::const_iterator & lit, std::ostream & oo, DumpUniquizer & uniq) const;
std::ostream & dump_global( std::ostream & o, const symbol_map::const_iterator & sit) const;
std::ostream & dump_global( std::ostream & o, const symbol_map::const_iterator & sit, std::ostream & oo, DumpUniquizer & uniq) const;
std::ostream & dump_llabel( std::ostream & o, const label_map::const_iterator & lit) const;
std::ostream & dump_local( std::ostream & o, const symbol_map::const_iterator & sit) const;
std::ostream & dump( std::ostream & o) const;
void init_builtins();
~symbol_tables();
friend int symtab_preprocess( MlaskalCtx *ctx, bool debug);
friend int symtab_postprocess(struct MlaskalCtx *ctx, const std::string & dump_fname);
};
/*************************************************************************/
/// creates an empty parameter list
parameter_list * create_parameter_list();
/// creates an empty field list
field_list * create_field_list();
/// compares two types
/** returns true if types are identical wrt. Mlaskal rules **/
bool identical_type( type_pointer a, type_pointer b);
/*************************************************************/
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
1194
]
]
] |
3d411f5558e170a124a063eb7280e7e2aeefad5b
|
b22c254d7670522ec2caa61c998f8741b1da9388
|
/dependencies/Boost/include/boost/archive/basic_binary_oprimitive.hpp
|
994430aa3298a68afbf8c4afa6cca531346a74ee
|
[] |
no_license
|
ldaehler/lbanet
|
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
|
ecb54fc6fd691f1be3bae03681e355a225f92418
|
refs/heads/master
| 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,099 |
hpp
|
#ifndef BOOST_ARCHIVE_BASIC_BINARY_OPRIMITIVE_HPP
#define BOOST_ARCHIVE_BASIC_BINARY_OPRIMITIVE_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// basic_binary_oprimitive.hpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
// archives stored as native binary - this should be the fastest way
// to archive the state of a group of obects. It makes no attempt to
// convert to any canonical form.
// IN GENERAL, ARCHIVES CREATED WITH THIS CLASS WILL NOT BE READABLE
// ON PLATFORM APART FROM THE ONE THEY ARE CREATE ON
#include <iosfwd>
#include <cassert>
#include <locale>
#include <streambuf> // basic_streambuf
#include <string>
#include <cstddef> // size_t
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::size_t;
} // namespace std
#endif
#include <boost/cstdint.hpp>
//#include <boost/limits.hpp>
//#include <boost/io/ios_state.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/serialization/throw_exception.hpp>
#include <boost/archive/basic_streambuf_locale_saver.hpp>
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/detail/auto_link_archive.hpp>
#include <boost/serialization/is_bitwise_serializable.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/serialization/array.hpp>
#include <boost/archive/detail/abi_prefix.hpp> // must be the last header
namespace boost {
namespace archive {
/////////////////////////////////////////////////////////////////////////
// class basic_binary_oprimitive - binary output of prmitives
template<class Archive, class Elem, class Tr>
class basic_binary_oprimitive
{
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
friend class save_access;
protected:
#else
public:
#endif
std::basic_streambuf<Elem, Tr> & m_sb;
// return a pointer to the most derived class
Archive * This(){
return static_cast<Archive *>(this);
}
#ifndef BOOST_NO_STD_LOCALE
boost::scoped_ptr<std::locale> archive_locale;
basic_streambuf_locale_saver<Elem, Tr> locale_saver;
#endif
// default saving of primitives.
template<class T>
void save(const T & t)
{
save_binary(& t, sizeof(T));
}
/////////////////////////////////////////////////////////
// fundamental types that need special treatment
// trap usage of invalid uninitialized boolean which would
// otherwise crash on load.
void save(const bool t){
assert(0 == static_cast<int>(t) || 1 == static_cast<int>(t));
save_binary(& t, sizeof(t));
}
BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
save(const std::string &s);
#ifndef BOOST_NO_STD_WSTRING
BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
save(const std::wstring &ws);
#endif
BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
save(const char * t);
BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
save(const wchar_t * t);
BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
init();
BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY())
basic_binary_oprimitive(
std::basic_streambuf<Elem, Tr> & sb,
bool no_codecvt
);
BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY())
~basic_binary_oprimitive();
public:
// we provide an optimized save for all fundamental types
// typedef serialization::is_bitwise_serializable<mpl::_1>
// use_array_optimization;
// workaround without using mpl lambdas
struct use_array_optimization {
template <class T>
#if defined(BOOST_NO_DEPENDENT_NESTED_DERIVATIONS)
struct apply {
typedef BOOST_DEDUCED_TYPENAME boost::serialization::is_bitwise_serializable<T>::type type;
};
#else
struct apply : public boost::serialization::is_bitwise_serializable<T> {};
#endif
};
// the optimized save_array dispatches to save_binary
template <class ValueType>
void save_array(boost::serialization::array<ValueType> const& a, unsigned int)
{
save_binary(a.address(),a.count()*sizeof(ValueType));
}
void save_binary(const void *address, std::size_t count);
};
template<class Archive, class Elem, class Tr>
inline void
basic_binary_oprimitive<Archive, Elem, Tr>::save_binary(
const void *address,
std::size_t count
){
//assert(
// static_cast<std::size_t>((std::numeric_limits<std::streamsize>::max)()) >= count
//);
// note: if the following assertions fail
// a likely cause is that the output stream is set to "text"
// mode where by cr characters recieve special treatment.
// be sure that the output stream is opened with ios::binary
//if(os.fail())
// boost::serialization::throw_exception(
// archive_exception(archive_exception::stream_error)
// );
// figure number of elements to output - round up
count = ( count + sizeof(Elem) - 1)
/ sizeof(Elem);
std::streamsize scount = m_sb.sputn(
static_cast<const Elem *>(address),
static_cast<std::streamsize>(count)
);
if(count != static_cast<std::size_t>(scount))
boost::serialization::throw_exception(
archive_exception(archive_exception::stream_error)
);
//os.write(
// static_cast<const BOOST_DEDUCED_TYPENAME OStream::char_type *>(address),
// count
//);
//assert(os.good());
}
} //namespace boost
} //namespace archive
#include <boost/archive/detail/abi_suffix.hpp> // pop pragams
#endif // BOOST_ARCHIVE_BASIC_BINARY_OPRIMITIVE_HPP
|
[
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] |
[
[
[
1,
183
]
]
] |
a79ac05847f08c01758bab71cf790ef2ec343e15
|
27d5670a7739a866c3ad97a71c0fc9334f6875f2
|
/CPP/Targets/MapLib/Symbian/include/VisibilityAdapter.h
|
fbaf457bf0948a41635a47f16531e24b468d1454
|
[
"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 | 2,354 |
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 VISIBILITYADAPTER_H
#define VISIBILITYADAPTER_H
#include "config.h"
#include "VisibilityAdapterBase.h"
/**
* Class used to set the visibility of a generic type.
*/
template <class T>
class VisibilityAdapter : public VisibilityAdapterBase
{
public:
VisibilityAdapter(T* control) :
m_control(control)
{
}
virtual ~VisibilityAdapter()
{
}
T* getControl()
{
return m_control;
}
virtual void setVisible(bool visible)
{
if (iMainControlVisible) {
iVisible = visible;
m_control->MakeVisible(visible);
} else {
iVisible = visible;
m_control->MakeVisible(false);
}
}
private:
T* m_control;
};
#endif
// End of File
|
[
"[email protected]"
] |
[
[
[
1,
59
]
]
] |
7ca99d10c26856391b88b5197fcbf7b5b31cc55e
|
080d0991b0b9246584851c8378acbd5111c9220e
|
/11483 - Code Creator/codecoder.cpp
|
ed971d6faefcc932b1b2b2686f421689b1466816
|
[] |
no_license
|
jlstr/acm
|
93c9bc3192dbfbeb5e39c18193144503452dac2a
|
cd3f99e66ac5eb9e16a5dccaf563ca489e08abc3
|
refs/heads/master
| 2021-01-16T19:33:50.867234 | 2011-09-29T19:56:16 | 2011-09-29T19:56:16 | 8,509,059 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,270 |
cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int cases;
string header="#include<string.h>\n#include<stdio.h>\nint main()\n{\n";
string cola="printf(\"\\n\");\nreturn 0;\n}\n";
int n=0;
while(cin >> cases && cases){
cout<<"Case "<<++n<<":"<<endl;
cout<<header;
string ans;
getline(cin,ans);
while(cases--){
getline(cin,ans);
if(ans==""){
cases++;
continue;
}
for(int i=0;i<ans.size();++i){
//cout<<"debug"<<endl;
if(ans[i]=='\\'){
ans.insert(i+1,"\\");
++i;
}else if(ans[i]=='"'){
//ans[i]='';
ans.insert(i,"\\");
++i;
}else if(ans[i]=='"'){
ans.insert(i,"\\");
++i;
}
}
cout<<"printf(\""<<ans<<"\\n\");"<<endl;
}
cout<<cola;
}
//getchar();
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
44
]
]
] |
d07284ef760c826997fc3d1584755b8d613636ca
|
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
|
/XMonitor/src/JsHighlighter.cpp
|
0e98297df992ad1eedc06cf21c171e1a463b657a
|
[] |
no_license
|
yewberry/yewtic
|
9624d05d65e71c78ddfb7bd586845e107b9a1126
|
2468669485b9f049d7498470c33a096e6accc540
|
refs/heads/master
| 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,484 |
cpp
|
#include <QtGui>
#include "JsHighlighter.h"
JsHighlighter::JsHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
keywordFormat.setForeground(Qt::darkRed);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
keywordPatterns << "\\bbreak\\b" << "\\bfalse\\b" << "\\bin\\b"
<< "\\bthis\\b" << "\\bvoid\\b" << "\\bcontinue\\b"
<< "\\bfor\\b" << "\\bnew\\b" << "\\btrue\\b"
<< "\\bwhile\\b" << "\\bdelete\\b" << "\\bfunction\\b"
<< "\\bnull\\b" << "\\btypeof\\b" << "\\bwith\\b"
<< "\\belse\\b" << "\\bif\\b" << "\\breturn\\b"
<< "\\bvar\\b" << "\\bcase\\b" << "\\bdebugger\\b"
<< "\\bexport\\b" << "\\bsuper\\b" << "\\bcatch\\b"
<< "\\bdefault\\b" << "\\bextends\\b" << "\\bswitch\\b"
<< "\\bclass\\b" << "\\bdo\\b"<< "\\bfinally\\b"
<< "\\bthrow\\b" << "\\bconst\\b"<< "\\benum\\b"
<< "\\bimport\\b" << "\\btry\\b";
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
/*
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
*/
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::darkGreen);
quotationFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat;
highlightingRules.append(rule);
functionFormat.setFontItalic(true);
functionFormat.setForeground(Qt::black);
functionFormat.setFontWeight(QFont::Bold);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
commentStartExpression = QRegExp("/\\*");
commentEndExpression = QRegExp("\\*/");
}
void JsHighlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = commentStartExpression.indexIn(text);
while (startIndex >= 0) {
int endIndex = commentEndExpression.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ commentEndExpression.matchedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = commentStartExpression.indexIn(text, startIndex + commentLength);
}
}
|
[
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86",
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
] |
[
[
[
1,
1
],
[
3,
3
],
[
5,
8
],
[
10,
11
],
[
24,
29
],
[
31,
35
],
[
37,
37
],
[
39,
42
],
[
45,
49
],
[
52,
59
],
[
61,
76
],
[
78,
78
],
[
80,
92
]
],
[
[
2,
2
],
[
4,
4
],
[
9,
9
],
[
12,
23
],
[
30,
30
],
[
36,
36
],
[
38,
38
],
[
43,
44
],
[
50,
51
],
[
60,
60
],
[
77,
77
],
[
79,
79
]
]
] |
44e1db2549fe5d2bc894b1751a1a8d0a2a10407a
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/xpressive/test/test_regex_constants.cpp
|
22357149a7eaa59834079a4078c1564c9cc077d8
|
[
"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 | 562 |
cpp
|
///////////////////////////////////////////////////////////////////////////////
// test_regex_constants.cpp
//
// Copyright 2004 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/xpressive/regex_constants.hpp>
///////////////////////////////////////////////////////////////////////////////
// test_main
// read the tests from the input file and execute them
int test_main( int, char*[] )
{
return 0;
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
16
]
]
] |
dddce109eccfe422399602c7a55f627c6707e374
|
bef7d0477a5cac485b4b3921a718394d5c2cf700
|
/dingus/dingus/lua/LuaHelper.cpp
|
9445f5eed24feeaff1a774cea716655f931a528e
|
[
"MIT"
] |
permissive
|
TomLeeLive/aras-p-dingus
|
ed91127790a604e0813cd4704acba742d3485400
|
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
|
refs/heads/master
| 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,540 |
cpp
|
// --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "LuaHelper.h"
using namespace dingus;
std::string CLuaHelper::getString( CLuaValue& val, const char* name )
{
std::string s = val.getElement( name ).getString();
val.getLua().discard();
return s;
}
double CLuaHelper::getNumber( CLuaValue& val, const char* name )
{
double d = val.getElement( name ).getNumber();
val.getLua().discard();
return d;
}
SVector3 CLuaHelper::getVector3( CLuaValue& val, const char* name )
{
CLuaWrapper& lua = val.getLua();
CLuaValue luaVec = val.getElement(name);
SVector3 vec;
if( luaVec.isTable() ) {
vec.x = (float)luaVec.getElement(1).getNumber();
vec.y = (float)luaVec.getElement(2).getNumber();
vec.z = (float)luaVec.getElement(3).getNumber();
lua.discard(); lua.discard(); lua.discard();
} else {
vec.set(0,0,0);
}
lua.discard();
return vec;
}
SQuaternion CLuaHelper::getQuaternion( CLuaValue& val, const char* name )
{
CLuaWrapper& lua = val.getLua();
CLuaValue luaQ = val.getElement(name);
SQuaternion q;
if( luaQ.isTable() ) {
q.x = (float)luaQ.getElement(1).getNumber();
q.y = (float)luaQ.getElement(2).getNumber();
q.z = (float)luaQ.getElement(3).getNumber();
q.w = (float)luaQ.getElement(4).getNumber();
lua.discard(); lua.discard(); lua.discard(); lua.discard();
} else {
q = SQuaternion(0,0,0,1);
}
lua.discard();
return q;
}
void CLuaHelper::getMatrix3x3( CLuaValue& val, const char* name, SMatrix4x4& m )
{
CLuaWrapper& lua = val.getLua();
CLuaValue luaM = val.getElement(name);
if( luaM.isTable() ) {
m._11 = (float)luaM.getElement(1).getNumber();
m._12 = (float)luaM.getElement(2).getNumber();
m._13 = (float)luaM.getElement(3).getNumber();
m._21 = (float)luaM.getElement(4).getNumber();
m._22 = (float)luaM.getElement(5).getNumber();
m._23 = (float)luaM.getElement(6).getNumber();
m._31 = (float)luaM.getElement(7).getNumber();
m._32 = (float)luaM.getElement(8).getNumber();
m._33 = (float)luaM.getElement(9).getNumber();
lua.discard(); lua.discard(); lua.discard();
lua.discard(); lua.discard(); lua.discard();
lua.discard(); lua.discard(); lua.discard();
} else {
m.getAxisX().set(0,0,0);
m.getAxisY().set(0,0,0);
m.getAxisZ().set(0,0,0);
}
lua.discard();
}
|
[
"[email protected]"
] |
[
[
[
1,
82
]
]
] |
86fc117e573acc28d1788527758b26b65a7b25af
|
02cd7f7be30f7660f6928a1b8262dc935673b2d7
|
/ invols --username [email protected]/StereoPanel.cpp
|
94912e4b33efa8a34adbc7381940a1cd5cd16db3
|
[] |
no_license
|
hksonngan/invols
|
f0886a304ffb81594016b3b82affc58bd61c4c0b
|
336b8c2d11d97892881c02afc2fa114dbf56b973
|
refs/heads/master
| 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 1,805 |
cpp
|
#include "StereoPanel.h"
#include "MyApp.h"
#include "CT.h"
#include "AllDef.h"
BEGIN_EVENT_TABLE(StereoPanel, wxPanel)
EVT_SLIDER(1, StereoPanel::OnSliderZ)
EVT_CHOICE(3, StereoPanel::OnListStereo)
END_EVENT_TABLE()
StereoPanel::StereoPanel(wxWindow *frame) : wxPanel(frame)
{
wxPoint ster(10,10);
m_box = new wxChoice(this,3,ster,wxSize(140,30));
m_box->Append(MY_TXT("Mono","Моно-изображение"));
m_box->Append(MY_TXT("True anaglyph","Правильный анаглиф"));
m_box->Append(MY_TXT("Gray anaglyph","Серый анаглиф"));
m_box->Append(MY_TXT("Color anaglyph","Цветной анаглиф"));
m_box->Append(MY_TXT("Half-color anaglyph","Полуцветной анаглиф"));
m_box->Append(MY_TXT("Optimized anaglyph","Оптимизированный анаглиф"));
m_box->Append(MY_TXT("Two screens","Для проектора"));
m_box->Append(MY_TXT("Interlaced","Черезстрочный рендеринг"));
m_box->Append("3D Vision");
m_box->Select(0);
new wxStaticText(this,wxID_ANY,MY_TXT("Parallax","Расстояние между глаз"),ster+wxPoint(0,40));
m_slider_eye = new wxSlider(this,1,100,-1000,1000,ster+wxPoint(0,60),wxSize(140,30));
}
void StereoPanel::OnSliderZ(wxCommandEvent& WXUNUSED(event))
{
CT::stereo_step = m_slider_eye->GetValue()*0.0003f;
CT::need_rerender=1;
}
void StereoPanel::OnListStereo(wxCommandEvent& WXUNUSED(event))
{
int sm=1,sel = m_box->GetSelection();
CT::anag = sel;
if(!sel) sm=0;
if(sel>=6) sm=sel-4;
CT::SetStereoMode(sm);
}
void StereoPanel::Update_(bool self)
{
if(self)
{
m_slider_eye->SetValue(CT::stereo_step/0.0003f);
}else
{
CT::stereo_step = m_slider_eye->GetValue()*0.0003f;
}
}
|
[
"[email protected]"
] |
[
[
[
1,
62
]
]
] |
aa0e33da4cd4403502634e6ac92068ba400596a0
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/zombie/tutorials/src/entity_test/nentityobject1.cc
|
dd29830cb9b7eb8644cc3f920352e3fa5ba0f107
|
[] |
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,006 |
cc
|
#include "entity_test/entity01.h"
nNebulaEntityObject(nEntityObject1,"nentityobject","nentityclass1");
/*
static void
n_print(void* slf, nCmd* cmd)
{
nEntityObject1* self = (nEntityObject1*) slf;
self->nComponentObjectA::print();
self->nComponentObjectB::print();
self->nComponentObjectC::print();
}
static void
n_printa(void* slf, nCmd* cmd)
{
nComponentObjectA* self = (nEntityObject1*) slf;
self->printa();
}
static void
n_printb(void* slf, nCmd* cmd)
{
nComponentObjectB* self = (nEntityObject1*) slf;
self->printb();
}
static void
n_printc(void* slf, nCmd* cmd)
{
nComponentObjectC* self = (nEntityObject1*) slf;
self->printc();
}
void n_initcmds_nEntityObject1(nClass * cl)
{
cl->BeginCmds();
cl->AddCmd("v_print_v", 'PRIN', n_print);
cl->AddCmd("v_printa_v", 'PRIA', n_printa);
cl->AddCmd("v_printb_v", 'PRIB', n_printb);
cl->AddCmd("v_printc_v", 'PRIC', n_printc);
cl->EndCmds();
}
*/
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
45
]
]
] |
bcb933bebad35d1a422f6319001909a3465bcea6
|
e2e49023f5a82922cb9b134e93ae926ed69675a1
|
/tools/aosdesigner/core/EditionSessionInfos.hpp
|
9b13da7830d79a382c84d26fce1ef93344ab1fc1
|
[] |
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 | 458 |
hpp
|
#ifndef HGUARD_AOSD_CORE_EDITIONSESSIONINFOS_HPP__
#define HGUARD_AOSD_CORE_EDITIONSESSIONINFOS_HPP__
#pragma once
#include <string>
#include "core/SequenceId.hpp"
namespace aosd
{
namespace core
{
struct EditionSessionInfos
{
std::string name;
SequenceId sequence_id;
};
inline bool is_valid( const EditionSessionInfos& infos )
{
return !( infos.sequence_id.empty()
|| infos.name.empty()
);
}
}
}
#endif
|
[
"klaim@localhost"
] |
[
[
[
1,
29
]
]
] |
eba8710c7b66405f5a78545f8b230f4d5e85cbee
|
b0fe69a13b1f10295788e8ddd243354c9cb0bfbe
|
/amv_core/main.cpp
|
7993ba91695d53be98a34a2ddf0ae1797c77ff71
|
[] |
no_license
|
Surrog/avmfrandflo
|
d2346ce281b336eaeb4b79ec8303ed4f6c45774d
|
bfbaa57f7e52ff36352eaee7ca99d56ff64d16b0
|
refs/heads/master
| 2021-01-22T13:26:32.415282 | 2010-06-13T08:38:02 | 2010-06-13T08:38:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 530 |
cpp
|
#include <iostream>
#include <string>
#include "script.h"
#ifdef WIN32
#include "WSharedLib.h"
#else
#include "LSharedLib.h"
#endif
int main(int ac, char** av)
{
if (ac < 2)
{
std::cout << "Usage ./amv [Script ...]" << std::endl;
return 0;
}
#ifdef WIN32
WSharedLib shared;
#else
LSharedLib shared;
#endif
ObjFactory factory(shared);
for (int i = 1; i < ac; ++i)
{
Script file(factory, av[i]);
file.run();
}
return 0;
}
|
[
"Florian Chanioux@localhost"
] |
[
[
[
1,
33
]
]
] |
c4b1244b92e4377534f421b930d92b796e9a5732
|
b947582d4a5a285af530b5091bb242d8d0edf855
|
/pemilik/basis.cpp
|
b0c168bf21345f643a6da62054d4b7946e2f2285
|
[] |
no_license
|
dieend/simproyek1
|
c58a1d1335b350f1fab837f8283e62f964570abc
|
fc56985d471626c9f063b120aecfc7a7434506a6
|
refs/heads/master
| 2021-01-19T01:48:53.547580 | 2010-10-24T08:12:40 | 2010-10-24T08:12:40 | 32,120,427 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,030 |
cpp
|
// basis.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "basis.h"
const int MaxJenisBaju = 10000;
// This is an example of an exported variable
// This is an example of an exported function.
int fnbasis(void)
{
return 42;
}
// This is the constructor of a class that has been exported.
// see basis.h for the class definition
VAR::VAR()
{
return;
}
KoleksiBaju VAR::Lemari(0);
msi VAR::Mapping;
FILE * VAR::text;
int VAR::n;
TypeBaju ElmtBajuKode(kode a)
// mengembalikan Baju dengan Kode a dari Koleksi Baju dengan index diambil dari VAR::Mapping
// return (VAR::Lemari
{
return (VAR::Lemari[VAR::Mapping[a]]);
}
bool AddMapping(TypeBaju Baju,int nJenisBaju)
// mengeset VAR::Mapping index. m[Baju.Kode] = nJenisBaju
{
if (VAR::Mapping.find(Baju.Kode) == VAR::Mapping.end()){
VAR::Mapping[Baju.Kode] = nJenisBaju;
return true;
}
else return false;
}
bool TambahBaju(TypeBaju BajuBaru)
// VAR::Lemari.push_back(BajuBaru); AddMapping(BajuBaru, VAR::Lemari.size());
{
if (VAR::Lemari.size() > MaxJenisBaju) return false;
if (AddMapping(BajuBaru, VAR::Lemari.size())) {
VAR::Lemari.push_back(BajuBaru);
return true;
}
else return false;
}
void SimpanData() {
VAR::text = fopen ("Data.dat","w");
fprintf(VAR::text, "%d\n", VAR::Lemari.size());
for (int i=0; i<(int)VAR::Lemari.size(); i++) {
fprintf(VAR::text,"%d\n", VAR::Lemari[i].StokGudang);
fprintf(VAR::text,"%d\n", VAR::Lemari[i].StokToko);
fprintf(VAR::text,"%d\n", VAR::Lemari[i].StokIdealToko);
fprintf(VAR::text,"%d\n", VAR::Lemari[i].StokMinimumToko);
fprintf(VAR::text,"%c\n", VAR::Lemari[i].Ukuran);
fprintf(VAR::text,"%lf\n", VAR::Lemari[i].Harga);
fprintf(VAR::text,"%lf\n", VAR::Lemari[i].Diskon);
fprintf(VAR::text,"%s\n", VAR::Lemari[i].Kode.c_str());
fprintf(VAR::text,"%s\n", VAR::Lemari[i].Image.c_str());
}
fclose(VAR::text);
}
void LoadData() {
VAR::text = fopen("Data.dat","r");
int n;
TypeBaju BajuBaru;
char Tmp[1000];
fscanf_s(VAR::text, "%d", &n);
for (int i=0; i<n; i++) {
fscanf_s(VAR::text,"%d\n", &BajuBaru.StokGudang);
fscanf_s(VAR::text,"%d\n", &BajuBaru.StokToko);
fscanf_s(VAR::text,"%d\n", &BajuBaru.StokIdealToko);
fscanf_s(VAR::text,"%d\n", &BajuBaru.StokMinimumToko);
fscanf_s(VAR::text,"%c\n", &BajuBaru.Ukuran);
fscanf_s(VAR::text,"%lf\n", &BajuBaru.Harga);
fscanf_s(VAR::text,"%lf\n", &BajuBaru.Diskon);
fscanf_s(VAR::text,"%s\n", &Tmp);
BajuBaru.Kode = Tmp;
fscanf_s(VAR::text,"%s\n", &Tmp);
BajuBaru.Image = Tmp;
TambahBaju(BajuBaru);
}
fclose(VAR::text);
}
void PindahGudangkeToko(TypeBaju& Baju, int n)
// memindahkan baju sebanyak n dari gudang ke toko
{
Baju.StokToko += n;
Baju.StokGudang -= n;
}
void PindahTokokeGudang(TypeBaju * Baju, int n)
// memindahkan baju sebanyak n dari toko ke gudang
{
(*Baju).StokToko -= n;
(*Baju).StokGudang += n;
}
bool CekAdaDiToko(TypeBaju Baju)
{
if (Baju.StokToko == 0) return false;
return true;
}
bool CekAdaDiGudang(TypeBaju Baju)
{
if (Baju.StokGudang == 0) return false;
return true;
}
bool NextBaju(TypeBaju * Baju, int TGA) // TGA toko gudang all
{
int i = VAR::Mapping[(*Baju).Kode];
i+=1;
if (TGA == 2) {
while (i<(int)VAR::Lemari.size() && VAR::Lemari[i].StokGudang<=0)
i++;
}
else if (TGA == 1) {
while (i<(int)VAR::Lemari.size() && VAR::Lemari[i].StokToko<=0)
i++;
}
if (i>=(int)VAR::Lemari.size()) return false;
else {
(*Baju).Diskon = VAR::Lemari[i].Diskon;
(*Baju).Harga = VAR::Lemari[i].Harga;
(*Baju).Image = VAR::Lemari[i].Image;
(*Baju).Kode = VAR::Lemari[i].Kode;
(*Baju).StokGudang = VAR::Lemari[i].StokGudang;
(*Baju).StokIdealToko = VAR::Lemari[i].StokIdealToko;
(*Baju).StokMinimumToko = VAR::Lemari[i].StokMinimumToko;
(*Baju).StokToko = VAR::Lemari[i].StokToko;
(*Baju).Ukuran= VAR::Lemari[i].Ukuran;
return true;
}
}
|
[
"[email protected]@3f482c3b-0193-a96f-f1fb-1ccff6c3e739"
] |
[
[
[
1,
149
]
]
] |
5dfddad5d25f84a1a8b195f5e2717a77bd082ac5
|
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
|
/tags/pyplusplus_dev_0.9.5/docs/troubleshooting_guide/automatic_conversion/custom_rvalue.cpp
|
a467695681fb73dd35fd5c0dffe2169460f4467d
|
[
"BSL-1.0"
] |
permissive
|
gatoatigrado/pyplusplusclone
|
30af9065fb6ac3dcce527c79ed5151aade6a742f
|
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
|
refs/heads/master
| 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,601 |
cpp
|
#include "boost/python.hpp"
#include "boost/python/object.hpp" //len function
#include "boost/python/ssize_t.hpp" //ssize_t type definition
#include "boost/python/detail/none.hpp"
#include "tuples.hpp"
/**
* Custom r-value converter example.
*
* Use-case description. I and few other developers work on Python bindings for
* Ogre (http://ogre3d.org). The engine defines ColourValue class. This class
* describes colour using 4 components: red, green, blue and transparency. The
* class is used through the whole engine. One of the first features users ask
* is to add an ability to pass a tuple, instead of the "ColourValue" instance.
* This feature would allow them to write less code:
*
* x.do_smth( (1,2,3,4) )
*
* instead of
*
* x.do_smth( ogre.ColourValue( 1,2,3,4 ) )
*
* That's not all. They also wanted to be able to use ColourValue functionality.
*
* Solution.
*
* Fortunately, Boost.Python library provides enough functionality to implement
* users requirements - r-value converters.
*
* R-Value converters allows to register custom conversion from Python type to
* C++ type. The conversion will be handled by Boost.Python library automaticly
* "on-the-fly".
*
* The example introduces "colour_t" class and few testers.
*
**/
struct colour_t{
explicit colour_t( float red_=0.0, float green_=0.0, float blue_=0.0 )
: red( red_ ), green( green_ ), blue( blue_ )
{}
bool operator==( const colour_t& other ) const{
return red == other.red && green == other.green && blue == other.blue;
}
float red, green, blue;
};
struct desktop_t{
bool is_same_colour( const colour_t& colour ) const{
return colour == background;
}
colour_t background;
};
namespace bpl = boost::python;
struct pytuple2colour{
typedef boost::tuples::tuple< float, float, float> colour_tuple_type;
typedef bpl::from_py_sequence< colour_tuple_type > converter_type;
static void* convertible(PyObject* obj){
return converter_type::convertible( obj );
}
static void
construct( PyObject* obj, bpl::converter::rvalue_from_python_stage1_data* data){
typedef bpl::converter::rvalue_from_python_storage<colour_t> colour_storage_t;
colour_storage_t* the_storage = reinterpret_cast<colour_storage_t*>( data );
void* memory_chunk = the_storage->storage.bytes;
float red(0.0), green(0.0), blue(0.0);
boost::tuples::tie(red, green, blue) = converter_type::to_c_tuple( obj );
colour_t* colour = new (memory_chunk) colour_t(red, green, blue);
data->convertible = memory_chunk;
}
};
void register_pytuple2colour(){
bpl::converter::registry::push_back( &pytuple2colour::convertible
, &pytuple2colour::construct
, bpl::type_id<colour_t>() );
}
bool test_val_010( colour_t colour ){
return colour == colour_t( 0, 1, 0);
}
bool test_cref_000( const colour_t& colour ){
return colour == colour_t( 0, 0, 0);
}
bool test_ref_111( colour_t& colour ){
return colour == colour_t( 1, 1, 1);
}
bool test_ptr_101( colour_t* colour ){
return colour && *colour == colour_t( 1, 0, 1);
}
bool test_cptr_110( const colour_t* colour ){
return colour && *colour == colour_t( 1, 1, 0);
}
BOOST_PYTHON_MODULE( custom_rvalue ){
bpl::class_< colour_t >( "colour_t" )
.def( bpl::init< bpl::optional< float, float, float > >(
( bpl::arg("red_")=0.0, bpl::arg("green_")=0.0, bpl::arg("blue_")=0.0 ) ) )
.def_readwrite( "red", &colour_t::red )
.def_readwrite( "green", &colour_t::green )
.def_readwrite( "blue", &colour_t::blue );
register_pytuple2colour();
bpl::class_< desktop_t >( "desktop_t" )
//naive aproach that will not work - plain Python assignment
//.def_readwrite( "background", &desktop_t::background )
//You should use properties to force the conversion
.add_property( "background"
, bpl::make_getter( &desktop_t::background )
, bpl::make_setter( &desktop_t::background ) )
.def( "is_same_colour", &desktop_t::is_same_colour );
bpl::def("test_val_010", &::test_val_010);
bpl::def("test_cref_000", &::test_cref_000);
bpl::def("test_ref_111", &::test_ref_111);
bpl::def("test_ptr_101", &::test_ptr_101);
bpl::def("test_cptr_110", &::test_cptr_110);
}
|
[
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] |
[
[
[
1,
135
]
]
] |
0a37351002dc20c2e61e4290ee25b8ade3bfe894
|
335783c9e5837a1b626073d1288b492f9f6b057f
|
/source/fbxcmd/daolib/Model/PHY/PHYFile.h
|
c19e2accbe2eb660260c40d0950030a2316d81ef
|
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
code-google-com/fbx4eclipse
|
110766ee9760029d5017536847e9f3dc09e6ebd2
|
cc494db4261d7d636f8c4d0313db3953b781e295
|
refs/heads/master
| 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 539 |
h
|
/**********************************************************************
*<
FILE: PHYFile.h
DESCRIPTION: PHY File Format
HISTORY:
*> Copyright (c) 2009, All Rights Reserved.
**********************************************************************/
#pragma once
#include "PHYCommon.h"
#include "GFF/GFFFile.h"
#include "MMH/MDLH.h"
namespace DAO {
namespace PHY {
class PHYFile
: public DAO::GFF::GFFFile
{
typedef DAO::GFF::GFFFile base;
public:
PHYFile();
virtual DAO::MMH::MDLHPtr get_Root();
};
}
}
|
[
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
] |
[
[
[
1,
30
]
]
] |
a0d542af8db14f5d542730b4f02eb8c8c16a7f1d
|
83c9b35f2327528b6805b8e9de147ead75e8e351
|
/filters/FreeFrameFilter.h
|
8519216e24c17b4b61ae75bdf31cc564e3346688
|
[] |
no_license
|
playmodes/playmodes
|
ec6ced2e637769353eb66db89aa88ebd1d5185ac
|
9a91b192be92c8dedc67cbd126d5a50a4d2b9c54
|
refs/heads/master
| 2021-01-22T10:14:18.586477 | 2010-01-02T17:55:50 | 2010-01-02T17:55:50 | 456,188 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 836 |
h
|
/*
* AudioFrame.h
*
* Created on: 09-oct-2008
* Author: arturo castro
*/
// for FreeFrame 1.0 plugin effect
#ifndef FREEFRAMEFILTER_H_
#define FREEFRAMEFILTER_H_
#include "filters/VideoFilter.h"
#include "pipeline/video/VideoSource.h"
#include "FreeFrame/ofFreeframe.h"
class FreeFrameFilter : public VideoFilter {
public:
///
FreeFrameFilter(){};
FreeFrameFilter(VideoSource * source,int w,int h);
virtual ~FreeFrameFilter();
///
VideoFrame * getNextVideoFrame();
int getFps();
void newVideoFrame(VideoFrame &frame);
///
void loadPlugin(char * filename);
void setFFParameter(int index,float value);
ofFreeframe* ff;
private:
///
VideoSource * source;
VideoFrame * currentFrame;
///
int w,h;
};
#endif /* FREEFRAMEFILTER_H_ */
|
[
"[email protected]"
] |
[
[
[
1,
44
]
]
] |
6f91995fff54e3851d3be795355a198b503f64f7
|
6a2e2931641de25b228d323c08ea4f52908c2fad
|
/third_party/skia/src/utils/win/skia_win.cpp
|
0fbc7fc05c6b4dff529dc599e16a4b94461e5c7c
|
[
"BSD-3-Clause"
] |
permissive
|
cnsuhao/chromium_base
|
875417cbbab6857af2349aa57a6037b7563b5fab
|
e252f10aa64f0a0ec942997f73dbf3bd685087cf
|
refs/heads/master
| 2021-04-06T17:04:41.317674 | 2011-12-26T15:06:47 | 2011-12-26T15:06:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,388 |
cpp
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <Windows.h>
#include <tchar.h>
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[] = _T("SampleApp"); // The title bar text
TCHAR szWindowClass[] = _T("SAMPLEAPP"); // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int, LPTSTR);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
MSG msg;
// Initialize global strings
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow, lpCmdLine))
{
return FALSE;
}
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (true)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
#include "SkOSWindow_Win.h"
extern SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
static SkOSWindow* gSkWind;
char* tchar_to_utf8(const TCHAR* str) {
#ifdef _UNICODE
int size = WideCharToMultiByte(CP_UTF8, 0, str, wcslen(str), NULL, 0, NULL, NULL);
char* str8 = (char*) malloc(size+1);
WideCharToMultiByte(CP_UTF8, 0, str, wcslen(str), str8, size, NULL, NULL);
str8[size] = '\0';
return str8;
#else
return strdup(str);
#endif
}
//
// FUNCTION: InitInstance(HINSTANCE, int, LPTSTR)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow, LPTSTR lpCmdLine)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
char* argv[4096];
int argc = 0;
TCHAR exename[1024], *next;
int exenameLen = GetModuleFileName(NULL, exename, 1024);
argv[argc++] = tchar_to_utf8(exename);
TCHAR* arg = _tcstok_s(lpCmdLine, _T(" "), &next);
while (arg != NULL) {
argv[argc++] = tchar_to_utf8(arg);
arg = _tcstok_s(NULL, _T(" "), &next);
}
gSkWind = create_sk_window(hWnd, argc, argv);
for (int i = 0; i < argc; ++i) {
free(argv[i]);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_COMMAND:
return DefWindowProc(hWnd, message, wParam, lParam);
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
if (gSkWind->wndProc(hWnd, message, wParam, lParam)) {
return 0;
} else {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
[
"[email protected]"
] |
[
[
[
1,
201
]
]
] |
8b5af85d6c7dd484682ff8c7d2fdd6f1bf7004a4
|
478570cde911b8e8e39046de62d3b5966b850384
|
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemopen/src/tsemopencases.cpp
|
b84a837531fcedaf752b760d0efc06c39afa9398
|
[] |
no_license
|
SymbianSource/oss.FCL.sftools.ana.compatanamdw
|
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
|
1169475bbf82ebb763de36686d144336fcf9d93b
|
refs/heads/master
| 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,815 |
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:
*
*/
#include "tsemopen.h"
int SemOpen()
{
int retval;
retval = KNotSupported;
return retval;
}
int VerifyResult(ThreadData* aThreadData,int expectedResult)
{
int retval=0;
if ( (expectedResult == aThreadData->iRetValue) && (aThreadData->iExpectederrno == aThreadData->ierrno) )
{
errno = 0;
}
else
{
#ifdef WINDOWS
printf("Expected retval %d Seen %d Expected errno %d Seen %d\n",expectedResult, aThreadData->iRetValue,aThreadData->iExpectederrno,aThreadData->ierrno);
#else
;
#endif
retval = 0;
}
aThreadData->iRetValue = 0;
aThreadData->ierrno = 0;
return retval;
}
void StopThread(ThreadData* aThreadData)
{
if(aThreadData->iSelf != EThreadMain)
{
aThreadData->iStopped = true;
sem_post(aThreadData->iSuspendSemaphore);
#ifdef USE_RTHREAD
User::Exit(KErrNone);
#endif
}
}
//sem_open called on a semaphore
TInt CTestSemopen::TestSem321()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
retval = SemOpen();
retval = VerifyResult(&lThreadData,ENOSYS);
StopThread(&lThreadData);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
|
[
"none@none"
] |
[
[
[
1,
195
]
]
] |
3d701682426235b9cc623910a1a786e91e85dc39
|
c95a83e1a741b8c0eb810dd018d91060e5872dd8
|
/Game/ClientShellDLL/ClientShellShared/MarkSFX.h
|
aa4abc92881338e94e94e9dff8ef2125c6abe2ee
|
[] |
no_license
|
rickyharis39/nolf2
|
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
|
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
|
refs/heads/master
| 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,445 |
h
|
// ----------------------------------------------------------------------- //
//
// MODULE : MarkSFX.h
//
// PURPOSE : Mark special fx class - Definition
//
// CREATED : 11/6/97
//
// ----------------------------------------------------------------------- //
#ifndef __MARKSFX_H__
#define __MARKSFX_H__
#include "SpecialFX.h"
#include "ltlink.h"
struct MARKCREATESTRUCT : public SFXCREATESTRUCT
{
MARKCREATESTRUCT();
LTRotation m_Rotation;
LTVector m_vPos;
LTFLOAT m_fScale;
uint8 nAmmoId;
uint8 nSurfaceType;
};
inline MARKCREATESTRUCT::MARKCREATESTRUCT()
{
m_Rotation.Init();
m_vPos.Init();
m_fScale = 0.0f;
nAmmoId = 0;
nSurfaceType = 0;
}
class CMarkSFX : public CSpecialFX
{
public :
CMarkSFX()
{
m_Rotation.Init();
VEC_INIT(m_vPos);
m_fScale = 1.0f;
m_nAmmoId = 0;
m_nSurfaceType = 0;
m_fElapsedTime = 0.0f;
}
virtual LTBOOL Init(SFXCREATESTRUCT* psfxCreateStruct);
virtual LTBOOL Update();
virtual LTBOOL CreateObject(ILTClient* pClientDE);
virtual void WantRemove(LTBOOL bRemove=LTTRUE);
virtual uint32 GetSFXID() { return SFX_MARK_ID; }
private :
LTRotation m_Rotation;
LTVector m_vPos;
LTFLOAT m_fScale;
LTFLOAT m_fElapsedTime;
uint8 m_nAmmoId;
uint8 m_nSurfaceType;
};
#endif // __MARKSFX_H__
|
[
"[email protected]"
] |
[
[
[
1,
70
]
]
] |
4247d52bd5101f84ff87e2cc1608b1682e9c6711
|
50f4c404a5bace0abf8970ed79623a9c18b3909b
|
/Color.h
|
b94c0e7967dccb31635f8850a61992789a1f04cb
|
[] |
no_license
|
Fissuras/mugenformation
|
94fba15e08ee836db6948e16c0f6b2b552d10a80
|
9293988dd5032538646ef9db8639622ce038239c
|
refs/heads/master
| 2021-01-10T17:21:54.359790 | 2008-07-30T04:15:27 | 2008-07-30T04:15:27 | 49,397,123 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,082 |
h
|
/**
* Utility class that represents a color to draw on the screen.
*
* @author Francis BISSON
*/
#ifndef COLOR_H
#define COLOR_H
// INCLUDES ////////////////////////////////////////////////////////////////////
#include "Types.h"
// CLASS DEFINITION ////////////////////////////////////////////////////////////
class Color
{
public:
Color();
Color(Byte r, Byte g, Byte b);
Color(int hexCode);
~Color();
void SetRed(Byte r) { m_Red = r; }
void SetGreen(Byte g) { m_Green = g; }
void SetBlue(Byte b) { m_Blue = b; }
Byte GetRed() const { return m_Red; }
Byte GetGreen() const { return m_Green; }
Byte GetBlue() const { return m_Blue; }
bool operator== (const Color& color) const;
bool operator!= (const Color& color) const;
static const Color Black;
static const Color White;
static const Color Red;
static const Color Green;
static const Color Blue;
static const Color Grey;
private:
bool IsEqual(const Color& color) const;
Byte m_Red;
Byte m_Green;
Byte m_Blue;
};
#endif // COLOR_H
|
[
"xezekielx@4c29ad15-fc4f-0410-bf84-09c4532b2003"
] |
[
[
[
1,
47
]
]
] |
e211bc42f10388d01673743da8c608d1a935ba2c
|
216398e30aca5f7874edfb8b72a13f95c22fbb5a
|
/CamMonitor/Client/Test/Network.cpp
|
efca5ebf17beb9d9501231d2bc8190124f572af1
|
[] |
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 | 2,247 |
cpp
|
#include "stdafx.h"
#include "Network.h"
#include "CommonType.h"
Network Network::_instance;
Network::Network() :
_isSuccessAuth( -1 ),
_isConnecting( 1 )
{
}
Network::~Network()
{
}
void Network::Init()
{
// 서버 설정
int clientPort = 200;
//std::string ip = "211.189.20.246";
std::string ip = "211.189.19.160";
int serverPort = 10000;
//
RakNetStatistics *rss;
_client=RakNetworkFactory::GetRakPeerInterface();
_client->AllowConnectionResponseIPMigration(false);
//
SocketDescriptor socketDescriptor( clientPort, 0 );
_client->Startup(1,30,&socketDescriptor, 1);
_client->SetOccasionalPing(true);
BOOL b = _client->Connect(ip.c_str(), serverPort, "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"));
if (!b)
{
exit(1);
}
_isConnecting = 1;
_isSuccessAuth = -1;
}
int Network::IsConnected()
{
return _client->NumberOfConnections();
}
void Network::Uninit()
{
//
Sleep(500);
//
_client->Shutdown(300);
RakNetworkFactory::DestroyRakPeerInterface(_client);
}
bool Network::ProcPacket()
{
if( _client == NULL )
{
return FALSE;
}
Sleep(30);
Packet* p;
p = _client->Receive();
if (p==0)
return FALSE;
RakNet::BitStream inStream( p->data, p->length, false );
unsigned char packetIdentifier;
inStream.Read( packetIdentifier );
switch (packetIdentifier)
{
case ID_CONNECTION_LOST:
{
// 데이터 저장
Network::GetInstance()._isConnecting = 0;
}
break;
case S2CH_LOGIN_RES:
{
// 패킷 읽기
int isSuccessAuth;
inStream.Read( isSuccessAuth );
// 데이터 저장
Network::GetInstance()._isSuccessAuth = isSuccessAuth;
}
break;
default:
{
}
break;
}
_client->DeallocatePacket(p);
return TRUE;
}
void Network::ReqLoginSend( std::string id, std::string pass )
{
RakNet::BitStream outBuffer;
outBuffer.Write( (unsigned char)MessageType::CH2S_LOGIN );
outBuffer.Write( id );
outBuffer.Write( pass );
if( _client )
{
_client->Send(&outBuffer, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
}
}
void Network::Disconnect()
{
if( _client )
{
_client->Shutdown( 0 );
}
}
|
[
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
] |
[
[
[
1,
131
]
]
] |
c99a27b127465457845f72e2eaa2f9930ef2cbb0
|
7f30cb109e574560873a5eb8bb398c027f85eeee
|
/src/fusionFilter.h
|
703192bc68c6043bf53d84c87cbe7f39ac895562
|
[] |
no_license
|
svn2github/MITO
|
e8fd0e0b6eebf26f2382f62660c06726419a9043
|
71d1269d7666151df52d6b5a98765676d992349a
|
refs/heads/master
| 2021-01-10T03:13:55.083371 | 2011-10-14T15:40:14 | 2011-10-14T15:40:14 | 47,415,786 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,381 |
h
|
/**
* \file fusionFilter.h
* \brief File per la gestione delle tecniche di fusione
* \author ICAR-CNR Napoli
*/
#ifndef _fusionFilter_h_
#define _fusionFilter_h_
#include "itkVtkFilter.h"
#include "itkFlip.h"
#include <itkImage.h>
#include <itkNumericTraits.h>
/**
* \class fusionFilter
* \brief Filtro che implementa le varie tecniche di fusione.
*/
class fusionFilter {
public:
/**
* \brief Enumerazione delle tecniche di fusione implementate
*/
enum fusionType{
not_defined, /*!< Tecnica di fusione non definita */
media_pesata, /*!< Tecnica di fusione con combinazione aritmetica delle immagini */
wavelet /*!< Tecnica di fusione con trasformata wavelet Daubechies */
};
enum ruleType{
Modulo_max,
Consistenza_media,
Consistenza_var,
Sostituzione_dettaglio
};
typedef int LivelloDec; //definizioni di tipo necessarie per il passaggio di parametri dalla gui (luca)
typedef int SizeWindow;
typedef int WaveletType;
/**
* \brief Tipo di dato reale utilizzato per la gestione dei pesi delle immagini
*/
typedef itk::NumericTraits < short >::RealType InputRealType;
/**
* \brief Costruttore del filtro
*
* \param path1 Percorso della prima immagine o serie
* \param path2 Percorso della seconda immagine o serie
* \param idData0 Id della immagine o serie prodotta
* \param dataHandler Gestore dei dati
*/
fusionFilter (string path1, string path2, unsigned int idData0, dataHandler *dataHandler);
/**
* \brief Distruttore del filtro
*/
~fusionFilter() {};
/**
* \brief Metodo che effettua la fusione tra le immagini o le serie scelte con gli opportuni parametri fissati
*
* \param param1 Peso per la prima immagine, di default 0.5
* \param param2 Peso per la seconda immagine, di default 0.5
* \param param3 Parametro vuoto, lasciato per sviluppi futuri, di defualt 0
* \param fusionType Tecnica di fusione da implementare, di default <b>media_pesata</b>
* \param applyClut Valore booleano che indica l'applicazione della Clut, di default FALSE
* \param leveldec Livello di decomposizione
* \param ruleType Regola di fusione
*\ param sizewin Grandezza della finestra
*\ param DaubCoef Livello della wavelet Daubechies
*/
void computeFusion (InputRealType param1 = 0.5, InputRealType param2 = 0.5, InputRealType param3 = 0, fusionType fusionType = media_pesata, bool applyClut = false, LivelloDec leveldec=1,ruleType ruleType=Modulo_max, SizeWindow sizewin=1, WaveletType waveletType=2);
private:
/**
* \brief Indica se applicare la CLUT
*/
bool _applyClut;
/**
* \brief Dato di uscita
*/
itkVtkData* _itkVtkData0;
/**
* \brief Prima immagine
*/
ImageType::Pointer _itkImage1;
/**
* \brief Seconda immagine
*/
ImageType::Pointer _itkImage2;
/**
* \brief Header DICOM
*/
ImageIOType::Pointer _itkDicomIO;
/**
* \brief Tipo di fusione
*/
fusionType _fusionType;
/**
* \brief Livello di decomposizione
*/
LivelloDec _levelDec;
/**
* \brief Grandezza della finestra
*/
SizeWindow _sizeWindow;
/**
* \brief Livello della wavelet Daubechies
*/
WaveletType _waveletType;
/**
* \brief Regola di fusione
*/
int _fusionRule;
/**
* \brief Window Level della seconda immagine
*/
double _wl2;
/**
* \brief Window Width della seconda immagine
*/
double _ww2;
/**
* \brief Metodo che aggiorna la pipeline verso VTK
*
* \param image Immagine da visualizzare con VTK
*/
inline void update (ImageType::Pointer image) {
if (_itkImage1) {
ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
_itkVtkData0->setRgb(false);
_itkVtkData0->setItkImage(_itkVtkData0->computeFlipping(image));
_itkVtkData0->setDicomEntry(_itkDicomIO,"0010|0020","");
_itkVtkData0->setDicomEntry(_itkDicomIO,"0020|0010","");
_itkVtkData0->setDicomEntry(_itkDicomIO,"0008|1030","");
_itkVtkData0->readDicomEntries(_itkDicomIO);
_itkVtkData0->setSliceNumber(size[2]);
//if(_fusionType == media_pesata) _itkVtkData0->setWl(_wl2*0.8);
//else _itkVtkData0->setWl(_wl2*1.2);
//_itkVtkData0->setWw(_ww2);
_itkVtkData0->setWl(140.0);
_itkVtkData0->setWw(210.0);
_itkVtkData0->getItkVtkConnector()->SetInput(_itkVtkData0->getItkImage());
_itkVtkData0->setVtkImage(_itkVtkData0->getItkVtkConnector()->GetOutput());
}
};
/**
* \brief Metodo che aggiorna la pipeline verso VTK
*
* \param rgbImage Immagine da visualizzare con VTK in formatro RGB
*/
inline void update (RGBImageType::Pointer rgbImage) {
if (_itkImage1) {
RGBImageType::SizeType size = rgbImage->GetLargestPossibleRegion().GetSize();
_itkVtkData0->setRgb(true);
_itkVtkData0->setItkRgbImage(_itkVtkData0->computeRgbFlipping(rgbImage));
_itkVtkData0->setDicomEntry(_itkDicomIO,"0010|0020","");
_itkVtkData0->setDicomEntry(_itkDicomIO,"0020|0010","");
_itkVtkData0->setDicomEntry(_itkDicomIO,"0008|1030","");
_itkVtkData0->readDicomEntries(_itkDicomIO);
_itkVtkData0->setWl(140.0);
_itkVtkData0->setWw(210.0);
_itkVtkData0->setSliceNumber(size[2]);
_itkVtkData0->getItkVtkRgbConnector()->SetInput(_itkVtkData0->getItkRgbImage());
_itkVtkData0->setVtkImage(_itkVtkData0->getItkVtkRgbConnector()->GetOutput());
}
};
/**
* \brief Metodo che effettua la fusione con la tecnica di combinazione aritmetica delle immagini
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void MediaPesata (InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua la fusione con la trasformata wavelet
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void HaarWavelet(InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua la fusione con la tecnica di combinazione aritmetica delle immagini applicando la Clut
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void MediaPesataClut(InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua la fusione con la trasfromata wavelet applicando la Clut
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void HaarWaveletClut(InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua la fusione con la trasformata wavelet secondo DN
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void DaubNWavelet(InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua la fusione con la trasformata wavelet secondo DN applicando la clut
*
* \param pesoA Peso per la prima immagine
* \param pesoB Peso per la seconda immagine
*/
void DaubNWaveletClut(InputRealType pesoA, InputRealType pesoB);
/**
* \brief Metodo che effettua un riposizionamento delle immagini per la fusione 2D
*
* \param im1 Puntatore alla prima immagine
* \param im2 Puntatore alla seconda immagine
*/
void PreStadio2D(ImageType::Pointer im1, ImageType::Pointer im2);
};
#endif _fusionFilter_h_
|
[
"kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de"
] |
[
[
[
1,
250
]
]
] |
6f17561d73b052ff59a4ff0491a60a5e6116dbfc
|
d6eba554d0c3db3b2252ad34ffce74669fa49c58
|
/Source/Engines/CAnimationManager.h
|
7650ca1597b3de6eb654901edb9a36f1628a16e6
|
[] |
no_license
|
nbucciarelli/Polarity-Shift
|
e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10
|
8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017
|
refs/heads/master
| 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 3,841 |
h
|
#ifndef CANIMATIONMANAGER_H_
#define CANIMATIONMANAGER_H_
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: “CAnimationManager.h”
// Author: Jared Hamby (JH)
// Purpose: This is the header file for the animation manager
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "../Wrappers/viewManager.h"
#include <vector>
using std::vector;
class CAnimationEngine;
union matrix;
class baseObj;
class CAnimationManager
{
private:
viewManager* m_pTM;
int references;
baseObj* m_pBase;
CAnimationManager(void) : references(1), m_pBase(0)
{ m_pTM = viewManager::getInstance(); }
CAnimationManager(const CAnimationManager&);
CAnimationManager& operator=(const CAnimationManager&);
~CAnimationManager(void) {};
public:
vector<CAnimationEngine*> m_pAE;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “GetInstance”
// Last modified: August 27, 2008
// Purpose: This gets an instance of the animation manager
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static CAnimationManager* GetInstance(void);
void acquireInstance();
void releaseInstance();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Load”
// Last modified: August 27, 2008
// Purpose: This loads a file for the animation manager to then call on the animation engine
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Load(const char* szFileName, baseObj* object);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Shutdown”
// Last modified: August 27, 2008
// Purpose: This is shuts down the animation manager
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Shutdown(void);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Render”
// Last modified: August 27, 2008
// Purpose: This renders the specific frame for the specific animation engine
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//void Render(int ID, int nPosX, int nPosY, float fScaleX = 1.0f, float fScaleY = 1.0f, float fRotationX = 0.0f,
// float fRotationY = 0.0f, float fRotation = 0.0f, unsigned color = 0xFFFFFFFF);
void Render(int ID, matrix* transform);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Update”
// Last modified: August 27, 2008
// Purpose: This updates the set of frames
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Update(float fDelta);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Accessors”
// Last modified: August 27, 2008
// Purpose: This gets the information needed
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CAnimationEngine* GetEngine(unsigned int nIndex);
};
#endif
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
13
],
[
16,
21
],
[
28,
37
],
[
39,
40
],
[
43,
48
],
[
50,
62
],
[
65,
65
],
[
67,
82
]
],
[
[
14,
15
],
[
22,
27
],
[
38,
38
],
[
41,
42
],
[
49,
49
],
[
63,
64
],
[
66,
66
]
]
] |
9df1603aa6d543008c05d04651d38dd475a93676
|
5a9924aff39460fa52f1f55ff387d9ab82c3470f
|
/tibia80/ini/ini.cpp
|
b493c16f5c81efc5a807d94325f2550108212a0e
|
[] |
no_license
|
PimentelM/evremonde
|
170e4f1916b0a1007c6dbe52b578db53bc6e70de
|
6b56e8461a602ea56f0eae47a96d340487ba987d
|
refs/heads/master
| 2021-01-10T16:03:38.410644 | 2010-12-04T17:31:01 | 2010-12-04T17:31:01 | 48,460,569 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,112 |
cpp
|
/*
INI
by Evremonde
*/
#include "ini.h"
/* constructor and deconstructor */
CIni::CIni()
{
//
}
CIni::~CIni()
{
//
}
/* read ini */
std::vector<std::string> CIni::getSections(std::string fileName)
{
// sections vector
std::vector<std::string> sections;
// open ini file
std::ifstream file(fileName.c_str());
// read line by line
std::string line;
while (std::getline(file, line))
{
// find and parse section
int findPositionBegin = line.find("[");
int findPositionEnd = line.find("]");
if (findPositionBegin != std::string::npos)
{
// get the string between parenthesis
line = line.substr(findPositionBegin + 1, findPositionEnd - 1);
// add the string to sections vector
sections.push_back(line);
}
}
// close ini file
file.close();
return sections;
}
int CIni::readInteger(std::string fileName, std::string section, std::string key)
{
// required for full path fix
std::string fileLocation = "./" + fileName;
return ::GetPrivateProfileInt(section.c_str(), key.c_str(), 0, fileLocation.c_str());
}
|
[
"evretibia@cc901e99-3b3f-0410-afbc-77a0fa429cc7"
] |
[
[
[
1,
59
]
]
] |
dbfed5048b82257de82df64a8f68c2adf041ae58
|
9426ad6e612863451ad7aac2ad8c8dd100a37a98
|
/Samples/smplMDIWnd/MDIApp.cpp
|
50cfdb1ee8e35449b147921f60304ad3d3f7d398
|
[] |
no_license
|
piroxiljin/ullib
|
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
|
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
|
refs/heads/master
| 2020-12-28T19:46:57.920199 | 2010-02-17T01:43:44 | 2010-02-17T01:43:44 | 57,068,293 | 0 | 0 | null | 2016-04-25T19:05:41 | 2016-04-25T19:05:41 | null |
UTF-8
|
C++
| false | false | 1,107 |
cpp
|
#ifdef _DEBUG
#pragma comment(lib,"..\\..\\ULLib\\Lib\\uULLibd.lib")
#else
#pragma comment(lib,"..\\..\\ULLib\\Lib\\uULLib.lib")
#endif
#include "..\..\ULLib\Include\ULStates.h"
#include "..\..\ULLib\Include\ULApp.h"
#include "..\..\ULLib\Include\ULWnd.h"
#include "..\..\ULLib\Include\ULMDIFrameWnd.h"
#include "..\..\ULLib\Include\ULMDIChildWnd.h"
/////////////////////////////////////////////////////
#include ".\mdichild.h"
#include ".\mdiframe.h"
/////////////////////////////////////////////////////
class CMDIApp:public ULApps::CULApp
{
public:
CMDIApp():CULApp(){LOGFILE_ADD(_T("CMDIApp"))};
~CMDIApp()
{
#ifdef _DEBUG
delete m_pMainWnd;m_pMainWnd=NULL;
#endif
LOGFILE_SAVE(_T("CMDIApp"))
};
virtual BOOL InitInstance()
{
CMDIFrame*m_ULMDIFrameWnd=new CMDIFrame;
m_pMainWnd=m_ULMDIFrameWnd;
m_ULMDIFrameWnd->Create(_T("MDI exampla"),IDR_MENU_MAIN,IDI_ICON_MAIN,IDI_ICON_MAIN,
COLOR_WINDOW-1,1);
m_ULMDIFrameWnd->ShowWindow(m_nCmdShow);
m_ULMDIFrameWnd->UpdateWindow();
return (*m_ULMDIFrameWnd!=NULL);
}
};
CMDIApp g_app;
|
[
"UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f"
] |
[
[
[
1,
42
]
]
] |
f99677847f5f63a8dbcb863c4cc032977f375aaf
|
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
|
/WinEdition/browser-lcc/jscc/src/v8/v8/src/.svn/text-base/log-inl.h.svn-base
|
4dc3ee86e3d646939bb55b64a34cc8878c46cdf4
|
[
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-public-domain",
"Artistic-2.0",
"Artistic-1.0"
] |
permissive
|
baxtree/OKBuzzer
|
c46c7f271a26be13adcf874d77a7a6762a8dc6be
|
a16e2baad145f5c65052cdc7c767e78cdfee1181
|
refs/heads/master
| 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,456 |
// Copyright 2006-2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_LOG_INL_H_
#define V8_LOG_INL_H_
#include "log.h"
#include "cpu-profiler.h"
namespace v8 {
namespace internal {
#ifdef ENABLE_LOGGING_AND_PROFILING
Logger::LogEventsAndTags Logger::ToNativeByScript(Logger::LogEventsAndTags tag,
Script* script) {
if ((tag == FUNCTION_TAG || tag == LAZY_COMPILE_TAG || tag == SCRIPT_TAG)
&& script->type()->value() == Script::TYPE_NATIVE) {
switch (tag) {
case FUNCTION_TAG: return NATIVE_FUNCTION_TAG;
case LAZY_COMPILE_TAG: return NATIVE_LAZY_COMPILE_TAG;
case SCRIPT_TAG: return NATIVE_SCRIPT_TAG;
default: return tag;
}
} else {
return tag;
}
}
#endif // ENABLE_LOGGING_AND_PROFILING
} } // namespace v8::internal
#endif // V8_LOG_INL_H_
|
[
"[email protected]"
] |
[
[
[
1,
59
]
]
] |
|
0c15b97aa48167db4c273960dec453a685fd2386
|
27d5670a7739a866c3ad97a71c0fc9334f6875f2
|
/CPP/Shared/Nav2ErrorEl.cpp
|
976e56b91b97e041cbb67e9695710df47ef16296
|
[
"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 | 2,280 |
cpp
|
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define LANGUAGE_EL
#include "master.loc"
#include "Nav2Error.h"
#include "Nav2ErrorXX.h"
namespace isab {
namespace Nav2Error {
static const Nav2ErrorElement nav2ErrorVector[] = {
#define NAV2ERROR_LINE(symbol, id, txt) {ErrorNbr(id), txt},
#define NAV2ERROR_LINE_LAST(symbol, id, txt) {ErrorNbr(id), txt}
#include "Nav2Error.master"
#undef NAV2ERROR_LINE
#undef NAV2ERROR_LINE_LAST
};
Nav2ErrorTableEl::Nav2ErrorTableEl() : Nav2ErrorTable()
{
int32 elementSize = (uint8*)&nav2ErrorVector[1] -
(uint8*)&nav2ErrorVector[0];
m_table = nav2ErrorVector;
m_tableSize = sizeof(nav2ErrorVector) / elementSize;
}
} /* namespace Nav2Error */
} /* namespace isab */
|
[
"[email protected]"
] |
[
[
[
1,
41
]
]
] |
19cf860a0deb0875b0110b5bcc88c9e7bd7f8ab9
|
f95341dd85222aa39eaa225262234353f38f6f97
|
/Dreams/Dreams/Asteroids/main.h
|
e575f00f9ab32df766b0655b7714e196dcec4dc5
|
[] |
no_license
|
Templier/threeoaks
|
367b1a0a45596b8fe3607be747b0d0e475fa1df2
|
5091c0f54bd0a1b160ddca65a5e88286981c8794
|
refs/heads/master
| 2020-06-03T11:08:23.458450 | 2011-10-31T04:33:20 | 2011-10-31T04:33:20 | 32,111,618 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,513 |
h
|
////////////////////////////////////////////////////////////////////////////
//
// Author:
// Joakim Eriksson
//
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Utils/stdafx.h"
#include "XBMC/types.h"
/***************************** D E F I N E S *******************************/
#define NUMLINES 100
/****************************** M A C R O S ********************************/
/***************************** C L A S S E S *******************************/
////////////////////////////////////////////////////////////////////////////
//
typedef struct TRenderVertex
{
f32 x, y, z, w;
DWORD col;
enum FVF { FVF_Flags = D3DFVF_XYZRHW | D3DFVF_DIFFUSE };
} TRenderVertex;
////////////////////////////////////////////////////////////////////////////
//
class CRenderD3D
{
public:
void Init();
bool RestoreDevice();
void InvalidateDevice();
bool Draw();
void DrawLine(const CVector2& pos1, const CVector2& pos2, const CRGBA& col1, const CRGBA& col2);
LPDIRECT3DDEVICE9 GetDevice() { return m_D3dDevice; }
s32 m_NumLines;
int m_Width;
int m_Height;
TRenderVertex* m_Verts;
// Device objects
LPDIRECT3DDEVICE9 m_D3dDevice;
LPDIRECT3DVERTEXBUFFER9 m_VertexBuffer;
};
/***************************** G L O B A L S *******************************/
extern CRenderD3D gRender;
/***************************** I N L I N E S *******************************/
|
[
"julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d"
] |
[
[
[
1,
57
]
]
] |
c4b9950cb68da49df0531192286fe34e33b98df2
|
78d2527df34c524b0742f7e2a9686ea98c5a1bc8
|
/src/effect/volumepan.cpp
|
d3221585757da206a3fcecad33d74cdf8b10d7eb
|
[] |
no_license
|
BackupTheBerlios/flamenco
|
0a5f51c10f9bd089c59b16af070d68e567b72d6b
|
7352e727d3bb8b45f5ce8e512874280cecd1f8f1
|
refs/heads/master
| 2021-01-19T21:28:12.881078 | 2008-12-29T15:46:46 | 2008-12-29T15:46:46 | 39,894,137 | 0 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 1,478 |
cpp
|
/*
libflamenco - lightweight and efficient software sound mixing library.
(c) Trickster Games, 2008. Licensed under GPL license.
Реализация эффекта для изменения громкости и панорамирования.
*/
#include <flamenco/flamenco.h>
using namespace flamenco;
namespace
{
// Приведение f32 к диапазону от 0 до 1.
inline f32 clamp_0_1( f32 value )
{
return value < 0.0f ? 0.0f : value > 1.0f ? 1.0f : value;
}
}
// Создание нового эффекта.
reference<volume_pan> volume_pan::create( reference<pin> input, f32 volume, f32 pan )
{
return reference<volume_pan>(new volume_pan(input, volume, pan));
}
// Конструктор.
volume_pan::volume_pan( reference<pin> input, f32 volume, f32 pan )
: effect(input), volume(volume), pan(pan)
{
assert(0.0f <= volume && volume <= 1.0f);
assert(-1.0f <= pan && pan <= 1.0f);
}
// Заполняет буферы каналов звуковыми данными.
void volume_pan::process( f32 * left, f32 * right )
{
f32 volume = clamp_0_1(this->volume()), pan = this->pan();
f32 volumeLeft = volume * clamp_0_1(1.0f - pan),
volumeRight = volume * clamp_0_1(1.0f + pan);
process_input_pin(left, right);
for (u32 i = 0; i < CHANNEL_BUFFER_SIZE_IN_SAMPLES; ++i)
{
*left++ *= volumeLeft;
*right++ *= volumeRight;
}
}
|
[
"devnull@localhost"
] |
[
[
[
1,
49
]
]
] |
ee487e8ae6bb8ec6616b08034515e80fe45dd675
|
b67f9fa50b816d0c8a0d6328cafe711c8c21f75e
|
/trunk/moc/moc_curve.cpp
|
5d24aac31b7cb1fa8bf8da55cdb65cab3644edc0
|
[] |
no_license
|
BackupTheBerlios/osibs-svn
|
d46db4e3f78fe872f3dad81d2767d8d8e530e831
|
151911e8fb044c183fca251d226a21cfbf4c6c8f
|
refs/heads/master
| 2021-01-20T12:42:52.308488 | 2011-08-17T19:51:02 | 2011-08-17T19:51:02 | 40,800,844 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,213 |
cpp
|
/****************************************************************************
** Meta object code from reading C++ file 'curve.h'
**
** Created: Mon 25. Apr 18:56:49 2011
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../QMapControl/src/curve.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'curve.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_qmapcontrol__Curve[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_qmapcontrol__Curve[] = {
"qmapcontrol::Curve\0"
};
const QMetaObject qmapcontrol::Curve::staticMetaObject = {
{ &Geometry::staticMetaObject, qt_meta_stringdata_qmapcontrol__Curve,
qt_meta_data_qmapcontrol__Curve, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &qmapcontrol::Curve::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *qmapcontrol::Curve::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *qmapcontrol::Curve::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_qmapcontrol__Curve))
return static_cast<void*>(const_cast< Curve*>(this));
return Geometry::qt_metacast(_clname);
}
int qmapcontrol::Curve::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = Geometry::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
|
[
"osiair@cc7348f7-d3be-4701-adbb-128cb98a0978"
] |
[
[
[
1,
69
]
]
] |
432bfcf99ad4c5080dd88793c0a337cb995be00b
|
c86f787916e295d20607cbffc13c524018888a0f
|
/tp2/benchmarks/ejercicio3/operaciones/operacionesLista/main.cpp
|
1828444030cef9150f8b4b77bb53fd844d29fa0f
|
[] |
no_license
|
federicoemartinez/algo3-2008
|
0039a4bc6d83ab8005fa2169b919e6c03524bad5
|
3b04cbea4583d76d7a97f2aee72493b4b571a77b
|
refs/heads/master
| 2020-06-05T05:56:20.127248 | 2008-08-04T04:59:32 | 2008-08-04T04:59:32 | 32,117,945 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,146 |
cpp
|
#include <iostream>
#include "PATRICIA_t.h"
using namespace std;
int main()
{
PATRICIA patri;
ifstream in("palabras500a1000letras.txt", ifstream::in);
string *buff;
int cant;
if(!in.is_open()){
cout << "no se puede encontrar el archivo" << endl;
return 0;
}
//tomo la cantidad de palabras
in >> cant;
buff = new string[cant];
for (int i = 0; i < cant; i++){
getline(in, buff[i]);
}
//empiezo a contar las operaciones, en funcion del largo de las palabras
for (int i = 0; i < cant; i++){
patri.agregar(buff[i]);
//descomentar para contar operaciones de agregar
//cout << patri.operaciones << endl;
}
//descomentar para contar operaciones de pertenece
/*
for (int i = 0; i < cant; i++){
patri.pertenece(buff[i]);
cout << patri.operaciones << endl;
}*/
//descomentar para contar operaciones de sacar
for (int i = 0; i < cant; i++){
patri.sacar(buff[i]);
cout << patri.operaciones << endl;
}
delete [] buff;
return 0;
}
|
[
"seges.ar@bfd18afd-6e49-0410-abef-09437ef2666c"
] |
[
[
[
1,
49
]
]
] |
c3c821216938eabde664cfdb91462ddec66129e8
|
4891542ea31c89c0ab2377428e92cc72bd1d078f
|
/GameEditor/Brick.h
|
7505c3cb2295f4b7e09527a022e0c992ad432eb2
|
[] |
no_license
|
koutsop/arcanoid
|
aa32c46c407955a06c6d4efe34748e50c472eea8
|
5bfef14317e35751fa386d841f0f5fa2b8757fb4
|
refs/heads/master
| 2021-01-18T14:11:00.321215 | 2008-07-17T21:50:36 | 2008-07-17T21:50:36 | 33,115,792 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,672 |
h
|
/*
*author: koutsop
*/
#ifndef BRICK_H
#define BRICK_H
#include <string>
#include <cassert>
#include "Oblong.h"
#include "Point.h"
using namespace std;
class Brick : public Oblong{
private:
int frameNum, timesToBreak, score;
bool canBreak, isActive;
//To isActive 8a to xriastoume gia na 3eroume an ena brick tou pinaka exei
//sxediastei apo ton xristi h' oxi.
public:
//constructor
Brick( const int _frameNum,
const Point _up,
const Point _down,
const int w, const int h,
const bool _canBreak,
const int _timesToBreak,
const int _score,
const bool _isActive);
//overload constructor
Brick( const int _frameNum,
const Point * const _up,
const Point * const _down,
const int w, const int h,
const bool _canBreak,
const int _timesToBreak,
const int _score,
const bool _isActive);
//destructor
~Brick(void);
int GetScore(void) const { return score; }
int GetFrameNum(void) const { return frameNum; }
bool GetCanBreak(void) const { return canBreak; }
bool IsActive(void) const { return isActive; }
int GetTimesToBreak(void) const { return timesToBreak; }
void SetScore(const int score) { this->score = score; }
void SetFrameNum(const int num) { frameNum = num; }
void SetCanBreak(const bool cn) { canBreak = cn; }
void SetIsActive(const bool is) { isActive = is; }
void SetTimesToBreak(const int times) {timesToBreak = times; }
/* @target: Na kanei dep copy ena tou brick pou dinete san orisma ston euato tou.
* @param : To brick pou exei thn pliroforia pou 8eloume.
*/
void Copy(Brick* brick);
};
#endif
|
[
"koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4"
] |
[
[
[
1,
67
]
]
] |
541e48ed69ae8b8410f9c245526144b4e5dd7089
|
c8f467a4cee0b4067b93936574c884c9de0b36cf
|
/source/Irrlicht/CImageLoaderBMP.h
|
d17e1be2198e70f98026a471da14aa13940babcf
|
[
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
flaithbheartaigh/mirrlicht
|
1ff418d29017e55e5f4a27a70dcfd5a88cb244b5
|
ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b
|
refs/heads/master
| 2021-01-10T11:29:49.569701 | 2009-01-12T21:08:31 | 2009-01-12T21:08:31 | 49,994,212 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,357 |
h
|
// Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_IMAGE_LOADER_BMP_H_INCLUDED__
#define __C_IMAGE_LOADER_BMP_H_INCLUDED__
#include "IImageLoader.h"
namespace irr
{
namespace video
{
// byte-align structures
#if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
# pragma pack( push, packing )
# pragma pack( 1 )
# define PACK_STRUCT
#elif defined( __GNUC__ )
# define PACK_STRUCT __attribute__((packed))
#elif defined(__SYMBIAN32__)
# if defined(__WINS__)
# define PACK_STRUCT
# pragma pack(1)
# elif defined(__ARMCC__)
# define PACK_STRUCT
# else
# define PACK_STRUCT __attribute__((packed,aligned(1)))
# endif
#else
# error compiler not supported
#endif
#if defined(__SYMBIAN32__) && defined(__ARMCC__)
__packed
#endif
struct SBMPHeader
{
u16 Id; // BM - Windows 3.1x, 95, NT, 98, 2000, ME, XP
// BA - OS/2 Bitmap Array
// CI - OS/2 Color Icon
// CP - OS/2 Color Pointer
// IC - OS/2 Icon
// PT - OS/2 Pointer
u32 FileSize;
u32 Reserved;
u32 BitmapDataOffset;
u32 BitmapHeaderSize; // should be 28h for windows bitmaps or
// 0Ch for OS/2 1.x or F0h for OS/2 2.x
u32 Width;
u32 Height;
u16 Planes;
u16 BPP; // 1: Monochrome bitmap
// 4: 16 color bitmap
// 8: 256 color bitmap
// 16: 16bit (high color) bitmap
// 24: 24bit (true color) bitmap
// 32: 32bit (true color) bitmap
u32 Compression; // 0: none (Also identified by BI_RGB)
// 1: RLE 8-bit / pixel (Also identified by BI_RLE4)
// 2: RLE 4-bit / pixel (Also identified by BI_RLE8)
// 3: Bitfields (Also identified by BI_BITFIELDS)
u32 BitmapDataSize; // Size of the bitmap data in bytes. This number must be rounded to the next 4 byte boundary.
u32 PixelPerMeterX;
u32 PixelPerMeterY;
u32 Colors;
u32 ImportantColors;
} PACK_STRUCT;
// Default alignment
#if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__)
# pragma pack( pop, packing )
#elif defined(__SYMBIAN32__) && defined(__WINS__)
# pragma pack(4) //default alignment in Project settings
#endif
#undef PACK_STRUCT
/*!
Surface Loader for Windows bitmaps
*/
class CImageLoaderBMP : public IImageLoader
{
public:
//! constructor
CImageLoaderBMP();
//! destructor
virtual ~CImageLoaderBMP();
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".tga")
virtual bool isALoadableFileExtension(const c8* fileName);
//! returns true if the file maybe is able to be loaded by this class
virtual bool isALoadableFileFormat(irr::io::IReadFile* file);
//! creates a surface from the file
virtual IImage* loadImage(irr::io::IReadFile* file);
private:
void decompress8BitRLE(u8*& BmpData, s32 size, s32 width, s32 height, s32 pitch);
void decompress4BitRLE(u8*& BmpData, s32 size, s32 width, s32 height, s32 pitch);
u8* BmpData;
s32* PaletteData;
};
} // end namespace video
} // end namespace irr
#endif
|
[
"limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf"
] |
[
[
[
1,
126
]
]
] |
d817920b06ec2c0c1891720e42e6318150a241d0
|
a3d70ef949478e1957e3a548d8db0fddb9efc125
|
/src/win32/Display.cpp
|
018ab94ca4f5559b7569affa8b54b437038b5960
|
[] |
no_license
|
SakuraSinojun/ling
|
fc58afea7c4dfe536cbafa93c0c6e3a7612e5281
|
46907e5548008d7216543bdd5b9cc058421f4eb8
|
refs/heads/master
| 2021-01-23T06:54:30.049039 | 2011-01-16T12:23:24 | 2011-01-16T12:23:24 | 32,323,103 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,654 |
cpp
|
#include "Display.h"
CDisplay * CDisplay::m_display = NULL;
CDisplay * CDisplay::Get()
{
if(m_display == NULL)
{
m_display = new CDisplay();
}
return m_display;
}
CDisplay::CDisplay()
{
changed = false;
StoreDisplayMode();
}
CDisplay::~CDisplay()
{
RestoreDisplayMode();
m_display = NULL;
}
void CDisplay::StoreDisplayMode()
{
HDC dc = GetDC(0);
devmode_org.dmSize = sizeof(devmode_org);
devmode_org.dmDriverExtra = 0;
devmode_org.dmPelsWidth = GetDeviceCaps(dc, HORZRES);
devmode_org.dmPelsHeight = GetDeviceCaps(dc, VERTRES);
devmode_org.dmBitsPerPel = GetDeviceCaps(dc, BITSPIXEL);
devmode_org.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
if ((GetVersion() & 0x80000000) == 0) // Windows NT/2000
{
devmode_org.dmFields |= DM_DISPLAYFREQUENCY;
devmode_org.dmDisplayFrequency = GetDeviceCaps(dc, VREFRESH);
}
ReleaseDC(0, dc);
}
void CDisplay::RestoreDisplayMode()
{
if (changed)
{
ChangeDisplaySettings(&devmode_org, 0);
changed = false;
}
}
bool CDisplay::ChangeDisplayMode(int width, int height)
{
DEVMODE devmode;
devmode = devmode_org;
devmode.dmPelsWidth = width;
devmode.dmPelsHeight = height;
devmode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT;
if (ChangeDisplaySettings(&devmode, CDS_FULLSCREEN)
== DISP_CHANGE_SUCCESSFUL)
{
changed = true;
return true;
}
return false;
}
|
[
"SakuraSinojun@f09d58f5-735d-f1c9-472e-e8791f25bd30"
] |
[
[
[
1,
78
]
]
] |
e33a9bb5c8be4789ebdcacf40b8c3c67aaf7123e
|
28476e6f67b37670a87bfaed30fbeabaa5f773a2
|
/src/test/testDll/MyData.h
|
a2ae0aa0ebc266ea7f467af1e48f54ad1691d126
|
[] |
no_license
|
rdmenezes/autumnframework
|
d1aeb657cd470b67616dfcf0aacdb173ac1e96e1
|
d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d
|
refs/heads/master
| 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 117 |
h
|
#ifndef AUTUMN_MYDATA_H
#define AUTUMN_MYDATA_H
typedef struct{
int i;
std::string s;
}MyData;
#endif
|
[
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
] |
[
[
[
1,
10
]
]
] |
0d3993a3041fb3daec11a9f8707b4370e9127a69
|
480c44ff4e052723caa9326457921ea1eada5b25
|
/server/src/ServerMain.h
|
bec072a6e36d7c7b0df5f448f4cb9241bbda7335
|
[] |
no_license
|
kevinhs1150/open-online-judge
|
cd898329cf039e0d07835eb98f45b8bd87cff609
|
979e3bffd2965eb21904a73e84cd5bb12a48dbb8
|
refs/heads/master
| 2020-12-25T18:17:15.013425 | 2011-07-16T13:15:49 | 2011-07-16T13:15:49 | 32,213,625 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 786 |
h
|
#ifndef _SERVERMAIN_H_
#define _SERVERMAIN_H_
#include <wx/wx.h>
#include "ServerApp.h"
#include "gui.h"
#include "sqlite3.h"
#include <stdlib.h>
#include <string.h>
extern "C"
{
#include "serverproto.h"
#include "proto_commondefine.h"
}
/* Server GUI class. */
class ServerFrame: public ServerGUI
{
public:
ServerFrame(wxFrame *frame);
~ServerFrame();
/* callback_submission_request{_dlfin}() protection */
wxMutex m_mutexSubmissionRequest;
private:
wxTimer m_timer;
void OnButtonClickStart( wxCommandEvent& event );
void OnButtonClickStop( wxCommandEvent& event );
void OnTimerEvent(wxTimerEvent &event);
void TimerCall(wxCommandEvent &event);
DECLARE_EVENT_TABLE()
};
#endif // _SERVERMAIN_H_
|
[
"fishy0903@e3896563-57da-0129-da3f-310c26432eee",
"[email protected]@e3896563-57da-0129-da3f-310c26432eee",
"[email protected]@e3896563-57da-0129-da3f-310c26432eee",
"kevinhs1150@e3896563-57da-0129-da3f-310c26432eee"
] |
[
[
[
1,
6
],
[
19,
23
],
[
28,
28
],
[
34,
34
],
[
37,
38
]
],
[
[
7,
7
],
[
14,
15
],
[
17,
17
],
[
29,
29
],
[
33,
33
],
[
35,
36
]
],
[
[
8,
11
],
[
18,
18
],
[
24,
27
],
[
30,
32
],
[
39,
39
]
],
[
[
12,
13
],
[
16,
16
]
]
] |
6120e2920668e8f4d2a6007d7347896c6ecc07e8
|
27d5670a7739a866c3ad97a71c0fc9334f6875f2
|
/CPP/Targets/WayFinder/symbian-r6/TimeOutErrorFilter.h
|
84f345104dd5c083b4099694ec9c3fd59c91164b
|
[
"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 | 2,062 |
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 TIMEOUTERRORFILTER_H
#define TIMEOUTERRORFILTER_H
#include "ErrorFilter.h"
class TimeOutErrorFilter : public ErrorFilter {
public:
TimeOutErrorFilter(uint32 timeBetweenShownErrors,
uint32 maxReproducedErrorTime);
/**
* Controls if a reported error should be displayed
* for the user or not.
* @return true if message should be displayed.
* false if not.
*/
virtual bool displayErrorMessage();
};
#endif // TIMEOUTERRORFILTER_H
|
[
"[email protected]"
] |
[
[
[
1,
32
]
]
] |
e0e8faf2ca585bdd676ad10a7125e9c54989f765
|
4a5fd612c361afd2ccca1e0d916724502e2c2741
|
/Source/piece_rook.h
|
38660460c37638381dc3c826bb746dbd8906dcfc
|
[] |
no_license
|
tiagoc/laig-proj3
|
0420a2b117ea2608e13009758bb6328c23fce79e
|
ece8084d7be9556f5f2ad63cc629da9620943546
|
refs/heads/master
| 2020-05-28T07:35:49.407681 | 2011-12-21T00:13:42 | 2011-12-21T00:13:42 | 32,113,920 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 519 |
h
|
#pragma once
#include <GL\glui.h>
#include <math.h>
#include <iostream>
#include "Auxiliary.h"
class Rook{
public:
Rook();
Rook(unsigned int pos_x, unsigned int pos_y, float color[3]);
~Rook();
void render(float scale);
unsigned int get_pos_x(){return this->pos_x;}
unsigned int get_pos_y(){return this->pos_y;}
void set_pos_x(unsigned int npx){this->pos_x = npx;}
void set_pos_y(unsigned int npy){this->pos_y = npy;}
private:
unsigned int pos_x;
unsigned int pos_y;
float color[3];
};
|
[
"[email protected]@8736d240-d46c-fd57-217c-2e9aadc87275"
] |
[
[
[
1,
22
]
]
] |
38f61c92e285e4ea15b63eb9067323e3f2fb878d
|
4763f35af09e206c95301a455afddcf10ffbc1fe
|
/Game Developers Club Puzzle Fighter/Game Developers Club Puzzle Fighter/AI/behaviorClass.h
|
05dd6f20552e0dfba4e7a6a926e35bd5767066db
|
[] |
no_license
|
robertmcconnell2007/gdcpuzzlefighter
|
c7388634677875387ae165fc21f8ff977cea7cfb
|
63dd1daec36d85f6a36ddccffde9f15496a6a1c2
|
refs/heads/master
| 2021-01-20T23:26:48.386768 | 2010-08-25T02:48:00 | 2010-08-25T02:48:00 | 32,115,139 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,259 |
h
|
#pragma once
//#include "..\World States\Main_Game_State.h"
//class pieceClass;
class pos
{
private:
int x, y, d;
public:
int getX() {return x;}
int getY() {return y;}
int getD() {return d;}
void set(int nx, int ny, int nd) { x = nx; y = ny; d = nd;}
};
class behaviorParent // this is the parent class for the behavior classes
{
protected:
bool finished; // has found a position for the piece
int iterator; // used for when the find spot function takes too long to calculate
pos desiredPos; // the desired position based on the behavior
public:
//behaviorParent() { finished = false; iterator = 0; }
behaviorParent();
~behaviorParent();
bool isDone() { return finished; } // will return true when the desired position has been found
void notDone() { finished = false; } // run this when a new desired position needs to be found
pos* getLoc() { return &desiredPos; } // returns the position and orientation of the piece as a struct. x, y, and r(otation)
virtual void findSpot() = 0; // the function to find the desired position of the piece based on the behavior
};
class basicBehavior : public behaviorParent // testing to see if I even remember how this works
{
private:
public:
void findSpot();
};
|
[
"ignatusfordon@7fdb7857-aad3-6fc1-1239-45cb07d991c5"
] |
[
[
[
1,
38
]
]
] |
8076880bc13960fe95338fdd884551a1da888f64
|
6dac9369d44799e368d866638433fbd17873dcf7
|
/src/branches/06112002/projects/src/libQuake2.cpp
|
202f9f04ee1b43317c13be89a03f98f108791c79
|
[] |
no_license
|
christhomas/fusionengine
|
286b33f2c6a7df785398ffbe7eea1c367e512b8d
|
95422685027bb19986ba64c612049faa5899690e
|
refs/heads/master
| 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 635 |
cpp
|
// libQuake2.cpp : Defines the entry point for the DLL application.
//
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "libQuake2.h"
Fusion *fusion;
BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
return TRUE;
}
LIBQUAKE2_API VFSPlugin * CreatePlugin(Fusion *f)
{
static int count = 0;
fusion = f;
VFSPlugin *p = NULL;
switch(count){
// Quake2 Plugins
case 0:{
p = new VFSPlugin_Q2BSP();
}break;
case 1:{
p = new VFSPlugin_Q2WAL();
}break;
case 2:{
p = new VFSPlugin_PCX();
}break;
};
count++;
return p;
}
|
[
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] |
[
[
[
1,
41
]
]
] |
6e72f20dd5d95062bf63fa8ae9f1eaf6ac0de0f7
|
b22c254d7670522ec2caa61c998f8741b1da9388
|
/Server/ConnectedTracker/SharedData.h
|
9d253d55bf9396783befe2a7e3476be207f7d767
|
[] |
no_license
|
ldaehler/lbanet
|
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
|
ecb54fc6fd691f1be3bae03681e355a225f92418
|
refs/heads/master
| 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,090 |
h
|
/*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#if !defined(__Agent_shared_data_h)
#define __Agent_shared_data_h
#include <string>
#include <vector>
#include <map>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <Ice/Config.h>
#include <ConnectedTracker.h>
#include <ChatInfo.h>
/***********************************************************************
* Module: SharedData.h
* Author: vivien
* Modified: lundi 27 juillet 2009 14:59:17
* Purpose: Declaration of the class SharedData
***********************************************************************/
class SharedData : public IceUtil::Mutex
{
public:
//! default construtor
SharedData();
//! get player id
Ice::Long GetId(const std::string & PlayerName);
//! check if user already logged in
//! if not log him in
bool TryLogin(const std::string & PlayerName, long id);
//! get connected list
const LbaNet::ConnectedL & GetConnected();
//! disconnect player
bool Disconnect(Ice::Long playerid);
//! set wisper interface used for web chat
void SetWebWisperInterface(const LbaNet::ChatRoomObserverPrx& winterface);
//! connect from web chat
void ConnectFromWebChat(const std::string& Nickname);
//! disconnect from web chat
void DisconnectFromWebChat(const std::string& Nickname);
//! change player status
void ChangeStatus(const std::string& Nickname, const std::string& NewStatus);
//! change player name display color
void ChangeNameColor(const std::string& Nickname, const std::string& Color);
//! set player wisper interface
void SetWhisperInterface(const std::string& Nickname, const LbaNet::ChatRoomObserverPrx& winterface);
//! a player wisper to another
bool Whisper(const std::string& From, const std::string& To, const std::string& Message);
protected:
SharedData(const SharedData &);
const SharedData & operator=(const SharedData &);
private:
LbaNet::ConnectedL m_connected_users;
std::map<std::string, long> m_id_map;
std::map<std::string, LbaNet::ChatRoomObserverPrx> m_wisper_map;
LbaNet::ChatRoomObserverPrx m_web_wisper;
};
#endif
|
[
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] |
[
[
[
1,
100
]
]
] |
ef51c9b653533d8cccd2dbef213be9f297270928
|
03dd9bf03949715e110f15e4ddeff6d363615290
|
/branches/ntu_xpi/VIII semester/WEB/9/CGI/main.cpp
|
369e03721181e99353e1431bf5d737954aec0b2f
|
[] |
no_license
|
AndriiBorysov/dron-studies
|
a237cc721dcf31ff4a9c4b995c5c7e1d7a934372
|
a5f56faf7c25509e6feeb67aee3dea690f57fad7
|
refs/heads/master
| 2021-01-13T02:23:04.828024 | 2009-12-17T12:29:04 | 2009-12-17T12:29:04 | 32,206,032 | 0 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 1,254 |
cpp
|
#include "main.h"
void main(void)
{
using namespace std;
char *szQueryString;
char *szMethod,*szString;
int size;
// Вывод HTTP-заголовка:
printf("Content-type:text/html;charset=windows-1251\n\n");
// Динамическое формирование Web-страницы:
printf("<H1 style=\"text-align:center;font:italic bold 10mm;color:red\">\
Страница сформирована CGI приложением </H1>");
szMethod=getenv("REQUEST_METHOD");
printf("<P style=\"text-align:center; font-size:7mm; color:green\"> Метод передачи данных: %s</p>",szMethod);
size=atoi(getenv("CONTENT_lENGTH"));
szString=(char*)malloc(size*sizeof(char));
fread(szString,size,1,stdin);
szString[size]='\0';
printf("<P>Объем переданных параметров: %d</p>",size);
printf("<P>Параметры, переданные из формы: %s</p>",szString);
for(int i=0;i<size;i++)
{
if(szString[i]=='+')
szString[i]=' ';
}
char *token;
char seps[] = "=&";
token = strtok(szString,seps);
while( token != NULL )
{
printf( "<P> %s:", token );
token = strtok( NULL, seps );
printf( "%s</p>", token );
token = strtok( NULL, seps );
}
}
|
[
"dron.kh@e01182d0-c8fe-11dd-b6f5-21ad4398c266"
] |
[
[
[
1,
38
]
]
] |
18a6a6cf7437259deccca1c74de338f447c89b38
|
a296df442777ae1e63188cbdf5bcd2ca0adedf3f
|
/2372/2372/Item.cpp
|
d16c4f6a4635e21cf21fa4aac4d04458faf9cabe
|
[] |
no_license
|
piyushv94/jpcap-scanner
|
39b4d710166c12a2fe695d9ec222da7b36787443
|
8fbf4214586e4f07f1b3ec4819f9a3c7451bd679
|
refs/heads/master
| 2021-01-10T06:15:32.064675 | 2011-11-26T20:23:55 | 2011-11-26T20:23:55 | 44,114,378 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 482 |
cpp
|
#include"Item.h"
#include<iostream>
Item::Item(int a,int b){
x=a;
y=b;
}
int Item::getX()const{
return x;
};
int Item::getY() const{
return y;
};
void Item::unitTest(){
std::cout<<"Item Test:"<<std::endl;
std::cout<<(Item)*this;
std::cout<<std::endl;
};
ostream& Item::printOut(ostream& os,const Item& i) const{
os<<i.getX()<<','<<i.getY();
return os;
}
ostream& operator<<(ostream& _os,const Item& _i){
_i.printOut(_os,_i);
return _os;
};
|
[
"[email protected]"
] |
[
[
[
1,
25
]
]
] |
d59e64a732412b823ff1ac93635774a4132bbcc0
|
aa825896cc7c672140405ab51634d00d28fad09b
|
/zomgatron/Thingie.h
|
00056f7bec4557f842d1d4581174a408edee013f
|
[] |
no_license
|
kllrnohj/zomgatron
|
856fa6693b924d629f166c82cdd4db7524f3255d
|
099955f0ab84eb432ab87d351b8defd3123a8991
|
refs/heads/master
| 2021-01-10T08:26:13.826555 | 2009-01-27T17:21:45 | 2009-01-27T17:21:45 | 46,742,521 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,024 |
h
|
#ifndef __THINGIE_H__
#define __THINGIE_H__
#include "Operations3D.h"
#include "d3dx9math.h"
#include "Quaternion.h"
class Thingie{
protected:
Vector3 position;
Vector3 forward, right, up;
public:
Thingie();
Thingie(Vector3 position, Vector3 dirOrLookAt, bool lookAt = true);
void LookAt(Vector3 position, float percent = 100.0f);
void SetPosition(Vector3 position);
void TurnRight(float angle);
void TurnUp(float angle);
void RotateByForward(float angle);
void RotateAt(Vector3 axis, float angle);
void MoveRight(float amount);
void MoveUp(float amount);
void MoveForward(float amount);
void Mimic(Thingie* toMimic) { this->position = toMimic->position; this->forward = toMimic->forward; this->right = toMimic->right; this->up = toMimic->up; }
Vector3 GetPosition() { return position;}
Vector3 GetForward() { return forward; }
Vector3 GetRight() { return right; }
Vector3 GetUp() { return up; }
Quaternion GetQuaternion();
Matrix GetMatrix();
};
#endif
|
[
"Kivu.Rako@54144a58-e977-11dd-a550-c997509ed985"
] |
[
[
[
1,
40
]
]
] |
3145d56d5f4b6ba8151678c1aeda6683cbf91bdb
|
8b0840f68733f5e6ca06ca53e6afcb66341cd4ef
|
/HouseOfPhthah/HouseOfPhthah.h
|
598ebf1895600aa3dbe07b017ff6e650a075fe9c
|
[] |
no_license
|
adkoba/the-house-of-phthah
|
886ee45ee67953cfd67e676fbccb61a12a095e20
|
5be2084b49fe1fbafb22545c4d31d3b6458bf90f
|
refs/heads/master
| 2021-01-18T16:04:29.460707 | 2010-03-20T16:32:09 | 2010-03-20T16:32:09 | 32,143,404 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,639 |
h
|
#ifndef _HouseOfPhthah_
#define _HouseOfPhthah_
#include <OgreSingleton.h>
#include <OgreString.h>
#include "IHouseOfPhthah.h"
#include "Macros.h"
#include "Sky.h"
#include "Terrain.h"
#include "Water.h"
#include "DefaultMeshes.h"
namespace Ogre
{
class Ogre::Root;
class Ogre::SceneManager;
class Ogre::Viewport;
class Ogre::Camera;
class Ogre::RenderWindow;
}
namespace HOP
{
class CHOPFrameListener;
class CCamera;
}
class IEntityMgr;
class CHouseOfPhthah : public Ogre::Singleton< CHouseOfPhthah >
, public IHouseOfPhthah
{
public :
CHouseOfPhthah();
~CHouseOfPhthah();
CSky& getSky() { return mSkyDome; };
static CHouseOfPhthah& getSingleton(void);
static CHouseOfPhthah* getSingletonPtr(void);
HOP::CCamera* getCamera() { return mCamera; }
Ogre::SceneManager* getSceneMgr() { return mSceneMgr; }
Ogre::Root* getRoot() { return mRoot; }
bool Start();
void Run();
void Exit();
public:
Ogre::Root* mRoot;
Ogre::SceneManager* mSceneMgr;
Ogre::Viewport* mViewport;
Ogre::RenderWindow* mWindow;
Ogre::String mResourcePath;
HOP::CHOPFrameListener* mFrameListener;
IEntityMgr* mEntityMgr;
private:
bool configure();
void chooseSceneManager();
void createCamera();
void createScene();
void destroyScene();
void createViewports();
void setupResources();
void loadResources();
void createResourceListener();
void createFrameListener();
private:
HOP::CCamera* mCamera;
CSky mSkyDome;
CTerrain mTerrain;
CWater mWater;
CDefaultMeshes mWorldMeshes;
};
#endif //_HouseOfPhthah_
|
[
"franstreb@4d33156a-524b-11de-a3da-17e148e7a168",
"thilamb@4d33156a-524b-11de-a3da-17e148e7a168"
] |
[
[
[
1,
10
],
[
12,
70
],
[
75,
77
]
],
[
[
11,
11
],
[
71,
74
]
]
] |
aaf89155e677229c5cc5353377d78f7867ebd7dc
|
72071dfcccdab286fce3b0d4483d9e075f0a2ae3
|
/SDLScoreSystem.h
|
1b3289fdd625358ef92d621a6f852b6a818eea53
|
[] |
no_license
|
rickumali/RicksTetris
|
bc824d25ca6403cd12891aa2eae59fc5c6c41a9c
|
76128d72f0cfb75ff4d619784c70fec9562d5c71
|
refs/heads/master
| 2016-09-06T04:27:15.587789 | 2011-12-23T18:17:10 | 2011-12-23T18:17:10 | 3,043,175 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 684 |
h
|
#include "SDL/SDL.h"
#include "SDL_ttf.h"
#include "ScoreSystem.h"
// Similar pattern followed as SDLShape.h and Shape.h.
#ifndef GUARD_sdlscoresystem_h
#define GUARD_sdlscoresystem_h
class SDLScoreSystem {
private:
ScoreSystem *scoresystem;
SDL_Surface *surface;
TTF_Font *font;
Uint32 color;
public:
SDLScoreSystem(SDL_Surface *, TTF_Font *);
void add_lines_to_score(int);
int get_current_score();
void set_current_score(int);
void add_to_current_score(int);
void write_score();
void write_score_to_file();
int get_level();
void increment_level();
void write_gameover();
void write_level();
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
28
]
]
] |
80b7e2a4ef5c5489b9e27c61fc25219aeedc6a3e
|
011359e589f99ae5fe8271962d447165e9ff7768
|
/src/burner/win32/dialogmanager.cpp
|
cd13bbb1db411c1eb6ef6e11f4804e2c76dd8daf
|
[] |
no_license
|
PS3emulators/fba-next-slim
|
4c753375fd68863c53830bb367c61737393f9777
|
d082dea48c378bddd5e2a686fe8c19beb06db8e1
|
refs/heads/master
| 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,078 |
cpp
|
// modeless dialog manager, added by regret
/* changelog:
update 1: create
*/
#include "burner.h"
map<int, HWND> dialogMap;
void dialogAdd(int id, HWND dialog)
{
dialogDelete(id);
dialogMap[id] = dialog;
}
HWND dialogGet(int id)
{
map<int, HWND>::iterator iter = dialogMap.find(id);
if (iter != dialogMap.end()) {
return iter->second;
}
return NULL;
}
void dialogDelete(int id)
{
map<int, HWND>::iterator iter = dialogMap.find(id);
if (iter != dialogMap.end()) {
DestroyWindow(iter->second);
dialogMap.erase(iter);
}
}
bool dialogIsEmpty()
{
return dialogMap.empty();
}
void dialogClear()
{
map<int, HWND>::iterator iter = dialogMap.begin();
for (; iter != dialogMap.end(); iter++) {
DestroyWindow(iter->second);
}
dialogMap.clear();
}
bool dialogIsDlgMessage(MSG* msg)
{
if (!msg) {
return false;
}
map<int, HWND>::iterator iter = dialogMap.begin();
for (; iter != dialogMap.end(); iter++) {
if (IsDialogMessage(iter->second, msg)) {
return true;
}
}
return false;
}
|
[
"[email protected]"
] |
[
[
[
1,
62
]
]
] |
1eced7ab3281527cdc818dedf8b99fdf859da949
|
8a3fce9fb893696b8e408703b62fa452feec65c5
|
/QQTool/QQTool/QQTool.h
|
6065a6ad1e652de1284bbe1a4fc1282d2af9de2e
|
[] |
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 | 485 |
h
|
// QQTool.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CQQToolApp:
// 有关此类的实现,请参阅 QQTool.cpp
//
class CQQToolApp : public CWinApp
{
public:
CQQToolApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CQQToolApp theApp;
|
[
"[email protected]"
] |
[
[
[
1,
31
]
]
] |
e495d8b28685a8d187febb8d1b0bd268e09857b3
|
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
|
/108/10801/c.cpp
|
cc72601cbfd385cca8ab631dce31016c5ab8dfe2
|
[] |
no_license
|
Emerson21/uva-problems
|
399d82d93b563e3018921eaff12ca545415fd782
|
3079bdd1cd17087cf54b08c60e2d52dbd0118556
|
refs/heads/master
| 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,720 |
cpp
|
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int n,k;
int t[200];
#define FOR(z,a) for(int z=0;z<a;z++)
#define PR(v) cout << v
#define PRS(v) cout << v << " "
char l[1000];
bool vai[200][200];
long minimo[200];
bool v[200];
int TEMPO(int el,int de,int pa) {
return abs(de-pa) * t[el];
}
void tenta(int at,long t) {
v[at] = true;
if(at==k) {
return;
}
cout << at << " at " << t << endl;
if(t!=0) t += 60;
// ve quais elevadores para nesse
FOR(i,n) {
if(!vai[i][at]) continue;
//PR("elevador " << i << endl);
FOR(j,100) {
if(v[j]) continue;
if(!vai[i][j]) continue;
if(minimo[j] <= t + TEMPO(i,at,j)) continue;
minimo[j] = t + TEMPO(i,at,j);
}
}
int m1 = -1;
FOR(j,100) {
if(v[j]) continue;
if(m1==-1 || minimo[m1]>minimo[j]) {
m1 = j;
}
}
FOR(j,100) if(!v[j] && minimo[j]!=2<<10) cout << j << "=" << minimo[j] << " ";
cout << endl;
if(m1!=-1 && minimo[m1]!=2<<10) tenta(m1,minimo[m1]);
}
int main() {
while((cin >> n >> k)) {
cout << "START" << endl;
FOR(i,n) { cin >> t[i]; }
FOR(i,100) v[i] = false;
cout << endl;
FOR(i,n) FOR(j,100) vai[i][j] = false;
scanf(" ");
FOR(i,n) {
cin.getline(l,1000);
char *s = strtok(l," ");
while(s) {
int v = atoi(s);
vai[i][v] = true;
s = strtok(0," ");
}
}
FOR(i,n) {
FOR(j,51) PRS(vai[i][j]);
PR(endl);
}
FOR(i,100) minimo[i] = 2 << 10;
minimo[0] = 0;
if(n!=0) tenta(0,0);
FOR(i,100) if(minimo[i]!=2<<10) PRS(i << "=" << minimo[i]);
PR(endl);
if(v[k]==false) PR("IMPOSSIBLE" << endl);
else PR(minimo[k] << endl);
}
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
94
]
]
] |
115b2e343451e68c4547e6ae5bb73754d8620241
|
6581dacb25182f7f5d7afb39975dc622914defc7
|
/CMichaelJanssonJokeConsole/cMichaelJanssonJokeConsole_main.cpp
|
6c4a0d61b762e28b67f02c1920c0c8333307ccb5
|
[] |
no_license
|
dice2019/alexlabonline
|
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
|
4c433839965ed0cff99dad82f0ba1757366be671
|
refs/heads/master
| 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,433 |
cpp
|
// *********************************************************************
// * This software is made available only to individuals and only *
// * for educational purposes. Any and all commercial use is *
// * stricly prohibited. *
// *********************************************************************
//**********************************************************************
//* Disclaimer: Any borrowed code used in this *
//* program is the property of the *
//* code originator. credit to them. *
//* *
//* *
//* Unfinished *
//* WARNING: *
//* *
//* *
//* *
//**********************************************************************
#include "cMichaelJanssonJokeConsole.h"
int main()
{
cMichaelJanssonJokeConsole *MichaelJanssonJokeConsole = new cMichaelJanssonJokeConsole(1);
return 0;
}
|
[
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] |
[
[
[
1,
27
]
]
] |
8c376f322050d06ee172d9cd1be2b7a652ec7e04
|
4c3c35e4fe1ff2567ef20f0b203fe101a4a2bf20
|
/HW5/src/GzFrameBuffer.h
|
9256bf25d7bd76775158c195c68580fce2ffcef9
|
[] |
no_license
|
kolebole/monopolocoso
|
63c0986707728522650bd2704a5491d1da20ecf7
|
a86c0814f5da2f05e7676b2e41f6858d87077e6a
|
refs/heads/master
| 2021-01-19T15:04:09.283953 | 2011-03-27T23:21:53 | 2011-03-27T23:21:53 | 34,309,551 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,143 |
h
|
#ifndef __GZ_FRAME_BUFFER_H_
#define __GZ_FRAME_BUFFER_H_
#include "GzCommon.h"
#include "GzImage.h"
#include "GzVector.h"
#include "GzMatrix.h"
#include <vector>
#include <cmath>
using namespace std;
//Frame buffer with Z-buffer -------------------------------------------------
class GzFrameBuffer {
public:
//The common interface
void initFrameSize(GzInt width, GzInt height);
GzImage toImage();
void clear(GzFunctional buffer);
void setClearColor(const GzColor& color);
void setClearDepth(GzReal depth);
void drawPoint(const GzVertex& v, const GzColor& c, GzFunctional status);
void drawTriangle(vector<GzVertex>& v, vector<GzColor>& c, GzFunctional status);
void shadeModel(const GzInt model); //Set the current shade model (curShadeModel)
void addLight(const GzVector& v, const GzColor& c); //Add a light source at position p with color c
void material(GzReal _kA, GzReal _kD, GzReal _kS, GzReal _s); //Specify the meterial of the object, includes:
// _kA: The ambient coefficients
// _kD: The diffuse coefficients
// _kS: The specular coefficients
// _s: The spec power
void loadLightTrans(GzMatrix& mat);
void drawPointWLight(const GzVertex& v, const GzColor& c, const GzVector& n, GzFunctional status);
void drawTriangleWLight(vector<GzVertex>& v, vector<GzColor>& c, vector<GzVector>& n, GzFunctional status);
//Assignment 5 functions right here
//Loading the Texture into frame buffer
void texture(const GzImage& t);
//draw triangle with vertex
void drawTriangle(vector<GzVertex>& v, vector<GzTexCoord> t, GzFunctional status);
private:
//Shading
GzInt curShadeModel;
vector<GzVector> lightDir;
vector<GzColor> lightColor;
GzReal kA, kD, kS, s;
GzMatrix lightTrans;
GzImage image;
vector<vector<GzReal> > depthBuffer;
GzColor clearColor;
GzReal clearDepth;
void realInterpolate(GzReal key1, GzReal val1, GzReal key2, GzReal val2, GzReal key, GzReal& val);
void colorInterpolate(GzReal key1, GzColor& val1, GzReal key2, GzColor& val2, GzReal key, GzColor& val);
void normalInterpolate(GzReal key1, GzVector& val1, GzReal key2, GzVector& val2, GzReal key, GzVector& val);
void textureInterpolate(GzReal key1, GzTexCoord& val1, GzReal key2, GzTexCoord& val2, GzReal key, GzTexCoord& val);
void drawRasLine(GzInt y, GzReal xMin, GzReal zMin, GzColor& cMin, GzReal xMax, GzReal zMax, GzColor& cMax, GzFunctional status);
void drawRasLine(GzInt y, GzReal xMin, GzReal zMin, GzTexCoord& tMin, GzReal xMax, GzReal zMax, GzTexCoord& tMax, GzFunctional status);
void drawRasLineWLight(GzInt y, GzReal xMin, GzReal zMin, GzColor& cMin, GzVector& nMin, GzReal xMax, GzReal zMax, GzColor& cMax, GzVector& nMax, GzFunctional status);
GzColor colorWLight(GzColor c, GzVector n);
//Assigment 5
//Store the current texture
GzImage tex;
};
GzTexCoord operator / (const GzTexCoord& tex,const GzReal& c);
//----------------------------------------------------------------------------
#endif
|
[
"[email protected]@a7811d78-34aa-4512-2aaf-9c23cbf1bc95"
] |
[
[
[
1,
78
]
]
] |
2a5d523586a4d35eb9613e70a740947525168f66
|
7c3b9e8e05236a05de3a5097b70160dfde0313e3
|
/firmware/eLua/mux/frontend/main.cpp
|
8a0dcaeecac2f1c3111cd9292c9661751e7295f9
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
yisea123/moonlight
|
e1c228ad063cf39b8b85e163d90d1ca185bfad85
|
377b8370f2bab42980389c664ac84d43c2299291
|
refs/heads/master
| 2020-06-28T06:34:51.039649 | 2011-01-27T02:13:38 | 2011-01-27T02:13:38 | 200,165,435 | 1 | 0 | null | 2019-08-02T04:32:02 | 2019-08-02T04:32:02 | null |
UTF-8
|
C++
| false | false | 1,534 |
cpp
|
// -*- C++ -*- generated by wxGlade 0.6.3 on Sun Feb 28 15:10:07 2010
#include <wx/wx.h>
#include <wx/image.h>
#include <wx/debug.h>
#include "MuxFrontendDialog.h"
#include "ListPorts.h"
#include "wxs.h"
// A struct to convert from pointer to chars to wxstrings, too lazy to edit listports.c
struct PortInfo
{
wxString PortName;
wxString FriendlyName;
wxString Technology;
PortInfo( LISTPORTS_PORTINFO* pInfo ):
PortName( pInfo->lpPortName ),
FriendlyName( pInfo->lpFriendlyName ),
Technology( pInfo->lpTechnology ) {}
};
class MuxFrontendApp: public wxApp {
public:
bool OnInit();
};
IMPLEMENT_APP(MuxFrontendApp)
DEFINE_EVENT_TYPE( wxEVT_TEXTCTRL_DATA )
#ifdef WIN32_BUILD
// Serial enumeration callback
extern "C" BOOL CALLBACK ser_callback( LPVOID lpCallbackValue, LISTPORTS_PORTINFO* lpPortInfo )
{
wxArrayString* ports = ( wxArrayString* )lpCallbackValue;
ports->Add( wxString( lpPortInfo->lpPortName ) );
return TRUE;
}
#endif
bool MuxFrontendApp::OnInit()
{
wxInitAllImageHandlers();
// List all serial ports in the system
wxArrayString ports;
#ifdef WIN32_BUILD
ListPorts( ser_callback, &ports );
#endif
if( ports.GetCount() == 0 )
{
wxMessageBox( _( "Unable to find a serial port" ), _( "Error" ) );
return false;
}
MuxFrontendDialog dialog_fe( NULL, wxID_ANY, wxEmptyString, ports );
//SetTopWindow(dialog_fe);
dialog_fe.ShowModal();
return false;
}
|
[
"[email protected]"
] |
[
[
[
1,
61
]
]
] |
c63713fc357ee91771bcd0717ba89a05f63a4490
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/nebula2/src/file/nrlefile.cc
|
d5bd97b0f3877b82cd69b3f5c90a2b74778bdd88
|
[] |
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 | 7,040 |
cc
|
//------------------------------------------------------------------------------
// nrlefile.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchnnebula.h"
#include "file/nrlefile.h"
//------------------------------------------------------------------------------
/**
Default constructor
*/
nRleFile::nRleFile() :
writeMode(false)
{
// Empty
}
//------------------------------------------------------------------------------
/**
Destructor
*/
nRleFile::~nRleFile()
{
if ( this->IsOpen() )
{
this->Close();
}
}
//------------------------------------------------------------------------------
/**
Open a file
*/
bool nRleFile::Open(const nString & fileName, const char* accessMode )
{
n_assert_return( !fileName.IsEmpty(), false );
n_assert_return( accessMode, false );
this->fileName = fileName;
this->writeMode = nString(accessMode).FindChar('w', 0) != -1;
// Init memory file
nString emptyFilename;
bool success = nMemFile::Open( emptyFilename, "r" );
// If opening a file for read, read and decode it entirely to memory
if ( !this->writeMode && success )
{
nFile* sourceFile = nFileServer2::Instance()->NewFileObject();
n_assert( sourceFile );
success = sourceFile->Open( fileName, "rb" );
if ( success )
{
success = this->DecodeFile( sourceFile, this );
sourceFile->Close();
this->Seek( 0, nFile::START );
}
else
{
nMemFile::Close();
}
sourceFile->Release();
}
return success;
}
//------------------------------------------------------------------------------
/**
Close the file
*/
void nRleFile::Close()
{
this->Close2();
}
//------------------------------------------------------------------------------
/**
Same as Close, but indicating if the file has been successfully writen
*/
bool nRleFile::Close2()
{
if ( !this->IsOpen() )
{
return false;
}
bool success( true );
// If writing a file, encode and write it entirely from memory
if ( this->writeMode )
{
nFile* targetFile = nFileServer2::Instance()->NewFileObject();
n_assert( targetFile );
success = targetFile->Open( this->fileName, "wb" );
if ( success )
{
this->Seek( 0, nFile::START );
success = this->EncodeFile( this, targetFile );
targetFile->Close();
}
targetFile->Release();
}
// Clear memory file
nMemFile::Close();
return success;
}
//------------------------------------------------------------------------------
/**
Write a run length encoded version of a file
*/
bool nRleFile::EncodeFile( nFile* sourceFile, nFile* targetFile )
{
// Copy whole file to memory
int size = sourceFile->GetSize();
char* buf = n_new(char)[size];
size = sourceFile->Read( buf, size );
// Encode the file
if ( size > 0 )
{
targetFile->Write( buf, 1 );
--size;
unsigned int runlength(0);
char* prev = buf;
char* next = buf + 1;
for ( ; size > 0; ++prev, ++next, --size )
{
if ( *prev == *next )
{
if ( runlength == 0 )
{
// Repeat value so decode knows that 2 equal values indicates that
// a runlength code follows up
targetFile->Write( next, 1 );
++runlength;
}
else if ( runlength == 256 )
{
// Write runlength code even if there's still more repeated values,
// since the runlength is limitted to 256
unsigned char code( 255 );
targetFile->Write( &code, 1 );
runlength = 0;
targetFile->Write( next, 1 );
}
else
{
// Keep counting repeated values
++runlength;
}
}
else
{
if ( runlength > 0 )
{
// Write the runlength code only when two equal consecutive values are found
n_assert( runlength >= 1 && runlength <= 256 );
unsigned char code = static_cast<unsigned char>( runlength - 1 );
targetFile->Write( &code, 1 );
runlength = 0;
}
targetFile->Write( next, 1 );
}
}
}
n_delete( buf );
return true;
}
//------------------------------------------------------------------------------
/**
Write a run length decoded version of a file
*/
bool nRleFile::DecodeFile( nFile* sourceFile, nFile* targetFile )
{
// Copy whole file to memory
int size = sourceFile->GetSize();
unsigned char* buf = n_new(unsigned char)[size];
size = sourceFile->Read( buf, size );
// Decode the file
if ( size > 0 )
{
targetFile->Write( buf, 1 );
--size;
unsigned char* prev = buf;
unsigned char* next = buf + 1;
unsigned char repetition = 1;
for ( ; size > 0; ++prev, ++next, --size )
{
if ( repetition == 2 )
{
// 2 repeated values are followed by a run length code,
// so read it and write the same value the amount indicated by the run length
for ( unsigned char runlength = *next; runlength > 0; --runlength )
{
targetFile->Write( prev, 1 );
}
repetition = 0;
}
else if ( repetition == 0 )
{
// Previous value was a run length code, so now follows a non run length code
// which must be writen direct to target file
targetFile->Write( next, 1 );
++repetition;
}
else
{
n_assert( repetition == 1 );
if ( *prev == *next )
{
// Two repetead values, mark it so next iteration knows that a run length code follows up
repetition = 2;
}
else
{
// A diferent value, no run length code will follow up
repetition = 1;
}
// The two values following a run length code are always writen
targetFile->Write( next, 1 );
}
}
}
n_delete( buf );
return true;
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
234
]
]
] |
401d21efa8ce1f305c8e10cd3ea98d02ee337ff9
|
905a210043c8a48d128822ddb6ab141a0d583d27
|
/sigviewer/tcltkconsole.cpp
|
b958f02043b93e15ed5f17207384232323820f6f
|
[] |
no_license
|
mweiguo/sgt
|
50036153c81f35356e2bfbba7019a8307556abe4
|
7770cdc030f5e69fef0b2150b92b87b7c8b56ba5
|
refs/heads/master
| 2020-04-01T16:32:21.566890 | 2011-10-31T04:35:02 | 2011-10-31T04:35:02 | 1,139,668 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,932 |
cpp
|
#include "tcltkconsole.h"
#include <locale.h>
#include <stdexcept>
#include "sgr_interface.h"
void WishPanic( CONST char *format, ...)
{
va_list argList;
char buf[1024];
va_start(argList, format);
vsprintf(buf, format, argList);
}
int Tcl_AppInit( Tcl_Interp *interp)
{
// Tcl_Eval (interp, "set tcl_library \"C:/Tcl/lib/tcl8.5\"" );
try
{
if ( TCL_OK != Tcl_Init(interp) )
throw std::logic_error ( Tcl_GetStringResult ( interp ));
if ( TCL_OK != Tk_Init(interp) )
throw std::logic_error ( Tcl_GetStringResult ( interp ));
Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit);
Tk_InitConsoleChannels(interp);
if ( TCL_OK != Tk_CreateConsoleWindow(interp) )
throw std::logic_error ( Tcl_GetStringResult ( interp ));
if ( TCL_OK != Tcl_Eval (interp, "wm withdraw ." ) )
throw std::logic_error ( Tcl_GetStringResult ( interp ));
if ( TCL_OK != Tcl_Eval (interp, "console show" ) )
throw std::logic_error ( Tcl_GetStringResult ( interp ));
register_tclcmds ( interp );
Tcl_SetVar(interp, "tcl_rcFileName", "./.rc", TCL_GLOBAL_ONLY);
}
catch ( std::exception& ex )
{
const char* errinfo = ex.what();
return TCL_ERROR;
}
return TCL_OK;
}
void Tk_MainThread ( int argc, char **argv )
{
char *p;
Tcl_SetPanicProc(WishPanic);
/*
* Set up the default locale to be standard "C" locale so parsing is
* performed correctly.
*/
setlocale(LC_ALL, "C");
/*
* Forward slashes substituted for backslashes.
*/
for (p = argv[0]; *p != '\0'; p++) {
if (*p == '\\') {
*p = '/';
}
}
#ifdef TK_LOCAL_MAIN_HOOK
TK_LOCAL_MAIN_HOOK(&argc, &argv);
#endif
Tk_Main(argc, argv, Tcl_AppInit);
}
|
[
"[email protected]"
] |
[
[
[
1,
72
]
]
] |
899da5f8ba8d6d2227cbf0d9c0241538806ccb45
|
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
|
/pyplusplus_dev/unittests/data/refee_refer_to_be_exported.hpp
|
a8c80b7ebc5f269e93c1e27e09327d3b49ab7ef3
|
[
"BSL-1.0"
] |
permissive
|
gatoatigrado/pyplusplusclone
|
30af9065fb6ac3dcce527c79ed5151aade6a742f
|
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
|
refs/heads/master
| 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 585 |
hpp
|
// Copyright 2004-2008 Roman Yakovenko.
// 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 __refee_refer_to_be_exported_hpp__
#define __refee_refer_to_be_exported_hpp__
#include <memory>
struct refee_t{
int i;
};
struct refer_t{
refee_t& refee;
};
inline std::auto_ptr<refer_t> make_refer(refee_t* refee){
refer_t tmp = { *refee };
return std::auto_ptr<refer_t>(new refer_t(tmp));
}
#endif//__refee_refer_to_be_exported_hpp__
|
[
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] |
[
[
[
1,
24
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.