blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e1f72018c4e8800f37175cddc638b9a9b75908cd | 8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab | /src-ginga-editing/ncl30-generator-cpp/src/AssessmentStatementGenerator.cpp | c2d43d9c741d6d088df0d2a6ea5285a20b2777e3 | [] | no_license | BrunoSSts/ginga-wac | 7436a9815427a74032c9d58028394ccaac45cbf9 | ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c | refs/heads/master | 2020-05-20T22:21:33.645904 | 2011-10-17T12:34:32 | 2011-10-17T12:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,090 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file AssessmentStatementGenerator.cpp
* @author Caio Viel
* @date 29-01-10
*/
#include "../include/AssessmentStatementGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generate {
string AssessmentStatementGenerator::generateCode() {
string ret = "<assessmentStatement comparator =\"";
ret += Comparator::toString(this->getComparator()) + "\" ";
ret += ">\n";
ret += static_cast<AtributeAssessmentGenerator*>(this->getMainAssessment())->generateCode() + "\n";
Assessment* other = this->getOtherAssessment();
if (other->instanceOf("AttributeAssessment")) {
ret+= static_cast<AtributeAssessmentGenerator*>(other)->generateCode();
} else if (other->instanceOf("ValueAssessment")) {
ret+= static_cast<ValueAssessmentGenerator*>(other)->generateCode();
}
ret += "</assessmentStatement>\n";
return ret;
}
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
85
]
]
] |
927431c9e2415923501eb7d68e679326660ef356 | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /lib/entity/components/timecomponent.h | 2a7cae0539af2e2dd4fa26770a3390dfb795a28c | [] | no_license | akin666/ice | 4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2 | 7cfd26a246f13675e3057ff226c17d95a958d465 | refs/heads/master | 2022-11-06T23:51:57.273730 | 2011-12-06T22:32:53 | 2011-12-06T22:32:53 | 276,095,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | h | /*
* timecomponent.h
*
* Created on: 31.10.2011
* Author: akin
*/
#ifndef TIMECOMPONENT_H_
#define TIMECOMPONENT_H_
#include <entity/component>
#include <entity/entity>
#include <system/common>
#include <system/clock>
#include <deque>
#include <entity/properties/timeproperty.h>
#include "timework.h"
namespace ice
{
class TimeComponent : public Component
{
public:
const static std::string KEY;
protected:
std::deque<EntityKey> entities;
Clock clock;
TimeWork work;
TimeProperty *property;
// EVIL! but, imagining that the work is just a package,
// and this is the distributor. No need to save all data
// twice or thrice.
friend class TimeWork;
public:
TimeComponent() throw (ComponentException);
virtual ~TimeComponent();
virtual void attach( Entity& entity ) throw (ComponentException);
virtual void detach( Entity& entity ) throw (ComponentException);
virtual void start() throw (ComponentException);
};
} /* namespace ice */
#endif /* TIMECOMPONENT_H_ */
| [
"akin@lich",
"akin@localhost"
] | [
[
[
1,
10
],
[
12,
12
],
[
15,
21
],
[
23,
23
],
[
26,
28
],
[
30,
38
],
[
40,
41
],
[
44,
44
],
[
46,
49
]
],
[
[
11,
11
],
[
13,
14
],
[
22,
22
],
[
24,
25
],
[
29,
29
],
[
39,
39
],
[
42,
43
],
[
45,
45
]
]
] |
85383a752f2bde927d3866e24ed0f9bdbe0b8565 | ea2786bfb29ab1522074aa865524600f719b5d60 | /MultimodalSpaceShooter/src/entities/Explosion.h | a19b9f5a3cad4d65a1b2ccbc62e89275dbfe5aa9 | [] | no_license | jeremysingy/multimodal-space-shooter | 90ffda254246d0e3a1e25558aae5a15fed39137f | ca6e28944cdda97285a2caf90e635a73c9e4e5cd | refs/heads/master | 2021-01-19T08:52:52.393679 | 2011-04-12T08:37:03 | 2011-04-12T08:37:03 | 1,467,691 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 764 | h | #ifndef EXPLOSION_H
#define EXPLOSION_H
#include "entities/Entity.h"
#include "utils/AnimatedSprite.h"
#include <string>
#include <SFML/Graphics.hpp>
//////////////////////////////////////////////////
/// Explosion entity, when a planet or another
/// object is destroyed
//////////////////////////////////////////////////
class Explosion : public Entity
{
public:
static const sf::Vector2f FRAME_SIZE;
Explosion(const sf::Vector2f& initialPos);
virtual void update(float frameTime);
virtual void draw(sf::RenderTarget& window) const;
virtual sf::FloatRect getBoundingRect() const;
private:
AnimatedSprite mySprite;
sf::Clock myClock;
};
#endif // EXPLOSION_H | [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
0469758a636ae32a87ba46ca44250022cd2f0fb0 | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/Item.cpp | fd6d93d8c8d7d967f6537120743bdea5c39a4641 | [
"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 | 25,366 | 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"
Item::Item( )
{
m_objectType |= TYPE_ITEM;
m_objectTypeId = TYPEID_ITEM;
m_valuesCount = ITEM_END;
m_itemProto = NULL;
m_owner = NULL;
loot = NULL;
locked = false;
_dbguid = 0;
}
Item::~Item()
{
if(loot != NULL)
delete loot;
sEventMgr.RemoveEvents(this);
EnchantmentMap::iterator itr;
for(itr = Enchantments.begin(); itr != Enchantments.end(); ++itr)
{
if(itr->second.Enchantment->type == 0 && itr->second.Slot == 0 && itr->second.ApplyTime == 0 && itr->second.Duration == 0)
{
delete itr->second.Enchantment;
itr->second.Enchantment = NULL;
}
}
}
void Item::Create( uint32 guidlow, uint32 itemid, Player *owner )
{
Object::_Create( guidlow, HIGHGUID_ITEM );
SetUInt32Value( OBJECT_FIELD_ENTRY, itemid );
SetFloatValue( OBJECT_FIELD_SCALE_X, 1.0f );
SetUInt64Value( ITEM_FIELD_OWNER, owner->GetGUID() );
SetUInt64Value( ITEM_FIELD_CONTAINED, owner->GetGUID() );
SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
m_itemProto = objmgr.GetItemPrototype( itemid );
ASSERT(m_itemProto);
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES , m_itemProto->SpellCharges[0] );
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES_01 , m_itemProto->SpellCharges[1] );
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES_02 , m_itemProto->SpellCharges[2] );
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES_03 , m_itemProto->SpellCharges[3] );
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES_04 , m_itemProto->SpellCharges[4] );
SetUInt32Value( ITEM_FIELD_MAXDURABILITY, m_itemProto->MaxDurability);
SetUInt32Value( ITEM_FIELD_DURABILITY, m_itemProto->MaxDurability);
m_owner = owner;
_dbguid = GetGUID();
if(m_itemProto->LockId > 1)
locked = true;
else
locked = false;
}
void Item::LoadFromDB( Field *fields, Player * plr, bool light)
{
_dbguid = fields[1].GetUInt32();
Object::_Create( fields[1].GetUInt32(), HIGHGUID_ITEM );
uint32 itemid=fields[2].GetUInt32();
m_itemProto = objmgr.GetItemPrototype( itemid );
ASSERT(m_itemProto);
if(m_itemProto->LockId > 1)
locked = true;
else
locked = false;
SetUInt32Value( OBJECT_FIELD_ENTRY, itemid );
m_owner = plr;
SetFloatValue( OBJECT_FIELD_SCALE_X, 1.0f );
SetUInt32Value( ITEM_FIELD_CREATOR, fields[3].GetUInt32() );
SetUInt32Value( ITEM_FIELD_STACK_COUNT, fields[4].GetUInt32());
for(uint32 x=0;x<5;x++)
if(m_itemProto->SpellId[x])
{
SetUInt32Value( ITEM_FIELD_SPELL_CHARGES+x , fields[5].GetUInt32() );
break;
}
SetUInt32Value( ITEM_FIELD_FLAGS, fields[6].GetUInt32());
SetUInt32Value( ITEM_FIELD_RANDOM_PROPERTIES_ID, fields[7].GetUInt32());
SetUInt32Value( ITEM_FIELD_ITEM_TEXT_ID, fields[8].GetUInt32());
SetUInt32Value( ITEM_FIELD_MAXDURABILITY, m_itemProto->MaxDurability);
SetUInt32Value( ITEM_FIELD_DURABILITY, fields[9].GetUInt32());
if(light) return;
string enchant_field = fields[12].GetString();
vector<string> enchants = StrSplit(enchant_field, ";");
uint32 enchant_id;
EnchantEntry * entry;
uint32 time_left;
uint32 enchslot;
for(vector<string>::iterator itr = enchants.begin(); itr != enchants.end(); ++itr)
{
if(sscanf((*itr).c_str(), "%u,%u,%u", &enchant_id, &time_left, &enchslot) == 3)
{
entry = sEnchantStore.LookupEntry(enchant_id);
if(entry && entry->Id == enchant_id)
AddEnchantment(entry, time_left, (enchslot != 2) ? false : true, false);
else
{
EnchantEntry *pEnchant = new EnchantEntry;
memset(pEnchant,0,sizeof(EnchantEntry));
pEnchant->Id = enchant_id;
if(enchslot != 2)
AddEnchantment(pEnchant,0,true, false);
else
AddEnchantment(pEnchant,0,false,false);
}
}
}
ApplyRandomProperties();
}
void Item::ApplyRandomProperties()
{
// apply random properties
if(m_uint32Values[ITEM_FIELD_RANDOM_PROPERTIES_ID] != 0)
{
RandomProps *rp= sRandomPropStore.LookupEntry(m_uint32Values[ITEM_FIELD_RANDOM_PROPERTIES_ID]);
if(rp)
{
for (int k=0;k<3;k++)
{
if (rp->spells[k] != 0)
{
EnchantEntry * ee = sEnchantStore.LookupEntry(rp->spells[k]);
if(HasEnchantment(ee->Id) < 0) AddEnchantment(ee, 0, false, false, true);
}
}
}
}
}
void Item::SaveToDB(int8 containerslot, int8 slot, bool firstsave)
{
std::stringstream ss;
if(firstsave || _dbguid == 0)
ss << "INSERT INTO playeritems VALUES(";
else
ss << "REPLACE INTO playeritems VALUES(";
_dbguid = m_uint32Values[OBJECT_FIELD_ENTRY];
ss << m_uint32Values[ITEM_FIELD_OWNER] << ",";
ss << m_uint32Values[OBJECT_FIELD_GUID] << ",";
ss << m_uint32Values[OBJECT_FIELD_ENTRY] << ",";
ss << GetUInt32Value(ITEM_FIELD_CREATOR) << ",";
ss << GetUInt32Value(ITEM_FIELD_STACK_COUNT) << ",";
ss << GetChargesLeft() << ",";
ss << GetUInt32Value(ITEM_FIELD_FLAGS) << ",";
ss << GetUInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID) << ",";
ss << GetUInt32Value(ITEM_FIELD_ITEM_TEXT_ID) << ",";
ss << GetUInt32Value(ITEM_FIELD_DURABILITY) << ",";
ss << static_cast<int>(containerslot) << ",";
ss << static_cast<int>(slot) << ",'";
// Pack together enchantment fields
EnchantmentMap::iterator itr = Enchantments.begin();
for(; itr != Enchantments.end(); ++itr)
{
uint32 elapsed_duration = time(NULL) - itr->second.ApplyTime;
int32 remaining_duration = itr->second.Duration - elapsed_duration;
if(remaining_duration < 0) remaining_duration = 0;
if(!itr->second.RemoveAtLogout &&
(remaining_duration > 5 && itr->second.Slot != 2) || itr->second.Slot == 2) // no point saving stuff with < 5 seconds... unless is perm enchant
{
ss << itr->second.Enchantment->Id << ",";
ss << remaining_duration << ",";
ss << itr->second.Slot << ";";
}
}
ss << "')";
if(firstsave)
sDatabase.WaitExecute(ss.str().c_str());
else
sDatabase.Execute( ss.str().c_str());
}
void Item::DeleteFromDB()
{
sDatabase.WaitExecute("DELETE FROM playeritems WHERE guid = %u", GetGUIDLow());
}
uint32 GetSkillByProto(ItemPrototype *proto)
{
const static uint32 arm_skills[7]={0,SKILL_CLOTH,SKILL_LEATHER,SKILL_MAIL,SKILL_PLATE_MAIL,0,SKILL_SHIELD};
const static uint32 weap_skills[21]={SKILL_AXES,SKILL_2H_AXES,SKILL_BOWS,SKILL_GUNS,SKILL_MACES,SKILL_2H_MACES,
SKILL_POLEARMS,SKILL_SWORDS,SKILL_2H_SWORDS,0,SKILL_STAVES,0,0,SKILL_FIST_WEAPONS,0,//<-13
SKILL_DAGGERS,SKILL_THROWN,SKILL_SPEARS,SKILL_CROSSBOWS,SKILL_WANDS,SKILL_FISHING};
//14--used by professions
if(proto->Class == 4 && proto->SubClass < 7)
{
return arm_skills[proto->SubClass];
} else if(proto->Class == 2 && proto->SubClass < 21)
{
return weap_skills[proto->SubClass];
}
return 0;
}
//This map is used for profess.
//Prof packe strcut: {SMSG_SET_PROFICIENCY,(uint8)item_class,(uint32)1<<item_subclass}
//ie: for fishing (it's class=2--weapon, subclass ==20 -- fishing rod) permissive packet
// will have structure 0x2,524288
//this table is needed to get class/subclass by skill, valid classes are 2 and 4
const ItemProf * GetProficiencyBySkill(uint32 skill)
{
const static ItemProf prof[22]={
{4,2},{4,4},{4,8},{4,16},{4,64},
{2,1},{2,2},{2,4},{2,8},{2,16},{2,32},{2,64},{2,128},{2,256},{2,1024},{2,8192},{2,32768},{2,65536},{2,131072},
{2,262144},{2,524288},{2,1048576}};
switch(skill)
{
case SKILL_CLOTH:
return &prof[0];
case SKILL_LEATHER:
return &prof[1];
case SKILL_MAIL:
return &prof[2];
case SKILL_PLATE_MAIL:
return &prof[3];
case SKILL_SHIELD:
return &prof[4];
case SKILL_AXES:
return &prof[5];
case SKILL_2H_AXES:
return &prof[6];
case SKILL_BOWS:
return &prof[7];
case SKILL_GUNS:
return &prof[8];
case SKILL_MACES:
return &prof[9];
case SKILL_2H_MACES:
return &prof[10];
case SKILL_POLEARMS:
return &prof[11];
case SKILL_SWORDS:
return &prof[12];
case SKILL_2H_SWORDS:
return &prof[13];
case SKILL_STAVES:
return &prof[14];
case SKILL_FIST_WEAPONS:
return &prof[15];
case SKILL_DAGGERS:
return &prof[16];
case SKILL_THROWN:
return &prof[17];
case SKILL_SPEARS:
return &prof[18];
case SKILL_CROSSBOWS:
return &prof[19];
case SKILL_WANDS:
return &prof[20];
case SKILL_FISHING:
return &prof[21];
default:
return NULL;
}
}
uint32 GetSellPriceForItem(ItemPrototype *proto, uint32 count)
{
int32 cost;
switch(proto->Class)
{
case ITEM_CLASS_PROJECTILE: // as far as i can tell these can't be sold at all
{
cost = ( proto->SellPrice * ((count < 1) ? 1 : count) ) / proto->MaxCount;
}break;
case ITEM_CLASS_CONSUMABLE: // same as default, but leaving it like that in case
// someone can correct me - Doron
{
cost = ( proto->SellPrice * ((count < 1) ? 1 : count) );
}break;
default:
{
cost = ( proto->SellPrice * ((count < 1) ? 1 : count) );
}break;
}
return cost;
}
uint32 GetBuyPriceForItem(ItemPrototype *proto, uint32 count, uint32 vendorcount)
{
int32 cost;
switch(proto->Class)
{
case ITEM_CLASS_PROJECTILE:
case ITEM_CLASS_CONSUMABLE:
{
cost = ( proto->BuyPrice * ((count < 1) ? 1 : count) ) / ((vendorcount < 1) ? proto->MaxCount : vendorcount);
}break;
default:
{
cost = ( proto->BuyPrice * ((count < 1) ? 1 : count));
}break;
}
return cost;
}
uint32 GetSellPriceForItem(uint32 itemid, uint32 count)
{
if(ItemPrototype *proto = objmgr.GetItemPrototype(itemid))
return GetSellPriceForItem(proto, count);
else
return 1;
}
uint32 GetBuyPriceForItem(uint32 itemid, uint32 count, uint32 vendorcount)
{
if(ItemPrototype *proto = objmgr.GetItemPrototype(itemid))
return GetBuyPriceForItem(proto, count, vendorcount);
else
return 1;
}
void Item::AddToWorld()
{
// we may need to do some special shit here
if(m_inWorld)
{
printf("Warning: Item was tried to be added to world when this had already been done.\n");
return;
}
Object::AddToWorld();
}
void Item::RemoveFromWorld()
{
// if we have an owner->send destroy
if(m_owner)
{
DestroyForPlayer(m_owner);
}
if(!m_inWorld)
{
printf("Warning: Item was tried to be removed from world when this had already been done.\n");
return;
}
Object::RemoveFromWorld();
}
void Item::SetOwner(Player *owner)
{
if(owner)
SetUInt64Value(ITEM_FIELD_OWNER,((Object*)owner)->GetGUID());
else SetUInt64Value(ITEM_FIELD_OWNER,0);
m_owner = owner;
}
int32 Item::AddEnchantment(EnchantEntry * Enchantment, uint32 Duration, bool Perm /* = false */, bool apply /* = true */, bool RemoveAtLogout /* = false */)
{
int32 Slot;
if(Perm)
{
// put slot 2 as permanent
Slot = 2;
RemoveEnchantment(2);
}
else
{
if(Enchantment->EnchantGroups > 1) // replaceable temp enchants
{
Slot = 1;
RemoveEnchantment(1);
}
else
{
Slot = FindFreeEnchantSlot(Enchantment);
// reach max of temp enchants
if(Slot < 0) return Slot;
}
}
// Create the enchantment struct.
EnchantmentInstance Instance;
Instance.ApplyTime = (Enchantment->type ? time(NULL) : 0);
Instance.BonusApplied = false;
Instance.Slot = Slot;
Instance.Enchantment = Enchantment;
Instance.AddAmount = 0;
Instance.Duration = Duration;
Instance.RemoveAtLogout = RemoveAtLogout;
// Set the enchantment in the item fields.
uint32 EnchantBase = Slot * 3 + ITEM_FIELD_ENCHANTMENT;
SetUInt32Value(EnchantBase + 0, Enchantment->Id);
SetUInt32Value(EnchantBase + 1, Instance.ApplyTime);
SetUInt32Value(EnchantBase + 2, 0); // charges
// Add it to our map.
Enchantments[Slot] = Instance;
if(m_owner == 0) return Slot;
// Add the removal event.
if(Duration)
{
sEventMgr.AddEvent(this, &Item::RemoveEnchantment, uint32(Slot),
EVENT_REMOVE_ENCHANTMENT1 + Slot, Duration * 1000, 1);
}
// No need to send the log packet, if the owner isn't in world (we're still loading)
if(!m_owner->IsInWorld())
return Slot;
/*
{SERVER} Packet: (0x01D7) SMSG_ENCHANTMENTLOG Size = 25
|------------------------------------------------|----------------|
|00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F |0123456789ABCDEF|
|------------------------------------------------|----------------|
|51 46 35 00 00 00 00 00 51 46 35 00 00 00 00 00 |QF5.....QF5.....|
|9F 4A 00 00 80 06 00 00 00 |.J....... |
-------------------------------------------------------------------
uint64 SourceGuid
uint64 TargetGuid
uint32 ItemEntryId
uint32 EnchantmentId
uint8 Unk
*/
if(apply)
{
WorldPacket EnchantLog(SMSG_ENCHANTMENTLOG, 25);
EnchantLog << m_owner->GetGUID();
EnchantLog << m_owner->GetGUID();
EnchantLog << m_uint32Values[OBJECT_FIELD_ENTRY];
EnchantLog << Enchantment->Id;
EnchantLog << uint8(0);
m_owner->GetSession()->SendPacket(&EnchantLog);
ApplyEnchantmentBonus(Slot, APPLY);
}
return Slot;
}
void Item::RemoveEnchantment(uint32 EnchantmentSlot)
{
// Make sure we actually exist.
EnchantmentMap::iterator itr = Enchantments.find(EnchantmentSlot);
if(itr == Enchantments.end())
return;
uint32 Slot = itr->first;
if(itr->second.BonusApplied)
ApplyEnchantmentBonus(EnchantmentSlot, REMOVE);
// Unset the item fields.
uint32 EnchantBase = Slot * 3 + ITEM_FIELD_ENCHANTMENT;
SetUInt32Value(EnchantBase + 0, 0);
SetUInt32Value(EnchantBase + 1, 0);
SetUInt32Value(EnchantBase + 2, 0);
// Remove the enchantment event for removal.
event_RemoveEvents(EVENT_REMOVE_ENCHANTMENT1 + Slot);
// Remove the enchantment instance.
Enchantments.erase(itr);
}
void Item::ApplyEnchantmentBonus(uint32 Slot, bool Apply)
{
EnchantmentMap::iterator itr = Enchantments.find(Slot);
if(itr == Enchantments.end())
return;
EnchantEntry * Entry = itr->second.Enchantment;
if(itr->second.BonusApplied == Apply)
return;
itr->second.BonusApplied = Apply;
if(Apply)
{
// Send the enchantment time update packet.
SendEnchantTimeUpdate(itr->second.Slot, itr->second.Duration);
}
// Apply the visual on the player.
uint32 ItemSlot = m_owner->GetItemInterface()->GetInventorySlotByGuid(GetGUID()) * 16;
uint32 VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + ItemSlot;
m_owner->SetUInt32Value(VisibleBase + 1 + Slot, Apply ? Entry->Id : 0);
// Depending on the enchantment type, take the appropriate course of action.
switch(Entry->type)
{
case 1: // Trigger spell on melee attack.
{
if(Apply)
{
// Create a proc trigger spell
ProcTriggerSpell TS;
TS.caster = m_owner->GetGUID();
TS.origId = 0;
TS.procFlags = PROC_ON_MELEE_ATTACK;
TS.procCharges = 0;
TS.procChance = Entry->min ? Entry->min : 101;
for(uint32 Index = 0; Index < 2; ++Index)
{
if(Entry->spell[Index] != 0)
{
TS.spellId = Entry->spell[Index];
m_owner->m_procSpells.push_back(TS);
}
}
}
else
{
// Remove the proctriggerspell
uint32 SpellId;
list<struct ProcTriggerSpell>::iterator itr, itr2;
for(itr = m_owner->m_procSpells.begin();
itr != m_owner->m_procSpells.end();)
{
SpellId = itr->spellId;
itr2 = itr++;
if(SpellId == Entry->spell[0] ||
SpellId == Entry->spell[1])
{
m_owner->m_procSpells.erase(itr2);
}
}
}
}break;
case 2: // Mod damage done.
{
int32 AddAmount;
if(Apply)
{
AddAmount = Entry->min;
if(Entry->max > AddAmount)
{
uint32 Range = Entry->max - Entry->min;
AddAmount += sRand.randInt(Range);
}
itr->second.AddAmount = AddAmount;
}
else
{
AddAmount = -itr->second.AddAmount;
}
m_owner->ModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, AddAmount);
m_owner->CalcDamage();
}break;
case 3: // Cast spell (usually means apply aura)
{
if(Apply)
{
SpellCastTargets targets(m_owner->GetGUID());
SpellEntry * sp;
Spell * spell;
for(uint32 Index = 0; Index < 2; ++Index)
{
if(Entry->spell[Index] != 0)
{
sp = sSpellStore.LookupEntry(Entry->spell[Index]);
if(!sp) continue;
spell = new Spell(m_owner, sp, true, 0);
spell->prepare(&targets);
}
}
}
else
{
for(uint32 Index = 0; Index < 2; ++Index)
{
if(Entry->spell[Index] != 0)
{
m_owner->RemoveAura(Entry->spell[Index]);
}
}
}
}break;
case 4: // Modify physical resistance
{
int32 AddAmount;
if(Apply)
{
AddAmount = Entry->min;
if(Entry->max > AddAmount)
{
uint32 Range = Entry->max - Entry->min;
AddAmount += sRand.randInt(Range);
}
itr->second.AddAmount = AddAmount;
}
else
{
AddAmount = -itr->second.AddAmount;
}
m_owner->FlatResistanceModifierPos[0] += AddAmount;
m_owner->CalcResistance(0);
}break;
case 5: // Gems (Socketing)
{
// todo
}break;
case 6: // Rockbiter weapon (increase damage per second... how the hell do you calc that)
{
int32 AddAmount;
if(Apply)
{
AddAmount = Entry->min;
if(Entry->max > AddAmount)
{
uint32 Range = Entry->max - Entry->min;
AddAmount += sRand.randInt(Range);
}
itr->second.AddAmount = AddAmount;
}
else
{
AddAmount = -itr->second.AddAmount;
}
m_owner->ModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, AddAmount);
m_owner->CalcDamage();
}break;
default:
{
sLog.outError("Unknown enchantment type: %u (%u)", Entry->type, Entry->Id);
}break;
}
}
void Item::ApplyEnchantmentBonuses()
{
EnchantmentMap::iterator itr;
for(itr = Enchantments.begin(); itr != Enchantments.end(); ++itr)
{
ApplyEnchantmentBonus(itr->first, APPLY);
}
}
void Item::RemoveEnchantmentBonuses()
{
EnchantmentMap::iterator itr;
for(itr = Enchantments.begin(); itr != Enchantments.end(); ++itr)
{
ApplyEnchantmentBonus(itr->first, REMOVE);
}
}
void Item::EventRemoveEnchantment(uint32 Slot)
{
// Remove the enchantment.
RemoveEnchantment(Slot);
}
int32 Item::FindFreeEnchantSlot(EnchantEntry * Enchantment)
{
if(!Enchantment) return -1;
uint32 Slot = Enchantment->type ? 3 : 0;
for(uint32 Index = ITEM_FIELD_ENCHANTMENT_09; Index < ITEM_FIELD_ENCHANTMENT_32; Index += 3)
{
if(m_uint32Values[Index] == 0) return Slot;
++Slot;
}
return -1;
}
int32 Item::HasEnchantment(uint32 Id)
{
uint32 Slot = 0;
for(uint32 Index = ITEM_FIELD_ENCHANTMENT; Index < ITEM_FIELD_ENCHANTMENT_32; Index += 3)
{
if(m_uint32Values[Index] == Id) return Slot;
++Slot;
}
return -1;
}
void Item::ModifyEnchantmentTime(uint32 Slot, uint32 Duration)
{
EnchantmentMap::iterator itr = Enchantments.find(Slot);
if(itr == Enchantments.end())
return;
// Reset the apply time.
itr->second.ApplyTime = time(NULL);
itr->second.Duration = Duration;
// Change the event timer.
event_ModifyTimeAndTimeLeft(EVENT_REMOVE_ENCHANTMENT1 + Slot, Duration * 1000);
// Send update packet
SendEnchantTimeUpdate(itr->second.Slot, Duration);
}
void Item::SendEnchantTimeUpdate(uint32 Slot, uint32 Duration)
{
/*
{SERVER} Packet: (0x01EB) SMSG_ITEM_ENCHANT_TIME_UPDATE Size = 24
|------------------------------------------------|----------------|
|00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F |0123456789ABCDEF|
|------------------------------------------------|----------------|
|69 32 F0 35 00 00 00 40 01 00 00 00 08 07 00 00 |i2.5...@........|
|51 46 35 00 00 00 00 00 |QF5..... |
-------------------------------------------------------------------
uint64 item_guid
uint32 count?
uint32 time_in_seconds
uint64 player_guid
*/
WorldPacket *data = new WorldPacket(SMSG_ITEM_ENCHANT_TIME_UPDATE, 24);
*data << GetGUID();
*data << Slot;
*data << Duration;
*data << m_owner->GetGUID();
m_owner->delayedPackets.add(data);
}
void Item::RemoveAllEnchantments(bool OnlyTemporary)
{
EnchantmentMap::iterator itr, it2;
for(itr = Enchantments.begin(); itr != Enchantments.end();)
{
it2 = itr++;
if(OnlyTemporary && it2->second.Duration == 0)
continue;
RemoveEnchantment(it2->first);
}
}
void Item::RemoveRelatedEnchants(EnchantEntry * newEnchant)
{
EnchantmentMap::iterator itr,itr2;
for(itr = Enchantments.begin(); itr != Enchantments.end();)
{
itr2 = itr++;
if(itr2->second.Enchantment->Id == newEnchant->Id ||
(itr2->second.Enchantment->EnchantGroups > 1 && newEnchant->EnchantGroups > 1 ))
{
RemoveEnchantment(itr2->first);
}
}
}
| [
"[email protected]"
] | [
[
[
1,
820
]
]
] |
710d76cfa9a6b3acc1a40fd78d078b20adf856f8 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/tools/wflod.cc | f374927d5186c1b41094b5583463aadbb09f0718 | [] | no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | cc | //--------------------------------------------------------------------
// wflod.cc
//
// Triangle-Reduzierer. Der hereinkommende Wavefront-File muss
// bereits trianguliert worden sein!
//
// (C) 1998 A.Weissflog
//--------------------------------------------------------------------
#include "tools/wfobject.h"
#include "tools/wftools.h"
#include "list.h"
#include "vector.h"
#include "progmesh.h"
List<tridata> tri; // global list of triangles
List<Vector> vert; // global list of vertices
//--------------------------------------------------------------------
// reduce()
// 04-Jan-99 floh created
// 06-Jan-99 floh + uebernimmt jetzt Textur-Koordinaten
// in die Triangles
// 07-Jan-99 floh + komplett neu
// 25-Oct-00 floh + rewritten to wfObject
//--------------------------------------------------------------------
void reduce(wfObject& src, wfObject& dst, int face_num)
{
fprintf(stderr, "translating vertex and triangle data...\n");
// add vertices
nArray<wfCoord>::iterator cur_v;
for (cur_v=src.v_array.Begin(); cur_v!=src.v_array.End(); cur_v++) {
vert.Add(Vector(cur_v->v.x,cur_v->v.y,cur_v->v.z));
}
// add triangles
nArray<wfFace>::iterator cur_f;
for (cur_f=src.f_array.Begin(); cur_f!=src.f_array.End(); cur_f++) {
wfPoint p[3];
p[0] = cur_f->points.At(0);
p[1] = cur_f->points.At(1);
p[2] = cur_f->points.At(2);
tridata td;
int i;
for (i=0; i<3; i++) {
td.v[i] = p[i].v_index;
td.vt[i] = p[i].vt_index; // may be -1
}
tri.Add(td);
}
fprintf(stderr, "generating reduced mesh...\n");
GenMesh(vert,tri,src,dst,face_num);
}
//--------------------------------------------------------------------
int main(int argc, char *argv[])
{
List<tridata> dummy0;
List<Vector> dummy2;
bool help;
long retval = 0;
int abs_v, rel_v, num_v;
fprintf(stderr,"-> wflod\n");
// get args
help = wf_getboolarg(argc,argv,"-help");
abs_v = wf_getintarg(argc,argv,"-abs",0);
rel_v = wf_getintarg(argc,argv,"-rel",100);
// show help?
if (help) {
fprintf(stderr,"wflod [-help] [-rel] [-abs]\n"
"Based on lod demo by Stan Melax ([email protected])\n"
"Triangle reduction tool.\n"
"-help -- show help and exit\n"
"-rel -- reduce to n percent of original vertice number\n"
"-abs -- reduce to abs number of vertices\n");
return 0;
}
wfObject src;
wfObject dst;
FILE *in, *out;
if (!wf_openfiles(argc, argv, in, out)) {
fprintf(stderr,"file open failed!\n");
retval = 10; goto ende;
}
// load source object
fprintf(stderr,"loading...\n");
if (!src.load(in)) {
fprintf(stderr,"Load failed!\n");
retval = 10; goto ende;
}
if (abs_v > 0) {
num_v = src.f_array.Size();
if (abs_v < num_v) num_v = abs_v;
} else {
if (rel_v < 0) rel_v = 0;
else if (rel_v > 100) rel_v = 100;
num_v = (src.f_array.Size() * rel_v) / 100;
}
fprintf(stderr, "before: %d vertices, %d faces\n", src.v_array.Size(), src.f_array.Size());
reduce(src,dst,num_v);
fprintf(stderr, "after: %d vertices, %d faces\n", dst.v_array.Size(), dst.f_array.Size());
// write the result
fprintf(stderr,"saving...\n");
dst.save(out);
wf_closefiles(in, out);
ende:
fprintf(stderr,"<- wflod\n");
return retval;
}
//--------------------------------------------------------------------
// EOF
//--------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] | [
[
[
1,
126
]
]
] |
7804b534a132f3c65505a6b9e9704a7e0a73aa3c | 2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc | /engine/component/contactcallbackcomponent.h | fe68a54db52baced3385e55eb1dcfd057f560b1d | [] | no_license | tstivers/eXistenZ | eb2da9d6d58926b99495319080e13f780862fca0 | 2f5df51fb71d44c3e2689929c9249d10223f8d56 | refs/heads/master | 2021-09-02T22:50:36.733142 | 2010-11-16T06:47:24 | 2018-01-04T00:51:21 | 116,196,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | h | #pragma once
#include "component/component.h"
#include "entity/interfaces.h"
namespace component
{
struct ContactCallbackEventArgs
{
weak_reference<Component> otherComponent;
D3DXVECTOR3 contactForce;
ContactCallbackEventArgs(Component* otherComponent, D3DXVECTOR3& contactForce)
: otherComponent(otherComponent), contactForce(contactForce)
{}
};
typedef function<void(Component*, const ContactCallbackEventArgs&)> ContactCallbackFunction;
struct ContactCallbackComponentDesc : public ComponentDesc
{
ContactCallbackFunction callback;
ContactCallbackComponentDesc()
: callback(NULL)
{}
};
class ContactCallbackComponent : public Component
{
public:
// typedefs
typedef ContactCallbackComponentDesc desc_type;
typedef ContactCallbackComponent component_type;
// constructor/destructor
ContactCallbackComponent(entity::Entity* entity, const string& name, const desc_type& desc);
~ContactCallbackComponent();
// Component overloads
int getType() { return CONTACTCALLBACKCOMPONENT; }
void acquire();
void release();
// methods
void onContact(Component* sender, const ContactCallbackEventArgs& args);
// properties
ContactCallbackFunction getCallback() { return m_callback; }
void setCallback(ContactCallbackFunction callback) { m_callback = callback; }
// script class
static ScriptedObject::ScriptClass m_scriptClass;
protected:
// methods
// ScriptedObject overrides
JSObject* createScriptObject();
void destroyScriptObject();
// members
ContactCallbackFunction m_callback;
bool m_started;
};
}
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
8bac79f96e2f9241328385ebd9093a4bec5b5876 | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/uslsext/USViewport.cpp | b1a36300f3f6f2b9a3481a3bec80c3d7c7f780c3 | [] | no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,785 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslsext/USMathConsts.h>
#include <uslsext/USGfxDevice.h>
#include <uslsext/USViewport.h>
//================================================================//
// USViewport
//================================================================//
//----------------------------------------------------------------//
float USViewport::GetAspect () const {
return this->Width () / this->Height ();
}
//----------------------------------------------------------------//
float USViewport::GetInvAspect () const {
return this->Height () / this->Width ();
}
//----------------------------------------------------------------//
USRect USViewport::GetRect () const {
return *this;
}
//----------------------------------------------------------------//
USVec2D USViewport::GetScale () const {
USVec2D scale ( 1.0f, 1.0f );
if ( this->mXScale && this->mYScale ) {
scale.mX = this->Width () / this->mScale.mX;
scale.mY = this->Height () / this->mScale.mY;
}
else {
float result = 1.0f;
if ( this->mXScale ) {
result = (( float )this->Width ()) / this->mScale.mX;
}
if ( this->mYScale ) {
result = (( float )this->Height ()) / this->mScale.mY;
}
scale.mX = result;
scale.mY = result;
}
return scale;
}
//----------------------------------------------------------------//
USVec2D USViewport::GetUnits () const {
USVec2D scale ( 1.0f, 1.0f );
if ( this->mXScale && this->mYScale ) {
scale.mX = this->mScale.mX;
scale.mY = this->mScale.mY;
}
else {
float result = 1.0f;
if ( this->mXScale ) {
result = this->mScale.mX;
}
if ( this->mYScale ) {
result = this->mScale.mY;
}
scale.mX = result;
scale.mY = result;
}
return scale;
}
//----------------------------------------------------------------//
void USViewport::SetOffset ( float xOffset, float yOffset ) {
this->mOffset.Init ( xOffset, yOffset );
}
//----------------------------------------------------------------//
void USViewport::SetRotation ( float degrees ) {
this->mRotation = degrees;
}
//----------------------------------------------------------------//
void USViewport::SetScale ( float xScale, float yScale ) {
this->mXScale = ( xScale != 0.0f );
this->mScale.mX = xScale;
this->mYScale = ( yScale != 0.0f );
this->mScale.mY = yScale;
}
//----------------------------------------------------------------//
USViewport::USViewport () :
mXScale ( true ),
mYScale ( true ),
mScale ( 1.0f, 1.0f ),
mOffset ( 0.0f, 0.0f ),
mRotation ( 0.0f ) {
this->Init ( 0.0f, 0.0f, 1.0f, 1.0f );
}
| [
"[email protected]",
"Patrick@agile.(none)"
] | [
[
[
1,
13
],
[
15,
18
],
[
20,
23
],
[
25,
29
],
[
31,
56
],
[
85,
116
]
],
[
[
14,
14
],
[
19,
19
],
[
24,
24
],
[
30,
30
],
[
57,
84
]
]
] |
06f7e9a467f2fee652cb0a82522926ad7f3bb8d6 | 1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50 | /look_for_face/look_for_face/detector.cpp | 0c2f8ba539eaf4cb81efe5ee708477c4a3e37cb6 | [] | no_license | llvllrbreeze/alcorapp | dfe2551f36d346d73d998f59d602c5de46ef60f7 | 3ad24edd52c19f0896228f55539aa8bbbb011aac | refs/heads/master | 2021-01-10T07:36:01.058011 | 2008-12-16T12:51:50 | 2008-12-16T12:51:50 | 47,865,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,228 | cpp | #include "detector.h"
FaceDetector::FaceDetector()
{
storage_ = 0;
cascade_ = 0;
}
FaceDetector::~FaceDetector()
{
}
bool FaceDetector::init(const char * fileName)
{
storage_ = cvCreateMemStorage(0);
cascade_ = (CvHaarClassifierCascade*)cvLoad( fileName, 0, 0, 0 );
if (!cascade_)
{
fprintf( stderr, "ERROR: Could not load classifier cascade\n" );
return false;
}
return true;
}
bool FaceDetector::detect( IplImage* img, int * center_x, int * center_y, int * width, int * height, double scale, CvSize minFaceSize )
{
IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
/*IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
cvRound (img->height/scale)),
8, 1 );*/
cvCvtColor( img, gray, CV_BGR2GRAY );
/*cvResize( gray, small_img, CV_INTER_LINEAR );
cvEqualizeHist( small_img, small_img );*/
cvClearMemStorage( storage_ );
// double t = (double)cvGetTickCount();
//CvSeq* faces = cvHaarDetectObjects( small_img, cascade_, storage_,
// 1.1, 3, /*CV_HAAR_DO_CANNY_PRUNING*/ CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH ,
// cvSize(60,60) );
CvSeq* faces = cvHaarDetectObjects( gray, cascade_, storage_,
1.1, 60, /*CV_HAAR_DO_CANNY_PRUNING*/ CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH ,
minFaceSize );
// t = (double)cvGetTickCount() - t;
//printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
if(faces->total > 0)
{
resultRect_ = ( CvRect* )cvGetSeqElem( faces, 0 );
/**center_x = resultRect_->x*scale;
*center_y = resultRect_->y*scale;
*width = resultRect_->width*scale;
*height = resultRect_->height*scale;*/
*center_x = resultRect_->x;
*center_y = resultRect_->y;
*width = resultRect_->width;
*height = resultRect_->height;
cvReleaseImage( &gray );
//cvReleaseImage( &small_img );
return true;
}
cvReleaseImage( &gray );
// cvReleaseImage( &small_img );
return false;
} | [
"matia.pizzoli@1ffd000b-a628-0410-9a29-793f135cad17"
] | [
[
[
1,
66
]
]
] |
ef445db4f7a69962513b0f8ede637a50c12e03db | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /SecurityClient/dongle.cpp | 4f688b703afff3866f03f2109db6bf92053d662f | [] | no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,064 | cpp | //--------------------------------------------------------------------------------
//
// Copyright (c) 2000 MarkCare Solutions
//
// Programming by Rich Schonthal
//
//--------------------------------------------------------------------------------
#include "stdafx.h"
#include "dongle.h"
// if we're building a security client that does not support dongle backup...
#ifdef _SECCON_NODONGLE
//--------------------------------------------------------------------------------
bool CDongle::Connect() { return true; }
//--------------------------------------------------------------------------------
bool CDongle::GetDongleMemory(BYTE[128]) { return false; }
//--------------------------------------------------------------------------------
bool CDongle::SetDongleMemory(BYTE[32]) { return false; }
#else
#include <hlapi_c.h>
//#pragma comment(lib, "hlw32_mc.lib")
#ifdef _DEBUG
bool CDongle::m_bDoNothing =
#ifdef _CHECK_DONGLE
false;
#else
false;
#endif
#endif
CMutex CDongle::m_mutex;
BYTE pVerKey[9] = {0x9A,0x7D,0x8E,0x75,0x4F,0xEF,0xC4,0x39, 0x00};
BYTE pRefKey[9] = {'M', 'O', 'O', 'N', 'A', 'C', 'H', 'I', 0};
// maybe hackers will get confused and think its already been cracked!! : )
//--------------------------------------------------------------------------------
WORD CDongle::GetMagicNumber()
{// 0x612c or 0x6122
return 0x612c;
}
//--------------------------------------------------------------------------------
BYTE* CDongle::GetRefKey()
{
return pRefKey;
}
//--------------------------------------------------------------------------------
BYTE* CDongle::GetVersionKey()
{
return pVerKey;
}
//--------------------------------------------------------------------------------
bool CDongle::Connect()
{
#ifdef _DEBUG
if(m_bDoNothing)
return true;
#endif
CSingleLock lock(&m_mutex);
if(! lock.Lock(3000))
return false;
bool bOk = false;
switch(HL_LOGIN(GetMagicNumber(), LOCAL_DEVICE, GetRefKey(), GetVersionKey()))
{
case NETWORK_ERROR:
TRACE("NE\n");
break;
case NO_DONGLE:
TRACE("ND\n");
HL_LOGOUT();
return false;
case VERSION_MISMATCH:
TRACE("VM\n");
break;
case INVALID_ENV:
TRACE("IE\n");
break;
case CANNOT_OPEN_DRIVER:
TRACE("COD\n");
break;
case DYNALINK_FAILED:
TRACE("DF\n");
break;
case (Word)TOO_MANY_USERS:
TRACE("TMU\n");
break;
case INVALID_LIC:
TRACE("IL\n");
break;
case NO_LICENSE:
TRACE("NL\n");
break;
default:
bOk = true;
break;
}
HL_LOGOUT();
return bOk;
}
//--------------------------------------------------------------------------------
bool CDongle::GetDongleMemory(BYTE pMem[128])
{
#ifdef _DEBUG
if(m_bDoNothing)
return true;
#endif
CSingleLock lock(&m_mutex);
if(! lock.Lock(3000))
return false;
bool bOk = false;
switch(HL_LOGIN(GetMagicNumber(), LOCAL_DEVICE, GetRefKey(), GetVersionKey()))
{
case NETWORK_ERROR:
TRACE("NE\n");
break;
case NO_DONGLE:
TRACE("ND\n");
HL_LOGOUT();
return false;
case VERSION_MISMATCH:
TRACE("VM\n");
break;
case INVALID_ENV:
TRACE("IE\n");
break;
case CANNOT_OPEN_DRIVER:
TRACE("COD\n");
break;
case DYNALINK_FAILED:
TRACE("DF\n");
break;
case (Word)TOO_MANY_USERS:
TRACE("TMU\n");
break;
case INVALID_LIC:
TRACE("IL\n");
break;
case NO_LICENSE:
TRACE("NL\n");
break;
default:
bOk = true;
break;
}
if(! bOk)
{
HL_LOGOUT();
return false;
}
if(HL_READBL(pMem) != STATUS_OK)
{
HL_LOGOUT();
return false;
}
for(int i = 0; i < 64; i += 2)
{
BYTE nTemp = pMem[i];
pMem[i] = pMem[i+1];
pMem[i+1] = nTemp;
}
HL_LOGOUT();
return true;
}
//--------------------------------------------------------------------------------
bool CDongle::SetDongleMemory(BYTE pMem[32])
{
#ifdef _DEBUG
if(m_bDoNothing)
return true;
#endif
CSingleLock lock(&m_mutex);
if(! lock.Lock(3000))
return false;
bool bOk = false;
switch(HL_LOGIN(GetMagicNumber(), LOCAL_DEVICE, GetRefKey(), GetVersionKey()))
{
case NETWORK_ERROR:
TRACE("NE\n");
break;
case NO_DONGLE:
TRACE("ND\n");
HL_LOGOUT();
return false;
case VERSION_MISMATCH:
TRACE("VM\n");
break;
case INVALID_ENV:
TRACE("IE\n");
break;
case CANNOT_OPEN_DRIVER:
TRACE("COD\n");
break;
case DYNALINK_FAILED:
TRACE("DF\n");
break;
case (Word)TOO_MANY_USERS:
TRACE("TMU\n");
break;
case INVALID_LIC:
TRACE("IL\n");
break;
case NO_LICENSE:
TRACE("NL\n");
break;
default:
bOk = true;
break;
}
if(bOk)
bOk = HL_WRITEBL(pMem) == STATUS_OK;
HL_LOGOUT();
return bOk;
}
//--------------------------------------------------------------------------------
bool CDongle::IsCorrectDongleMemory()
{
return false;
}
#endif // _SECCON_NODONGLE
| [
"[email protected]"
] | [
[
[
1,
243
]
]
] |
9e1c2794820e1d4dfa476bf659322fece43094f4 | 42e90e170e2516157730d6cc881ace3a408692f2 | /src/Utils.h | dd10399c6364aefe96fa002b28156bd675b6e730 | [] | no_license | optixx/rbox | a6019bac6e7f972f357e4ef07304fbba60574c9f | 609636ee604a3b0a1a91dbc9ab9d220934e40ae5 | refs/heads/master | 2016-09-06T16:13:04.833131 | 2010-12-22T12:18:50 | 2010-12-22T12:18:50 | 1,190,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,742 | h |
/* Copyright (c) 2009, Peter Barrett
**
** Permission to use, copy, modify, and/or distribute this software for
** any purpose with or without fee is hereby granted, provided that the
** above copyright notice and this permission notice appear in all copies.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
** SOFTWARE.
*/
#define PROGMEM
#ifndef byte
typedef unsigned char byte;
typedef unsigned short ushort;
typedef unsigned long ulong;
#endif
#ifndef uchar
typedef unsigned char uchar;
#endif
#ifndef uint8_t
typedef unsigned char uint8_t;
#endif
#ifndef uint16_t
typedef unsigned short uint16_t;
#endif
#ifndef uint32_t
typedef unsigned int uint32_t;
#endif
extern "C"
{
#include <string.h>
}
#ifndef abs
#define abs(_x) ((_x) < 0 ? -(_x) : (_x))
#endif
#define pgm_read_byte(_x) (*(_x))
#define pgm_read_word(_x) (*((short*)(_x)))
#ifndef max
#define max(_a,_b) (((_a) > (_b)) ? (_a) : (_b))
#define min(_a,_b) (((_a) < (_b)) ? (_a) : (_b))
#endif
void delay(ushort ms);
void print(const char* s);
void printhex(int d);
void printdec(int d);
void assertFailed(const char* str, int len);
#define ASSERT(_x) if (!(_x)) assertFailed(0,0);
//#define ASSERT(_x) if (!(_x)) assertFailed(NULL,__LINE__);
ulong ReadPerfCounter(); // 1.5 mhz counter
void Console(const char* s);
void Console(const char* s, long n);
void ConsoleReset();
class Perf
{
ulong _t;
public:
Perf();
ulong Elapsed();
ulong ElapsedMS();
};
typedef struct
{
ushort x;
ushort y;
} TouchEvent;
byte TouchRead(TouchEvent& e);
typedef struct
{
enum EventType
{
None,
Up,
Down,
Move
};
EventType Type;
ushort X;
ushort Y;
ushort LastX;
ushort LastY;
} TouchState;
class Application
{
public:
static void Init();
static void Loop(byte phase);
static byte Command(byte len, const byte* cmd);
static void TouchDown(TouchEvent& e);
static void TouchUp(TouchEvent& e);
static void TouchMove(TouchEvent& e);
};
void printHex4(uchar h);
void printHex8(uchar h);
void printHex(int h);
void printChar(char c);
void print(long d);
void print(const char* str);
void sendFlush(); // Wait until send buffer is empty
class RingBuffer
{
byte* _buffer;
byte _len;
volatile byte _head;
volatile byte _tail;
public:
RingBuffer(byte* buffer, byte len) : _buffer(buffer),_len(len),_head(0),_tail(0){};
byte Count()
{
return _head - _tail;
}
byte Read()
{
//while (_head == _tail); // don't read empty buffers please
byte c = _buffer[_tail & (_len-1)];
_tail++;
return c;
}
void Write(byte c)
{
if ((_head - _tail) == _len)
return; // overrun
_buffer[_head & (_len-1)] = c;
_head++;
}
};
void Fatal(int count);
void CheckStack(void* t, int len);
class Smashed
{
short _sentinel;
public:
Smashed() : _sentinel(0x1234)
{
CheckStack(this,sizeof(*this));
}
~Smashed()
{
if (_sentinel != 0x1234)
Fatal(1);
}
};
| [
"[email protected]"
] | [
[
[
1,
174
]
]
] |
e9a927a6e66ec9af2ff78da4215465ea20c07b2a | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/external/gameswf/base/smart_ptr.h | 1d63a014e4ff46637c7f3c5b58821687585dd48e | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,055 | h | // smart_ptr.h -- by Thatcher Ulrich <[email protected]> 2003
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// Smart (ref-counting) pointer classes. Uses "intrusive" approach:
// the types pointed to must have add_ref() and drop_ref() methods.
// Typically this is done by inheriting from a ref_counted class,
// although the nice thing about templates is that no particular
// ref-counted class is mandated.
#ifndef SMART_PTR_H
#define SMART_PTR_H
#include "base/tu_config.h"
#include "base/utility.h"
// A smart (strong) pointer asserts that the pointed-to object will
// not go away as long as the strong pointer is valid. "Owners" of an
// object should keep strong pointers; other objects should use a
// strong pointer temporarily while they are actively using the
// object, to prevent the object from being deleted.
template<class T>
class smart_ptr
{
public:
smart_ptr(T* ptr)
:
m_ptr(ptr)
{
if (m_ptr)
{
m_ptr->add_ref();
}
}
smart_ptr() : m_ptr(NULL) {}
smart_ptr(const smart_ptr<T>& s)
:
m_ptr(s.m_ptr)
{
if (m_ptr)
{
m_ptr->add_ref();
}
}
~smart_ptr()
{
if (m_ptr)
{
m_ptr->drop_ref();
}
}
// operator bool() const { return m_ptr != NULL; }
void operator=(const smart_ptr<T>& s) { set_ref(s.m_ptr); }
void operator=(T* ptr) { set_ref(ptr); }
// void operator=(const weak_ptr<T>& w);
T* operator->() const { assert(m_ptr); return m_ptr; }
T* get_ptr() const { return m_ptr; }
bool operator==(const smart_ptr<T>& p) const { return m_ptr == p.m_ptr; }
bool operator!=(const smart_ptr<T>& p) const { return m_ptr != p.m_ptr; }
bool operator==(T* p) const { return m_ptr == p; }
bool operator!=(T* p) const { return m_ptr != p; }
// Provide work-alikes for static_cast, dynamic_cast, implicit up-cast? ("gentle_cast" a la ajb?)
private:
void set_ref(T* ptr)
{
if (ptr != m_ptr)
{
if (m_ptr)
{
m_ptr->drop_ref();
}
m_ptr = ptr;
if (m_ptr)
{
m_ptr->add_ref();
}
}
}
// friend weak_ptr;
T* m_ptr;
};
// Helper for making objects that can have weak_ptr's.
class weak_proxy
{
public:
weak_proxy()
:
m_ref_count(0),
m_alive(true)
{
}
// weak_ptr's call this to determine if their pointer is valid or not.
bool is_alive() const { return m_alive; }
// Only the actual object should call this.
void notify_object_died() { m_alive = false; }
void add_ref()
{
assert(m_ref_count >= 0);
m_ref_count++;
}
void drop_ref()
{
assert(m_ref_count > 0);
m_ref_count--;
if (m_ref_count == 0)
{
// Now we die.
delete this;
}
}
private:
// Don't use these.
weak_proxy(const weak_proxy& w) { assert(0); }
void operator=(const weak_proxy& w) { assert(0); }
int m_ref_count;
bool m_alive;
};
// A weak pointer points at an object, but the object may be deleted
// at any time, in which case the weak pointer automatically becomes
// NULL. The only way to use a weak pointer is by converting it to a
// strong pointer (i.e. for temporary use).
//
// The class pointed to must have a "weak_proxy* get_weak_proxy()" method.
//
// Usage idiom:
//
// if (smart_ptr<my_type> ptr = m_weak_ptr_to_my_type) { ... use ptr->whatever() safely in here ... }
template<class T>
class weak_ptr
{
public:
weak_ptr()
:
m_ptr(0)
{
}
weak_ptr(T* ptr)
:
m_ptr(0)
{
operator=(ptr);
}
weak_ptr(const smart_ptr<T>& ptr)
{
operator=(ptr.get_ptr());
}
// Default constructor and assignment from weak_ptr<T> are OK.
void operator=(T* ptr)
{
m_ptr = ptr;
if (m_ptr)
{
m_proxy = m_ptr->get_weak_proxy();
assert(m_proxy != NULL);
assert(m_proxy->is_alive());
}
else
{
m_proxy = NULL;
}
}
void operator=(const smart_ptr<T>& ptr) { operator=(ptr.get_ptr()); }
bool operator==(const smart_ptr<T>& ptr) const
{
check_proxy();
return m_ptr == ptr.get_ptr();
}
bool operator!=(const smart_ptr<T>& ptr) const
{
check_proxy();
return m_ptr != ptr.get_ptr();
}
bool operator==(T* ptr) const
{
check_proxy();
return m_ptr == ptr;
}
bool operator!=(T* ptr) const
{
check_proxy();
return m_ptr != ptr;
}
T* operator->() const
{
check_proxy();
assert(m_ptr);
return m_ptr;
}
T* get_ptr() const
{
check_proxy();
return m_ptr;
}
// Conversion to smart_ptr.
operator smart_ptr<T>()
{
check_proxy();
return smart_ptr<T>(m_ptr);
}
bool operator==(T* ptr) { check_proxy(); return m_ptr == ptr; }
bool operator==(const smart_ptr<T>& ptr) { check_proxy(); return m_ptr == ptr.get_ptr(); }
// for hash< weak_ptr<...>, ...>
bool operator==(const weak_ptr<T>& ptr) const
{
check_proxy();
ptr.check_proxy();
return m_ptr == ptr.m_ptr;
}
private:
void check_proxy() const
// Set m_ptr to NULL if the object died.
{
if (m_ptr)
{
assert(m_proxy != NULL);
if (m_proxy->is_alive() == false)
{
// Underlying object went away.
m_proxy = NULL;
m_ptr = NULL;
}
}
}
mutable smart_ptr<weak_proxy> m_proxy;
mutable T* m_ptr;
};
// Example ref_counted class:
//
#if 0
ref_counted
{
mutable int m_ref_count
mutable weak_proxy* m_weak_proxy;
ref_counted()
:
m_ref_count(0),
m_weak_proxy(0)
{
}
// @@ usual ref-counted stuff here for add_ref() and drop_ref()
virtual ~ref_counted()
{
assert(m_ref_count == 0);
if (m_weak_proxy)
{
m_weak_proxy->notify_object_died();
m_weak_proxy->drop_ref();
m_weak_proxy = NULL;
}
}
weak_proxy* get_weak_proxy() const
{
if (m_weak_proxy == NULL)
{
m_weak_proxy = new weak_proxy;
m_weak_proxy->add_ref();
}
}
};
#endif // 0
#endif // SMART_PTR_H
// Local Variables:
// mode: C++
// c-basic-offset: 8
// tab-width: 8
// indent-tabs-mode: t
// End:
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
317
]
]
] |
f62bd7dbd784b185d92b716f1a6f9fddf8eccb9f | 718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1 | /soft micros/Codigo/codigo portable/SD/Fat/SDFat.cpp | 5edc19f68bc0989456a438f4e22d19ea61131946 | [] | no_license | jonyMarino/microsdhacel | affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca | 66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3 | refs/heads/master | 2020-05-18T19:53:51.301695 | 2011-05-30T20:40:24 | 2011-05-30T20:40:24 | 34,532,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cpp | #include "SDFat.hpp"
SDFat::SDFat(ISPI& spi,BitIn& sdPresent){
byte errr= SD_Init(spi,sdPresent);
FAT_Read_Master_Block();
}
VUINT8 SDFat::fileOpen(const VUINT8 *pu8FileName,VUINT8 u8Function){
return FAT_FileOpen(pu8FileName,u8Function);
}
void SDFat::fileWrite(const VUINT8 *pu8DataPointer,VUINT32 u32Size){
FAT_FileWrite(pu8DataPointer,u32Size);
}
VUINT16 SDFat::fileRead(VUINT8 *pu8UserBuffer){
return FAT_FileRead(pu8UserBuffer);
}
void SDFat::fileClose(){
FAT_FileClose();
}
| [
"jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549"
] | [
[
[
1,
25
]
]
] |
29eef97932b1d94ca1f0a68360b20bbd79c5c406 | 3e94c7f668d9903556ecc3a00faac8d9aca869c9 | /MMA Semestralka/GeometryNode.cpp | 7bd469d14c90c6f5ba93cc2151e7da04f8655fdd | [] | no_license | kucerad/rpak-snowman-madness2 | 5a6ab30bf273ac71dcaccdb4b0c6215f8a7bd600 | 74409305cc6a4cc1face84e22403a2058dd447ea | refs/heads/master | 2016-09-05T19:26:00.750294 | 2010-12-20T19:53:27 | 2010-12-20T19:53:27 | 35,802,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,826 | cpp | #include "GeometryNode.h"
CGeometryNode::CGeometryNode(void) {
}
CGeometryNode::~CGeometryNode(void) {
}
void CGeometryNode::Update(void) {
// update the children
CSceneNode::Update();
}
COBJNode::COBJNode(void) {
_model_p = NULL;
}
COBJNode::~COBJNode(void) {
// clean up
if(_model_p != NULL) {
glDeleteLists(_modelDL, 1);
glmDelete(_model_p);
_model_p = NULL;
}
}
void COBJNode::Update(void) { // Draw the geometry
//printf("CAVE_INDEX %i\n", CAVE_INDEX);
// save all attributes
glPushAttrib(GL_ALL_ATTRIB_BITS);
glEnable(GL_NORMALIZE);
#if CAVEMOD
// if defined DL for this thread
if (DLarr[CAVE_INDEX]==-1){
// insert in arr
DLarr[CAVE_INDEX]=glmList(_model_p, GLM_SMOOTH | GLM_MATERIAL | GLM_TEXTURE);
}
glCallList(DLarr[CAVE_INDEX]);
//glCallList(_modelDL);
#else
// draw model
glCallList(_modelDL);
#endif
// restore attributes
glPopAttrib();
// update the children
CGeometryNode::Update();
}
bool COBJNode::Load(char* filename) {
#if CAVEMOD
/*init DLarr */
for (int i=0; i<10; i++){
DLarr[i]=-1;
}
#endif
if ( _model_p == NULL ) { // model still not loaded
// read model from file
_model_p = glmReadOBJ(filename);
if(_model_p == NULL)
return false;
// translate model to the origin and scale it
// to fit in a unit cube around the origin = "unitize"
glmUnitize(_model_p);
// precompute normal vectors
glmFacetNormals(_model_p);
glmVertexNormals(_model_p, 90.0);
#if CAVEMOD
// do not create DL... create on first update instead
//_modelDL = glmList(_model_p, GLM_SMOOTH | GLM_MATERIAL | GLM_TEXTURE);
#else
// create display list
_modelDL = glmList(_model_p, GLM_SMOOTH | GLM_MATERIAL | GLM_TEXTURE);
#endif
}
return true;
}
| [
"roman.polasek@defb9fe8-8568-b3c7-aa61-90d022bbe42a"
] | [
[
[
1,
97
]
]
] |
74811727708fc479de72dd9cb349d77c63117360 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /LemonTangram/source/XmlLib/src/DefaultDeclHandler.cpp | 32e4c68f5fb2635ca352cd223827884d02042b02 | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | cpp | /*
============================================================================
Name : DefaultDeclHandler.cpp
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CDefaultDeclHandler implementation
============================================================================
*/
#include "DefaultDeclHandler.h"
CDefaultDeclHandler::CDefaultDeclHandler()
{
// No implementation required
}
CDefaultDeclHandler::~CDefaultDeclHandler()
{
}
void CDefaultDeclHandler::ConstructL()
{
}
TSyExpatStatus CDefaultDeclHandler::NotStandalone()
{
return EStatusOk;
}
void CDefaultDeclHandler::StartDocType(const TDesC& aDocType,
const TDesC& aSystemId, const TDesC& aPublicId,
const TBool aHasInternalSubset)
{
}
void CDefaultDeclHandler::EndDocType()
{
}
void CDefaultDeclHandler::StartNamespace(const TDesC& aPrefix, const TDesC& aURI)
{
}
void CDefaultDeclHandler::EndNamespace(const TDesC& aPrefix)
{
}
void CDefaultDeclHandler::Entity(const TDesC& aName, const TBool aIsParameter,
const TDesC& aValue, const TDesC& aBase, const TDesC& aSystemId,
const TDesC& aPublicId, const TDesC& aNotation)
{
}
void CDefaultDeclHandler::SkippedEntity(const TDesC& aEntity,
const TBool aIsParameter)
{
}
void CDefaultDeclHandler::Notation(const TDesC& aNotationName,
const TDesC& aBase, const TDesC& aSystemId, const TDesC& aPublicId)
{
}
void CDefaultDeclHandler::SetParser(CExpatParserBase* aParser)
{
} | [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
68
]
]
] |
3fe13f5a52e313507f72ad304e599697784dfe47 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /MainTreeCtrl.cpp | 17997be0ac78c8445274fd31228eeb22bbe2666c | [] | no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73,955 | cpp | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * 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, 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 GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#include "stdafx.h"
#include "TeenSpirit.h"
#include "MainTreeCtrl.h"
#include "PrgAPI.h"
#include "ActionManager.h"
#include "ServicesRegistrationSrv.h"
#include "InfoDownloadManager.h"
#include "MenuManager.h"
#include "SQLManager.h"
#include "InformationProviders/InfoProviderFactory.h"
#include "LocalPictureManager.h"
#include "GuiControls/GdiPlusPicDrawer.h"
#include "GdiplusUtilities.h"
#include "UserProgressDlg.h"
#include "PointerCache.h"
#include "CollectionManager.h"
#define TIMER_AUTOUPDATE 110
#define TIMER_AUTOUPDATE_DELAY 30000
//===================================================================
//===================================================================
// Custom Nodes
//===================================================================
//===================================================================
static const int cMargin = 1;
class MainTreeDrawerHelper
{
public:
MainTreeDrawerHelper() {}
COLORREF selectedTextColor;
COLORREF expandableTextColor;
COLORREF notExpandableTextColor;
HBRUSH selectedBrush;
HBRUSH expandableBrush;
HBRUSH notExpandableBrush;
CFont* pTitleFont;
CFont* pMainFont;
DWORD dwStrFormat;
HICON hAntiStarIcon;
HICON hStarIcon;
BOOL bPicturesEnabled;
virtual void Draw(Gdiplus::Graphics& g,
CFlexTreeCtrl::DrawNodeInfo& nfo,
CMainTreeCtrl::GDIRes& res,
InfoItemTypeEnum iit,
UINT itemID,
LPCTSTR firstPart,
LPCTSTR secondPart,
INT rating,
BOOL bIsExpandable
) const
{
HDC hdc = g.GetHDC();
COLORREF textColor = bIsExpandable ? expandableTextColor : notExpandableTextColor;
if (nfo.bSelected)
textColor = selectedTextColor;
HBRUSH bkBrush = bIsExpandable ? expandableBrush : notExpandableBrush;
if (nfo.bSelected)
bkBrush = selectedBrush;
::FillRect(hdc, &CRect(nfo.fullRC.X, nfo.fullRC.Y, nfo.fullRC.GetRight(), nfo.fullRC.GetBottom()), bkBrush);
HFONT oldFont = NULL;
INT X = nfo.itemRC.X + cMargin;
if (res.bShowImages)
{
FLOAT imageScale = res.fImageScale;
if (iit == IIT_AlbumPicture)
imageScale = 1.0f;
INT imgHeight = nfo.itemRC.Height - 2 * cMargin;
INT imgWidth = INT(imgHeight * imageScale);
INT startX = X;
INT startY = nfo.itemRC.Y + cMargin;
INT endX = startX + imgWidth;
INT endY = startY + imgHeight;
//=== Image
LocalPictureManager* pLM = PRGAPI()->GetLocalPictureManager();
CRect rcImage(startX + 1, startY + 1, endX - 1, endY - 1);
BOOL bRet = pLM->DrawThumbnail(iit, itemID, hdc, rcImage);
if (!bRet)
bRet = pLM->DrawDefaultThumbnail(iit, hdc, rcImage);
X += imgWidth + cMargin;
//=== Image Frame
HBRUSH oldBr = (HBRUSH)::SelectObject(hdc, ::GetStockObject(NULL_BRUSH));
HPEN oldPen = (HPEN)::SelectObject(hdc, ::GetStockObject(BLACK_PEN));
::Rectangle(hdc, startX, startY, endX, endY);
::SelectObject(hdc, oldBr);
::SelectObject(hdc, oldPen);
}
//===Draw Rating if available
INT ratingWidth = DrawRating(hdc, rating, X, nfo.itemRC.Y + cMargin);
if (res.nLines == 1)
{
X += ratingWidth;
::SetBkMode(hdc, TRANSPARENT);
::SetTextColor(hdc, textColor);
oldFont = (HFONT)::SelectObject(hdc, pTitleFont->m_hObject);
CRect rc(X, nfo.itemRC.Y, nfo.itemRC.GetRight() - cMargin, nfo.itemRC.GetBottom());
CRect calcRC(rc);
DrawText(hdc, firstPart, -1, &calcRC, dwStrFormat | DT_CALCRECT);
DrawText(hdc, firstPart, -1, &rc, dwStrFormat);
if (secondPart != NULL)
{
oldFont = (HFONT)::SelectObject(hdc, pMainFont->m_hObject);
rc.left += calcRC.Width() + 10;
DrawText(hdc, secondPart, -1, &rc, dwStrFormat | DT_RIGHT);
}
}
else
{
INT lineHeight = nfo.itemRC.Height / res.nLines;
INT yStart = nfo.itemRC.Y + cMargin;
INT xStart = ratingWidth + X;
if (res.nLines > 2)
{
yStart += 18;//=== (Rating should be i a different line
lineHeight = (nfo.itemRC.Height - 18) / (res.nLines - 1);
xStart = X;
}
//===Draw First Line.
::SetBkMode(hdc, TRANSPARENT);
::SetTextColor(hdc, textColor);
oldFont = (HFONT)::SelectObject(hdc, pTitleFont->m_hObject);
DrawText(hdc, firstPart, -1,
&CRect(xStart,
yStart,
nfo.itemRC.GetRight(),
yStart + lineHeight),
dwStrFormat);
if (secondPart)
{
yStart += lineHeight;
::SelectObject(hdc, pMainFont->m_hObject);
DrawText(hdc,
secondPart,
-1,
&CRect(X,
yStart,
nfo.itemRC.GetRight(),
nfo.itemRC.GetBottom()),
dwStrFormat);
}
}
if (oldFont != NULL)
::SelectObject(hdc, oldFont);
g.ReleaseHDC(hdc);
}
private:
INT DrawRating(HDC hdc, INT rating, INT x, INT y) const
{
if (rating > 0 && rating < 256)
{
FLOAT fStars = Rating2Stars(rating);
INT ret = 0;
if (fStars > 0.0f && fStars <=1.0f && hAntiStarIcon)
{
DrawIconEx(hdc, x, y, hAntiStarIcon, 16, 16, 0, 0, DI_NORMAL);
ret = 16;
}
while (fStars > 1.0f && hStarIcon)
{
DrawIconEx(hdc, x + ret, y, hStarIcon, 16, 16, 0, 0, DI_NORMAL);
fStars -= 1.0f;
ret += 16;
}
return ret;
}
return 0;
}
};
class TSNode: public TreeNode
{
public:
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const = 0;
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const = 0;
virtual void Draw(Gdiplus::Graphics& g,
CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const = 0;
};
class ArtistNode: public TSNode //--------------------------------------------
{
public:
ArtistNode(TreeNode* parent/*, FullArtistRecordSP& rec*/)
{/*SetFullArtistRecord(rec);*/bExpandable = TRUE; pParent = parent;}
virtual ~ArtistNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_Artist : - ST_Artist;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return m_rec->artist.name.c_str();
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.ArtistTrackCount.val = sv.GetSmallSectionLimit();
filter.ArtistTrackCount.match = NUMM_Under;
}
else
{
filter.ArtistID.val = m_rec->artist.ID;
filter.ArtistID.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return m_rec->artist.ID == rec->artist.ID;
}
void SetFullArtistRecord(FullArtistRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
m_rec = rec;
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_ArtistPicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
LPCTSTR firstPart = m_rec->artist.name.c_str();
if (_tcscmp(firstPart, TS_UnknownString) == 0)
firstPart = pAPI->GetString(IDS_UNKNOWN);
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
if (res.nLines == 1)
{
INT curLen = 0;
if (m_rec->genre.ID != 1)
curLen = _sntprintf(bf, cMaxLen, _T("%s | %d"),
m_rec->genre.name.c_str(),
m_rec->artist.trackCount);
else
curLen = _sntprintf(bf, cMaxLen, _T("%d"),
m_rec->artist.trackCount);
secondPart = bf;
}
else
{
INT curLen = 0;
if (m_rec->genre.ID != 1)
curLen = _sntprintf(bf, 300, _T("%s: %s | %s: %d"),
pAPI->GetString(IDS_GENRE),
m_rec->genre.name.c_str(),
pAPI->GetString(IDS_TRACKS),
m_rec->artist.trackCount);
else
curLen = _sntprintf(bf, 300, _T("%s: %d"),
pAPI->GetString(IDS_TRACKS),
m_rec->artist.trackCount);
secondPart = bf;
}
}
res.pDrawer->Draw(g, nfo, res, IIT_ArtistPicture, m_rec->artist.ID, firstPart, secondPart, m_rec->artist.rating, bExpandable);
}
const FullArtistRecordSP& GetFullArtistRecord() const {return m_rec;}
private:
FullArtistRecordSP m_rec;
};
class AlbumNode: public TSNode //--------------------------------------------
{
public:
AlbumNode(TreeNode* parent)
{bExpandable = FALSE; pParent = parent;}
virtual ~AlbumNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_Album : -ST_Album;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return m_rec->album.name.c_str();
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.AlbumTrackCount.val = sv.GetSmallSectionLimit();
filter.AlbumTrackCount.match = NUMM_Under;
}
else
{
filter.AlbumID.val = m_rec->album.ID;
filter.AlbumID.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return m_rec->album.ID == rec->album.ID;
}
void SetFullAlbumRecord(FullAlbumRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
m_rec = rec;
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_AlbumPicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
//===Translate [Unknown]
LPCTSTR firstPart = m_rec->album.name.c_str();
if (_tcscmp(firstPart, TS_UnknownString) == 0)
firstPart = pAPI->GetString(IDS_UNKNOWN);
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
if (res.nLines == 1)
{
INT curLen = 0;
if (m_rec->album.year > 1800)
curLen = _sntprintf(bf, 300, _T("%d | %d"),
m_rec->album.year,
m_rec->album.trackCount);
else
curLen = _sntprintf(bf, 300, _T("%d"),
m_rec->album.trackCount);
secondPart = bf;
}
else
{
INT curLen = 0;
if (m_rec->album.year > 1800)
curLen = _sntprintf(bf, 300, _T("%s: %d | %s: %d"),
PRGAPI()->GetString(IDS_YEAR),
m_rec->album.year,
PRGAPI()->GetString(IDS_TRACKS),
m_rec->album.trackCount);
else
curLen = _sntprintf(bf, 300, _T("%s: %d"),
PRGAPI()->GetString(IDS_TRACKS),
m_rec->album.trackCount);
secondPart = bf;
}
}
res.pDrawer->Draw(g, nfo, res, IIT_AlbumPicture, m_rec->album.ID, firstPart, secondPart, m_rec->album.rating, bExpandable);
}
const FullAlbumRecordSP& GetFullAlbumRecord() const {return m_rec;}
private:
FullAlbumRecordSP m_rec;
};
class AlbumByNameNode:public AlbumNode
{
public:
AlbumByNameNode(TreeNode* parent): AlbumNode(parent) {}
virtual ~AlbumByNameNode() {}
virtual INT GetType() const {return GetFullAlbumRecord().get() != 0 ? ST_AlbumByName : -ST_AlbumByName;}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
const FullAlbumRecordSP& rec = GetFullAlbumRecord();
if (rec.get() == NULL)
{
filter.AlbumTrackCount.val = sv.GetSmallSectionLimit();
filter.AlbumTrackCount.match = NUMM_Under;
}
else
{
filter.Album.val = rec->album.name;
filter.Album.match = TXTM_Exact;
}
}
};
class GenreNode: public TSNode //--------------------------------------------
{
public:
GenreNode(TreeNode* parent/*, GenreRecordSP& rec*/)
{/*SetGenreRecord(rec);*/bExpandable = TRUE; pParent = parent;}
virtual ~GenreNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_Genre : -ST_Genre;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return m_rec->name.c_str();
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.GenreTrackCount.val = sv.GetSmallSectionLimit();
filter.GenreTrackCount.match = NUMM_Under;
}
else
{
filter.GenreID.val = m_rec->ID;
filter.GenreID.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return m_rec->ID == rec->genre.ID;
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_GenrePicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
LPCTSTR firstPart = m_rec->name.c_str();
if (_tcscmp(firstPart, TS_UnknownString) == 0)
firstPart = pAPI->GetString(IDS_UNKNOWN);
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
INT curLen = 0;
secondPart = bf;
if (res.nLines == 1)
curLen = _sntprintf(bf, 300, _T("%d"), m_rec->trackCount);
else if (res.nLines == 2)
curLen = _sntprintf(bf, 300, _T("%s: %d"), pAPI->GetString(IDS_TRACKS), m_rec->trackCount);
else
ASSERT(0);
}
res.pDrawer->Draw(g, nfo, res, IIT_GenrePicture, m_rec->ID, firstPart, secondPart, 0, bExpandable);
}
void SetGenreRecord(GenreRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
m_rec = rec;
}
const GenreRecordSP& GetGenreRecord() const {return m_rec;}
private:
GenreRecordSP m_rec;
};
class CollectionNode: public TSNode //--------------------------------------------
{
public:
CollectionNode(TreeNode* parent, CollectionRecordSP& rec)
{SetCollectionRecord(rec);bExpandable = TRUE; pParent = parent;}
virtual ~CollectionNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_Collection : - ST_Collection;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return m_rec->name.c_str();
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.CollectionTrackCount.val = sv.GetSmallSectionLimit();
filter.CollectionTrackCount.match = NUMM_Under;
}
else
{
filter.CollectionID.val = m_rec->ID;
filter.CollectionID.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return m_rec->ID == rec->collection.ID;
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_CollectionPicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
LPCTSTR firstPart = m_rec->name.c_str();
if (_tcscmp(firstPart, TS_UnknownString) == 0)
firstPart = pAPI->GetString(IDS_UNKNOWN);
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
INT curLen = 0;
secondPart = bf;
if (res.nLines == 1)
curLen = _sntprintf(bf, 300, _T("%d"), m_rec->trackCount);
else if (res.nLines == 2)
curLen = _sntprintf(bf, 300, _T("%s: %s (0x%X) | %s: %d"),
pAPI->GetString(IDS_LOCATION),
m_rec->location.c_str(),
m_rec->serial,
pAPI->GetString(IDS_TRACKS),
m_rec->trackCount);
else
ASSERT(0);
}
res.pDrawer->Draw(g, nfo, res, IIT_CollectionPicture, m_rec->ID, firstPart, secondPart, 0, bExpandable);
}
void SetCollectionRecord(CollectionRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
m_rec = rec;
}
const CollectionRecordSP& GetCollectionRecord() const {return m_rec;}
private:
CollectionRecordSP m_rec;
};
class YearNode: public TSNode //--------------------------------------------
{
public:
YearNode(TreeNode* parent/*, YearRecordSP& rec*/)
{/*SetYearRecord(rec);*/bExpandable = TRUE; pParent = parent;}
virtual ~YearNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_Year : - ST_Year;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return year;
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.YearTrackCount.val = sv.GetSmallSectionLimit();
filter.YearTrackCount.match = NUMM_Under;
}
else
{
filter.Year.val = m_rec->year;
filter.Year.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return m_rec->year == rec->track.year;
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_YearPicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
TCHAR firstPart[100];
_sntprintf(firstPart, 300, _T("%d"), m_rec->year);
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
INT curLen = 0;
secondPart = bf;
if (res.nLines == 1)
curLen = _sntprintf(bf, 300, _T("%d"), m_rec->trackCount);
else if (res.nLines == 2)
curLen = _sntprintf(bf, 300, _T("%s: %d"), pAPI->GetString(IDS_TRACKS), m_rec->trackCount);
else
ASSERT(0);
}
res.pDrawer->Draw(g, nfo, res, IIT_YearPicture, m_rec->year, firstPart, secondPart, 0, bExpandable);
}
void SetYearRecord(YearRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
if (rec->year > 0)
_itot(rec->year, year, 10);
else
{
_tcsncpy(year, PRGAPI()->GetString(IDS_UNKNOWN), 30);
year[29] = 0;
}
m_rec = rec;
}
const YearRecordSP& GetYearRecord() const {return m_rec;}
private:
YearRecordSP m_rec;
TCHAR year[30];
};
class MonthAddedNode: public TSNode //--------------------------------------------
{
public:
MonthAddedNode(TreeNode* parent/*, YearRecordSP& rec*/)
{/*SetYearRecord(rec);*/bExpandable = TRUE; pParent = parent;}
virtual ~MonthAddedNode() {}
virtual INT GetType() const {return m_rec.get() != 0 ? ST_MonthAdded : - ST_MonthAdded;}
virtual LPCTSTR GetString() const
{
if (m_rec.get() != NULL)
return month;
return _T("");
}
virtual void AppendTracksFilter(TracksFilter& filter, CMainTreeCtrl& sv) const
{
if (m_rec.get() == NULL)
{
filter.MonthAddedTrackCount.val = sv.GetSmallSectionLimit();
filter.MonthAddedTrackCount.match = NUMM_Under;
}
else
{
filter.MonthAdded.val = m_rec->month;
filter.MonthAdded.match = NUMM_Exact;
}
}
virtual BOOL IsFullTrackContained(FullTrackRecordSP& rec) const
{
if (m_rec.get() == NULL)
return FALSE;
return (GetYear() == rec->track.dateAdded.wYear) &&
(GetMonth() == rec->track.dateAdded.wMonth);
}
virtual void Draw(Gdiplus::Graphics& g, CFlexTreeCtrl::DrawNodeInfo& nfo, CMainTreeCtrl::GDIRes& res) const
{
PrgAPI* pAPI = PRGAPI();
if (m_rec.get() == NULL)
{
res.pDrawer->Draw(g, nfo, res, IIT_MonthPicture, 0, pAPI->GetString(IDS_VARIOUS), NULL, 0, bExpandable);
return;
}
Bitmap* bmp = NULL;
if (res.bShowImages)
bmp = res.pBitmap;
TCHAR firstPart[100];
_sntprintf(firstPart, 300, _T("%d %d"),
GetYear(),
GetMonth());
LPCTSTR secondPart = NULL;
const INT cMaxLen = 300;
TCHAR bf[cMaxLen];
if (res.bFullInformation)
{
INT curLen = 0;
secondPart = bf;
if (res.nLines == 1)
curLen = _sntprintf(bf, 300, _T("%d"), m_rec->trackCount);
else if (res.nLines == 2)
curLen = _sntprintf(bf, 300, _T("%s: %d"), pAPI->GetString(IDS_TRACKS), m_rec->trackCount);
else
ASSERT(0);
}
res.pDrawer->Draw(g, nfo, res, IIT_MonthPicture, m_rec->month, firstPart, secondPart, 0, bExpandable);
}
void SetMonthAddedRecord(MonthAddedRecordSP& rec)
{
ASSERT(rec.get() != NULL && rec->IsValid());
m_rec = rec;
_sntprintf(month, 30, _T("%d %d"), GetYear(), GetMonth());
}
const MonthAddedRecordSP& GetMonthAddedRecord() const {return m_rec;}
private:
INT GetMonth() const
{
if (m_rec.get() != NULL)
return (m_rec->month % 12) + 1;
return 0;
}
INT GetYear() const
{
if (m_rec.get() != NULL)
return (m_rec->month / 12);
return 0;
}
MonthAddedRecordSP m_rec;
TCHAR month[30];
};
//===================================================================
//===================================================================
// Main Control
//===================================================================
//===================================================================
#define REFRESH_DELAY_TIMER_ID 100
#define REFRESH_DELAY_TIMER_DELAY 300
#define ID_PROVIDERS 1000
//#define ID_INSERTRANDOMTRACKS 600
CMainTreeCtrl::CMainTreeCtrl():
m_bSmallSectionsGrouped(FALSE),
m_smallSectionsLimit(3),
m_sectionMode(SMODE_ArtistsAlbums),
m_sectionFilter(SFILT_All),
m_bInitialRefresh(TRUE),
m_lastNotification(0),
m_notificationDelay(200),
m_pMenuItitiator(NULL),
m_actionsHappened(FALSE),
m_style(SSTYL_1_Small),
m_bModifyState(TRUE),
m_bAutoUpdateIsEnabled(FALSE),
m_updatesPerformed(0)
{
SetSort(ST_Artist, SortOption(RSO_Title,TRUE));
SetSort(ST_Album, SortOption(RSO_Year,FALSE));
SetSort(ST_Genre, SortOption(RSO_Title,TRUE));
SetSort(ST_Collection, SortOption(RSO_Title,TRUE));
SetSort(ST_Year, SortOption(RSO_Title,FALSE));
SetSort(ST_MonthAdded, SortOption(RSO_Title,FALSE));
PrgAPI* pAPI = PRGAPI();
//HDC hdc = ::GetDC(0);
//CFont* pFont = pAPI->GetFont(FONT_Main);
//m_gdiRes.pMainFont = pFont;
//m_gdiRes.pTitleFont = pAPI->GetFont(FONT_MainBold);
m_gdiRes.pDrawer = new MainTreeDrawerHelper;
m_gdiRes.pDrawer->expandableBrush = ::CreateSolidBrush(RGB(200, 200, 255));
m_gdiRes.pDrawer->expandableTextColor = RGB(0, 0, 0);
// m_gdiRes.pDrawer->notExpandableBrush = ::CreateSolidBrush(RGB(200, 200, 255));
// m_gdiRes.pDrawer->notExpandableTextColor = RGB(0, 0, 0);
m_gdiRes.pDrawer->selectedBrush = ::CreateSolidBrush(RGB(50, 50, 230));
m_gdiRes.pDrawer->selectedTextColor = RGB(200, 200, 200);
m_gdiRes.pDrawer->dwStrFormat = DT_LEFT | DT_NOPREFIX | DT_END_ELLIPSIS | DT_SINGLELINE | DT_VCENTER;
m_gdiRes.pDrawer->hStarIcon = pAPI->GetIcon(ICO_StarGold16);
m_gdiRes.pDrawer->hAntiStarIcon = pAPI->GetIcon(ICO_StarBad16);
//m_gdiRes.pBitmap = NULL;
//m_gdiRes.pBitmap = new CGdiPPicDrawer;
//m_gdiRes.pBitmap->LoadResourceID(IDR_PNG_ARTIST, _T("png"));
//m_gdiRes.pBitmap->SetBkColor(RGB(0,0,0), 0);
////m_gdiRes.m_pArtistBitmap->LoadResourceID(IDR_ARTIST, _T("jpg"));
//m_gdiRes.m_pArtistBitmap->GetDrawParams().zoomLockMode = CGdiPPicDrawer::ZLM_FillArea;
//m_gdiRes.m_pArtistBitmap->GetDrawParams().positionY = 0;
//m_gdiRes.m_pAlbumBitmap = new CGdiPPicDrawer;
//m_gdiRes.m_pAlbumBitmap->LoadResourceID(IDR_ALBUM, _T("jpg"));
//m_gdiRes.m_pAlbumBitmap->GetDrawParams().zoomLockMode = CGdiPPicDrawer::ZLM_FillArea;
m_gdiRes.bShowImages = TRUE;
m_gdiRes.bFullInformation = TRUE;
m_gdiRes.nLines = 2;
SetStyle(SSTYL_3);
}
CMainTreeCtrl::~CMainTreeCtrl()
{
DeleteMenus();
if (m_hWnd) DestroyWindow();
DeleteObject(m_gdiRes.pDrawer->selectedBrush);
DeleteObject(m_gdiRes.pDrawer->expandableBrush);
DeleteObject(m_gdiRes.pDrawer->notExpandableBrush);
delete m_gdiRes.pDrawer;
}
void CMainTreeCtrl::Reset()
{
TRACEST(_T("CMainTreeCtrl::Reset"));
TreeNode* lastNode = GetNodeByIndex(GetNextSelectedItem());
SectionTypeEnum lastST = ST_Unknown;
BOOL bLastExpanded = FALSE;
FullTrackRecordSP rec;
INT lastScrollPos = GetScrollPos();
if (lastNode != NULL)
{
//===Store LastItem
lastST = (SectionTypeEnum) lastNode->GetType();
bLastExpanded = lastNode->bExpanded;
while (lastST != ST_Root)
{
TracksFilter tf;
GetTracksFilterForNode(*lastNode, tf);
FullTrackRecordCollection col;
PrgAPI* pAPI = PRGAPI();
if (pAPI->GetSQLManager()->GetFullTrackRecordCollectionByTracksFilter(col, tf, 1))
{
if (col.size() == 1)
{
rec = col[0];
break;
}
else
TRACE(_T("@3 CMainTreeCtrl::Reset. Cant find tracks from tracks filter (1)\r\n"));
}
else
{
TRACE(_T("@3 CMainTreeCtrl::Reset. Cant find tracks from tracks filter (2)\r\n"));
}
lastNode = lastNode->pParent;
if (lastNode == NULL)
{
ASSERT(0);
break;
}
lastST = (SectionTypeEnum) lastNode->GetType();
bLastExpanded = TRUE;//=== Set it to true as the current item does not exist anymore
}
}
ClearItems();
GetRootNode().RemoveChildren();
GetRootNode().bExpanded = FALSE;
Expand(GetRootNode(), TRUE); //===ReExpand root
BOOL bItemSelected = FALSE;
if (rec.get() != NULL && lastST != ST_Unknown) //===ReStore LastItem
bItemSelected = SelectNodeFromFullTrackRecord(rec, lastST);
if (bItemSelected)
{
INT idx = GetNextSelectedItem();
if (idx != -1)
{
TreeNode* pTN = GetNodeByIndex(idx);
if (pTN != NULL)
Expand(*pTN, TRUE);
}
}
else
{
if (lastScrollPos != 0)
{
SetScrollPos(lastScrollPos);
INT vis = GetNextVisibleItem();
if (vis != -1)
SetItemSelection(vis + 1, TRUE);
TRACE(_T("@3 CMainTreeCtrl::Reset. Locate using scrollPos\r\n"));
}
else
TRACE(_T("@3 CMainTreeCtrl::Reset. No location\r\n"));
}
//if (!bItemSelected && GetItemCount() > 0)
// SetItemSelection(0, TRUE);
Refresh();
}
void CMainTreeCtrl::Update(BOOL bInvalidateData)
{
if (bInvalidateData)
Reset();
Refresh();
}
void CMainTreeCtrl::EnableAutoUpdates(BOOL bEnable)
{
if (m_bAutoUpdateIsEnabled != bEnable)
{
m_bAutoUpdateIsEnabled = bEnable;
m_updatesPerformed = 0;
if (bEnable)
SetTimer(TIMER_AUTOUPDATE, TIMER_AUTOUPDATE_DELAY, 0);
else
KillTimer(TIMER_AUTOUPDATE);
}
}
SectionTypeEnum CMainTreeCtrl::GetSelectedType()
{
INT nItem = GetNextSelectedItem();
if (nItem > -1)
{
TreeNode* pTN = GetNodeByIndex(GetNextSelectedItem());
if (pTN != NULL)
return (SectionTypeEnum) pTN->GetType();
ASSERT(0);
}
return ST_Unknown;
}
TreeNode* CMainTreeCtrl::FindCompatibleNode(TreeNode* pParent, FullTrackRecordSP& rec, SectionTypeEnum desiredST)
{
ASSERT(pParent != NULL);
UINT childCount = pParent->GetChildCount();
for (UINT i = 0; i < childCount; i++)
{
TSNode* pNode = dynamic_cast<TSNode*> (pParent->GetChild(i));
if (pNode->IsFullTrackContained(rec))
//if (IsNodeCompatible(pNode, rec))
{
//Found Compatible. We will return something here
if (pNode->GetType() != desiredST && pNode->bExpandable)
{
Expand(*pNode, TRUE);
TreeNode* ret = FindCompatibleNode(pNode, rec, desiredST);
if (ret != NULL)
return ret;
}
return pNode;
}
}
return NULL;
}
BOOL CMainTreeCtrl::SelectNodeFromFullTrackRecord(FullTrackRecordSP& rec, SectionTypeEnum desiredST)
{
TRACEST(_T("CMainTreeCtrl::SelectNodeFromFullTrackRecord"), desiredST);
ASSERT(rec->IsValid());
TreeNode* pRoot = &GetRootNode();
TreeNode* ret = FindCompatibleNode(pRoot, rec, desiredST);
if (ret == NULL)
{
if (pRoot->GetChildCount() > 0)
{
TreeNode* pParent = pRoot->GetChild(0);
if (pParent->GetType() < 0)
{
//Various collection is available. Search inside there
Expand(*pParent, TRUE);
ret = FindCompatibleNode(pParent, rec, desiredST);
}
}
}
if (ret != NULL)
{
INT nItem = GetIndexByNode(ret);
if (nItem != -1)
{
SetItemSelection(nItem, TRUE);
CenterItem(nItem);
}
return TRUE;
}
return FALSE;
}
void CMainTreeCtrl::GroupSmallSections(BOOL bGroup)
{
if (bGroup != m_bSmallSectionsGrouped)
m_bSmallSectionsGrouped = bGroup ;
}
void CMainTreeCtrl::SetSmallSectionLimit(UINT value)
{
if (value != m_smallSectionsLimit)
m_smallSectionsLimit = value;
}
BEGIN_MESSAGE_MAP(CMainTreeCtrl, CFlexTreeCtrl)
ON_WM_TIMER()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()
void CMainTreeCtrl::GetTracksFilterForNode(const TreeNode& node, TracksFilter& filter)
{
filter = m_tracksFilter;
const TreeNode* pFilterNode = &node;
ASSERT(pFilterNode != NULL);
if (pFilterNode == NULL)
return;
while (pFilterNode->pParent != NULL)
{
const TSNode* pTSNode = dynamic_cast<const TSNode*> (pFilterNode);
if (pTSNode != NULL)
{
pTSNode->AppendTracksFilter(filter, *this);
pFilterNode = pFilterNode->pParent;
if (pFilterNode == NULL)
{
ASSERT(0);
break;
}
}
else
{
TRACE(_T("CMainTreeCtrl::GetTracksFilterForNode Cast failure\r\n"));
ASSERT(0);
break;
}
}
}
BOOL CMainTreeCtrl::OnFillItems(TreeNode& node)
{
ASSERT(node.bExpandable);
ASSERT(node.GetChildCount() == 0);
if (node.bExpandable && node.GetChildCount() == 0)
{
TRACEST(_T("CMainTreeCtrl::OnFillItems"));
node.bExpanded = TRUE;
//===Application Objects
PrgAPI* pAPI = PRGAPI();
SQLManager* pSM = pAPI->GetSQLManager();
//===Init
BOOL bVarious = FALSE;
INT nodeType = node.GetType();
if (nodeType < 0)
{
bVarious = TRUE;
//nodeType = -nodeType;
}
SectionTypeEnum stNode = (SectionTypeEnum) nodeType;
SectionTypeEnum stChild = GetChildForSectionType(m_sectionMode, stNode);
BOOL bExpandable = GetChildForSectionType(m_sectionMode, stChild) != ST_Unknown;
if (bVarious)
bExpandable = TRUE;
//===Build the filter based on inheritance
TracksFilter filter;
GetTracksFilterForNode(node, filter);
filter.MinNumTracks.val = m_smallSectionsLimit;
filter.MinNumTracks.match = NUMM_Disabled;
//===Fill the node
SortOptionCollection soc;
BOOL bAllowGrouping = m_bSmallSectionsGrouped && (stNode == ST_Root);
switch(stChild)
{
case ST_Artist:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
node.AppendChild(new ArtistNode(&node));
filter.MinNumTracks.match = NUMM_Over;
}
FullArtistRecordCollection recCol;
if (pSM->GetFullArtistRecordCollectionByTracksFilter(recCol, filter))
{
soc.ApplySortOption(GetSort(ST_Artist));
RecordCollectionSorter::SortFullArtistRecordCollection(recCol, soc);
FullArtistRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
ArtistNode* pTN = new ArtistNode(&node);
pTN->SetFullArtistRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_Album:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
AlbumNode* pTN = new AlbumNode(&node);
pTN->bExpandable = TRUE;
node.AppendChild(pTN);
filter.MinNumTracks.match = NUMM_Over;
}
FullAlbumRecordCollection recCol;
if (pSM->GetFullAlbumRecordCollectionByTracksFilter(recCol, filter))
{
soc.ApplySortOption(GetSort(ST_Album));
RecordCollectionSorter::SortFullAlbumRecordCollection(recCol, soc);
FullAlbumRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
AlbumNode* pTN = new AlbumNode(&node);
pTN->SetFullAlbumRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_AlbumByName:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
AlbumByNameNode* pTN = new AlbumByNameNode(&node);
pTN->bExpandable = TRUE;
node.AppendChild(pTN);
filter.MinNumTracks.match = NUMM_Over;
}
FullAlbumRecordCollection recCol;
if (pSM->GetFullAlbumGPNRecordCollectionByTracksFilter(recCol, filter))
{
soc.ApplySortOption(GetSort(ST_Album));
RecordCollectionSorter::SortFullAlbumRecordCollection(recCol, soc);
FullAlbumRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
AlbumByNameNode* pTN = new AlbumByNameNode(&node);
pTN->SetFullAlbumRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_Genre:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
node.AppendChild(new GenreNode(&node));
filter.MinNumTracks.match = NUMM_Over;
}
GenreRecordCollection recCol;
if (pSM->GetGenreRecordCollectionByTracksFilter(recCol, filter, TRUE))
{
soc.ApplySortOption(GetSort(ST_Genre));
RecordCollectionSorter::SortGenreRecordCollection(recCol, soc);
GenreRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
GenreNode* pTN = new GenreNode(&node/*, *it*/);
pTN->SetGenreRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_Collection:
{
CollectionRecordCollection recCol;
if (pSM->GetCollectionRecordCollectionByTracksFilter(recCol, filter, TRUE))
{
soc.ApplySortOption(GetSort(ST_Collection));
RecordCollectionSorter::SortCollectionRecordCollection(recCol, soc);
CollectionRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
TreeNode* pTN = new CollectionNode(&node, *it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_Year:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
node.AppendChild(new YearNode(&node));
filter.MinNumTracks.match = NUMM_Over;
}
YearRecordCollection recCol;
if (pSM->GetYearRecordCollectionByTracksFilter(recCol, filter, TRUE))
{
soc.ApplySortOption(GetSort(ST_Year));
RecordCollectionSorter::SortYearRecordCollection(recCol, soc);
YearRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
YearNode* pTN = new YearNode(&node/*, *it*/);
pTN->SetYearRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
case ST_MonthAdded:
{
if (bVarious)
filter.MinNumTracks.match = NUMM_Under;
else if (bAllowGrouping)
{
node.AppendChild(new MonthAddedNode(&node));
filter.MinNumTracks.match = NUMM_Over;
}
MonthAddedRecordCollection recCol;
if (pSM->GetMonthAddedRecordCollectionByTracksFilter(recCol, filter, TRUE))
{
soc.ApplySortOption(GetSort(ST_MonthAdded));
RecordCollectionSorter::SortMonthAddedRecordCollection(recCol, soc);
MonthAddedRecordCollection::iterator it = recCol.begin();
for (;it != recCol.end(); it++)
{
MonthAddedNode* pTN = new MonthAddedNode(&node/*, *it*/);
pTN->SetMonthAddedRecord(*it);
pTN->bExpandable = bExpandable;
node.AppendChild(pTN);
}
}
}
break;
//case ST_Directory:
// {
// DirectoryRecordCollection recCol;
// if (pSM->GetDirectoryRecordCollectionByTracksFilter(recCol, filter, TRUE))
// {
// soc.ApplySortOption(GetSort(ST_MonthAdded));
// RecordCollectionSorter::SortMonthAddedRecordCollection(recCol, soc);
// DirectoryRecordCollection::iterator it = recCol.begin();
// for (;it != recCol.end(); it++)
// {
// DirectoryNode* pTN = new DirectoryNode(&node/*, *it*/);
// pTN->SetDirectoryRecord(*it);
// pTN->bExpandable = bExpandable;
// node.AppendChild(pTN);
// }
// }
// }
// break;
case ST_Root:
default:
ASSERT(0);
break;
}
return node.GetChildCount() > 0;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetFullArtistRecordSP(FullArtistRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_Artist);
if ((SectionTypeEnum)node.GetType() == ST_Artist)
{
rec = ((ArtistNode*) (&node))->GetFullArtistRecord();
return TRUE;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetFullAlbumRecordSP(FullAlbumRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_Album);
if ((SectionTypeEnum)node.GetType() == ST_Album)
{
rec = ((AlbumNode*) (&node))->GetFullAlbumRecord();
return TRUE;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetGenreRecordSP(GenreRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_Genre);
if ((SectionTypeEnum)node.GetType() == ST_Genre)
{
rec = ((GenreNode*) (&node))->GetGenreRecord();
return TRUE;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetCollectionRecordSP(CollectionRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_Collection);
if ((SectionTypeEnum)node.GetType() == ST_Collection)
{
rec = ((CollectionNode*) (&node))->GetCollectionRecord();
return TRUE;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetYearRecordSP(YearRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_Year);
if ((SectionTypeEnum)node.GetType() == ST_Year)
{
rec = ((YearNode*) (&node))->GetYearRecord();
return TRUE;
}
return FALSE;
}
BOOL CMainTreeCtrl::GetMonthAddedRecordSP(MonthAddedRecordSP& rec, const TreeNode& node)
{
ASSERT((SectionTypeEnum)node.GetType() == ST_MonthAdded);
if ((SectionTypeEnum)node.GetType() == ST_MonthAdded)
{
rec = ((MonthAddedNode*) (&node))->GetMonthAddedRecord();
return TRUE;
}
return FALSE;
}
void CMainTreeCtrl::DrawNode(Gdiplus::Graphics& g, TreeNode& node, DrawNodeInfo& nfo)
{
const TSNode* pNode = dynamic_cast<const TSNode*>(&node);
ASSERT(pNode != NULL);
pNode->Draw(g, nfo, m_gdiRes);
}
void CMainTreeCtrl::DrawBackground(Graphics& g, const Rect& r)
{
SolidBrush bkBrush(GdiplusUtilities::COLORREF2Color(m_colors[COL_TextBk1]));
g.FillRectangle(&bkBrush, r);
}
void CMainTreeCtrl::OnItemMouseEvent(const ItemMouseEvent& ev)
{
switch (ev.type)
{
case IMET_LButtonDblClick:
{
TreeNode* tn = GetNodeByIndex(ev.activeItem);
if (tn != NULL)
{
if (tn->bExpandable)
Expand(*tn, !tn->bExpanded);
else
ExecuteNode(ACMD_DefaultPlayerAction, *tn);
}
break;
}
default:
CFlexTreeCtrl::OnItemMouseEvent(ev);
}
}
void CMainTreeCtrl::ApplyTranslation(ITranslation& translation)
{
if (m_hWnd)
{
DeleteMenus();
SetStyle(GetStyle());
//Refresh();
}
}
void CMainTreeCtrl::ApplySkin(ISkin& _skin)
{
TSSkin& skin = (TSSkin&) _skin;
//=== Colors
SetColor(COL_Text, skin.GetColor(CSEC_TreeCtrl, CVAL_Text));
SetColor(COL_TextBk1, skin.GetColor(CSEC_TreeCtrl, CVAL_Bk));
SetColor(COL_TextSub, skin.GetColor(CSEC_TreeCtrl, CVAL_SubText));
SetColor(COL_TextSubBk1, skin.GetColor(CSEC_TreeCtrl, CVAL_SubBk));
SetColor(COL_TextSel, skin.GetColor(CSEC_TreeCtrl, CVAL_SelText));
SetColor(COL_TextSelBk1, skin.GetColor(CSEC_TreeCtrl, CVAL_SelBk));
SetStyle(m_style);
//COL_Text,
//COL_TextBk1,
//COL_TextBk2,
//COL_TextSub,
//COL_TextSubBk1,
//COL_TextSubBk2,
//COL_TextSel,
//COL_TextSelBk1,
//COL_TextSelBk2,
}
//void CMainTreeCtrl::UpdateConfiguration()
//{
//
// PrgAPI* pAPI = PRGAPI();
// SetMode((SectionModesEnum)pAPI->GetOption(OPT_TREE_Mode));
// GroupSmallSections(pAPI->GetOption(OPT_TREE_GroupingEnabled) != 0);
// SetSmallSectionLimit(pAPI->GetOption(OPT_TREE_GroupingValue));
// SetStyle((SectionStylesEnum)pAPI->GetOption(OPT_TREE_Style));
//
// INT rso = pAPI->GetOption(OPT_TREE_SortArtist);
// SetSort(ST_Artist, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
// rso = pAPI->GetOption(OPT_TREE_SortAlbum);
// SetSort(ST_Album, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
// rso = pAPI->GetOption(OPT_TREE_SortGenre);
// SetSort(ST_Genre, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
// rso = pAPI->GetOption(OPT_TREE_SortCollection);
// SetSort(ST_Collection, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
// rso = pAPI->GetOption(OPT_TREE_SortYear);
// SetSort(ST_Year, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
// rso = pAPI->GetOption(OPT_TREE_SortMonthAdded);
// SetSort(ST_MonthAdded, SortOption((RecordSortOptionsEnum)(rso > 0 ? rso : - rso), rso > 0));
//
// SetFilter((SectionFiltersEnum)pAPI->GetOption(OPT_TREE_Filter));
//
//}
void CMainTreeCtrl::DeleteMenus()
{
if (m_ArtistMenu.m_hMenu) m_ArtistMenu.DestroyMenu();
if (m_AlbumMenu.m_hMenu) m_AlbumMenu.DestroyMenu();
if (m_GenericMenu.m_hMenu) m_GenericMenu.DestroyMenu();
m_ProviderRequests.clear();
}
void CMainTreeCtrl::DrawQuickSearchString(Gdiplus::Graphics& g, LPCTSTR searchString)
{
CRect rc;
GetClientRect(&rc);
const INT margin = 10;
rc.left += margin;
rc.right -= 3 * margin;
rc.top += margin;
rc.bottom = rc.top + 20;
if (rc.Width() > 50)
{
Gdiplus::SolidBrush br(Gdiplus::Color::MakeARGB(150, 0, 50, 0));
g.FillRectangle(&br, rc.left, rc.top, rc.Width(), rc.Height());
HDC hdc = g.GetHDC();
//Gdiplus::SolidBrush textBr(Gdiplus::Color::MakeARGB(255, 255,255,255));
::SetBkMode(hdc, TRANSPARENT);
::SetTextColor(hdc, RGB(255,255,255));
HFONT oldFont = (HFONT)::SelectObject(hdc, m_gdiRes.pDrawer->pTitleFont->m_hObject);
DrawText(hdc, searchString, -1,
&rc, m_gdiRes.pDrawer->dwStrFormat);
//DT_LEFT | DT_NOPREFIX | DT_END_ELLIPSIS | DT_SINGLELINE | DT_VCENTER);
::SelectObject(hdc, oldFont);
g.ReleaseHDC(hdc);
// g.DrawString(searchString,
// -1,
// m_gdiRes.pMainTextFont,
// Gdiplus::RectF(
// (Gdiplus::REAL)rc.left,
// (Gdiplus::REAL)rc.top,
// (Gdiplus::REAL)rc.Width(),
// (Gdiplus::REAL)rc.Height()),
// m_gdiRes.pMainStringFormat,
// &textBr);
}
}
void CMainTreeCtrl::SetMode(SectionModesEnum smode)
{
ASSERT(smode > SMODE_First && smode < SMODE_Last);
if (m_sectionMode != smode)
m_sectionMode = smode;
}
void CMainTreeCtrl::SetStyle(SectionStylesEnum style)
{
ASSERT(style > SSTYL_First && style < SSTYL_Last);
INT oldScrollPos = GetScrollPos();
INT oldItemHeight = GetItemHeight();
m_style = style;
TSSkin& skin = (TSSkin&) PRGAPI()->GetSkinManager()->GetSkin();
INT rfs = skin.GetRelativeFontSize();
m_gdiRes.nLines = 2;
m_gdiRes.bShowImages = TRUE;
m_gdiRes.bFullInformation = TRUE;
m_gdiRes.fImageScale = 1.0f;
switch (m_style)
{
case SSTYL_1_Small:
SetItemHeight(18 + rfs);
m_gdiRes.nLines = 1;
m_gdiRes.bShowImages = FALSE;
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_NormalBold);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Normal);
break;
case SSTYL_2:
SetItemHeight(32 + 2 * rfs);
m_gdiRes.bShowImages = FALSE;
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_NormalBold);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Normal);
break;
case SSTYL_3:
SetItemHeight(32 + 2 * rfs);
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_NormalBold);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Normal);
break;
case SSTYL_4:
m_gdiRes.nLines = 3;
SetItemHeight(64 + 2 * rfs);
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Big);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Normal);
break;
case SSTYL_5:
m_gdiRes.nLines = 3;
SetItemHeight(64 + 2 * rfs);
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_BigBold);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Big);
m_gdiRes.fImageScale = 1.4f;
break;
case SSTYL_6:
m_gdiRes.nLines = 4;
SetItemHeight(96 + 2 * rfs);
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_VeryBig);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Big);
break;
case SSTYL_7:
SetItemHeight(32 + rfs);
m_gdiRes.nLines = 1;
m_gdiRes.bFullInformation = FALSE;
m_gdiRes.pDrawer->pTitleFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Big);
m_gdiRes.pDrawer->pMainFont = skin.GetFont(CSEC_TreeCtrl, FSTY_Big);
break;
default:
ASSERT(0);
break;
}
SetScrollPos(oldScrollPos * GetItemHeight() / oldItemHeight);
Refresh();
}
void CMainTreeCtrl::SetFilter(SectionFiltersEnum sfilter)
{
ASSERT(sfilter > SFILT_First && sfilter < SFILT_Last);
if (m_sectionFilter != sfilter)
{
m_tracksFilter = TracksFilter();
switch (sfilter)
{
case SFILT_Audio:
m_tracksFilter.TrackType.match = NUMM_Under;
m_tracksFilter.TrackType.val = 99;
break;
case SFILT_Video:
m_tracksFilter.TrackType.match = NUMM_Over;
m_tracksFilter.TrackType.val = 99;
break;
case SFILT_New:
{
SYSTEMTIME st;
GetLocalTime(&st);
DOUBLE dtime;
SystemTimeToVariantTime(&st, &dtime);
dtime -= PRGAPI()->GetOption(OPT_GEN_DaysMeansNew);
VariantTimeToSystemTime(dtime, &st);
m_tracksFilter.DateAdded.val = st;
m_tracksFilter.DateAdded.match = DATM_After;
}
break;
}
m_sectionFilter = sfilter;
}
}
const SectionTypeEnum ArtAlb[] = {ST_Root, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum ArtGen[] = {ST_Root, ST_Artist, ST_Genre, ST_Unknown};
const SectionTypeEnum ArtYea[] = {ST_Root, ST_Artist, ST_Year, ST_Unknown};
const SectionTypeEnum GenArtAlb[] = {ST_Root, ST_Genre, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum GenYea[] = {ST_Root, ST_Genre, ST_Year, ST_Unknown};
const SectionTypeEnum ColArtAlb[] = {ST_Root, ST_Collection, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum ColGenArtAlb[] = {ST_Root, ST_Collection, ST_Genre, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum YeaAlb[] = {ST_Root, ST_Year, ST_AlbumByName, ST_Unknown};
const SectionTypeEnum YeaArtAlb[] = {ST_Root, ST_Year, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum AlbBN[] = {ST_Root, ST_AlbumByName, ST_Unknown};
const SectionTypeEnum MonArtAlb[] = {ST_Root, ST_MonthAdded, ST_Artist, ST_Album, ST_Unknown};
const SectionTypeEnum ColAlb[] = {ST_Root, ST_Collection, ST_AlbumByName, ST_Unknown};
SectionTypeEnum CMainTreeCtrl::GetChildForSectionType(SectionModesEnum smode, SectionTypeEnum st)
{
if ((INT) st < 0)
return SectionTypeEnum(- INT(st));
const SectionTypeEnum* pCurEnum = ArtAlb;
switch (smode)
{
case SMODE_ArtistsAlbums:
pCurEnum = ArtAlb;
break;
case SMODE_ArtistsGenres:
pCurEnum = ArtGen;
break;
case SMODE_ArtistsYears:
pCurEnum = ArtYea;
break;
case SMODE_GenreArtistsAlbums:
pCurEnum = GenArtAlb;
break;
case SMODE_GenreYears:
pCurEnum = GenYea;
break;
case SMODE_CollectionsArtistsAlbums:
pCurEnum = ColArtAlb;
break;
case SMODE_CollectionsGenresArtistsAlbums:
pCurEnum = ColGenArtAlb;
break;
case SMODE_YearAlbums:
pCurEnum = YeaAlb;
break;
case SMODE_YearArtistsAlbums:
pCurEnum = YeaArtAlb;
break;
case SMODE_AlbumsByName:
pCurEnum = AlbBN;
break;
case SMODE_MonthAddedArtistAlbum:
pCurEnum = MonArtAlb;
break;
case SMODE_CollectionsAlbums:
pCurEnum = ColAlb;
break;
//case SMODE_Directories:
// return ST_Directory;
// break;
default:
ASSERT(0);
break;
}
while (*pCurEnum != ST_Unknown)
{
if (*pCurEnum == st)
{
pCurEnum++;
return *pCurEnum;
}
pCurEnum++;
}
ASSERT(0);
return ST_Unknown;
}
void CMainTreeCtrl::SetSort(SectionTypeEnum type,SortOption so)
{
ASSERT(type > ST_Unknown && type < ST_Last);
if (type > ST_Unknown && type < ST_Last)
m_sort[type] = so;
}
SortOption CMainTreeCtrl::GetSort(SectionTypeEnum type)
{
ASSERT(type > ST_Unknown && type < ST_Last);
if (type > ST_Unknown && type < ST_Last)
return m_sort[type];
return SortOption();
}
BOOL CMainTreeCtrl::GetSelectedFullArtistRecordSP(FullArtistRecordSP& rec)
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetFullArtistRecordSP(rec, *tn);
}
BOOL CMainTreeCtrl::GetSelectedFullAlbumRecordSP(FullAlbumRecordSP& rec )
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetFullAlbumRecordSP(rec, *tn);
}
BOOL CMainTreeCtrl::GetSelectedGenreRecordSP(GenreRecordSP& rec )
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetGenreRecordSP(rec, *tn);
}
BOOL CMainTreeCtrl::GetSelectedCollectionRecordSP(CollectionRecordSP& rec )
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetCollectionRecordSP(rec, *tn);
}
BOOL CMainTreeCtrl::GetSelectedYearRecordSP(YearRecordSP& rec )
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetYearRecordSP(rec, *tn);
}
BOOL CMainTreeCtrl::GetSelectedMonthAddedRecordSP(MonthAddedRecordSP& rec)
{
TreeNode* tn = GetNodeByIndex(GetNextSelectedItem());
ASSERT(tn!=NULL);
if (tn == NULL) return FALSE;
return GetMonthAddedRecordSP(rec, *tn);
}
void CMainTreeCtrl::OnSelectionChanged()
{
UINT curTick = GetTickCount();
if (curTick - m_lastNotification > 1000)
{
ModifyState();
}
else
{
KillTimer(REFRESH_DELAY_TIMER_ID);
SetTimer(REFRESH_DELAY_TIMER_ID,
m_notificationDelay / (curTick - m_lastNotification < m_notificationDelay ? 1 : 10),
NULL);
}
m_lastNotification = curTick;
}
void CMainTreeCtrl::OnTimer(UINT nIDEvent)
{
switch (nIDEvent)
{
case REFRESH_DELAY_TIMER_ID:
KillTimer(REFRESH_DELAY_TIMER_ID);
ModifyState();
return;
case TIMER_AUTOUPDATE:
{
CollectionManager* pCM = PRGAPI()->GetCollectionManager();
CollectionManager::State state = pCM->GetState();
if (state == CollectionManager::S_Idle)
KillTimer(TIMER_AUTOUPDATE);
else
{
INT updates = pCM->GetProgress().updateActionsPerformed;
if (updates != m_updatesPerformed)
Update(TRUE);
}
}
break;
}
__super::OnTimer(nIDEvent);
}
void CMainTreeCtrl::ModifyState()
{
if (m_bModifyState == FALSE)
return;
TreeNode* pNode = GetNodeByIndex(GetNextSelectedItem());
if (pNode != NULL)
{
StateManager* pSM = PRGAPI()->GetStateManager();
TSState& state = pSM->GetState();
GetTracksFilterForNode(*pNode, state.activeTracksFilter);
// state.sectionSelectionStyle = TSState::SSS_Normal;
switch (GetSelectedType())
{
case ST_Artist:
state.activeItemType = IT_Artist;
break;
case ST_Album:
case ST_AlbumByName:
state.activeItemType = IT_Album;
break;
case ST_Year:
state.activeItemType = IT_Year;
break;
case ST_Genre:
state.activeItemType = IT_Genre;
break;
case ST_Collection:
state.activeItemType = IT_Collection;
break;
default:
state.activeItemType = IT_Various;
break;
}
PRGAPI()->SendMessage(SM_CurrentSectionChanged);
}
}
void CMainTreeCtrl::AppendInfoProviderMenuItem(BCMenu& mnu, const IInfoProvider& IP, InfoItemTypeEnum iit)
{
PrgAPI* pAPI = PRGAPI();
m_ProviderRequests.push_back(ProviderRequest(IP.GetModuleInfo(IInfoProvider::IPI_UniqueID), iit));
TCHAR bf[500];
_sntprintf(bf, 500, _T("\"%s\" - %s"), IP.GetModuleInfo(IInfoProvider::IPI_Name), pAPI->GetStringForInfoItemType(iit));
mnu.AppendMenu(MF_STRING, ID_PROVIDERS + m_ProviderRequests.size() - 1, bf, pAPI->GetIconForInfoItemType(iit));
}
BOOL CMainTreeCtrl::ExecuteNode(AppCommandsEnum appCmd, const TreeNode& node)
{
TRACEST(_T("CMainTreeCtrl::ExecuteNode (p=appCmd)"), appCmd);
PrgAPI* pAPI = PRGAPI();
switch (appCmd)
{
case ACMD_DefaultPlayerAction:
case ACMD_Play:
case ACMD_Enqueue:
{
TracksFilter tf;
GetTracksFilterForNode(node, tf);
FullTrackRecordCollection tracks;
if (pAPI->GetSQLManager()->GetFullTrackRecordCollectionByTracksFilter(tracks, tf))
{
ASSERT(tracks.size() > 0);
MediaPlayer* pMP = pAPI->GetMediaPlayer();
if (tracks.size() > 0)
{
SortOptionCollection soc;
soc.ApplySortOption(SortOption(RSO_TrackNo, TRUE));
soc.ApplySortOption(SortOption(RSO_Location, TRUE));
RecordCollectionSorter::SortFullTrackRecordCollection(tracks, soc);
if (appCmd == ACMD_Enqueue)
pAPI->GetActionManager()->Enqueue(pMP, tracks);
else if (appCmd == ACMD_Play)
pAPI->GetActionManager()->Play(pMP, tracks);
else
pAPI->GetActionManager()->DefaultPlayerAction(pMP, tracks);
}
}
}
break;
case ACMD_PurchaseInfo:
{
SectionTypeEnum st = ST_Unknown;
st = (SectionTypeEnum) node.GetType();
switch (st)
{
case ST_Artist:
{
FullArtistRecordSP rec;
if (GetFullArtistRecordSP(rec, node))
pAPI->GetActionManager()->GoToArtistBuyPage(rec->artist.name.c_str());
}
break;
case ST_Album:
{
FullAlbumRecordSP rec;
if (GetFullAlbumRecordSP(rec, node))
pAPI->GetActionManager()->GoToAlbumBuyPage(rec->artist.name.c_str(), rec->album.name.c_str());
}
break;
default:
ASSERT(0);
break;
}
}
break;
case ACMD_Properties:
{
SectionTypeEnum st = (SectionTypeEnum) node.GetType();
switch (st)
{
case ST_Artist:
{
FullArtistRecordSP rec;
if (GetFullArtistRecordSP(rec, node))
{
//=== Detect Changes
//UINT oldArtID = rec->artist.ID;
//UINT oldGenID = rec->genre.ID;
if (pAPI->GetActionManager()->ShowArtistPropertiesDlg(rec, this, TRUE))
{
//if (oldArtID != rec->artist.ID || oldGenID != rec->genre.ID)
// Update(TRUE);//=== Full Refresh
//else
// Update(FALSE);
Update(TRUE);//=== Full Refresh
}
}
}
break;
case ST_Album:
{
FullAlbumRecordSP rec;
if (GetFullAlbumRecordSP(rec, node))
{
//=== Detect Changes
//UINT oldArtID = rec->artist.ID;
//UINT oldAlbID = rec->album.ID;
if (pAPI->GetActionManager()->ShowAlbumPropertiesDlg(rec, this, TRUE))
{
//if (oldArtID != rec->artist.ID || oldAlbID != rec->album.ID)
// Update(TRUE);//=== Full Refresh
//else
// Update(FALSE);
Update(TRUE);
}
}
}
break;
default:
ASSERT(0);
break;
}
}
break;
case ACMD_InsertRandomTracks:
{
ActionManager* pAM = pAPI->GetActionManager();
TracksFilter tf;
GetTracksFilterForNode(node, tf);
FullTrackRecordCollection col;
pAM->GetRandomTrackCollection(col, tf, 5);
if (col.size() > 0)
pAM->Enqueue(pAPI->GetMediaPlayer(), col);
}
break;
default:
{
ServicesRegistrationSrv* srv = pAPI->GetServicesRegistrationSrv();
if (appCmd >= MENU_WebServicesHolder && appCmd < MENU_WebServicesHolder + (INT)srv->GetServicesCount())
{
ServicesExecuteInfo sei;
SectionTypeEnum st = (SectionTypeEnum) node.GetType();
switch (st)
{
case ST_Artist:
{
FullArtistRecordSP rec;
if (GetFullArtistRecordSP(rec, node))
{
sei.artist = rec->artist.name.c_str();
ServiceInfo si;
if (srv->GetServiceInfo(appCmd - MENU_WebServicesHolder, si))
srv->Execute(si, sei, srv->GetWebViewer());
}
}
break;
case ST_Album:
{
FullAlbumRecordSP rec;
if (GetFullAlbumRecordSP(rec, node))
{
sei.artist = rec->artist.name.c_str();
sei.album = rec->album.name.c_str();
ServiceInfo si;
if (srv->GetServiceInfo(appCmd - MENU_WebServicesHolder, si))
srv->Execute(si, sei, srv->GetWebViewer());
}
}
break;
default:
ASSERT(0);
break;
}
}
else if (appCmd >= ID_PROVIDERS && appCmd < ID_PROVIDERS + (INT)m_ProviderRequests.size())
{
InfoDownloadManager* pIDM = pAPI->GetInfoDownloadManager();
InfoItemTypeEnum iit = m_ProviderRequests[appCmd - ID_PROVIDERS].iit;
SectionTypeEnum st = (SectionTypeEnum) node.GetType();
switch (iit)
{
case IIT_ArtistBio:
case IIT_ArtistPicture:
{
ASSERT(st == ST_Artist);
FullArtistRecordSP rec;
if (GetFullArtistRecordSP(rec, node))
{
if (iit == IIT_ArtistBio)
pIDM->RequestArtistInfo(rec->artist,
m_ProviderRequests[appCmd - ID_PROVIDERS].provID.c_str(), TRUE);
else
pIDM->RequestArtistPic(rec->artist,
m_ProviderRequests[appCmd - ID_PROVIDERS].provID.c_str(), TRUE);
}
}
break;
case IIT_AlbumReview:
case IIT_AlbumPicture:
{
ASSERT(st == ST_Album);
FullAlbumRecordSP rec;
if (GetFullAlbumRecordSP(rec, node))
{
if (iit == IIT_AlbumReview)
pIDM->RequestAlbumInfo(rec->album, rec->artist.name.c_str(),
m_ProviderRequests[appCmd - ID_PROVIDERS].provID.c_str(),
TRUE);
else
pIDM->RequestAlbumPic(rec->album, rec->artist.name.c_str(),
m_ProviderRequests[appCmd - ID_PROVIDERS].provID.c_str(),
TRUE);
}
}
break;
default:
ASSERT(0);
break;
}
}
else if (appCmd >= MENU_RatingHolder && appCmd <= MENU_RatingHolder+5)
{
SectionTypeEnum st = (SectionTypeEnum) node.GetType();
INT Rating = Stars2Rating((FLOAT)(appCmd - MENU_RatingHolder));
SQLManager* pSM = PRGAPI()->GetSQLManager();
switch (st)
{
case ST_Artist:
{
FullArtistRecordSP rec;
if (GetFullArtistRecordSP(rec, node))
{
if (rec->artist.rating != Rating)
{
rec->artist.rating = Rating;
pSM->UpdateArtistRecord(rec->artist, FALSE);
Update(FALSE);
}
}
}
break;
case ST_Album:
{
FullAlbumRecordSP rec;
if (GetFullAlbumRecordSP(rec, node))
{
if (rec->album.rating != Rating)
{
rec->album.rating = Rating;
pSM->UpdateAlbumRecord(rec->album, FALSE);
Update(FALSE);
}
}
}
break;
default:
ASSERT(FALSE);
}
Invalidate();
}
else
{
TRACE(_T("@1 CMainTreeCtrl::ExecuteNode. Unknown Command\n"));
ASSERT(0);
}
}
}
return TRUE;
}
BOOL CMainTreeCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
TRACEST(_T("CMainTreeCtrl::OnCommand"), wParam);
ASSERT(m_pMenuItitiator != NULL);
if (m_pMenuItitiator != NULL)
ExecuteNode((AppCommandsEnum) wParam, *m_pMenuItitiator);
return __super::OnCommand(wParam, lParam);
}
TreeNode* CMainTreeCtrl::OnFindNode(LPCTSTR str)
{
ASSERT(str != NULL);
if (str == NULL || str[0] == 0)
return NULL;
TRACEST(_T("CMainTreeCtrl::OnFindNode"), str);
INT strSize = _tcslen(str);
INT itemCount = GetItemCount();
INT startItem = GetNextSelectedItem();
if (startItem == -1)
return NULL;
INT curItem = startItem;
while (TRUE)
{
curItem++;
if (curItem >= itemCount)
curItem = 0;
if (curItem == startItem)
return NULL;//Not found
TreeNode* curNode = GetNodeByIndex(curItem);
ASSERT(curNode != NULL);
if (curNode != NULL)
{
if (_tcsnicmp(str, curNode->GetString(), strSize) == 0)
return curNode;
}
}
return NULL;
}
BOOL CMainTreeCtrl::ItemAcceptsFileDrop(CPoint& p, INT nItem)
{
TreeNode* node = GetNodeByIndex(nItem);
if (node != NULL)
{
SectionTypeEnum nt = (SectionTypeEnum) node->GetType();
switch (nt)
{
case ST_Artist:
case ST_Album:
case ST_Genre:
case ST_Year:
return TRUE;
}
}
return FALSE;
}
BOOL CMainTreeCtrl::OnFileDrop(const std::vector<std::tstring>& files, CPoint& p)
{
TRACEST(_T("CMainTreeCtrl::OnFileDrop"));
ASSERT(!files.empty());
TreeNode* node = GetNodeByPoint(p.x, p.y);
if (node != NULL)
{
PrgAPI* pAPI = PRGAPI();
SQLManager* pSM = pAPI->GetSQLManager();
ActionManager* pAM = pAPI->GetActionManager();
//=== Get The required changes in a TagInfo structure
TagInfo ti;
SectionTypeEnum nt = (SectionTypeEnum) node->GetType();
while (nt != ST_Root)
{
switch (nt)
{
case ST_Artist:
{
FullArtistRecordSP artRec;
if (GetFullArtistRecordSP(artRec, *node))
{
ti.validFields |= TagInfo_Artist;
ti.Artist = artRec->artist.name;
}
}
break;
case ST_Album:
{
FullAlbumRecordSP albRec;
if (GetFullAlbumRecordSP(albRec, *node))
{
ti.validFields |= TagInfo_Album;
ti.Album = albRec->album.name;
}
}
break;
case ST_Genre:
{
GenreRecordSP genRec;
if (GetGenreRecordSP(genRec, *node))
{
ti.validFields |= TagInfo_Genre;
ti.Genre = genRec->name;
}
}
break;
case ST_Year:
{
YearRecordSP yeaRec;
if (GetYearRecordSP(yeaRec, *node))
{
ti.validFields |= TagInfo_Year;
ti.Year = yeaRec->year;
}
}
break;
}
node = node->pParent;
nt = (SectionTypeEnum) node->GetType();
}
if (ti.validFields == TagInfo_None)
{
TRACE(_T("@1 CMainTreeCtrl::OnFileDrop Nothing to do\r\n"));
return TRUE;//===Nothing to do
}
HWND parent = GetAncestor(GA_ROOT)->m_hWnd;
UINT total = files.size();
UINT pos = 0;
FullTrackRecordCollection col;
CUserProgressDlg dlg(CWnd::FromHandle(parent));
dlg.SetTitle(pAPI->GetString(IDS_TAGGING));
for (std::vector<std::tstring>::const_iterator itFiles = files.begin();itFiles != files.end(); itFiles++)
{
col.clear();
LPCTSTR fileName = (*itFiles).c_str();
dlg.SetMessage(fileName);
dlg.SetProgress(pos++ / (FLOAT)total);
dlg.Show();
if (pSM->GetFullTrackRecordCollectionByLocation(col, fileName) && !col.empty())
{
FullTrackRecordCollection::iterator it = col.begin();
for (; it!= col.end(); it++)
{
FullTrackRecordSP& rec = *it;
pSM->UpdateTrackFromTagInfo(rec->track.ID, rec->track.colID, fileName, ti);
pAM->TagTrack(fileName, ti);
}
}
else
{
TRACE(_T("@1 CMainTreeCtrl::OnFileDrop File Not Found: %s\r\n"), fileName);
}
}
pAPI->SendMessage(SM_DatabaseUpdated);
}
return TRUE;
}
//---------------------------------------------------
//ICtrlColors ---------------------------------------
//---------------------------------------------------
void CMainTreeCtrl::SetColor(UINT idx, COLORREF value)
{
ASSERT(idx < COL_Last);
if (idx < COL_Last)
{
m_colors[idx] = value;
switch (idx)
{
case COL_Text:
m_gdiRes.pDrawer->expandableTextColor = value;
break;
case COL_TextBk1:
DeleteObject(m_gdiRes.pDrawer->expandableBrush);
m_gdiRes.pDrawer->expandableBrush = CreateSolidBrush(value);
break;
case COL_TextBk2://Unused
break;
case COL_TextSub:
m_gdiRes.pDrawer->notExpandableTextColor = value;
break;
case COL_TextSubBk1:
DeleteObject(m_gdiRes.pDrawer->notExpandableBrush);
m_gdiRes.pDrawer->notExpandableBrush = CreateSolidBrush(value);
break;
case COL_TextSubBk2://Unused
break;
case COL_TextSel:
m_gdiRes.pDrawer->selectedTextColor = value;
break;
case COL_TextSelBk1:
DeleteObject(m_gdiRes.pDrawer->selectedBrush);
m_gdiRes.pDrawer->selectedBrush = CreateSolidBrush(value);
break;
case COL_TextSelBk2://Unused
break;
}
Refresh();
}
}
COLORREF CMainTreeCtrl::GetColor(UINT idx)
{
ASSERT(idx < COL_Last);
if (idx < COL_Last)
return m_colors[idx];
return 0;
}
//const TCHAR* const cColorNames[] = {
// _T("Text"),
// _T("TextBk1"),
// _T("TextBk2"),
// _T("TextSub"),
// _T("TextSubBk1"),
// _T("TextSubBk2"),
// _T("TextSel"),
// _T("TextSelBk1"),
// _T("TextSelBk2"),
// NULL
//};
//
//
//LPCTSTR CMainTreeCtrl::GetColorName(UINT idx)
//{
// ASSERT(idx <= COL_Last);
// if (idx < COL_Last)
// return cColorNames[idx];
// return NULL;
//}
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
void CMainTreeCtrl::OnRButtonUp(UINT nFlags, CPoint point)
{
TRACEST(_T("CMainTreeCtrl::OnRButtonUp"));
m_pMenuItitiator = GetNodeByPoint(point.x, point.y);
if (m_pMenuItitiator == NULL)
{
TRACE(_T("@3 CMainTreeCtrl::OnRButtonUp. Empty Space\r\n"));
return;
}
LPCTSTR ret = m_pMenuItitiator->GetString();
if (ret == 0)
return;
SectionTypeEnum nt = ST_Unknown;
PrgAPI* pAPI = PRGAPI();
ITSMenu& mnuRatings = pAPI->GetMenuManager()->GetMenu(MenuManager::MNU_Rating);
ClientToScreen(&point);
if (ret[0] != '[')
nt = (SectionTypeEnum) m_pMenuItitiator->GetType();
switch (nt)
{
case ST_Artist:
if (m_ArtistMenu.m_hMenu == NULL)
{
ITSMenu& mnuArtistServicesMenu = pAPI->GetMenuManager()->GetMenu(MenuManager::MNU_ArtistServices);
m_ArtistMenu.CreatePopupMenu();
m_ArtistMenu.SetFont(pAPI->GetFont(FONT_Dialogs));
m_ArtistMenu.SetIconSize(16,16);
TCHAR bf[1000];
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_PLAY), pAPI->GetString(IDS_KEYENTER));
m_ArtistMenu.AppendMenu(MF_STRING, ACMD_Play, bf, pAPI->GetIcon(ICO_Play16));
_sntprintf(bf, 1000, _T("%s\t%s + %s"), pAPI->GetString(IDS_ENQUEUE), pAPI->GetString(IDS_KEYSHIFT), pAPI->GetString(IDS_KEYENTER));
m_ArtistMenu.AppendMenu(MF_STRING, ACMD_Enqueue, bf, pAPI->GetIcon(ICO_Add16));
m_ArtistMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_INSERTRANDOMTRACKS), pAPI->GetString(IDS_KEYINSERT));
m_ArtistMenu.AppendMenu(MF_POPUP, ACMD_InsertRandomTracks, bf);
m_ArtistMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
m_ArtistMenu.AppendMenu(MF_POPUP, (UINT) mnuArtistServicesMenu.GetInternalHandler(),
(LPTSTR)pAPI->GetString(IDS_SERVICES), pAPI->GetIcon(ICO_Providers16));
m_ArtistMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
InfoProviderFactory* pIPF = pAPI->GetInfoProviderFactory();
INT itCount = m_ProviderRequests.size();
INT ipIdx = 0;
while (pIPF->GetItemByIndex(ipIdx) != NULL)
{
if (pIPF->ForPublicUse(ipIdx))
{
const IInfoProvider* pIP = pIPF->GetItemByIndex(ipIdx);
if (pIP->CanHandle(IInfoProvider::SRV_ArtistBio))
AppendInfoProviderMenuItem(m_ArtistMenu, *pIP, IIT_ArtistBio);
if (pIP->CanHandle(IInfoProvider::SRV_ArtistImage))
AppendInfoProviderMenuItem(m_ArtistMenu, *pIP, IIT_ArtistPicture);
}
ipIdx++;
}
if (itCount != m_ProviderRequests.size())
{
m_ArtistMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
}
m_ArtistMenu.AppendMenu(MF_POPUP, (UINT) mnuRatings.GetInternalHandler(), (LPTSTR)pAPI->GetString(IDS_RATING), pAPI->GetIcon(ICO_StarGold16));
_sntprintf(bf, 1000, _T("%s - %s"), pAPI->GetString(IDS_MOREALBUMS), pAPI->GetString(IDS_PURCHASEINFO));
m_ArtistMenu.AppendMenu(MF_POPUP, ACMD_PurchaseInfo,
bf, pAPI->GetIcon(ICO_Buy16));
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_PROPERTIES), pAPI->GetString(IDS_KEYHOME));
m_ArtistMenu.AppendMenu(MF_STRING, ACMD_Properties, bf, pAPI->GetIcon(ICO_Properties16));
}
pAPI->GetMenuManager()->PrepareMenu(MenuManager::MNU_ArtistServices);
m_ArtistMenu.TrackPopupMenu(NULL, point.x, point.y, this);
break;
case ST_Album:
if (m_AlbumMenu.m_hMenu == NULL)
{
TCHAR bf[1000];
ITSMenu& mnuAlbumServicesMenu = pAPI->GetMenuManager()->GetMenu(MenuManager::MNU_AlbumServices);
m_AlbumMenu.CreatePopupMenu();
m_AlbumMenu.SetFont(pAPI->GetFont(FONT_Dialogs));
m_AlbumMenu.SetIconSize(16,16);
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_PLAY), pAPI->GetString(IDS_KEYENTER));
m_AlbumMenu.AppendMenu(MF_STRING, ACMD_Play, bf, pAPI->GetIcon(ICO_Play16));
_sntprintf(bf, 1000, _T("%s\t%s + %s"), pAPI->GetString(IDS_ENQUEUE), pAPI->GetString(IDS_KEYSHIFT), pAPI->GetString(IDS_KEYENTER));
m_AlbumMenu.AppendMenu(MF_STRING, ACMD_Enqueue, bf, pAPI->GetIcon(ICO_Add16));
m_AlbumMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_INSERTRANDOMTRACKS), pAPI->GetString(IDS_KEYINSERT));
m_AlbumMenu.AppendMenu(MF_POPUP, ACMD_InsertRandomTracks, bf);
m_AlbumMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
m_AlbumMenu.AppendMenu(MF_POPUP, (UINT) mnuAlbumServicesMenu.GetInternalHandler(),
(LPTSTR)pAPI->GetString(IDS_SERVICES), pAPI->GetIcon(ICO_Providers16));
m_AlbumMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
InfoProviderFactory* pIPF = pAPI->GetInfoProviderFactory();
INT itCount = m_ProviderRequests.size();
INT ipIdx = 0;
while (pIPF->GetItemByIndex(ipIdx) != NULL)
{
if (pIPF->ForPublicUse(ipIdx))
{
const IInfoProvider* pIP = pIPF->GetItemByIndex(ipIdx);
if (pIP->CanHandle(IInfoProvider::SRV_AlbumReview))
AppendInfoProviderMenuItem(m_AlbumMenu, *pIP, IIT_AlbumReview);
if (pIP->CanHandle(IInfoProvider::SRV_AlbumImage))
AppendInfoProviderMenuItem(m_AlbumMenu, *pIP, IIT_AlbumPicture);
}
ipIdx++;
}
if (itCount != m_ProviderRequests.size())
{
m_AlbumMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
}
m_AlbumMenu.AppendMenu(MF_POPUP, (UINT) mnuRatings.GetInternalHandler(),
(LPTSTR)pAPI->GetString(IDS_RATING), pAPI->GetIcon(ICO_StarGold16));
_sntprintf(bf, 500, _T("%s - %s - %s"),
pAPI->GetString(IDS_PREVIEW),
pAPI->GetString(IDS_SIMILAR),
pAPI->GetString(IDS_PURCHASEINFO));
m_AlbumMenu.AppendMenu(MF_POPUP, ACMD_PurchaseInfo,
bf, pAPI->GetIcon(ICO_Buy16));
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_PROPERTIES), pAPI->GetString(IDS_KEYHOME));
m_AlbumMenu.AppendMenu(MF_STRING, ACMD_Properties, bf, pAPI->GetIcon(ICO_Properties16));
//m_AlbumMenu.LoadToolbar(IDR_MAINLISTNORMAL);
}
pAPI->GetMenuManager()->PrepareMenu(MenuManager::MNU_AlbumServices);
m_AlbumMenu.TrackPopupMenu(NULL, point.x, point.y, this);
break;
default:
if (m_GenericMenu.m_hMenu == NULL)
{
m_GenericMenu.CreatePopupMenu();
m_GenericMenu.SetFont(pAPI->GetFont(FONT_Dialogs));
m_GenericMenu.SetIconSize(16,16);
TCHAR bf[1000];
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_PLAY), pAPI->GetString(IDS_KEYENTER));
m_GenericMenu.AppendMenu(MF_STRING, ACMD_Play, bf, pAPI->GetIcon(ICO_Play16));
_sntprintf(bf, 1000, _T("%s\t%s + %s"), pAPI->GetString(IDS_ENQUEUE), pAPI->GetString(IDS_KEYSHIFT), pAPI->GetString(IDS_KEYENTER));
m_GenericMenu.AppendMenu(MF_STRING, ACMD_Enqueue, bf, pAPI->GetIcon(ICO_Add16));
m_GenericMenu.AppendMenu(MF_SEPARATOR, NULL, NULL);
_sntprintf(bf, 1000, _T("%s\t%s"), pAPI->GetString(IDS_INSERTRANDOMTRACKS), pAPI->GetString(IDS_KEYINSERT));
m_GenericMenu.AppendMenu(MF_POPUP, ACMD_InsertRandomTracks, bf);
}
m_GenericMenu.TrackPopupMenu(NULL, point.x, point.y, this);
}
__super::OnRButtonUp(nFlags, point);
}
BOOL CMainTreeCtrl::PreTranslateMessage(MSG* pMsg)
{
switch (pMsg->message)
{
case WM_KEYDOWN:
{
//TRACE(_T("WM_KEYDOWN: %d - %d\r\n"), pMsg->wParam, pMsg->lParam);
INT nItem = GetNextSelectedItem();
if (nItem != -1)
{
TreeNode* pTN = GetNodeByIndex(nItem);
if (pTN != NULL)
{
BOOL bHandled = TRUE;
switch (pMsg->wParam)
{
case VK_RETURN:
ExecuteNode(ACMD_Play, *pTN);
break;
case VK_BACK:
ExecuteNode(ACMD_Enqueue, *pTN);
break;
case VK_INSERT:
ExecuteNode(ACMD_InsertRandomTracks, *pTN);
break;
case VK_HOME:
ExecuteNode(ACMD_Properties, *pTN);
break;
default:
bHandled = FALSE;
}
if (bHandled)
return TRUE;
}
}
}
break;
case WM_CHAR:
{
BOOL bHandled = TRUE;
switch (pMsg->wParam)
{
case VK_RETURN:
case VK_BACK:
case VK_INSERT:
case VK_HOME:
default:
bHandled = FALSE;
}
if (bHandled)
return TRUE;
}
break;
}
return CFlexTreeCtrl::PreTranslateMessage(pMsg);
}
void CMainTreeCtrl::PostCreate()
{
PrgAPI* pAPI = PRGAPI();
ApplyTranslation(*pAPI->GetTranslationManager());
ApplySkin(pAPI->GetSkinManager()->GetSkin());
}
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
2532
]
]
] |
d62237880ab62f5df2a18a7c9e8bc2af108af310 | 823e34ee3931091af33fbac28b5c5683a39278e4 | /MailReceiver/StdAfx.cpp | 93cd18a222bec9a2d920dc8235c7b0aa7a9cd162 | [] | no_license | tangooricha/tangoorichas-design-for-graduation | aefdd0fdf0e8786308c22311f2598ad62b3f5be8 | cf227651b9baa0deb5748a678553b145a3ce6803 | refs/heads/master | 2020-06-06T17:48:37.691814 | 2010-04-14T07:22:23 | 2010-04-14T07:22:23 | 34,887,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | // stdafx.cpp : source file that includes just the standard includes
// MailReceiver.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]@91cf4698-544a-0410-9e3e-f171e2291419"
] | [
[
[
1,
8
]
]
] |
8df3647ca52d50b5da9438ed9c256c01ee8f91f5 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/OneTimeTrigger.h | bd4b21e604d92546de98a7bf9c0ba389a38ede3e | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | #pragma once
#include "PuzzleEntity.h"
#include <Ogre.h>
#include <OgreNewt.h>
class GameServices;
class TriggerEvent;
class EventManager;
//This switch only fires once the first time it is touched, then becoming inactice indefinitely
class OneTimeTrigger : public PuzzleEntity { //kinda need access to protected members...
public:
OneTimeTrigger(GameServices *gs, OgreNewt::World* collisionWorld, Ogre::SceneNode *parentNode,
const Ogre::Vector3 &pos, const Ogre::Vector3 &size,
const Ogre::String &entityName, const Ogre::String &modelFile,
const Ogre::String &triggername, const int triggerID);
void onCollisionEntered(RigidModelEntity *colEntity);
protected:
bool mHasFired;
}; | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
19
]
]
] |
91e24f0399817a20709527fc02ec9056d35ae940 | 1736474d707f5c6c3622f1cd370ce31ac8217c12 | /PseudoUnitTest/TestStackWalk.hpp | 08ea809140a5e0c000aef48878bf3bf1d791d4bc | [] | no_license | arlm/pseudo | 6d7450696672b167dd1aceec6446b8ce137591c0 | 27153e50003faff31a3212452b1aec88831d8103 | refs/heads/master | 2022-11-05T23:38:08.214807 | 2011-02-18T23:18:36 | 2011-02-18T23:18:36 | 275,132,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | hpp | #include <Pseudo\StackWalk.hpp>
using namespace Pseudo;
BEGIN_TEST_CLASS(TestStackWalk)
BEGIN_TEST_METHODS
TEST_METHOD(Test)
END_TEST_METHODS
void C()
{
// TODO-johnls-3/24/2008: Why doesn't this work in release builds...?
#if DEBUG
ArrayList<StackFrame> stack;
StackWalker::get_StackWalker().GetStack(stack);
for (Int i = 0; i < stack.get_Count(); i++)
{
TEST_ASSERT(
(i < 4 && *stack[i].methodName != 0) || (i >= 4),
"Expect method names for at least first four methods on stack");
//Console::WriteLine(stack[i].methodName);
}
#endif
}
void B()
{
C();
}
void A()
{
B();
}
void Test()
{
A();
}
END_TEST_CLASS
| [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
cdd3788705f0e5892ae7a905af702c6eccf3498e | 96e96a73920734376fd5c90eb8979509a2da25c0 | /C3DE/GameMesh.h | 120649624876b907a60751aee0fd43b87431c3d3 | [] | no_license | lianlab/c3de | 9be416cfbf44f106e2393f60a32c1bcd22aa852d | a2a6625549552806562901a9fdc083c2cacc19de | refs/heads/master | 2020-04-29T18:07:16.973449 | 2009-11-15T10:49:36 | 2009-11-15T10:49:36 | 32,124,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | h | #ifndef GAME_MESH_H
#define GAME_MESH_H
#include "D3DMesh.h"
class GameMesh : public D3DMesh
{
public:
GameMesh(int a_meshId, int a_texId, bool a_calculateAABB = true);
~GameMesh();
void SetShaderHandlers();
//void UniformScale(float a_value);
void PreRender(Renderer * a_renderer);
void PosRender(Renderer * a_renderer);
protected:
D3DXHANDLE m_hTex;
D3DXHANDLE m_shaderAlpha;//galpha
};
#endif
| [
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
] | [
[
[
1,
34
]
]
] |
0c8db29aa9e824a5e3369939aeba57cba23a8e3a | b5b57f95c6ee44fbb7d9c8ddda870c5338359e01 | /weaponMeter.cpp | c57927b7d711655741e2e4d714b456628b83145d | [] | no_license | Objelisks/descendinghammer | bcaa81b086da65f4207339c2348cbcdb2c765e44 | 2cbd67bcfba5ee1008d58bde59cfee18f01166b6 | refs/heads/master | 2020-04-21T17:26:35.740409 | 2009-04-04T06:20:01 | 2009-04-04T06:20:01 | 32,121,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | cpp | #include "weaponMeter.h"
#include "gameState.h"
#include "vector"
#include "allegro.h"
WeaponVisual::WeaponVisual(std::string n, int* cool, int coolMax, RLE_SPRITE* img)
{
name = n;
cooldown = cool;
cooldownMax = coolMax;
image = img;
};
WeaponMeter::WeaponMeter(BITMAP *parentScreen, int x, int y)
{
weapons = std::vector<WeaponVisual>();
for(boost::ptr_vector<Weapon>::iterator iter=theState()->player.weapons.begin(); iter != theState()->player.weapons.end(); iter++)
{
weapons.insert(weapons.end(),WeaponVisual(iter->name,&iter->cooldown, iter->cooldownMax, get_rle_sprite(theState()->resources.images[iter->name.c_str()])));
}
m_subScreen = create_sub_bitmap(parentScreen,x,y,150,50*weapons.size());
};
void WeaponMeter::draw()
{
for(std::vector<WeaponVisual>::iterator iter=weapons.begin(); iter != weapons.end(); iter++)
{
int pos = iter-weapons.begin();
draw_rle_sprite(m_subScreen, iter->image, 15, 5+50*pos);
textout_ex(m_subScreen, font, iter->name.c_str(), 35, 15+50*pos, makecol(255,255,255), -1);
rect(m_subScreen, 25, 30+50*pos, 95, 38+50*pos, makecol(150,150,150));
rectfill(m_subScreen, 26, 31+50*pos, 26+((double)*iter->cooldown/(double)iter->cooldownMax)*69, 37+50*pos, makecol(200,20,0));
if(theState()->player.currentWeapon == pos)
{
rectfill(m_subScreen, 5, 25+50*pos, 9, 33+50*pos, makecol(200, 200, 20));
}
}
}; | [
"supertyrian@ae15d362-055d-11de-a1f0-819f45317607"
] | [
[
[
1,
38
]
]
] |
bec2ee8b05f899de6291811ca642f445151b0c08 | b822313f0e48cf146b4ebc6e4548b9ad9da9a78e | /KylinSdk/Client/Source/ChainFactor.h | af5651396145f13ccfd3fafc158bf994764e9813 | [] | no_license | dzw/kylin001v | 5cca7318301931bbb9ede9a06a24a6adfe5a8d48 | 6cec2ed2e44cea42957301ec5013d264be03ea3e | refs/heads/master | 2021-01-10T12:27:26.074650 | 2011-05-30T07:11:36 | 2011-05-30T07:11:36 | 46,501,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | h | #pragma once
#include "factor.h"
namespace Kylin
{
class ChainFactor : public Factor
{
public:
BtDeclareRTTI
Declare_Event_Handler(ChainFactor, Factor)
Declare_Entity_Creator(ChainFactor)
ChainFactor();
virtual KBOOL Init(const PropertySet& kProp);
protected:
virtual KVOID PostSpawn();
virtual KVOID PostDestroy();
};
} | [
"apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f"
] | [
[
[
1,
24
]
]
] |
07cf79ce52007bb96240c14472e75568734f049c | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_STableLocalNumeric.cpp | ddb9e158c8d08d5999ef1d828dbd5040cbb3e836 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,064 | cpp | // Aipi_STableLocalNumeric.cpp: implementation of the CAipi_STableLocalNumeric class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AIPI.h"
#include "Aipi_STableLocalNumeric.h"
#include "../MainFrm.h"
#include "../ChildFrm.h"
#include "../OutputTabView.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAipi_STableLocalNumeric::CAipi_STableLocalNumeric()
{
}
CAipi_STableLocalNumeric::~CAipi_STableLocalNumeric()
{
}
CAipi_STableLocalNumeric* CAipi_STableLocalNumeric::addSymbol(long iform, tstring name, int type, double val )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CAipi_STableLocalNumeric *pObject = new CAipi_STableLocalNumeric();
try
{
pObject->setSymbolName(name);
pObject->setSymbolType(type);
pObject->setSymbolValue(val);
pMainFrame->gmSTableLocalNumeric.insert(CMainFrame::g_mSTableLocalNumeric::value_type(iform, *pObject));
}
catch( CMemoryException* pErr)
{
AfxMessageBox(_T("Out of memory!!!"), MB_ICONSTOP | MB_OK);
if(pObject)
{
delete pObject;
pObject = NULL;
}
pErr->Delete();
}
return pObject;
}
double CAipi_STableLocalNumeric::findIdValue( long id )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
iter = pMainFrame->gmSTableLocalNumeric.find(id);
if( iter != pMainFrame->gmSTableLocalNumeric.end())
{
CAipi_STableLocalNumeric num = (CAipi_STableLocalNumeric)iter->second;
return num.getSymbolValue();
}
return NOT_FOUND;
}
int CAipi_STableLocalNumeric::findIdType( long id )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
iter = pMainFrame->gmSTableLocalNumeric.find(id);
if( iter != pMainFrame->gmSTableLocalNumeric.end())
{
CAipi_STableLocalNumeric num = (CAipi_STableLocalNumeric)iter->second;
return num.getSymbolType();
}
return NOT_FOUND;
}
tstring CAipi_STableLocalNumeric::findIdName( long id )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
iter = pMainFrame->gmSTableLocalNumeric.find(id);
if( iter != pMainFrame->gmSTableLocalNumeric.end())
{
CAipi_STableLocalNumeric num = (CAipi_STableLocalNumeric)iter->second;
return num.getSymbolName();
}
return _T("NOT_FOUND");
}
int CAipi_STableLocalNumeric::findSTableNumericMembers(long id)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
iter = pMainFrame->gmSTableLocalNumeric.find(id);
if( iter != pMainFrame->gmSTableLocalNumeric.end())
{
CAipi_STableLocalNumeric num = (CAipi_STableLocalNumeric)iter->second;
m_STLNumId = id;
m_STLNumName = num.getSymbolName();
m_STLNumType = num.getSymbolType();
m_STLNumValue = num.getSymbolValue();
return FOUND;
}
return NOT_FOUND;
}
void CAipi_STableLocalNumeric::eraseSTableNumeric(long id)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
iter = pMainFrame->gmSTableLocalNumeric.find(id);
if( iter != pMainFrame->gmSTableLocalNumeric.end())
{
pMainFrame->gmSTableLocalNumeric.erase(id);
}
}
void CAipi_STableLocalNumeric::editLastSTableNumericValue(double value)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
if( !pMainFrame->gmSTableLocalNumeric.empty())
{
iter = pMainFrame->gmSTableLocalNumeric.end();
--iter;
CAipi_STableLocalNumeric v = (CAipi_STableLocalNumeric)iter->second;
long id = iter->first;
tstring name = v.getSymbolName();
int type = v.getSymbolType();
double oldValue = v.getSymbolValue();
pMainFrame->gmSTableLocalNumeric.erase(id);
addSymbol(id, name, type, value);
CString str;
str.Format(_T("OLD VALUE %f" ), oldValue);
AfxMessageBox(str);
str.Format(_T("EDIT VALUE %f" ), value);
AfxMessageBox(str);
str.Format(_T("%d" ), id);
AfxMessageBox(str);
AfxMessageBox(name.data());
}
}
void CAipi_STableLocalNumeric::editSTableNumericValue(long id, double value)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mSTableLocalNumeric::iterator iter;
if( !pMainFrame->gmSTableLocalNumeric.empty())
{
int found = findSTableNumericMembers( id );
if( found != NOT_FOUND )
{
pMainFrame->gmSTableLocalNumeric.erase(id);
addSymbol(m_STLNumId, m_STLNumName, m_STLNumType, value);
CString str;
str.Format(_T("OLD VALUE %f" ), m_STLNumValue);
AfxMessageBox(str);
str.Format(_T("EDIT VALUE %f" ), value);
AfxMessageBox(str);
str.Format(_T("%d" ), m_STLNumId);
AfxMessageBox(str);
AfxMessageBox(m_STLNumName.data());
}
}
}
void CAipi_STableLocalNumeric::clearSTableNumeric()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->gmSTableLocalNumeric.clear();
}
int CAipi_STableLocalNumeric::sizeSTableNumeric()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
return pMainFrame->gmSTableLocalNumeric.size();
}
void CAipi_STableLocalNumeric::printSTableNumeric()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
TCHAR buffer[16];
pMainFrame->m_wndOutputTabView.AddMsg1(_T("******* LOCAL IDENTIFIER - Type Double *******"));
//Print map container
for( CMainFrame::g_mSTableLocalNumeric::const_iterator iter = pMainFrame->gmSTableLocalNumeric.begin(); iter!= pMainFrame->gmSTableLocalNumeric.end(); ++iter)
{
CString strID =_T("ID_");
CString strType =_T("TYPE_");
CString strValue = _T("VAL");
pMainFrame->m_wndOutputTabView.AddMsg1(_T("******* Local Id - TypeDouble *******"));
long id = iter->first;
CAipi_STableNumeric num = (CAipi_STableLocalNumeric)iter->second;
tstring name = num.getSymbolName();
int type = num.getSymbolType();
double value = num.getSymbolValue();
pMainFrame->m_wndOutputTabView.AddMsg1(_T("Identifier: "));
strID.Format(_T("%d" ), id);
pMainFrame->m_wndOutputTabView.AddMsg1(strID);
pMainFrame->m_wndOutputTabView.AddMsg1(_T("Name: "));
pMainFrame->m_wndOutputTabView.AddMsg1(name.data());
pMainFrame->m_wndOutputTabView.AddMsg1(_T("Type: "));
strType += _itot( type, buffer, 10 );
pMainFrame->m_wndOutputTabView.AddMsg1(strType);
pMainFrame->m_wndOutputTabView.AddMsg1(_T("Value: "));
strValue.Format(_T("%f" ), value);
pMainFrame->m_wndOutputTabView.AddMsg1(strValue);
}
}
| [
"[email protected]"
] | [
[
[
1,
280
]
]
] |
0ca4e2b2392eea06e3c11f0bec3d2908675db2ba | 25f79693b806edb9041e3786fa3cf331d6fd4b97 | /tests/unit/core/RuntimeTests.cpp | c1efdc58bc12e9ce576e36c461b2a59eacebd6f9 | [] | no_license | ouj/amd-spl | ff3c9faf89d20b5d6267b7f862c277d16aae9eee | 54b38e80088855f5e118f0992558ab88a7dea5b9 | refs/heads/master | 2016-09-06T03:13:23.993426 | 2009-08-29T08:55:02 | 2009-08-29T08:55:02 | 32,124,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | cpp | #include "CommonTestDefs.h"
#include "RuntimeTestFixture.h"
using namespace amdspl;
using namespace amdspl::core::cal;
TEST(RuntimeTests, RuntimeGetInstanceTest)
{
ASSERT_TRUE(Runtime::getInstance() != NULL);
}
TEST_F(RuntimeTestFixture, RuntimeGetDeviceManagerTest)
{
DeviceManager* _deviceMgr = _runtime->getDeviceManager();
ASSERT_TRUE(_deviceMgr != NULL);
}
TEST_F(RuntimeTestFixture, RuntimeGetBufferManagerTest)
{
BufferManager* _deviceMgr = _runtime->getBufferManager();
ASSERT_TRUE(_deviceMgr != NULL);
}
TEST_F(RuntimeTestFixture, RuntimeGetProgramManagerTest)
{
ProgramManager* _deviceMgr = _runtime->getProgramManager();
ASSERT_TRUE(_deviceMgr != NULL);
}
| [
"jiawei.ou@1960d7c4-c739-11dd-8829-37334faa441c"
] | [
[
[
1,
28
]
]
] |
7fbc42ccca9e4b384836b0ce98e54a8237b721d0 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /Tangram3D/inc/Tangram3DAppView.h | 724e4e23ed9a418d24dcb91a8e5bddb8ba2b45cc | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | h | /*
============================================================================
Name : Tangram3DAppView.h
Author :
Copyright : Your copyright notice
Description : Declares view class for application.
============================================================================
*/
#ifndef __TANGRAM3DAPPVIEW_h__
#define __TANGRAM3DAPPVIEW_h__
// INCLUDES
#include <coecntrl.h>
class CLT3DEngine;
// CLASS DECLARATION
class CTangram3DAppView : public CCoeControl
{
public:
// New methods
/**
* NewL.
* Two-phased constructor.
* Create a CTangram3DAppView object, which will draw itself to aRect.
* @param aRect The rectangle this view will be drawn to.
* @return a pointer to the created instance of CTangram3DAppView.
*/
static CTangram3DAppView* NewL(const TRect& aRect);
/**
* NewLC.
* Two-phased constructor.
* Create a CTangram3DAppView object, which will draw itself
* to aRect.
* @param aRect Rectangle this view will be drawn to.
* @return A pointer to the created instance of CTangram3DAppView.
*/
static CTangram3DAppView* NewLC(const TRect& aRect);
/**
* ~CTangram3DAppView
* Virtual Destructor.
*/
virtual ~CTangram3DAppView();
public:
// Functions from base classes
/**
* From CCoeControl, Draw
* Draw this CTangram3DAppView to the screen.
* @param aRect the rectangle of this view that needs updating
*/
void Draw(const TRect& aRect) const;
/**
* From CoeControl, SizeChanged.
* Called by framework when the view size is changed.
*/
virtual void SizeChanged();
/**
* From CoeControl, HandlePointerEventL.
* Called by framework when a pointer touch event occurs.
* Note: although this method is compatible with earlier SDKs,
* it will not be called in SDKs without Touch support.
* @param aPointerEvent the information about this event
*/
virtual void HandlePointerEventL(const TPointerEvent& aPointerEvent);
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType);
private:
// Constructors
/**
* ConstructL
* 2nd phase constructor.
* Perform the second phase construction of a
* CTangram3DAppView object.
* @param aRect The rectangle this view will be drawn to.
*/
void ConstructL(const TRect& aRect);
/**
* CTangram3DAppView.
* C++ default constructor.
*/
CTangram3DAppView();
static TInt DrawCallBack( TAny* aInstance );
private:
CLT3DEngine* iEngine;
CPeriodic* iPeriodic;
};
#endif // __TANGRAM3DAPPVIEW_h__
// End of File
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
101
]
]
] |
7005bfb09723e778a9f281c695a97a42048a2b86 | bf19f77fdef85e76a7ebdedfa04a207ba7afcada | /NewAlpha/TMNT Tactics Tech Demo/Source/Ninja.h | 3e5dc05f8cd8b1557e44e3d6a02975ac73f14844 | [] | no_license | marvelman610/tmntactis | 2aa3176d913a72ed985709843634933b80d7cb4a | a4e290960510e5f23ff7dbc1e805e130ee9bb57d | refs/heads/master | 2020-12-24T13:36:54.332385 | 2010-07-12T08:08:12 | 2010-07-12T08:08:12 | 39,046,976 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,471 | h | ////////////////////////////////////////////////////////
// File Name : "Ninja.h"
//
// Author : Matthew Di Matteo (MD)
//
// Purpose : To provide a game object to be used as an emeny
// against the user during the game.
////////////////////////////////////////////////////////
#ifndef NINJA_H
#define NINJA_H
#include "Base.h"
#include "CSGD_TextureManager.h"
#include "Player.h"
#include "Tile.h"
#include "Timer.h"
class CBitmapFont;
class CNinja : public CBase
{
private:
//set up integers to change state
int m_nAttack;
int m_nDefend;
int m_nLowHealth;
int m_nInRange;
int m_nTurtle; //store the turtle number id
int m_nXChange; //difference in x between turtle and ninja
int m_nYChange; //difference in y between turtle and ninja
CPlayer* m_pPlayer; //pointer to player
CTile* m_pTile; //pointer to tile
CBattleMap* m_pBattleMap;
vector<POINT> m_vPath; //path to take
MY_POINT_FLOAT m_ptStartXY; //point for movement
bool m_bMoving;
bool m_bMovingDone;
bool m_bAttackBool;
//float m_fTimer;
int m_nTotalAttacks;
int m_nAttacksSoFar;
int m_nDamage;
CTimer m_Timer;
CBitmapFont* m_pBitmapFont;
int Random(int min, int max)
{
int number = 0;
number = abs(max) - abs(min);
number = ((rand()%number) + abs(min));
if(rand() % 2 == 0)
number = -number;
return number;
}
public:
///////////////////////////////////////////////////////////////////
// Function: "CNinja(Constructor)"
///////////////////////////////////////////////////////////////////
CNinja(void);
///////////////////////////////////////////////////////////////////
// Function: "~CNinja(Destructor)"
///////////////////////////////////////////////////////////////////
~CNinja(void);
////////////////////////////////////////////////////////////////////
// Function: “AI”
//
// Purpose: Function to handle artificial intelligence of the object.
////////////////////////////////////////////////////////////////////
void AI();
/////////////////////////////////////////////////////////////////////
// Function : "FindPath"
//
// Purpose : Function to handle the path finding for the ninja
/////////////////////////////////////////////////////////////////////
void FindPath(POINT begin, POINT end);
////////////////////////////////////////////////////////////////////
// Function: “Update”
//
// Purpose: Updates game objects based on time.
////////////////////////////////////////////////////////////////////
void Update(float fElapsedTime);
////////////////////////////////////////////////////////////////////
// Function: “Render”
//
// Purpose: Draws game objects to the screen.
////////////////////////////////////////////////////////////////////
void Render();
////////////////////////////////////////////////////////////////////
// Function: Accessor and Mutator
////////////////////////////////////////////////////////////////////
inline int GetInRange(void) { return m_nInRange; }
inline void SetInRange(int set) { m_nInRange = set; }
inline int GetXDifference(void) { return m_nXChange; }
inline void SetXDifference(int set) { m_nXChange = set; }
inline int GetYDifference(void) { return m_nYChange; }
inline void SetYDifference(int set) { m_nYChange = set; }
inline int GetTurtle(void) { return m_nTurtle; }
void SetLevel(int nLevel);
};
#endif | [
"AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"jsierra099@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"marvelman610@7dc79cba-3e6d-11de-b8bc-ddcf2599578a"
] | [
[
[
1,
14
],
[
20,
30
],
[
38,
38
],
[
42,
42
],
[
56,
83
],
[
91,
107
],
[
118,
119
]
],
[
[
15,
16
],
[
31,
37
],
[
39,
41
],
[
84,
90
],
[
108,
115
]
],
[
[
17,
19
],
[
43,
55
],
[
116,
117
]
]
] |
5ca1ff7af79ed4437623b0d5a2aa8f207f955f46 | 8342f87cc7e048aa812910975c68babc6fb6c5d8 | /include/OIS/linux/LinuxKeyboard.h | 8f59eb7f8a1facc666a41be323a7df0b0e9b31d2 | [] | no_license | espes/hoverrace | 1955c00961af4bb4f5c846f20e65ec9312719c08 | 7d5fd39ba688e2c537f35f7c723dedced983a98c | refs/heads/master | 2021-01-23T13:23:03.710443 | 2010-12-19T22:26:12 | 2010-12-19T22:26:12 | 2,005,364 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,490 | h | /*
The zlib/libpng License
Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef _LINUX_KEYBOARD_H_EADER_
#define _LINUX_KEYBOARD_H_EADER_
#include "linux/LinuxPrereqs.h"
#include "OISKeyboard.h"
#include <X11/Xlib.h>
namespace OIS
{
/** Linux implementation of Keyboard object - uses x11 */
class LinuxKeyboard : public Keyboard
{
public:
LinuxKeyboard(InputManager* creator, bool buffered, bool grab, bool useXRepeat );
virtual ~LinuxKeyboard();
/** @copydoc Keyboard::isKeyDown */
virtual bool isKeyDown( KeyCode key );
/** @copydoc Keyboard::getAsString */
virtual const std::string& getAsString( KeyCode kc );
/** @copydoc Keyboard::copyKeyStates */
virtual void copyKeyStates( char keys[256] );
/** @copydoc Object::setBuffered */
virtual void setBuffered(bool buffered);
/** @copydoc Object::capture */
virtual void capture();
/** @copydoc Object::queryInterface */
virtual Interface* queryInterface(Interface::IType) {return 0;}
/** @copydoc Object::_initialize */
virtual void _initialize();
protected:
bool _injectKeyDown( KeySym key, int text );
bool _injectKeyUp( KeySym key );
//! 1:1 Conversion Map between X Key Events and OIS KeyCodes
typedef std::map<KeySym, KeyCode> XtoOIS_KeyMap;
XtoOIS_KeyMap keyConversion;
//! Depressed Key List
char KeyBuffer[256];
//! X11 Stuff
Window window;
Display *display;
bool grabKeyboard;
bool keyFocusLost;
bool xAutoRepeat;
bool oldXAutoRepeat;
std::string mGetString;
};
}
#endif //_LINUX_KEYBOARD_H_EADER_
| [
"ryan@7d5085ce-8879-48fc-b0cc-67565f2357fd"
] | [
[
[
1,
84
]
]
] |
3e22b059ad803187a771135d8d67f3460cf852de | dde32744a06bb6697823975956a757bd6c666e87 | /bwapi/SCProjects/BTHAIModule/Source/HydraliskAgent.h | a503ac0caf05cb269e890a2abafc788bed346678 | [] | 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 | 557 | h | #ifndef __HYDRALISKAGENT_H__
#define __HYDRALISKAGENT_H__
#include <BWAPI.h>
#include "UnitAgent.h"
using namespace BWAPI;
using namespace std;
/** The HydraliskAgent handles Zerg Hydralisk units.
*
* Author: Johan Hagelback ([email protected])
*/
class HydraliskAgent : public UnitAgent {
private:
Unit* findTarget();
public:
HydraliskAgent(Unit* mUnit);
/** Called each update to issue orders. */
void computeActions();
/** Returns the unique type name for unit agents. */
string getTypeName();
};
#endif | [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
986893ef8985aba640afbdf861d729a4ed7cba26 | 3a103ad1fc799ce85943c78bcaf092e34208c0e2 | /Include/Assignment3.h | 15dd46e02fab5274a6917eaa98e2714c0b8901cc | [] | no_license | whirlp00l/rendering | 2e93d5c6835e054e85f9710efac27de938cae445 | 770c2ad19b62fd8dce86ff0ebf2c7ffc829893ca | refs/heads/master | 2020-05-16T23:19:16.307640 | 2010-10-20T22:36:47 | 2010-10-20T22:36:47 | 37,064,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | #ifndef CSE168_ASSIGNMENT_3_H_INCLUDED
#define CSE168_ASSIGNMENT_3_H_INCLUDED
#include "Material.h"
class Assignment3
{
public:
Assignment3();
virtual ~Assignment3();
void makeCornellScene();
void makeCornellSceneWithSpheres();
void makeTeapotScene( Material::Type teapotMaterialType );
void makeMultipleTeapotsScene();
void make3TeapotsScene();
void makeSphereScene();
};
#endif // CSE168_ASSIGNMENT_3_H_INCLUDED | [
"DaStar2B@82a46b14-ece5-f9c8-6756-62631a89e06b"
] | [
[
[
1,
20
]
]
] |
d96aae888e6b5ac41d3845a2355d663069a2f29a | 17083b919f058848c3eb038eae37effd1a5b0759 | /SimpleGL/src/GL/GLFont.cpp | b6015d8992e688ce7f04e6e205e4eceb4df2b10d | [] | no_license | BackupTheBerlios/sgl | e1ce68dfc2daa011bdcf018ddce744698cc7bc5f | 2ab6e770dfaf5268c1afa41a77c04ad7774a70ed | refs/heads/master | 2021-01-21T12:39:59.048415 | 2011-10-28T16:14:29 | 2011-10-28T16:14:29 | 39,894,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,752 | cpp | #include "GL/GLCommon.h"
#include "GL/GLDevice.h"
#include "GL/GLFont.h"
#include "Math/Containers.hpp"
#include "Math/Matrix.hpp"
namespace {
using namespace sgl;
using namespace std;
using namespace math;
const char* font_vertex_shader = "\
uniform mat4 mvp;\
\
attribute vec4 position;\
attribute vec2 texcoord;\
\
varying vec2 fp_texcoord;\
\
void main()\
{\
fp_texcoord = texcoord;\
gl_Position = mvp * position;\
}";
const char* font_fragment_shader = "\
uniform vec4 color;\
uniform sampler2D texture;\
\
varying vec2 fp_texcoord;\
\
void main()\
{\
gl_FragColor = color * texture2D(texture, fp_texcoord);\
}";
} // anonymous namespace
namespace sgl {
GLFont::GLFont(GLDevice* device_) :
device(device_)
{
{
RasterizerState::DESC desc;
desc.colorMask = RasterizerState::RGBA;
desc.cullMode = RasterizerState::NONE;
desc.fillMode = RasterizerState::SOLID;
rasterizerState.reset( device->CreateRasterizerState(desc) );
}
{
BlendState::DESC_SIMPLE desc;
desc.blendEnable = true;
desc.srcBlend = BlendState::ONE;
desc.destBlend = BlendState::ONE_MINUS_SRC_ALPHA;
desc.blendOp = BlendState::ADD;
blendState.reset( device->CreateBlendState(Extend(desc)) );
}
{
DepthStencilState::DESC desc;
desc.depthEnable = false;
desc.depthWriteMask = 0;
desc.stencilEnable = false;
depthStencilState.reset( device->CreateDepthStencilState(desc) );
}
vbo.reset( device->CreateVertexBuffer() );
if (!vbo) {
throw gl_error("Can't create vertex buffer for font rendering.");
}
const size_t maxStrLength = 1024;
const size_t bufSize = maxStrLength * 96 * sizeof(float);
if ( SGL_OK != vbo->SetData(bufSize, 0, Buffer::DYNAMIC_DRAW) ) {
throw gl_error("Can't allocate vertex buffer for font rendering.");
}
}
GLFont::~GLFont()
{
}
SGL_HRESULT GLFont::SetTexture(sgl::Texture2D* texture_)
{
texture.reset(texture_);
if (texture)
{
bool haveMipmaps = true;
SGL_HRESULT result = texture->GenerateMipmap();
if (SGL_OK != result) {
haveMipmaps = false;
}
SamplerState::DESC desc;
desc.filter[0] = SamplerState::LINEAR;
desc.filter[1] = SamplerState::LINEAR;
desc.filter[2] = haveMipmaps ? SamplerState::LINEAR : SamplerState::NONE;
desc.wrapping[0] = SamplerState::REPEAT;
desc.wrapping[1] = SamplerState::REPEAT;
texture->BindSamplerState( device->CreateSamplerState(desc) );
}
return SGL_OK;
}
void GLFont::Print(float x, float y, const char* str) const
{
data.clear();
{
math::Matrix4f transform(charWidth, 0.0f, 0.0f, x,
0.0f, charHeight, 0.0f, y,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
math::Vector4f position[6];
{
position[0] = math::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);
position[1] = math::Vector4f(1.0f, 0.0f, 0.0f, 1.0f);
position[2] = math::Vector4f(1.0f, 1.0f, 0.0f, 1.0f);
position[3] = math::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);
position[4] = math::Vector4f(1.0f, 1.0f, 0.0f, 1.0f);
position[5] = math::Vector4f(0.0f, 1.0f, 0.0f, 1.0f);
}
math::Vector2f texcoord[6];
for(; *str; ++str)
{
if (*str == '\n')
{
transform[0][3] = x;
transform[1][3] += charHeight;
}
else if (*str == '\r')
{
transform[0][3] = x;
}
else if (*str == '\t')
{
transform[0][3] += charWidth * 2.0f;
}
else if (*str == ' ')
{
transform[0][3] += charWidth * 0.5f;
}
else
{
unsigned char c = *reinterpret_cast<const unsigned char*>(str);
const float ds = 1.0f / 16.0f;
const float dt = 1.0f / 16.0f;
float s = float(c % 16) / 16.0f;
float t = float(c / 16) / 16.0f;
texcoord[0] = math::Vector2f(s, t);
texcoord[1] = math::Vector2f(s + ds, t);
texcoord[2] = math::Vector2f(s + ds, t + dt);
texcoord[3] = math::Vector2f(s, t);
texcoord[4] = math::Vector2f(s + ds, t + dt);
texcoord[5] = math::Vector2f(s, t + dt);
for (int j = 0; j<6; ++j)
{
math::Vector4f pos = transform * position[j];
data.push_back(pos.x);
data.push_back(pos.y);
data.push_back(pos.z);
data.push_back(pos.w);
data.push_back(texcoord[j].x);
data.push_back(texcoord[j].y);
}
transform[0][3] += charWidth * 0.666667f;
}
}
}
size_t bufSize = data.size() * sizeof(float);
if ( bufSize > vbo->Size() ) {
vbo->SetData(bufSize, &data[0], Buffer::DYNAMIC_DRAW);
}
else {
vbo->SetSubData(0, bufSize, &data[0]);
}
device->Draw(TRIANGLES, 0, data.size() / 6);
}
sgl::Texture2D* GLFont::Texture() const
{
return texture.get();
}
GLFontFixed::GLFontFixed(GLDevice* device) :
GLFont(device)
{
// create states
ffpProgram.reset( device->FixedPipelineProgram() );
projectionMatrixUniform = ffpProgram->GetProjectionMatrixUniform();
modelViewMatrixUniform = ffpProgram->GetModelViewMatrixUniform();
lightingEnableUniform = ffpProgram->GetLightingToggleUniform();
ambientUniform = ffpProgram->GetAmbientUniform();
materialAmbientUniform = ffpProgram->GetMaterialAmbientUniform();
{
VertexLayout::ELEMENT elements[] =
{
{0, 4, 0, 24, sgl::FLOAT, VertexLayout::VERTEX},
{0, 2, 16, 24, sgl::FLOAT, VertexLayout::TEXCOORD}
};
vertexLayout.reset( device->CreateVertexLayout(2, elements) );
}
}
SGL_HRESULT GLFontFixed::SetTexture(sgl::Texture2D* texture)
{
SGL_HRESULT result = GLFont::SetTexture(texture);
if (SGL_OK != result) {
return result;
}
return SGL_OK;
}
SGL_HRESULT GLFontFixed::Bind(int width, int height, const math::Vector4f& color) const
{
rectangle vp = device->Viewport();
vpWidth = float(vp.width);
vpHeight = float(vp.height);
charWidth = float(width);
charHeight = float(height);
// setup states
projectionMatrix = projectionMatrixUniform->Value();
modelViewMatrix = modelViewMatrixUniform->Value();
modelViewMatrixUniform->Set( Matrix4f::identity() );
projectionMatrixUniform->Set( Matrix4f::ortho( 0.0f, vpWidth,
vpHeight, 0.0f,
-1.0f, 1.0f ) );
device->PushState(State::RASTERIZER_STATE);
device->PushState(State::DEPTH_STENCIL_STATE);
device->PushState(State::BLEND_STATE);
ffpProgram->Bind();
rasterizerState->Bind();
depthStencilState->Bind();
blendState->Bind();
vbo->Bind( vertexLayout.get() );
return texture->Bind(0);
}
void GLFontFixed::Unbind() const
{
vbo->Unbind();
texture->Unbind();
device->PopState(State::RASTERIZER_STATE);
device->PopState(State::DEPTH_STENCIL_STATE);
device->PopState(State::BLEND_STATE);
projectionMatrixUniform->Set(projectionMatrix);
modelViewMatrixUniform->Set(modelViewMatrix);
}
GLFontProgrammable::GLFontProgrammable(GLDevice* device) :
GLFont(device)
{
// create states
program.reset( device->CreateProgram() );
{
Shader::DESC desc;
desc.source = font_vertex_shader;
desc.type = Shader::VERTEX;
sgl::Shader* vertexShader = device->CreateShader(desc);
if (!vertexShader) {
throw gl_error("GLFont::GLFont failed. Can't create vertex shader for font.");
}
desc.source = font_fragment_shader;
desc.type = Shader::FRAGMENT;
sgl::Shader* fragmentShader = device->CreateShader(desc);
if (!fragmentShader) {
throw gl_error("GLFont::GLFont failed. Can't create fragment shader for font.");
}
program->AddShader(vertexShader);
program->AddShader(fragmentShader);
if ( SGL_OK != program->Dirty() ) {
throw gl_error("GLFont::GLFont failed. Can't create shader program for font.");
}
}
textureUniform = program->GetSamplerUniform2D("texture");
colorUniform = program->GetUniform4F("color");
mvpUniform = program->GetUniform4x4F("mvp");
// create vertex layout
{
int positionLoc = program->AttributeLocation("position");
if (positionLoc == -1) {
throw gl_error("GLFont::GLFont failed. Can't get location of font attribute.");
}
int texcoordLoc = program->AttributeLocation("texcoord");
if (texcoordLoc == -1) {
throw gl_error("GLFont::GLFont failed. Can't get location of font attribute.");
}
VertexLayout::ELEMENT elements[] =
{
{positionLoc, 4, 0, 24, sgl::FLOAT, VertexLayout::ATTRIBUTE},
{texcoordLoc, 2, 16, 24, sgl::FLOAT, VertexLayout::ATTRIBUTE},
};
vertexLayout.reset( device->CreateVertexLayout(2, elements) );
}
}
SGL_HRESULT GLFontProgrammable::Bind(int width, int height, const math::Vector4f& color) const
{
rectangle vp = device->Viewport();
vpWidth = float(vp.width);
vpHeight = float(vp.height);
charWidth = float(width);
charHeight = float(height);
program->Bind();
colorUniform->Set(color);
textureUniform->Set( 0, texture.get() );
mvpUniform->Set( Matrix4f::ortho( 0.0f, vpWidth,
vpHeight, 0.0f,
-1.0f, 1.0f ) );
device->PushState(State::RASTERIZER_STATE);
device->PushState(State::DEPTH_STENCIL_STATE);
device->PushState(State::BLEND_STATE);
rasterizerState->Bind();
depthStencilState->Bind();
blendState->Bind();
vbo->Bind( vertexLayout.get() );
return SGL_OK;
}
void GLFontProgrammable::Unbind() const
{
vbo->Unbind();
texture->Unbind();
device->PopState(State::RASTERIZER_STATE);
device->PopState(State::DEPTH_STENCIL_STATE);
device->PopState(State::BLEND_STATE);
program->Unbind();
}
} // namespace sgl
| [
"devnull@localhost"
] | [
[
[
1,
361
]
]
] |
d4a00903caa8617ab2f1199c7c85c3202851a278 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/test/conditioning_class_c.cpp | 7bf42e2ecebd6ede13d5398d961187789564da84 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,513 | cpp | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#include <sstream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <dlib/conditioning_class.h>
#include "tester.h"
#include "conditioning_class.h"
namespace
{
class conditioning_class_tester : public tester
{
public:
conditioning_class_tester (
) :
tester ("test_conditioning_class_c",
"Runs tests on the conditioning_class checked components.")
{}
void perform_test (
)
{
dlog << LINFO << "testing kernel_1a_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_1a_c,
conditioning_class<2>::kernel_1a_c
>();
print_spinner();
dlog << LINFO << "testing kernel_2a_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_2a_c,
conditioning_class<2>::kernel_2a_c
>();
print_spinner();
dlog << LINFO << "testing kernel_3a_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_3a_c,
conditioning_class<2>::kernel_3a_c
>();
print_spinner();
dlog << LINFO << "testing kernel_4a_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_4a_c,
conditioning_class<2>::kernel_4a_c
>();
print_spinner();
dlog << LINFO << "testing kernel_4b_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_4b_c,
conditioning_class<2>::kernel_4b_c
>();
print_spinner();
dlog << LINFO << "testing kernel_4c_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_4c_c,
conditioning_class<2>::kernel_4c_c
>();
print_spinner();
dlog << LINFO << "testing kernel_4d_c";
conditioning_class_kernel_test<
conditioning_class<256>::kernel_4d_c,
conditioning_class<2>::kernel_4d_c
>();
print_spinner();
}
} a;
}
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
87
]
]
] |
999b1c797914bf2d0e68d0cf8ec31c050b9c8340 | d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18 | /source/server/ents/baseworld.h | 46b53573796f86bbba31086a2eba362619031a81 | [] | no_license | ferhan66h/Xash3D_ancient | 7491cd4ff1c7d0b48300029db24d7e08ba96e88a | 075e0a6dae12a0952065eb9b2954be4a8827c72f | refs/heads/master | 2021-12-10T07:55:29.592432 | 2010-05-09T00:00:00 | 2016-07-30T17:37:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | //=======================================================================
// Copyright (C) XashXT Group 2006
//=======================================================================
#ifndef BASEWORLD_H
#define BASEWORLD_H
class CWorld : public CBaseEntity
{
public:
void Spawn( void );
void Precache( void );
void KeyValue( KeyValueData *pkvd );
void PostActivate( void );
};
extern BOOL g_startSuit;
extern CWorld *g_pWorld;
#endif //BASEWORLD_H | [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
c44aca3065af6c4ef605d51170bd36f15bb28f0c | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/AuctionHouse.cpp | dd2bbaf24d815aace2767d5dcef3b1250a5c8069 | [
"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 | 21,618 | 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"
AuctionHouse::AuctionHouse(uint32 aid,uint32 entry,uint32 c, uint32 t)
{
Id = aid;
tax = t;
cut = c;
auctioneerentry = entry;
maxId = 0;
LoadFromDB();
LoadMaxId();
}
AuctionHouse::~AuctionHouse()
{
}
void WorldSession::HandleAuctionListBidderItems( WorldPacket & recv_data )
{
CHECK_PACKET_SIZE(recv_data, 16);
uint64 guid;
//uint32 unk1,unk2;
recv_data >> guid;// >> unk1 >> unk2;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
WorldPacket out = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry())->GenerateBidderList(GetPlayer());
SendPacket(&out);
}
AuctionSystem::AuctionSystem()
{
this->ThreadType = WOWD_THREADTYPE_AUCTIONHOUSE;
}
void AuctionSystem::run()
{
SetThreadName("Auction House Operations");
WOWD_THREAD_TRY_EXECUTION2
int count = 0;
while(this->ThreadState != WOWD_THREADSTATE_TERMINATE)
{
if(ThreadState == WOWD_THREADSTATE_TERMINATE)
return;
ThreadState = WOWD_THREADSTATE_BUSY;
count++;
if(count == 30) // every 60 sec
{
count = 0;
sAuctionMgr.Update();
}
if(ThreadState == WOWD_THREADSTATE_TERMINATE)
return;
ThreadState = WOWD_THREADSTATE_SLEEPING;
Sleep(2000);//update Auctions each minute
}
WOWD_THREAD_HANDLE_CRASH2
}
void AuctionHouse::UpdateAuction(uint32 id)
{
AuctionEntry *ae = GetAuction(id);
if(ae)
{
if (time(NULL) > (ae->time))
{
if (ae->bidder == 0)
RemoveAuction(ae->Id,AUCTION_REMOVE_EXPIRED);
else
RemoveAuction(ae->Id,AUCTION_REMOVE_WON);
}
}
}
void AuctionHouse::Update()
{
std::map<uint32,AuctionEntry*>::iterator itr,next;
for (itr = GetAuctionsBegin(); itr != GetAuctionsEnd();itr = next)
{
next = itr;
next++;
UpdateAuction(itr->second->Id);
}
}
AuctionEntry* AuctionHouse::GetAuction(uint32 id)
{
std::map<uint32,AuctionEntry*>::iterator iter;
iter = Auctions.find(id);
if(iter != Auctions.end())
return iter->second;
return NULL;
}
void AuctionHouse::RemoveAuction(uint32 id,uint32 reason)
{
std::map<uint32,AuctionEntry*>::iterator itr;
itr = Auctions.find(id);
char sub[64];
if(reason == AUCTION_REMOVE_EXPIRED)
{
sprintf(sub,"%u:%u:%u",objmgr.GetAItem(itr->second->item)->GetEntry(),0,AUCTION_EXPIRED);
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->owner, sub, "", 0, 0, itr->second->item,62);
//SendMailToPlayer(itr->second->owner,itr->second->owner,sub,"",0,0,objmgr.GetAItem(itr->second->item),62,AUCTION,GetId());
}
else if (reason == AUCTION_REMOVE_WON)
{
Player *pl = sObjHolder.GetObject<Player>(itr->second->bidder);
if(pl)
pl->GetSession()->SendPacket(&BuildBidderNotificationPacket(itr->second));
sprintf(sub,"%u:%u:%u",objmgr.GetAItem(itr->second->item)->GetEntry(),0,AUCTION_SOLD);
//sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->bidder, sub, "", 0, 0, itr->second->item, 62);
//SendMailToPlayer(itr->second->bidder,itr->second->owner,sub,"",itr->second->bid-((cut / 100.0f)*objmgr.GetAItem(itr->second->item)->GetProto()->SellPrice)+itr->second->deposit,0,NULL,62,AUCTION,GetId());
uint32 amount = itr->second->bid-((cut / 100.0f)*objmgr.GetAItem(itr->second->item)->GetProto()->SellPrice)+itr->second->deposit;
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->owner, sub, "", amount, 0, 0, 62);
sprintf(sub,"%u:%u:%u",objmgr.GetAItem(itr->second->item)->GetEntry(),0,AUCTION_WON);
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->bidder, sub, "", 0, 0, itr->second->item, 62);
//SendMailToPlayer(itr->second->owner,itr->second->bidder,sub,"",0,0,objmgr.GetAItem(itr->second->item),62,AUCTION,GetId());
} else if (reason == AUCTION_REMOVE_CANCELLED)
{
Player *pl = sObjHolder.GetObject<Player>(itr->second->owner);
if(pl)
if(pl->GetUInt32Value(PLAYER_FIELD_COINAGE) > floor(((cut / 100.0f)*itr->second->bid)))
pl->SetUInt32Value(PLAYER_FIELD_COINAGE,pl->GetUInt32Value(PLAYER_FIELD_COINAGE) - floor(((cut / 100.0f)*itr->second->bid)));
else
return;
else
return;
sprintf(sub,"%u:%u:%u",objmgr.GetAItem(itr->second->item)->GetEntry(),0,AUCTION_CANCELLED);
if(itr->second->bidder)
{
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->owner, sub, "", itr->second->bid, 0, itr->second->item, 62);
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->owner, sub, "", itr->second->bid, 0, 0, 62);
//SendMailToPlayer(itr->second->owner,itr->second->owner,sub,"",itr->second->bid,0,objmgr.GetAItem(itr->second->item),62,AUCTION,GetId());
//SendMailToPlayer(itr->second->bidder,itr->second->owner,sub,"",itr->second->bid,0,NULL,62,AUCTION,GetId());
}
else
{
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), itr->second->owner, sub, "", 0, 0, itr->second->item, 62);
//SendMailToPlayer(itr->second->owner,itr->second->owner,sub,"",0,0,objmgr.GetAItem(itr->second->item),62,AUCTION,GetId());
}
}
sDatabase.Execute("DELETE FROM auctions WHERE auctionId = %u", itr->second->Id);
sDatabase.Execute("DELETE FROM bids WHERE ID = %u", itr->second->Id );
objmgr.RemoveAItem(itr->second->item);
if(itr != Auctions.end())
Auctions.erase(itr);
}
void AuctionHouse::SaveAuction(AuctionEntry* auction)
{
std::stringstream sql;
sql << "INSERT INTO auctions SET auctionId = '" << auction->Id << "', auctionhouse = '" << auction->auctionhouse << "', item = '" << auction->item << "', owner = '" << auction->owner << "', buyout = '" << auction->buyout << "', time = '" << auction->time << "', bidder = '" << auction->bidder << "', bid = '" << auction->bid << "', deposit = '" << auction->deposit << "'";
sDatabase.Execute("DELETE FROM auctions WHERE auctionId = %u", auction->Id);
sDatabase.Execute(sql.str().c_str());
}
void AuctionHouse::PlaceBid(WorldPacket &recv_data, Player *pl)
{
uint32 auction,price;
recv_data >> auction >> price;
AuctionEntry* ah = GetAuction(auction);
char sub[64];
if(!ah) return;
if (ah->owner != pl->GetGUID())
{
if (ah->bidder != 0)
{
sprintf(sub,"%u:%u:%u",objmgr.GetAItem(ah->item)->GetEntry(),0,AUCTION_CANCELLED);
sMailSystem.SendAutomatedMessage(AUCTION, GetId(), ah->bidder, sub, "", ah->bid, 0, 0, 62);
//SendMailToPlayer(ah->owner,ah->bidder,sub,"",ah->bid,0,NULL,62,AUCTION,GetId());
}
ah->bidder = pl->GetGUID();
ah->bid = price;
pl->SetUInt32Value(PLAYER_FIELD_COINAGE,(pl->GetUInt32Value(PLAYER_FIELD_COINAGE) - price));
if (((price < ah->buyout) || (ah->buyout == 0)))
{
bidentry *be = new bidentry;
be->AuctionID = auction;
be->amt = price;
be->AHid = GetId();
pl->AddBid(be);
}
else
{
pl->GetSession()->SendPacket(&BuildResultPacket(ah->Id,AUCTION_BID));
RemoveAuction(ah->Id,AUCTION_REMOVE_WON);
return;
}
}
UpdateAuction(auction);
SaveAuction(ah);
pl->GetSession()->SendPacket(&BuildResultPacket(ah->Id,AUCTION_BID));
}
WorldPacket AuctionHouse::AddAuctionToPacket(WorldPacket data,AuctionEntry* ae,Item* it)
{
data << ae->Id;
data << it->GetUInt32Value(OBJECT_FIELD_ENTRY);
for (uint32 i = 0; i < 6; i++)
{
data << (uint32)it->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + (3 * i)); // Enchantment ID
data << (uint32)it->GetEnchantmentApplytime(i); // Unknown / maybe ApplyTime
data << (uint32)it->GetUInt32Value(ITEM_FIELD_SPELL_CHARGES + i); // Charges
}
data << (uint32)it->GetUInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID); // -ItemRandomSuffix / random property : If the value is negative its ItemRandomSuffix if its possitive its RandomItemProperty
data << (uint32)0; // when ItemRandomSuffix is used this is the modifier
/**Capt: ****************** ItemRandomSuffix***************************
* For what I have seen ItemRandomSuffix is like RandomItemProperty
* The only difference is has is that it has a modifier.
* That is the result of jewelcrafting, the effect is that the
* enchantment is variable. That means that a enchantment can be +1 and
* with more Jem's +12 or so.
* Decription for lookup: You get the enchantmentSuffixID and search the
* DBC for the last 1 - 3 value's(depending on the enchantment).
* That value is what I call EnchantmentValue. You guys might find a
* better name but for now its good enough. The formula to calculate
* The ingame "GAIN" is:
* (Modifier / 10000) * enchantmentvalue = EnchantmentGain;
*/
data << uint32(it->GetUInt32Value(ITEM_FIELD_STACK_COUNT)); // Amount
data << uint32(0); // Unknown
data << uint32(0); // Unknown
data << ae->owner; // Owner guid
data << ae->bid; // Current prize
// hehe I know its evil, this creates a nice trough put of money
data << uint32(50); // Next bid value modifier, like current bid + this value
data << ae->buyout; // Buyout
data << uint32((ae->time - time(NULL)) * 1000); // Time left
data << uint64(ae->bidder); // Last bidder
data << ae->bid; // The bid of the last bidder
return data;
}
WorldPacket AuctionHouse::GenerateBidderList(Player *pl)
{
WorldPacket data;
std::list<bidentry*>::iterator itr;
std::list<bidentry*>tempList;
for (itr = pl->GetBidBegin(); itr != pl->GetBidEnd(); itr++)
{
AuctionEntry* ae = GetAuction((*itr)->AuctionID);
if(ae)
{
if(ae->auctionhouse == GetId())
{
tempList.push_back((*itr));
}
}
}
data.Initialize( SMSG_AUCTION_BIDDER_LIST_RESULT );
data << uint32(tempList.size());
for (itr = tempList.begin(); itr != tempList.end(); itr++)
{
AuctionEntry *ae = GetAuction((*itr)->AuctionID);
Item *it = objmgr.GetAItem(ae->item);
data = AddAuctionToPacket(data,ae,it);
}
return data;
}
WorldPacket AuctionHouse::BuildBidderNotificationPacket(AuctionEntry* ac)
{
uint32 unk1,unk2,unk3;
unk1 = 0;
unk2 = 0;
unk3 = 0;
WorldPacket data;
data.Initialize(SMSG_AUCTION_BIDDER_NOTIFICATION);
data << uint32(this->GetId());
data << uint32(ac->Id);
data << uint64(ac->bidder);
data << uint32(unk1);
data << uint32(unk2);
data << uint32(objmgr.GetAItem(ac->item)->GetEntry());
data << uint32(unk3);
return data;
}
WorldPacket AuctionHouse::BuildResultPacket(uint32 aid,uint32 result)
{
WorldPacket data;
data.Initialize(SMSG_AUCTION_COMMAND_RESULT);
data << uint32(aid);
if(result != AUCTION_BUYOUT)
data << uint32(result);
else
data << uint32(result-1);
data << uint32(0);
if(result == AUCTION_BUYOUT)
data << uint32(0);
return data;
}
void WorldSession::HandleAuctionPlaceBid( WorldPacket & recv_data )
{
CHECK_PACKET_SIZE(recv_data, 8);
uint64 guid;
recv_data >> guid;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry())->PlaceBid(recv_data,GetPlayer());
WorldPacket out = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry())->GenerateBidderList(GetPlayer());
SendPacket(&out);
}
void AuctionHouse::LoadMaxId()
{
std::stringstream sql;
QueryResult* result;
sql << "SELECT MAX(auctionId) FROM auctions WHERE auctionhouse = '" << GetId() << "'";
result = sDatabase.Query( sql.str().c_str() );
if( result )
{
maxId = result->Fetch()[0].GetUInt32()+1;
delete result;
}
else
{
maxId = 0;
}
}
void WorldSession::HandleCancelAuction( WorldPacket & recv_data)
{
CHECK_PACKET_SIZE(recv_data, 12);
uint32 auctionID;
uint64 guid;
recv_data >> guid;
recv_data >> auctionID;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
if(!auctioneer) return;
AuctionHouse *AH = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry());
if(!AH) return;
AH->RemoveAuction(auctionID,AUCTION_REMOVE_CANCELLED);
WorldPacket data = AH->GenerateOwnerList(GetPlayer());
SendPacket(&data);
SendPacket(&AH->BuildResultPacket(auctionID,AUCTION_CANCEL));
}
void AuctionHouse::SellItem( WorldPacket & recv_data, Player *pl)
{
uint64 item;
uint32 bid,buyout,etime;
recv_data >> item;
recv_data >> bid >> buyout >> etime;
Item* it = pl->GetItemInterface()->GetItemByGUID(item);
if(!it) return;
float deposit = floor(tax * it->GetProto()->SellPrice / 100.0);
deposit *= etime/120;
if (pl->GetUInt32Value(PLAYER_FIELD_COINAGE) < deposit)
return;
AuctionEntry* ah = new AuctionEntry;
ah->deposit = deposit;
ah->auctionhouse = GetId();
ah->item = item;
ah->owner = pl->GetGUID();
ah->bid = bid;
ah->bidder = 0;
ah->buyout = buyout;
time_t base = time(NULL);
ah->time = ((time_t)(etime * 60)) + base;
ah->Id = GetMaxId();
it = pl->GetItemInterface()->SafeRemoveAndRetreiveItemByGuid(item, true);
if(!it)
{
return;
}
pl->SetUInt32Value(PLAYER_FIELD_COINAGE,(pl->GetUInt32Value(PLAYER_FIELD_COINAGE) - deposit));
Auctions[ah->Id] = ah;
objmgr.AddAItem(it);
it->SetOwner(NULL);
it->SaveToDB(INVENTORY_SLOT_NOT_SET, 0);
SaveAuction(ah);
pl->GetSession()->SendPacket(&BuildResultPacket(ah->Id,AUCTION_CREATE));
}
void WorldSession::HandleAuctionSellItem( WorldPacket & recv_data )
{
uint64 guid;
recv_data >> guid;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
if(!auctioneer) return;
AuctionHouse *AH = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry());
if(!AH) return;
AH->SellItem(recv_data,GetPlayer());
WorldPacket data = AH->GenerateOwnerList(GetPlayer());
SendPacket(&data);
}
WorldPacket AuctionHouse::GenerateOwnerList(Player *pl)
{
WorldPacket data;
std::map<uint32,AuctionEntry*>::iterator itr;
std::list<AuctionEntry*>tempList;
std::list<AuctionEntry*>::iterator tempitr;
uint32 cnt = 0;
for (itr = GetAuctionsBegin();itr != GetAuctionsEnd();itr++)
{
if (itr->second->owner == pl->GetGUID())
{
tempList.push_back(itr->second);
}
}
sLog.outString("sending owner list with %u items",cnt);
data.Initialize( SMSG_AUCTION_OWNER_LIST_RESULT );
if (tempList.size() < 51)
{
data << uint32(tempList.size());
}
else
{
data << uint32(50);
}
uint32 cnter = 1;
for (tempitr = tempList.begin();tempitr != tempList.end();tempitr++)
{
if ((*tempitr)->owner == pl->GetGUID())
{
AuctionEntry *ae = GetAuction((*tempitr)->Id);
Item *it = objmgr.GetAItem(ae->item);
data = AddAuctionToPacket(data,ae,it);
}
}
return data;
}
void WorldSession::HandleAuctionListOwnerItems( WorldPacket & recv_data )
{
CHECK_PACKET_SIZE(recv_data, 12);
uint64 guid;
uint32 unk1;
recv_data >> guid >> unk1;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
if(!auctioneer) return;
AuctionHouse * AH = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry());
if(!AH) return;
WorldPacket out = AH->GenerateOwnerList(GetPlayer());
SendPacket(&out);
}
WorldPacket AuctionHouse::GenerateItemList( WorldPacket & recv_data )
{
std::string auctionString;
uint8 levelRange1, levelRange2, usableCheck;
uint32 cnt, auctionSlotID, auctionMainCatagory, auctionSubCatagory, rarityCheck,temp;
int32 startID;
recv_data >> temp;
recv_data >> auctionString;
recv_data >> levelRange1 >> levelRange2;
recv_data >> auctionSlotID >> auctionMainCatagory >> auctionSubCatagory;
recv_data >> rarityCheck >> usableCheck;
startID = temp;
WorldPacket data;
std::map<uint32,AuctionEntry*>::iterator itr;
std::list<AuctionEntry*>templist;
cnt = 0;
levelRange2 == 0?levelRange2 = 100:levelRange2=levelRange2;
uint32 tempcat1, tempcat2, temprarity, tempslot;
for (itr = GetAuctionsBegin();itr != GetAuctionsEnd() && cnt < 50;itr++)
{
AuctionEntry *Aentry = itr->second;
Item *it = objmgr.GetAItem(Aentry->item);
tempcat1 = auctionMainCatagory;
tempcat2 = auctionSubCatagory;
temprarity = rarityCheck;
tempslot = auctionSlotID;
if (auctionMainCatagory == (0xffffffff))
auctionMainCatagory = it->GetProto()->Class;
if (auctionSlotID == (0xffffffff))
auctionSlotID = it->GetProto()->InventoryType;
if (rarityCheck == (0xffffffff))
rarityCheck = it->GetProto()->Quality;
if (auctionSubCatagory == (0xffffffff))
auctionSubCatagory = it->GetProto()->SubClass;
if ((startID-- <= 0) && (it->GetProto()->InventoryType == auctionSlotID) &&(it->GetProto()->Quality == rarityCheck) && (it->GetProto()->ItemLevel >= levelRange1) && (it->GetProto()->ItemLevel <= levelRange2) && (it->GetProto()->Class == auctionMainCatagory) && (it->GetProto()->SubClass == auctionSubCatagory))
templist.push_back(itr->second);
auctionMainCatagory = tempcat1;
auctionSubCatagory = tempcat2;
rarityCheck = temprarity;
auctionSlotID = tempslot;
tempcat1 = 0;
tempcat2 = 0;
temprarity = 0;
tempslot = 0;
}
data.Initialize( SMSG_AUCTION_LIST_RESULT );
data << uint32(templist.size());
uint32 cnter = 0;
std::list<AuctionEntry*>::iterator tempitr;
for (tempitr = templist.begin();tempitr!=templist.end();tempitr++)
{
AuctionEntry *ae = GetAuction((*tempitr)->Id);
Item *it = objmgr.GetAItem(ae->item);
data = AddAuctionToPacket(data,ae,it);
}
templist.clear();
return data;
}
void WorldSession::HandleAuctionListItems( WorldPacket & recv_data )
{
uint64 guid;
recv_data >> guid;
Creature* auctioneer = sObjHolder.GetObject<Creature>(guid);
if(!auctioneer) return;
AuctionHouse * AH = sAuctionMgr.GetAuctionHouseByEntry(auctioneer->GetEntry());
WorldPacket out = AH->GenerateItemList(recv_data);
SendPacket(&out);
}
void AuctionHouse::LoadFromDB()
{
std::stringstream sql;
sql << "SELECT * FROM auctions WHERE auctionhouse = '" << GetId() << "'";
QueryResult *result = sDatabase.Query( sql.str().c_str());
if( !result )
return;
AuctionEntry* aItem;
do
{
aItem = new AuctionEntry;
Field *fields = result->Fetch();
aItem->Id = fields[0].GetUInt32();
aItem->item = fields[2].GetUInt64();
Item * it=objmgr.LoadItem(aItem->item);
if(it)
objmgr.AddAItem(it);
aItem->owner = fields[3].GetUInt64();
aItem->buyout = fields[4].GetUInt32();
aItem->time = fields[5].GetUInt32();
aItem->bidder = fields[6].GetUInt64();
aItem->bid = fields[7].GetUInt32();
aItem->deposit = fields[8].GetUInt32();
aItem->auctionhouse = fields[1].GetUInt32();
Auctions[aItem->Id] = aItem;
} while (result->NextRow());
delete result;
}
| [
"[email protected]"
] | [
[
[
1,
587
]
]
] |
636237971c963257915078bb89824df3a18115d2 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/Curves/Wm4NaturalSpline3.h | 8fdf01ccee937aba3edc575de841a0c1c94c72cf | [] | no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,342 | h | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#ifndef WM4NATURALSPLINE3_H
#define WM4NATURALSPLINE3_H
#include "Wm4FoundationLIB.h"
#include "Wm4MultipleCurve3.h"
namespace Wm4
{
template <class Real>
class WM4_FOUNDATION_ITEM NaturalSpline3 : public MultipleCurve3<Real>
{
public:
enum BoundaryType
{
BT_FREE,
BT_CLAMPED,
BT_CLOSED
};
// Construction and destruction. NaturalSpline3 accepts responsibility
// for deleting the input arrays.
NaturalSpline3 (BoundaryType eType, int iSegments, Real* afTime,
Vector3<Real>* akPoint);
virtual ~NaturalSpline3 ();
const Vector3<Real>* GetPoints () const;
virtual Vector3<Real> GetPosition (Real fTime) const;
virtual Vector3<Real> GetFirstDerivative (Real fTime) const;
virtual Vector3<Real> GetSecondDerivative (Real fTime) const;
virtual Vector3<Real> GetThirdDerivative (Real fTime) const;
protected:
using MultipleCurve3<Real>::m_iSegments;
using MultipleCurve3<Real>::m_afTime;
using MultipleCurve3<Real>::GetSpeedWithData;
void CreateFreeSpline ();
void CreateClampedSpline ();
void CreateClosedSpline ();
virtual Real GetSpeedKey (int iKey, Real fTime) const;
virtual Real GetLengthKey (int iKey, Real fDT0, Real fDT1) const;
virtual Real GetVariationKey (int iKey, Real fT0, Real fT1,
const Vector3<Real>& rkA, const Vector3<Real>& rkB) const;
Vector3<Real>* m_akA;
Vector3<Real>* m_akB;
Vector3<Real>* m_akC;
Vector3<Real>* m_akD;
class WM4_FOUNDATION_ITEM ThisPlusKey
{
public:
ThisPlusKey (const NaturalSpline3* pkThis, int iKey)
:
This(pkThis),
Key(iKey)
{
}
const NaturalSpline3* This;
int Key;
};
};
typedef NaturalSpline3<float> NaturalSpline3f;
typedef NaturalSpline3<double> NaturalSpline3d;
}
#endif
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
84
]
]
] |
594b9594031f5a5c9098d6929787a0dddc139db3 | c2b9ffd6fcefa401ceb098408958210e5f763ca1 | /src/Win32/D2DManager.hpp | 2b55d1eca151061f4bb00eb31d5a4be77d89ea4a | [] | no_license | cnsuhao/stroker | acc2eac60ce0f1222c897b67f4a1dc156f5df50b | e258b8e9b5b3d0469f1ceb02ab310d1229a35caa | refs/heads/master | 2021-05-27T13:29:53.012065 | 2011-12-17T04:07:26 | 2011-12-17T04:07:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | hpp | #ifndef WIN32_D2DMANAGER_HPP_
#define WIN32_D2DMANAGER_HPP_
#include <Win32/Config.hpp>
#include <Windows.h>
#include <d2d1.h>
#include <dwrite.h>
template<typename COMObject>
inline void coSafeRelease(COMObject*& ptr)
{
if( ptr != nullptr ) {
ptr->Release();
ptr = nullptr;
}
}
class D2DManager {
public:
static D2DManager& getInstance() { return d2dManager_; }
D2DManager();
bool initialize();
void finish();
ID2D1Factory* getD2DFactory() { return d2dFactory_; }
IDWriteFactory* getDWriteFactory() { return dwriteFactory_; }
private:
static D2DManager d2dManager_;
ID2D1Factory* d2dFactory_;
IDWriteFactory* dwriteFactory_;
};
#endif // WIN32_D2DMANAGER_HPP_
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
d11b39f4382fedb8fbb9ac70ae941d2d84104afd | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/LMPlugin/functions.cpp | 4ed6b2e1f2ee3295e122337bd13dba2fa9ba234d | [] | no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 126,034 | cpp | // implementace funkci pro vyrizeni pozadavku na AP v zasuvce pro LM
// functions.cpp
/*
This file is part of LM Report Asistent.
Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
LM Report Asistent 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.
LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "functions.h"
#include "Hyp_4ft_Recordset.h"
#include "TCategory_Recordset.h"
#include "TCatDefEnum.h"
#include "TCatDefInt.h"
#include "TCatOrder.h"
#include "TAttribute_Recordset.h"
#include "TCategory_list.h"
#include "LM_Metabase.h"
#include "Bool_Cedent_Recordset.h"
#include "Equivalence_Lit_Rs.h"
#include "TCategory_Scan.h"
#include "TEmpty_Cedents_Recordset.h"
#include "TLit_Scan_Recordset.h"
#include "CF_Cedent_Recordset.h"
#include "TCFLiteral.h"
#include "KL_Cedent_Recordset.h"
#include "TKLLiteral.h"
#include "Task_Recordset.h"
#include "tiHypothesis_Recordset.h"
#include "TFTQuantifier_Recordset.h"
#include "TCFQuantifier_Recordset.h"
#include "TKLQuantifier_Recordset.h"
#include "TDFQuantifier_Recordset.h"
#include "TDCQuantifier_Recordset.h"
#include "TDKQuantifier_Recordset.h"
#include "Hyp_CF_Recordset.h"
#include "tiCFFrequencyI_Recordset.h"
#include "tmCategory_Recordset.h"
#include "TCondition_Recordset.h"
#include "Hyp_SD4ft_Recordset.h"
#include "Hyp_SDCF_Recordset.h"
#include "tiDCFrequencyI_Recordset.h"
#include "Hyp_KL_Recordset.h"
#include "tiKLFrequencyI_Recordset.h"
#include "TKLquant_Recordset.h"
#include "TKLCategory_Recordset.h"
#include "Hyp_SDKL_Recordset.h"
#include "tiDKFrequencyI_Recordset.h"
#include "TCoef_type_Recordset.h"
#include "ODBCINST.H"
#include "TData_Matrix_Recordset.h"
#include "TColumn_Recordset.h"
#include "direct.h"
#include "math.h"
#include "LMPlErrorMessages.h"
#include "LMPlugin.h"
#include "CTime_Utils.h"
#include <afxdb.h>
#include <Shlwapi.h>
#import <msxml3.dll>
using namespace MSXML2;
//pastes the namespace MSXML2;
bool ar2nl_err = false;
CString Get_4ftar2nl_output (LPCTSTR file_path)
{
// kody - reading and serialization of the outputof the AR2NL using XML DOM
MSXML2::IXMLDOMDocumentPtr dom;
dom.CreateInstance(_T("Msxml2.DOMDocument"));
dom->async = VARIANT_FALSE; // default - true,
if (dom->load((LPCTSTR) file_path)!=VARIANT_TRUE)
{
return "";
}
MSXML2::IXMLDOMElementPtr el_hyp = dom->GetdocumentElement();
dom.Release();
if (el_hyp != NULL)
{
return (LPCTSTR) el_hyp->Getxml();
}
else
{
return "";
}
}
class CAR2NLHlp
{
CString DSN;
CString AR2NL_exe_command;
CString AR2NL_path;
CString config;
BOOL source_is_set;
void ReplaceDollars(LPSTR str)
{
while (* str)
{
if (* str == '$') * str = '\0';
str++;
}
}
public:
LPCTSTR getConfig() {return config;};
CString getEXEPath() {return AR2NL_path + "\\bin";};
LPCTSTR getEXECommand() {return AR2NL_exe_command;};
CString getOutput12Path() {return AR2NL_path + "\\output\\output12.xml";};
CAR2NLHlp (long hypno, CString db_name)
{
source_is_set = FALSE;
DSN.Format("LMxRepAssistxtempx%d", hypno);
TCHAR module_path[MAX_PATH];
GetModuleFileName(NULL, module_path, MAX_PATH);
//deletes the last two levels from the path
PathFindFileName(module_path)[-1] = 0;
PathFindFileName(module_path)[-1] = 0;
PathFindFileName(module_path)[-1] = 0;
AR2NL_path.Format("%s\\4ftAR2NL", module_path);
AR2NL_exe_command.Format("4ftar2nl.exe -DSN=%s -hypno=%d", (LPCTSTR) DSN, hypno);
config.Format("DSN=%s$ DESCRIPTION=Temporary ODBC$ DBQ=%s.mdb$ FIL=MicrosoftAccess$ DEFAULTDIR= $",
(LPCSTR) DSN, (LPCTSTR) db_name);
}
BOOL setODBCSource()
{
CString conf_str = getConfig();
LPSTR buf = conf_str.GetBuffer(0);
ReplaceDollars(buf);
source_is_set = SQLConfigDataSource (NULL, ODBC_ADD_DSN, "Microsoft Access Driver (*.mdb)\0", buf);
conf_str.ReleaseBuffer();
return source_is_set;
}
~CAR2NLHlp()
{
if (source_is_set)
{
CString conf_str = "DSN=" + DSN + "$";
LPSTR buf = conf_str.GetBuffer(0);
ReplaceDollars(buf);
if (FALSE == SQLConfigDataSource (NULL, ODBC_REMOVE_DSN,
"Microsoft Access Driver (*.mdb)", buf))
{
conf_str.ReleaseBuffer();
CLMSock::ReportError (5, LMERR_CANNOT_REMOVE_ODBC);
}
conf_str.ReleaseBuffer();
}
}
};
CString Get_4ftAR2NL (long hypno, CString db_name)
{
CAR2NLHlp AR2NLHlp(hypno, db_name);
//create the temporary datasource
if (FALSE == AR2NLHlp.setODBCSource())
{
CLMSock::ReportError (4, LMERR_CANNOT_CREATE_ODBC);
ar2nl_err = true;
return "";
}
//change the working directory
if (_chdir (AR2NLHlp.getEXEPath()) != 0)
{
CLMSock::ReportError(6, LMERR_CANNOT_FIND_AR2NL_EXE_PATH, (LPCTSTR) AR2NLHlp.getEXEPath());
ar2nl_err = true;
return "";
}
CFileStatus status;
bool file_exists;
CTime last_modif_time;
try
{
CFile f (AR2NLHlp.getOutput12Path(), CFile::modeRead);
if(f.GetStatus (status))
{
file_exists = true;
last_modif_time = status.m_mtime;
}
else file_exists = false;
f.Close ();
}
catch (...)
{
file_exists = false;
}
STARTUPINFO si;
ZeroMemory(& si, sizeof si);
si.cb = sizeof si;
PROCESS_INFORMATION pi;
ZeroMemory(& pi, sizeof pi);
try
{
//run the 4ftAR2NL application
CString exe_cmd = AR2NLHlp.getEXECommand();
if (!CreateProcess(NULL, exe_cmd.GetBuffer(0),
NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, & si, & pi))
{
exe_cmd.ReleaseBuffer();
CLMSock::ReportError (7, LMERR_AR2NL_EXE_FAIL,
(LPCTSTR) (AR2NLHlp.getEXEPath() + "\\" + AR2NLHlp.getEXECommand()));
ar2nl_err = true;
return "";
}
exe_cmd.ReleaseBuffer();
}
catch (...)
{
CLMSock::ReportError (7, LMERR_AR2NL_EXE_FAIL,
(LPCTSTR) (AR2NLHlp.getEXEPath() + "\\" + AR2NLHlp.getEXECommand()));
ar2nl_err = true;
return "";
}
try
{
DWORD exit_code = 1;//0 = successful
if (!GetExitCodeProcess (pi.hProcess, &exit_code))
{
CLMSock::ReportError (8, LMERR_AR2NL_EXIT_FAIL);
ar2nl_err = true;
return "";
}
int cnt = 0;
while (exit_code == STILL_ACTIVE)
{
if (!GetExitCodeProcess (pi.hProcess, &exit_code))
{
CLMSock::ReportError (8, LMERR_AR2NL_EXIT_FAIL);
ar2nl_err = true;
return "";
}
Sleep (500);
cnt += 500;
if (cnt > 60000) exit_code = 0;
}
if (exit_code != 0)
{
return "";
}
}
catch (...)
{
CLMSock::ReportError (8, LMERR_AR2NL_EXIT_FAIL);
ar2nl_err = true;
return "";
}
try
{
if (!CloseHandle(pi.hProcess) || !CloseHandle(pi.hThread))
{
ar2nl_err = true;
return "";
}
}
catch (...)
{
ar2nl_err = true;
return "";
}
try
{
CFile f1 (AR2NLHlp.getOutput12Path(), CFile::modeRead);
if (f1.GetStatus (status))
{
if (file_exists && status.m_mtime == last_modif_time)
{
return "";
}
}
else
{
f1.Close ();
return "";
}
f1.Close ();
}
catch (...)
{
return "";
}
try
{
return Get_4ftar2nl_output (AR2NLHlp.getOutput12Path());
}
catch (...)
{
CLMSock::ReportError (9, LMERR_CANNOT_READ_AR2NL_OUTPUT);
ar2nl_err = true;
return "";
}
return "";
}
CString Get_DTD ()
{
TCHAR module_path[MAX_PATH];
GetModuleFileName(NULL, module_path, MAX_PATH);
//deletes the last two levels from the path
PathFindFileName(module_path)[-1] = 0;
PathFindFileName(module_path)[-1] = 0;
PathFindFileName(module_path)[-1] = 0;
CString file_path = module_path;
file_path += "\\XML\\plug_output_DTD.xml";
CString buf;
CFile f(file_path, CFile::modeRead);
int size = (int) f.GetLength();
LPTSTR ps = buf.GetBuffer(size);
f.Read(ps, size);
f.Close();
ps[size] = 0; //the data read from the output must be ended by zero to represent the valid string
buf.ReleaseBuffer(); //ps is not valid from now and no further actions are allowed
return buf;
}
// ---AP Quantifier
CString fLMQuantifier (void* hSource)
{
CString buf = "";
CString hlp;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
TQuantifier_Meta_Array list;
Quantifier_Meta * ptquant;
quant_item item;
BOOL result;
bool exc = false;
TFTQuantifier_Recordset rs ((CDatabase *) hSource);
TCFQuantifier_Recordset rsCF ((CDatabase *) hSource);
TKLQuantifier_Recordset rsKL ((CDatabase *) hSource);
TDFQuantifier_Recordset rsDF ((CDatabase *) hSource);
TDCQuantifier_Recordset rsDC ((CDatabase *) hSource);
TDKQuantifier_Recordset rsDK ((CDatabase *) hSource);
LPCTSTR q = "SELECT * \
FROM taTask, tdFTQuantifier, tmMatrix, tsQuantifierType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdFTQuantifier.TaskID=taTask.TaskID \
AND tsQuantifierType.QuantifierTypeID=tdFTQuantifier.FTQuantifierTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rs.m_Name2;
ptquant->name = rs.m_Name3;
ptquant->task_name = rs.m_Name;
ptquant->task_type = rs.m_Name4;
ptquant->type = "N/A";
hlp.Format ("%d", rs.m_FTQuantifierID);
hlp = "quantFT" + hlp;
ptquant->id = hlp;
if (rs.m_ShortName == "FUI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "LCI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "SUPP")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "UCI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "AAI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "BAI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "DFUI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "DLCI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "DUCI")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "FUE")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "LCE")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "UCE")
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamP;
ptquant->items.Add (item);
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "SID")
{
item.name = "Delta";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamDelta;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "FSH")
{
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "CHI")
{
item.name = "Alpha";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "E-Q")
{
item.name = "Delta";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamDelta;
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "BASE")
{
if (rs.m_ParamRelativ)
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamBeta;
}
else
{
item.name = "count";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
}
ptquant->items.Add (item);
}
else if (rs.m_ShortName == "CEIL")
{
if (rs.m_ParamRelativ)
{
item.name = "p";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamBeta;
}
else
{
item.name = "count";
item.value = (LPCTSTR) (_bstr_t) rs.m_ParamAlfa;
}
ptquant->items.Add (item);
}
list.Add (ptquant);
rs.MoveNext();
}
rs.Close();
}
else return "";
q = "SELECT * \
FROM taTask, tdCFQuantifier, tmMatrix, tsCFQuantifierType,\
tsCFQuantifierValueType, tsCompareType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdCFQuantifier.TaskID=taTask.TaskID \
AND tsCFQuantifierType.CFQuantifierTypeID=tdCFQuantifier.CFQuantifierTypeID \
AND tsCFQuantifierValueType.CFQuantifierValueTypeID=tdCFQuantifier.CFQuantifierValueTypeID \
AND tsCompareType.CompareTypeID=tdCFQuantifier.CompareTypeID";
try
{
result = rsCF.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rsCF.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rsCF.m_Name2;
ptquant->name = rsCF.m_Name3;
ptquant->task_name = rsCF.m_Name;
ptquant->task_type = rsCF.m_Name6;
ptquant->type = "N/A";
hlp.Format ("%d", rsCF.m_CFQuantifierID);
hlp = "quantCF" + hlp;
ptquant->id = hlp;
item.name = "Value type";
item.value = rsCF.m_Name4;
ptquant->items.Add (item);
item.name = "From";
item.value = (LPCTSTR) (_bstr_t) rsCF.m_FromCol;
ptquant->items.Add (item);
item.name = "To";
item.value = (LPCTSTR) (_bstr_t) rsCF.m_ToCol;
ptquant->items.Add (item);
item.name = "Param";
item.value = (LPCTSTR) (_bstr_t) rsCF.m_ValuePar;
ptquant->items.Add (item);
item.name = "Comparation";
item.value = rsCF.m_ShortName3;
ptquant->items.Add (item);
list.Add (ptquant);
rsCF.MoveNext();
}
rsCF.Close();
}
else return "";
q = "SELECT * \
FROM taTask, tdKLQuantifier, tmMatrix, tsCompareType,\
tsKLQuantifierType, tsKLQuantifierValueType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdKLQuantifier.TaskID=taTask.TaskID \
AND tsKLQuantifierType.KLQuantifierTypeID=tdKLQuantifier.KLQuantifierTypeID \
AND tsKLQuantifierValueType.KLQuantifierValueTypeID=tdKLQuantifier.KLQuantifierValueTypeID \
AND tsCompareType.CompareTypeID=tdKLQuantifier.CompareTypeID";
try
{
result = rsKL.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rsKL.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rsKL.m_Name2;
ptquant->name = rsKL.m_Name4;
ptquant->task_name = rsKL.m_Name;
ptquant->task_type = rsKL.m_Name6;
ptquant->type = "N/A";
hlp.Format ("%d", rsKL.m_KLQuantifierID);
hlp = "quantKL" + hlp;
ptquant->id = hlp;
item.name = "Value type";
item.value = rsKL.m_Name5;
ptquant->items.Add (item);
item.name = "From Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_FromCol;
ptquant->items.Add (item);
item.name = "To Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ToCol;
ptquant->items.Add (item);
item.name = "From Row";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_FromRow;
ptquant->items.Add (item);
item.name = "To Row";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ToRow;
ptquant->items.Add (item);
item.name = "Param";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ValuePar;
ptquant->items.Add (item);
item.name = "Comparation";
item.value = rsKL.m_ShortName;
ptquant->items.Add (item);
list.Add (ptquant);
rsKL.MoveNext();
}
rsKL.Close();
}
else return "";
q = "SELECT * \
FROM taTask, tdDFQuantifier, tmMatrix, tsCompareType,\
tsDFQuantifierType, tsDFQuantifierValueType, \
tsSDQuantifierSourceType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdDFQuantifier.TaskID=taTask.TaskID \
AND tsDFQuantifierType.DFQuantifierTypeID=tdDFQuantifier.DFQuantifierTypeID \
AND tsDFQuantifierValueType.DFQuantifierValueTypeID=tdDFQuantifier.DFQuantifierValueTypeID \
AND tsCompareType.CompareTypeID=tdDFQuantifier.CompareTypeID \
AND tsSDQuantifierSourceType.SDQuantifierSourceTypeID=tdDFQuantifier.SDQuantifierSourceTypeID";
try
{
result = rsDF.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rsDF.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rsDF.m_Name2;
ptquant->name = rsDF.m_Name4;
ptquant->task_name = rsDF.m_Name;
ptquant->task_type = rsDF.m_Name7;
ptquant->type = "N/A";
hlp.Format ("%d", rsDF.m_DFQuantifierID);
hlp = "quantDF" + hlp;
ptquant->id = hlp;
item.name = "Value type";
item.value = rsDF.m_Name5;
ptquant->items.Add (item);
item.name = "Param";
item.value = (LPCTSTR) (_bstr_t) rsDF.m_ValuePar;
ptquant->items.Add (item);
item.name = "Comparation";
item.value = rsDF.m_ShortName;
ptquant->items.Add (item);
item.name = "Source";
item.value = rsDF.m_Name6;
ptquant->items.Add (item);
list.Add (ptquant);
rsDF.MoveNext();
}
rsDF.Close();
}
else return "";
q = "SELECT * \
FROM taTask, tdDCQuantifier, tmMatrix, tsCompareType,\
tsDCQuantifierType, tsDCQuantifierValueType, \
tsSDQuantifierSourceType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdDCQuantifier.TaskID=taTask.TaskID \
AND tsDCQuantifierType.DCQuantifierTypeID=tdDCQuantifier.DCQuantifierTypeID \
AND tsDCQuantifierValueType.DCQuantifierValueTypeID=tdDCQuantifier.DCQuantifierValueTypeID \
AND tsCompareType.CompareTypeID=tdDCQuantifier.CompareTypeID \
AND tsSDQuantifierSourceType.SDQuantifierSourceTypeID=tdDCQuantifier.SDQuantifierSourceTypeID";
try
{
result = rsDC.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rsDC.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rsDC.m_Name2;
ptquant->name = rsDC.m_Name4;
ptquant->task_name = rsDC.m_Name;
ptquant->task_type = rsDC.m_Name7;
ptquant->type = "N/A";
hlp.Format ("%d", rsDC.m_DCQuantifierID);
hlp = "quantDC" + hlp;
ptquant->id = hlp;
item.name = "Value type";
item.value = rsDC.m_Name5;
ptquant->items.Add (item);
item.name = "Param";
item.value = (LPCTSTR) (_bstr_t) rsDC.m_ValuePar;
ptquant->items.Add (item);
item.name = "Comparation";
item.value = rsDC.m_ShortName;
ptquant->items.Add (item);
item.name = "Source";
item.value = rsDC.m_Name6;
ptquant->items.Add (item);
item.name = "From Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_FromCol;
ptquant->items.Add (item);
item.name = "To Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ToCol;
ptquant->items.Add (item);
list.Add (ptquant);
rsDC.MoveNext();
}
rsDC.Close();
}
else return "";
q = "SELECT * \
FROM taTask, tdDKQuantifier, tmMatrix, tsCompareType,\
tsDKQuantifierType, tsDKQuantifierValueType, \
tsSDQuantifierSourceType, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdDKQuantifier.TaskID=taTask.TaskID \
AND tsDKQuantifierType.DKQuantifierTypeID=tdDKQuantifier.DKQuantifierTypeID \
AND tsDKQuantifierValueType.DKQuantifierValueTypeID=tdDKQuantifier.DKQuantifierValueTypeID \
AND tsCompareType.CompareTypeID=tdDKQuantifier.CompareTypeID \
AND tsSDQuantifierSourceType.SDQuantifierSourceTypeID=tdDKQuantifier.SDQuantifierSourceTypeID";
try
{
result = rsDK.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rsDK.IsEOF())
{
ptquant = new (Quantifier_Meta);
ptquant->db_name = db_name;
ptquant->matrix_name = rsDK.m_Name2;
ptquant->name = rsDK.m_Name4;
ptquant->task_name = rsDK.m_Name;
ptquant->task_type = rsDK.m_Name7;
ptquant->type = "N/A";
hlp.Format ("%d", rsDK.m_DKQuantifierID);
hlp = "quantDK" + hlp;
ptquant->id = hlp;
item.name = "Value type";
item.value = rsDK.m_Name5;
ptquant->items.Add (item);
item.name = "Param";
item.value = (LPCTSTR) (_bstr_t) rsDK.m_ValuePar;
ptquant->items.Add (item);
item.name = "Comparation";
item.value = rsDK.m_ShortName;
ptquant->items.Add (item);
item.name = "Source";
item.value = rsDK.m_Name6;
ptquant->items.Add (item);
item.name = "From Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_FromCol;
ptquant->items.Add (item);
item.name = "To Column";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ToCol;
ptquant->items.Add (item);
item.name = "From Row";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_FromRow;
ptquant->items.Add (item);
item.name = "To Row";
item.value = (LPCTSTR) (_bstr_t) rsKL.m_ToRow;
ptquant->items.Add (item);
list.Add (ptquant);
rsDK.MoveNext();
}
rsDK.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
list.GetAt (i)->items.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// ---AP Task
CString fLMTask (void* hSource)
{
CString buf = "";
CString hlp;
CString hlp1;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString q_hyp;
int hours;
int minutes;
int seconds;
double secf;
long up;
long down;
BOOL result;
bool exc = false;
TTask_Meta_Array list;
Task_Meta * pttask;
Task_Recordset rs ((CDatabase *) hSource);
tiHypothesis_Recordset rs_hyp ((CDatabase *) hSource);
long hyp_cnt = 0; //number of hypothesis
LPCTSTR q = "SELECT * \
FROM taTask, tmMatrix, tsTaskSubType \
WHERE taTask.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
pttask = new (Task_Meta);
pttask->db_name = db_name;
try
{
pttask->gen_start_time =
get_date_in_user_format (rs.m_GenerationStartTime) + " ";
pttask->gen_start_time += get_time_in_user_format (rs.m_GenerationStartTime);
pttask->gen_start_time.Replace ("/", ".");
}
catch (...)
{
pttask->gen_start_time = rs.m_GenerationStartTime.Format ("%c");
}
secf = rs.m_GenerationTotalTime / 1000;
up = (long) ceil (secf);
down = (long) floor (secf);
if ((up - secf) < 0.5) seconds = up;
else seconds = down;
hours = seconds / 3600;
seconds = seconds - hours * 3600;
minutes = (int) floor (float(seconds / 60));
seconds = seconds - minutes * 60;
hlp1.Format ("%d", hours);
if (hlp1.GetLength () == 1) hlp1 = "0" + hlp1;
hlp = hlp1 + ":";
hlp1.Format ("%d", minutes);
if (hlp1.GetLength () == 1) hlp1 = "0" + hlp1;
hlp += hlp1;
hlp += ":";
hlp1.Format ("%d", seconds);
if (hlp1.GetLength () == 1) hlp1 = "0" + hlp1;
hlp += hlp1;
pttask->gen_total_time = hlp;
hlp.Format ("%d", rs.m_TaskID);
pttask->id = "Task" + hlp;
pttask->matrix_name = rs.m_Name2;
pttask->num_tests.Format ("%d", rs.m_GenerationNrOfTests);
pttask->task_name = rs.m_Name;
pttask->task_type = rs.m_Name3;
q_hyp = "SELECT * \
FROM tiHypothesis \
WHERE TaskID=" + hlp;
try
{
result = rs_hyp.Open (AFX_DB_USE_DEFAULT_TYPE, q_hyp);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
hyp_cnt = 0;
while (!rs_hyp.IsEOF())
{
hyp_cnt++;
rs_hyp.MoveNext ();
}
rs_hyp.Close ();
}
else return "";
pttask->num_hyp.Format ("%d", hyp_cnt);
if (hyp_cnt >= HYPOTHESIS_LIMIT)
{
pttask->gen_state = "Limit of hypotheses reached";
}
else if (rs.m_GenerationInterrupted)
{
pttask->gen_state = "Generation interrupted";
}
else if (rs.m_HypothesisGenerated)
{
pttask->gen_state = "Hypotheses generated";
}
else pttask->gen_state = "Modified task has not been processed yet";
list.Add (pttask);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
delete (list.GetAt (i));
list.RemoveAll ();
return buf;
}
// ---AP KL cedent
CString fLMKLCedent (void* hSource)
{
CString buf = "";
CString hlp;
CString hlp1;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString q_lit;
CString q_cat;
long sub_cedent_cnt = 0;
long literal_cnt = 0;
long ct_id;
long ct_id_tst = 0; //test, wheather the new cedent type appears
long c_id;
long c_id_tst = 0; //test, wheather the new sub cedent appears
long c = 0; //counter
BOOL result;
bool exc = false;
KL_Cedent_Recordset rs ((CDatabase *) hSource);
TKLLiteral rs_lit ((CDatabase *) hSource);
TCategory_Scan rs_cat ((CDatabase *) hSource);
TKL_Cedent_Meta_Array list;
KL_Cedent_Meta * ptklcdnt;
Sub_KL_Cedent_Meta * ptsub_kl_cedent;
KL_Literal_Meta lit;
LPCTSTR q =
"SELECT * \
FROM taTask, tdKLCedentD, tmMatrix, tsCedentType, tsTaskSubType \
WHERE taTask.TaskID=tdKLCedentD.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tdKLCedentD.CedentTypeID=tsCedentType.CedentTypeID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
ORDER BY taTask.TaskID, tdKLCedentD.CedentTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ct_id = rs.m_CedentTypeID;
c_id = rs.m_KLCedentDID;
if (ct_id != ct_id_tst) //new cedent
{
sub_cedent_cnt = 0;
literal_cnt = 0;
ptklcdnt = new (KL_Cedent_Meta);
ptklcdnt->db_name = db_name;
hlp.Format ("%d", rs.m_KLCedentDID);
ptklcdnt->id = "KLcdnt" + hlp;
ptklcdnt->matrix_name = rs.m_Name3;
ptklcdnt->task_name = rs.m_Name;
ptklcdnt->task_type = rs.m_Name5;
ptklcdnt->cedent_type = rs.m_Name4;
if (ptklcdnt->cedent_type == "Antecedent")
ptklcdnt->cedent_type = "Row attributes";
else if (ptklcdnt->cedent_type == "Succedent")
ptklcdnt->cedent_type = "Column attributes";
list.Add (ptklcdnt);
}
if (c_id != c_id_tst) //new sub cedent
{
ptsub_kl_cedent = new (Sub_KL_Cedent_Meta);
literal_cnt = 0;
sub_cedent_cnt++;
ptklcdnt->sub_cedent_cnt.Format ("%d", sub_cedent_cnt);
hlp = rs.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
ptsub_kl_cedent->name = hlp;
hlp.Format ("%d", rs.m_MinLen);
hlp1.Format ("%d", rs.m_MaxLen);
hlp += " - ";
hlp += hlp1;
ptsub_kl_cedent->length = hlp;
ptklcdnt->sub_cedents_list.Add (ptsub_kl_cedent);
hlp.Format ("%d", c_id);
q_lit =
"SELECT * \
FROM tdKLLiteralD, tmAttribute, tmQuantity \
WHERE tdKLLiteralD.KLCedentDID=" + hlp +
" AND tmQuantity.QuantityID=tdKLLiteralD.QuantityID \
AND tmQuantity.AttributeID=tmAttribute.AttributeID";
try
{
result = rs_lit.Open(AFX_DB_USE_DEFAULT_TYPE, q_lit);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_lit.IsEOF())
{
literal_cnt++;
ptsub_kl_cedent->literal_cnt.Format ("%d", literal_cnt);
lit.underlying_attribute = rs_lit.m_Name;
hlp.Format ("%d", rs_lit.m_QuantityID2);
q_cat =
"SELECT * \
FROM tmCategory \
WHERE tmCategory.QuantityID=" + hlp;
try
{
result = rs_cat.Open(AFX_DB_USE_DEFAULT_TYPE, q_cat);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
c = 0;
//iteration on query results
while (!rs_cat.IsEOF())
{
c++;
rs_cat.MoveNext ();
}
rs_cat.Close ();
}
else return "";
lit.category_cnt.Format ("%d", c);
ptsub_kl_cedent->lit_list.Add (lit);
rs_lit.MoveNext ();
}
rs_lit.Close ();
}
else return "";
}
c_id_tst = c_id;
ct_id_tst = ct_id;
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
for (int j = 0; j < list.GetAt (i)->sub_cedents_list.GetSize (); j++)
{
delete (list.GetAt (i)->sub_cedents_list.GetAt (j));
}
list.GetAt (i)->sub_cedents_list.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// ---AP CF cedent
CString fLMCFCedent (void* hSource)
{
CString buf = "";
CString hlp;
CString hlp1;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString q_lit;
CString q_cat;
long sub_cedent_cnt = 0;
long literal_cnt = 0;
long ct_id;
long ct_id_tst = 0; //test, wheather the new cedent type appears
long c_id;
long c_id_tst = 0; //test, wheather the new sub cedent appears
long c = 0; //counter
BOOL result;
bool exc = false;
CF_Cedent_Recordset rs ((CDatabase *) hSource);
TCFLiteral rs_lit ((CDatabase *) hSource);
TCategory_Scan rs_cat ((CDatabase *) hSource);
TCF_Cedent_Meta_Array list;
CF_Cedent_Meta * ptcfcdnt;
Sub_CF_Cedent_Meta * ptsub_cf_cedent;
CF_Literal_Meta lit;
LPCTSTR q =
"SELECT * \
FROM taTask, tdCFCedentD, tmMatrix, tsCedentType, tsTaskSubType \
WHERE taTask.TaskID=tdCFCedentD.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tdCFCedentD.CedentTypeID=tsCedentType.CedentTypeID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
ORDER BY taTask.TaskID, tdCFCedentD.CedentTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ct_id = rs.m_CedentTypeID;
c_id = rs.m_CFCedentDID;
if (ct_id != ct_id_tst) //new cedent
{
sub_cedent_cnt = 0;
literal_cnt = 0;
ptcfcdnt = new (CF_Cedent_Meta);
ptcfcdnt->db_name = db_name;
hlp.Format ("%d", rs.m_CFCedentDID);
ptcfcdnt->id = "CFcdnt" + hlp;
ptcfcdnt->matrix_name = rs.m_Name3;
ptcfcdnt->task_name = rs.m_Name;
ptcfcdnt->task_type = rs.m_Name5;
ptcfcdnt->cedent_type = "Attributes";
list.Add (ptcfcdnt);
}
if (c_id != c_id_tst) //new sub cedent
{
ptsub_cf_cedent = new (Sub_CF_Cedent_Meta);
literal_cnt = 0;
sub_cedent_cnt++;
ptcfcdnt->sub_cedent_cnt.Format ("%d", sub_cedent_cnt);
hlp = rs.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
ptsub_cf_cedent->name = hlp;
hlp.Format ("%d", rs.m_MinLen);
hlp1.Format ("%d", rs.m_MaxLen);
hlp += " - ";
hlp += hlp1;
ptsub_cf_cedent->length = hlp;
ptcfcdnt->sub_cedents_list.Add (ptsub_cf_cedent);
hlp.Format ("%d", c_id);
q_lit =
"SELECT * \
FROM tdCFLiteralD, tmAttribute, tmQuantity \
WHERE tdCFLiteralD.CFCedentDID=" + hlp +
" AND tmQuantity.QuantityID=tdCFLiteralD.QuantityID \
AND tmQuantity.AttributeID=tmAttribute.AttributeID";
try
{
result = rs_lit.Open(AFX_DB_USE_DEFAULT_TYPE, q_lit);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_lit.IsEOF())
{
literal_cnt++;
ptsub_cf_cedent->literal_cnt.Format ("%d", literal_cnt);
lit.underlying_attribute = rs_lit.m_Name;
hlp.Format ("%d", rs_lit.m_QuantityID2);
q_cat =
"SELECT * \
FROM tmCategory \
WHERE tmCategory.QuantityID=" + hlp;
try
{
result = rs_cat.Open(AFX_DB_USE_DEFAULT_TYPE, q_cat);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
c = 0;
//iteration on query results
while (!rs_cat.IsEOF())
{
c++;
rs_cat.MoveNext ();
}
rs_cat.Close ();
}
else return "";
lit.category_cnt.Format ("%d", c);
ptsub_cf_cedent->lit_list.Add (lit);
rs_lit.MoveNext ();
}
rs_lit.Close ();
}
else return "";
}
c_id_tst = c_id;
ct_id_tst = ct_id;
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
for (int j = 0; j < list.GetAt (i)->sub_cedents_list.GetSize (); j++)
{
delete (list.GetAt (i)->sub_cedents_list.GetAt (j));
}
list.GetAt (i)->sub_cedents_list.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// ---AP bool cedent
CString fLMBoolCedent (void* hSource)
{
CString buf = "";
CString hlp;
CString hlp1;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
long sub_cedent_cnt = 0;
long literal_cnt = 0;
long c_id;
long c_id_tst = 0; //test, wheather the new sub cedent appears
long l_id;
long l_id_tst = 0; //test, wheather the new literal appears
long c = 0; //counter - help variable
BOOL result;
bool exc = false;
BOOL missing_type = FALSE;
TBool_Cedent_Meta_Array list;
Bool_Cedent_Meta * ptboolcdnt;
Bool_Cedent_Recordset rs ((CDatabase *) hSource);
Equivalence_Lit_Rs rs_eq ((CDatabase *) hSource);
TCategory_Scan rs_cat ((CDatabase *) hSource);
TEmpty_Cedents_Recordset rs_em ((CDatabase *) hSource);
TLit_Scan_Recordset rs_lit ((CDatabase *) hSource);
Literal_Meta lit;
CString q_eq;
CString q_cat;
CString q_lit;
LPCTSTR q =
"SELECT * \
FROM taTask, tdCedentD, tdLiteralD, tmAttribute, \
tmMatrix, tmQuantity, tsCedentType, tsCoefficientType, tsGaceType, \
tsLiteralType, tsTaskSubType \
WHERE tdCedentD.CedentTypeID=tsCedentType.CedentTypeID \
AND tdCedentD.TaskID=taTask.TaskID \
AND tdCedentD.CedentDID=tdLiteralD.CedentDID \
AND tdLiteralD.QuantityID=tmQuantity.QuantityID \
AND tdLiteralD.LiteralTypeID=tsLiteralType.LiteralTypeID \
AND tdLiteralD.GaceTypeID=tsGaceType.GaceTypeID \
AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID \
AND tmQuantity.AttributeID=tmAttribute.AttributeID \
AND tmAttribute.MatrixID=tmMatrix.MatrixID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
ORDER BY tdCedentD.TaskID, tdCedentD.CedentTypeID, tdLiteralD.LiteralDID";
LPCTSTR q_em =
"SELECT * \
FROM taTask, tdCedentD, tmMatrix, tsCedentType, tsTaskSubType \
WHERE tdCedentD.CedentTypeID=tsCedentType.CedentTypeID \
AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
AND tdCedentD.TaskID=taTask.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
c++;
c_id = rs.m_CedentDID;
l_id = rs.m_LiteralDID;
if (c_id != c_id_tst) //new sub cedent
{
literal_cnt = 0;
ptboolcdnt = new (Bool_Cedent_Meta);
ptboolcdnt->db_name = db_name;
hlp.Format ("%d", rs.m_CedentDID);
ptboolcdnt->id = "cdnt" + hlp;
ptboolcdnt->matrix_name = rs.m_Name4;
ptboolcdnt->task_name = rs.m_Name;
ptboolcdnt->task_type = rs.m_Name10;
ptboolcdnt->cedent_type = rs.m_Name6;
hlp = rs.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
ptboolcdnt->name = hlp;
hlp.Format ("%d", rs.m_MinLen);
hlp1.Format ("%d", rs.m_MaxLen);
hlp += " - ";
hlp += hlp1;
ptboolcdnt->length = hlp;
list.Add (ptboolcdnt);
}
if (l_id != l_id_tst) //new literal
{
literal_cnt++;
ptboolcdnt->literal_cnt.Format ("%d", literal_cnt);
hlp = rs.m_Name3;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.underlying_attribute = hlp;
hlp = rs.m_Name7;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.coefficient_type = hlp;
if (rs.m_ShortName3 == "one")
{
hlp.Format ("%d", rs.m_CategoryID);
//this query returns only one row - primary key in WHERE clause
q_cat = "SELECT * \
FROM tmCategory \
WHERE CategoryID=" + hlp;
//find one category value
try
{
result = rs_cat.Open(AFX_DB_USE_DEFAULT_TYPE, q_cat);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results - one row
while (!rs_cat.IsEOF())
{
hlp = rs_cat.m_Name;
rs_cat.MoveNext ();
}
rs_cat.Close ();
}
else return "";
hlp = "(" + hlp + ")";
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.coefficient_type += hlp;
}
hlp.Format ("%d", rs.m_MinLen2);
hlp1.Format ("%d", rs.m_MaxLen2);
hlp += " - ";
hlp += hlp1;
lit.length = hlp;
hlp = rs.m_Name8;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.gace = hlp;
hlp = rs.m_Name9;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.literal_type = hlp;
hlp.Format ("%d", c_id);
q_eq = "SELECT * \
FROM tdEquivalenceClass \
WHERE CedentDID=" + hlp;
//find all equivalence classes
hlp = "";
try
{
result = rs_eq.Open(AFX_DB_USE_DEFAULT_TYPE, q_eq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
c = 0;
//iteration on query results
while (!rs_eq.IsEOF())
{
c++;
if (c != 1) hlp += "; ";
hlp += rs_eq.m_Name;
rs_eq.MoveNext ();
}
rs_eq.Close ();
}
else return "";
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
lit.equivalence_class = hlp;
hlp.Format ("%d", rs.m_QuantityID2);
q_cat ="SELECT * \
FROM tmCategory \
WHERE QuantityID=" + hlp;
//find categories and missing values
missing_type = FALSE;
try
{
result = rs_cat.Open(AFX_DB_USE_DEFAULT_TYPE, q_cat);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
c = 0;
//iteration on query results
while (!rs_cat.IsEOF())
{
c++;
if (rs_cat.m_XCategory) missing_type = TRUE;
rs_cat.MoveNext ();
}
rs_cat.Close ();
}
else return "";
lit.category_cnt.Format ("%d", c);
if (missing_type) lit.missing_type = "Yes";
else lit.missing_type = "No";
ptboolcdnt->lit_list.Add (lit);
}
l_id_tst = l_id;
c_id_tst = c_id;
rs.MoveNext();
}
rs.Close();
}
else return "";
//add empty subcedents
try
{
result = rs_em.Open(AFX_DB_USE_DEFAULT_TYPE, q_em);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_em.IsEOF())
{
hlp.Format ("%d", rs_em.m_CedentDID);
q_lit = "SELECT * FROM tdLiteralD WHERE CedentDID=" + hlp;
c = 0;
try
{
result = rs_lit.Open (AFX_DB_USE_DEFAULT_TYPE, q_lit);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_lit.IsEOF ())
{
c++;
rs_lit.MoveNext ();
}
rs_lit.Close ();
}
else return "";
if (c == 0) //new empty subcedent
{
ptboolcdnt = new (Bool_Cedent_Meta);
ptboolcdnt->literal_cnt.Format ("%d", 0);
ptboolcdnt->name = rs_em.m_Name2;
hlp.Format ("%d", rs_em.m_MinLen);
hlp1.Format ("%d", rs_em.m_MaxLen);
hlp += " - ";
hlp += hlp1;
ptboolcdnt->length = hlp;
ptboolcdnt->lit_list.RemoveAll ();
ptboolcdnt->db_name = db_name;
hlp.Format ("%d", rs_em.m_CedentDID);
ptboolcdnt->id = "cdnt" + hlp;
ptboolcdnt->matrix_name = rs_em.m_Name3;
ptboolcdnt->task_name = rs_em.m_Name;
ptboolcdnt->task_type = rs_em.m_Name5;
ptboolcdnt->cedent_type = rs_em.m_Name4;
list.Add (ptboolcdnt);
}
rs_em.MoveNext ();
}
rs_em.Close ();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// --- AP attribute
CString fLMAttribute(void* hSource)
{
CString buf = "";
CString hlp;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString qcat;
long count = 0;
BOOL result;
bool exc = false;
TAttribute_Recordset rs ((CDatabase *) hSource);
TCategory_list rscat ((CDatabase *) hSource);
Attribute_Meta * ptatt;
TAttribute_Meta_Array list;
TCtgr cat;
LPCTSTR q =
"SELECT * \
FROM tmAttribute, tmMatrix, tsAttributeSubType \
WHERE tmAttribute.MatrixID=tmMatrix.MatrixID \
AND tmAttribute.AttributeSubTypeID=tsAttributeSubType.AttributeSubTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ptatt = new (Attribute_Meta);
ptatt->attr_name = rs.m_Name;
ptatt->db_name = db_name;
ptatt->matrix_name = rs.m_Name2;
hlp.Format ("%d", rs.m_AttributeID);
ptatt->id = "attr" + hlp;
if (rs.m_Formula == "")
ptatt->creation = rs.m_Name;
else ptatt->creation = rs.m_Formula;
hlp.Format ("%d", rs.m_AttributeID);
qcat =
"SELECT * \
FROM tmAttribute, tmCategory, tmQuantity \
WHERE tmAttribute.AttributeID=" + hlp + " \
AND tmAttribute.AttributeID=tmQuantity.AttributeID \
AND tmQuantity.QuantityID=tmCategory.QuantityID";
try
{
result = rscat.Open(AFX_DB_USE_DEFAULT_TYPE, qcat);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rscat.IsEOF ())
{
count++;
hlp = rscat.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace ("<", "<");
hlp.Replace (">", ">");
cat.name = hlp;
cat.freq = "N/A";
ptatt->category_list.Add (cat);
//add missing category
if (rscat.m_XCategory)
ptatt->missing_type_list.Add (hlp);
rscat.MoveNext ();
}
rscat.Close ();
ptatt->ctgr_count.Format ("%d", count);
count = 0;
}
else return "";
list.Add (ptatt);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// --- AP category
CString fLMCategory(void* hSource)
{
CString buf = "";
CString hlp;
CString hlp1;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
long cat_id;
int count = 0;
int ord = 0;
TCategory_Meta_Array list;
Category_Meta * ptcat;
TCategory_Recordset rs ((CDatabase *) hSource);
TCatDefEnum rs_def_enum ((CDatabase *) hSource);
TCatDefInt rs_def_int_l ((CDatabase *) hSource);
TCatDefInt rs_def_int_r ((CDatabase *) hSource);
TCatOrder rs_ord ((CDatabase *) hSource);
TCatDefArray def;
CString subqenum;
CString subqintervall;
CString subqintervalr;
CString qord;
BOOL result;
bool exc = false;
LPCTSTR q =
"SELECT * \
FROM tmAttribute, tmCategory, tmMatrix, tmQuantity, tsBoolType, tsCategorySubType \
WHERE tmCategory.QuantityID=tmQuantity.QuantityID \
AND tmQuantity.AttributeID=tmAttribute.AttributeID \
AND tmAttribute.MatrixID=tmMatrix.MatrixID \
AND tmCategory.CategorySubTypeID=tsCategorySubType.CategorySubTypeID \
AND tmCategory.BoolTypeID = tsBoolType.BoolTypeID \
ORDER BY tmCategory.CategoryID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ptcat = new (Category_Meta);
ptcat->attr_name = rs.m_Name;
ptcat->ctgr_name = rs.m_Name2;
ptcat->ctgr_type = rs.m_Name6;
ptcat->db_name = db_name;
ptcat->matrix_name = rs.m_Name3;
cat_id = rs.m_CategoryID;
hlp.Format ("%d", cat_id);
ptcat->id = "cat" + hlp;
ptcat->ctgr_bool_type = rs.m_Name5;
if (rs.m_Name6 == "Enumeration")
{
subqenum =
"SELECT * \
FROM tmCategoryEnumValue, tmValue, tsValueSubType \
WHERE tmCategoryEnumValue.CategoryID=" + hlp +
" AND tmCategoryEnumValue.ValueID=tmValue.ValueID \
AND tmValue.ValueSubTypeID=tsValueSubType.ValueSubTypeID";
try
{
result = rs_def_enum.Open(AFX_DB_USE_DEFAULT_TYPE, subqenum);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_def_enum.IsEOF ())
{
if (rs_def_enum.m_Name == "Long integer")
hlp.Format ("%d", rs_def_enum.m_ValueLong);
else if (rs_def_enum.m_Name == "Float")
hlp = (LPCTSTR) (_bstr_t) rs_def_enum.m_ValueFloat;
else if (rs_def_enum.m_Name == "String")
hlp = rs_def_enum.m_ValueString;
else if (rs_def_enum.m_Name == "Boolean")
if (rs_def_enum.m_ValueBool) hlp = "TRUE";
else hlp = "FALSE";
else if (rs_def_enum.m_Name == "Date")
hlp = rs_def_enum.m_ValueDate.Format ("%d/%m/%Y %H:%M:%S");
ptcat->ctgr_def.Add (hlp);
count++;
rs_def_enum.MoveNext ();
}
ptcat->def_length = count;
count = 0;
rs_def_enum.Close ();
}
else return "";
}
else if ((rs.m_Name6 == "Interval") || (rs.m_Name6 == "Fuzzy interval"))
{
subqintervall =
"SELECT * \
FROM tmInterval, tmValue, tsBracketType, tsValueSubType \
WHERE tmInterval.CategoryID=" + hlp +
" AND tmInterval.FromValueID=tmValue.ValueID \
AND tmValue.ValueSubTypeID=tsValueSubType.ValueSubTypeID \
AND tmInterval.LeftBracketTypeID=tsBracketType.BracketTypeID";
subqintervalr =
"SELECT * \
FROM tmInterval, tmValue, tsBracketType, tsValueSubType \
WHERE tmInterval.CategoryID=" + hlp +
" AND tmInterval.ToValueID=tmValue.ValueID \
AND tmValue.ValueSubTypeID=tsValueSubType.ValueSubTypeID \
AND tmInterval.RightBracketTypeID=tsBracketType.BracketTypeID";
try
{
result = (rs_def_int_l.Open(AFX_DB_USE_DEFAULT_TYPE, subqintervall))
&&
(rs_def_int_r.Open(AFX_DB_USE_DEFAULT_TYPE, subqintervalr));
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while ((!rs_def_int_l.IsEOF ()) && (!rs_def_int_r.IsEOF ()))
{
hlp1 = rs_def_int_l.m_LeftBracket;
if (rs_def_int_l.m_Name2 == "Long integer")
hlp.Format ("%d", rs_def_int_l.m_ValueLong);
else if (rs_def_int_l.m_Name2 == "Float")
hlp = (LPCTSTR) (_bstr_t) rs_def_int_l.m_ValueFloat;
else if (rs_def_int_l.m_Name2 == "String")
hlp = rs_def_int_l.m_ValueString;
else if (rs_def_int_l.m_Name2 == "Boolean")
if (rs_def_int_l.m_ValueBool) hlp = "TRUE";
else hlp = "FALSE";
else if (rs_def_int_l.m_Name2 == "Date")
hlp = rs_def_int_l.m_ValueDate.Format ("%d/%m/%Y %H:%M:%S");
hlp1 += hlp;
hlp1 += ";";
if (rs_def_int_r.m_Name2 == "Long integer")
hlp.Format ("%d", rs_def_int_r.m_ValueLong);
else if (rs_def_int_r.m_Name2 == "Float")
hlp = (LPCTSTR) (_bstr_t) rs_def_int_r.m_ValueFloat;
else if (rs_def_int_r.m_Name2 == "String")
hlp = rs_def_int_r.m_ValueString;
else if (rs_def_int_r.m_Name2 == "Boolean")
if (rs_def_int_r.m_ValueBool) hlp = "TRUE";
else hlp = "FALSE";
else if (rs_def_int_r.m_Name2 == "Date")
hlp = rs_def_int_r.m_ValueDate.Format ("%d/%m/%Y %H:%M:%S");
hlp1 += hlp;
hlp1 += rs_def_int_r.m_RightBracket;
hlp1.Replace ("&", "&");
hlp1.Replace (">", ">");
hlp1.Replace ("<", "<");
ptcat->ctgr_def.Add (hlp1);
count++;
rs_def_int_l.MoveNext ();
rs_def_int_r.MoveNext ();
}
ptcat->def_length = count;
count = 0;
rs_def_int_l.Close ();
rs_def_int_r.Close ();
}
else return "";
}
else return "";
ptcat->ctgr_freq = "N/A";
list.Add (ptcat);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// --- AP 4ft-hypothese
CString fLM4fthyp_hlp(void * hSource, bool ar2nl)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
THyp_4ft_Meta_Array list;
Hyp_4ft_Recordset rs ((CDatabase *) hSource);
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
Hyp_4ft_Meta * pthyp;
long h_id;
long l_id;
long c_id;
long ld_id;//store the tdCedentDID
long h_id_tst = 0;//test variable - values from previous iteration
BOOL result;
bool exc = false;
BOOL neg_lit;
CString neg_lit_smbl;
CString ced_name;
CString q_name;
CString q_value;
CString q_type;
CString q_coef_type;
CString q = "SELECT * \
FROM taTask,tiCoefficient, tiHypothesis, tiLiteralI, tmCategory, \
tmMatrix, tmQuantity, tsCedentType, tsTaskSubType \
WHERE tiCoefficient.TaskID=taTask.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tiHypothesis.HypothesisID=tiLiteralI.HypothesisID \
AND tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tsCedentType.CedentTypeID=tiLiteralI.CedentTypeID \
AND tsTaskSubType.ShortName=";
q += "'CDASSOC'";
q += "AND taTask.TaskSubTypeID=tsTaskSubType.TaskSubTypeID \
ORDER BY taTask.TaskID, tiHypothesis.HypothesisID, \
tiLiteralI.CedentTypeID, tmQuantity.QuantityID, \
tmCategory.Ord";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisID;
l_id = rs.m_LiteralIID2;
ld_id = rs.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
q_type = rs_coef_type.m_ShortName;
q_type.Replace ("&", "&");
q_type.Replace (">", ">");
q_type.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
neg_lit = rs.m_Negation;
ced_name = rs.m_Name5;
c_id = rs.m_CategoryID2;
q_name = rs.m_Name4;
q_name.Replace ("&", "&");
q_name.Replace (">", ">");
q_name.Replace ("<", "<");
q_value = rs.m_Name2;
q_value.Replace ("&", "&");
q_value.Replace (">", ">");
q_value.Replace ("<", "<");
if (h_id != h_id_tst)
{
pthyp = new (Hyp_4ft_Meta);
pthyp->ar2nl_sentences = "";
id_hlp.Format ("%d", h_id);
if (!ar2nl) pthyp->id = "hyp4ft" + id_hlp;
else pthyp->id = "hyp4ftar2nl" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name3;
pthyp->task_name = rs.m_Name;
pthyp->a = rs.m_FreqA;
pthyp->b = rs.m_FreqB;
pthyp->c = rs.m_FreqC;
pthyp->d = rs.m_FreqD;
pthyp->conf = ((double)rs.m_FreqA/(rs.m_FreqA+rs.m_FreqB));
pthyp->d_conf = ((double)rs.m_FreqA/(rs.m_FreqA+rs.m_FreqB+rs.m_FreqC));
pthyp->e_conf = ((double)(rs.m_FreqA+rs.m_FreqD)/(rs.m_FreqA+rs.m_FreqB+rs.m_FreqC+rs.m_FreqD));
pthyp->support = ((double)rs.m_FreqA/(rs.m_FreqA+rs.m_FreqB+rs.m_FreqC+rs.m_FreqD));
pthyp->completeness = ((double)rs.m_FreqA/(rs.m_FreqA+rs.m_FreqC));
pthyp->avg_diff = ((double)rs.m_FreqA*(rs.m_FreqA+rs.m_FreqB+rs.m_FreqC+rs.m_FreqD)/((rs.m_FreqA+rs.m_FreqB)*(rs.m_FreqA+rs.m_FreqC))- 1);
pthyp->low_bnd_imp = pthyp->get_low_bnd_imp ();
pthyp->up_bnd_imp = pthyp->get_up_bnd_imp ();
pthyp->low_bnd_dbl_imp = pthyp->get_low_bnd_dbl_imp ();
pthyp->up_bnd_dbl_imp = pthyp->get_up_bnd_dbl_imp ();
pthyp->low_bnd_eq = pthyp->get_low_bnd_eq ();
pthyp->up_bnd_eq = pthyp->get_up_bnd_eq ();
pthyp->fisher = pthyp->get_fisher ();
pthyp->chi_sq = pthyp->get_chi_sq ();
ar2nl_err = false;
try
{
if (ar2nl) pthyp->ar2nl_sentences = Get_4ftAR2NL (h_id, db_name);
}
catch (...)
{
ar2nl_err = true;
}
if (ar2nl_err)
{
CLMSock::ReportError (10, LMERR_AR2NL_ERR);
return "";
}
pthyp->ant_id = "ant" + pthyp->id;
pthyp->suc_id = "suc" + pthyp->id;
pthyp->con_id = "con" + pthyp->id;
list.Add (pthyp);
}
if (ced_name == "Antecedent")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->antecedent.Add (x);
}
else if (ced_name == "Succedent")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->succedent.Add (x);
}
else if (ced_name == "Condition")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->condition.Add (x);
}
else return "";//error
rs.MoveNext();
h_id_tst = h_id;
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert (ar2nl);
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
CString fLM4fthyp (void * hSource)
{
return fLM4fthyp_hlp (hSource, false);
}
CString fLM4fthyp_ar2nl(void* hSource)
{
return fLM4fthyp_hlp (hSource, true);
}
// --- AP CF-hypothese
CString fLMCFhyp(void* hSource)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
CString hlp;
CString q_coef_type;
THyp_CF_Meta_Array list;
Hyp_CF_Recordset rs ((CDatabase *) hSource);
tiCFFrequencyI_Recordset rs_freq ((CDatabase *) hSource);
tmCategory_Recordset rs_attr ((CDatabase *) hSource);
TCondition_Recordset rs_cond ((CDatabase *) hSource);
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
Hyp_CF_Meta * pthyp;
long h_id;
long ld_id;
BOOL result;
bool exc = false;;
CString neg_lit_smbl;
CString q_name;
CString q_value;
Hyp_tiLiteral lit;
CString q = "SELECT * \
FROM taTask, tdCFLiteralD, tiHypothesisCF, tmMatrix, tmQuantity \
WHERE taTask.TaskID=tiHypothesisCF.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tiHypothesisCF.CFLiteralDID=tdCFLiteralD.CFLiteralDID \
AND tdCFLiteralD.QuantityID=tmQuantity.QuantityID";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisCFID;
pthyp = new (Hyp_CF_Meta);
id_hlp.Format ("%d", h_id);
pthyp->id = "hypCF" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name2;
pthyp->task_name = rs.m_Name;
pthyp->quant = rs.m_Name3;
pthyp->a_id = "attr_" + pthyp->id;
pthyp->c_id = "cond_" + pthyp->id;
id_hlp.Format ("%d", rs.m_HypothesisCFID);
CString q_freq = "SELECT * \
FROM tiCFFrequencyI \
WHERE tiCFFrequencyI.HypothesisCFID=" + id_hlp +
" ORDER BY Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_freq.IsEOF())
{
pthyp->frequencies.Add (rs_freq.m_Frequency);
rs_freq.MoveNext();
}
rs_freq.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_QuantityID2);
CString q_attr = "SELECT * \
FROM tmCategory \
WHERE tmCategory.QuantityID=" + id_hlp;
q_attr += " ORDER BY Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_attr_cf;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->attributes.Add (hlp);
next_attr_cf:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_HypothesisID);
CString q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiCFLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->condition.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
pthyp->asym = "Unknown";
pthyp->avg_a = "Unknown";
pthyp->avg_g = "Unknown";
pthyp->dor_var = pthyp->get_dor_var ();
hlp.Format ("%d", pthyp->get_max ());
pthyp->max = hlp;
pthyp->min = pthyp->get_min ();
pthyp->nom_var = pthyp->get_nom_var ();
pthyp->skew = "Unknown";
pthyp->st_dev = "Unknown";
hlp.Format ("%d", pthyp->get_sum ());
pthyp->sum = hlp;
pthyp->v = "Unknown";
pthyp->var = "Unknown";
list.Add (pthyp);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
list.GetAt (i)->attributes.RemoveAll ();
list.GetAt (i)->condition.RemoveAll ();
list.GetAt (i)->frequencies.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// --- AP SD4FT-hypothese
CString fLMSD4fthyp(void * hSource)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
THyp_SD4ft_Meta_Array list;
Hyp_SD4ft_Recordset rs ((CDatabase *) hSource);
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
Hyp_SD4ft_Meta * pthyp;
long h_id;
long l_id;
long c_id;
long h_id_tst = 0;//test variable - values from previous iteration
long ld_id;//store the tdCedentDID
BOOL result;
bool exc = false;
BOOL neg_lit;
CString neg_lit_smbl;
CString ced_name;
CString q_name;
CString q_value;
CString q_type;
CString q_coef_type;
CString q = "SELECT * \
FROM taTask,tiCoefficient, tiHypothesisDF, tiLiteralI, tmCategory, \
tmMatrix, tmQuantity, tsCedentType \
WHERE tiCoefficient.TaskID=taTask.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tiHypothesisDF.HypothesisID=tiLiteralI.HypothesisID \
AND tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tsCedentType.CedentTypeID=tiLiteralI.CedentTypeID \
ORDER BY taTask.TaskID, tiHypothesisDF.HypothesisID, \
tiLiteralI.CedentTypeID, tmQuantity.QuantityID, \
tmCategory.Ord";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisDFID;
l_id = rs.m_LiteralIID2;
ld_id = rs.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
q_type = rs_coef_type.m_ShortName;
q_type.Replace ("&", "&");
q_type.Replace (">", ">");
q_type.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
neg_lit = rs.m_Negation;
ced_name = rs.m_Name5;
c_id = rs.m_CategoryID2;
q_name = rs.m_Name4;
q_name.Replace ("&", "&");
q_name.Replace (">", ">");
q_name.Replace ("<", "<");
q_value = rs.m_Name2;
q_value.Replace ("&", "&");
q_value.Replace (">", ">");
q_value.Replace ("<", "<");
if (h_id != h_id_tst)
{
pthyp = new (Hyp_SD4ft_Meta);
id_hlp.Format ("%d", h_id);
pthyp->id = "hypSD4ft" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name3;
pthyp->task_name = rs.m_Name;
pthyp->a.Format ("%d", rs.m_FirstFreqA);
pthyp->b.Format ("%d", rs.m_FirstFreqB);
pthyp->c.Format ("%d", rs.m_FirstFreqC);
pthyp->d.Format ("%d", rs.m_FirstFreqD);
pthyp->e.Format ("%d", rs.m_SecondFreqA);
pthyp->f.Format ("%d", rs.m_SecondFreqB);
pthyp->g.Format ("%d", rs.m_SecondFreqC);
pthyp->h.Format ("%d", rs.m_SecondFreqD);
pthyp->conf1 = (LPCTSTR) (_bstr_t)
(pthyp->get_conf (rs.m_FirstFreqA, rs.m_FirstFreqB));
pthyp->d_conf1 = (LPCTSTR) (_bstr_t)
(pthyp->get_d_conf (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC));
pthyp->e_conf1 = (LPCTSTR) (_bstr_t)
(pthyp->get_e_conf (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->support1 = (LPCTSTR) (_bstr_t)
(pthyp->get_support (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->completeness1 = (LPCTSTR) (_bstr_t)
(pthyp->get_completeness (rs.m_FirstFreqA, rs.m_FirstFreqC));
pthyp->avg_diff1 = (LPCTSTR) (_bstr_t)
(pthyp->get_avg_diff (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->low_bnd_imp1 =
(pthyp->get_low_bnd_imp (rs.m_FirstFreqA, rs.m_FirstFreqB));
pthyp->up_bnd_imp1 =
(pthyp->get_up_bnd_imp (rs.m_FirstFreqA, rs.m_FirstFreqB));
pthyp->low_bnd_dbl_imp1 =
(pthyp->get_low_bnd_dbl_imp (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC));
pthyp->up_bnd_dbl_imp1 =
(pthyp->get_up_bnd_dbl_imp (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC));
pthyp->low_bnd_eq1 =
(pthyp->get_low_bnd_eq (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->up_bnd_eq1 =
(pthyp->get_up_bnd_eq (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->fisher1 =
(pthyp->get_fisher (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->chi_sq1 = (LPCTSTR) (_bstr_t)
(pthyp->get_chi_sq (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD));
pthyp->conf2 = (LPCTSTR) (_bstr_t)
(pthyp->get_conf (rs.m_SecondFreqA, rs.m_SecondFreqB));
pthyp->d_conf2 = (LPCTSTR) (_bstr_t)
(pthyp->get_d_conf (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC));
pthyp->e_conf2 = (LPCTSTR) (_bstr_t)
(pthyp->get_e_conf (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->support2 = (LPCTSTR) (_bstr_t)
(pthyp->get_support (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->completeness2 = (LPCTSTR) (_bstr_t)
(pthyp->get_completeness (rs.m_SecondFreqA, rs.m_SecondFreqC));
pthyp->avg_diff2 = (LPCTSTR) (_bstr_t)
(pthyp->get_avg_diff (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->low_bnd_imp2 =
(pthyp->get_low_bnd_imp (rs.m_SecondFreqA, rs.m_SecondFreqB));
pthyp->up_bnd_imp2 =
(pthyp->get_up_bnd_imp (rs.m_SecondFreqA, rs.m_SecondFreqB));
pthyp->low_bnd_dbl_imp2 =
(pthyp->get_low_bnd_dbl_imp (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC));
pthyp->up_bnd_dbl_imp2 =
(pthyp->get_up_bnd_dbl_imp (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC));
pthyp->low_bnd_eq2 =
(pthyp->get_low_bnd_eq (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->up_bnd_eq2 =
(pthyp->get_up_bnd_eq (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->fisher2 =
(pthyp->get_fisher (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->chi_sq2 = (LPCTSTR) (_bstr_t)
(pthyp->get_chi_sq (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->dr_sum = (LPCTSTR) (_bstr_t) (
pthyp->get_dr_sum ( rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD,
rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->df_conf = (LPCTSTR) (_bstr_t) (pthyp->get_conf (rs.m_FirstFreqA, rs.m_FirstFreqB) -
pthyp->get_conf (rs.m_SecondFreqA, rs.m_SecondFreqB));
pthyp->df_dfui = (LPCTSTR) (_bstr_t) (pthyp->get_d_conf (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC) -
pthyp->get_d_conf (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC));
pthyp->df_fue = (LPCTSTR) (_bstr_t) (pthyp->get_e_conf (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD) -
pthyp->get_e_conf (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->df_avg = (LPCTSTR) (_bstr_t) (pthyp->get_avg_diff (rs.m_FirstFreqA, rs.m_FirstFreqB, rs.m_FirstFreqC, rs.m_FirstFreqD) -
pthyp->get_avg_diff (rs.m_SecondFreqA, rs.m_SecondFreqB, rs.m_SecondFreqC, rs.m_SecondFreqD));
pthyp->ant_id = "ant" + pthyp->id;
pthyp->suc_id = "suc" + pthyp->id;
pthyp->con_id = "con" + pthyp->id;
pthyp->set1_id = "set1" + pthyp->id;
pthyp->set2_id = "set2" + pthyp->id;
list.Add (pthyp);
}
if (ced_name == "Antecedent")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->antecedent.Add (x);
}
else if (ced_name == "Succedent")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->succedent.Add (x);
}
else if (ced_name == "Condition")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->condition.Add (x);
}
else if (ced_name == "First set")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->set1.Add (x);
}
else if (ced_name == "Second set")
{
Hyp_tiLiteral x;
id_hlp.Format ("%d", l_id);
x.id = "tiLit" + id_hlp + pthyp->id;
id_hlp.Format ("%d", c_id);
x.id = x.id + id_hlp;
if (neg_lit) neg_lit_smbl = "¬"; else neg_lit_smbl = "";
x.quant = neg_lit_smbl + q_name;
x.value = q_value;
x.coef_type = q_type;
pthyp->set2.Add (x);
}
else return "";//error
rs.MoveNext();
h_id_tst = h_id;
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
// --- AP SDCF-hypothese
CString fLMSDCFhyp(void * hSource)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
CString hlp;
CString q_coef_type;
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
THyp_SDCF_Meta_Array list;
Hyp_SDCF_Recordset rs ((CDatabase *) hSource);
tiDCFrequencyI_Recordset rs_freq ((CDatabase *) hSource);
tmCategory_Recordset rs_attr ((CDatabase *) hSource);
TCondition_Recordset rs_cond ((CDatabase *) hSource);
Hyp_SDCF_Meta * pthyp;
long h_id;
long ld_id;
BOOL result;
bool exc = false;
CString neg_lit_smbl;
CString q_name;
CString q_value;
Hyp_tiLiteral lit;
CString q = "SELECT * \
FROM taTask, tdCFLiteralD, tiHypothesisDC, tmMatrix, tmQuantity \
WHERE taTask.TaskID=tiHypothesisDC.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID \
AND tiHypothesisDC.CFLiteralDID=tdCFLiteralD.CFLiteralDID \
AND tdCFLiteralD.QuantityID=tmQuantity.QuantityID";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisDCID;
pthyp = new (Hyp_SDCF_Meta);
id_hlp.Format ("%d", h_id);
pthyp->id = "hypDC" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name2;
pthyp->task_name = rs.m_Name;
pthyp->quant = rs.m_Name3;
pthyp->a_id = "attr_" + pthyp->id;
pthyp->c_id = "cond_" + pthyp->id;
pthyp->s1_id = "set1_" + pthyp->id;
pthyp->s2_id = "set2_" + pthyp->id;
id_hlp.Format ("%d", rs.m_HypothesisDCID);
CString q_freq = "SELECT * \
FROM tiDCFrequencyI \
WHERE tiDCFrequencyI.CedentTypeID = 5 \
AND tiDCFrequencyI.HypothesisDCID=" + id_hlp +
" ORDER BY Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_freq.IsEOF())
{
pthyp->frequencies1.Add (rs_freq.m_Frequency);
rs_freq.MoveNext();
}
rs_freq.Close();
}
else return "";
q_freq = "SELECT * \
FROM tiDCFrequencyI \
WHERE tiDCFrequencyI.CedentTypeID = 6 \
AND tiDCFrequencyI.HypothesisDCID=" + id_hlp +
" ORDER BY Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_freq.IsEOF())
{
pthyp->frequencies2.Add (rs_freq.m_Frequency);
rs_freq.MoveNext();
}
rs_freq.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_QuantityID2);
CString q_attr = "SELECT * \
FROM tmCategory \
WHERE tmCategory.QuantityID=" + id_hlp;
q_attr += " ORDER BY Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_attr_sdcf;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->attributes.Add (hlp);
next_attr_sdcf:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
//condition
id_hlp.Format ("%d", rs.m_HypothesisID);
CString q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=4 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiCFLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->condition.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
//first set
id_hlp.Format ("%d", rs.m_HypothesisID);
q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=5 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiCFLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->set1.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
//second set
id_hlp.Format ("%d", rs.m_HypothesisID);
q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=6 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiDCLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->set2.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
pthyp->asym1 = "Unknown";
pthyp->avg_a1 = "Unknown";
pthyp->avg_g1 = "Unknown";
pthyp->dor_var1 = pthyp->get_dor_var1 ();
hlp.Format ("%d", pthyp->get_max1 ());
pthyp->max1 = hlp;
pthyp->min1 = pthyp->get_min1 ();
pthyp->nom_var1 = pthyp->get_nom_var1 ();
pthyp->skew1 = "Unknown";
pthyp->st_dev1 = "Unknown";
hlp.Format ("%d", pthyp->get_sum1 ());
pthyp->sum1 = hlp;
pthyp->v1 = "Unknown";
pthyp->var1 = "Unknown";
pthyp->asym2 = "Unknown";
pthyp->avg_a2 = "Unknown";
pthyp->avg_g2 = "Unknown";
pthyp->dor_var2 = pthyp->get_dor_var2 ();
hlp.Format ("%d", pthyp->get_max2 ());
pthyp->max2 = hlp;
pthyp->min2 = pthyp->get_min2 ();
pthyp->nom_var2 = pthyp->get_nom_var2 ();
pthyp->skew2 = "Unknown";
pthyp->st_dev2 = "Unknown";
hlp.Format ("%d", pthyp->get_sum2 ());
pthyp->sum2 = hlp;
pthyp->v2 = "Unknown";
pthyp->var2 = "Unknown";
pthyp->da_sum = pthyp->get_da_sum ();
pthyp->da_min = pthyp->get_da_min ();
pthyp->da_max = pthyp->get_da_max ();
pthyp->dr_sum = pthyp->get_dr_sum ();;
pthyp->dr_min = pthyp->get_dr_min ();
pthyp->dr_max = pthyp->get_dr_max ();
list.Add (pthyp);
rs.MoveNext();
}
rs.Close();
}
else return "";
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
list.GetAt (i)->attributes.RemoveAll ();
list.GetAt (i)->condition.RemoveAll ();
list.GetAt (i)->frequencies1.RemoveAll ();
list.GetAt (i)->frequencies2.RemoveAll ();
list.GetAt (i)->set1.RemoveAll ();
list.GetAt (i)->set2.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
CString fLMKLhyp(void* hSource)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
CString hlp;
CString q_coef_type;
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
THyp_KL_Meta_Array list;
Hyp_KL_Recordset rs ((CDatabase *) hSource);
tiKLFrequencyI_Recordset rs_freq ((CDatabase *) hSource);
TKLCategory_Recordset rs_attr ((CDatabase *) hSource);
TCondition_Recordset rs_cond ((CDatabase *) hSource);
TKLquant_Recordset rs_quant ((CDatabase *) hSource);
Hyp_KL_Meta * pthyp;
long h_id;
long ld_id;
long row;
BOOL result;
bool exc = false;
CString neg_lit_smbl;
CString q_name;
CString q_value;
Cint_Array * row_freq_hlp;
Hyp_tiLiteral lit;
CString q = "SELECT * \
FROM taTask, tiHypothesisKL, tmMatrix \
WHERE taTask.TaskID=tiHypothesisKL.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisKLID;
pthyp = new (Hyp_KL_Meta);
id_hlp.Format ("%d", h_id);
pthyp->id = "hypKL" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name2;
pthyp->task_name = rs.m_Name;
id_hlp.Format ("%d", rs.m_KLLiteralDColID);
CString q_quant = "SELECT * \
FROM tdKLLiteralD, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
//single row returned expected
try
{
result = rs_quant.Open(AFX_DB_USE_DEFAULT_TYPE, q_quant);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_quant.IsEOF())
{
pthyp->quant_col = rs_quant.m_Name;
rs_quant.MoveNext();
}
rs_quant.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDRowID);
q_quant = "SELECT * \
FROM tdKLLiteralD, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
//single row returned expected
try
{
result = rs_quant.Open(AFX_DB_USE_DEFAULT_TYPE, q_quant);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_quant.IsEOF())
{
pthyp->quant_row = rs_quant.m_Name;
rs_quant.MoveNext();
}
rs_quant.Close();
}
else return "";
pthyp->row_id = "attr_row_" + pthyp->id;
pthyp->col_id = "attr_col_" + pthyp->id;
pthyp->c_id = "cond_" + pthyp->id;
id_hlp.Format ("%d", rs.m_HypothesisKLID);
CString q_freq = "SELECT * \
FROM tiKLFrequencyI \
WHERE tiKLFrequencyI.HypothesisKLID=" + id_hlp +
" ORDER BY Row, Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
row_freq_hlp = new (Cint_Array);
row = -1;
while (!rs_freq.IsEOF())
{
if ((row != rs_freq.m_Row) && (row != -1))
{
pthyp->table.Add (row_freq_hlp);
row_freq_hlp = new (Cint_Array);
}
row_freq_hlp->Add (rs_freq.m_Frequency);
row = rs_freq.m_Row;
rs_freq.MoveNext();
}
rs_freq.Close();
if (row_freq_hlp->GetSize () > 0)
pthyp->table.Add (row_freq_hlp);
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDColID);
CString q_attr = "SELECT * \
FROM tdKLLiteralD, tmCategory, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
q_attr += " ORDER BY tmCategory.Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_col_kl;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->column_attributes.Add (hlp);
next_col_kl:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDRowID);
q_attr = "SELECT * \
FROM tdKLLiteralD, tmCategory, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
q_attr += " ORDER BY tmCategory.Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_row_kl;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->row_attributes.Add (hlp);
next_row_kl:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_HypothesisID);
CString q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiKLLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->condition.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
hlp.Format ("%d", pthyp->get_sum ());
pthyp->sum = hlp;
pthyp->min = pthyp->get_min ();
hlp.Format ("%d", pthyp->get_max ());
pthyp->max = hlp;
pthyp->chi_sq = pthyp->get_chi_sq ();
pthyp->fnc_s = pthyp->get_fnc_s ();
pthyp->fnc_r = pthyp->get_fnc_r ();
pthyp->mi = pthyp->get_mi ();
if (pthyp->mi == "Unknown")
{
pthyp->h_c = "Unknown";
pthyp->h_r = "Unknown";
pthyp->h_c_r = "Unknown";
}
else
{
pthyp->h_c = (LPCTSTR) (_bstr_t) pthyp->get_h_c ();
pthyp->h_r = (LPCTSTR) (_bstr_t) pthyp->get_h_r ();
pthyp->h_c_r = (LPCTSTR) (_bstr_t) pthyp->get_h_c_r ();
}
pthyp->aic = pthyp->get_aic ();
pthyp->kend = pthyp->get_kend ();
list.Add (pthyp);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
list.GetAt (i)->row_attributes.RemoveAll ();
list.GetAt (i)->column_attributes.RemoveAll ();
list.GetAt (i)->condition.RemoveAll ();
for (int j = 0; j < list.GetAt (i)->table.GetSize (); j++)
{
for (int k = 0; list.GetAt (i)->table.GetAt (j)->GetSize (); k++)
{
list.GetAt (i)->table.GetAt (j)->RemoveAll ();
}
delete (list.GetAt (i)->table.GetAt (j));
}
list.GetAt (i)->table.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
CString fLMSDKLhyp(void* hSource)
{
CString buf;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString id_hlp;
CString hlp;
CString q_coef_type;
TCoef_type_Recordset rs_coef_type ((CDatabase *) hSource);
THyp_SDKL_Meta_Array list;
Hyp_SDKL_Recordset rs ((CDatabase *) hSource);
tiDKFrequencyI_Recordset rs_freq ((CDatabase *) hSource);
TKLCategory_Recordset rs_attr ((CDatabase *) hSource);
TCondition_Recordset rs_cond ((CDatabase *) hSource);
TKLquant_Recordset rs_quant ((CDatabase *) hSource);
Hyp_SDKL_Meta * pthyp;
long h_id;
long ld_id;
long row;
BOOL result;
bool exc = false;
CString neg_lit_smbl;
CString q_name;
CString q_value;
Cint_Array * row_freq_hlp;
Hyp_tiLiteral lit;
CString q = "SELECT * \
FROM taTask, tiHypothesisDK, tmMatrix \
WHERE taTask.TaskID=tiHypothesisDK.TaskID \
AND taTask.MatrixID=tmMatrix.MatrixID";
//load data from metabase
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
h_id = rs.m_HypothesisDKID;
pthyp = new (Hyp_SDKL_Meta);
id_hlp.Format ("%d", h_id);
pthyp->id = "hypSDKL" + id_hlp;
pthyp->db_name = db_name;
pthyp->matrix_name = rs.m_Name2;
pthyp->task_name = rs.m_Name;
id_hlp.Format ("%d", rs.m_KLLiteralDColID);
CString q_quant = "SELECT * \
FROM tdKLLiteralD, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
//single row returned expected
try
{
result = rs_quant.Open(AFX_DB_USE_DEFAULT_TYPE, q_quant);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_quant.IsEOF())
{
pthyp->quant_col = rs_quant.m_Name;
rs_quant.MoveNext();
}
rs_quant.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDRowID);
q_quant = "SELECT * \
FROM tdKLLiteralD, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
//single row returned expected
try
{
result = rs_quant.Open(AFX_DB_USE_DEFAULT_TYPE, q_quant);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_quant.IsEOF())
{
pthyp->quant_row = rs_quant.m_Name;
rs_quant.MoveNext();
}
rs_quant.Close();
}
else return "";
pthyp->row_id = "attr_row_" + pthyp->id;
pthyp->col_id = "attr_col_" + pthyp->id;
pthyp->c_id = "cond_" + pthyp->id;
pthyp->s1_id = "set1_" + pthyp->id;
pthyp->s2_id = "set2_" + pthyp->id;
id_hlp.Format ("%d", rs.m_HypothesisDKID);
//first set frequencies
CString q_freq = "SELECT * \
FROM tiDKFrequencyI \
WHERE HypothesisDKID=" + id_hlp +
" AND CedentTypeID=5 \
ORDER BY Row, Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
row_freq_hlp = new (Cint_Array);
row = -1;
while (!rs_freq.IsEOF())
{
if ((row != rs_freq.m_Row) && (row != -1))
{
pthyp->table1.Add (row_freq_hlp);
row_freq_hlp = new (Cint_Array);
}
row_freq_hlp->Add (rs_freq.m_Frequency);
row = rs_freq.m_Row;
rs_freq.MoveNext();
}
rs_freq.Close();
if (row_freq_hlp->GetSize () > 0)
pthyp->table1.Add (row_freq_hlp);
}
else return "";
//second set frequencies
q_freq = "SELECT * \
FROM tiDKFrequencyI \
WHERE HypothesisDKID=" + id_hlp +
" AND CedentTypeID=6 \
ORDER BY Row, Col";
try
{
result = rs_freq.Open(AFX_DB_USE_DEFAULT_TYPE, q_freq);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
row_freq_hlp = new (Cint_Array);
row = -1;
while (!rs_freq.IsEOF())
{
if ((row != rs_freq.m_Row) && (row != -1))
{
pthyp->table2.Add (row_freq_hlp);
row_freq_hlp = new (Cint_Array);
}
row_freq_hlp->Add (rs_freq.m_Frequency);
row = rs_freq.m_Row;
rs_freq.MoveNext();
}
rs_freq.Close();
if (row_freq_hlp->GetSize () > 0)
pthyp->table2.Add (row_freq_hlp);
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDColID);
CString q_attr = "SELECT * \
FROM tdKLLiteralD, tmCategory, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
q_attr += " ORDER BY tmCategory.Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_col_sdkl;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->column_attributes.Add (hlp);
next_col_sdkl:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
id_hlp.Format ("%d", rs.m_KLLiteralDRowID);
q_attr = "SELECT * \
FROM tdKLLiteralD, tmCategory, tmQuantity \
WHERE tdKLLiteralD.QuantityID=tmQuantity.QuantityID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tdKLLiteralD.KLLiteralDID=" + id_hlp;
q_attr += " ORDER BY tmCategory.Ord";
try
{
result = rs_attr.Open(AFX_DB_USE_DEFAULT_TYPE, q_attr);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_attr.IsEOF())
{
if (rs_attr.m_XCategory) goto next_row_sdkl;
hlp = rs_attr.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
pthyp->row_attributes.Add (hlp);
next_row_sdkl:
rs_attr.MoveNext();
}
rs_attr.Close();
}
else return "";
//condition
id_hlp.Format ("%d", rs.m_HypothesisID);
CString q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=4 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiDKLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->condition.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
//first set
id_hlp.Format ("%d", rs.m_HypothesisID);
q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=5 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiDKLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->set1.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
//second set
id_hlp.Format ("%d", rs.m_HypothesisID);
q_cond = "SELECT * \
FROM tiCoefficient, tiLiteralI, tmCategory, tmQuantity \
WHERE tiLiteralI.LiteralIID=tiCoefficient.LiteralIID \
AND tiLiteralI.CedentTypeID=6 \
AND tiCoefficient.CategoryID=tmCategory.CategoryID \
AND tmCategory.QuantityID=tmQuantity.QuantityID \
AND tiLiteralI.HypothesisID=" + id_hlp +
" ORDER BY tmQuantity.QuantityID, tmCategory.Ord";
try
{
result = rs_cond.Open(AFX_DB_USE_DEFAULT_TYPE, q_cond);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs_cond.IsEOF())
{
if (rs_cond.m_Negation)
neg_lit_smbl = "¬";
else
neg_lit_smbl = "";
id_hlp.Format ("%d", rs_cond.m_LiteralIID);
lit.id = "tiDKLit" + id_hlp + pthyp->id;
hlp = rs_cond.m_Name2;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.quant = neg_lit_smbl + hlp;
hlp = rs_cond.m_Name;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
lit.value = hlp;
ld_id = rs_cond.m_LiteralDID;
id_hlp.Format ("%d", ld_id);
//exactly one row expected to return by the following query:
q_coef_type = "SELECT * \
FROM tdLiteralD, tsCoefficientType \
WHERE LiteralDID=" + id_hlp;
q_coef_type +=
" AND tdLiteralD.CoefficientTypeID=tsCoefficientType.CoefficientTypeID";
try
{
result = rs_coef_type.Open(AFX_DB_USE_DEFAULT_TYPE, q_coef_type);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
while (!rs_coef_type.IsEOF())
{
hlp = rs_coef_type.m_ShortName;
hlp.Replace ("&", "&");
hlp.Replace (">", ">");
hlp.Replace ("<", "<");
rs_coef_type.MoveNext ();
}
rs_coef_type.Close ();
}
else return "";
lit.coef_type = hlp;
pthyp->set2.Add (lit);
rs_cond.MoveNext();
}
rs_cond.Close();
}
else return "";
hlp.Format ("%d", pthyp->get_sum1 ());
pthyp->sum1 = hlp;
pthyp->min1 = pthyp->get_min1 ();
hlp.Format ("%d", pthyp->get_max1 ());
pthyp->max1 = hlp;
pthyp->chi_sq1 = pthyp->get_chi_sq1 ();
pthyp->fnc_s1 = pthyp->get_fnc_s1 ();
pthyp->fnc_r1 = pthyp->get_fnc_r1 ();
pthyp->h_c1 = (LPCTSTR) (bstr_t) pthyp->get_h_c1 ();
pthyp->h_r1 = (LPCTSTR) (bstr_t) pthyp->get_h_r1 ();
pthyp->h_c_r1 = (LPCTSTR) (bstr_t) pthyp->get_h_c_r1 ();
pthyp->mi1 = pthyp->get_mi1 ();
pthyp->aic1 = pthyp->get_aic1 ();
pthyp->kend1 = pthyp->get_kend1 ();
hlp.Format ("%d", pthyp->get_sum2 ());
pthyp->sum2 = hlp;
pthyp->min2 = pthyp->get_min2 ();
hlp.Format ("%d", pthyp->get_max2 ());
pthyp->max2 = hlp;
pthyp->chi_sq2 = pthyp->get_chi_sq2 ();
pthyp->fnc_s2 = pthyp->get_fnc_s2 ();
pthyp->fnc_r2 = pthyp->get_fnc_r2 ();
pthyp->h_c2 = (LPCTSTR) (bstr_t) pthyp->get_h_c2 ();
pthyp->h_r2 = (LPCTSTR) (bstr_t) pthyp->get_h_r2 ();
pthyp->h_c_r2 = (LPCTSTR) (bstr_t) pthyp->get_h_c_r2 ();
pthyp->mi2 = pthyp->get_mi2 ();
pthyp->aic2 = pthyp->get_aic2 ();
pthyp->kend2 = pthyp->get_kend2 ();
pthyp->da_sum = pthyp->get_da_sum ();
pthyp->da_min = pthyp->get_da_min ();
pthyp->da_max = pthyp->get_da_max ();
pthyp->dr_sum = pthyp->get_dr_sum ();
pthyp->dr_min = pthyp->get_dr_min ();
pthyp->dr_max = pthyp->get_dr_max ();
list.Add (pthyp);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
list.GetAt (i)->row_attributes.RemoveAll ();
list.GetAt (i)->column_attributes.RemoveAll ();
list.GetAt (i)->condition.RemoveAll ();
list.GetAt (i)->set1.RemoveAll ();
list.GetAt (i)->set2.RemoveAll ();
int j;
for (j = 0; j < list.GetAt (i)->table1.GetSize (); j++)
{
for (int k = 0; list.GetAt (i)->table1.GetAt (j)->GetSize (); k++)
{
list.GetAt (i)->table1.GetAt (j)->RemoveAll ();
}
delete (list.GetAt (i)->table1.GetAt (j));
}
for (j = 0; j < list.GetAt (i)->table2.GetSize (); j++)
{
for (int k = 0; list.GetAt (i)->table2.GetAt (j)->GetSize (); k++)
{
list.GetAt (i)->table2.GetAt (j)->RemoveAll ();
}
delete (list.GetAt (i)->table2.GetAt (j));
}
list.GetAt (i)->table1.RemoveAll ();
list.GetAt (i)->table2.RemoveAll ();
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
CString fLMdata_matrix (void* hSource)
{
CString buf = "";
CString hlp;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
long matrix_id = -1;
long matrix_id_tst = 0;
BOOL result;
bool exc = false;
TData_Matrix_Recordset rs ((CDatabase *) hSource);
Data_Matrix_Meta * ptatt;
TData_Matrix_Meta_Array list;
LPCTSTR q =
"SELECT * \
FROM tmAttribute, tmMatrix, tsValueSubType \
WHERE tmAttribute.MatrixID=tmMatrix.MatrixID \
AND tmAttribute.ValueSubTypeID=tsValueSubType.ValueSubTypeID \
ORDER BY tmAttribute.MatrixID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
matrix_id_tst = rs.m_MatrixID;
if (matrix_id != matrix_id_tst)
{
hlp.Format ("%d", matrix_id_tst);
ptatt = new (Data_Matrix_Meta);
ptatt->db_name = db_name;
ptatt->id = "table" + hlp;
ptatt->matrix_name = rs.m_Name2;
ptatt->record_count = rs.m_RecordCount;
ptatt->integer_count = 0;
ptatt->float_count = 0;
ptatt->string_count = 0;
ptatt->boolean_count = 0;
ptatt->date_count = 0;
list.Add (ptatt);
}
if (rs.m_ShortName == "long") ptatt->integer_count++;
else if (rs.m_ShortName == "float") ptatt->float_count++;
else if (rs.m_ShortName == "string") ptatt->string_count++;
else if (rs.m_ShortName == "bool") ptatt->boolean_count++;
else if (rs.m_ShortName == "date") ptatt->date_count++;
matrix_id = matrix_id_tst;
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
}
CString fLMcolumn(void* hSource)
{
CString buf = "";
CString hlp;
CString db_name = ((CDatabase *) hSource)->GetDatabaseName ();
CString qcat;
long count = 0;
BOOL result;
bool exc = false;
TColumn_Recordset rs ((CDatabase *) hSource);
Column_Meta * ptatt;
TColumn_Meta_Array list;
CString q =
"SELECT * \
FROM tmAttribute, tmMatrix, tsAttributeSubType, tsValueSubType \
WHERE tmAttribute.MatrixID=tmMatrix.MatrixID \
AND tmAttribute.AttributeSubTypeID=tsAttributeSubType.AttributeSubTypeID \
AND tsAttributeSubType.ShortName=";
q += "'DB'";
q += "AND tmAttribute.ValueSubTypeID=tsValueSubType.ValueSubTypeID";
try
{
result = rs.Open(AFX_DB_USE_DEFAULT_TYPE, q);
}
catch (CDBException* e)
{
exc = true;
CLMSock::ReportError (11, LMERR_BAD_MDB_VERSION);
e->Delete ();
}
if (exc) return "";
if (result)
{
//iteration on query results
while (!rs.IsEOF())
{
ptatt = new (Column_Meta);
ptatt->column_name = rs.m_Name;
ptatt->db_name = db_name;
ptatt->matrix_name = rs.m_Name2;
hlp.Format ("%d", rs.m_AttributeID);
ptatt->id = "col" + hlp;
ptatt->value_type = rs.m_Name4;
ptatt->primary_key_position.Format("%d", rs.m_PrimaryKeyPosition);
ptatt->avg = (LPCSTR) (_bstr_t) rs.m_ValueAvg;
ptatt->min = (LPCSTR) (_bstr_t) rs.m_ValueMin;
ptatt->max = (LPCSTR) (_bstr_t) rs.m_ValueMax;
list.Add (ptatt);
rs.MoveNext();
}
rs.Close();
}
else return "";
//creation of xml string
//load DTD
try
{
buf = Get_DTD ();
}
catch (...)
{
CLMSock::ReportError (12, LMERR_DTD_ERROR);
return "";
}
//create xml data
buf = buf + " <active_list> ";
int i;
for (i = 0; i < list.GetSize (); i++)
{
buf = buf + list.GetAt (i)->xml_convert ();
}
buf += " </active_list>";
for (i = 0; i < list.GetSize (); i++)
{
delete (list.GetAt (i));
}
list.RemoveAll ();
return buf;
} | [
"kodyj1am@fded5620-0c03-0410-a24c-85322fa64ba0",
"chrzm@fded5620-0c03-0410-a24c-85322fa64ba0",
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0"
] | [
[
[
1,
1
],
[
22,
22
],
[
82,
87
],
[
89,
94
],
[
356,
356
],
[
1025,
1025
],
[
2223,
2223
],
[
2225,
2225
],
[
3468,
3469
],
[
3484,
3485
]
],
[
[
2,
21
],
[
23,
69
],
[
75,
78
],
[
80,
81
],
[
103,
104
],
[
106,
106
],
[
111,
111
],
[
113,
113
],
[
122,
122
],
[
128,
128
],
[
132,
132
],
[
134,
134
],
[
137,
137
],
[
144,
144
],
[
148,
148
],
[
153,
153
],
[
155,
155
],
[
157,
157
],
[
159,
159
],
[
169,
169
],
[
171,
171
],
[
181,
181
],
[
187,
188
],
[
190,
196
],
[
198,
198
],
[
200,
203
],
[
205,
206
],
[
210,
211
],
[
213,
224
],
[
234,
236
],
[
240,
240
],
[
244,
244
],
[
246,
246
],
[
248,
250
],
[
253,
255
],
[
257,
258
],
[
261,
266
],
[
269,
280
],
[
286,
309
],
[
311,
331
],
[
333,
340
],
[
342,
343
],
[
345,
346
],
[
350,
350
],
[
358,
358
],
[
360,
1024
],
[
1026,
1299
],
[
1302,
1497
],
[
1500,
1848
],
[
1851,
1979
],
[
1982,
2016
],
[
2018,
2030
],
[
2034,
2035
],
[
2037,
2204
],
[
2207,
2219
],
[
2222,
2222
],
[
2224,
2224
],
[
2227,
2429
],
[
2432,
2441
],
[
2443,
2444
],
[
2447,
2457
],
[
2460,
2470
],
[
2472,
2489
],
[
2491,
3467
],
[
3470,
3483
],
[
3486,
4560
],
[
4563,
4772
]
],
[
[
70,
74
],
[
79,
79
],
[
88,
88
],
[
95,
102
],
[
105,
105
],
[
107,
110
],
[
112,
112
],
[
114,
121
],
[
123,
127
],
[
129,
131
],
[
133,
133
],
[
135,
136
],
[
138,
143
],
[
145,
147
],
[
149,
152
],
[
154,
154
],
[
156,
156
],
[
158,
158
],
[
160,
168
],
[
170,
170
],
[
172,
180
],
[
182,
186
],
[
189,
189
],
[
197,
197
],
[
199,
199
],
[
204,
204
],
[
207,
209
],
[
212,
212
],
[
225,
233
],
[
237,
239
],
[
241,
243
],
[
245,
245
],
[
247,
247
],
[
251,
252
],
[
256,
256
],
[
259,
260
],
[
267,
268
],
[
281,
285
],
[
310,
310
],
[
332,
332
],
[
341,
341
],
[
344,
344
],
[
347,
349
],
[
351,
355
],
[
357,
357
],
[
359,
359
],
[
1300,
1301
],
[
1498,
1499
],
[
1849,
1850
],
[
1980,
1981
],
[
2017,
2017
],
[
2031,
2033
],
[
2036,
2036
],
[
2205,
2206
],
[
2220,
2221
],
[
2226,
2226
],
[
2430,
2431
],
[
2442,
2442
],
[
2445,
2446
],
[
2458,
2459
],
[
2471,
2471
],
[
2490,
2490
],
[
4561,
4562
]
]
] |
e7e045a06a906e8b02690dd4d56620129f33b088 | 5dc78c30093221b4d2ce0e522d96b0f676f0c59a | /src/modules/graphics/opengl/wrap_SpriteBatch.cpp | 29b8d66bc555b0147ffcd0a88cb496b5ea8e1c0c | [
"Zlib"
] | permissive | JackDanger/love | f03219b6cca452530bf590ca22825170c2b2eae1 | 596c98c88bde046f01d6898fda8b46013804aad6 | refs/heads/master | 2021-01-13T02:32:12.708770 | 2009-07-22T17:21:13 | 2009-07-22T17:21:13 | 142,595 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,144 | cpp | /**
* Copyright (c) 2006-2009 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "wrap_SpriteBatch.h"
namespace love
{
namespace graphics
{
namespace opengl
{
SpriteBatch * luax_checkspritebatch(lua_State * L, int idx)
{
return luax_checktype<SpriteBatch>(L, idx, "SpriteBatch", LOVE_GRAPHICS_SPRITE_BATCH_BITS);
}
int _wrap_SpriteBatch_add(lua_State * L)
{
SpriteBatch * t = luax_checkspritebatch(L, 1);
float x = (float)luaL_optnumber(L, 2, 0.0f);
float y = (float)luaL_optnumber(L, 3, 0.0f);
float angle = (float)luaL_optnumber(L, 4, 0.0f);
float sx = (float)luaL_optnumber(L, 5, 1.0f);
float sy = (float)luaL_optnumber(L, 6, sx);
float ox = (float)luaL_optnumber(L, 7, 0);
float oy = (float)luaL_optnumber(L, 8, 0);
t->add(x, y, angle, sx, sy, ox, oy);
return 0;
}
int _wrap_SpriteBatch_clear(lua_State * L)
{
SpriteBatch * t = luax_checkspritebatch(L, 1);
t->clear();
return 0;
}
static const luaL_Reg wrap_SpriteBatch_functions[] = {
{ "add", _wrap_SpriteBatch_add },
{ "clear", _wrap_SpriteBatch_clear },
{ 0, 0 }
};
int wrap_SpriteBatch_open(lua_State * L)
{
luax_register_type(L, "SpriteBatch", wrap_SpriteBatch_functions);
return 0;
}
} // opengl
} // graphics
} // love | [
"prerude@3494dbca-881a-0410-bd34-8ecbaf855390"
] | [
[
[
1,
69
]
]
] |
332f009c40f5c0e6ce1e19a31a9e910b42914c6f | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/inc/node/nlenseflare.h | 33973e5430658826ecae8dbb19093e9ff2f066d0 | [] | no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,749 | h | //==============================================================================
// node/nlenseflare.h
// author: Jeremy Bishop
// (C) 2000 Radon Labs GmbH
//------------------------------------------------------------------------------
#ifndef N_NLENSEFLARE_H
#define N_NLENSEFLARE_H
#ifndef N_VISNODE_H
#include "node/nvisnode.h"
#endif
#ifndef N_REF_H
#include "kernel/nref.h"
#endif
#ifndef N_SPECIALFXSERVER_H
#include "misc/nspecialfxserver.h"
#endif
#ifndef N_VECTOR_H
#include "mathlib/vector.h"
#endif
#ifndef N_MATRIX_H
#include "mathlib/matrix.h"
#endif
#ifndef N_DYNVERTEXBUFFER_H
#include "gfx/ndynvertexbuffer.h"
#endif
#undef N_DEFINES
#define N_DEFINES nLenseFlare
#include "kernel/ndefdllclass.h"
//------------------------------------------------------------------------------
struct nFlareDesc
{
friend class nLenseFlare;
nFlareDesc();
~nFlareDesc();
private:
float fSize; // length of one side of quad (flare)
float fHalfSize; // 1/2 of the size (used when placing quad on line)
float fPosition; // % distance from light source to center of screen;
// 0.0f places the flare over the light source, 1.0f
// places the flare at the center of the screen; higher
// values place the flare further along the line (2.0f
// places the flare opposite the light source, etc.),
// and negative values place the flare behind the light
float fRed; // the vertex coloring of the flare
float fGreen; // ...
float fBlue; // ...
float fAlpha; // ...
};
//------------------------------------------------------------------------------
inline
nFlareDesc::nFlareDesc(): fSize(0.125f),
fHalfSize(fSize / 2),
fPosition(1.0f),
fRed(1.0f),
fGreen(1.0f),
fBlue(1.0f),
fAlpha(1.0f)
{}
//------------------------------------------------------------------------------
inline
nFlareDesc::~nFlareDesc() {}
//------------------------------------------------------------------------------
class N_DLLCLASS nLenseFlare : public nVisNode
{
public:
nLenseFlare();
~nLenseFlare();
static nKernelServer* kernelServer;
virtual bool SaveCmds(nPersistServer*);
virtual bool Attach(nSceneGraph2*);
virtual void Compute(nSceneGraph2*);
virtual void BeginFlares(int iNumberOfFlares);
virtual void EndFlares();
virtual void SetBaseColor(float red, float grn, float blu, float alpha);
virtual void SetBlindColor(const vector4& vBlindClr);
virtual void SetFlareSizeAt(int ndx, float size);
virtual void SetFlarePosAt(int ndx, float pos);
virtual void SetFlareColorAt(int ndx,
float red,
float grn,
float blu,
float alpha);
virtual inline int GetNumberOfFlares();
virtual void GetBaseColor(float& red, float& grn, float& blu, float& alpha);
virtual vector4 GetBlindColor() const;
virtual inline float GetFlareSizeAt(int ndx);
virtual inline float GetFlarePosAt(int ndx);
virtual void GetFlareColorAt(int ndx,
float& red,
float& grn,
float& blu,
float& alpha);
protected:
virtual void InitVBuffer();
virtual void CalcSource2d();
virtual void PlaceFlares();
virtual void ColorFlares();
virtual void UVFlares();
virtual void Blind();
private:
enum {
MAXFLARES = 16,
};
nAutoRef<nGfxServer> ref_gs;
nDynVertexBuffer ref_dynvbuf;
nRef<nIndexBuffer> ref_ibuf;
nAutoRef<nSpecialFxServer> ref_fx;
nVertexBuffer *vb_dest;
matrix44 mModelView;
matrix44 mProjection;
nFlareDesc* aFlares;
ushort iNumberOfFlares;
vector4 vSource2d; // eventual pseudo-screen space position of light
bool bBegun; // signals that BeginFlares(...) has completed
bool bEnded; // signals that EndFlares(...) has completed
bool bWithinBounds; // signals that the lenseflare is visible
float fBaseRed, fBaseBlue, fBaseGreen, fBaseAlpha; // base color that is
// combined with float
// values received from
// a mixer (fix so that
// nlenseflare works
// with a mixer
vector4 vBlindColor; // blinding color when looking at light source
};
//------------------------------------------------------------------------------
inline
int
nLenseFlare::GetNumberOfFlares()
{
return iNumberOfFlares;
}
//------------------------------------------------------------------------------
inline
float
nLenseFlare::GetFlareSizeAt(int ndx)
{
return aFlares[ndx].fSize;
}
//------------------------------------------------------------------------------
inline
float
nLenseFlare::GetFlarePosAt(int ndx)
{
return aFlares[ndx].fPosition;
}
//------------------------------------------------------------------------------
#endif
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] | [
[
[
1,
175
]
]
] |
353b399af428a1198c84c3d7ea446a918830d655 | f96efcf47a7b6a617b5b08f83924c7384dcf98eb | /tags/tlen_1_0_7_1/chat/AdminWindow.cpp | 9e0cc1506b100591c74e1f1ea391f8c2a1c69005 | [] | no_license | BackupTheBerlios/mtlen-svn | 0b4e7c53842914416ed3f6b1fa02c3f1623cac44 | f0ea6f0cec85e9ed537b89f7d28f75b1dc108554 | refs/heads/master | 2020-12-03T19:37:37.828462 | 2011-12-07T20:02:16 | 2011-12-07T20:02:16 | 40,800,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,502 | cpp | /*
MUCC Group Chat GUI Plugin for Miranda IM
Copyright (C) 2004 Piotr Piastucki
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 "AdminWindow.h"
#include "Utils.h"
static BOOL CALLBACK UserKickDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
int i;
const char *banOptions[]={"No ban", "1 minute", "5 minutes", "15 minutes", "30 minutes",
"1 hour", "6 hours", "1 day", "3 days", "1 week", "2 weeks", "4 weeks"};
const int banTime[] = {0, 1, 5, 15, 30, 60, 360, 1440, 4320, 10080, 20160, 40320};
const char *roleOptions[]={"No role", "Member", "Admin", "Moderator"};
const int roleMask[] = {0, MUCC_EF_USER_MEMBER, MUCC_EF_USER_ADMIN, MUCC_EF_USER_MODERATOR};
AdminWindow *adminWindow;
adminWindow = (AdminWindow *) GetWindowLong(hwndDlg, GWL_USERDATA);
switch (msg) {
case WM_INITDIALOG:
adminWindow = (AdminWindow *) lParam;
TranslateDialogDefault(hwndDlg);
SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) adminWindow);
adminWindow->setKickTabHWND(hwndDlg);
for (i=0;i<12;i++) {
SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_ADDSTRING, 0, (LPARAM) banOptions[i]);
}
SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_SETCURSEL, 0, 0);
for (i=0;i<3;i++) {
SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_ADDSTRING, 0, (LPARAM) roleOptions[i]);
}
SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_SETCURSEL, 0, 0);
SetDlgItemText(hwndDlg, IDC_NICK, adminWindow->getNick());
return FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
{
char nick[256], reason[256];
GetDlgItemText(hwndDlg, IDC_NICK, nick, sizeof(nick));
GetDlgItemText(hwndDlg, IDC_REASON, reason, sizeof(reason));
if (strlen(nick)>0) {
int iSel = SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_GETCURSEL, 0, 0);
if (iSel>=0 && iSel<12) {
adminWindow->getParent()->kickAndBan(nick, banTime[iSel] * 60, reason);
}
}
}
// EndDialog(hwndDlg, 1);
// return TRUE;
break;
case IDC_SET_ROLE:
{
char nick[256];
GetDlgItemText(hwndDlg, IDC_NICK, nick, sizeof(nick));
if (strlen(nick)>0) {
int iSel = SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_GETCURSEL, 0, 0);
if (iSel>=0 && iSel<3) {
adminWindow->getParent()->setRights(nick, roleMask[iSel]);
}
}
}
break;
// EndDialog(hwndDlg, 1);
// return TRUE;
case IDCANCEL:
// EndDialog(hwndDlg, 0);
return TRUE;
}
break;
case WM_CLOSE:
// EndDialog(hwndDlg, 0);
break;
}
return FALSE;
}
static BOOL CALLBACK UserBrowserDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{ int i;
const char *browseOptions[]={"Banned", "Owners", "Administrators", "Members", "Moderators"};
const int browserFlags[]={MUCC_EF_USER_BANNED, MUCC_EF_USER_OWNER, MUCC_EF_USER_ADMIN, MUCC_EF_USER_MEMBER, MUCC_EF_USER_MODERATOR};
LVCOLUMN lvCol;
HWND lv;
AdminWindow *adminWindow;
adminWindow = (AdminWindow *) GetWindowLong(hwndDlg, GWL_USERDATA);
switch (msg) {
case WM_INITDIALOG:
adminWindow = (AdminWindow *) lParam;
TranslateDialogDefault(hwndDlg);
SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) adminWindow);
adminWindow->setBrowserTabHWND(hwndDlg);
lv = GetDlgItem(hwndDlg, IDC_LIST);
ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
lvCol.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;
lvCol.pszText = Translate("Login");
lvCol.cx = 80;
lvCol.iSubItem = 0;
ListView_InsertColumn(lv, 0, &lvCol);
lvCol.pszText = Translate("Nick name");
lvCol.cx = 80;
lvCol.iSubItem = 1;
ListView_InsertColumn(lv, 1, &lvCol);
lvCol.pszText = Translate("When");
lvCol.cx = 95;
lvCol.iSubItem = 2;
ListView_InsertColumn(lv, 2, &lvCol);
lvCol.pszText = Translate("Admin");
lvCol.cx = 80;
lvCol.iSubItem = 2;
ListView_InsertColumn(lv, 3, &lvCol);
lvCol.pszText = Translate("Reason");
lvCol.cx = 70;
lvCol.iSubItem = 2;
ListView_InsertColumn(lv, 5, &lvCol);
lvCol.pszText = Translate("Remaining");
lvCol.cx = 80;
lvCol.iSubItem = 2;
ListView_InsertColumn(lv, 4, &lvCol);
for (i=0;i<(adminWindow->getParent()->getRoomFlags() & MUCC_EF_ROOM_MEMBERS_ONLY ? 4 : 3);i++) {
SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_ADDSTRING, 0, (LPARAM) browseOptions[i]);
}
SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_SETCURSEL, 0, 0);
return FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_SHOW:
int iSel;
iSel = SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_GETCURSEL, 0, 0);
if (iSel< 5) {
adminWindow->queryUsers(browserFlags[iSel]);
}
break;
// return TRUE;
case IDCANCEL:
// EndDialog(hwndDlg, 0);
return TRUE;
}
break;
case WM_CLOSE:
// EndDialog(hwndDlg, 0);
break;
case WM_MEASUREITEM:
if (wParam == IDC_LIST) {
MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
lpMis->itemHeight = 16;//GetSystemMetrics(SM_CYSMICON);
return TRUE;
}
break;
case WM_DRAWITEM:
if (wParam == IDC_LIST) {
RECT rc;
int x, w;
char text[256];
DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
switch (lpDis->itemAction) {
default:
case ODA_SELECT:
case ODA_DRAWENTIRE:
if (lpDis->itemState & ODS_SELECTED) {
HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
FillRect(lpDis->hDC, &(lpDis->rcItem), hBrush);//(HBRUSH) (COLOR_HIGHLIGHT+1));
DeleteObject(hBrush);
SetTextColor(lpDis->hDC, 0);
SetBkMode(lpDis->hDC, TRANSPARENT);
}
else {
FillRect(lpDis->hDC, &(lpDis->rcItem), (HBRUSH) (COLOR_WINDOW+1));
SetTextColor(lpDis->hDC, RGB(0, 0, 0));//GetSysColor(COLOR_WINDOWTEXT));
SetBkMode(lpDis->hDC, TRANSPARENT);
}
x = lpDis->rcItem.left + 1;
for (int col=0;col<6;col++) {
w = ListView_GetColumnWidth(GetDlgItem(hwndDlg, IDC_LIST), col);
rc.left = x;
rc.top = lpDis->rcItem.top;
rc.bottom = lpDis->rcItem.bottom;
rc.right = x+w-2;
ListView_GetItemText(GetDlgItem(hwndDlg, IDC_LIST), lpDis->itemID, col, text, sizeof(text));
if (strlen(text)==0) {
strcpy(text, "-");
}
DrawText(lpDis->hDC, text, strlen(text), &rc, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
x+=w;
}
break;
}
}
break;
case WM_NOTIFY:
LPNMHDR pNmhdr;
pNmhdr = (LPNMHDR)lParam;
if (pNmhdr->idFrom = IDC_LIST && adminWindow->getBrowserMode() == MUCC_EF_USER_BANNED) {
switch (pNmhdr->code) {
case NM_RCLICK:
{
LVHITTESTINFO hti;
int hitItem;
hti.pt.x=(short)LOWORD(GetMessagePos());
hti.pt.y=(short)HIWORD(GetMessagePos());
ScreenToClient(pNmhdr->hwndFrom, &hti.pt);
if ((hitItem = ListView_HitTest(pNmhdr->hwndFrom,&hti)) !=-1) {
LVITEM lvi = {0};
HMENU hMenu;
int iSelection;
char nick[256];
lvi.mask = TVIF_TEXT;
lvi.iItem = hitItem;
lvi.iSubItem = 0;
lvi.pszText = nick;
lvi.cchTextMax = sizeof(nick);
ListView_GetItem(pNmhdr->hwndFrom, &lvi);
hMenu=GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)), 3);
CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0);
iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, (short)LOWORD(GetMessagePos()), (short)HIWORD(GetMessagePos()), 0, hwndDlg, NULL);
DestroyMenu(hMenu);
if (iSelection == ID_USERMENU_UNBAN) {
adminWindow->getParent()->unban(nick);
}
}
}
break;
}
}
}
return FALSE;
}
static BOOL CALLBACK AdminDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
HWND hwnd;
TCITEM tci;
HWND tc;
AdminWindow *adminWindow;
adminWindow = (AdminWindow *) GetWindowLong(hwndDlg, GWL_USERDATA);
switch (msg) {
case WM_INITDIALOG:
adminWindow = (AdminWindow *) lParam;
TranslateDialogDefault(hwndDlg);
SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) adminWindow);
SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_ADMINISTRATION]);
hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_USER_KICK), hwndDlg, UserKickDlgProc, (LPARAM) adminWindow);
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
ShowWindow(hwnd, SW_SHOW);
hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_USER_BROWSER), hwndDlg, UserBrowserDlgProc, (LPARAM) adminWindow);
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
adminWindow->setCurrentTab(0);
adminWindow->setHWND(hwndDlg);
tc = GetDlgItem(hwndDlg, IDC_TABS);
tci.mask = TCIF_TEXT;
tci.pszText = Translate("Administration");
TabCtrl_InsertItem(tc, 0, &tci);
tci.pszText = Translate("Browser");
TabCtrl_InsertItem(tc, 1, &tci);
return FALSE;
case WM_NOTIFY:
switch (wParam) {
case IDC_TABS:
switch (((LPNMHDR) lParam)->code) {
case TCN_SELCHANGE:
switch (adminWindow->getCurrentTab()) {
case 0:
ShowWindow(adminWindow->getKickTabHWND(), SW_HIDE);
break;
case 1:
ShowWindow(adminWindow->getBrowserTabHWND(), SW_HIDE);
break;
}
adminWindow->setCurrentTab(TabCtrl_GetCurSel(GetDlgItem(hwndDlg, IDC_TABS)));
switch (adminWindow->getCurrentTab()) {
case 0:
ShowWindow(adminWindow->getKickTabHWND(), SW_SHOW);
break;
case 1:
ShowWindow(adminWindow->getBrowserTabHWND(), SW_SHOW);
break;
}
break;
}
break;
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCANCEL:
delete adminWindow;
// EndDialog(hwndDlg, 0);
return TRUE;
}
break;
case WM_CLOSE:
delete adminWindow;
// EndDialog(hwndDlg, 0);
break;
}
return FALSE;
}
AdminWindow::AdminWindow(ChatWindow *parent, const char *nick, int mode) {
this->parent = parent;
hWnd = NULL;
browserMode = 0;
this->nick = NULL;
Utils::copyString(&this->nick, nick);
}
AdminWindow::~AdminWindow() {
if (hWnd != NULL) {
EndDialog(hWnd, 0);
}
if (parent != NULL) {
parent->setAdminWindow(NULL);
}
if (nick != NULL) {
delete nick;
}
}
void AdminWindow::start() {
DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_USER_ADMIN), NULL, AdminDlgProc, (LPARAM) this);
}
void AdminWindow::setHWND(HWND hWnd) {
this->hWnd = hWnd;
}
void AdminWindow::setCurrentTab(int t) {
currentTab = t;
}
int AdminWindow::getCurrentTab() {
return currentTab;
}
void AdminWindow::setKickTabHWND(HWND hWnd) {
hKickTabWnd = hWnd;
}
void AdminWindow::setBrowserTabHWND(HWND hWnd) {
hBrowserTabWnd = hWnd;
}
HWND AdminWindow::getKickTabHWND() {
return hKickTabWnd;
}
HWND AdminWindow::getBrowserTabHWND() {
return hBrowserTabWnd;
}
void AdminWindow::queryUsers(int queryType) {
MUCCEVENT muce;
EnableWindow(GetDlgItem(getBrowserTabHWND(), IDC_SHOW), FALSE);
muce.cbSize = sizeof(MUCCEVENT);
muce.iType = MUCC_EVENT_QUERY_USERS;
muce.pszModule = parent->getModule();
muce.pszID = parent->getRoomId();
muce.dwFlags = queryType;
browserMode = queryType;
NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
}
ChatWindow * AdminWindow::getParent() {
return parent;
}
void AdminWindow::queryResultUsers(MUCCQUERYRESULT *queryResult) {
ListView_DeleteAllItems(GetDlgItem(getBrowserTabHWND(), IDC_LIST));
for (int i=0;i<queryResult->iItemsNum;i++) {
char timestampStr[100];
DBTIMETOSTRING dbtts;
LVITEM lvItem;
lvItem.mask = LVIF_TEXT;// | LVIF_PARAM;
lvItem.iSubItem = 0;
lvItem.iItem = ListView_GetItemCount(GetDlgItem(getBrowserTabHWND(), IDC_LIST));
lvItem.pszText = (char *) queryResult->pItems[i].pszID;
if (lvItem.pszText == NULL) lvItem.pszText = "";
// lvItem.lParam = (LPARAM) room;
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
lvItem.iSubItem = 1;
lvItem.pszText = (char *) queryResult->pItems[i].pszName;
if (lvItem.pszText == NULL) lvItem.pszText = "";
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
lvItem.iSubItem = 2;
dbtts.cbDest = 90;
dbtts.szDest = timestampStr;
dbtts.szFormat = (char *)"d t";
timestampStr[0]='\0';
if (queryResult->pItems[i].dwFlags) {
CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)queryResult->pItems[i].dwFlags, (LPARAM) & dbtts);
}
lvItem.pszText = timestampStr;
if (lvItem.pszText == NULL) lvItem.pszText = "";
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
lvItem.iSubItem = 3;
lvItem.pszText = (char *) queryResult->pItems[i].pszNick;
if (lvItem.pszText == NULL) lvItem.pszText = "";
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
lvItem.iSubItem = 4;
timestampStr[0] = '\0';
if (queryResult->pItems[i].iCount > 0) {
int days = queryResult->pItems[i].iCount / (60*60*24);
int hours = (queryResult->pItems[i].iCount % (60*60*24)) / (60*60);
int minutes = (queryResult->pItems[i].iCount % (60*60)) / 60;
int seconds = queryResult->pItems[i].iCount % 60;
if (days != 0) {
sprintf(timestampStr, "%dd%dh%dm%ds", days, hours, minutes, seconds);
} else if (hours != 0) {
sprintf(timestampStr, "%dh%dm%ds", hours, minutes, seconds);
} else if (minutes != 0) {
sprintf(timestampStr, "%dm%ds", minutes, seconds);
} else {
sprintf(timestampStr, "%ds", seconds);
}
}
lvItem.pszText = timestampStr;
if (lvItem.pszText == NULL) lvItem.pszText = "";
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
lvItem.iSubItem = 5;
lvItem.pszText = (char *) queryResult->pItems[i].pszText;
if (lvItem.pszText == NULL) lvItem.pszText = "";
ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
/*
ptr = new HelperContact(queryResult->pItems[i].pszID, queryResult->pItems[i].pszName);
if (lastptr !=NULL) {
lastptr->setNext(ptr);
} else {
contactList=ptr;
}
lastptr=ptr;
*/
}
EnableWindow(GetDlgItem(getBrowserTabHWND(), IDC_SHOW), TRUE);
}
const char *AdminWindow::getNick() {
return nick;
}
int AdminWindow::getBrowserMode() {
return browserMode;
}
| [
"the_leech@3f195757-89ef-0310-a553-cc0e5972f89c"
] | [
[
[
1,
475
]
]
] |
6c870b90c939fec8bad429b9c0b29947d2f84416 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/NetWheelController/include/Probability.h | f6e97444e462e7507b0e1a637320159eecacbdd0 | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | h | #ifndef __Orz_Probability_h__
#define __Orz_Probability_h__
#include "WheelControllerConfig.h"
#include "WheelEngineInterface.h"
namespace Orz
{
class _OrzNetWheelControlleExport Probability
{
public:
Probability(void);
~Probability(void);
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
23
]
]
] |
4e685086ddc69f1b94433e09963ced4aa183a346 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/BigCube.cpp | cedfcee11ceaeefe96c71f8a4cb7d771acb3065b | [] | no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,846 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "BigCube.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
class BigCube {
public:
string largestCube(vector <string> range) {
stringstream ss;
long long low=0;
long long high=0;
vector <long long> vll;
for(long long i=0;i<100009;i++){
vll.push_back(i*i*i);
}
long long ret = -1;
forv(i,range){
ss << range[i];
sscanf(range[i].c_str(),"%llu-%llu",&low,&high);
forv(j,vll){
if(vll[j] >= low && vll[j] <= high){
ret >?= vll[j];
}
}
ss.str("");
}
ss << ret;
if(ret == -1) return "";
return ss.str();
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"1-1000000000001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "1000000000000"; verify_case(0, Arg1, largestCube(Arg0)); }
void test_case_1() { string Arr0[] = {"10-999999999999990","11-999999999999991","12-999999999999992",
"13-999999999999993","14-999999999999994","15-999999999999995",
"16-999999999999996","17-999999999999993","18-999999999999994",
"19-999999999999999"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "999970000299999"; verify_case(1, Arg1, largestCube(Arg0)); }
void test_case_2() { string Arr0[] = {"0-3","10-20","30-60","80-120"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "1"; verify_case(2, Arg1, largestCube(Arg0)); }
void test_case_3() { string Arr0[] = {"999700030000-999999999999","999400119993-999700029998",
"999100269974-999400119991","998800479937-999100269972"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = ""; verify_case(3, Arg1, largestCube(Arg0)); }
void test_case_4() { string Arr0[] = {"0-0","2-2","3-3","4-4","5-5","6-6","7-7","9-9","10-10","12-12",
"14-14","16-16","18-18","20-20","22-22","24-24","26-26","28-28",
"30-30","32-32","34-34","36-36","38-38","40-40","42-42","44-44",
"46-46","48-48","50-50","52-52","54-54","56-56","58-58","60-60",
"62-62","65-65","67-67","69-69","71-71","73-73","75-75","77-77",
"79-79","81-81","83-83","85-85","87-87","89-89","99-99",
"999970000300000-999999999999999" }
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "0"; verify_case(4, Arg1, largestCube(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
BigCube ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
] | [
[
[
1,
100
]
]
] |
40668be5ce345ba6d2c991317be961df42e8c64f | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/component/TitleBar.h | 26a7b045752e66ae3fa7ba7410b2d041bb52ab19 | [
"BSD-3-Clause"
] | permissive | gui-works/ui | 3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b | 023faf07ff7f11aa7d35c7849b669d18f8911cc6 | refs/heads/master | 2020-07-18T00:46:37.172575 | 2009-11-18T22:05:25 | 2009-11-18T22:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | h | /*
* Copyright (c) 2003-2006, Bram Stein
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE 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 TITLEBAR_H
#define TITLEBAR_H
#include "../CompoundComponent.h"
#include "./Button.h"
#include "./Label.h"
#include "../layout/BorderLayout.h"
#include "../event/MouseListener.h"
#include "../event/MouseEvent.h"
namespace ui
{
class TitleBar : public CompoundComponent, public event::MouseAdapter
{
public:
TitleBar(const std::string &label);
TitleBar(Icon *icon, const std::string &label);
const std::string & getTitle() const;
void setTitle(const std::string &title);
void setIcon(Icon *icon);
Icon * getIcon() const;
// *cough*
Button * getCloseButton();
Label * getTitleLabel();
void setActive(bool active);
private:
void init();
Button closeButton;
Label titleLabel;
void mousePressed(const event::MouseEvent &e);
void mouseReleased(const event::MouseEvent &e);
void mouseDragged(const event::MouseEvent &e);
layout::BorderLayout layout;
bool dragging;
int nextX, nextY;
};
}
#endif | [
"bs@bram.(none)"
] | [
[
[
1,
77
]
]
] |
f88a163fad3c3baf35782e0fb12faade794d1ff6 | 7ba7440b6a7b6068c900d561ad03c3ff86439c09 | /GalDemo/GalDemo/RenderableObject.cpp | 12f310942a06e8b10ff7baffa2f753657f055260 | [] | no_license | weimingtom/gal-demo | 96dc06f8f02b4c767412aac7fcf050e241b40c04 | f2b028591a195516af3ce33d084b7b29cbea84aa | refs/heads/master | 2021-01-20T11:47:07.598476 | 2011-08-10T23:48:43 | 2011-08-10T23:48:43 | 42,379,726 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52 | cpp | #include "stdafx.h"
#include "RenderableObject.h"
| [
"[email protected]"
] | [
[
[
1,
2
]
]
] |
0d30fc0fff630ea08b2e24184f25f9f984dbd7df | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Common/time/car_timestamp.h | 832fb14e502db2486f24970968e61ff3dc2c54fa | [] | no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,525 | h | #ifndef _CAR_TIMESTAMP_H
#define _CAR_TIMESTAMP_H
#ifdef __cplusplus_cli
#pragma managed(push,off)
#endif
#include "timestamp.h"
#include <limits>
using namespace std;
#define TICK_PERIOD 0.0001 // in secs
#define TICK_FREQUENCY 10000
// handle min/max macro defines
#ifdef max
#pragma push_macro("max")
#undef max
#define _MAX_DEF_
#endif
#ifdef min
#pragma push_macro("min")
#undef min
#define _MIN_DEF_
#endif
class car_timestamp {
private:
unsigned short s;
unsigned int t;
public:
inline car_timestamp() { s = 0xffff; t = 0xffffffff; }
inline car_timestamp(unsigned short secs, unsigned int ticks) { s = secs; t = ticks; }
inline car_timestamp& operator = (const car_timestamp& c) { s = c.s; t = c.t; return *this; }
inline static car_timestamp invalid() { return car_timestamp(); }
inline bool is_valid() const { return s != 0xffff || t != 0xffffffff; }
inline bool is_invalid() const { return s == 0xffff || t == 0xffffffff; }
inline void invalidate() { s = 0xffff; t = 0xffffffff; }
inline static car_timestamp from_secs(double secs) {
int s = (int)floor(secs);
if (s > numeric_limits<unsigned short>::max()) {
s = numeric_limits<unsigned short>::max();
}
unsigned int t = (unsigned int)(floor((secs - s) * TICK_FREQUENCY));
return car_timestamp((unsigned short)s, (unsigned int)t);
}
inline int secs() const { return s; }
inline int ticks() const { return t; }
inline double total_secs() const { return s + t * TICK_PERIOD; }
inline int total_ticks() const { return s * TICK_FREQUENCY + t; }
inline bool operator == (const car_timestamp& c) const { return s == c.s && t == c.t; }
inline bool operator != (const car_timestamp& c) const { return s != c.s || t != c.t; }
inline bool operator > (const car_timestamp& c) const { return total_ticks() > c.total_ticks(); }
inline bool operator >= (const car_timestamp& c) const { return total_ticks() >= c.total_ticks(); }
inline bool operator < (const car_timestamp& c) const { return total_ticks() < c.total_ticks(); }
inline bool operator <= (const car_timestamp& c) const { return total_ticks() <= c.total_ticks(); }
friend timespan operator - (const car_timestamp&, const car_timestamp&);
friend car_timestamp operator + (const car_timestamp&, const timespan&);
friend car_timestamp operator + (const timespan&, const car_timestamp&);
friend car_timestamp operator - (const car_timestamp&, const timespan&);
};
inline timespan operator - (const car_timestamp& l, const car_timestamp& r) {
assert(l.is_valid() && r.is_valid());
return timespan::from_secs(l.total_secs() - r.total_secs());
}
inline car_timestamp operator + (const car_timestamp& l, const timespan& r) {
assert(l.is_valid() && r.is_valid());
double ts = l.total_secs() + r.total_secs();
assert(ts > 0 && ts < 495031.7296);
int s = (int)floor(ts);
if (s > numeric_limits<unsigned short>::max()) {
s = numeric_limits<unsigned short>::max();
}
unsigned int t = (unsigned int)(floor((ts - s) * TICK_FREQUENCY));
return car_timestamp((unsigned short)s, (unsigned int)t);
}
inline car_timestamp operator + (const timespan& l, const car_timestamp& r) { return r + l; }
inline car_timestamp operator - (const car_timestamp& l, const timespan& r) { return l + (-r); }
#ifdef _MAX_DEF_
#pragma pop_macro("max")
#endif
#ifdef _MIN_DEF_
#pragma pop_macro("min")
#endif
#ifdef __cplusplus_cli
#pragma managed(pop)
#endif
#endif | [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
] | [
[
[
1,
108
]
]
] |
fa1fb1f8cc83a6f8ede8132188843d0daaa0c052 | 82d364f8be686abe0201314cdb58012af49e66a5 | /ptexture.h | 625a5eb157cab5aec504b38357acef52dc79c849 | [] | no_license | youkaicountry/ProceduralTextureMaker | b55d7dbcc70da62e3473bbb093394e748ec9aef7 | 499923221edeab1832cfe4e264c713feec93c658 | refs/heads/master | 2021-05-26T18:45:39.204113 | 2011-12-10T04:02:55 | 2011-12-10T04:02:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,742 | h | #ifndef __PTEXTURE_
#define __PTEXTURE_
#include <vector.h>
class PTexture
{
public:
PTexture();
PTexture(int xsize, int ysize);
~PTexture();
int getXSize();
int getYSize();
float getHeight(int x, int y);
float getHeightD(int x, int y);
int getRed(int x, int y);
int getGreen(int x, int y);
int getBlue(int x, int y);
float getRedD(int x, int y);
float getGreenD(int x, int y);
float getBlueD(int x, int y);
int getExtendRed(int x, int y);
int getExtendGreen(int x, int y);
int getExtendBlue(int x, int y);
float getExtendRedD(int x, int y);
float getExtendGreenD(int x, int y);
float getExtendBlueD(int x, int y);
int getA8R8G8B8(int x, int y);
void getA8R8G8B8row(int y, int *buffer);
void setColourD(int x, int y, float red, float green, float blue); //0-255.0
void setColour(int x, int y, int red, int green, int blue); //sets colour and clamps
void setColourWrap(int x, int y, int red, int green, int blue); //sets colour and wraps
void setColourWrapD(int x, int y, float red, float green, float blue);
void setA8R8G8B8(int x, int y, int argb);
void copyFromTexture(PTexture *src); //TODO: Make this function cleaner
float *imager;
float *imageg;
float *imageb;
int xdim;
int ydim;
private:
int flatCoord(int x, int y)
{
//if (tindex > (this->xdim * this->ydim)-1) { tindex = (this->xdim * this->ydim)-1;}
//if (tindex < 0) {tindex = 0;}
if (x < 0) {x = 0;}
if (y < 0) {y = 0;}
if (x >= this->xdim) {x = this->xdim-1;}
if (y >= this->ydim) {y = this->ydim-1;}
int tindex = (y * this->xdim) + x;
return tindex; }
void init();
};
/*class PColour
{
public:
PColour();
PColour(int nred, int ngreen, int nblue);
~PColour();
int red;
int green;
int blue;
void setRed(int nred);
void setGreen(int ngreen);
void setBlue(int nblue);
int getRed();
int getGreen();
int getBlue();
void setColour(int nred, int ngreen, int nblue);
};
class PTexture
{
public:
PTexture();
PTexture(int xsize, int ysize);
~PTexture();
int getXSize();
int getYSize();
PColour* getColour(int x, int y);
float getHeight(int x, int y);
int getRed(int x, int y);
int getGreen(int x, int y);
int getBlue(int x, int y);
int getA8R8G8B8(int x, int y);
void setColour(int x, int y, PColour col);
void setColour(int x, int y, int red, int green, int blue);
private:
vector<PColour*> image;
int xdim;
int ydim;
int flatCoord(int x, int y);
};*/
#endif
| [
"[email protected]"
] | [
[
[
1,
119
]
]
] |
3929651f881c4abf8bac699acd07b8ace770d7f7 | f2b4a9d938244916aa4377d4d15e0e2a6f65a345 | /Game/ArtifactList.cpp | bd99ee38660610246e00598a764fd0b820444214 | [
"Apache-2.0"
] | permissive | notpushkin/palm-heroes | d4523798c813b6d1f872be2c88282161cb9bee0b | 9313ea9a2948526eaed7a4d0c8ed2292a90a4966 | refs/heads/master | 2021-05-31T19:10:39.270939 | 2010-07-25T12:25:00 | 2010-07-25T12:25:00 | 62,046,865 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,353 | cpp | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
#include "stdafx.h"
#include "ArtifactList.h"
#include "Dlg_ArtInfo.h"
enum ART_BUTTON_FLAGS {
ABF_PRESSED = 0x1
};
const sint32 DRAG_DELTA = 5;
const uint16 INVART = 0xFFFF;
//
inline void ComposeArtifactCell(const iRect& rect, uint16 artId, uint32 flags)
{
iRect rc(rect);
rc.InflateRect(1);
gApp.Surface().FrameRect(rc,cColor_Black);
/*
SpriteId bsid;
if (artId == INVART) bsid = PDGG_ART_CELLS;
else if (flags & ABF_PRESSED) bsid = PDGG_ART_CELLS + 1;
else bsid = PDGG_ART_CELLS + 2;
Tile3x3Sprite(gApp.Surface(), rect, bsid);*/
gApp.Surface().FillRect(rect,(artId == INVART)?RGB16(64,64,64):RGB16(128,128,0),64);
ButtonFrame(gApp.Surface(),rect, (flags & ABF_PRESSED)?iButton::Pressed:0);
if (artId != INVART) BlitIcon(gApp.Surface(), gGame.ItemMgr().m_artMgr[artId].Sprite(), rect);
}
/*
* DragItem
*/
iArtDragDropItem::iDragItem::iDragItem(iArtDragDropItem* pSender, sint32 fromCell,const iArtCell& artCell, const iPoint& pos, const iSize& siz)
: m_pSender(pSender), m_fromCell(fromCell), m_artCell(artCell), m_pos(pos), m_siz(siz), m_pReceiver(NULL), m_toCell(-1)
{}
void iArtDragDropItem::iDragItem::ComposeDragGlyph()
{
iRect rc(m_pos.x-(sint32)(m_siz.w/2),m_pos.y-(sint32)(m_siz.h/2),m_siz.w,m_siz.h);
ComposeArtifactCell(rc, m_artCell.artId, 0);
if (!m_pReceiver || m_toCell == -1) gApp.Surface().FillRect(rc,cColor_Red,32);
else gApp.Surface().FillRect(rc,cColor_Green,32);
}
/*
* iArtDragDropItem
*/
iArtDragDropItem::iArtDragDropItem(iSimpleArray<iArtDragDropItem*>& competitors, const iSize& cellSiz, iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect, uint32 uid)
: iBaseCtrl(pViewMgr,pCmdHandler, rect, GENERIC_VIEWPORT, uid, Visible|Enabled)
, m_cellSiz(cellSiz)
, m_Competitors(competitors)
, m_pDragItem(NULL), m_pDropItem(NULL)
{
m_Competitors.Add(this);
}
void iArtDragDropItem::BeginDrag(sint32 fromCell, const iArtCell& artCell, const iPoint& pos)
{
check(!m_pDragItem);
m_pDragItem = new iDragItem(this, fromCell, artCell, pos, m_cellSiz);
m_pMgr->SetDragGlyph(m_pDragItem);
Drag(pos);
}
void iArtDragDropItem::EndDrag()
{
check(m_pDragItem);
if (m_pDragItem->m_pReceiver) m_pDragItem->m_pReceiver->Drop();
m_pMgr->SetDragGlyph(NULL);
delete m_pDragItem;
m_pDragItem = NULL;
Invalidate();
}
void iArtDragDropItem::Drag(const iPoint& pos)
{
check(m_pDragItem);
m_pDragItem->m_pos = pos;
for (uint32 xx=0; xx<m_Competitors.GetSize(); ++xx) {
if (m_Competitors[xx]->GetScrRect().PtInRect(pos)) {
if (m_pDragItem->m_pReceiver != m_Competitors[xx]) {
if (m_pDragItem->m_pReceiver) m_pDragItem->m_pReceiver->LeaveDrop();
m_Competitors[xx]->EnterDrop(m_pDragItem);
}
if (m_pDragItem->m_pReceiver) m_pDragItem->m_pReceiver->DragDrop();
Invalidate();
return;
}
}
if (m_pDragItem->m_pReceiver) m_pDragItem->m_pReceiver->LeaveDrop();
Invalidate();
}
/*
* iArtItemCtrl
*/
iArtItemCtrl::iArtItemCtrl(iSimpleArray<iArtDragDropItem*>& competitors, iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iPoint& pos, const iSize& cellSiz, uint32 uid)
: iArtDragDropItem(competitors, cellSiz, pViewMgr, pCmdHandler, iRect(pos, cellSiz) , uid)
, m_pOwner(NULL)
, m_pArtCell(NULL)
, m_bPressed(false)
, m_bClickMode(false)
{
}
void iArtItemCtrl::OnCompose()
{
iRect rc = GetScrRect();
ComposeArtifactCell(rc, (m_pArtCell)?m_pArtCell->artId:0xFFFF, (m_bPressed)?ABF_PRESSED:0);
if (m_pDragItem) gApp.Surface().FrameRect(rc,cColor_Blue,64);
if (m_pDropItem && m_pDropItem->m_toCell != -1) gApp.Surface().FrameRect(rc,cColor_Yello,64);
}
void iArtItemCtrl::OnMouseDown(const iPoint& pos)
{
if (!m_pArtCell || m_pArtCell->artId == INVART) return;
m_bPressed = true;
m_dragAnchor = pos;
m_bClickMode = true;
Invalidate();
}
void iArtItemCtrl::OnMouseUp(const iPoint& pos)
{
if (m_pDragItem) {
EndDrag();
}
m_bPressed = false;
Invalidate();
}
void iArtItemCtrl::OnMouseClick(const iPoint& pos)
{
if (m_bClickMode) {
iDlg_ArtInfo dlg(m_pMgr, m_pArtCell->artId, m_pOwner);
dlg.DoModal();
m_bClickMode = false;
}
}
void iArtItemCtrl::OnMouseTrack(const iPoint& pos)
{
if (m_pDragItem) {
Drag(pos);
} else if (m_pArtCell && !m_pArtCell->Empty() && pos.GetSqDelta(m_dragAnchor) > DRAG_DELTA) {
m_bClickMode = false;
BeginDrag(0, *m_pArtCell, pos);
m_bPressed = false;
}
}
void iArtItemCtrl::EnterDrop(iDragItem* pDragItem)
{
check(!m_pDropItem);
m_pDropItem = pDragItem;
m_pDropItem->m_pReceiver = this;
m_pDropItem->m_toCell = -1;
Invalidate();
}
void iArtItemCtrl::LeaveDrop()
{
check(m_pDropItem);
m_pDropItem->m_pReceiver = NULL;
m_pDropItem->m_toCell = -1;
m_pDropItem = NULL;
Invalidate();
}
bool iArtItemCtrl::Drop()
{
if (m_pDropItem->m_toCell == -1) {
LeaveDrop();
Invalidate();
return false;
}
if (m_pDropItem->m_pSender == m_pDropItem->m_pReceiver) {
// (same cell) do nothing
} else {
if (m_pArtCell->artId != INVART) Replace(0, m_pDropItem->m_pSender->Replace(m_pDropItem->m_fromCell, *m_pArtCell));
else Replace(0, m_pDropItem->m_pSender->Remove(m_pDropItem->m_fromCell));
}
LeaveDrop();
Invalidate();
return true;
}
bool iArtItemCtrl::DragDrop() const
{
if ( gGame.ItemMgr().m_artMgr[m_pDropItem->m_artCell.artId].Assign() == m_pArtCell->AssignType() && m_pOwner->Artifacts().CanAttach(m_pDropItem->m_artCell.artId)) m_pDropItem->m_toCell = 0;
else m_pDropItem->m_toCell = -1;
return true;
}
iArtCell iArtItemCtrl::Remove(sint32 cell)
{
iArtCell result = *m_pArtCell;
if (result.artId != INVART) gGame.ItemMgr().m_artMgr[result.artId].Dettach(m_pOwner);
m_pArtCell->Reset();
return result;
}
iArtCell iArtItemCtrl::Replace(sint32 cell, const iArtCell& newArt)
{
iArtCell result = *m_pArtCell;
if (result.artId != INVART) gGame.ItemMgr().m_artMgr[result.artId].Dettach(m_pOwner);
if (newArt.artId != INVART) gGame.ItemMgr().m_artMgr[newArt.artId].Attach(m_pOwner);
m_pArtCell->artId = newArt.artId;
return result;
}
/*
* iArtBackPackCtrl
*/
const uint32 SCROLL_BTN_SIZE = 15;
inline iRect BackPackListMetrics(const iPoint& pos, const iSize& cellSiz, uint32 cellsCount, uint32 flags)
{
uint32 w = cellSiz.w;
uint32 h = cellSiz.h;
if (flags & iArtBackPackCtrl::Horizontal) {
w = SCROLL_BTN_SIZE * 2 + cellSiz.w * cellsCount + cellsCount + 1;
} else {
h = SCROLL_BTN_SIZE * 2 + cellSiz.h * cellsCount + cellsCount + 1;
}
return iRect(pos.x, pos.y, w, h);
}
iArtBackPackCtrl::iArtBackPackCtrl(iSimpleArray<iArtDragDropItem*>& competitors, iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iPoint& pos, const iSize& cellSiz, uint32 cellsCount, uint32 flags, uint32 uid)
: iArtDragDropItem(competitors, cellSiz, pViewMgr,pCmdHandler,BackPackListMetrics(pos, cellSiz, cellsCount, flags), uid)
, m_flags(flags)
, m_cellSize(cellSiz)
, m_cellsCount(cellsCount)
, m_pBackPack(NULL)
, m_listOffset(0)
, m_dCell(-1)
, m_bClickMode(false)
, m_pOwner(NULL)
{
if (flags & Horizontal) {
AddChild(new iIconButton(pViewMgr, this, iRect(0,0,SCROLL_BTN_SIZE, m_Rect.h),PDGG_SCRBAR_BTNS+2,101));
AddChild(new iIconButton(pViewMgr, this, iRect(m_Rect.w-SCROLL_BTN_SIZE,0,SCROLL_BTN_SIZE, m_Rect.h),PDGG_SCRBAR_BTNS+3,102));
} else {
AddChild(new iIconButton(pViewMgr, this, iRect(0,0,m_Rect.w,SCROLL_BTN_SIZE),PDGG_SCRBAR_BTNS,101));
AddChild(new iIconButton(pViewMgr, this, iRect(0,m_Rect.h-SCROLL_BTN_SIZE,m_Rect.w,SCROLL_BTN_SIZE),PDGG_SCRBAR_BTNS+1,102));
}
}
void iArtBackPackCtrl::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param)
{
uint32 uid = pView->GetUID();
if (uid == 101) ListPageUp();
else if (uid == 102) ListPageDown();
}
void iArtBackPackCtrl::ListPageUp()
{
if (!m_pBackPack || !m_pBackPack->GetSize()) {
m_listOffset = 0;
return;
}
if (m_pBackPack->GetSize() > m_cellsCount) {
if (m_listOffset == 0) SetListOffset(m_pBackPack->GetSize() - 1);
else SetListOffset(m_listOffset - 1);
}
}
void iArtBackPackCtrl::ListPageDown()
{
if (!m_pBackPack || !m_pBackPack->GetSize()) {
m_listOffset = 0;
return;
}
if (m_pBackPack->GetSize() > m_cellsCount) {
if (m_listOffset == ((sint32)m_pBackPack->GetSize()-1)) SetListOffset(0);
else SetListOffset(m_listOffset + 1);
}
}
void iArtBackPackCtrl::SetListOffset(sint32 offs)
{
if (m_pBackPack) {
m_listOffset = iCLAMP<sint32>(0,m_pBackPack->GetSize()-1, offs);
} else m_listOffset = 0;
}
sint32 iArtBackPackCtrl::CellByPos(const iPoint& pos) const
{
sint32 val;
if (m_flags & Horizontal) {
val = (pos.x - GetScrRect().x - SCROLL_BTN_SIZE) / (sint32)(m_cellSize.w+1);
} else {
val = (pos.y - GetScrRect().y - SCROLL_BTN_SIZE) / (sint32)(m_cellSize.h+1);
}
if (val<0 || val >= (sint32)m_cellsCount) return -1;
return val;
}
sint32 iArtBackPackCtrl::BackPackIdxByCell(sint32 cellIdx) const
{
if (!m_pBackPack || cellIdx == -1 || cellIdx >= (sint32)m_pBackPack->GetSize()) return -1;
return (m_listOffset + cellIdx) % m_pBackPack->GetSize();
}
void iArtBackPackCtrl::OnCompose()
{
iRect rc = GetScrRect();
iRect crc(rc.x, rc.y, m_cellSize.w, m_cellSize.h);
// Draw frame arround up/down buttons
for (uint32 ctrlId=0; ctrlId<m_Childs.GetSize(); ++ctrlId) {
iRect ctrlRc = m_Childs[ctrlId]->GetScrRect();
ctrlRc.InflateRect(1);
gApp.Surface().FrameRect(ctrlRc,cColor_Black);
}
if (m_flags & Horizontal) crc.x += SCROLL_BTN_SIZE + 1;
else crc.y += SCROLL_BTN_SIZE + 1;
// Compose cells
for (uint32 xx=0; xx<m_cellsCount; ++xx) {
sint32 bpidx = BackPackIdxByCell(xx);
ComposeArtifactCell(crc, (bpidx==-1)?INVART:m_pBackPack->At(bpidx), ((sint32)xx==m_dCell)?ABF_PRESSED:0);
if (m_flags & Horizontal) crc.x += m_cellSize.w + 1;
else crc.y += m_cellSize.h + 1;
}
}
void iArtBackPackCtrl::OnMouseDown(const iPoint& pos)
{
if (!m_pBackPack) return;
sint32 ncell = CellByPos(pos);
if (ncell == -1 || BackPackIdxByCell(ncell) == -1) return;
m_dCell = ncell;
m_dragAnchor = pos;
m_bClickMode = true;
Invalidate();
}
void iArtBackPackCtrl::OnMouseUp(const iPoint& pos)
{
if (m_pDragItem) {
EndDrag();
}
m_dCell = -1;
Invalidate();
}
void iArtBackPackCtrl::OnMouseClick(const iPoint& pos)
{
if (m_bClickMode) {
sint32 bpIdx = BackPackIdxByCell(CellByPos(pos));
if (bpIdx != -1) {
iDlg_ArtInfo dlg(m_pMgr, m_pBackPack->At(bpIdx), m_pOwner);
dlg.DoModal();
}
m_bClickMode = false;
}
}
void iArtBackPackCtrl::OnMouseTrack(const iPoint& pos)
{
if (m_pDragItem) {
Drag(pos);
} else if (m_pBackPack && m_dCell != -1 && pos.GetSqDelta(m_dragAnchor) > DRAG_DELTA) {
sint32 bpidx = BackPackIdxByCell(m_dCell);
if (bpidx != -1) {
iArtCell ac(AC_UNDEFINED, m_pBackPack->At(bpidx));
m_bClickMode = false;
BeginDrag(m_dCell, ac, pos);
}
m_dCell = -1;
}
}
void iArtBackPackCtrl::EnterDrop(iDragItem* pDragItem)
{
check(!m_pDropItem);
m_pDropItem = pDragItem;
m_pDropItem->m_pReceiver = this;
m_pDropItem->m_toCell = -1;
Invalidate();
}
void iArtBackPackCtrl::LeaveDrop()
{
check(m_pDropItem);
m_pDropItem->m_pReceiver = NULL;
m_pDropItem->m_toCell = -1;
m_pDropItem = NULL;
Invalidate();
}
bool iArtBackPackCtrl::Drop()
{
if (m_pDropItem->m_toCell == -1) {
LeaveDrop();
Invalidate();
return false;
}
sint32 tobpidx = BackPackIdxByCell(m_pDropItem->m_toCell);
if (m_pDropItem->m_pSender == m_pDropItem->m_pReceiver && tobpidx != -1) {
sint32 frombpidx = BackPackIdxByCell(m_pDropItem->m_fromCell);
if (tobpidx != frombpidx) {
iSwap(m_pBackPack->At(frombpidx), m_pBackPack->At(tobpidx));
}
} else {
if (tobpidx == -1) m_pBackPack->Add(m_pDropItem->m_pSender->Remove(m_pDropItem->m_fromCell).artId);
else m_pBackPack->InsertBefore(tobpidx, m_pDropItem->m_pSender->Remove(m_pDropItem->m_fromCell).artId);
}
LeaveDrop();
Invalidate();
return true;
}
bool iArtBackPackCtrl::DragDrop() const
{
m_pDropItem->m_toCell = CellByPos(m_pDropItem->m_pos);
return true;
}
iArtCell iArtBackPackCtrl::Remove(sint32 cell)
{
check(m_pBackPack);
sint32 bpidx = BackPackIdxByCell(cell);
check(bpidx != -1);
iArtCell result(AC_UNDEFINED, m_pBackPack->At(bpidx));
m_pBackPack->RemoveAt(bpidx);
return result;
}
iArtCell iArtBackPackCtrl::Replace(sint32 cell, const iArtCell& newArt)
{
check(m_pBackPack);
sint32 bpidx = BackPackIdxByCell(cell);
check(bpidx != -1);
iArtCell result(AC_UNDEFINED, m_pBackPack->At(bpidx));
m_pBackPack->At(bpidx) = newArt.artId;
return result;
}
/*
* simple Artifact list control
*/
iArtListCtrl::iArtListCtrl(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iArtList& artList, const iPoint& pos, const iSize& cellSiz, uint32 cellsCount, uint32 flags, uint32 uid)
: iBaseCtrl(pViewMgr, pCmdHandler, BackPackListMetrics(pos, cellSiz, cellsCount, flags), GENERIC_VIEWPORT, uid, Visible|Enabled)
, m_flags(flags)
, m_cellSize(cellSiz)
, m_cellsCount(cellsCount)
, m_artList(artList)
, m_listOffset(0)
, m_dCell(-1)
, m_clickItem(-1)
{
if (flags & Horizontal) {
AddChild(new iIconButton(pViewMgr, this, iRect(0,0,SCROLL_BTN_SIZE, m_Rect.h),PDGG_SCRBAR_BTNS+2,101));
AddChild(new iIconButton(pViewMgr, this, iRect(m_Rect.w-SCROLL_BTN_SIZE,0,SCROLL_BTN_SIZE, m_Rect.h),PDGG_SCRBAR_BTNS+3,102));
} else {
AddChild(new iIconButton(pViewMgr, this, iRect(0,0,m_Rect.w,SCROLL_BTN_SIZE),PDGG_SCRBAR_BTNS,101));
AddChild(new iIconButton(pViewMgr, this, iRect(0,m_Rect.h-SCROLL_BTN_SIZE,m_Rect.w,SCROLL_BTN_SIZE),PDGG_SCRBAR_BTNS+1,102));
}
}
void iArtListCtrl::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param)
{
uint32 uid = pView->GetUID();
if (uid == 101) ListPageUp();
else if (uid == 102) ListPageDown();
}
void iArtListCtrl::ListPageUp()
{
if (!m_artList.GetSize()) {
m_listOffset = 0;
return;
}
if (m_artList.GetSize() > m_cellsCount) {
if (m_listOffset == 0) SetListOffset(m_artList.GetSize() - 1);
else SetListOffset(m_listOffset - 1);
}
}
void iArtListCtrl::ListPageDown()
{
if (!m_artList.GetSize()) {
m_listOffset = 0;
return;
}
if (m_artList.GetSize() > m_cellsCount) {
if (m_listOffset == ((sint32)m_artList.GetSize()-1)) SetListOffset(0);
else SetListOffset(m_listOffset + 1);
}
}
void iArtListCtrl::SetListOffset(sint32 offs)
{
m_listOffset = iCLAMP<sint32>(0,m_artList.GetSize()-1, offs);
}
sint32 iArtListCtrl::CellByPos(const iPoint& pos) const
{
sint32 val;
if (m_flags & Horizontal) {
val = (pos.x - GetScrRect().x - SCROLL_BTN_SIZE) / (sint32)(m_cellSize.w+1);
} else {
val = (pos.y - GetScrRect().y - SCROLL_BTN_SIZE) / (sint32)(m_cellSize.h+1);
}
if (val<0 || val >= (sint32)m_cellsCount) return -1;
return val;
}
sint32 iArtListCtrl::BackPackIdxByCell(sint32 cellIdx) const
{
if (cellIdx == -1 || cellIdx >= (sint32)m_artList.GetSize()) return -1;
return (m_listOffset + cellIdx) % m_artList.GetSize();
}
void iArtListCtrl::OnCompose()
{
iRect rc = GetScrRect();
iRect crc(rc.x, rc.y, m_cellSize.w, m_cellSize.h);
// Draw frame arround up/down buttons
for (uint32 ctrlId=0; ctrlId<m_Childs.GetSize(); ++ctrlId) {
iRect ctrlRc = m_Childs[ctrlId]->GetScrRect();
ctrlRc.InflateRect(1);
gApp.Surface().FrameRect(ctrlRc,cColor_Black);
}
if (m_flags & Horizontal) crc.x += SCROLL_BTN_SIZE + 1;
else crc.y += SCROLL_BTN_SIZE + 1;
// Compose cells
for (uint32 xx=0; xx<m_cellsCount; ++xx) {
sint32 bpidx = BackPackIdxByCell(xx);
ComposeArtifactCell(crc, (bpidx==-1)?INVART:m_artList[bpidx], ((sint32)xx==m_dCell)?ABF_PRESSED:0);
if (m_flags & Horizontal) crc.x += m_cellSize.w + 1;
else crc.y += m_cellSize.h + 1;
}
}
void iArtListCtrl::OnMouseDown(const iPoint& pos)
{
sint32 ncell = CellByPos(pos);
if (ncell == -1 || BackPackIdxByCell(ncell) == -1) return;
m_dCell = ncell;
Invalidate();
}
void iArtListCtrl::OnMouseUp(const iPoint& pos)
{
sint32 ncell = CellByPos(pos);
if (m_dCell != -1 && m_dCell == ncell) m_clickItem = m_dCell;
m_dCell = -1;
Invalidate();
}
void iArtListCtrl::OnMouseClick(const iPoint& pos)
{
if (m_clickItem != -1) {
sint32 bpIdx = BackPackIdxByCell(m_clickItem);
if (bpIdx != -1) {
iDlg_ArtInfo dlg(m_pMgr, m_artList[bpIdx], NULL);
dlg.DoModal();
}
m_clickItem = -1;
}
}
| [
"palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276"
] | [
[
[
1,
598
]
]
] |
e16a02527e1d8b41ac2c3c7400c72d04328f4404 | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/external/gameswf/gameswf/gameswf_function.h | 7169b5830ce38d785de8786d733044cb1f437d99 | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,415 | h | // gameswf_function.h -- Thatcher Ulrich <[email protected]> 2003
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// ActionScript function.
#ifndef GAMESWF_FUNCTION_H
#define GAMESWF_FUNCTION_H
#include "gameswf/gameswf.h"
#include "gameswf/gameswf_environment.h"
#include "gameswf/gameswf_object.h"
#include "gameswf/gameswf_action.h"
#include "base/container.h"
#include "base/smart_ptr.h"
namespace gameswf
{
struct as_environment;
struct as_object;
struct as_function : public as_object
{
// Unique id of a gameswf resource
enum { m_class_id = AS_FUNCTION };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_object::is(class_id);
}
as_function(player* player) :
as_object(player)
{
}
virtual const char* typeof() { return "function"; }
virtual const char* to_string()
{
// NOT THREAD SAFE!!!
static char buffer[50];
snprintf(buffer, 50, "<function 0x%p>", this);
return buffer;
}
// Dispatch.
virtual void operator()(const fn_call& fn) = 0;
};
struct as_c_function : public as_function
{
// Unique id of a gameswf resource
enum { m_class_id = AS_C_FUNCTION };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_function::is(class_id);
}
as_c_function(player* player, as_c_function_ptr func);
// Dispatch.
virtual void operator()(const fn_call& fn);
as_c_function_ptr m_func;
};
struct as_s_function : public as_function
{
// Unique id of a gameswf resource
enum { m_class_id = AS_S_FUNCTION };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_function::is(class_id);
}
action_buffer m_action_buffer;
array<with_stack_entry> m_with_stack; // initial with-stack on function entry.
int m_start_pc;
int m_length;
struct arg_spec
{
int m_register;
tu_string m_name;
};
array<arg_spec> m_args;
bool m_is_function2;
uint8 m_local_register_count;
uint16 m_function2_flags; // used by function2 to control implicit arg register assignments
// if function has been declared in moviclip then we should use its environment
// And for this purpose it is necessary to keep target that has created 'this'
// testcase:
// _root.myclip.onEnterFrame = _root.myfunc;
// myfunc should use _root environment
weak_ptr<as_object> m_target;
as_s_function(player* player,
const action_buffer* ab, int start, const array<with_stack_entry>& with_stack);
~as_s_function();
void set_is_function2() { m_is_function2 = true; }
void set_local_register_count(uint8 ct) { assert(m_is_function2); m_local_register_count = ct; }
void set_function2_flags(uint16 flags) { assert(m_is_function2); m_function2_flags = flags; }
void add_arg(int arg_register, const char* name)
{
assert(arg_register == 0 || m_is_function2 == true);
m_args.resize(m_args.size() + 1);
m_args.back().m_register = arg_register;
m_args.back().m_name = name;
}
void set_length(int len) { assert(len >= 0); m_length = len; }
void set_target(as_object* target)
{
m_target = target;
}
// Dispatch.
virtual void operator()(const fn_call& fn);
};
}
#endif
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
132
]
]
] |
a2d16281c8faf7b42b0b753c1e4448d600a7ff94 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome_extension/third_party/gecko-1.9.0.11/win32/include/nsIDOMEntity.h | 6b626569e10a4001ba0597a37570763881917d63 | [
"Apache-2.0"
] | permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,926 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/dom/public/idl/core/nsIDOMEntity.idl
*/
#ifndef __gen_nsIDOMEntity_h__
#define __gen_nsIDOMEntity_h__
#ifndef __gen_nsIDOMNode_h__
#include "nsIDOMNode.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMEntity */
#define NS_IDOMENTITY_IID_STR "a6cf9079-15b3-11d2-932e-00805f8add32"
#define NS_IDOMENTITY_IID \
{0xa6cf9079, 0x15b3, 0x11d2, \
{ 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMEntity : public nsIDOMNode {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMENTITY_IID)
/**
* The nsIDOMEntity interface represents an entity, either parsed
* or unparsed, in an XML document.
*
* For more information on this interface please see
* http://www.w3.org/TR/DOM-Level-2-Core/
*
* @status FROZEN
*/
/* readonly attribute DOMString publicId; */
NS_SCRIPTABLE NS_IMETHOD GetPublicId(nsAString & aPublicId) = 0;
/* readonly attribute DOMString systemId; */
NS_SCRIPTABLE NS_IMETHOD GetSystemId(nsAString & aSystemId) = 0;
/* readonly attribute DOMString notationName; */
NS_SCRIPTABLE NS_IMETHOD GetNotationName(nsAString & aNotationName) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMEntity, NS_IDOMENTITY_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMENTITY \
NS_SCRIPTABLE NS_IMETHOD GetPublicId(nsAString & aPublicId); \
NS_SCRIPTABLE NS_IMETHOD GetSystemId(nsAString & aSystemId); \
NS_SCRIPTABLE NS_IMETHOD GetNotationName(nsAString & aNotationName);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMENTITY(_to) \
NS_SCRIPTABLE NS_IMETHOD GetPublicId(nsAString & aPublicId) { return _to GetPublicId(aPublicId); } \
NS_SCRIPTABLE NS_IMETHOD GetSystemId(nsAString & aSystemId) { return _to GetSystemId(aSystemId); } \
NS_SCRIPTABLE NS_IMETHOD GetNotationName(nsAString & aNotationName) { return _to GetNotationName(aNotationName); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMENTITY(_to) \
NS_SCRIPTABLE NS_IMETHOD GetPublicId(nsAString & aPublicId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPublicId(aPublicId); } \
NS_SCRIPTABLE NS_IMETHOD GetSystemId(nsAString & aSystemId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemId(aSystemId); } \
NS_SCRIPTABLE NS_IMETHOD GetNotationName(nsAString & aNotationName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotationName(aNotationName); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMEntity : public nsIDOMEntity
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMENTITY
nsDOMEntity();
private:
~nsDOMEntity();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMEntity, nsIDOMEntity)
nsDOMEntity::nsDOMEntity()
{
/* member initializers and constructor code */
}
nsDOMEntity::~nsDOMEntity()
{
/* destructor code */
}
/* readonly attribute DOMString publicId; */
NS_IMETHODIMP nsDOMEntity::GetPublicId(nsAString & aPublicId)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString systemId; */
NS_IMETHODIMP nsDOMEntity::GetSystemId(nsAString & aSystemId)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString notationName; */
NS_IMETHODIMP nsDOMEntity::GetNotationName(nsAString & aNotationName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMEntity_h__ */
| [
"simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9"
] | [
[
[
1,
124
]
]
] |
c7324dad58fbfe71214547e49f39e76d4630b30f | 8452181661aa28d1979a1e6e1f39d495e00570cf | /include/jsw_slib.h | 88d61e24b8600225430551f0999051e242592a93 | [] | no_license | viscousliquid/bitcask-c | 8b6169a33613e28774f1a37dc0bbfd1638f7f254 | 53f03e97bb7af80b3b99347a32770ad43c8fa6c0 | refs/heads/master | 2020-05-17T08:21:12.400972 | 2011-11-21T18:43:11 | 2011-11-21T18:43:11 | 2,822,033 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,288 | h | #ifndef JSW_SLIB_H
#define JSW_SLIB_H
/*
Classic skip list library
> Created (Julienne Walker): April 11, 2004
> Updated (Julienne Walker): August 19, 2005
This code is in the public domain. Anyone may
use it or change it in any way that they see
fit. The author assumes no responsibility for
damages incurred through use of the original
code or any variations thereof.
It is requested, but not required, that due
credit is given to the original author and
anyone who has modified the code through
a header comment, such as this one.
*/
#ifdef __cplusplus
#include <cstddef>
using std::size_t;
extern "C" {
#else
#include <stddef.h>
#endif
typedef struct jsw_skip jsw_skip_t;
/* Application specific key comparison function */
typedef int (*cmp_f) ( const void *a, const void *b );
/* Application specific item copying function */
typedef void *(*dup_f) ( const void *item );
/* Application specific item deletion function */
typedef void (*rel_f) ( void *item );
/*
Create a new skip list with a max height of max
Returns: An empty skip list, or NULL on failure
*/
jsw_skip_t *jsw_snew ( size_t max, cmp_f cmp, dup_f dup, rel_f rel );
/* Release all memory used by the skip list */
void jsw_sdelete ( jsw_skip_t *skip );
/*
Find an item with the selected key
Returns: The item, or NULL if not found
*/
void *jsw_sfind ( jsw_skip_t *skip, void *item );
/*
Insert an item with the selected key
Returns: non-zero for success, zero for failure
*/
int jsw_sinsert ( jsw_skip_t *skip, void *item );
/*
Remove an item with the selected key
Returns: non-zero for success, zero for failure
*/
int jsw_serase ( jsw_skip_t *skip, void *item );
/* Current number of items at height 0 */
size_t jsw_ssize ( jsw_skip_t *skip );
/* Reset the traversal markers to the beginning */
void jsw_sreset ( jsw_skip_t *skip );
/*
Get the current item
Returns the item, or NULL if end-of-list
*/
void *jsw_sitem ( jsw_skip_t *skip );
/*
Traverse forward by one key
Returns 0 if end-of-list, 1 otherwise
*/
int jsw_snext ( jsw_skip_t *skip );
#ifdef __cplusplus
}
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
97
]
]
] |
4c8ea35734ac89d06363ed742748766c9011ae35 | f1608b631fe2c1c7b6051cf5451cae361cd20848 | /widget.cpp | e87ea3e814e5341e57f44510f19bdafe42d28a5d | [] | no_license | troublemake/qt_led | f2e5a25e097113a6708599985a3e5c4d4a729218 | c37a4078b724d927b27fd41c3533d2eb10a2a2a1 | refs/heads/master | 2021-01-15T10:47:46.705014 | 2011-08-12T08:55:53 | 2011-08-12T08:55:53 | 2,148,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,994 | cpp | #include <QApplication>
#include <QtDebug>
#include <QFont>
#include <QPushButton>
#include <QWidget>
#include "widget.h"
#include "gpio.h"
#include "led.h"
#include "chestnut.h"
Widget::Widget(QWidget *parent)
: QWidget(parent) {
// setFixedSize(200, 120);
/* The old way over GPIO:
_blue_led = new Gpio(OVERO_GPIO_CHESTNUT_BLUE_LED, GPIO_DIR_OUTPUT);
*/
_blue_led = new Led(LED_BLUE);
QPushButton *ledButton = new QPushButton(tr("LED an/aus"), this);
ledButton->setGeometry(62, 40, 140, 30);
ledButton->setFont(QFont("Times", 18, QFont::Bold));
connect(ledButton, SIGNAL(clicked()),this, SLOT(on_toggle_gpio_led_blue_clicked()));
QPushButton *quitButton = new QPushButton(tr("Quit"), this);
quitButton->setGeometry(62, 80, 75, 30);
quitButton->setFont(QFont("Times", 18, QFont::Bold));
connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));
/* The old way initialize GPIO Port
if (! _blue_led->init())
{
qWarning() << "Error initializing GPIO" << "\n";
}
*/
}
void Widget::on_toggle_gpio_led_blue_clicked()
{
LedState state = _blue_led->get_state();
if (state == LED_STATE_OFF)
_blue_led->set_state(LED_STATE_ON);
else
_blue_led->set_state(LED_STATE_OFF);
/* The old way
GpioState state = _blue_led->get_state();
if (state == GPIO_STATE_LOW) {
_blue_led->set_state(GPIO_STATE_HIGH);
} else {
_blue_led->set_state(GPIO_STATE_LOW);
}
*/
}
void Widget::on_toggle_gpio_led_red_clicked()
{
LedState state = _red_led->get_state();
if (state == LED_STATE_OFF)
_red_led->set_state(LED_STATE_ON);
else
_red_led->set_state(LED_STATE_OFF);
/* The old way
GpioState state = _red_led->get_state();
if (state == GPIO_STATE_LOW) {
_red_led->set_state(GPIO_STATE_HIGH);
} else {
_red_led->set_state(GPIO_STATE_LOW);
}
*/
}
| [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
6c13d6d42e116de12529449b0081e70609b18719 | 502efe97b985c69d6378d9c428c715641719ee03 | /src/moaicore/MOAIAnim.cpp | 65dc7a33ac00ce9d774980c693a923c21deeb14d | [] | no_license | neojjang/moai-beta | c3933bca2625bca4f4da26341de6b855e41b9beb | 6bc96412d35192246e35bff91df101bd7c7e41e1 | refs/heads/master | 2021-01-16T20:33:59.443558 | 2011-09-19T23:45:06 | 2011-09-19T23:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,351 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIAnim.h>
#include <moaicore/MOAIAnimCurve.h>
#include <moaicore/MOAILogMessages.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name apply
@text Apply the anim at a given time or time step.
@overload Apply the anim at time t0.
@in MOAIAnim self
@in number t0 - Default value is 0.
@out nil
@overload Apply the anim for the step t0 to t1.
@in MOAIAnim self
@in number t0 - Default value is 0.
@in number t1 - Default value is 0.
@out nil
*/
int MOAIAnim::_apply ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIAnim, "U" );
float t0 = state.GetValue < float >( 2, 0.0f );
float t1 = state.GetValue < float >( 3, 0.0f );
self->Apply ( t0, t1 );
return 0;
}
//----------------------------------------------------------------//
/** @name getLength
@text Return the length of the animation.
@in MOAIAnim self
@out number length
*/
int MOAIAnim::_getLength ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIAnim, "U" )
lua_pushnumber ( state, self->GetLength ());
return 1;
}
//----------------------------------------------------------------//
/** @name reserveLinks
@text Reserves a specified number of links for the animation.
@in MOAIAnim self
@in number nLinks
@out nil
*/
int MOAIAnim::_reserveLinks ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIAnim, "UN" );
u32 totalLinks = state.GetValue < u32 >( 2, 0 );
self->ReserveLinks ( totalLinks );
return 0;
}
//----------------------------------------------------------------//
/** @name setLink
@text Connect a curve to a given node attribute.
@in MOAIAnim self
@in number linkID
@in MOAIAnimCurve curve
@in MOAINode target - Target node.
@in number attrID - Attribute of the target node to be driven by the curve.
@in boolean asDelta - 'true' to apply the curve as a delta instead of an absolute.
@out nil
*/
int MOAIAnim::_setLink ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIAnim, "UNUUN" );
MOAINode* target = state.GetLuaObject < MOAINode >( 4 );
if ( !target ) return 0;
u32 linkID = state.GetValue < u32 >( 2, 1 ) - 1;
MOAIAnimCurve* curve = state.GetLuaObject < MOAIAnimCurve >( 3 );
u32 attrID = state.GetValue < u32 >( 5, 0 );
bool relative = state.GetValue < bool >( 6, false );
self->SetLink ( linkID, curve, target, attrID, relative );
return 0;
}
//================================================================//
// MOAIAnim
//================================================================//
//----------------------------------------------------------------//
void MOAIAnim::Apply ( float t ) {
u32 total = this->mLinks.Size ();
for ( u32 i = 0; i < total; ++i ) {
MOAIAnimLink& link = this->mLinks [ i ];
MOAIAnimCurve* curve = link.mCurve;
MOAINode* target = link.mTarget;
if ( curve && target ) {
if ( !link.mRelative ) {
float value = curve->GetFloatValue ( t );
target->SetAttributeValue < float >( link.mAttrID, value );
}
target->ScheduleUpdate ();
}
}
}
//----------------------------------------------------------------//
void MOAIAnim::Apply ( float t0, float t1 ) {
if ( t0 == t1 ) {
this->Apply ( t0 );
return;
}
USAttrAdder adder;
u32 total = this->mLinks.Size ();
for ( u32 i = 0; i < total; ++i ) {
MOAIAnimLink& link = this->mLinks [ i ];
MOAIAnimCurve* curve = link.mCurve;
MOAINode* target = link.mTarget;
if ( curve && target ) {
if ( link.mRelative ) {
float value = curve->GetFloatDelta ( t0, t1 );
adder.Set ( value );
target->ApplyAttrOp ( link.mAttrID, adder );
}
else {
float value = curve->GetFloatValue ( t1 );
target->SetAttributeValue < float >( link.mAttrID, value );
}
target->ScheduleUpdate ();
}
}
}
//----------------------------------------------------------------//
void MOAIAnim::Clear () {
this->mLinks.Clear ();
this->mLength = 0.0f;
}
//----------------------------------------------------------------//
MOAIAnim::MOAIAnim () :
mLength ( 0.0f ) {
RTTI_SINGLE ( MOAITimer )
}
//----------------------------------------------------------------//
MOAIAnim::~MOAIAnim () {
this->Clear ();
}
//----------------------------------------------------------------//
void MOAIAnim::OnUpdate ( float step ) {
float t0 = this->mTime;
float t1 = t0 + this->DoStep ( step );
this->Apply ( t0, t1 );
}
//----------------------------------------------------------------//
void MOAIAnim::RegisterLuaClass ( USLuaState& state ) {
MOAITimer::RegisterLuaClass ( state );
}
//----------------------------------------------------------------//
void MOAIAnim::RegisterLuaFuncs ( USLuaState& state ) {
MOAITimer::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "apply", _apply },
{ "getLength", _getLength },
{ "reserveLinks", _reserveLinks },
{ "setLink", _setLink },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAIAnim::ReserveLinks ( u32 totalLinks ) {
this->mLinks.Init ( totalLinks );
}
//----------------------------------------------------------------//
void MOAIAnim::SetLink ( u32 linkID, MOAIAnimCurve* curve, MOAINode* target, u32 attrID, bool relative ) {
if ( linkID >= this->mLinks.Size ()) return;
if ( !target ) return;
if ( !target->AttrExists ( attrID )) return;
MOAIAnimLink& link = this->mLinks [ linkID ];
link.mCurve = curve;
link.mTarget = target;
link.mAttrID = attrID;
link.mRelative = relative;
float length = curve->GetLength ();
if ( this->mLength < length ) {
this->mLength = length;
}
this->mEndTime = this->mLength;
}
//----------------------------------------------------------------//
STLString MOAIAnim::ToString () {
STLString repr;
PRETTY_PRINT ( repr, mLength )
PRETTY_PRINT ( repr, mLinks )
return repr;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
150
],
[
152,
246
]
],
[
[
151,
151
]
]
] |
c8f437e0b06dfca239a0a69ac3fa1e5cae713efd | c9adb5667e26166f73278c703c1e4c3d8383d298 | /source/game_states/State.h | d6c06e4fdc371f279e52b5bb0a8ab6c2b6cad0d9 | [] | no_license | aguperezpala/ggj-11-cpp | 671b2b0aae04abcb249872c90787b239aa01277f | 52074481eea0d4d53a396e61add39a71f981d54d | refs/heads/master | 2016-09-03T02:42:36.483142 | 2011-02-04T01:48:58 | 2011-02-04T01:48:58 | 33,815,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | #ifndef STATE_H
#define STATE_H
//////////////////////////////////////////////////////////////////////////
//
// Name: State.h
//
// Desc: Abstract class that represent a game's state
//
// Author: Bertoa Nicolas - [email protected]
//
//////////////////////////////////////////////////////////////////////////
//
// Headers
//
#include <SFML/Graphics.hpp>
//
// Forward declarations
//
class StateMachine;
class State
{
public:
virtual ~State() {}
//this will execute when the state is entered
virtual void Init(sf::RenderWindow* screen)=0;
//this is the states normal update function
virtual void Execute(StateMachine* pStateMachine)=0;
//this will execute when the state is exited.
virtual void Clear()=0;
};
#endif // STATE_H
| [
"[email protected]@3c77addd-9743-8da5-14ef-4e68ef62d26b"
] | [
[
[
1,
47
]
]
] |
b7fdb94f6fab9a8beb0a2e0ffee56470cc92b086 | 1bd75b9c45c3d5d5af3a9c9ba84ab0d4ec1bfd8f | /Recorder.cpp | ee9f60e033a777883583f604850cc8fb70656418 | [] | no_license | nadernt/whistle-recognizer | 168634eda147752fada31d1b4e073971a053b4bf | 7f260f7ee38d9445e2f0806566bbc0ceb45d3986 | refs/heads/master | 2020-04-06T04:26:13.138539 | 2010-01-12T17:11:08 | 2017-02-23T12:22:25 | 82,922,754 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,890 | cpp | // Recorder.cpp: implementation of the CRecorder class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "waveInFFT.h"
#include "Recorder.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
void CALLBACK waveInProc(HWAVEIN hwi, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
Recorder* pRecorder = NULL;
switch (uMsg)
{
case WIM_OPEN:
break;
case WIM_DATA:
//if ((((LPWAVEHDR)dwParam1)->dwFlags) == WHDR_DONE)
{
pRecorder = (Recorder*)(((LPWAVEHDR)dwParam1)->dwUser);
pRecorder->m_lpWaveHdr = (LPWAVEHDR)dwParam1;
SetEvent(pRecorder->m_hEvent);
}
break;
case WIM_CLOSE:
break;
default:
break;
}
}
DWORD CALLBACK RecorderThreadFunc(LPVOID lpThreadData)
{
Recorder* pRecorder = NULL;
pRecorder = (Recorder*)lpThreadData;
while (pRecorder->IsRecording())
{
WaitForSingleObject(pRecorder->m_hEvent,INFINITE);
pRecorder->ProcessNextBuffer(pRecorder->m_lpWaveHdr);
}
return 0;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Recorder::Recorder(int nBufferLength)
{
m_bRecording = FALSE;
m_bDeviceOpen = FALSE;
m_PcmFormat.wBitsPerSample = 16;
m_PcmFormat.wChannels = 1;
m_PcmFormat.dwSampleRate = 11025;
m_dwBufferSize = (nBufferLength * m_PcmFormat.wChannels * m_PcmFormat.wBitsPerSample / 8);
fnProcessBuffer = NULL;
m_lpWaveHdr = NULL;
m_hEvent = NULL;
m_hThread = NULL;
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
m_hWaveInHdr[i] = NULL;
m_hInBuffer[i] = NULL;
}
}
Recorder::Recorder(PCMFORMAT pcm,int nBufferLength)
{
m_bRecording = FALSE;
m_bDeviceOpen = FALSE;
m_PcmFormat.wBitsPerSample = pcm.wBitsPerSample;
m_PcmFormat.wChannels = pcm.wChannels;
m_PcmFormat.dwSampleRate = pcm.dwSampleRate;
m_dwBufferSize = (nBufferLength * m_PcmFormat.wChannels * m_PcmFormat.wBitsPerSample / 8);
fnProcessBuffer = NULL;
m_lpWaveHdr = NULL;
m_hEvent = NULL;
m_hThread = NULL;
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
m_hWaveInHdr[i] = NULL;
m_hInBuffer[i] = NULL;
}
}
Recorder::Recorder(WORD wBitsPerSample,WORD wChannels,DWORD dwSampleRate,int nBufferLength)
{
m_bRecording = FALSE;
m_bDeviceOpen = FALSE;
m_PcmFormat.wBitsPerSample = wBitsPerSample;
m_PcmFormat.wChannels = wChannels;
m_PcmFormat.dwSampleRate = dwSampleRate;
m_dwBufferSize = (nBufferLength * m_PcmFormat.wChannels * m_PcmFormat.wBitsPerSample / 8);
fnProcessBuffer = NULL;
m_lpWaveHdr = NULL;
m_hEvent = NULL;
m_hThread = NULL;
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
m_hWaveInHdr[i] = NULL;
m_hInBuffer[i] = NULL;
}
}
Recorder::~Recorder()
{
if(m_bRecording)
Stop();
if(m_bDeviceOpen)
Close();
fnProcessBuffer = NULL;
}
void Recorder::Open(DWORD dwCallBack, DWORD dwCallbackType,MCIDEVICEID wMCIDeviceID)
{
if(m_bDeviceOpen)
{
TRACE("Device Already Opened. Please Stop Recorder before attempting to Open\n");
return;
}
if (dwCallBack == NULL)
dwCallBack = (DWORD)waveInProc;
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
m_hWaveInHdr[i] = GlobalAlloc(GHND | GMEM_SHARE , sizeof(WAVEHDR));
m_lpWaveInHdr[i] = (LPWAVEHDR)GlobalLock(m_hWaveInHdr[i]);
m_hInBuffer[i] = GlobalAlloc(GHND | GMEM_SHARE , m_dwBufferSize);
m_lpInBuffer[i] = (LPBYTE)GlobalLock(m_hInBuffer[i]);
m_lpWaveInHdr[i]->lpData = (LPSTR)m_lpInBuffer[i];
m_lpWaveInHdr[i]->dwBufferLength = m_dwBufferSize;
m_lpWaveInHdr[i]->dwBytesRecorded = 0L;
m_lpWaveInHdr[i]->dwUser = (DWORD)(void*)this;
m_lpWaveInHdr[i]->dwFlags = 0L;
m_lpWaveInHdr[i]->dwLoops = 1L;
m_lpWaveInHdr[i]->lpNext = NULL;
m_lpWaveInHdr[i]->reserved = 0L;
}
m_WaveFormat.wFormatTag = WAVE_FORMAT_PCM;
m_WaveFormat.nChannels = m_PcmFormat.wChannels;
m_WaveFormat.wBitsPerSample = m_PcmFormat.wBitsPerSample;
m_WaveFormat.nSamplesPerSec = m_PcmFormat.dwSampleRate;
m_WaveFormat.nBlockAlign = m_WaveFormat.nChannels * m_WaveFormat.wBitsPerSample/8;
m_WaveFormat.nAvgBytesPerSec = m_WaveFormat.nBlockAlign * m_WaveFormat.nSamplesPerSec;
m_waveClass.lpData = this;
if(waveInOpen((LPHWAVEIN)&m_waveClass, wMCIDeviceID, &m_WaveFormat, (DWORD)dwCallBack , 0L, dwCallbackType) || m_waveClass.hWave==0)
return;
m_waveClass.lpData = this;
m_hWaveIn = (HWAVEIN)m_waveClass.hWave;
m_hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
m_bDeviceOpen=TRUE;
}
void Recorder::Start()
{
if(!m_bDeviceOpen)
{
TRACE("Device not Opened. Please open device before attempting to Start\n");
return;
}
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
// Prepare wave in header
if(waveInPrepareHeader(m_hWaveIn, m_lpWaveInHdr[i], sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
return;
// Add buffer into recording queue
if(waveInAddBuffer(m_hWaveIn, m_lpWaveInHdr[i], sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
return;
}
// Begin sampling
m_bRecording = TRUE;
m_hThread = CreateThread(NULL,NULL,RecorderThreadFunc,this,NULL,NULL);
waveInStart(m_hWaveIn);
ASSERT(m_hThread!=NULL);
SetPriorityClass(m_hThread,REALTIME_PRIORITY_CLASS);
SetThreadPriority(m_hThread,THREAD_PRIORITY_HIGHEST);
}
void Recorder::Stop()
{
if(!m_bDeviceOpen || !m_bRecording)
return;
if(waveInStop(m_hWaveIn) != MMSYSERR_NOERROR)
return;
else
m_bRecording=FALSE;
}
void Recorder::Close()
{
if(m_bRecording)
Stop();
if (m_hThread != NULL)
CloseHandle(m_hThread);
if(m_bDeviceOpen)
waveInClose(m_hWaveIn);
for(int i=0; i<MAXNUMOFBUFFER; i++)
{
if (m_hWaveInHdr[i] != NULL)
{
if (GlobalUnlock(m_hWaveInHdr[i]))
GlobalFree(m_hWaveInHdr[i]);
if (GlobalUnlock(m_hInBuffer[i]))
GlobalFree(m_hInBuffer[i]);
m_hWaveInHdr[i] = NULL;
m_hInBuffer[i] = NULL;
}
}
m_bDeviceOpen=FALSE;
m_bRecording = FALSE;
m_hThread = NULL;
}
void Recorder::SetFormat(LPPCMFORMAT lpPcmFormat)
{
ASSERT(m_bDeviceOpen==FALSE);
m_PcmFormat.wBitsPerSample = lpPcmFormat->wBitsPerSample;
m_PcmFormat.wChannels = lpPcmFormat->wChannels;
m_PcmFormat.dwSampleRate = lpPcmFormat->dwSampleRate;
}
void Recorder::SetFormat(WORD wBitsPerSample,WORD wChannels,DWORD dwSampleRate)
{
ASSERT(m_bDeviceOpen==FALSE);
m_PcmFormat.wBitsPerSample = wBitsPerSample;
m_PcmFormat.wChannels = wChannels;
m_PcmFormat.dwSampleRate = dwSampleRate;
}
BOOL Recorder::IsRecording()
{
return m_bRecording;
}
BOOL Recorder::IsDeviceOpen()
{
return m_bDeviceOpen;
}
void Recorder::ProcessNextBuffer(LPWAVEHDR pwh)
{
if (fnProcessBuffer != NULL)
fnProcessBuffer(m_lpData,pwh);
waveInUnprepareHeader(m_hWaveIn, pwh, sizeof(WAVEHDR));
waveInPrepareHeader (m_hWaveIn, pwh, sizeof(WAVEHDR));
waveInAddBuffer(m_hWaveIn, pwh, sizeof(WAVEHDR));
}
DWORD Recorder::GetPosition()
{
if (m_hWaveIn)
{
MMTIME mmtime;
mmtime.wType = TIME_SAMPLES;
if (waveInGetPosition(m_hWaveIn, &mmtime, sizeof(MMTIME)) != MMSYSERR_NOERROR)
return -1;
else
return mmtime.u.sample;
}
return -1;
}
BOOL Recorder::Pause()
{
if (m_hWaveIn)
{
if (waveInStop(m_hWaveIn) == MMSYSERR_NOERROR)
{
m_bRecording = FALSE;
return TRUE;
}
}
return FALSE;
}
BOOL Recorder::Continue()
{
if (m_hWaveIn)
{
if (waveInStart(m_hWaveIn) == MMSYSERR_NOERROR)
{
m_bRecording = FALSE;
return TRUE;
}
}
return FALSE;
}
BOOL Recorder::IsFormatSupported(WAVEFORMATEX wfEx, UINT nDev)
{
MMRESULT mm = waveInOpen(0,nDev,&wfEx,0,0,WAVE_FORMAT_QUERY);
return (BOOL)mm == MMSYSERR_NOERROR;
}
| [
"[email protected]"
] | [
[
[
1,
294
]
]
] |
78de3addcab7d17d037d1d9ffa58d218ab932af1 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Collide/Agent/Util/LinearCast/hkpIterativeLinearCastAgent.h | 726ead601d88ec2a5671be06a068011bcbfcfa16 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,239 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_LEAF_AGENT_H
#define HK_COLLIDE2_LEAF_AGENT_H
#include <Common/Base/hkBase.h>
#include <Physics/Collide/Agent/hkpCollisionAgent.h>
/// This agent adds some linear casting functionality shared by terminal/leaf hkCollisionAgents.
class hkpIterativeLinearCastAgent : public hkpCollisionAgent
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_AGENT);
hkpIterativeLinearCastAgent(hkpContactMgr* contactMgr): hkpCollisionAgent(contactMgr){}
//implementation of the hkpCollisionAgent
virtual void linearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
//implementation of the hkpCollisionAgent
static void HK_CALL staticLinearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector );
HK_FORCE_INLINE ~hkpIterativeLinearCastAgent(){}
};
#endif // HK_COLLIDE2_LEAF_AGENT_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
50
]
]
] |
1d54bcb81621055513125be3b3a24d59de4fc8d3 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/win/WebCoreSupport/WebInspectorClient.cpp | 0c2b9d159c2db27c796619888bb5662c9765c69e | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,226 | cpp | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebInspectorClient.h"
#include "WebInspectorDelegate.h"
#include "WebKit.h"
#include "WebMutableURLRequest.h"
#include "WebNodeHighlight.h"
#include "WebView.h"
#pragma warning(push, 0)
#include <WebCore/BString.h>
#include <WebCore/Element.h>
#include <WebCore/FloatRect.h>
#include <WebCore/FrameView.h>
#include <WebCore/InspectorController.h>
#include <WebCore/NotImplemented.h>
#include <WebCore/Page.h>
#include <WebCore/RenderObject.h>
#include <WebCore/WindowMessageBroadcaster.h>
#pragma warning(pop)
#include <tchar.h>
#include <wtf/RetainPtr.h>
using namespace WebCore;
static LPCTSTR kWebInspectorWindowClassName = TEXT("WebInspectorWindowClass");
static ATOM registerWindowClass();
static LPCTSTR kWebInspectorPointerProp = TEXT("WebInspectorPointer");
static const IntRect& defaultWindowRect()
{
static IntRect rect(60, 200, 750, 650);
return rect;
}
static CFBundleRef getWebKitBundle()
{
return CFBundleGetBundleWithIdentifier(CFSTR("com.apple.WebKit"));
}
WebInspectorClient::WebInspectorClient(WebView* webView)
: m_inspectedWebView(webView)
, m_frontendPage(0)
{
ASSERT(m_inspectedWebView);
m_inspectedWebView->viewWindow((OLE_HANDLE*)&m_inspectedWebViewHwnd);
}
WebInspectorClient::~WebInspectorClient()
{
m_frontendPage = 0;
}
void WebInspectorClient::inspectorDestroyed()
{
delete this;
}
void WebInspectorClient::openInspectorFrontend(InspectorController* inspectorController)
{
registerWindowClass();
HWND frontendHwnd = ::CreateWindowEx(0, kWebInspectorWindowClassName, 0, WS_OVERLAPPEDWINDOW,
defaultWindowRect().x(), defaultWindowRect().y(), defaultWindowRect().width(), defaultWindowRect().height(),
0, 0, 0, 0);
if (!frontendHwnd)
return;
COMPtr<WebView> frontendWebView(AdoptCOM, WebView::createInstance());
if (FAILED(frontendWebView->setHostWindow((OLE_HANDLE)(ULONG64)frontendHwnd)))
return;
RECT rect;
GetClientRect(frontendHwnd, &rect);
if (FAILED(frontendWebView->initWithFrame(rect, 0, 0)))
return;
COMPtr<WebInspectorDelegate> delegate(AdoptCOM, WebInspectorDelegate::createInstance());
if (FAILED(frontendWebView->setUIDelegate(delegate.get())))
return;
// Keep preferences separate from the rest of the client, making sure we are using expected preference values.
// One reason this is good is that it keeps the inspector out of history via "private browsing".
// FIXME: It's crazy that we have to do this song and dance to end up with
// a private WebPreferences object, even within WebKit. We should make this
// process simpler, and consider whether we can make it simpler for WebKit
// clients as well.
COMPtr<WebPreferences> tempPreferences(AdoptCOM, WebPreferences::createInstance());
COMPtr<IWebPreferences> iPreferences;
if (FAILED(tempPreferences->initWithIdentifier(BString(L"WebInspectorPreferences"), &iPreferences)))
return;
COMPtr<WebPreferences> preferences(Query, iPreferences);
if (!preferences)
return;
if (FAILED(preferences->setAutosaves(FALSE)))
return;
if (FAILED(preferences->setPrivateBrowsingEnabled(TRUE)))
return;
if (FAILED(preferences->setLoadsImagesAutomatically(TRUE)))
return;
if (FAILED(preferences->setAuthorAndUserStylesEnabled(TRUE)))
return;
if (FAILED(preferences->setAllowsAnimatedImages(TRUE)))
return;
if (FAILED(preferences->setLoadsImagesAutomatically(TRUE)))
return;
if (FAILED(preferences->setPlugInsEnabled(FALSE)))
return;
if (FAILED(preferences->setJavaEnabled(FALSE)))
return;
if (FAILED(preferences->setUserStyleSheetEnabled(FALSE)))
return;
if (FAILED(preferences->setTabsToLinks(FALSE)))
return;
if (FAILED(preferences->setMinimumFontSize(0)))
return;
if (FAILED(preferences->setMinimumLogicalFontSize(9)))
return;
if (FAILED(preferences->setFixedFontFamily(BString(L"Courier New"))))
return;
if (FAILED(preferences->setDefaultFixedFontSize(13)))
return;
if (FAILED(frontendWebView->setPreferences(preferences.get())))
return;
frontendWebView->setProhibitsMainFrameScrolling(TRUE);
HWND frontendWebViewHwnd;
if (FAILED(frontendWebView->viewWindow(reinterpret_cast<OLE_HANDLE*>(&frontendWebViewHwnd))))
return;
COMPtr<WebMutableURLRequest> request(AdoptCOM, WebMutableURLRequest::createInstance());
RetainPtr<CFURLRef> htmlURLRef(AdoptCF, CFBundleCopyResourceURL(getWebKitBundle(), CFSTR("inspector"), CFSTR("html"), CFSTR("inspector")));
if (!htmlURLRef)
return;
CFStringRef urlStringRef = ::CFURLGetString(htmlURLRef.get());
if (FAILED(request->initWithURL(BString(urlStringRef), WebURLRequestUseProtocolCachePolicy, 60)))
return;
if (FAILED(frontendWebView->topLevelFrame()->loadRequest(request.get())))
return;
m_frontendPage = core(frontendWebView.get());
WebInspectorFrontendClient* frontendClient = new WebInspectorFrontendClient(m_inspectedWebView, m_inspectedWebViewHwnd, frontendHwnd, frontendWebView, frontendWebViewHwnd, this);
m_frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient);
m_frontendHwnd = frontendHwnd;
}
void WebInspectorClient::highlight(Node*)
{
bool creatingHighlight = !m_highlight;
if (creatingHighlight)
m_highlight.set(new WebNodeHighlight(m_inspectedWebView));
if (m_highlight->isShowing())
m_highlight->update();
else
m_highlight->setShowsWhileWebViewIsVisible(true);
if (creatingHighlight && IsWindowVisible(m_frontendHwnd))
m_highlight->placeBehindWindow(m_frontendHwnd);
}
void WebInspectorClient::hideHighlight()
{
if (m_highlight)
m_highlight->setShowsWhileWebViewIsVisible(false);
}
void WebInspectorClient::updateHighlight()
{
if (m_highlight && m_highlight->isShowing())
m_highlight->update();
}
WebInspectorFrontendClient::WebInspectorFrontendClient(WebView* inspectedWebView, HWND inspectedWebViewHwnd, HWND frontendHwnd, const COMPtr<WebView>& frontendWebView, HWND frontendWebViewHwnd, WebInspectorClient* inspectorClient)
: InspectorFrontendClientLocal(inspectedWebView->page()->inspectorController(), core(frontendWebView.get()))
, m_inspectedWebView(inspectedWebView)
, m_inspectedWebViewHwnd(inspectedWebViewHwnd)
, m_inspectorClient(inspectorClient)
, m_frontendHwnd(frontendHwnd)
, m_frontendWebView(frontendWebView)
, m_frontendWebViewHwnd(frontendWebViewHwnd)
, m_attached(false)
, m_destroyingInspectorView(false)
{
::SetProp(frontendHwnd, kWebInspectorPointerProp, reinterpret_cast<HANDLE>(this));
// FIXME: Implement window size/position save/restore
#if 0
[self setWindowFrameAutosaveName:@"Web Inspector"];
#endif
}
WebInspectorFrontendClient::~WebInspectorFrontendClient()
{
destroyInspectorView(true);
}
void WebInspectorFrontendClient::frontendLoaded()
{
InspectorFrontendClientLocal::frontendLoaded();
setAttachedWindow(m_attached);
}
String WebInspectorFrontendClient::localizedStringsURL()
{
RetainPtr<CFURLRef> url(AdoptCF, CFBundleCopyResourceURL(getWebKitBundle(), CFSTR("localizedStrings"), CFSTR("js"), 0));
if (!url)
return String();
return CFURLGetString(url.get());
}
String WebInspectorFrontendClient::hiddenPanels()
{
// FIXME: implement this
return String();
}
void WebInspectorFrontendClient::bringToFront()
{
showWindowWithoutNotifications();
}
void WebInspectorFrontendClient::closeWindow()
{
destroyInspectorView(true);
}
void WebInspectorFrontendClient::disconnectFromBackend()
{
destroyInspectorView(false);
}
void WebInspectorFrontendClient::attachWindow()
{
if (m_attached)
return;
m_inspectedWebView->page()->inspectorController()->setSetting(InspectorController::inspectorStartsAttachedSettingName(), "true");
closeWindowWithoutNotifications();
showWindowWithoutNotifications();
}
void WebInspectorFrontendClient::detachWindow()
{
if (!m_attached)
return;
m_inspectedWebView->page()->inspectorController()->setSetting(InspectorController::inspectorStartsAttachedSettingName(), "false");
closeWindowWithoutNotifications();
showWindowWithoutNotifications();
}
void WebInspectorFrontendClient::setAttachedWindowHeight(unsigned height)
{
if (!m_attached)
return;
HWND hostWindow;
if (!SUCCEEDED(m_inspectedWebView->hostWindow((OLE_HANDLE*)&hostWindow)))
return;
RECT hostWindowRect;
GetClientRect(hostWindow, &hostWindowRect);
RECT inspectedRect;
GetClientRect(m_inspectedWebViewHwnd, &inspectedRect);
int totalHeight = hostWindowRect.bottom - hostWindowRect.top;
int webViewWidth = inspectedRect.right - inspectedRect.left;
SetWindowPos(m_frontendWebViewHwnd, 0, 0, totalHeight - height, webViewWidth, height, SWP_NOZORDER);
// We want to set the inspected web view height to the totalHeight, because the height adjustment
// of the inspected web view happens in onWebViewWindowPosChanging, not here.
SetWindowPos(m_inspectedWebViewHwnd, 0, 0, 0, webViewWidth, totalHeight, SWP_NOZORDER);
RedrawWindow(m_frontendWebViewHwnd, 0, 0, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
RedrawWindow(m_inspectedWebViewHwnd, 0, 0, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
}
void WebInspectorFrontendClient::inspectedURLChanged(const String& newURL)
{
m_inspectedURL = newURL;
updateWindowTitle();
}
void WebInspectorFrontendClient::closeWindowWithoutNotifications()
{
if (!m_frontendHwnd)
return;
if (!m_attached) {
ShowWindow(m_frontendHwnd, SW_HIDE);
return;
}
ASSERT(m_frontendWebView);
ASSERT(m_inspectedWebViewHwnd);
ASSERT(!IsWindowVisible(m_frontendHwnd));
// Remove the Inspector's WebView from the inspected WebView's parent window.
WindowMessageBroadcaster::removeListener(m_inspectedWebViewHwnd, this);
m_attached = false;
m_frontendWebView->setHostWindow(reinterpret_cast<OLE_HANDLE>(m_frontendHwnd));
// Make sure everything has the right size/position.
HWND hostWindow;
if (SUCCEEDED(m_inspectedWebView->hostWindow((OLE_HANDLE*)&hostWindow)))
SendMessage(hostWindow, WM_SIZE, 0, 0);
}
void WebInspectorFrontendClient::showWindowWithoutNotifications()
{
if (!m_frontendHwnd)
return;
ASSERT(m_frontendWebView);
ASSERT(m_inspectedWebViewHwnd);
bool shouldAttach = false;
if (m_attached)
shouldAttach = true;
else {
// If no preference is set - default to an attached window. This is important for inspector LayoutTests.
String shouldAttachPref = m_inspectedWebView->page()->inspectorController()->setting(InspectorController::inspectorStartsAttachedSettingName());
shouldAttach = shouldAttachPref != "false";
if (shouldAttach && !canAttachWindow())
shouldAttach = false;
}
if (!shouldAttach) {
// Put the Inspector's WebView inside our window and show it.
m_frontendWebView->setHostWindow(reinterpret_cast<OLE_HANDLE>(m_frontendHwnd));
SendMessage(m_frontendHwnd, WM_SIZE, 0, 0);
updateWindowTitle();
SetWindowPos(m_frontendHwnd, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
return;
}
// Put the Inspector's WebView inside the inspected WebView's parent window.
WindowMessageBroadcaster::addListener(m_inspectedWebViewHwnd, this);
HWND hostWindow;
if (FAILED(m_inspectedWebView->hostWindow(reinterpret_cast<OLE_HANDLE*>(&hostWindow))))
return;
m_frontendWebView->setHostWindow(reinterpret_cast<OLE_HANDLE>(hostWindow));
// Then hide our own window.
ShowWindow(m_frontendHwnd, SW_HIDE);
m_attached = true;
// Make sure everything has the right size/position.
SendMessage(hostWindow, WM_SIZE, 0, 0);
m_inspectorClient->updateHighlight();
}
void WebInspectorFrontendClient::destroyInspectorView(bool notifyInspectorController)
{
if (m_destroyingInspectorView)
return;
m_destroyingInspectorView = true;
closeWindowWithoutNotifications();
if (notifyInspectorController) {
m_inspectedWebView->page()->inspectorController()->disconnectFrontend();
m_inspectorClient->updateHighlight();
m_inspectorClient->frontendClosing();
}
::DestroyWindow(m_frontendHwnd);
}
void WebInspectorFrontendClient::updateWindowTitle()
{
// FIXME: The series of appends should be replaced with a call to String::format()
// when it can be figured out how to get the unicode em-dash to show up.
String title = "Web Inspector ";
title.append((UChar)0x2014); // em-dash
title.append(' ');
title.append(m_inspectedURL);
::SetWindowText(m_frontendHwnd, title.charactersWithNullTermination());
}
LRESULT WebInspectorFrontendClient::onGetMinMaxInfo(WPARAM, LPARAM lParam)
{
MINMAXINFO* info = reinterpret_cast<MINMAXINFO*>(lParam);
POINT size = {400, 400};
info->ptMinTrackSize = size;
return 0;
}
LRESULT WebInspectorFrontendClient::onSize(WPARAM, LPARAM)
{
RECT rect;
::GetClientRect(m_frontendHwnd, &rect);
::SetWindowPos(m_frontendWebViewHwnd, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER);
return 0;
}
LRESULT WebInspectorFrontendClient::onClose(WPARAM, LPARAM)
{
::ShowWindow(m_frontendHwnd, SW_HIDE);
m_inspectedWebView->page()->inspectorController()->close();
return 0;
}
LRESULT WebInspectorFrontendClient::onSetFocus()
{
SetFocus(m_frontendWebViewHwnd);
return 0;
}
void WebInspectorFrontendClient::onWebViewWindowPosChanging(WPARAM, LPARAM lParam)
{
ASSERT(m_attached);
WINDOWPOS* windowPos = reinterpret_cast<WINDOWPOS*>(lParam);
ASSERT_ARG(lParam, windowPos);
if (windowPos->flags & SWP_NOSIZE)
return;
RECT inspectorRect;
GetClientRect(m_frontendWebViewHwnd, &inspectorRect);
unsigned inspectorHeight = inspectorRect.bottom - inspectorRect.top;
windowPos->cy -= inspectorHeight;
SetWindowPos(m_frontendWebViewHwnd, 0, windowPos->x, windowPos->y + windowPos->cy, windowPos->cx, inspectorHeight, SWP_NOZORDER);
}
static LRESULT CALLBACK WebInspectorWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
WebInspectorFrontendClient* client = reinterpret_cast<WebInspectorFrontendClient*>(::GetProp(hwnd, kWebInspectorPointerProp));
if (!client)
return ::DefWindowProc(hwnd, msg, wParam, lParam);
switch (msg) {
case WM_GETMINMAXINFO:
return client->onGetMinMaxInfo(wParam, lParam);
case WM_SIZE:
return client->onSize(wParam, lParam);
case WM_CLOSE:
return client->onClose(wParam, lParam);
case WM_SETFOCUS:
return client->onSetFocus();
default:
break;
}
return ::DefWindowProc(hwnd, msg, wParam, lParam);
}
void WebInspectorFrontendClient::windowReceivedMessage(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_WINDOWPOSCHANGING:
onWebViewWindowPosChanging(wParam, lParam);
break;
default:
break;
}
}
static ATOM registerWindowClass()
{
static bool haveRegisteredWindowClass = false;
if (haveRegisteredWindowClass)
return true;
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = WebInspectorWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = 0;
wcex.hIcon = 0;
wcex.hCursor = LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = 0;
wcex.lpszMenuName = 0;
wcex.lpszClassName = kWebInspectorWindowClassName;
wcex.hIconSm = 0;
haveRegisteredWindowClass = true;
return ::RegisterClassEx(&wcex);
}
| [
"[email protected]"
] | [
[
[
1,
542
]
]
] |
61200fc5cb41758ad11f762b6c29103649645fb5 | 12d558835322c0beafeeff98f99729aa7ee1a205 | /QuartoApp/src/include/Piece.hpp | ec26176e52ed108287978312757034a12817c2c1 | [] | no_license | douglyuckling/quarto | b3fae27a9e06be774dd4f12bf9cef67dada3b201 | fc493b83c8c7a6964c334b32281850d1c659b394 | refs/heads/master | 2020-12-30T10:36:33.716568 | 2010-07-09T04:48:33 | 2010-07-09T04:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | hpp | /**
* @file Piece.hpp
*/
#pragma once
typedef unsigned char byte;
namespace quarto {
const byte SQUARE = 0x40;
const byte ROUND = 0x80;
const byte SHORT = 0x10;
const byte TALL = 0x20;
const byte SOLID = 0x04;
const byte HOLLOW = 0x08;
const byte DARK = 0x01;
const byte LIGHT = 0x02;
class Piece {
public:
Piece(bool isRound, bool isTall, bool isHollow, bool isLight);
Piece(byte description);
inline byte getInfo() const { return description; }
inline bool isRound() const { return (description & ROUND) != 0; }
inline bool isTall() const { return (description & TALL) != 0; }
inline bool isHollow() const { return (description & HOLLOW) != 0; }
inline bool isLight() const { return (description & LIGHT) != 0; }
inline bool operator==(const Piece &piece) const { return description == piece.description; }
private:
byte description;
void validateDescription(byte description);
};
}
| [
"douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9"
] | [
[
[
1,
43
]
]
] |
2d20db37eeecdf48aca6d4eabb7839d3b6369ffd | d22a7c4b1de9d388725cbbe8f91d7f0bad6d6631 | /test/test.cpp | 4f243e76197720ec529ef2d1eeacf06fda69a0c3 | [] | no_license | shachaoshu/tinycollision | 7d4a365126cf58368fa9dc34653eea010dce9c33 | e60572c3995d3e94e6c58a439d04c9c36d52c187 | refs/heads/master | 2016-09-06T03:02:23.394961 | 2008-10-12T15:11:39 | 2008-10-12T15:11:39 | 32,302,852 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,199 | cpp | // test.cpp : 定义控制台应用程序的入口点。
//
#include <Windows.h>
#include <iostream>
#include "SDL.h"
#include "tinycollision.h"
using namespace TinyCollison;
class Man :public Object{
public:
Man(int x=0, int y=0, int z=0 ,int x_width =1,int y_width =1,int z_width=1)
{
this->x = x;
this->y = y;
this->z = z;
this->x_width = x_width;
this->y_width = y_width;
this->z_width = z_width;
}
void OnCollision( const Object * other_obj){
MessageBoxA(0,"碰撞了","碰撞了", MB_OK);
};
};
class MyView :public ObjectView{
public:
SDL_Surface *image;
SDL_Surface *screen;
void InitDisplay()
{
if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "无法初始化SDL: %s\n", SDL_GetError());
exit(1);
}
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
if ( screen == NULL ) {
fprintf(stderr, "无法设置640x480的视频模式:%s\n", SDL_GetError());
exit(1);
}
image = SDL_LoadBMP("obj.bmp");
if(!image)
fprintf(stderr, "无法加载obj图片:%s\n", SDL_GetError());
}
void DrawObj(const Object *obj)
{
SDL_Rect pos;
pos.x = obj->x - obj->x_width;
pos.y = obj->y - obj->y_width;
pos.h = obj->y_width *2;
pos.w = obj->x_width *2;
SDL_BlitSurface(image ,NULL,screen ,&pos);
}
};
int main(int argc, char * argv[])
{
MyView Screen;
CollisionManager Collistion;
Screen.InitDisplay();
Man man1(100 ,100 ,0 , 10,10 ,10);
Man man2(500, 100 ,0 , 10,10 ,10);
Collistion.AddObject(&man1);
Collistion.AddObject(&man2);
//下面演示一下碰撞
Uint32 time_start = SDL_GetTicks();
Uint32 time_now;
SDL_Rect fullscreen;
fullscreen.x = 0;
fullscreen.y = 0;
fullscreen.w = 640;
fullscreen.h = 480;
for(;;)
{
time_now = SDL_GetTicks();
//
if(time_now -time_start >50)
{//50毫秒一个计算周期
man1.AddX(10);
Collistion.CheckCollision();
Screen.DrawObj(&man1);
Screen.DrawObj(&man2);
}
else
{
SDL_Delay(1);
continue;
}
SDL_UpdateRects(Screen.screen, 1, &fullscreen);
time_start = time_now;
}
atexit(SDL_Quit);
return 0;
}
| [
"cpluser@cd4e6698-9453-11dd-a67f-f17f0f716292"
] | [
[
[
1,
104
]
]
] |
30d29c5adae1eed8a70a9e758e573ee576104a80 | c3531ade6396e9ea9c7c9a85f7da538149df2d09 | /Param/src/OGF/basic/os/environment.cpp | 619504da91cb12e2692b2d4ce10d464948b2bfff | [] | no_license | feengg/MultiChart-Parameterization | ddbd680f3e1c2100e04c042f8f842256f82c5088 | 764824b7ebab9a3a5e8fa67e767785d2aec6ad0a | refs/heads/master | 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,438 | cpp | /*
* OGF/Graphite: Geometry and Graphics Programming Library + Utilities
* Copyright (C) 2000 Bruno Levy
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* [email protected]
*
* ISA Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
* Note that the GNU General Public License does not permit incorporating
* the Software into proprietary programs.
*/
#include <OGF/basic/os/environment.h>
#include <OGF/basic/types/types.h>
#include <OGF/basic/debug/assert.h>
#include <algorithm>
#include <stdlib.h>
namespace OGF {
//__________________________________________________________________
EnvironmentVariableObserver::EnvironmentVariableObserver(const std::string& var_name) {
observed_variable_ = var_name ;
bool added_observer = Environment::instance()->add_observer(var_name, this) ;
ogf_assert(added_observer) ;
}
EnvironmentVariableObserver::~EnvironmentVariableObserver() {
bool removed_observer = Environment::instance()->remove_observer(observed_variable_, this) ;
ogf_assert(removed_observer) ;
}
void EnvironmentVariableObserverList::notify_observers(const std::string& value) {
if(block_notify_) {
return ;
}
block_notify_ = true ;
for(unsigned int i = 0; i < observers_.size(); i++) {
observers_[i]->notify_value_changed(value) ;
}
block_notify_ = false ;
}
void EnvironmentVariableObserverList::add_observer(EnvironmentVariableObserver* obs) {
std::vector<EnvironmentVariableObserver*>::iterator it =
std::find(observers_.begin(), observers_.end(), obs) ;
ogf_assert(it == observers_.end()) ;
observers_.push_back(obs) ;
}
void EnvironmentVariableObserverList::remove_observer(EnvironmentVariableObserver* obs) {
std::vector<EnvironmentVariableObserver*>::iterator it =
std::find(observers_.begin(), observers_.end(), obs) ;
ogf_assert(it != observers_.end()) ;
observers_.erase(it) ;
}
//__________________________________________________________________
Environment* Environment::instance_ = nil ;
Environment::~Environment() {
}
bool Environment::add_environment(Environment* env) {
return false ;
}
bool Environment::has_value(const std::string& name) const {
std::string value ;
return resolve(name, value) ;
}
bool Environment::set_value(const std::string&, const std::string&) {
return false ;
}
std::string Environment::get_value(const std::string& name) const {
std::string result ;
resolve(name, result) ;
return result ;
}
Environment* Environment::instance() {
if(instance_ == nil) {
instance_ = new StoredEnvironment() ;
instance_->add_environment(new SystemEnvironment()) ;
}
return instance_ ;
}
bool Environment::add_observer(const std::string& name, EnvironmentVariableObserver* obs) {
return Environment::instance()->add_observer(name, obs) ;
}
bool Environment::remove_observer(const std::string& name, EnvironmentVariableObserver* obs) {
return Environment::instance()->remove_observer(name, obs) ;
}
bool Environment::notify_observers(const std::string& name) {
return Environment::instance()->notify_observers(name) ;
}
//__________________________________________________________________
StoredEnvironment::~StoredEnvironment() { }
bool StoredEnvironment::add_environment(Environment* env) {
environments_.push_back(env) ;
return true ;
}
bool StoredEnvironment::set_value(
const std::string& name, const std::string& value
) {
for(unsigned int i=0; i<environments_.size(); i++) {
if(environments_[i]->set_value(name,value)) {
return true ;
}
}
values_[name] = value ;
notify_observers(name) ;
return true ;
}
bool StoredEnvironment::resolve(
const std::string& name, std::string& value
) const {
std::map<std::string, std::string>::const_iterator
it = values_.find(name) ;
if(it != values_.end()) {
value = it->second ;
return true ;
}
for(unsigned int i=0; i<environments_.size(); i++) {
if(environments_[i]->resolve(name,value)) {
return true ;
}
}
return false ;
}
bool StoredEnvironment::add_observer(
const std::string& name, EnvironmentVariableObserver* obs
) {
observers_[name].add_observer(obs) ;
return true ;
}
bool StoredEnvironment::remove_observer(
const std::string& name, EnvironmentVariableObserver* obs
) {
ogf_assert(observers_.find(name) != observers_.end()) ;
observers_[name].remove_observer(obs) ;
return true ;
}
bool StoredEnvironment::notify_observers(const std::string& name) {
std::string value ;
bool variable_exists = resolve(name, value) ;
if(!variable_exists) {
Logger::err("Environment") << name << ": no such environment variable" << std::endl ;
}
ogf_assert(variable_exists) ;
ObserverMap::iterator it = observers_.find(name) ;
if(it != observers_.end()) {
it->second.notify_observers(value) ;
}
return true ;
}
//__________________________________________________________________
bool SystemEnvironment::set_value(
const std::string& name, const std::string& value
) {
return false ;
}
bool SystemEnvironment::resolve(
const std::string& name, std::string& value
) const {
// For the moment, deactivated under Windows
#ifdef WIN32
return false ;
#else
char* result = ::getenv(name.c_str()) ;
if(result != nil) {
value = std::string(result) ;
}
return (result != nil) ;
#endif
}
//__________________________________________________________________
}
| [
"[email protected]"
] | [
[
[
1,
224
]
]
] |
f9500190f9c7a0a31dc7926598f23f63232d336b | 9c2a6fd19d8d1fede218b99749fc48d5123b248a | /3rdParty/Htmlayout/api/htmlayout_behavior.hpp | f4c0f6e2373610f2c6c77b7506ace9c00175d4a0 | [] | no_license | ans-ashkan/expemerent | 0f6bed7e630301f63e71992e3fbad70a0075082a | 054c33f55408d1274c50a2d6eb4cbc5295c92739 | refs/heads/master | 2021-01-15T22:15:18.929759 | 2008-12-21T00:40:52 | 2008-12-21T00:40:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,151 | hpp | /*
* Terra Informatica Lightweight Embeddable HTMLayout control
* http://terrainformatica.com/htmlayout
*
* Behaviors support (a.k.a windowless controls)
*
* The code and information provided "as-is" without
* warranty of any kind, either expressed or implied.
*
*
* (C) 2003-2005, Andrew Fedoniouk ([email protected])
*/
#ifndef __htmlayout_behavior_hpp__
#define __htmlayout_behavior_hpp__
#pragma warning(disable:4786) //identifier was truncated...
#pragma warning(disable:4996) //'strcpy' was declared deprecated
#pragma warning(disable:4100) //unreferenced formal parameter
/*!\file
\brief Behaiviors support (a.k.a windowless controls), C++ wrapper
*/
#include <windows.h>
#include <assert.h>
#include "htmlayout.h"
#include "htmlayout_behavior.h"
#if defined(_MSC_VER) && (_MSC_VER / 100) == 13 // appears as really bad number indeed
#define BRAINS_OFF #pragma optimize( "", off )
#define BRAINS_ON #pragma optimize( "", on )
#else
#define BRAINS_OFF
#define BRAINS_ON
#endif
namespace htmlayout
{
// event handler which can be attached to any DOM element.
// event handler can be attached to the element as a "behavior" (see below)
// or by htmlayout::dom::element::attach( event_handler* eh )
struct event_handler
{
event_handler(UINT subsriptions) // EVENT_GROUPS flags
:subscribed_to(subsriptions)
{
}
virtual ~event_handler() {}
virtual void detached (HELEMENT /*he*/ ) { }
virtual void attached (HELEMENT /*he*/ ) { }
virtual event_handler* attach (HELEMENT /*he*/ ) { return this; }
// handlers with extended interface
// by default they are calling old set of handlers (for compatibility with legacy code)
virtual BOOL handle_mouse (HELEMENT he, MOUSE_PARAMS& params )
{
return on_mouse( he, params.target, params.cmd, params.pos, params.button_state, params.alt_state );
}
virtual BOOL handle_key (HELEMENT he, KEY_PARAMS& params )
{
return on_key( he, params.target, params.cmd, params.key_code, params.alt_state );
}
virtual BOOL handle_focus (HELEMENT he, FOCUS_PARAMS& params )
{
return on_focus( he, params.target, params.cmd );
}
virtual BOOL handle_timer (HELEMENT he,TIMER_PARAMS& params )
{
if(params.timerId)
return on_timer( he, params.timerId );
return on_timer( he );
}
virtual void handle_size (HELEMENT he )
{
on_size( he );
}
virtual BOOL handle_scroll (HELEMENT he, SCROLL_PARAMS& params )
{
return on_scroll( he, params.target, (SCROLL_EVENTS)params.cmd, params.pos, params.vertical );
}
virtual BOOL handle_draw (HELEMENT he, DRAW_PARAMS& params )
{
return on_draw(he, params.cmd, params.hdc, params.area );
}
virtual BOOL handle_method_call (HELEMENT he, METHOD_PARAMS& params )
{
return on_method_call(he, params.methodID, ¶ms );
}
// handle CSSS! script calls
virtual BOOL handle_script_call (HELEMENT he, XCALL_PARAMS& params )
{
return on_script_call(he, params.method_name, params.argc, params.argv, params.retval );
}
// notification events from builtin behaviors - synthesized events: BUTTON_CLICK, VALUE_CHANGED
// see enum BEHAVIOR_EVENTS
virtual BOOL handle_event (HELEMENT he, BEHAVIOR_EVENT_PARAMS& params )
{
return on_event(he, params.heTarget, (BEHAVIOR_EVENTS)params.cmd, params.reason );
}
// notification event: data requested by HTMLayoutRequestData just delivered
virtual BOOL handle_data_arrived (HELEMENT he, DATA_ARRIVED_PARAMS& params )
{
return on_data_arrived(he, params.initiator, params.data, params.dataSize, params.dataType );
}
//
// alternative set of event handlers (aka old set).
//
virtual BOOL on_mouse (HELEMENT he, HELEMENT target, UINT event_type, POINT pt, UINT mouseButtons, UINT keyboardStates ) { return FALSE; }
virtual BOOL on_key (HELEMENT he, HELEMENT target, UINT event_type, UINT code, UINT keyboardStates ) { return FALSE; }
virtual BOOL on_focus (HELEMENT he, HELEMENT target, UINT event_type ) { return FALSE; }
virtual BOOL on_timer (HELEMENT he ) { return FALSE; /*stop this timer*/ }
virtual BOOL on_timer (HELEMENT he, UINT_PTR extTimerId ) { return FALSE; /*stop this timer*/ }
virtual BOOL on_draw (HELEMENT he, UINT draw_type, HDC hdc, const RECT& rc ) { return FALSE; /*do default draw*/ }
virtual void on_size (HELEMENT he ) { }
virtual BOOL on_method_call (HELEMENT he, UINT methodID, METHOD_PARAMS* params ) { return FALSE; /*not handled*/ }
// calls from CSSS! script. Override this if you want your own methods to the CSSS! namespace.
// Follwing declaration:
// #my-active-on {
// when-click: r = self.my-method(1,"one");
// }
// will end up with on_script_call(he, "my-method" , 2, argv, retval );
// where argv[0] will be 1 and argv[1] will be "one".
virtual BOOL on_script_call(HELEMENT he, LPCSTR name, UINT argc, json::value* argv, json::value& retval) { return FALSE; }
// notification events from builtin behaviors - synthesized events: BUTTON_CLICK, VALUE_CHANGED
// see enum BEHAVIOR_EVENTS
virtual BOOL on_event (HELEMENT he, HELEMENT target, BEHAVIOR_EVENTS type, UINT_PTR reason ) { return FALSE; }
// notification event: data requested by HTMLayoutRequestData just delivered
virtual BOOL on_data_arrived (HELEMENT he, HELEMENT initiator, LPCBYTE data, UINT dataSize, UINT dataType ) { return FALSE; }
virtual BOOL on_scroll( HELEMENT he, HELEMENT target, SCROLL_EVENTS cmd, INT pos, BOOL isVertical ) { return FALSE; }
// ElementWventProc implementeation
static BOOL CALLBACK element_proc(LPVOID tag, HELEMENT he, UINT evtg, LPVOID prms )
{
event_handler* pThis = static_cast<event_handler*>(tag);
if( pThis ) switch( evtg )
{
case HANDLE_INITIALIZATION:
{
INITIALIZATION_PARAMS *p = (INITIALIZATION_PARAMS *)prms;
if(p->cmd == BEHAVIOR_DETACH)
pThis->detached(he);
else if(p->cmd == BEHAVIOR_ATTACH)
pThis->attached(he);
return TRUE;
}
case HANDLE_MOUSE: { MOUSE_PARAMS *p = (MOUSE_PARAMS *)prms; return pThis->handle_mouse( he, *p ); }
case HANDLE_KEY: { KEY_PARAMS *p = (KEY_PARAMS *)prms; return pThis->handle_key( he, *p ); }
case HANDLE_FOCUS: { FOCUS_PARAMS *p = (FOCUS_PARAMS *)prms; return pThis->handle_focus( he, *p ); }
case HANDLE_DRAW: { DRAW_PARAMS *p = (DRAW_PARAMS *)prms; return pThis->handle_draw(he, *p ); }
case HANDLE_TIMER: { TIMER_PARAMS *p = (TIMER_PARAMS *)prms; return pThis->handle_timer(he, *p); }
case HANDLE_BEHAVIOR_EVENT: { BEHAVIOR_EVENT_PARAMS *p = (BEHAVIOR_EVENT_PARAMS *)prms; return pThis->handle_event(he, *p ); }
case HANDLE_METHOD_CALL:
{
METHOD_PARAMS *p = (METHOD_PARAMS *)prms;
if(p->methodID == XCALL)
{
XCALL_PARAMS *xp = (XCALL_PARAMS *)p;
return pThis->handle_script_call(he,*xp);
}
else
return pThis->handle_method_call(he, *p );
}
case HANDLE_DATA_ARRIVED: { DATA_ARRIVED_PARAMS *p = (DATA_ARRIVED_PARAMS *)prms; return pThis->handle_data_arrived(he, *p ); }
case HANDLE_SIZE: { pThis->handle_size(he); return FALSE; }
case HANDLE_SCROLL: { SCROLL_PARAMS *p = (SCROLL_PARAMS *)prms; return pThis->handle_scroll(he, *p ); }
default:
assert(false);
}
return FALSE;
}
UINT subscribed_to;
};
// "manually" attach event_handler proc to the DOM element
inline void attach_event_handler(HELEMENT he, event_handler* p_event_handler, UINT subscription = HANDLE_ALL )
{
HTMLayoutAttachEventHandlerEx(he, &event_handler::element_proc, p_event_handler, subscription);
}
inline void detach_event_handler(HELEMENT he, event_handler* p_event_handler )
{
HTMLayoutDetachEventHandler(he, &event_handler::element_proc, p_event_handler);
}
// "manually" attach event_handler proc to the window
inline void attach_event_handler(HWND hwndLayout, event_handler* p_event_handler, UINT subscription = HANDLE_ALL )
{
HTMLayoutWindowAttachEventHandler(hwndLayout, &event_handler::element_proc, p_event_handler, subscription);
}
inline void detach_event_handler(HWND hwndLayout, event_handler* p_event_handler )
{
HTMLayoutWindowDetachEventHandler(hwndLayout, &event_handler::element_proc, p_event_handler);
}
//
// "behavior" is a named event_handler
// behaviors organized into one global list to be processed
// automaticly while handling HLN_ATTACH_BEHAVIOR notification
//
#if defined(CUSTOM_BEHAVIOR_IMPL)
#include "behavior_impl.hpp" // provide your own implementation with ctor and handle() method as defined below
#else // standard behavior implementation
#if defined(_MSC_VER) && (_MSC_VER / 100) == 13
#pragma optimize( "", off )
#endif
struct behavior: event_handler
{
behavior(UINT subsriptions, const char* external_name)
:next(0),name(external_name), event_handler(subsriptions)
{
// add this implementation to the list (singleton)
next = root();
root(this);
}
// behavior list support
behavior* next;
const char* name; // name must be a pointer to a static string
// returns behavior implementation by name.
static event_handler* find(const char* name, HELEMENT he)
{
for(behavior* t = root(); t; t = t->next)
if(strcmp(t->name,name)==0)
{
return t->attach(he);
}
return 0; // not found
}
// implementation of static list of behaviors
static behavior* root(behavior* to_set = 0)
{
static behavior* _root = 0;
if(to_set) _root = to_set;
return _root;
}
// standard implementation of HLN_ATTACH_BEHAVIOR notification
static bool handle( LPNMHL_ATTACH_BEHAVIOR lpab )
{
htmlayout::event_handler *pb = htmlayout::behavior::find(lpab->behaviorName, lpab->element);
if(pb)
{
lpab->elementTag = pb;
lpab->elementProc = htmlayout::event_handler::element_proc;
lpab->elementEvents = pb->subscribed_to;
return true;
}
return false;
}
};
#if defined(_MSC_VER) && (_MSC_VER / 100) == 13
#pragma optimize( "", on )
#endif
#endif // standard behavior implementation
} //namespace htmlayout
#endif
| [
"userstvo@9d5f44c3-c14b-0410-8269-bdf5c58671da"
] | [
[
[
1,
292
]
]
] |
76cbe860fe18f7c0c80980847a9d81f043cfb4dd | 5dc1b23d97bc52e52074c4224d2df8a0b285aa72 | /Tetris/stdafx.cpp | 52972dc007033a6b7d7e026cda172ef60bd71e6f | [] | no_license | chanpi/Tetris | aaa014f7ee4fce3ce4540288d64e31dccc8a40b6 | 10668e5c4cc16ffa18d90a83840c74d7b64cc199 | refs/heads/master | 2016-08-03T07:38:12.024265 | 2011-04-19T23:51:08 | 2011-04-19T23:51:08 | 1,638,074 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 381 | cpp | // stdafx.cpp : 標準インクルード Tetris.pch のみを
// 含むソース ファイルは、プリコンパイル済みヘッダーになります。
// stdafx.obj にはプリコンパイル済み型情報が含まれます。
#include "stdafx.h"
// TODO: このファイルではなく、STDAFX.H で必要な
// 追加ヘッダーを参照してください。
| [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
571345415b54d65cb4dc2072636f30e2dc1f49d3 | a9cf0c2a8904e42a206c3575b244f8b0850dd7af | /gui/console/item.cpp | 7f2b8bed18304a9bde9ab0d561e00385f4b156f0 | [] | no_license | jayrulez/ourlib | 3a38751ccb6a38785d4df6f508daeff35ccfd09f | e4727d638f2d69ea29114dc82b9687ea1fd17a2d | refs/heads/master | 2020-04-22T15:42:00.891099 | 2010-01-06T20:00:17 | 2010-01-06T20:00:17 | 40,554,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | cpp | /*
@Group: BSC2D
@Group Members:
<ul>
<li>Robert Campbell: 0701334</li>
<li>Audley Gordon: 0802218</li>
<li>Dale McFarlane: 0801042</li>
<li>Dyonne Duberry: 0802189</li>
<li>Xavier Lowe: 0802488</li>
</ul>
@
*/
#include <iostream>
#include "item.h"
#include "console.h"
#include <string>
using namespace std;
item::item()
{
x=0;
y=0;
code=0;
}
item::item(string nm,int x1, int y1,int c)
{
if(x1>=0 && y1>=0){
name=nm;
x=x1;
y=y1;
code=c;
}
else{
cout<<"Item construction failed!"<<endl;
}
}
item::~item()
{
}
bool item::setItem(int x1,int y1,int c,string nm)
{
if(x1>=0 && y1>=0){ //check criteria
x=x1;
y=y1;
name=nm;
code =c;
return true;
}
cout<<"setItem Failed!"<<endl;
return false;
}
int item::getItemX()
{
return x;
}
int item::getItemY()
{
return y;
}
int item::getItemLenght()
{
string str (name);
return str.length();
}
int item::getCode()
{
return code;
}
void item::born()
{
console_item.xyCoord(x,y);
cout<<name;
}
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
eda5765eea8e4ba949a0028fee42337bd0ccc0ec | e8d4d84a342ab711799c46f9e55713831f4b90fd | /logwidget.cpp | ab7e2aacccafb6600617c6246db450181279e093 | [] | no_license | estherloeliger/uicrawler | c092ea25599ac667dfef911f4e092ea93d6b05bf | abb8325cf973e893665fd6806010cd4cf1e9f7f6 | refs/heads/master | 2020-04-09T05:14:18.518875 | 2011-06-27T23:15:07 | 2011-06-27T23:15:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | cpp | #include "logwidget.h"
#include "data.h"
LogWidget::LogWidget(QWidget *parent, const QString &title, Data *dataP) :
QDockWidget(title, parent), data(dataP)
{
edit = new QTextEdit(this);
edit->document()->setMaximumBlockCount(4096);
this->setWidget(edit);
this->setMinimumWidth(512);
}
LogWidget::~LogWidget()
{
//tbd: check if edit deleted by parent
}
void LogWidget::push(const QString &s)
{
edit->append(s);
edit->ensureCursorVisible();
}
void LogWidget::clear()
{
edit->clear();
}
QString LogWidget::text()
{
return edit->toPlainText();
}
void LogWidget::setText(const QString &s)
{
edit->clear();
edit->setText(s);
}
| [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
0d3a381bc7d6d6d9c582d768fca5b1cebd740de1 | 135522f4ca53fda5a5f5eac5b79a3f5f8f2c089f | /EasyWar/Demo02.cpp | c03a54ef6f23722a35d7e7b1f3f264dec62c268d | [] | no_license | weimingtom/easywar | b0a006a59cc059131ba30c6aa8fd238643a201de | 5279851c0c23af51b2273b2076d05f44a50bc2c7 | refs/heads/master | 2021-01-09T21:58:26.257817 | 2009-12-13T02:52:06 | 2009-12-13T02:52:06 | 44,422,879 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 431 | cpp | #include "stdafx.h"
#include "Demo02.h"
int groupNum;
//初始化
void Demo02::Init( void* host )
{
groupNum = DRAW.AddSpriteGroup( 1 );
DRAW.AddSprite( groupNum, 0, "bg2.png" );
int bgmID = SND.LoadBGM("close.wav");
SND.PlayBGM( bgmID, 0 );
}
//每帧运行
void Demo02::Run( void* host, unsigned int time )
{
DRAW.Draw( groupNum, 0, 0, 0 );
}
//结束
void Demo02::End( void* host )
{
;
}
| [
"xujia1985@d64887d6-d1e9-11de-a205-5990a31c5447"
] | [
[
[
1,
27
]
]
] |
883cc671ae518e5cac0f45290a3be49eadfce56e | 89d2197ed4531892f005d7ee3804774202b1cb8d | /Game/IBaseGameState.h | a36cbbf3df3d12edd34205af3b88c9987d555a5a | [
"MIT",
"Zlib"
] | permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,263 | h | //////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010 Harry Pidcock
//
// 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 __IBASEGAMESTATE_H__
#define __IBASEGAMESTATE_H__
class CBaseHandle;
class CKeyValues;
class IBaseGameState : public Gwen::Event::Handler
{
public:
virtual ~IBaseGameState(void) { };
virtual void Initilise(void) = 0;
virtual void Open(IBaseGameState *previous, const CKeyValues &keyValues) = 0;
virtual void Close(IBaseGameState *next) = 0;
virtual void PreThink(void) = 0;
virtual void Think(void) = 0;
virtual void PostThink(void) = 0;
virtual void PreDraw(void) = 0;
virtual Color GetBackgroundColor(void) = 0;
virtual void DrawBackground(int plane) = 0; // 0 is directly behind the foreground.
virtual void DrawForeground(void) = 0;
virtual void PostDraw(void) = 0;
virtual void OnCollide(CEntityHandle &a, CEntityHandle &b) = 0;
virtual void OnKeyEvent(const sf::Event &e) = 0;
virtual void OnMouseEvent(const sf::Event &e) = 0;
};
#endif // __IBASEGAMESTATE_H__ | [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
] | [
[
[
1,
55
]
]
] |
5713662948bcd0e88a1d237d67fa6dfc27dfb6aa | 7ce4c7148cf7f4d02c219eb9182a3bc93eb90f99 | /starv/EnvironmentEditor/AssemblyInfo.cpp | acf2ed465c5d1e600834b6fc1260704da7003c08 | [] | no_license | Aresinho/starv | 8ad017a10ee34359ab761ca22dc5add61eb199e8 | ba141ef527b7dc373bf069a4721196dc4eb6a8be | refs/heads/master | 2016-09-05T19:16:08.365707 | 2007-10-09T04:03:36 | 2007-10-09T04:03:36 | 33,396,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("EnvironmentEditior")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("EnvironmentEditior")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2007")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"[email protected]@41142a6e-483b-0410-9a39-79d5471c0866"
] | [
[
[
1,
40
]
]
] |
0992bc795c96192d02e38655dd74f2367f6219c6 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/gpsdisplay/gpsdisplaywidget.h | d6160883561d75b0f73649d4a11b6fe062920b9f | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | h | /**
******************************************************************************
*
* @file gpsdisplaywidget.h
* @author Edouard Lafargue Copyright (C) 2010.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup GPSGadgetPlugin GPS Gadget Plugin
* @{
* @brief A gadget that displays GPS status and enables basic configuration
*****************************************************************************/
/*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef GPSDISPLAYWIDGET_H_
#define GPSDISPLAYWIDGET_H_
#include "ui_gpsdisplaywidget.h"
#include "gpsdisplaygadgetconfiguration.h"
#include "gpsconstellationwidget.h"
#include "uavobjects/uavobject.h"
#include <QGraphicsView>
#include <QtSvg/QSvgRenderer>
#include <QtSvg/QGraphicsSvgItem>
class Ui_GpsDisplayWidget;
class GpsDisplayWidget : public QWidget, public Ui_GpsDisplayWidget
{
Q_OBJECT
public:
GpsDisplayWidget(QWidget *parent = 0);
~GpsDisplayWidget();
private slots:
void setSVs(int);
void setPosition(double, double, double);
void setDateTime(double, double);
void setSpeedHeading(double, double);
void dumpPacket(const QString &packet);
void setFixType(const QString &fixtype);
void setDOP(double hdop, double vdop, double pdop);
private:
GpsConstellationWidget * gpsConstellation;
QGraphicsSvgItem * marker;
};
#endif /* GPSDISPLAYWIDGET_H_ */
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
62
]
]
] |
11b7180a3c7e74a62e7c1e2ddd4aa9c1297b1ba7 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /PaperSizeScroll/_snip_pieces/xsl-fo_open/srcm/struct/pics_structure.h | af96bd5cca97ae83d8d860fabee87790846b757d | [] | no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,080 | h | /*******************************************************************************
* class SPics
*******************************************************************************
* Copyright (C) 2007 by Peter Hohl
* e-Mail: [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*******************************************************************************/
/* pic structure and flash structure in qtextdocument */
#ifndef PICS_STRUCTURE_H
#define PICS_STRUCTURE_H
#include <QtGui>
#include <QtCore>
#include <QPixmap>
#include <QSvgRenderer>
#include <QTextDocumentFragment>
#include <QTextCharFormat>
#include <QAbstractTextDocumentLayout> // for QTextObjectInterface
#include <QDomDocument>
#include "Basic_Config.h"
#include "Fop_Leader_Element.h"
#define FOPIMAGEDIR "Pictures/"
static const int ObjectName = 853;
static const int FlashReferenceID = 322;
#define _LINK_COLOR_ \
QColor("#dc0000")
#define _DEFAULT_TXT_COLOR_ \
QColor("#000088") /* cursor color palette from text now is cursor color */
#define _DOCUMENT_TXT_COLOR_ \
QColor("#717171") /* real txt palette */
static inline QIcon createColorIcon( QColor color )
{
QPixmap pixmap(50, 50);
pixmap.fill(color);
return QIcon(pixmap);
}
/* contains link on block */
static inline bool HavingLink( const QTextBlock para )
{
QTextBlock::iterator li;
for (li = para.begin(); !(li.atEnd()); ++li) {
QTextFragment lifrag = li.fragment();
if (lifrag.isValid()) {
const QTextCharFormat format = lifrag.charFormat();
if (format.isAnchor()) {
return true;
}
}
}
return false;
}
static inline QPixmap TestImage( QString txt )
{
QPixmap pError = QPixmap(500, 300 );
pError.fill( Qt::red );
QPainter pter( &pError );
pter.setFont( QFont( "Helvetica", 8 ) );
pter.setBrush( Qt::green );
pter.drawText( 5, 12 , txt );
return pError;
}
static inline QTextBlockFormat default_block_style( QTextBlockFormat pf = QTextBlockFormat() )
{
/* i not find on qt to remove default 12point default space !!! */
pf.setBottomMargin(0);
pf.setTopMargin(0);
pf.setRightMargin(0);
pf.setIndent(0);
pf.setLeftMargin(0);
pf.setProperty(FlashReferenceID,0);
pf.setProperty(ObjectName,0);
return pf;
}
static inline QTextCharFormat default_char_style( QTextCharFormat pf = QTextCharFormat() )
{
QFont font = QApplication::font();
font.setPointSize(10);
pf.setFont ( font );
pf.setProperty(FlashReferenceID,0);
pf.setProperty(ObjectName,0);
pf.setVerticalAlignment ( QTextCharFormat::AlignTop );
return pf;
}
static inline QRectF M_PagesizeMake( QPrinter::PageSize psize , bool landscape = true )
{
QPrinter *print = new QPrinter(QPrinter::HighResolution);
print->setFullPage(true);
print->setPageSize(psize);
if (landscape) {
print->setOrientation(QPrinter::Landscape);
} else {
print->setOrientation(QPrinter::Portrait);
}
QRectF pagere = print->pageRect ( QPrinter::Point );
delete print;
return pagere;
}
class M_PageSize
{
public:
enum { MAGICNUMBER = 0xFFAAFFAA, VERSION = 2 };
M_PageSize() {
landscape = false;
name = "A4 (210 x 297 mm, 8.26 x 11.7 inches)";
P_rect = QPrinter::A4;
G_regt = M_PagesizeMake(P_rect,landscape);
const qreal mr = FopInt("1cm");
P_margin = QRectF(mr,mr,mr,mr);
}
M_PageSize& operator=( const M_PageSize& d )
{
name = d.name;
landscape = d.landscape;
G_regt = d.G_regt;
P_rect = d.P_rect;
P_margin = d.P_margin;
return *this;
}
operator QVariant() const {
return QVariant::fromValue(*this);
}
QString HName()
{
QString sep(" /");
QString reg = name;
if (landscape) {
reg.append(sep+QT_TR_NOOP("Landscape"));
} else {
reg.append(sep+QT_TR_NOOP("Portrait"));
}
return reg;
}
qreal faktor()
{
return qMax(G_regt.width(),G_regt.height()) / qMin(G_regt.width(),G_regt.height());
}
void Register( QString n , QPrinter::PageSize pp , bool La )
{
G_regt = M_PagesizeMake(P_rect,La);
//////qDebug() << "### Register page name." << n << " G_regt ->" << G_regt;
name = n;
landscape = La;
P_rect = pp;
}
void SetMargin( QRectF rectp )
{
P_margin = rectp;
}
/* edit modus */
qreal HandleDocument( QTextDocument *doc )
{
const qreal RightMargin = P_margin.y();
const qreal LeftMargin = P_margin.height();
const qreal LargeDoc = G_regt.width() - RightMargin - LeftMargin;
///////.toSize()
doc->setPageSize ( G_regt.size() );
////////////doc->setTextWidth ( G_regt.width() * 1.5 );
QTextFrame *Tframe = doc->rootFrame();
QTextFrameFormat Ftf = Tframe->frameFormat();
//////Ftf.setLeftMargin(P_margin.height());
//////Ftf.setBottomMargin(P_margin.width());
//////Ftf.setTopMargin(P_margin.x());
///////Ftf.setRightMargin(P_margin.y());
///////Ftf.setPadding ( 0);
Ftf.setLeftMargin(0);
Ftf.setBottomMargin(0);
Ftf.setTopMargin(0);
Ftf.setRightMargin(0);
Ftf.setPadding (0);
Ftf.setWidth ( G_regt.width() * 1.5 );
Tframe->setFrameFormat(Ftf);
doc->adjustSize();
return LargeDoc;
}
qreal HandlePrint( QTextDocument *doc )
{
const qreal RightMargin = P_margin.y();
const qreal LeftMargin = P_margin.height();
const qreal LargeDoc = G_regt.width() - RightMargin - LeftMargin;
///////.toSize()
doc->setPageSize ( G_regt.size() );
//////doc->setTextWidth ( G_regt.width() * 1.5 );
QTextFrame *Tframe = doc->rootFrame();
QTextFrameFormat Ftf = Tframe->frameFormat();
Ftf.setLeftMargin(P_margin.height());
Ftf.setBottomMargin(P_margin.width());
Ftf.setTopMargin(P_margin.x());
Ftf.setRightMargin(P_margin.y());
Ftf.setPadding ( 0);
Tframe->setFrameFormat(Ftf);
return LargeDoc;
}
void ReportPage( QDomElement e )
{
const qreal TopMargin = Pointo(P_margin.x(),"mm");
const qreal RightMargin = Pointo(P_margin.y(),"mm");
const qreal BottomMargin = Pointo(P_margin.width(),"mm");
const qreal LeftMargin = Pointo(P_margin.height(),"mm");
e.setAttribute ("margin-top",QString("%1mm").arg(TopMargin));
e.setAttribute ("margin-bottom",QString("%1mm").arg(BottomMargin));
e.setAttribute ("margin-left",QString("%1mm").arg(LeftMargin));
e.setAttribute ("margin-right",QString("%1mm").arg(RightMargin));
e.setAttribute ("page-width",QString("%1mm").arg(Pointo(G_regt.width(),"mm")));
e.setAttribute ("page-height",QString("%1mm").arg(Pointo(G_regt.height(),"mm")));
}
///////// MarginPage = QRectF(xTopMargin,xRightMargin,xBottomMargin,xLeftMargin);
QPrinter::PageSize P_rect;
QRectF G_regt;
QRectF P_margin;
QString name;
bool landscape;
};
Q_DECLARE_METATYPE(M_PageSize);
class SPics
{
public:
enum { MAGICNUMBER = 0xFFAAFFAA, VERSION = 1 };
SPics() {
name = "error";
info = "Image Description to blind people";
extension = QByteArray("PNG");
}
QString MimeHard() const
{
if (extension == "PNG") {
return QString("image/png");
} else if (extension == "APNG") {
return QString("image/png");
} else if (extension == "JPG") {
return QString("image/jpg");
} else {
return QString("text/plain");
}
}
SPics& operator=( const SPics& d )
{
name = d.name;
info = d.info;
extension = d.extension;
data = d.data;
return *this;
}
bool operator!=( const SPics& d )
{
if (name != d.name ) {
return false;
} else {
return true;
}
}
operator QVariant() const {
return QVariant::fromValue(*this);
}
QPixmap erno_pix() {
QPixmap pError = QPixmap(20, 20 );
pError.fill( Qt::red );
QPainter pter( &pError );
pter.setFont( QFont( "Helvetica", 8 ) );
pter.setBrush( Qt::green );
pter.drawText( 5, 12 , "0" );
return pError;
}
QString web()
{
QString flusches;
if (data.size() < 1) {
return flusches;
}
QByteArray daunq = qUncompress( data );
return daunq.toBase64();
}
bool FopSaveImage( QDomElement e )
{
const QString dirref = QString("./%1%2").arg(FOPIMAGEDIR).arg(FileName());
e.setAttribute ("src",dirref); /* current path from export now! */
QFileInfo gosave(dirref);
Cache( gosave.absolutePath() );
QFile f( gosave.absoluteFilePath() );
if ( f.open( QIODevice::WriteOnly ) )
{
f.write ( qUncompress( data ) );
f.close();
return true;
}
return false;
}
QPixmap pix() {
if (data.size() < 1) {
return erno_pix();
}
QPixmap resultimage;
QByteArray daunq = qUncompress( data );
resultimage.loadFromData( daunq );
if (resultimage.isNull()) {
return erno_pix();
}
return resultimage;
}
QString FileName()
{
return Imagename(name) + "." + QString(extension.data()).toLower();
}
void SavePixThread( QString dir = QString() )
{
QString fullpath = dir + FileName();
QDir dira(dir);
if ( !dira.mkpath(dir) ) {
return;
}
QFile f( fullpath );
if ( f.open( QIODevice::WriteOnly ) )
{
f.write ( qUncompress( data ) );
f.close();
}
}
void set_pics( const QPixmap * barcode )
{
if (barcode->isNull()) {
return;
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
barcode->save(&buffer,extension.data());
data = qCompress(bytes,9);
}
void set_pics( QPixmap barcode )
{
if (barcode.isNull()) {
return;
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
barcode.save(&buffer,extension.data());
data = qCompress(bytes,9);
}
void set_pics( const QByteArray chunk )
{
data = qCompress(chunk,9);
}
QByteArray streams()
{
return qUncompress( data );
}
int picskilo() {
return data.size();
}
QUrl indoc()
{
const int grep = name.size() - name.indexOf(".");
QString webname = name.left(grep);
return QUrl(QString("./%1.%2").arg(name).arg(QString(extension.data()).toLower()));
}
/* vars permanent */
QString name;
QString info;
QByteArray extension;
QByteArray data; /* qCompress */
};
Q_DECLARE_METATYPE(SPics);
inline QDebug operator<<(QDebug debug, SPics& udoc)
{
debug.nospace() << "SPics(name."
<< udoc.name << ","
<< udoc.info << ",size()"
<< udoc.data.size() << ",type()"
<< udoc.extension << ")";
return debug.space();
}
inline QDataStream& operator<<(QDataStream& out, const SPics& udoc)
{
out << udoc.name;
out << udoc.info;
out << udoc.extension;
out << udoc.data;
return out;
}
inline QDataStream& operator>>(QDataStream& in, SPics& udoc)
{
in >> udoc.name;
in >> udoc.info;
in >> udoc.extension;
in >> udoc.data;
return in;
}
inline QString SaveImageGroup( QList<SPics> li )
{
if (li.size() < 1) {
return QString();
}
QByteArray bytes;
QBuffer buffer(&bytes);
if (!buffer.open(QIODevice::WriteOnly)) {
return QString();
}
QDataStream ds(&buffer);
/* place header */
ds.setVersion(QDataStream::Qt_4_2);
ds << (quint32)SPics::MAGICNUMBER;
ds << (quint32)SPics::VERSION;
/* place header */
///////QApplication::setOverrideCursor(Qt::WaitCursor);
for (int i=0; i<li.size(); i++) {
SPics conni = li[i];
ds << conni;
}
//////QApplication::restoreOverrideCursor();
buffer.close();
return bytes.toBase64();
}
/* decoded base64 stream to put on mysql row , file or network streams */
inline QList<SPics> OpenImageGroup( const QString datastream_base64 )
{
QList<SPics> li;
QByteArray xcode("");
xcode.append(datastream_base64);
quint32 magic, version;
QByteArray bytes(QByteArray::fromBase64(xcode)); /* decoded base64 string to QByteArray */
QBuffer buffer(&bytes);
if (!buffer.open(QIODevice::ReadOnly)) {
return li;
}
QDataStream ds(&buffer);
/* place header */
ds.setVersion(QDataStream::Qt_4_2);
ds >> magic;
if ( (quint32)SPics::MAGICNUMBER != magic ) {
qDebug() << "######## SPics::MAGICNUMBER not ok ";
buffer.close();
return li;
}
ds >> version;
if ( (quint32)SPics::VERSION != version ) {
qDebug() << "######## SPics::VERSION not ok ";
buffer.close();
return li;
}
SPics appoint;
/* place header */
while (!ds.atEnd()) {
ds >> appoint;
li.append(appoint);
}
buffer.close();
return li;
}
static inline QPixmap RenderPixmapFromSvgByte( QByteArray streams )
{
QSvgRenderer svgRenderer( streams );
QPixmap pix( svgRenderer.defaultSize() );
pix.fill(Qt::transparent);
QPainter paint(&pix);
svgRenderer.render(&paint);
return pix;
}
static inline QPixmap RenderPixmapFromSvgByte( const QString & filename )
{
QSvgRenderer svgRenderer;
if ( svgRenderer.load(filename)) {
QPixmap pix( svgRenderer.defaultSize() );
pix.fill(Qt::transparent);
QPainter paint(&pix);
svgRenderer.render(&paint);
return pix;
} else {
SPics xx;
return xx.erno_pix();
}
}
#endif // PICS_STRUCTURE_H
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
] | [
[
[
1,
556
]
]
] |
c8c1e014cb00afaefa22ae32408c8440f1ee93f7 | 521721c2e095daf757ad62a267b1c0f724561935 | /bsPixelShader.h | a4b46e73b015c83074f4a55b13998ca3a79c01da | [] | no_license | MichaelSPG/boms | 251922d78f2db85ece495e067bd56a1e9fae14b1 | 23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4 | refs/heads/master | 2021-01-10T16:23:51.722062 | 2011-12-08T00:04:33 | 2011-12-08T00:04:33 | 48,052,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | h | #pragma once
#include <d3d11.h>
struct ID3D11PixelShader;
/* Contains a single pixel shader.
Use bsShaderManager to create shaders.
*/
class bsPixelShader
{
friend class bsShaderManager;
public:
bsPixelShader(ID3D11PixelShader* pixelShader, unsigned int id)
: mPixelShader(pixelShader)
, mID(id)
{
}
~bsPixelShader()
{
mPixelShader->Release();
}
inline ID3D11PixelShader* getD3dPixelShader() const
{
return mPixelShader;
}
private:
//Not copyable
bsPixelShader(const bsPixelShader&);
void operator=(const bsPixelShader&);
ID3D11PixelShader* mPixelShader;
unsigned int mID;
};
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
2e6f8f278094d460b9a640fa78b98b31f18d7b8a | 699746171f662df8923b8894e5178126285beb2d | /Software/C++/applis/tablette-cpp/caveOsgViewer/stdafx.h | 23a28a9178b8d2004c4ddfef6c5cfba498cd0325 | [] | no_license | iurnah/tesis | 4793b539bec676255e0f880dc6524b1e70b78394 | 652d6096e53a56123408d325921981b0ff6c39fd | refs/heads/master | 2021-01-24T19:51:48.438405 | 2011-06-27T11:44:23 | 2011-06-27T11:44:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define WIN32_LEAN_AND_MEAN
#include "targetver.h"
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <osgGA/TrackballManipulator>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/Light>
#include <osg/Material>
#include <osg/Group>
#include <osg/ShapeDrawable>
#include <osgviewer/viewer>
#include <osg/Camera>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
// TODO: reference additional headers your program requires here
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
2c442ce38dcccfb0d13956643a7a9c79be8e64ef | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/LevelViewer.h | 65c862d577c6463aed2142422fc0e4f20e313c2d | [] | 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 | 1,109 | h | /***
* hesperus: LevelViewer.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_LEVELVIEWER
#define H_HESP_LEVELVIEWER
#include <source/gui/GUIComponent.h>
#include "Level.h"
namespace hesp {
//#################### FORWARD DECLARATIONS ####################
typedef shared_ptr<class Camera> Camera_Ptr;
class LevelViewer : public GUIComponent
{
//#################### TYPEDEFS ####################
private:
typedef std::vector<Portal_Ptr> PortalVector;
//#################### PRIVATE VARIABLES ####################
private:
Level_Ptr m_level;
Camera_Ptr m_camera;
//#################### CONSTRUCTORS ####################
public:
LevelViewer(const Level_Ptr& level, const Camera_Ptr& camera);
//#################### PUBLIC METHODS ####################
public:
void render() const;
//#################### PRIVATE METHODS ####################
private:
void render_level() const;
void render_navlinks() const;
void render_navmeshes() const;
void render_objects() const;
void render_portals() const;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
82a70be63d372f3370f2be09b41de722768de378 | 14bc620a0365e83444dad45611381c7f6bcd052b | /ITUEngine/Subsystems/Physics/PhysicsModels/PlayerInteraction.cpp | 481e22f751352bca7b0561b33ddff4f775cd5ac8 | [] | no_license | jumoel/itu-gameengine | a5750bfdf391ae64407217bfc1df8b2a3db551c7 | 062dd47bc1be0f39a0add8615e81361bcaa2bd4c | refs/heads/master | 2020-05-03T20:39:31.307460 | 2011-12-19T10:54:10 | 2011-12-19T10:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | cpp | #include <Subsystems/Physics/PhysicsModels/PlayerInteraction.hpp>
#include <Events/EventData/EventData.hpp>
#include <Events/Interfaces/IEventData.hpp>
#include <Math/GeometricFigures2D.hpp>
#include <memory>
void PlayerInteraction::StartUp(Object *playerObject)
{
this->player = playerObject;
safeAddListener(EventListenerPointer(this), EventType("mouseClickPositionEvent"));
}
void PlayerInteraction::ShutDown()
{
}
bool PlayerInteraction::HandleEvent(IEventData const & eventData)
{
shared_ptr<EventData<Vector3f>> data = dynamic_pointer_cast<EventData<Vector3f>, IEventData>(eventData.Copy());
Vector3f val = data->GetValue();
player->physicsModel->SetTargetPosition(new Point(val.x(), val.y()));
return true;
}
char const * PlayerInteraction::GetName( void )
{
return "PlayerInteraction";
} | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
31
]
],
[
[
32,
32
]
]
] |
0c73e28b5a5c0dc9ca7f9710c72df4f1e50d3195 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/uavobjects/objectpersistence.h | 1a8edb4da57fc76fecd1a5eb8899d15b8ca5f8a3 | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,960 | h | /**
******************************************************************************
*
* @file objectpersistence.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @see The GNU Public License (GPL) Version 3
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup UAVObjectsPlugin UAVObjects Plugin
* @{
*
* @note Object definition file: objectpersistence.xml.
* This is an automatically generated file.
* DO NOT modify manually.
*
* @brief The UAVUObjects GCS plugin
*****************************************************************************/
/*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef OBJECTPERSISTENCE_H
#define OBJECTPERSISTENCE_H
#include "uavdataobject.h"
#include "uavobjectmanager.h"
class UAVOBJECTS_EXPORT ObjectPersistence: public UAVDataObject
{
Q_OBJECT
public:
// Field structure
typedef struct {
quint8 Operation;
quint8 Selection;
quint32 ObjectID;
quint32 InstanceID;
} __attribute__((packed)) DataFields;
// Field information
// Field Operation information
/* Enumeration options for field Operation */
typedef enum { OPERATION_LOAD=0, OPERATION_SAVE=1, OPERATION_DELETE=2 } OperationOptions;
// Field Selection information
/* Enumeration options for field Selection */
typedef enum { SELECTION_SINGLEOBJECT=0, SELECTION_ALLSETTINGS=1, SELECTION_ALLMETAOBJECTS=2, SELECTION_ALLOBJECTS=3 } SelectionOptions;
// Field ObjectID information
// Field InstanceID information
// Constants
static const quint32 OBJID = 572614706U;
static const QString NAME;
static const bool ISSINGLEINST = 1;
static const bool ISSETTINGS = 0;
static const quint32 NUMBYTES = sizeof(DataFields);
// Functions
ObjectPersistence();
DataFields getData();
void setData(const DataFields& data);
Metadata getDefaultMetadata();
UAVDataObject* clone(quint32 instID);
static ObjectPersistence* GetInstance(UAVObjectManager* objMngr, quint32 instID = 0);
private:
DataFields data;
void setDefaultFieldValues();
};
#endif // OBJECTPERSISTENCE_H
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
88
]
]
] |
a375a5169010a2fc467a045c64ee318786b05a92 | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/EditFilterFrm.h | 90ab518430d7f470c9b58518d08322bd80e0b471 | [] | no_license | sridhar19091986/xmlconvertsql | 066344074e932e919a69b818d0038f3d612e6f17 | bbb5bbaecbb011420d701005e13efcd2265aa80e | refs/heads/master | 2021-01-21T17:45:45.658884 | 2011-05-30T12:53:29 | 2011-05-30T12:53:29 | 42,693,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,611 | h | //---------------------------------------------------------------------------
#ifndef EditFilterFrmH
#define EditFilterFrmH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "RzPanel.hpp"
#include <ExtCtrls.hpp>
#include "RzButton.hpp"
#include "RzCmboBx.hpp"
#include "RzEdit.hpp"
#include "RzSpnEdt.hpp"
#include <Mask.hpp>
#include "BillConfig.h"
//---------------------------------------------------------------------------
class TfrmEditFilter : public TForm
{
__published: // IDE-managed Components
TRzGroupBox *RzGroupBox1;
TRzBitBtn *btnOk;
TRzBitBtn *btnCancel;
TLabel *Label1;
TLabel *Label2;
TLabel *Label3;
TLabel *Label4;
TLabel *Label5;
TRzComboBox *cbxAction;
TRzSpinEdit *txtWidth;
TRzSpinEdit *txtPos;
TRzEdit *txtIs;
TRzEdit *txtLength;
TLabel *Label6;
TLabel *Label7;
TRzComboBox *cbxCause;
void __fastcall FormKeyPress(TObject *Sender, char &Key);
void __fastcall btnOkClick(TObject *Sender);
bool __fastcall FormHelp(WORD Command, int Data, bool &CallHelp);
private: // User declarations
RecordFilter * Filter;
int BillRecordLength;
public: // User declarations
__fastcall TfrmEditFilter(TComponent* Owner,RecordFilter * AFilter,int ABillRecordLength);
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmEditFilter *frmEditFilter;
//---------------------------------------------------------------------------
#endif
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
] | [
[
[
1,
50
]
]
] |
5715bfa786563b90689b4dfb0931280f7e994588 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /ytk_bak/BatDown/src/BatDown.cpp | 76c480019f3972e27e782b13ba3a97c095f32235 | [] | 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 | GB18030 | C++ | false | false | 8,349 | cpp | #include <QtGui>
#include "BatDown.h"
#include "SqliteDB.h"
#include "TabWidget.h"
#include "TabManager.h"
#include "FavoritesView.h"
#include "TreeNode.h"
#include "PostView.h"
#include "MusicView.h"
#include "ScriptDialog.h"
#include "md5.h"
#include "json.h"
#include "BatDownUtils.h"
BatDown::BatDown(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags){
initLogger();
m_dbMgr.open(("ytk.db"));
init();
readSettings();
}
BatDown::~BatDown(){
m_dbMgr.close();
}
void BatDown::init(){
createActions();
createMenus();
createContextMenu();
createToolBars();
createStatusBar();
createCentralArea();
}
void BatDown::closeEvent(QCloseEvent *event){
writeSettings();
event->accept();
}
void BatDown::analyseUrl(){
}
void BatDown::download(){
}
void BatDown::editScript()
{
if(0 == m_pFavoritesTree)return;
QModelIndex idx = m_pFavoritesTree->selectionModel()->currentIndex();
TreeNode *node = static_cast<TreeNode*>(idx.internalPointer());
QString scriptFilename = node->getScriptFilename();
ScriptDialog *editor = new ScriptDialog(scriptFilename, this);
editor->show();
}
void BatDown::about(){
}
void BatDown::testMd5(){
char *fn = "jquery.min.js";
QFile testFile(fn);
testFile.open( QIODevice::ReadOnly );
QByteArray ba = testFile.readAll();
const char *test = (const char *)ba;
md5_state_t state;
md5_byte_t digest[16];
char hex_output[16*2 + 1];
md5_init(&state);
md5_append(&state, (const md5_byte_t *)test, strlen(test));
md5_finish(&state, digest);
int di;
for(di = 0; di < 16; ++di)
sprintf(hex_output + di * 2, "%02x", digest[di]);
yDEBUG(hex_output);
}
void BatDown::testXml(){
/*
try
{
XMLPlatformUtils::Initialize();
XercesDOMParser *parser = new XercesDOMParser;
parser->setValidationScheme(false);
parser->setDoNamespaces(false);
parser->setDoSchema(false);
parser->setValidationSchemaFullChecking(false);
parser->setCreateEntityReferenceNodes(false);
} catch(...) {
XMLPlatformUtils::Terminate();
}
*/
}
void BatDown::testJson(){
char *fn = "script/2.json";
QFile testFile(fn);
if(!testFile.open(QIODevice::ReadOnly | QIODevice::Text) )
return;
QByteArray ba = testFile.readAll();
char* json = ba.data();
json_t* root = NULL;
json_t* item;
assert (JSON_OK == json_parse_document (&root, json));
assert (root->child);
item = json_find_first_label (root, "title");
QString ss = QString::fromLocal8Bit(item->child->text);
yDEBUG(ss.toLocal8Bit().data());
json_free_value (&item);
json_free_value (&root);
}
void BatDown::testPostView()
{
record_t t;
t.insert("cata","Fuck");
t.insert("title","Shit");
PostModel *m = static_cast<PostModel*>( m_pPostView->model() );
m->insertRecord(t, 1);
}
void BatDown::createActions(){
quitAct = new QAction(tr("&Quit"), this);
connect( quitAct,SIGNAL(triggered(bool)),
qApp, SLOT(quit()) );
aboutAct = new QAction(tr("&About"), this);
connect( aboutAct, SIGNAL(triggered(bool)),
this, SLOT(about()) );
analyseAct = new QAction(tr("Analyse Url"), this);
connect( analyseAct, SIGNAL(triggered(bool)),
this, SLOT(analyseUrl()) );
downloadAct = new QAction(tr("Download"), this);
connect( downloadAct, SIGNAL(triggered(bool)),
this, SLOT(download()) );
editScriptAct = new QAction(tr("Edit Script"), this);
connect( editScriptAct, SIGNAL(triggered(bool)),
this, SLOT(editScript()) );
}
void BatDown::createMenus(){
QMenuBar *mbar = menuBar();
fileMenu = mbar->addMenu(tr("&File"));
fileMenu->addAction(analyseAct);
fileMenu->addAction(downloadAct);
fileMenu->addAction(editScriptAct);
fileMenu->addSeparator();
fileMenu->addAction(quitAct);
helpMenu = mbar->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
}
void BatDown::createContextMenu(){
}
void BatDown::createToolBars(){
fileToolBar = addToolBar(tr("File"));
fileToolBar->addAction(analyseAct);
fileToolBar->addAction(downloadAct);
QToolBar *testToollBar = addToolBar("Test");
QAction *testMd5 = new QAction("Test MD5", this);
connect( testMd5, SIGNAL(triggered(bool)), this, SLOT(testMd5()) );
testToollBar->addAction(testMd5);
/*
QAction *testXml = new QAction("Test XML", this);
connect( testXml, SIGNAL(triggered(bool)), this, SLOT(testXml()) );
testToollBar->addAction(testXml);
*/
QAction *testJson = new QAction("Test JSON", this);
connect( testJson, SIGNAL(triggered(bool)), this, SLOT(testJson()) );
testToollBar->addAction(testJson);
QAction *testPost = new QAction("Test Post", this);
connect( testPost, SIGNAL(triggered(bool)), this, SLOT(testPostView()) );
testToollBar->addAction(testPost);
}
void BatDown::createStatusBar(){
m_pWebProgress = new QLabel;
statusBar()->addPermanentWidget(m_pWebProgress);
}
void BatDown::createCentralArea(){
m_pFavoritesTree = new FavoritesView(this);
m_pFavoritesTree->expandToDepth(0);
m_pMusicView = new MusicView(this);
m_pPostView = new PostView(this);
m_pWebTabWidget = new TabWidget(this);
TabManager::tabManager()->setTabWidget(m_pWebTabWidget);
TabManager::tabManager()->addTab();
m_pRightTopSplitter = new QSplitter(Qt::Horizontal);
m_pRightTopSplitter->addWidget(m_pMusicView);
m_pRightTopSplitter->addWidget(m_pPostView);
m_pRightButtomSplitter = new QSplitter(Qt::Horizontal);
m_pRightButtomSplitter->addWidget(logAppender);
m_pRightButtomSplitter->addWidget(m_pWebTabWidget);
m_pRightSplitter = new QSplitter(Qt::Vertical);
m_pRightSplitter->addWidget(m_pRightTopSplitter);
m_pRightSplitter->addWidget(m_pRightButtomSplitter);
m_pMainSplitter = new QSplitter(Qt::Horizontal);
m_pMainSplitter->addWidget(m_pFavoritesTree);
m_pMainSplitter->addWidget(m_pRightSplitter);
setCentralWidget(m_pMainSplitter);
}
void BatDown::readSettings(){
m_settings = BatDownUtils::readJsonFileToMap("BatDown.json");
QStringList ls;
ls = m_settings.value("main_splitter").split(",");
m_pMainSplitter->setSizes(BatDownUtils::stringListToIntList(ls));
ls = m_settings.value("r_splitter").split(",");
m_pRightSplitter->setSizes(BatDownUtils::stringListToIntList(ls));
ls = m_settings.value("r_t_splitter").split(",");
m_pRightTopSplitter->setSizes(BatDownUtils::stringListToIntList(ls));
ls = m_settings.value("r_b_splitter").split(",");
m_pRightButtomSplitter->setSizes(BatDownUtils::stringListToIntList(ls));
QStringList pos = m_settings.value("app_pos").split(",");
setGeometry(pos[0].toInt(), pos[1].toInt(), pos[2].toInt(), pos[3].toInt());
}
void BatDown::writeSettings(){
QRect rect = geometry();
QString pos = QString("%1,%2,%3,%4")
.arg(rect.x())
.arg(rect.y())
.arg(rect.width())
.arg(rect.height());
m_settings.insert("app_pos", pos);
m_settings.insert("r_t_splitter",
BatDownUtils::intListToStringList(m_pRightTopSplitter->sizes()).join(",") );
m_settings.insert("r_b_splitter",
BatDownUtils::intListToStringList(m_pRightButtomSplitter->sizes()).join(",") );
m_settings.insert("r_splitter",
BatDownUtils::intListToStringList(m_pRightSplitter->sizes()).join(",") );
m_settings.insert("main_splitter",
BatDownUtils::intListToStringList(m_pMainSplitter->sizes()).join(",") );
BatDownUtils::writeMapToJsonFile(m_settings, "BatDown.json");
}
void BatDown::initLogger(){
logAppender = new QTextEdit;
logAppender->setReadOnly(true);
logAppender->setWordWrapMode(QTextOption::NoWrap);
yewtic::appenders.insert(QString::fromUtf8("batdown_appender"), logAppender);
//LogLog::getLogLog()->setInternalDebugging(true);
//logger = Logger::getRoot();
try{
ConfigureAndWatchThread configureThread(LOG4CPLUS_TEXT("log4cplus.properties"), 3*1000);
yINFO("日志配置文件加载完毕。");
} catch(...) {
std::cout << "Exception..." << std::endl;
yERROR("Exception occured...");
}
}
SqliteDB& BatDown::getDbMgr()
{
return m_dbMgr;
}
QMap<QString, QString>& BatDown::getSettings()
{
return m_settings;
}
TabWidget* BatDown::getTabWidget()
{
return m_pWebTabWidget;
}
FavoritesView* BatDown::getFavoritesView()
{
return m_pFavoritesTree;
}
PostView* BatDown::getPostView()
{
return m_pPostView;
}
QLabel* BatDown::getWebProgress()
{
return m_pWebProgress;
} | [
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
] | [
[
[
1,
302
]
]
] |
349b7fc320a746b848205587f522cdd45d897fc6 | c440e6c62e060ee70b82fc07dfb9a93e4cc13370 | /src/gui2/algorithmview_loader.cpp | 6c7302e2846d75c25caff36717341e9d3f2e4290 | [] | no_license | BackupTheBerlios/pgrtsound-svn | 2a3f2ae2afa4482f9eba906f932c30853c6fe771 | d7cefe2129d20ec50a9e18943a850d0bb26852e1 | refs/heads/master | 2020-05-21T01:01:41.354611 | 2005-10-02T13:09:13 | 2005-10-02T13:09:13 | 40,748,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,463 | cpp | #include "algorithmview.h"
#include "./../xmlconfigfile.h"
#include <tinyxml.h>
#include <string>
#include <map>
#include <list>
#include <fstream>
void AlgorithmView::LoadFromFile(string fileName) {
XMLConfigFile xmlFile;
window->freeze_updates();
Clear();
xmlFile.OpenFile( fileName.c_str() );
xmlFile.LoadAlgorithm( &algorithm );
// utworzenie GUI modulow
Module* mod;
GuiModule* guiMod;
for( ModuleIdIterator it = algorithm.ModuleIdIteratorBegin();
it != algorithm.ModuleIdIteratorEnd(); it++ )
{
mod = algorithm.GetModule( *it );
//if( mod->GetName() == "AudioPortIn" || mod->GetName() == "AudioPortOut" ) {
// cout << " pomijam " << mod->GetName() << endl;
// continue;
//}
guiMod = guiFactory.CreateGuiModule( mod );
guiMod->SetParentView( this ); // konieczne na razie :(
//guiMod->SetModuleId( algorithm.GetModuleId( mod->GetName() ) );
guiMod->SetModuleId( *it );
name2GuiModuleMap.insert( make_pair(mod->GetName(), guiMod) );
guiModules.push_back( guiMod );
}
TRACE("AlgorithmView::LoadFromFile - Wczytywanie polozenia modulow...\n");
TiXmlElement* moduleXMLElem;
TiXmlNode* moduleXMLNode, * parent;
std::string moduleName;
int x, y;
//ModuleId moduleId;
TiXmlDocument document;
document.LoadFile( fileName.c_str() );
TiXmlHandle docHandle( &document );
parent = docHandle.FirstChild( "algorithm" ).FirstChild( "gui" ).Child("guimodule", 0).Node();
// przez wszystkie inne moduly
if(parent != NULL) {
for( moduleXMLNode = parent; moduleXMLNode;
moduleXMLNode = moduleXMLNode->NextSibling("guimodule") )
{
moduleXMLElem = moduleXMLNode->ToElement();
moduleName = moduleXMLElem->Attribute("name");
x = atoi( moduleXMLElem->Attribute("x") );
y = atoi( moduleXMLElem->Attribute("y") );
cout << "GUI: " << moduleName << " " << x << " " << y << endl;
guiMod = ( *name2GuiModuleMap.find(moduleName) ).second;
guiMod->SetXY(x, y);
}
}
TRACE("AlgorithmView::LoadFromFile - Polozenia modulow wczytane\n");
for(std::list<GuiModule*>::iterator it = guiModules.begin();
it != guiModules.end(); it++) {
guiMod = *it;
guiMod->GetPosition(x, y);
this->put(*guiMod, x, y);
}
// utworzenie GUI-polaczen na podstawie polaczen w obiekcie Algorithm
for(ConnectionIdIterator connIt = algorithm.ConnectionIdIteratorBegin();
connIt != algorithm.ConnectionIdIteratorEnd(); connIt++)
{
ConnectionId connId = *connIt;
GuiConnection* guiConn = new GuiConnection;
Connection* conn = algorithm.GetConnection(connId);
guiConn->Set(
connId,
(*name2GuiModuleMap.find( conn->sourceModule->GetName() )).second,
conn->sourceOutputId,
(*name2GuiModuleMap.find( conn->destinationModule->GetName() )).second,
conn->destinationInputId
);
(*name2GuiModuleMap.find( conn->destinationModule->GetName() )).second
->SetInputGuiConnection( conn->destinationInputId, guiConn );
connections.push_back(guiConn);
}
window->thaw_updates();
show_all_children();
TRACE("AlgorithmView::LoadFromFile - Polaczenia modulow wczytane\n");
}
/*
Zapis do pliku.
*/
void AlgorithmView::SaveToFile( string fileName ) {
cout << "save " << fileName << endl;
std::ofstream file;
file.open( fileName.c_str(), ios::out );
file << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
file << "<algorithm>\n";
file << "\t<modules>\n";
for( list<GuiModule*>::iterator modIt = guiModules.begin();
modIt != guiModules.end(); modIt++ )
{
Module* mod = (*modIt)->GetModule();
if( mod->GetName() == "AudioPortIn" || mod->GetName() == "AudioPortOut")
continue;
file << "\t\t<module type=\"" << mod->GetType()
<< "\" name=\"" << mod->GetName() << "\">\n";
for( int i = 0; i < mod->GetParameterCount(); i++ ) {
// file << "\t\t\t<parameter name=\"" << mod->GetParameter( i )->GetName()
// << "\" number=\"" << i << "\">";
file << "\t\t\t<parameter number=\"" << i << "\">";
if( mod->GetParameter( i )->GetType() == "float" ) {
ParameterFloat* param = (ParameterFloat*)mod->GetParameter( i );
file << param->GetValue();
}
if( mod->GetParameter( i )->GetType() == "string" ) {
ParameterString* param = (ParameterString*)mod->GetParameter( i );
file << param->GetText();
}
file << "</parameter>\n";
}
file << "\t\t</module>\n";
}
file << "\t</modules>\n";
file << "\t<connections>\n";
for(list<GuiConnection*>::iterator connIt = connections.begin();
connIt != connections.end(); connIt++)
{
Connection* conn = algorithm.GetConnection( (*connIt)->GetConnectionId() );
file << "\t\t<connection name1=\""
<< conn->sourceModule->GetName() << "\" output=\""
<< conn->sourceOutputId << "\" "
<< "name2=\""
<< conn->destinationModule->GetName() << "\" input=\""
<< conn->destinationInputId << "\" />\n";
}
file << "\t</connections>\n";
file << "\t<gui>\n";
int x, y;
for( list<GuiModule*>::iterator modIt = guiModules.begin();
modIt != guiModules.end(); modIt++ )
{
(*modIt)->GetPosition( x, y );
file << "\t\t<guimodule name=\"" << (*modIt)->GetModule()->GetName()
<< "\" x=\"" << x << "\" y=\"" << y << "\" />\n";
}
file << "\t</gui>\n";
file << "</algorithm>\n";
file.close();
}
| [
"ad4m@fa088095-53e8-0310-8a07-f9518708c3e6"
] | [
[
[
1,
187
]
]
] |
5eead8dffd0945dc4ee7652c616e46cbca17d846 | 8a2e417c772eba9cf4653d0c688dd3ac96590964 | /prop-src/constraint.h | f918c39f461bad6cb6b8772b81593c6b1073cc6b | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | romix/prop-cc | 1a190ba6ed8922428352826de38efb736e464f50 | 3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f | refs/heads/master | 2023-08-30T12:55:00.192286 | 2011-07-19T20:56:39 | 2011-07-19T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,745 | h | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "..\..\prop-src\constraint.ph".
///////////////////////////////////////////////////////////////////////////////
#define PROP_TUPLE2_USED
#include <propdefs.h>
#line 1 "../../prop-src/constraint.ph"
///////////////////////////////////////////////////////////////////////////////
//
// This file describes the interface of the constraint compiler.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef constraint_compiler_h
#define constraint_compiler_h
#include "basics.h"
#include "codegen.h"
#include "matchcom.h"
///////////////////////////////////////////////////////////////////////////////
//
// Forward datatype declarations
//
///////////////////////////////////////////////////////////////////////////////
#line 20 "../../prop-src/constraint.ph"
#line 28 "../../prop-src/constraint.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Ty
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Ty_defined
#define datatype_Ty_defined
class a_Ty;
typedef a_Ty * Ty;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Pat
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Pat_defined
#define datatype_Pat_defined
class a_Pat;
typedef a_Pat * Pat;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Exp
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Exp_defined
#define datatype_Exp_defined
class a_Exp;
typedef a_Exp * Exp;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Decl
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Decl_defined
#define datatype_Decl_defined
class a_Decl;
typedef a_Decl * Decl;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Def
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Def_defined
#define datatype_Def_defined
class a_Def;
typedef a_Def * Def;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Stmt
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Stmt_defined
#define datatype_Stmt_defined
class a_Stmt;
typedef a_Stmt * Stmt;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Instness
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Instness_defined
#define datatype_Instness_defined
class a_Instness;
typedef a_Instness * Instness;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for Determinism
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_Determinism_defined
#define datatype_Determinism_defined
class a_Determinism;
typedef a_Determinism * Determinism;
#endif
#line 28 "../../prop-src/constraint.ph"
#line 28 "../../prop-src/constraint.ph"
class HashTable;
///////////////////////////////////////////////////////////////////////////////
//
// The grammar of the constraint rules is defined as follows:
//
///////////////////////////////////////////////////////////////////////////////
#line 38 "../../prop-src/constraint.ph"
#line 66 "../../prop-src/constraint.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for ConstraintSet
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_ConstraintSet_defined
#define datatype_ConstraintSet_defined
class a_ConstraintSet;
typedef a_ConstraintSet * ConstraintSet;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for ConstraintDef
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_ConstraintDef_defined
#define datatype_ConstraintDef_defined
class a_ConstraintDef;
typedef a_ConstraintDef * ConstraintDef;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for ConstraintRule
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_ConstraintRule_defined
#define datatype_ConstraintRule_defined
class a_ConstraintRule;
typedef a_ConstraintRule * ConstraintRule;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Forward class definition for ConstraintBody
//
///////////////////////////////////////////////////////////////////////////////
#ifndef datatype_ConstraintBody_defined
#define datatype_ConstraintBody_defined
class a_ConstraintBody;
typedef a_ConstraintBody * ConstraintBody;
#endif
# define v_CONSTRAINTnone 0
# define v_CONSTRAINTcut 1
# define CONSTRAINTnone (ConstraintBody)v_CONSTRAINTnone
# define CONSTRAINTcut (ConstraintBody)v_CONSTRAINTcut
///////////////////////////////////////////////////////////////////////////////
// Definition of type ConstraintDefs
///////////////////////////////////////////////////////////////////////////////
#line 64 "../../prop-src/constraint.ph"
typedef a_List<ConstraintDef> * ConstraintDefs;
///////////////////////////////////////////////////////////////////////////////
// Definition of type ConstraintRules
///////////////////////////////////////////////////////////////////////////////
#line 65 "../../prop-src/constraint.ph"
typedef a_List<ConstraintRule> * ConstraintRules;
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintSet::CONSTRAINTset
//
///////////////////////////////////////////////////////////////////////////////
class a_ConstraintSet : public Loc {
public:
#line 38 "../../prop-src/constraint.ph"
ConstraintDefs CONSTRAINTset;
inline a_ConstraintSet (ConstraintDefs x_CONSTRAINTset)
: CONSTRAINTset(x_CONSTRAINTset)
{
}
};
inline int boxed(const a_ConstraintSet *) { return 1; }
inline int untag(const a_ConstraintSet *) { return 0; }
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for ConstraintSet
//
///////////////////////////////////////////////////////////////////////////////
inline a_ConstraintSet * CONSTRAINTset (ConstraintDefs x_CONSTRAINTset)
{
return new a_ConstraintSet (x_CONSTRAINTset);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for ConstraintSet
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Base class for datatype ConstraintDef
//
///////////////////////////////////////////////////////////////////////////////
class a_ConstraintDef : public Loc {
public:
enum Tag_ConstraintDef {
tag_CONSTRAINTruledef = 0, tag_CONSTRAINTtype = 1, tag_CONSTRAINTinstness = 2,
tag_CONSTRAINTdet = 3
};
public:
const Tag_ConstraintDef tag__; // variant tag
protected:
inline a_ConstraintDef(Tag_ConstraintDef t__) : tag__(t__) {}
public:
};
inline int boxed(const a_ConstraintDef *) { return 1; }
inline int untag(const a_ConstraintDef * x) { return x->tag__; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintDef::CONSTRAINTruledef
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintDef_CONSTRAINTruledef : public a_ConstraintDef {
public:
#line 41 "../../prop-src/constraint.ph"
ConstraintRule CONSTRAINTruledef;
inline ConstraintDef_CONSTRAINTruledef (ConstraintRule x_CONSTRAINTruledef)
: a_ConstraintDef(tag_CONSTRAINTruledef), CONSTRAINTruledef(x_CONSTRAINTruledef)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintDef::CONSTRAINTtype
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintDef_CONSTRAINTtype : public a_ConstraintDef {
public:
#line 43 "../../prop-src/constraint.ph"
Id _1; Ty _2;
inline ConstraintDef_CONSTRAINTtype (Id x_1, Ty x_2)
: a_ConstraintDef(tag_CONSTRAINTtype), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintDef::CONSTRAINTinstness
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintDef_CONSTRAINTinstness : public a_ConstraintDef {
public:
#line 44 "../../prop-src/constraint.ph"
Id _1; Pat _2;
inline ConstraintDef_CONSTRAINTinstness (Id x_1, Pat x_2)
: a_ConstraintDef(tag_CONSTRAINTinstness), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintDef::CONSTRAINTdet
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintDef_CONSTRAINTdet : public a_ConstraintDef {
public:
#line 45 "../../prop-src/constraint.ph"
Id _1; Pats _2; Determinism _3;
inline ConstraintDef_CONSTRAINTdet (Id x_1, Pats x_2, Determinism x_3)
: a_ConstraintDef(tag_CONSTRAINTdet), _1(x_1), _2(x_2), _3(x_3)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for ConstraintDef
//
///////////////////////////////////////////////////////////////////////////////
inline a_ConstraintDef * CONSTRAINTruledef (ConstraintRule x_CONSTRAINTruledef)
{
return new ConstraintDef_CONSTRAINTruledef (x_CONSTRAINTruledef);
}
inline a_ConstraintDef * CONSTRAINTtype (Id x_1, Ty x_2)
{
return new ConstraintDef_CONSTRAINTtype (x_1, x_2);
}
inline a_ConstraintDef * CONSTRAINTinstness (Id x_1, Pat x_2)
{
return new ConstraintDef_CONSTRAINTinstness (x_1, x_2);
}
inline a_ConstraintDef * CONSTRAINTdet (Id x_1, Pats x_2, Determinism x_3)
{
return new ConstraintDef_CONSTRAINTdet (x_1, x_2, x_3);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for ConstraintDef
//
///////////////////////////////////////////////////////////////////////////////
inline ConstraintDef_CONSTRAINTruledef * _CONSTRAINTruledef(const a_ConstraintDef * _x_) { return (ConstraintDef_CONSTRAINTruledef *)_x_; }
inline ConstraintDef_CONSTRAINTtype * _CONSTRAINTtype(const a_ConstraintDef * _x_) { return (ConstraintDef_CONSTRAINTtype *)_x_; }
inline ConstraintDef_CONSTRAINTinstness * _CONSTRAINTinstness(const a_ConstraintDef * _x_) { return (ConstraintDef_CONSTRAINTinstness *)_x_; }
inline ConstraintDef_CONSTRAINTdet * _CONSTRAINTdet(const a_ConstraintDef * _x_) { return (ConstraintDef_CONSTRAINTdet *)_x_; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintRule::CONSTRAINTrule
//
///////////////////////////////////////////////////////////////////////////////
class a_ConstraintRule : public Loc {
public:
#line 47 "../../prop-src/constraint.ph"
Id id; Pat pat; ConstraintBody body; Ty ty;
inline a_ConstraintRule (Id x_id, Pat x_pat, ConstraintBody x_body, Ty x_ty = NOty)
: id(x_id), pat(x_pat), body(x_body), ty(x_ty)
{
}
};
inline int boxed(const a_ConstraintRule *) { return 1; }
inline int untag(const a_ConstraintRule *) { return 0; }
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for ConstraintRule
//
///////////////////////////////////////////////////////////////////////////////
inline a_ConstraintRule * CONSTRAINTrule (Id x_id, Pat x_pat, ConstraintBody x_body, Ty x_ty = NOty)
{
return new a_ConstraintRule (x_id, x_pat, x_body, x_ty);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for ConstraintRule
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Base class for datatype ConstraintBody
//
///////////////////////////////////////////////////////////////////////////////
class a_ConstraintBody : public Loc {
public:
enum Tag_ConstraintBody {
tag_CONSTRAINTand = 0, tag_CONSTRAINTif = 1, tag_CONSTRAINTbody = 2,
tag_CONSTRAINTcall = 3
};
public:
const Tag_ConstraintBody tag__; // variant tag
protected:
inline a_ConstraintBody(Tag_ConstraintBody t__) : tag__(t__) {}
public:
};
inline int boxed(const a_ConstraintBody * x) { return (unsigned long)x >= 2; }
inline int untag(const a_ConstraintBody * x) { return boxed(x) ? x->tag__ + 2 : (int)x; }
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintBody::CONSTRAINTand
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintBody_CONSTRAINTand : public a_ConstraintBody {
public:
#line 59 "../../prop-src/constraint.ph"
ConstraintBody _1; ConstraintBody _2;
inline ConstraintBody_CONSTRAINTand (ConstraintBody x_1, ConstraintBody x_2)
: a_ConstraintBody(tag_CONSTRAINTand), _1(x_1), _2(x_2)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintBody::CONSTRAINTif
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintBody_CONSTRAINTif : public a_ConstraintBody {
public:
#line 60 "../../prop-src/constraint.ph"
ConstraintBody _1; ConstraintBody _2; ConstraintBody _3;
inline ConstraintBody_CONSTRAINTif (ConstraintBody x_1, ConstraintBody x_2, ConstraintBody x_3)
: a_ConstraintBody(tag_CONSTRAINTif), _1(x_1), _2(x_2), _3(x_3)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintBody::CONSTRAINTbody
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintBody_CONSTRAINTbody : public a_ConstraintBody {
public:
#line 61 "../../prop-src/constraint.ph"
a_List<Decl> * CONSTRAINTbody;
inline ConstraintBody_CONSTRAINTbody (a_List<Decl> * x_CONSTRAINTbody)
: a_ConstraintBody(tag_CONSTRAINTbody), CONSTRAINTbody(x_CONSTRAINTbody)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Class for datatype constructor ConstraintBody::CONSTRAINTcall
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintBody_CONSTRAINTcall : public a_ConstraintBody {
public:
#line 62 "../../prop-src/constraint.ph"
Exp CONSTRAINTcall;
inline ConstraintBody_CONSTRAINTcall (Exp x_CONSTRAINTcall)
: a_ConstraintBody(tag_CONSTRAINTcall), CONSTRAINTcall(x_CONSTRAINTcall)
{
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Datatype constructor functions for ConstraintBody
//
///////////////////////////////////////////////////////////////////////////////
inline a_ConstraintBody * CONSTRAINTand (ConstraintBody x_1, ConstraintBody x_2)
{
return new ConstraintBody_CONSTRAINTand (x_1, x_2);
}
inline a_ConstraintBody * CONSTRAINTif (ConstraintBody x_1, ConstraintBody x_2, ConstraintBody x_3)
{
return new ConstraintBody_CONSTRAINTif (x_1, x_2, x_3);
}
inline a_ConstraintBody * CONSTRAINTbody (a_List<Decl> * x_CONSTRAINTbody)
{
return new ConstraintBody_CONSTRAINTbody (x_CONSTRAINTbody);
}
inline a_ConstraintBody * CONSTRAINTcall (Exp x_CONSTRAINTcall)
{
return new ConstraintBody_CONSTRAINTcall (x_CONSTRAINTcall);
}
///////////////////////////////////////////////////////////////////////////////
//
// Downcasting functions for ConstraintBody
//
///////////////////////////////////////////////////////////////////////////////
inline ConstraintBody_CONSTRAINTand * _CONSTRAINTand(const a_ConstraintBody * _x_) { return (ConstraintBody_CONSTRAINTand *)_x_; }
inline ConstraintBody_CONSTRAINTif * _CONSTRAINTif(const a_ConstraintBody * _x_) { return (ConstraintBody_CONSTRAINTif *)_x_; }
inline ConstraintBody_CONSTRAINTbody * _CONSTRAINTbody(const a_ConstraintBody * _x_) { return (ConstraintBody_CONSTRAINTbody *)_x_; }
inline ConstraintBody_CONSTRAINTcall * _CONSTRAINTcall(const a_ConstraintBody * _x_) { return (ConstraintBody_CONSTRAINTcall *)_x_; }
#line 66 "../../prop-src/constraint.ph"
#line 66 "../../prop-src/constraint.ph"
///////////////////////////////////////////////////////////////////////////////
//
// Pretty printing routines.
//
///////////////////////////////////////////////////////////////////////////////
extern std::ostream& operator << (std::ostream&, ConstraintSet);
extern std::ostream& operator << (std::ostream&, ConstraintDef);
extern std::ostream& operator << (std::ostream&, ConstraintDefs);
extern std::ostream& operator << (std::ostream&, ConstraintRule);
extern std::ostream& operator << (std::ostream&, ConstraintRules);
extern std::ostream& operator << (std::ostream&, ConstraintBody);
///////////////////////////////////////////////////////////////////////////////
//
// Forward declaration.
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintCompilerInternal;
///////////////////////////////////////////////////////////////////////////////
//
// The constraint compiler is inherited from the code generator.
//
///////////////////////////////////////////////////////////////////////////////
class ConstraintCompiler : virtual public CodeGen,
virtual public MatchCompiler
{
ConstraintCompiler(const ConstraintCompiler&); // no copy constructor
void operator = (const ConstraintCompiler&); // no assignment
protected:
ConstraintCompilerInternal * internal; // internal implementation
public:
////////////////////////////////////////////////////////////////////////////
//
// Constructor and destructor
//
////////////////////////////////////////////////////////////////////////////
ConstraintCompiler();
virtual ~ConstraintCompiler();
////////////////////////////////////////////////////////////////////////////
//
// Methods for compiling a set of constraint rules.
//
////////////////////////////////////////////////////////////////////////////
void compile_ruleset( Id class_name, ConstraintSet rule_set);
private:
////////////////////////////////////////////////////////////////////////////
//
// Private implementation methods.
//
////////////////////////////////////////////////////////////////////////////
void process_typing_rules( Id,
#line 127 "../../prop-src/constraint.ph"
a_List<Tuple2<Id, Ty> > *
#line 127 "../../prop-src/constraint.ph"
);
void process_ruleset( Id, ConstraintRules);
void add_predicate_type( Id, Ty);
void analyze_rule( ConstraintBody);
};
#endif
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 0
Number of ifs generated = 0
Number of switches generated = 0
Number of labels = 0
Number of gotos = 0
Adaptive matching = disabled
Fast string matching = disabled
Inline downcasts = disabled
--------------------------------------------------------------------------
*/
| [
"[email protected]"
] | [
[
[
1,
568
]
]
] |
d60d8c0f994de1c51c9c522d49bd725a4722d9e7 | 26706a661c23f5c2c1f97847ba09f44b7b425cf6 | /TaskManager/CpuUsage.cpp | 377b45744f298ef2ef99cc53df2831b31b77c02f | [] | no_license | 124327288/nativetaskmanager | 96a54dbe150f855422d7fd813d3631eaac76fadd | e75b3d9d27c902baddbb1bef975c746451b1b8bb | refs/heads/master | 2021-05-29T05:18:26.779900 | 2009-02-10T13:23:28 | 2009-02-10T13:23:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,407 | cpp | #include "stdafx.h"
#include <atlbase.h> // for CRegKey use
#include "CpuUsage.h"
//
//#pragma pack(push,8)
//#include "PerfCounters.h"
//#pragma pack(pop)
#pragma warning( disable: 4996 )
#define SYSTEM_OBJECT_INDEX 2 // 'System' object
#define PROCESS_OBJECT_INDEX 230 // 'Process' object
#define PROCESSOR_OBJECT_INDEX 238 // 'Processor' object
#define TOTAL_PROCESSOR_TIME_COUNTER_INDEX 240 // '% Total processor time' counter (valid in WinNT under 'System' object)
#define PROCESSOR_TIME_COUNTER_INDEX 6 // '% processor time' counter (for Win2K/XP)
///////////////////////////////////////////////////////////////////
//
// GetCpuUsage uses the performance counters to retrieve the
// system cpu usage.
// The cpu usage counter is of type PERF_100NSEC_TIMER_INV
// which as the following calculation:
//
// Element Value
// ======= ===========
// X CounterData
// Y 100NsTime
// Data Size 8 Bytes
// Time base 100Ns
// Calculation 100*(1-(X1-X0)/(Y1-Y0))
//
// where the denominator (Y) represents the total elapsed time of the
// sample interval and the numerator (X) represents the time during
// the interval when the monitored components were inactive.
//
//
// Note:
// ====
// On windows NT, cpu usage counter is '% Total processor time'
// under 'System' object. However, in Win2K/XP Microsoft moved
// that counter to '% processor time' under '_Total' instance
// of 'Processor' object.
// Read 'INFO: Percent Total Performance Counter Changes on Windows 2000'
// Q259390 in MSDN.
//
///////////////////////////////////////////////////////////////////
typedef enum
{
WINNT, WIN2K_XP, WIN9X, UNKNOWN
}PLATFORM;
PLATFORM GetPlatform()
{
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi))
return UNKNOWN;
switch (osvi.dwPlatformId)
{
case VER_PLATFORM_WIN32_WINDOWS:
return WIN9X;
case VER_PLATFORM_WIN32_NT:
if (osvi.dwMajorVersion == 4)
return WINNT;
else
return WIN2K_XP;
}
return UNKNOWN;
}
CCpuUsage::CCpuUsage()
{
m_bFirstTime = true;
m_lnOldValue = 0;
memset(&m_OldPerfTime100nSec, 0, sizeof(m_OldPerfTime100nSec));
}
CCpuUsage::~CCpuUsage()
{
}
BOOL CCpuUsage::EnablePerformaceCounters(BOOL bEnable)
{
if (GetPlatform() != WIN2K_XP)
return TRUE;
CRegKey regKey;
if (regKey.Open(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\PerfOS\\Performance")) != ERROR_SUCCESS)
return FALSE;
regKey.SetValue(!bEnable, _T("Disable Performance Counters"));
regKey.Close();
if (regKey.Open(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\PerfProc\\Performance")) != ERROR_SUCCESS)
return FALSE;
regKey.SetValue((DWORD)!bEnable, _T("Disable Performance Counters"));
regKey.Close();
return TRUE;
}
//
// GetCpuUsage returns the system-wide cpu usage.
// Since we calculate the cpu usage by two samplings, the first
// call to GetCpuUsage() returns 0 and keeps the values for the next
// sampling.
// Read the comment at the beginning of this file for the formula.
//
int CCpuUsage::GetCpuUsage()
{
static PLATFORM Platform = GetPlatform();
if (m_bFirstTime)
EnablePerformaceCounters();
// Cpu usage counter is 8 byte length.
CPerfCounters<LONGLONG> PerfCounters;
TCHAR szInstance[256] = {0};
// Note:
// ====
// On windows NT, cpu usage counter is '% Total processor time'
// under 'System' object. However, in Win2K/XP Microsoft moved
// that counter to '% processor time' under '_Total' instance
// of 'Processor' object.
// Read 'INFO: Percent Total Performance Counter Changes on Windows 2000'
// Q259390 in MSDN.
DWORD dwObjectIndex;
DWORD dwCpuUsageIndex;
switch (Platform)
{
case WINNT:
dwObjectIndex = SYSTEM_OBJECT_INDEX;
dwCpuUsageIndex = TOTAL_PROCESSOR_TIME_COUNTER_INDEX;
break;
case WIN2K_XP:
dwObjectIndex = PROCESSOR_OBJECT_INDEX;
dwCpuUsageIndex = PROCESSOR_TIME_COUNTER_INDEX;
lstrcpy(szInstance,_T("_Total"));
break;
default:
return -1;
}
int CpuUsage = 0;
LONGLONG lnNewValue = 0;
PPERF_DATA_BLOCK pPerfData = NULL;
LARGE_INTEGER NewPerfTime100nSec = {0};
lnNewValue = PerfCounters.GetCounterValue(&pPerfData, dwObjectIndex, dwCpuUsageIndex, szInstance);
NewPerfTime100nSec = pPerfData->PerfTime100nSec;
if (m_bFirstTime)
{
m_bFirstTime = false;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
return 0;
}
LONGLONG lnValueDelta = lnNewValue - m_lnOldValue;
double DeltaPerfTime100nSec = (double)NewPerfTime100nSec.QuadPart - (double)m_OldPerfTime100nSec.QuadPart;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
double a = (double)lnValueDelta / DeltaPerfTime100nSec;
double f = (1.0 - a) * 100.0;
CpuUsage = (int)(f + 0.5); // rounding the result
if (CpuUsage < 0)
return 0;
return CpuUsage;
}
int CCpuUsage::GetCpuUsage(LPCTSTR pProcessName)
{
static PLATFORM Platform = GetPlatform();
if (m_bFirstTime)
EnablePerformaceCounters();
// Cpu usage counter is 8 byte length.
CPerfCounters<LONGLONG> PerfCounters;
TCHAR szInstance[256] = {0};
DWORD dwObjectIndex = PROCESS_OBJECT_INDEX;
DWORD dwCpuUsageIndex = PROCESSOR_TIME_COUNTER_INDEX;
lstrcpy(szInstance,pProcessName);
int CpuUsage = 0;
LONGLONG lnNewValue = 0;
PPERF_DATA_BLOCK pPerfData = NULL;
LARGE_INTEGER NewPerfTime100nSec = {0};
lnNewValue = PerfCounters.GetCounterValue(&pPerfData, dwObjectIndex, dwCpuUsageIndex, szInstance);
NewPerfTime100nSec = pPerfData->PerfTime100nSec;
if (m_bFirstTime)
{
m_bFirstTime = false;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
return 0;
}
LONGLONG lnValueDelta = lnNewValue - m_lnOldValue;
double DeltaPerfTime100nSec = (double)NewPerfTime100nSec.QuadPart - (double)m_OldPerfTime100nSec.QuadPart;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
double a = (double)lnValueDelta / DeltaPerfTime100nSec;
CpuUsage = (int) (a*100);
if (CpuUsage < 0)
return 0;
return CpuUsage;
}
int CCpuUsage::GetCpuUsage(DWORD dwProcessID)
{
static PLATFORM Platform = GetPlatform();
if (m_bFirstTime)
EnablePerformaceCounters();
// Cpu usage counter is 8 byte length.
CPerfCounters<LONGLONG> PerfCounters;
DWORD dwObjectIndex = PROCESS_OBJECT_INDEX;
DWORD dwCpuUsageIndex = PROCESSOR_TIME_COUNTER_INDEX;
int CpuUsage = 0;
LONGLONG lnNewValue = 0;
PPERF_DATA_BLOCK pPerfData = NULL;
LARGE_INTEGER NewPerfTime100nSec = {0};
lnNewValue = PerfCounters.GetCounterValueForProcessID(&pPerfData, dwObjectIndex, dwCpuUsageIndex, dwProcessID);
NewPerfTime100nSec = pPerfData->PerfTime100nSec;
if (m_bFirstTime)
{
m_bFirstTime = false;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
return 0;
}
LONGLONG lnValueDelta = lnNewValue - m_lnOldValue;
double DeltaPerfTime100nSec = (double)NewPerfTime100nSec.QuadPart - (double)m_OldPerfTime100nSec.QuadPart;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
double a = (double)lnValueDelta / DeltaPerfTime100nSec;
CpuUsage = (int) (a*100);
if (CpuUsage < 0)
return 0;
return CpuUsage;
}
| [
"[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
270
]
]
] |
b0329fbdb5c2255656417318da4394472b831284 | a48646eddd0eec81c4be179511493cbaf22965b9 | /src/sip/transaction/sip_txn_mngt.inc | ca5ac08a8ddb4df53a25b486a3a8f8a4bcbb8420 | [] | no_license | lengue/tsip | 0449f791a5cbe9e9fdaa1b4d7f1d1e28eff2f0ec | da8606bd7d865d4b4a389ec1594248a4044bc890 | refs/heads/master | 2021-01-10T08:40:32.925501 | 2010-06-05T12:44:10 | 2010-06-05T12:44:10 | 53,989,315 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 967 | inc | /*******************************************************************************
功能 : SIP协议栈传输层功能函数
创建人 : 唐春平
创建日期: 2009.01.10
修改记录:
*******************************************************************************/
ULONG SIP_Txn_AllocTxn(ULONG ulCoreID, ULONG *pulTxnID);
ULONG SIP_Txn_FreeTxn(ULONG ulTxnID);
ULONG SIP_Txn_Match(UBUF_HEADER_S *pstUbufSipMsg, ULONG *pulTxnID);
ULONG SIP_Txn_MakeKey(void *pCompared);
ULONG SIP_Txn_Compare(void *pCompared, ULONG ulPara);
ULONG SIP_Txn_CompareResponse(UBUF_HEADER_S *pstUbufResponse,
UBUF_HEADER_S *pstUbufTxnInitMsg);
ULONG SIP_Txn_CompareRequest(UBUF_HEADER_S *pstUbufRequest,
UBUF_HEADER_S *pstUbufTxnInitMsg);
ULONG SIP_Txn_CompareSendBy(UBUF_HEADER_S *pstUbufRequest,
UBUF_HEADER_S *pstUbufTxnInitMsg);
ULONG SIP_Txn_GenerateBranch(ULONG *pulTxnID);
| [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
f26cb384f7157d25a543a0f4cb271ccd3c3406c1 | 016c54cb102ac6b792ee9756614d43b5687950b7 | /UiCommon/UiInstructionDlg.h | 9e320ae83406535637c5655ce64a24f04e6a580a | [] | no_license | jemyzhang/MzCommonDll | 3103fc4f5214a069c473b5aaca90aaf09d355517 | 82cbfa7eaa872809fa0bdea4531d5df73e23ca47 | refs/heads/master | 2021-01-19T14:53:26.687575 | 2010-05-20T03:18:16 | 2010-05-20T03:18:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,801 | h | #pragma once
/*
* @filename UiSingleOption.h
* @note 单选列表
* @author JEMYZHANG
* @date 2009.10.16
* @ver. 1.0
* @changelog
* ver.1.0 初始化程序
*/
#include <MzCommonDll.h>
#include "UiImage.h"
class COMMON_API Ui_InstructionWnd : public CMzWndEx
{
MZ_DECLARE_DYNAMIC(Ui_InstructionWnd);
public:
Ui_InstructionWnd(void);
~Ui_InstructionWnd(void);
public:
UiImage m_splitter_top;
UiImage m_Instruction;
UiButton m_BtnOK;
UiStatic m_Title;
public:
void SetInstructionImage(ImagingHelper* img){
m_Instruction.setupImage(img);
}
void PaintWin(HDC hdc, RECT* prcUpdate = NULL){
if(bUpdateBgWin == TRUE){
bUpdateBgWin = FALSE;
bgWin = ::ScreenSnapshot();
}
RECT rectWin = {0,0,0,0};
rectWin.right = this->GetWidth();
rectWin.bottom = this->GetHeight();
::SetBkMode(hdc,TRANSPARENT);
HBRUSH myBrush = CreateSolidBrush(RGB(16,16,16));
FillRect(hdc,&rectWin,myBrush);//底色
::BitmapTransBlt(hdc,&rectWin,bgWin,&rectCopy,RGB(128,128,128));
CMzWndEx::PaintWin(hdc,prcUpdate);
}
virtual BOOL Create(int xPos, int yPos, int width, int height, HWND hwndParent=NULL, int uID = NULL, DWORD style=WS_CHILD, DWORD exstyle=0){
rectCopy.left = xPos;
rectCopy.top = yPos;
rectCopy.right = xPos + width;
rectCopy.bottom = yPos + height;
return CMzWndEx::Create(xPos,yPos,width,height,hwndParent,uID,style,exstyle);
}
protected:
// Initialization of the window (dialog)
virtual BOOL OnInitDialog();
// override the MZFC command handler
virtual void OnMzCommand(WPARAM wParam, LPARAM lParam);
private:
LPTSTR m_title;
HBITMAP bgWin;
BOOL bUpdateBgWin;
RECT rectCopy;
};
| [
"jemyzhang@96341596-6814-2f4c-99ee-b9cf7f28d869"
] | [
[
[
1,
61
]
]
] |
17a2629918fbb6ae60e8b59e279543192c123ab7 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_FactoryManager.h | 939d2d1e1724030015591a712a2476c8014d1fa0 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,605 | h | /*!
@file
@author Albert Semenov
@date 06/2009
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_FACTORY_MANAGER_H__
#define __MYGUI_FACTORY_MANAGER_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Singleton.h"
#include "MyGUI_IObject.h"
#include "MyGUI_GenericFactory.h"
namespace MyGUI
{
class MYGUI_EXPORT FactoryManager :
public Singleton<FactoryManager>
{
public:
FactoryManager();
void initialise();
void shutdown();
typedef delegates::CDelegate1<IObject*&> Delegate;
// DESCRIBEME
void registerFactory(const std::string& _category, const std::string& _type, Delegate::IDelegate* _delegate);
// DESCRIBEME
void unregisterFactory(const std::string& _category, const std::string& _type);
// DESCRIBEME
void unregisterFactory(const std::string& _category);
// DESCRIBEME
bool isFactoryExist(const std::string& _category, const std::string& _type);
// DESCRIBEME
template<typename Type>
void registerFactory(const std::string& _category)
{
registerFactory(_category, Type::getClassTypeName(), GenericFactory<Type>::getFactory());
}
// DESCRIBEME
template<typename Type>
void registerFactory(const std::string& _category, const std::string& _type)
{
registerFactory(_category, _type, GenericFactory<Type>::getFactory());
}
// DESCRIBEME
template<typename Type>
void unregisterFactory(const std::string& _category)
{
unregisterFactory(_category, Type::getClassTypeName());
}
// DESCRIBEME
IObject* createObject(const std::string& _category, const std::string& _type);
// DESCRIBEME
void destroyObject(IObject* _object);
private:
typedef std::map<std::string, Delegate> MapFactoryItem;
typedef std::map<std::string, MapFactoryItem> MapRegisterFactoryItem;
MapRegisterFactoryItem mRegisterFactoryItems;
bool mIsInitialise;
};
} // namespace MyGUI
#endif // __MYGUI_FACTORY_MANAGER_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
89
]
]
] |
38a31473a767eefcf42eb3ee14d1d4446efcfcdb | f77f105963cd6447d0f392b9ee7d923315a82ac6 | /Box2DandOgre/source/GameObjectOgre.cpp | d1b65cd64e57dcf9bddad5348f6f19c4c4264fc3 | [] | no_license | GKimGames/parkerandholt | 8bb2b481aff14cf70a7a769974bc2bb683d74783 | 544f7afa462c5a25c044445ca9ead49244c95d3c | refs/heads/master | 2016-08-07T21:03:32.167272 | 2010-08-26T03:01:35 | 2010-08-26T03:01:35 | 32,834,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,539 | cpp | /*=============================================================================
GameObjectOgre.cpp
Author: Matt King
=============================================================================*/
#include "GameObjectOgre.h"
#include "GameFramework.h"
#include "MessageDispatcher.h"
//=============================================================================
// GameObjectOgre::Constructor
//
/// Grabs the SceneManager and creates a SceneNode for this object.
GameObjectOgre::GameObjectOgre(Ogre::String name):
GameObject(name)
{
sceneManager_ = GAMEFRAMEWORK->sceneManager;
sceneNode_ = sceneManager_->getRootSceneNode()->createChildSceneNode();
transparency_ = 0;
particleSystem_ = 0;
}
//=============================================================================
// GameObjectOgre::Destructor
//
/// Destroys the SceneNode.
GameObjectOgre::~GameObjectOgre()
{
if(sceneNode_)
{
sceneManager_->destroySceneNode(sceneNode_);
}
}
//=============================================================================
// Initialize
//
/// All children of the class must call this Initialize function before their
/// own. This pattern should extend through all children.
bool GameObjectOgre::Initialize()
{
initialized_ = GameObject::Initialize();
return initialized_;
}
//=============================================================================
// Initialize
//
/// Initialize the object with a mesh.
/// All children of the class must call this Initialize function before their
/// own. This pattern should extend through all children.
bool GameObjectOgre::Initialize(Ogre::String meshName)
{
objectName_ = meshName;
initialized_ = GameObject::Initialize();
if(initialized_)
{
Ogre::String entityName = objectName_;
entityName += "_Entity_";
entityName += Ogre::StringConverter::toString(objectId_);
entity_ = sceneManager_->createEntity(entityName, meshName);
sceneNode_->attachObject(entity_);
initialized_ = true;
}
/*transparency_ = new EntityMaterialInstance(entity_);*/
return initialized_;
}
//=============================================================================
// Update
//
/// Update calls UpdataGraphics
bool GameObjectOgre::Update(double timeSinceLastFrame)
{
if(GameObject::Update(timeSinceLastFrame))
{
UpdateGraphics(timeSinceLastFrame);
return true;
}
else
{
return false;
}
}
//=============================================================================
// UpdateGraphics
//
///
bool GameObjectOgre::UpdateGraphics(double timeSinceLastFrame)
{
return true;
}
//=============================================================================
// HandleMessage
//
/// Each class that extends this class should call this HandleMessage
/// before their own in case this class can handle the message.
/// If you want this class to do something with a message and its children
/// to something with it as well just return false for that message.
bool GameObjectOgre::HandleMessage(const KGBMessage message)
{
if(GameObject::HandleMessage(message))
{
return true;
}
else
{
if(message.messageType == GOO_SET_TRANSPARENCY)
{
if(message.messageData.empty() == false)
{
Ogre::String typeName(message.messageData.type().name());
SetTransparency(boost::any_cast<double>(message.messageData));
}
return true;
}
else if(message.messageType == SET_POSITION)
{
if(message.messageData.empty() == false)
{
Ogre::String typeName(message.messageData.type().name());
sceneNode_->setPosition(boost::any_cast<Ogre::Vector3>(message.messageData));
}
return false;
}
}
return false;
}
//=============================================================================
// SetTransparency
//
/// Set the transparency of the mesh in this object.
void GameObjectOgre::SetTransparency(Ogre::Real alpha)
{
if(transparency_ == 0)
{
transparency_ = new EntityMaterialInstance(entity_);
}
transparency_->setTransparency(alpha);
}
//=============================================================================
// SetBlendType
//
/// Set the blending type of the mesh matieral.
void GameObjectOgre::SetBlendType(Ogre::SceneBlendType type)
{
if(transparency_ == 0)
{
transparency_ = new EntityMaterialInstance(entity_);
}
transparency_->setSceneBlending(type);
} | [
"mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce",
"Kaziks@34afb35a-be5b-11de-bb5c-85734917f5ce"
] | [
[
[
1,
21
],
[
23,
74
],
[
76,
103
],
[
107,
150
],
[
160,
163
],
[
170,
170
],
[
172,
172
]
],
[
[
22,
22
],
[
75,
75
],
[
104,
106
],
[
151,
159
],
[
164,
169
],
[
171,
171
]
]
] |
72379c72dc1b146fd52f7c0ef124deb8a8a89d9e | fac8de123987842827a68da1b580f1361926ab67 | /inc/math/HMVector4.h | 7f7baae2ae56d4d7431dc9a140020c7ce7c7591d | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 15,075 | h | #ifndef HYPERMATH_VECTOR4
#define HYPERMATH_VECTOR4
#include "math/HMath.h"
namespace hmath
{
class v4
{
public :
union
{
struct
{
f32 x;
f32 y;
f32 z;
f32 w;
};
f32 val[4];
};
inline v4(){};
inline v4( const f32 fX, const f32 fY, const f32 fZ, const f32 fW );
inline explicit v4( const i32 fX, const i32 fY, const i32 fZ, const i32 fW );
inline explicit v4( const f32 vec[4] );
inline explicit v4( const i32 vec[4] );
inline explicit v4( f32* const r );
inline explicit v4( const f32 scaler );
inline v4( const v4& vec );
inline f32 operator [] ( const size_t i ) const;
inline f32& operator [] ( const size_t i );
inline v4& operator = ( const v4& vec );
inline v4& operator = ( const f32 scaler );
inline bit operator == ( const v4& vec ) const;
inline bit operator != ( const v4& vec ) const;
inline v4 operator + ( const v4& vec ) const;
inline v4 operator - ( const v4& vec ) const;
inline v4 operator * ( const f32 scalar ) const;
inline v4 operator * ( const v4& rhs) const;
inline v4 operator / ( const f32 scalar ) const;
inline v4 operator / ( const v4& rhs) const;
inline v4 operator - () const;
inline v4 operator + () const;
inline v4& operator += ( const v4& vec );
inline v4& operator += ( const f32 scalar );
inline v4& operator -= ( const v4& vec );
inline v4& operator -= ( const f32 scalar );
inline v4& operator *= ( const f32 scalar );
inline v4& operator *= ( const v4& vec );
inline v4& operator /= ( const f32 scalar );
inline v4& operator /= ( const v4& vec );
inline bit operator < ( const v4& rhs ) const;
inline bit operator > ( const v4& rhs ) const;
inline f32 len () const;
inline f32 sqlen () const;
inline f32 dot(const v4& vec) const;
inline f32 norm();
inline v4 cross( const v4& vec ) const;
inline v4 reflect(const v4& normal) const;
inline bit iszerolen(void) const;
inline v4 up(void) const;
inline v4 mid( const v4& vec ) const;
inline void floor( const v4& cmp );
inline void ceil( const v4& cmp );
static const v4 zero;
static const v4 unitX;
static const v4 unitY;
static const v4 unitZ;
static const v4 unitW;
static const v4 neg_unitX;
static const v4 neg_unitY;
static const v4 neg_unitZ;
static const v4 neg_unitW;
static const v4 unit;
quat getRotationTo(const v4& dest, const v4& fallbackAxis = v4::zero) const;
};
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const f32 fX, const f32 fY, const f32 fZ, const f32 fW )
: x( fX ), y( fY ), z( fZ ), w( fW )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const i32 fX, const i32 fY, const i32 fZ, const i32 fW )
{
x = f32(fX);
y = f32(fY);
z = f32(fZ);
w = f32(fW);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const f32 vec[4] )
: x( vec[0] ), y( vec[1] ), z( vec[2] ), w( vec[3] )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const i32 vec[4] )
{
x = (f32)vec[0];
y = (f32)vec[1];
z = (f32)vec[2];
w = (f32)vec[3];
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( f32* const r )
: x( r[0] ), y( r[1] ), z( r[2] ), w( r[3] )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const f32 scaler )
: x( scaler ), y( scaler ), z( scaler ), w( scaler )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4::v4( const v4& vec )
: x( vec.x ), y( vec.y ), z( vec.z ), w( vec.w )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v4::operator [] ( const size_t i ) const
{
// assert( i < 4 );
return *(&x+i);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32& v4::operator [] ( const size_t i )
{
// assert( i < 4 );
return *(&x+i);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator = ( const v4& vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
w = vec.w;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator = ( const f32 scaler )
{
x = scaler;
y = scaler;
z = scaler;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v4::operator == ( const v4& vec ) const
{
return ( x == vec.x && y == vec.y && z == vec.z && w == vec.w );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v4::operator != ( const v4& vec ) const
{
return ( x != vec.x || y != vec.y || z != vec.z || w != vec.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator + ( const v4& vec ) const
{
return v4(x + vec.x,y + vec.y,z + vec.z,w + vec.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator - ( const v4& vec ) const
{
return v4(x - vec.x,y - vec.y,z - vec.z,w - vec.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator * ( const f32 scalar ) const
{
return v4(x * scalar,y * scalar,z * scalar,w * scalar);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator * ( const v4& rhs) const
{
return v4(x * rhs.x,y * rhs.y, z * rhs.z,w * rhs.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator / ( const f32 scalar ) const
{
assert( scalar != 0.0 );
f32 fInv = f32(1.0) / scalar;
return v4( x * fInv,y * fInv,z * fInv,w * fInv);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator / ( const v4& rhs) const
{
return v4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator + () const
{
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::operator - () const
{
return v4(-x, -y, -z, -w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
static v4 operator * ( const f32 scalar, const v4& vec )
{
return v4( scalar * vec.x, scalar * vec.y, scalar * vec.z, scalar * vec.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
static v4 operator + (const v4& lhs, const f32 rhs)
{
return v4( lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
static v4 operator + (const f32 lhs, const v4& rhs)
{
return v4( lhs + rhs.x, lhs + rhs.y,lhs + rhs.z, lhs + rhs.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
static v4 operator - (const v4& lhs, const f32 rhs)
{
return v4( lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
static v4 operator - (const f32 lhs, const v4& rhs)
{
return v4(lhs - rhs.x,lhs - rhs.y,lhs - rhs.z, lhs - rhs.w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator += ( const v4& vec )
{
x += vec.x;
y += vec.y;
z += vec.z;
w += vec.w;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator += ( const f32 scalar )
{
x += scalar;
y += scalar;
z += scalar;
w += scalar;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator -= ( const v4& vec )
{
x -= vec.x;
y -= vec.y;
z -= vec.z;
w -= vec.w;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator -= ( const f32 scalar )
{
x -= scalar;
y -= scalar;
z -= scalar;
w -= scalar;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator *= ( const f32 scalar )
{
x *= scalar;
y *= scalar;
z *= scalar;
w *= scalar;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator *= ( const v4& vec )
{
x *= vec.x;
y *= vec.y;
z *= vec.z;
w *= vec.w;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator /= ( const f32 scalar )
{
assert( scalar != 0.0 );
f32 fInv = f32(1.0) / scalar;
x *= fInv;
y *= fInv;
z *= fInv;
w *= fInv;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4& v4::operator /= ( const v4& vec )
{
x /= vec.x;
y /= vec.y;
z /= vec.z;
w /= vec.w;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v4::operator < ( const v4& rhs ) const
{
if( x < rhs.x && y < rhs.y && z < rhs.z && w < rhs.w)
return true;
return false;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v4::operator > ( const v4& rhs ) const
{
if( x > rhs.x && y > rhs.y && z > rhs.z && w>rhs.w)
return true;
return false;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v4::len () const
{
return sqrt( x * x + y * y + z * z + w * w);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v4::sqlen () const
{
return x * x + y * y + z * z + w * w;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v4::dot(const v4& vec) const
{
return x * vec.x + y * vec.y + z * vec.z + w * vec.w;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v4::norm()
{
f32 fLength = len();
if ( fLength > 1e-08 )
{
f32 fInvLength = f32(1.0) / fLength;
x *= fInvLength;
y *= fInvLength;
z *= fInvLength;
w *= fInvLength;
}
return fLength;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::cross( const v4& vec ) const
{
return v4( w * vec.x - x * vec.w,
y * vec.z - z * vec.y,
z * vec.w - w * vec.z,
x * vec.y - y * vec.x );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::reflect(const v4& normal) const
{
return v4( *this - ( 2 * this->dot(normal) * normal ) );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v4::iszerolen(void) const
{
f32 sqlen = (x * x) + (y * y) + (z * z) + (w * w);
return (sqlen < (1e-06 * 1e-06));
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::up(void) const
{
static const f32 fSquareZero = f32(1e-06 * 1e-06);
v4 perp = this->cross( v4::unitX );
if( perp.sqlen() < fSquareZero )
{
perp = this->cross( v4::unitY );
}
return perp;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v4 v4::mid( const v4& vec ) const
{
return v4( ( x + vec.x ) * f32(0.5),
( y + vec.y ) * f32(0.5),
( z + vec.z ) * f32(0.5),
( w + vec.w ) * f32(0.5) );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void v4::floor( const v4& cmp )
{
if( cmp.x < x ) x = cmp.x;
if( cmp.y < y ) y = cmp.y;
if( cmp.z < z ) z = cmp.z;
if( cmp.w < w ) w = cmp.w;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void v4::ceil( const v4& cmp )
{
if( cmp.x > x ) x = cmp.x;
if( cmp.y > y ) y = cmp.y;
if( cmp.z > z ) z = cmp.z;
if( cmp.w > w ) w = cmp.w;
}
}
#endif
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
511
]
]
] |
324350b2d5cf8a3d17a9695eb0bec76335715adc | 27bf1951e08b36c01374014a6da855a706680f7b | /USACO-Solution/src/2.1.4.cpp | c3d13775b87a992ca1f96fd7a24b0067e0a89d59 | [] | no_license | zinking/algorithm-exercise | 4c520fd3ff6c14804d32e4ea427e5f7809cc7315 | c58902709e9f12146d3d1f66610306e5ff19cfff | refs/heads/master | 2016-09-05T22:27:19.791962 | 2009-07-24T04:45:18 | 2009-07-24T04:45:18 | 32,133,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 983 | cpp | /*
ID: zinking1
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
struct frac {
int e,d;
};
bool check(int,int);
int cmp(const void*,const void*);
int main() {
ifstream fin ("frac1.in");
ofstream fout ("frac1.out");
int n,ans_num=0;
frac ans[25600];
fin >> n;
for (int i=1;i<=n;i++) for (int j=1;j<i;j++) if (check(j,i)) {
ans[++ans_num].e=j;
ans[ans_num].d=i;
}
qsort(&ans[1],ans_num,sizeof(ans[1]),cmp);
fout << "0/1" << endl;
for (int i=1;i<=ans_num;i++) fout << ans[i].e << '/' << ans[i].d << endl;
fout << "1/1" << endl;
fin.close();
fout.close();
return 0;
}
bool check(int a,int b) {
int upperbound = (int)sqrt( static_cast<float>(a) ) + 1;
for (int i=2; i<=a; i++) if (a%i==0 && b%i==0) return false;
return true;
}
int cmp(const void* a,const void* b) {
frac x=*(frac*)a,y=*(frac*)b;
return double(x.e)/x.d>double(y.e)/y.d?1:-1;
}
| [
"zinking3@e423e194-685c-11de-ba0c-230037762ff9"
] | [
[
[
1,
45
]
]
] |
8d1d4dcd3ac40bb479f4a12f1dccff40bf6079fc | 5d35825d03fbfe9885316ec7d757b7bcb8a6a975 | /inc/SceneManager.h | 588d3fa2679637bb442ded167711362c8506bce2 | [] | no_license | jjzhang166/3D-Landscape-linux | ce887d290b72ebcc23386782dd30bdd198db93ef | 4f87eab887750e3dc5edcb524b9e1ad99977bd94 | refs/heads/master | 2023-03-15T05:24:40.303445 | 2010-03-25T00:23:43 | 2010-03-25T00:23:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | h |
class SceneManager
{
public:
SceneManager();
~SceneManager();
void loadScene(char* file);
TGeomInfo* getModel(int modelId);
void render();
private:
TGeomInfo *models;
Object3D* objects;
} | [
"[email protected]"
] | [
[
[
1,
17
]
]
] |
11dd599fcda505d3a94ba62132b60cb14215fb7f | 744e9a2bf1d0aee245c42ee145392d1f6a6f65c9 | /tags/0.11.1-alpha/mpeg2window/ttmpeg2window.h | 338a88bf8d0c6edfb7d5ceb3eb86f007253f8a03 | [] | no_license | BackupTheBerlios/ttcut-svn | 2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a | 958032e74e8bb144a96b6eb7e1d63bc8ae762096 | refs/heads/master | 2020-04-22T12:08:57.640316 | 2009-02-08T16:14:00 | 2009-02-08T16:14:00 | 40,747,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,458 | h | /*----------------------------------------------------------------------------*/
/* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */
/*----------------------------------------------------------------------------*/
/* PROJEKT : TTCUT 2005 */
/* FILE : ttmpeg2window.h */
/*----------------------------------------------------------------------------*/
/* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/23/2005 */
/* MODIFIED: b. altendorf DATE: 03/01/2005 */
/* MODIFIED: b. altendorf DATE: 04/30/2005 */
/* MODIFIED: b. altendorf DATE: 06/22/2005 */
/* MODIFIED: DATE: */
/*----------------------------------------------------------------------------*/
// ----------------------------------------------------------------------------
// *** TTMPEG2WINDOW
// ----------------------------------------------------------------------------
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#ifndef TTMPEG2WINDOW_H
#define TTMPEG2WINDOW_H
#include <QGLWidget>
#include <qdatetime.h>
#include <qimage.h>
#include <QFileDialog>
//#if defined( __TTCUT)
#include "../gui/ttcut.h"
//#else
//#include "ttmpeg2.h"
//#endif
#include "../mpeg2decoder/ttmpeg2decoder.h"
#include "../avstream/ttfilebuffer.h"
#include "../avstream/ttavheader.h"
#include "../avstream/ttvideoheaderlist.h"
#include "../avstream/ttvideoindexlist.h"
#include "../avstream/ttmpeg2videoheader.h"
#include "../avstream/ttmpeg2videostream.h"
class TTMPEG2Window : public QGLWidget
{
Q_OBJECT
public:
TTMPEG2Window( QWidget* parent=0, const char* name=0 );
void openVideoFile( QString fName, TTVideoIndexList* viIndex=NULL, TTVideoHeaderList* viHeader=NULL );
void openVideoStream( TTMpeg2VideoStream* v_stream );
void closeVideoStream();
// navigation
void moveToFirstFrame( bool show = true );
long moveToVideoFrame( long iFramePos, int iFrameType=0 );
void showVideoFrame();
void showFrameAt( uint index );
bool showDecodedSlice();
long currentFrameIndex();
int getVideoWidth();
int getVideoHeight();
int getSceneWidth();
int getSceneHeight();
void saveCurrentFrame( QString fName, const char* format );
protected:
void initializeGL();
void resizeGL( int, int );
void paintGL();
bool decodeAndShowSlice();
protected slots:
void updateFrame();
private:
int iSceneWidth;
int iSceneHeight;
int iVideoWidth;
int iVideoHeight;
int iOldWidth;
int iOldHeight;
bool isResizeAction;
float fAspect;
long currentFrame;
uint8_t* picBuffer;
TFrameInfo* frameInfo;
QString mpeg2FileName;
TTMpeg2Decoder* mpeg2_decoder;
TTVideoIndex* frame_index;
TTVideoIndexList* video_index;
TTVideoHeaderList* video_header;
};
#endif //TTMPEG2WINDOW_H
| [
"tritime@7763a927-590e-0410-8f7f-dbc853b76eaa"
] | [
[
[
1,
114
]
]
] |
a5815809536aa02c434ca0cedc96c42dc1da340e | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/OprnFTPDialogFrm.h | 0b83bd210dc6d8ca38e5c27d2825aba817bc2144 | [] | no_license | sridhar19091986/xmlconvertsql | 066344074e932e919a69b818d0038f3d612e6f17 | bbb5bbaecbb011420d701005e13efcd2265aa80e | refs/heads/master | 2021-01-21T17:45:45.658884 | 2011-05-30T12:53:29 | 2011-05-30T12:53:29 | 42,693,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,120 | h | //---------------------------------------------------------------------------
#ifndef OprnFTPDialogFrmH
#define OprnFTPDialogFrmH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "RzCmboBx.hpp"
#include <ImgList.hpp>
#include "dcOutPanel.hpp"
#include "RzButton.hpp"
#include "RzListVw.hpp"
#include "RzPanel.hpp"
#include "RzShellCtrls.hpp"
#include "RzTreeVw.hpp"
#include <ComCtrls.hpp>
#include <ExtCtrls.hpp>
#include <Graphics.hpp>
#include <Menus.hpp>
#include <ToolWin.hpp>
#include <ActnList.hpp>
#include "RzEdit.hpp"
#include <Mask.hpp>
#include "RzRadChk.hpp"
#include <IdBaseComponent.hpp>
#include <IdComponent.hpp>
#include <IdFTP.hpp>
#include <IdTCPClient.hpp>
#include <IdTCPConnection.hpp>
//---------------------------------------------------------------------------
class TfrmOprnFTPDialog : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;
TImage *Image1;
TLabel *Label3;
TToolBar *ToolBar1;
TToolButton *ToolButton4;
TRzBitBtn *btnCancel;
TRzBitBtn *btnOpen;
TRzPanel *RzPanel1;
TRzComboBox *cbxFileFormat;
TImageList *ImageList2;
TPopupMenu *PopupMenu1;
TMenuItem *menuIcon;
TMenuItem *menuSmall;
TMenuItem *menuList;
TMenuItem *menuDetail;
TRzListView *lvFiles;
TIdFTP *IdFTP1;
TImageList *ImageList3;
TImageList *ImageList4;
TActionList *ActionList1;
TAction *Action1;
TDCHeaderPanel *DCHeaderPanel1;
TSplitter *Splitter1;
TRzTreeView *tvFolder;
TRzEdit *txtServer;
TLabel *Label2;
TRzEdit *txtUserName;
TLabel *Label4;
TRzEdit *txtPassword;
TToolButton *ToolButton2;
TLabel *Label5;
TRzEdit *txtPort;
TRzCheckBox *cbPasv;
void __fastcall menuIconClick(TObject *Sender);
void __fastcall menuSmallClick(TObject *Sender);
void __fastcall menuListClick(TObject *Sender);
void __fastcall menuDetailClick(TObject *Sender);
void __fastcall Action1Execute(TObject *Sender);
void __fastcall btnCancelClick(TObject *Sender);
void __fastcall btnOpenClick(TObject *Sender);
void __fastcall tvFolderChange(TObject *Sender, TTreeNode *Node);
void __fastcall ToolButton2Click(TObject *Sender);
void __fastcall lvFilesColumnClick(TObject *Sender, TListColumn *Column);
void __fastcall FormResize(TObject *Sender);
void __fastcall lvFilesCompare(TObject *Sender, TListItem *Item1,
TListItem *Item2, int Data, int &Compare);
void __fastcall FormDestroy(TObject *Sender);
private: // User declarations
void __fastcall ListDir(TTreeNode * ParentNode);
void __fastcall GetNodePath(TTreeNode * Node,AnsiString & Path);
public: // User declarations
__fastcall TfrmOprnFTPDialog(TComponent* Owner);
AnsiString Path;
TStringList * FileList;
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmOprnFTPDialog *frmOprnFTPDialog;
//---------------------------------------------------------------------------
#endif
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
] | [
[
[
1,
94
]
]
] |
7598371f521f8af4cbf8f8868dd1e60fa6bdab83 | 85c91b680d74357b379204ecf7643ae1423f8d1e | /branches/tri_ext_copis/examples/qos_providers/generic/reservation/QedoQoS_ReservationQoSProvider/QedoQoS_ReservationQoSProvider.cpp | 7f79aec87fab2c3ba55c3b646fd64f447989d120 | [] | no_license | BackupTheBerlios/qedo-svn | 6fdec4ca613d24b99a20b138fb1488f1ae9a80a2 | 3679ffe8ac7c781483b012dbef70176e28fea174 | refs/heads/master | 2020-11-26T09:42:37.603285 | 2010-07-02T10:00:26 | 2010-07-02T10:00:26 | 40,806,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,067 | cpp | //
// generated by Qedo
//
#include "QedoQoS_ReservationQoSProvider.h"
// BEGIN USER INSERT SECTION file
// END USER INSERT SECTION file
namespace QedoQoS {
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl
void
ReservationQoSproviderImpl::register_copis()
{
std::cout << "ReservationQoSProvider: register_copis" << std::endl;
client_interceptor_ = new QedoQoS_Reservation::ClientContainerInterceptor(context_, this);
server_interceptor_ = new QedoQoS_Reservation::ServerContainerInterceptor(context_, this);
//server
Components::Extension::ServerInterceptorRegistration_ptr server_reg =
context_->get_server_interceptor_dispatcher_registration();
server_reg->register_interceptor_for_all(server_interceptor_);
//Client
Components::Extension::ClientInterceptorRegistration_ptr client_reg =
context_->get_client_interceptor_dispatcher_registration();
client_reg->register_interceptor_for_all(client_interceptor_);
//Servant
Components::Extension::ServantInterceptorRegistration_ptr servant_reg =
context_->get_servant_interceptor_dispatcher_registration();
servant_reg->register_interceptor_for_all(server_interceptor_);
//Stub
Components::Extension::StubInterceptorRegistration_ptr stub_reg =
context_ -> get_stub_interceptor_dispatcher_registration();
stub_reg -> register_interceptor_for_all(client_interceptor_);
}
void
ReservationQoSproviderImpl::unregister_copis()
{
std::cout << "ReservationQoSProvider: unregister_copis" << std::endl;
//server
Components::Extension::ServerInterceptorRegistration_ptr server_reg =
context_->get_server_interceptor_dispatcher_registration();
server_reg->unregister_interceptor_for_all(server_interceptor_);
//Client
Components::Extension::ClientInterceptorRegistration_ptr client_reg =
context_->get_client_interceptor_dispatcher_registration();
client_reg->register_interceptor_for_all(client_interceptor_);
//Servant
Components::Extension::ServantInterceptorRegistration_ptr servant_reg =
context_->get_servant_interceptor_dispatcher_registration();
servant_reg->register_interceptor_for_all(server_interceptor_);
//Stub
Components::Extension::StubInterceptorRegistration_ptr stub_reg =
context_ -> get_stub_interceptor_dispatcher_registration();
stub_reg -> unregister_interceptor_for_all(client_interceptor_);
}
void
ReservationQoSproviderImpl::init_copis(Components::ConfigValues* config)
{
CORBA::Any test_any;
std::cout << "length of config values: " << config->length() << std::endl;
char* req_component_id;
char* req_operation_name;
Components::ConfigValues* data;
// search for extensionspecification
CORBA::ULong len;
for (len = 0; len < config->length(); len++)
{
if (!strcmp((*config)[len]->name(),"extensionspecification"))
{
Components::ConfigValues *extension_content;
Components::ConfigValue *extension_content_test;
CORBA::Any test_any;
test_any = ((*config)[len]-> value()) ;
// ((*config)[len]-> value()) >>= test_any;
test_any >>= extension_content;
CORBA::ULong ext_len;
for (ext_len = 0; ext_len < extension_content->length(); ext_len++)
{
// search for binding
if ( !strcmp((*extension_content)[ext_len]->name(), "binding"))
{
Components::ConfigValues *binding_content;
((*extension_content)[ext_len]-> value()) >>= binding_content ;
CORBA::ULong binding_len;
for (binding_len = 0; binding_len < binding_content->length(); binding_len++)
{
// search for component_id
if (!strcmp((*binding_content)[binding_len]->name(), "componentid"))
{
((*binding_content)[binding_len]-> value()) >>= req_component_id;
} // end of component_id
// search for restriction
if (!strcmp((*binding_content)[binding_len]->name(), "restriction"))
{
((*binding_content)[binding_len]-> value()) >>= req_operation_name;
} // end of restriction
} // end of binding search
} // end serach for binding
//search for constraint
if ( !strcmp((*extension_content)[ext_len]->name(), "constraint"))
{
Components::ConfigValues *constraint_content;
Components::ConfigValue *test;
((*extension_content)[ext_len]-> value()) >>= constraint_content ;
CORBA::ULong constraint_len;
for (constraint_len = 0; constraint_len < constraint_content->length(); constraint_len++)
{
// search for charakteristic
if ( !strcmp((*constraint_content)[constraint_len]->name(), "characteristic"))
{
// only search for reservation
// first element of content needs to be a name=Reservation
Components::ConfigValues *characteristic_content;
//((*constraint_content)[constraint_len]-> value()) >>= characteristic_content ;
CORBA::Any *test2_any = new CORBA::Any((*constraint_content)[constraint_len] -> value()) ;
*test2_any >>= data;//constraint_content;
char* char_name;
if ( !strcmp((*data)[0]->name(), "name"))
{
((*data)[0]-> value()) >>= char_name;
if (!strcmp(char_name,"Reservation"))
{
// ((*constraint_content)[constraint_len]-> value()) >>= data;
//data = characteristic_content;
} // end if Reservation
} // end name
} // end of if characteristic
}
}
} // end of for extension_content
server_interceptor_ -> register_requirement(req_component_id, req_operation_name, data);
} // end of if extensionspecification
} // end of extensionspecification search
}
// END USER INSERT SECTION ReservationQoSproviderImpl
ReservationQoSproviderImpl::ReservationQoSproviderImpl()
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::ReservationQoSproviderImpl
// END USER INSERT SECTION ReservationQoSproviderImpl::ReservationQoSproviderImpl
}
ReservationQoSproviderImpl::~ReservationQoSproviderImpl()
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::~ReservationQoSproviderImpl
// END USER INSERT SECTION ReservationQoSproviderImpl::~ReservationQoSproviderImpl
}
void
ReservationQoSproviderImpl::set_context(::QedoQoS::CCM_Reservation_ContextImpl_ptr context)
throw (CORBA::SystemException, Components::CCMException)
{
context_ = ::QedoQoS::CCM_Reservation_ContextImpl::_duplicate(context);
}
void
ReservationQoSproviderImpl::configuration_complete()
throw (CORBA::SystemException, Components::InvalidConfiguration)
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::configuration_complete
// create interceptors
//register interceptors
// END USER INSERT SECTION ReservationQoSproviderImpl::configuration_complete
}
void
ReservationQoSproviderImpl::remove()
throw (CORBA::SystemException)
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::remove
// END USER INSERT SECTION ReservationQoSproviderImpl::remove
}
void
ReservationQoSproviderImpl::trigger_negotiation()
throw(CORBA::SystemException)
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::trigger_negotiation
// END USER INSERT SECTION ReservationQoSproviderImpl::trigger_negotiation
}
Components::Extension::ContractDescription*
ReservationQoSproviderImpl::req_offer(const Components::Extension::ContractDescription& requirements, const char* client_id)
throw(CORBA::SystemException)
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::req_offer
std::cout << "@@@@@@@@ got req_contract" << std::endl;
// check for availability
// create offer
// store offer information and reserver resources for the offer
// return offer
return new Components::Extension::ContractDescription(requirements);
// END USER INSERT SECTION ReservationQoSproviderImpl::req_offer
}
CORBA::Boolean
ReservationQoSproviderImpl::accept(const Components::Extension::ContractDescription& requirements, const char* client_id)
throw(CORBA::SystemException)
{
// BEGIN USER INSERT SECTION ReservationQoSproviderImpl::accept
std::cout << "@@@@@@@@ got accept" << std::endl;
// check for offer reservation
// use ressources
// store contract info
server_interceptor_ -> add_contract(client_id, requirements.dimensions);
// return an identfier
// true meanwhile
return true;
// END USER INSERT SECTION ReservationQoSproviderImpl::accept
}
// BEGIN USER INSERT SECTION ReservationQoSProvider
// END USER INSERT SECTION ReservationQoSProvider
ReservationQoSProvider::ReservationQoSProvider()
:component_(new ReservationQoSproviderImpl())
{
// BEGIN USER INSERT SECTION ReservationQoSProvider::ReservationQoSProvider
// END USER INSERT SECTION ReservationQoSProvider::ReservationQoSProvider
}
ReservationQoSProvider::~ReservationQoSProvider()
{
// BEGIN USER INSERT SECTION ReservationQoSProvider::~ReservationQoSProvider
// END USER INSERT SECTION ReservationQoSProvider::~ReservationQoSProvider
component_->_remove_ref();
}
::CORBA::Object*
ReservationQoSProvider::obtain_executor(const char* name)
throw (CORBA::SystemException)
{
if (! strcmp ( name, "component" ) ) {
return Components::EnterpriseComponent::_duplicate (component_);
}
else if (! strcmp (name, "nego_external")) {
return Components::EnterpriseComponent::_duplicate (component_);
}
return Components::EnterpriseComponent::_nil();
}
void
ReservationQoSProvider::release_executor(::CORBA::Object_ptr executor)
throw (CORBA::SystemException)
{
CORBA::release (executor);
}
void
ReservationQoSProvider::configuration_complete()
throw (CORBA::SystemException, Components::InvalidConfiguration)
{
component_->configuration_complete();
// BEGIN USER INSERT SECTION ReservationQoSProvider::configuration_complete
// END USER INSERT SECTION ReservationQoSProvider::configuration_complete
}
void
ReservationQoSProvider::set_extension_context(::Components::ExtensionContext_ptr context)
throw (CORBA::SystemException, Components::CCMException)
{
#ifdef TAO_ORB
::QedoQoS::CCM_Reservation_Context_ptr tmp_context;
tmp_context = dynamic_cast<::QedoQoS::CCM_Reservation_ContextImpl*>(context);
if (tmp_context)
context_ = ::QedoQoS::CCM_Reservation_ContextImpl::_duplicate(tmp_context);
else
context_ = ::QedoQoS::CCM_Reservation_ContextImpl::_nil();
#else
context_ = ::QedoQoS::CCM_Reservation_ContextImpl::_narrow(context);
#endif
component_->set_context(context_);
}
void
ReservationQoSProvider::ccm_activate()
throw (CORBA::SystemException, Components::CCMException)
{
// BEGIN USER INSERT SECTION ReservationQoSProvider::ccm_activate
component_ -> register_copis();
component_ -> init_copis(context_ -> get_contract_data());
// END USER INSERT SECTION ReservationQoSProvider::ccm_activate
}
void
ReservationQoSProvider::ccm_passivate()
throw (CORBA::SystemException, Components::CCMException)
{
// BEGIN USER INSERT SECTION ReservationQoSProvider::ccm_passivate
component_ -> unregister_copis();
// END USER INSERT SECTION ReservationQoSProvider::ccm_passivate
}
void
ReservationQoSProvider::ccm_remove()
throw (CORBA::SystemException, Components::CCMException)
{
// BEGIN USER INSERT SECTION ReservationQoSProvider::ccm_remove
// END USER INSERT SECTION ReservationQoSProvider::ccm_remove
}
// BEGIN USER INSERT SECTION ReservationQoSProviderHomeImpl
// END USER INSERT SECTION ReservationQoSProviderHomeImpl
ReservationQoSProviderHomeImpl::ReservationQoSProviderHomeImpl()
{
// BEGIN USER INSERT SECTION ReservationQoSProviderHomeImpl::ReservationQoSProviderHomeImpl
// END USER INSERT SECTION ReservationQoSProviderHomeImpl::ReservationQoSProviderHomeImpl
}
ReservationQoSProviderHomeImpl::~ReservationQoSProviderHomeImpl()
{
// BEGIN USER INSERT SECTION ReservationQoSProviderHomeImpl::~ReservationQoSProviderHomeImpl
// END USER INSERT SECTION ReservationQoSProviderHomeImpl::~ReservationQoSProviderHomeImpl
}
void
ReservationQoSProviderHomeImpl::set_context(Components::HomeContext_ptr ctx)
throw (CORBA::SystemException, Components::CCMException)
{
context_ = Components::HomeContext::_duplicate(ctx);
}
::Components::EnterpriseComponent_ptr
ReservationQoSProviderHomeImpl::create ()
throw (CORBA::SystemException, Components::CreateFailure)
{
// BEGIN USER INSERT SECTION ReservationQoSProviderHomeImpl::create
// END USER INSERT SECTION ReservationQoSProviderHomeImpl::create
return new ReservationQoSProvider();
}
};
//
// entry point
//
::Components::HomeExecutorBase_ptr
create_ReservationHomeE(void)
{
// BEGIN USER INSERT SECTION create_ReservationHome
// END USER INSERT SECTION create_ReservationHome
return new ::QedoQoS::ReservationQoSProviderHomeImpl();
}
| [
"tom@798282e8-cfd4-0310-a90d-ae7fb11434eb"
] | [
[
[
1,
416
]
]
] |
cce07d0897371eb6dde498df0cf458943af4d442 | 07516ffece1a546440e34d71281d2073d1526089 | /workspace/teste/SearchTree/Object.cpp | b6d358d714ee8cc085cadfa2ac1ff73077efd97c | [] | no_license | jcvitorino/repositorio | a10ef2beba58072a720e06f6dae327d3fb991137 | cd5a8df7d42c2740c08b2f9a113979825b7464a3 | refs/heads/master | 2021-01-01T16:55:20.602680 | 2011-10-26T00:06:01 | 2011-10-26T00:06:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include "Object.h"
#include <typeinfo>
Object::~Object ()
{}
bool Object::IsNull () const
{ return false; }
int Object::Compare (Object const& object) const
{
if (typeid (*this) == typeid (object))
return CompareTo (object);
else if (typeid (*this).before (typeid (object)))
return -1;
else
return 1;
}
| [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
12fa9ee02692c6ed40492d30a3c7da2fcf140ba3 | d8a93d1a0152abf719b6d614a1871f7a65a940ba | /MovieVis/src/UiHandler.cpp | 04d3e5b01a31f12ae43d0e48abd14001c6a219e0 | [] | no_license | awshepard/movievis | be0d732e2e54d60ed1a31cd7c67e4ea6d26b0f5a | 079432ec45baa98d67d976b28c14cd96116760c6 | refs/heads/master | 2021-01-18T22:35:58.479908 | 2010-07-09T04:48:33 | 2010-07-09T04:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,684 | cpp | /**
* \file UiHandler.cpp
* \author Douglas W. Paul and Adam Shepard
*
* Defines the behavior for the UiHandler class
*/
#include "UiHandler.hpp"
/**
* \param app A pointer to the application to control
*/
UiHandler::UiHandler(Application *app) {
this->app = app;
this->leftMouseButtonDown = false;
this->rightMouseButtonDown = false;
this->minDistanceStep = 0.0001;
this->distanceRatio = 0.05;
this->mouseSensitivity = 0.0625;
}
UiHandler::~UiHandler() {}
void UiHandler::bindKeys() {
shared_ptr<Engine> engine(this->app->getEngine());
engine->bindKey(SDLK_ESCAPE, MV_EXIT);
engine->bindKey(SDLK_UP, MV_MOVE_NORTH);
engine->bindKey(SDLK_e, MV_MOVE_NORTH);
engine->bindKey(SDLK_DOWN, MV_MOVE_SOUTH);
engine->bindKey(SDLK_d, MV_MOVE_SOUTH);
engine->bindKey(SDLK_LEFT, MV_MOVE_WEST);
engine->bindKey(SDLK_s, MV_MOVE_WEST);
engine->bindKey(SDLK_RIGHT, MV_MOVE_EAST);
engine->bindKey(SDLK_f, MV_MOVE_EAST);
engine->bindKey(SDLK_PAGEUP, MV_MOVE_DOWN);
engine->bindKey(SDLK_PAGEDOWN, MV_MOVE_UP);
engine->bindKey(SDLK_SPACE, MV_UNBRUSH);
}
/**
* @param action The action to take
*/
void UiHandler::handleCustomEvent(int customEvent) {
switch (customEvent) {
case MV_EXIT: // Quit (ESC)
exit(0);
case MV_MOVE_NORTH: // Increase camera's latitude
this->app->getModel()->getCameraRigging()->changeY(getXYStep());
this->app->getEngine()->invalidate();
break;
case MV_MOVE_SOUTH: // Decrease camera's latitude
this->app->getModel()->getCameraRigging()->changeY(-getXYStep());
this->app->getEngine()->invalidate();
break;
case MV_MOVE_WEST: // Decrease camera's longitude
this->app->getModel()->getCameraRigging()->changeX(-getXYStep());
this->app->getEngine()->invalidate();
break;
case MV_MOVE_EAST: // Increase camera's longitude
this->app->getModel()->getCameraRigging()->changeX(getXYStep());
this->app->getEngine()->invalidate();
break;
case MV_MOVE_UP: // Increase camera's height
this->app->getModel()->getCameraRigging()->changeHeight(getHeightStep());
this->app->getEngine()->invalidate();
break;
case MV_MOVE_DOWN: // Decrease camera's height
this->app->getModel()->getCameraRigging()->changeHeight(-getHeightStep());
this->app->getEngine()->invalidate();
break;
case MV_UNBRUSH:
this->app->getModel()->setBrushedActor(optional<shared_ptr<Person>>());
this->app->getModel()->setBrushedMovie(optional<shared_ptr<Movie>>());
break;
default: break;
}
}
/*!
* @param buttonEvent The button event
*/
void UiHandler::handleMouseButtonEvent(const SDL_MouseButtonEvent &buttonEvent) {
const int button = buttonEvent.button;
const int state = buttonEvent.state;
const int x = buttonEvent.x;
const int y = buttonEvent.y;
if (button == SDL_BUTTON_LEFT) {
if (state == SDL_PRESSED) {
this->app->getModelRenderer()->brush(x, y);
}
} else if (button == SDL_BUTTON_RIGHT) {
if (state == SDL_PRESSED) {
// Begin dragging
this->rightMouseButtonDown = true;
SDL_ShowCursor(SDL_DISABLE);
SDL_WM_GrabInput(SDL_GRAB_ON);
this->isFirstDelta = true;
} else {
// End dragging
this->rightMouseButtonDown = false;
SDL_ShowCursor(SDL_ENABLE);
SDL_WM_GrabInput(SDL_GRAB_OFF);
}
} else if (button == SDL_BUTTON_WHEELUP) {
// Move camera down ("zoom in")
this->app->getModel()->getCameraRigging()->changeHeight(-getHeightStep());
this->app->getEngine()->invalidate();
} else if (button == SDL_BUTTON_WHEELDOWN) {
// Move camera up ("zoom out")
this->app->getModel()->getCameraRigging()->changeHeight(getHeightStep());
this->app->getEngine()->invalidate();
}
}
/*!
* @param motionEvent The motion event
*/
void UiHandler::handleMouseMotionEvent(const SDL_MouseMotionEvent &motionEvent) {
unsigned int mouseX = motionEvent.x;
unsigned int mouseY = motionEvent.y;
int mouseDX = motionEvent.xrel;
int mouseDY = motionEvent.yrel;
double step = getXYStep();
if (this->rightMouseButtonDown == true) {
if (this->isFirstDelta == true) {
this->isFirstDelta = false;
return;
}
double dX = (double) mouseDX * (-step) * this->mouseSensitivity;
double dY = (double) mouseDY * step * this->mouseSensitivity;
this->app->getModel()->getCameraRigging()->changeGroundPoint(dX, dY);
this->app->getEngine()->invalidate();
this->app->getModel()->setSelectedActor(optional<shared_ptr<Person>>());
this->app->getModel()->setSelectedMovie(optional<shared_ptr<Movie>>());
}
else {
this->app->getModelRenderer()->pick(mouseX, mouseY);
this->app->getEngine()->invalidate();
}
this->app->getModel()->setMouseXY(mouseX, mouseY);
}
/*!
* @param sizeX The new x-size of the window
* @param sizeY The new y-size of the window
*/
void UiHandler::handleResizeEvent(int sizeX, int sizeY) {
this->app->getModel()->getCamera()->setAspectRatio((double)sizeX/(double)sizeY);
this->app->getEngine()->invalidate();
}
/**
* We calculate the change in height based on the current height.
*
* \return The increment to move up or down
*/
double UiHandler::getXYStep() {
double distanceStep = this->app->getModel()->getCameraRigging()->getHeight() * this->distanceRatio;
return max(distanceStep, this->minDistanceStep);
}
/**
* We calculate the change in height based on the current height.
*
* \return The increment to move up or down
*/
double UiHandler::getHeightStep() {
double distanceStep = this->app->getModel()->getCameraRigging()->getHeight() * this->distanceRatio;
return max(distanceStep, this->minDistanceStep);
}
| [
"douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9"
] | [
[
[
1,
179
]
]
] |
675d1f889b7c92ac99073babd3fe65d43baefeec | f7d8a85f9d0c1956d64efbe96d056e338b0e0641 | /Src/DLManager.cpp | b1c6d5e1a25f8653c0c0bd9b4f9df57023adf7d8 | [] | no_license | thennequin/dlfm | 6183dfeb485f860396573eda125fd61dcd497660 | 0b122e7042ec3b48660722e2b41ef0a0551a70a9 | refs/heads/master | 2020-04-11T03:53:12.856319 | 2008-07-06T10:17:29 | 2008-07-06T10:17:29 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 15,647 | cpp | #include <curl\curl.h>
#include <wx/listctrl.h>
#include "DLManager.h"
#include "FileDownloader.h"
#include "FreeFileDownloader.h"
#include "MainWindow.h"
#include "FilePage.h"
#include "error.h"
DLManager::DLManager(Config *config)
{
wxLogMessage("Download Manager Initialisation");
mConfig = config;
//mConfig=NULL;
curl_global_init(CURL_GLOBAL_ALL);
mMain=NULL;
List.Clear();
LoadDownloads();
if (mConfig)
{
MaxRetry = mConfig->ReadIntValue("MaxRetry",3);
RetryTime = mConfig->ReadIntValue("RetryTime",90);
MaxDL = mConfig->ReadIntValue("MaxDL",3);
if (mConfig->ReadIntValue("StartDownload",0))
{
int DLCount=0;
for (int i=List.Count()-1;i>=0;i--)
{
if ( List[i]->GetStatus()!=FileDownloader::FFD_FINISH)
{
if (DLCount<MaxDL)
{
List[i]->StartDownload();
DLCount++;
}else
List[i]->SetStatus(FileDownloader::FFD_WAIT);
}
}
}
}
UpdateScreen(true);
Time = GetTickCount();
}
DLManager::~DLManager()
{
}
bool DLManager::AddDownload(wxString link,wxString filename)
{
if (!link || !filename)
return false;
FileDownloader *temp;
bool exist=false;
for (int i=0;i<List.Count();i++)
{
temp = (FileDownloader*)List[i];
if (temp!=NULL && (temp->GetLink()==link || temp->GetFilename()==filename))
{
exist=true;
break;
}
}
wxLogDebug("Exist : %d",exist);
if (exist)
return false;
FileDownloader *download=NULL;
if (Parser::IsFreeLink(link))
download = new FreeFileDownloader(link,filename,this);
else
download = new FileDownloader(link,filename,this);
if (!download)
return false;
if (/*download->GetStatus()==FileDownloader::FFD_ERROR ||*/ download->IsOK()==false)
{
delete download;
return false;
}
//wxLogMessage("adr %d",download);
//wxLogMessage("%s",download->GetLink());
List.Add(download);
mMain->GetNotebook()->InsertPage(1,new FilePage(mMain->GetNotebook()),download->GetFilename());
//download->SetItemId(itemId);
//download->StartDownload();
UpdateScreen(true);
return true;
}
void DLManager::UpdateScreen(bool force)
{
if (GetTickCount()-Time<1000 && force==false)
return;
//wxLogMessage("Language %s",STARTDOWNLOAD);
int DLCount=0;
for (int i=0;i<List.Count();i++)
{
FileDownloader *temp = (FileDownloader*)List[i];
if (temp)
if (temp->GetStatus()==FileDownloader::FFD_RETRY)
{
if (GetTickCount()-temp->GetErrorTime()>=RetryTime*1000)
{
wxLogMessage("Retry %d %d",temp->RetryCount,GetTickCount()-temp->GetErrorTime());
temp->RetryCount++;
StartDownload(temp,false,true);
}
}
}
for (int i=0;i<List.Count();i++)
{
FileDownloader *temp = (FileDownloader*)List[i];
if (temp)
if (temp->GetStatus()==FileDownloader::FFD_START || temp->GetStatus()==FileDownloader::FFD_RETRY)
{
DLCount++;
}
}
if (DLCount<MaxDL)
for (int i=List.Count()-1;i>=0;i--)
{
FileDownloader *temp = (FileDownloader*)List[i];
if (temp)
if (temp->GetStatus()==FileDownloader::FFD_WAIT
/*|| temp->GetStatus()==FileDownloader::FFD_RETRY*/)
{
if (temp->IsRunning()==false)
{
temp->StartDownload();
DLCount++;
if (DLCount>=MaxDL)
break;
}
}
}
Time = GetTickCount();
long item;
bool grey=false;
wxString text;
//wxLogDebug("UdateScreen");
if (mMain && mMain->GetListCtrl()!=NULL)
{
//wxLogDebug("UdateScreen2");
int selected = -1/*mMain->GetListCtrl()->GetTopItem()*/;
//wxLogMessage("Count %d %d",mMain->GetListCtrl()->GetItemCount(),List.Count());
if (mMain->GetListCtrl()->GetItemCount()==List.Count()/*-1*/)
{ // Update
for (int long i=1;i<=List.Count();i++)
{
}
for (int long i=0;i<mMain->GetListCtrl()->GetItemCount();i++)
{
}
}else{ // Delete all list link and update
mMain->GetListCtrl()->DeleteAllItems();
wxLogDebug("Count %d %d",mMain->GetNotebook()->GetPageCount(),List.Count());
bool Deleted=false;
if (mMain->GetNotebook()->GetPageCount()!=List.Count()+1)
{
Deleted=true;
wxLogDebug("Delete pages");
for (;1<mMain->GetNotebook()->GetPageCount();)
mMain->GetNotebook()->DeletePage(1);
}
}
//return;
long TotalSpeed=0;
for (int i=0 ; i<List.Count();i++)
{
FileDownloader *tmp = (FileDownloader*)List[i];
if (!tmp)
continue;
//wxLogMessage("Update %s",tmp->GetFilename());
UpdateOnce(tmp,grey);
TotalSpeed+=tmp->GetMoySpeed();
grey=!grey;
}
text.Printf("Total speed : %.1f Kb/s",TotalSpeed/1000.0);
mMain->SetStatusText(text);
}
}
void DLManager::UpdateOnce(FileDownloader *dl,bool grey)
{
if (!dl)
return;
FileDownloader *tmp = dl;
wxString text;
if (tmp)
{
long item=-1;
for (int long i=0;i<mMain->GetListCtrl()->GetItemCount();i++)
{
//wxLogMessage(mMain->GetListCtrl()->GetItemText(i));
if (mMain->GetListCtrl()->GetItemText(i)==dl->GetFilename())
{
item=i;
}
}
if (item==-1)
{
item = mMain->GetListCtrl()->InsertItem(0,tmp->GetFilename());
//wxLogDebug("Insert Item");
}
if (tmp->GetFileSize()==-2)
text.Printf("");
else if (tmp->GetFileSize()==-1)
text.Printf("??");
else
text.Printf("%I64d",tmp->GetFileSize());
mMain->GetListCtrl()->SetItem(item,1,text);
if (tmp->GetDownloadedSize()==0)
text.Printf("");
else
text.Printf("%I64d",tmp->GetDownloadedSize());
mMain->GetListCtrl()->SetItem(item,2,text);
//tmp->GetFileSize()/tmp->GetDownloadedSize();
if (tmp->GetFileSize()==-1 || tmp->GetFileSize()==-2)
text.Printf("");
else
text.Printf("%.2f",((float)tmp->GetDownloadedSize()/tmp->GetFileSize())*100);
mMain->GetListCtrl()->SetItem(item,3,text);
switch (tmp->GetStatus())
{
case FileDownloader::FFD_START:
text.Printf("Start");
mMain->GetListCtrl()->SetItemImage(item,0);
break;
case FileDownloader::FFD_STOP:
text.Printf("Stop");
mMain->GetListCtrl()->SetItemImage(item,1);
break;
case FileDownloader::FFD_WAIT:
text.Printf("Wait");
mMain->GetListCtrl()->SetItemImage(item,3);
break;
case FileDownloader::FFD_ERROR:
text.Printf("%s",ERROR_DESC[tmp->GetErrorCode()]);
mMain->GetListCtrl()->SetItemImage(item,2);
break;
case FileDownloader::FFD_RETRY:
text.Printf("Retry n°%d dans %d secondes : %s",tmp->RetryCount,RetryTime-(GetTickCount()-tmp->GetErrorTime())/1000,ERROR_DESC[tmp->GetErrorCode()]);
mMain->GetListCtrl()->SetItemImage(item,0);
break;
case FileDownloader::FFD_FINISH:
text.Printf("Finish");
mMain->GetListCtrl()->SetItemImage(item,4);
break;
default:
text.Printf("");
}
mMain->GetListCtrl()->SetItem(item,4,text);
text.Printf("%.1f Kb/s",tmp->GetMoySpeed()/1000);
mMain->GetListCtrl()->SetItem(item,5,text);
if (tmp->GetFileSize()>0
&& tmp->GetMoySpeed()>0)
{
long TimeRemaining = (tmp->GetFileSize()-tmp->GetDownloadedSize())/tmp->GetMoySpeed();
float TempTime=TimeRemaining/3600;
long Hours = TempTime;
if (TempTime-Hours>0)
Hours--;
long Minutes=0;
long Seconds=0;
text.Printf("%d:%2d:%2d",Hours,Minutes,Seconds);
}else
text.Printf("??:??:??");
mMain->GetListCtrl()->SetItem(item,6,text);
mMain->GetListCtrl()->SetItem(item,7,tmp->GetLink());
mMain->GetListCtrl()->SetItemBackgroundColour(item,grey==true ? wxColor(224,224,224) : wxColor(255,255,255));
//if (List.Count()-i-1==selected)
//mMain->GetListCtrl()->SetItemState(item,wxLIST_STATE_SELECTED,wxLIST_STATE_SELECTED);
/*if (Deleted)
{
mMain->GetNotebook()->InsertPage(1,new FilePage(mMain->GetNotebook()),tmp->GetFilename());
}else*/{
for (int j=1;j<mMain->GetNotebook()->GetPageCount();j++)
{
if (mMain->GetNotebook()->GetPageText(j) == tmp->GetFilename())
{
FilePage *page = (FilePage*)mMain->GetNotebook()->GetPage(j);
page->SetGaugeValue((float)tmp->GetDownloadedSize()/tmp->GetFileSize()*100.0);
page->SetFileSize(tmp->GetFileSize());
page->SetDownloadedSize(tmp->GetDownloadedSize());
if (mConfig)
page->SetBlockSize(mConfig->ReadIntValue("BlockSize",2048));
page->Refresh();
break;
}
}
}
/*tmp->pMutex->Unlock();*/
//tmp->Resume();
}
FilePage *page=NULL;
for (int j=1;j<mMain->GetNotebook()->GetPageCount();j++)
{
if (mMain->GetNotebook()->GetPageText(j) == tmp->GetFilename())
{
page = (FilePage*)mMain->GetNotebook()->GetPage(j);
break;
}
}
if (page==NULL)
{
mMain->GetNotebook()->InsertPage(1,new FilePage(mMain->GetNotebook()),tmp->GetFilename());
for (int j=1;j<mMain->GetNotebook()->GetPageCount();j++)
{
if (mMain->GetNotebook()->GetPageText(j) == tmp->GetFilename())
{
page = (FilePage*)mMain->GetNotebook()->GetPage(j);
break;
}
}
}
if (page)
{
page->SetGaugeValue((float)tmp->GetDownloadedSize()/tmp->GetFileSize()*100.0);
page->SetFileSize(tmp->GetFileSize());
page->SetDownloadedSize(tmp->GetDownloadedSize());
if (mConfig)
page->SetBlockSize(mConfig->ReadIntValue("BlockSize",2048));
page->Refresh();
}
}
void DLManager::UpdateBlocks(FileDownloader *tmp)
{
if (tmp)
for (int j=1;j<mMain->GetNotebook()->GetPageCount();j++)
{
if (mMain->GetNotebook()->GetPageText(j) == tmp->GetFilename())
{
FilePage *page = (FilePage*)mMain->GetNotebook()->GetPage(j);
//page->SetGaugeValue((float)tmp->GetDownloadedSize()/tmp->GetFileSize()*100.0);
page->SetFileSize(tmp->GetFileSize());
page->SetDownloadedSize(tmp->GetDownloadedSize());
//if (mConfig)
//page->SetBlockSize(mConfig->ReadIntValue("BlockSize",2048));
page->Refresh();
break;
}
}
}
void DLManager::StartDownload(wxString link)
{
FileDownloader *temp;
bool Found=false;
for (int i=0;i<List.Count();i++)
{
temp = (FileDownloader*)List[i];
if (!temp)
continue;
//wxLogDebug("Mutex OK %d",temp->pMutex->IsOk());
/*temp->pMutex->Lock();*/
wxLogDebug("Mutex Lock");
if (temp!=NULL && temp->GetFilename()==link)
{
if (temp->GetStatus()!=FileDownloader::FFD_START
&& temp->GetStatus()!=FileDownloader::FFD_WAIT
&& temp->GetStatus()!=FileDownloader::FFD_RETRY
&& temp->GetStatus()!=FileDownloader::FFD_FINISH)
{
StartDownload(temp,true);
}
UpdateScreen(true);
Found=true;
//break;
}
/*temp->pMutex->Unlock();*/
if (Found)
break;
}
}
void DLManager::StartDownload(FileDownloader *dl,bool ResetRetyCount, bool force)
{
wxLogMessage("StartDownload FileDL");
if (dl==NULL)
return;
int i=-1;
int DLCount=0;
for (int j=0;j<List.Count();j++)
{
FileDownloader *temp = (FileDownloader*)List[j];
if (temp)
{
if (temp==dl)
i=j;
if (temp->GetStatus()!=FileDownloader::FFD_START
/*|| temp->GetStatus()==FileDownloader::FFD_RETRY*/)
{
DLCount++;
}
}
}
if (i==-1)
return;
//if (dl->IsRunning())
//return;
if (ResetRetyCount)
dl->RetryCount=0;
if (dl->AlreadyRun())
{
/*dl->pMutex->Unlock();*/
if (dl->GetClass()=="FreeFileDownloader")
List[i] = new FreeFileDownloader(*dl);
else
List[i] = new FileDownloader(*dl);
delete dl;
dl = List[i];
/*dl->pMutex->Lock();*/
}
if (DLCount>=MaxDL && !force)
{
//wxLogMessage("Set status");
dl->SetStatus(FileDownloader::FFD_WAIT);
}else{
//wxLogMessage("Start Download");
/*if (dl->RetryCount>=MaxRetry)
{
dl->SetStatus(FileDownloader::FFD_ERROR);
}else*/
dl->StartDownload();
}
}
void DLManager::StopDownload(wxString link,bool update)
{
wxLogMessage("StartDownload String");
FileDownloader *temp;
bool Found=false;
for (int i=0;i<List.Count();i++)
{
temp = (FileDownloader*)List[i];
if (!temp)
continue;
if (temp/* && temp->pMutex && temp->pMutex->IsOk()*/)
{
/*temp->pMutex->Lock();*/
if (temp!=NULL && temp->GetFilename()==link)
{
if (temp->GetStatus()!=FileDownloader::FFD_FINISH)
{
temp->StopDownload();
if (update)
UpdateScreen(true);
}
Found=true;
}
/*temp->pMutex->Unlock();*/
}
if (Found)
break;
}
}
void DLManager::DeleteDownload(wxString link,bool update)
{
FileDownloader *temp;
bool Found=false;
for (int i=0;i<List.Count();i++)
{
FileDownloader *temp = (FileDownloader*)List[i];
if (!temp)
continue;
if (temp/* && temp->pMutex && temp->pMutex->IsOk()*/)
{
/*temp->pMutex->Lock();*/
if (temp!=NULL && temp->GetFilename()==link)
{
temp->StopDownload();
Found=true;
List.Remove(temp);
for (int i=1;i<mMain->GetNotebook()->GetPageCount();i++)
{
if (mMain->GetNotebook()->GetPageText(i) == temp->GetFilename())
{
mMain->GetNotebook()->DeletePage(i);
break;
}
}
/*temp->pMutex->Unlock();*/
delete temp;
if (update)
UpdateScreen(true);
}
}
if (Found)
break;
}
}
void DLManager::LoadDownloads()
{
FILE *file=fopen("downloads.cfg","rb");
if (file)
{
/*fseek(file,0,SEEK_END);
if (ftell(file)==0)
return;*/
long Count;
fread(&Count,sizeof(long),1,file);
wxString text;
curl_off_t Size;
char buffer[256*256];
FileDownloader *temp=NULL;
for (int i=0;i<Count;i++)
{
Size=0;
fread(&Size,sizeof(char),1,file);
if (Size==DL_HTTP)
temp = new FileDownloader("","",this);
else if (Size==DL_FREE)
temp = new FreeFileDownloader("","",this);
if (temp==NULL)
return;
Size=0;
fread(&Size,sizeof(short),1,file);
fread(buffer,sizeof(char),Size,file);
text="";
text.append(buffer,Size);
temp->SetLink(text);
Size=0;
fread(&Size,sizeof(short),1,file);
fread(buffer,sizeof(char),Size,file);
text="";
text.append(buffer,Size);
temp->SetFilename(text);
fread(&Size,sizeof(curl_off_t),1,file);
temp->SetFileSize(Size);
fread(&Size,sizeof(curl_off_t),1,file);
temp->SetDownloadedSize(Size);
if (temp->GetFileSize()==temp->GetDownloadedSize())
temp->SetStatus(FileDownloader::FFD_FINISH);
List.Add(temp);
}
fclose(file);
}
}
void DLManager::SaveDownloads()
{
FILE *file=fopen("downloads.cfg","wb");
if (file)
{
long Count = List.Count();
fwrite(&Count,sizeof(long),1,file);
curl_off_t Size;
FileDownloader *temp;
for (int i=0;i<List.Count();i++)
{
FileDownloader *temp = (FileDownloader*)List[i];
if (temp==NULL)
continue;
Size=0;
if (temp->GetClass()=="FileDownloader")
Size=DL_HTTP;
else if (temp->GetClass()=="FreeFileDownloader")
Size=DL_FREE;
fwrite(&Size,sizeof(char),1,file);
Size=temp->GetLink().length();
fwrite(&Size,sizeof(short),1,file);
fwrite(temp->GetLink().c_str(),sizeof(char),temp->GetLink().length(),file);
Size=temp->GetFilename().length();
fwrite(&Size,sizeof(short),1,file);
fwrite(temp->GetFilename().c_str(),sizeof(char),temp->GetFilename().length(),file);
Size = temp->GetFileSize();
fwrite(&Size,sizeof(curl_off_t),1,file);
Size = temp->GetDownloadedSize();
fwrite(&Size,sizeof(curl_off_t),1,file);
}
fclose(file);
}
} | [
"CameleonTH@0c2b0ced-2a4c-0410-b056-e1a948518b24"
] | [
[
[
1,
682
]
]
] |
87f4a84800c1c0cc9712353faf142149dddd2668 | 51c71b06d7fa1aa97df4ffe6782e9a4924480a33 | /Calibration/Calibration.h | 5303c494ea8cf85f96d3bdc976793d968ce9fa7e | [] | no_license | alonf01/open-light | 9eb8d185979cfa16797f9d2201cf192b3e91f270 | 685f974fcd7cc29b6bec00fa17804c5f2b7a83c3 | refs/heads/master | 2020-05-30T15:24:08.579565 | 2010-12-14T00:56:32 | 2010-12-14T00:56:32 | 35,759,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,499 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
// file: Calibration\Calibration.h
//
// summary: Declares the calibration class
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @struct slParams{
///
/// @brief .
///
/// @ingroup Calibration
///
/// @author Brett Jones
/// @date 12/12/2010
////////////////////////////////////////////////////////////////////////////////////////////////////
// Define structure for storing structured lighting parameters.
struct slParams{
// Output options.
char outdir[1024]; // base output directory
char object[1024]; // object name
bool save; // enable/disable saving of image sequence
// Camera options.
int cam_w; // camera columns
int cam_h; // camera rows
bool Logitech_9000; // enable/disable Logitech QuickCam 9000 raw-mode (should be disabled for all other cameras)
// Projector options.
int proj_w; // projector columns
int proj_h; // projector rows
bool proj_invert; // enable/disable inverted projector mode (i.e., camera and projector are flipped with respect to each other)
// Projector-camera gain parameters.
int cam_gain; // scale factor for camera images
int proj_gain; // scale factor for projector images
// Calibration model options.
bool cam_dist_model[2]; // enable/disable [tangential, 6th-order radial] distortion components for camera
bool proj_dist_model[2]; // enable/disable [tangential, 6th-order radial] distortion components for projector
// Define camera calibration chessboard parameters.
// Note: Width/height are number of "interior" corners, excluding outside edges.
int cam_board_w; // interior chessboard corners (along width)
int cam_board_h; // interior chessboard corners (along height)
float cam_board_w_mm; // physical length of chessboard square (width in mm)
float cam_board_h_mm; // physical length of chessboard square (height in mm)
// Define projector calibration chessboard parameters.
// Note: Width/height are number of "interior" corners, excluding outside edges.
int proj_board_w; // interior chessboard corners (along width)
int proj_board_h; // interior chessboard corners (along height)
int proj_board_w_pixels; // physical length of chessboard square (width in pixels)
int proj_board_h_pixels; // physical length of chessboard square (height in pixels)
// General options.
int mode; // structured light reconstruction mode (1 = "ray-plane", 2 = "ray-ray")
bool scan_cols; // enable/disable column scanning
bool scan_rows; // enable/disable row scanning
int delay; // frame delay between projection and image capture (in ms)
int thresh; // minimum contrast threshold for decoding (maximum of 255)
float dist_range[2]; // {minimum, maximum} distance (from camera), otherwise point is rejected
float dist_reject; // rejection distance (for outlier removal) if row and column scanning are both enabled (in mm)
float background_depth_thresh; // threshold distance for background removal (in mm)
bool generate_normals; // generate smoothed surface normals
// Visualization options.
bool display; // enable/disable display of intermediate results (e.g., image sequence, calibration data, etc.)
int window_w; // camera display window width (height is derived)
int window_h; // camera display window width (derived parameter)
int window_offset_x;
int window_offset_y;
};
// forward define of fundamental matrix
class FundamentalMatrix;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @struct slCalib{
///
/// @brief .
///
/// @ingroup Calibration
///
/// @author Brett Jones
/// @date 12/12/2010
////////////////////////////////////////////////////////////////////////////////////////////////////
// Define structure for structured lighting calibration parameters.
struct slCalib{
// Camera calibration.
CvMat* cam_intrinsic; // camera intrinsic parameter matrix
CvMat* cam_distortion; // camera distortion coefficient vector
CvMat* cam_extrinsic; // camera extrinsic parameter matrix
CvMat* cam_rot_vec;
CvMat* cam_rot_mat;
CvMat* cam_trans;
// Projector calibration.
CvMat* proj_intrinsic; // projector intrinsic parameter matrix
CvMat* proj_distortion; // projector distortion coefficient vector
CvMat* proj_extrinsic; // projector extrinsic parameter matrix
CvMat* proj_rot_vec;
CvMat* proj_rot_mat;
CvMat* proj_trans;
FundamentalMatrix *fundMatrx; // fundamental matrix relating the camera to the projector
// Projector-camera geometric parameters.
// Note: All quantities defined in the camera coordinate system.
CvMat* cam_center; // camera center of projection
CvMat* proj_center; // projector center of projection
CvMat* cam_rays; // optical rays for each camera pixel
CvMat* proj_rays; // optical rays for each projector pixel
CvMat* proj_column_planes; // plane equations describing every projector column
CvMat* proj_row_planes; // plane equations describing every projector row
// Flags to indicate calibration status.
bool cam_intrinsic_calib; // flag to indicate state of intrinsic camera calibration
bool proj_intrinsic_calib; // flag to indicate state of intrinsic projector calibration
bool procam_extrinsic_calib; // flag to indicate state of extrinsic projector-camera calibration
// Background model (used to segment foreground objects of interest from static background).
CvMat* background_depth_map; // background depth map
IplImage* background_image; // background image
IplImage* background_mask; // background mask
}; | [
"b.jonessoda@8a600b9a-ddf7-11de-b878-c5ec750a8c44"
] | [
[
[
1,
132
]
]
] |
98ace091a11ffe4e590019b8bfb6252ea720d83f | 7396ad6c1980808aba6716515ecf28390786d879 | /codigos/Plataformas.h | 6a63f386512ec2f901fc97d585c102de49e227e4 | [] | no_license | dairansc/linhasmetro | 9ee1a422a713d0ae9ad46402f67fef6f2aa4c162 | 2edcb9ffd7b6e7f7aaf098ba283bfa6bec17fa77 | refs/heads/master | 2021-01-10T12:44:18.286271 | 2010-10-07T19:36:32 | 2010-10-07T19:36:32 | 50,470,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,725 | h | //#include <iostream>
//#include <string>
//#include <math.h>
//using namespace std;
class Plataformas
{
public:
void inicializa (string, int, int);
//void add_todos_paineis(Conexoes*);
void desenha ();
int id;
string nome;
int posX;
int posY;
int paineis_ocupados;
bool com_defeito;
};
void Plataformas::inicializa(string n, int x, int y){
this->id = PLATAFORMA_QNT;
PLATAFORMA_QNT++;
this->nome = n;
this->posX = x;
this->posY = y;
this->com_defeito = false;
cout << "Nova Plataforma " << this->nome << "["<< this->id << "], na posição (" << this->posX << "," << this->posY << ")" << endl;
}
void Plataformas::desenha(){
GLfloat circle_points = 100.0f;
GLfloat angle;
glColor3f(PLATAFORMA_COR_FUNDO.r, PLATAFORMA_COR_FUNDO.g, PLATAFORMA_COR_FUNDO.b);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(this->posX, this->posY);
for (angle=0; angle<=361; angle++){
glVertex2f(this->posX + sin(angle) * PLATAFORMA_RAIOY, this->posY + cos(angle) * PLATAFORMA_RAIOX);
}
//glEnd();
glColor3f(PLATAFORMA_COR_BORDA.r, PLATAFORMA_COR_BORDA.g, PLATAFORMA_COR_BORDA.b);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < circle_points; i++) {
angle = 2*M_PI*i/circle_points;
glVertex2f(cos(angle)*PLATAFORMA_RAIOX + this->posX, sin(angle)*PLATAFORMA_RAIOX + this->posY);
}
glEnd();
glColor3f(PLATAFORMA_COR_TEXTO.r, PLATAFORMA_COR_TEXTO.g, PLATAFORMA_COR_TEXTO.b);
bitmap_output(this->posX-4, this->posY-5, this->nome, GLUT_BITMAP_HELVETICA_12);
//glFlush();
}
/*
void Plataformas::add_todos_paineis(Conexoes *cons){
for (int i = 0; i < CON_QNT; i++){
if(cons[i].ate
}
}*/
| [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
4eb5ffb9fcd9dcf29fc6246cac31cd1317786797 | a30b091525dc3f07cd7e12c80b8d168a0ee4f808 | /EngineAll/D3DObjects/D3D9PixelShader.h | 4ed4cf31b434de22a4b424b033565998493c0249 | [] | no_license | ghsoftco/basecode14 | f50dc049b8f2f8d284fece4ee72f9d2f3f59a700 | 57de2a24c01cec6dc3312cbfe200f2b15d923419 | refs/heads/master | 2021-01-10T11:18:29.585561 | 2011-01-23T02:25:21 | 2011-01-23T02:25:21 | 47,255,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | h | /*
D3D9PixelShader.h
Written by Matthew Fisher
D3D9PixelShader wraps the IDirect3DPixelShader9 object and an associated ID3DXConstantTable.
*/
#pragma once
#ifdef USE_D3D9
class D3D9PixelShader : public D3D9Object
{
public:
D3D9PixelShader();
~D3D9PixelShader();
void FreeMemory();
void ReleaseMemory();
void Reset(LPDIRECT3DDEVICE9 _Device);
void Init(const String &Filename, LPDIRECT3DDEVICE9 _Device);
void Init(const String &Filename, GraphicsDevice &GD);
void Set();
__forceinline void SetMatrix(const char *Name, const Matrix4 &M)
{
D3DXMATRIX DM(M);
D3DValidate( ConstantTable->SetMatrix(Device, Name, &DM), "SetMatrix");
}
__forceinline void SetMatrix(const String &Str, const Matrix4 &M)
{
SetMatrix(Str.CString(), M);
}
__forceinline void SetFloat(const char *Name, float Value)
{
D3DValidate( ConstantTable->SetFloat(Device, Name, Value), "SetFloat" );
}
__forceinline void SetFloat(const String &Str, float Value)
{
SetFloat(Str.CString(), Value);
}
__forceinline void SetVec3(const char *Name, const Vec3f &V)
{
float V3[3] = {V.x, V.y, V.z};
D3DValidate( ConstantTable->SetFloatArray(Device, Name, V3, 3), "SetFloatArray" );
}
__forceinline void SetVec3(const String &Str, const Vec3f &V)
{
SetVec3(Str.CString(), V);
}
__forceinline void SetVec4(const char *Name, const Vec4f &V)
{
float V4[4] = {V.x, V.y, V.z, V.w};
D3DValidate( ConstantTable->SetFloatArray(Device, Name, V4, 4), "SetFloatArray" );
}
__forceinline void SetVec4(const String &Str, const Vec4f &V)
{
SetVec4(Str.CString(), V);
}
__forceinline void SetBool(const char *Name, bool Value)
{
BOOL NewValue = FALSE;
if(Value)
{
NewValue = TRUE;
}
D3DValidate( ConstantTable->SetBool(Device, Name, NewValue), "SetBool" );
}
__forceinline void SetBool(const String &Str, bool Value)
{
SetBool(Str.CString(), Value);
}
private:
String ShaderFile;
LPDIRECT3DPIXELSHADER9 Shader;
LPDIRECT3DDEVICE9 Device;
LPD3DXCONSTANTTABLE ConstantTable;
};
#endif | [
"zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2"
] | [
[
[
1,
80
]
]
] |
ead4b9e515f7e059f7254b24fb7e1b2974acd0fa | d258dd0ca5e8678c8eb81777e5fe360b8bbf7b7e | /Library/PhysXCPP/NxaFixedJoint.h | 34a81b8e0dcca32cdc1d67d0131f27277138c382 | [] | no_license | ECToo/physxdotnet | 1e7d7e9078796f1dad5c8582d28441a908e11a83 | 2b85d57bc877521cdbf1a9147bd6716af68a64b0 | refs/heads/master | 2021-01-22T07:17:58.918244 | 2008-04-13T11:15:26 | 2008-04-13T11:15:26 | 32,543,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #pragma once
#include "NxaJoint.h"
ref class NxaFixedJointDescription;
class NxFixedJoint;
public ref class NxaFixedJoint : public NxaJoint
{
internal:
NxaFixedJoint(NxFixedJoint* nxFixedJoint);
public:
void LoadFromDescription(NxaFixedJointDescription^ desc);
void SaveToDescription([Out] NxaFixedJointDescription^% desc);
}; | [
"amiles@e8b6d1ee-b643-0410-9178-bfabf5f736f5"
] | [
[
[
1,
16
]
]
] |
7bc021bf7652813184726c0c13960daaa793f358 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP3/BattleCity/Classes/Socket.cpp | b564305091471e96dc0bd15078bf0e0037a8088b | [] | no_license | jfacorro/tp-taller-prog-1-fiuba | 2742d775b917cc6df28188ecc1f671d812017a0a | a1c95914c3be6b1de56d828ea9ff03e982560526 | refs/heads/master | 2016-09-14T04:32:49.047792 | 2008-07-15T20:17:27 | 2008-07-15T20:17:27 | 56,912,077 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,370 | cpp | #include "Socket.h"
#ifndef Socket_cpp
#define Socket_cpp
#define NULL_PORT -1 /* Se utiliza como valor nulo de puerto */
#define IP_SIZE 16 /* Longitud maxima de una direccion IP */
int Socket::Listen(int port)
{
WSADATA wsaData; /* Utilizada para inicializacion del winsock */
WORD wVersionReq = MAKEWORD(2, 2); /* Contiene la version */
SOCKET sock; /* Contiene la informacion del socket */
SOCKET sockAceptado; /* Contiene la informacion del socket que acepto */
struct sockaddr_in sockAddrIn; /* Direccion de socket */
int tamSockAddrIn; /* Se utiliza para aceptar el mensaje y obtener su info */
int codError = 0; /* Codigo de error que se evalua dentro de la funcion */
int resultado = RES_ERROR_UNKNOWN; /* Codigo de error que se devolvera */
/* Inicializa el socket */
codError = WSAStartup(wVersionReq, &wsaData);
if (codError != 0)
{
resultado = RES_ERROR_STARTUP;
}
else
{
/* Crea un socket */
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
resultado = RES_INVALID_SOCKET;
}
else
{
/* Carga los valores de sockAddrIn */
sockAddrIn.sin_family = AF_INET; /* Protocolo ipv4 */
sockAddrIn.sin_port = htons(port); /* Puerto indicado */
sockAddrIn.sin_addr.s_addr = INADDR_ANY; /* Cualquier direccion IP */
codError = bind(sock, (SOCKADDR*) &sockAddrIn, sizeof(sockAddrIn));
if (codError != 0)
{
resultado = RES_ERROR_BIND;
}
else
{
/* Escucha una sola conexion */
codError = listen(sock, 1);
if (codError != 0)
{
resultado = RES_ERROR_LISTEN;
}
else
{
/* Acepta la conexion */
sockAceptado = SOCKET_ERROR;
tamSockAddrIn = sizeof(sockAddrIn);
sockAceptado = accept(sock, (struct sockaddr*)&sockAddrIn, &tamSockAddrIn);
if (sockAceptado == SOCKET_ERROR)
{
resultado = RES_ERROR_ACCEPT;
}
else
{
this->connection.cxPuerto = port;
this->connection.cxIP = (char*) malloc(IP_SIZE);
this->connection.cxIP = GetIPAddressFromSocket(sockAddrIn);
this->connection.cxSocket = sockAceptado;
resultado = RES_OK;
}
}
}
}
}
return resultado;
}
int Socket::Connect(const char * address, int port)
{
WSADATA wsaData; /* Utilizada para inicializacion del winsock */
WORD wVersionReq = MAKEWORD(2, 2); /* Contiene la version */
SOCKET sock; /* Contiene la informacion del socket */
struct hostent* hostInfo; /* Se utiliza para convertir el nombre del host a su direccion IP */
struct sockaddr_in sockAddrIn; /* Direccion de socket */
int codError = 0; /* Codigo de error que se evalua dentro de la funcion */
int resultado = RES_ERROR_UNKNOWN; /* Codigo de error que se devolvera */
/* Inicializa el socket */
codError = WSAStartup(wVersionReq, &wsaData);
if (codError != 0)
{
resultado = RES_ERROR_STARTUP;
}
else
{
/* Crea un socket */
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
resultado = RES_INVALID_SOCKET;
}
else
{
/* Carga los valores de sockAddrIn */
sockAddrIn.sin_family = AF_INET; /* Protocolo ipv4 */
sockAddrIn.sin_port = htons(port); /* Puerto indicado */
hostInfo = gethostbyname(address); /* Direccion IP */
sockAddrIn.sin_addr = *((struct in_addr *)((*hostInfo).h_addr));
codError = connect(sock, (SOCKADDR *)(&sockAddrIn), sizeof(sockAddrIn));
if (codError != 0)
{
resultado = RES_ERROR_CONNECT;
}
else
{
this->connection.cxPuerto = port;
this->connection.cxIP = (char*) malloc(IP_SIZE);
this->connection.cxIP = GetIPAddressFromSocket(sockAddrIn);
this->connection.cxSocket = sock;
resultado = RES_OK;
}
}
}
return resultado;
}
int Socket::Send(Packet packet)
{
int tmp;
int resultado = RES_ERROR_UNKNOWN;
int cantEnviada = 0;
tmp = GetDataSize(packet.GetDataType());
cantEnviada = send(this->connection.cxSocket, (char *)packet.GetData(), packet.GetNumberOfItems() * tmp, 0);
if (cantEnviada != packet.GetNumberOfItems() * tmp) /* No envio la cantidad indicada */
{
resultado = RES_ERROR_SEND;
}
else
{
resultado = RES_OK;
}
return resultado;
}
int Socket::Receive(Packet packet)
{
int tmp;
int resultado = RES_ERROR_UNKNOWN;
int cantRecibida = 0, totalRecibido = 0, tamano;
tmp = this->GetDataSize(packet.GetDataType());
tamano = packet.GetNumberOfItems() * tmp;
while ( totalRecibido < tamano )
{
cantRecibida = recv (this->connection.cxSocket, (char *)((char *)packet.GetData() + totalRecibido), tamano - totalRecibido, 0);
if ( cantRecibida == 0 || cantRecibida == -1 )
return RES_ERROR_RECEIVE;
totalRecibido += cantRecibida;
if (totalRecibido >= tamano)
break;
}
return RES_OK;
}
int Socket::Close()
{
int resultado = RES_ERROR_UNKNOWN;
if (this->IsActive() == RES_OK) /* La conexion esta activa */
{
/* Cierra el socket y quita los valores de la conexion */
if (this->connection.cxIP != NULL)
{
free(this->connection.cxIP);
}
this->connection.cxPuerto = NULL_PORT;
closesocket(this->connection.cxSocket);
this->connection.cxSocket = INVALID_SOCKET;
resultado = RES_OK;
}
else
{ /* La conexion no esta activa */
resultado = RES_INACTIVE;
}
return resultado;
}
int Socket::IsActive()
{
int resultado = RES_ERROR_UNKNOWN;
if (this->connection.cxPuerto != 0)
{ /* La conexion no es nula */
if (this->connection.cxSocket != INVALID_SOCKET)
{ /* La conexion esta activa */
resultado = RES_OK;
}
else
{ /* La conexion no esta activa */
resultado = RES_INACTIVE;
}
}
else
{ /* La conexion es nula */
resultado = RES_INACTIVE;
}
return resultado;
}
char * Socket::GetIPAddressFromSocket(const struct sockaddr_in sockAddress)
{
char* charTemp = (char*) malloc(3);
char* dirIP = new char[IP_SIZE];
/* Inicializa el valor de la direccion */
strcpy(dirIP,"");
/* Obtiene el primer grupo de números de la direccion IP */
itoa((int)sockAddress.sin_addr.S_un.S_un_b.s_b1, charTemp, 10);
strcat(dirIP, charTemp);
strcat(dirIP, ".");
/* Obtiene el segundo grupo de números de la direccion IP */
itoa((int)sockAddress.sin_addr.S_un.S_un_b.s_b2, charTemp,10);
strcat(dirIP, charTemp);
strcat(dirIP, ".");
/* Obtiene el tercer grupo de números de la direccion IP */
itoa((int)sockAddress.sin_addr.S_un.S_un_b.s_b3, charTemp, 10);
strcat(dirIP, charTemp);
strcat(dirIP, ".");
/* Obtiene el cuarto grupo de números de la direccion IP */
itoa((int)sockAddress.sin_addr.S_un.S_un_b.s_b4, charTemp, 10);
strcat(dirIP, charTemp);
strcat(dirIP, "\0");
return dirIP;
}
int Socket::GetDataSize(enum DataType dataType)
{
if ( dataType == INT_TYPE )
return sizeof(int);
else if (dataType == DOUBLE_TYPE)
return sizeof(double);
else if (dataType == CHAR_TYPE)
return sizeof(char);
else if (dataType == FLOAT_TYPE)
return sizeof(float);
else
return 0;
}
#endif
| [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
] | [
[
[
1,
286
]
]
] |
92b5e1c63a7cc22bdd8017687e2d05c753ac2a23 | f9fd733174ef8a8bd07ff9be849431dfc46e541f | /NumberLib/NumbersLib/PingPongNumber.h | 54e1642c0e9b008182ec6a89aba8b195faf8a360 | [] | no_license | Jargyle214/specialnumbers | 8b33369c2bfb75b324cb70539c5daee19f7bce84 | 107b4c3022e5febed38136fa09023f66931df77e | refs/heads/master | 2021-01-10T16:33:58.894648 | 2008-09-21T18:56:04 | 2008-09-21T18:56:04 | 55,395,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,930 | h | #ifndef _PING_PONG_NUMBER_H
#define _PING_PONG_NUMBER_H
#include "RangedNumber.h"
#include "CyclicNumber.h"
namespace luma
{
namespace numbers
{
/**
A PingPongNumber is a number that can grow (or shrink) up to a point,
and then starts shrinking (or growing) again.
@author Herman Tulleken ([email protected])
@author luma/games (http://www.luma.co.za/)
For example:
@code
PingPongNumber n(0, 0, 3, 1);
for(int i = 0; i < 7; i++)
{
n++;
cout << n << " ";
}
@endcode
will print 0 1 2 1 0 1 2.
@param T
Must be
*/
template <class T>
class PingPongNumber: public RangedNumber<T>
{
private:
CyclicNumber<T> mCyclicNumber;
/**
Converts the internal cyclic value to a ping pong value.
*/
inline T pingPongValue(T value) const
{
return value >= mMax ? 2 * (mMax - mIncrement) - value: value;
}
/**
Converts the internal cyclic value to a ping pong value.
*/
inline T pingPongValue() const
{
return pingPongValue((T) mCyclicNumber);
}
public:
/**
Constructs a new PingPongNumber with the given
value, min, max, and direction.
*/
PingPongNumber(T value, T min, T max, T increment);
/**
*/
PingPongNumber(const PingPongNumber& other);
PingPongNumber<T>& operator=(const PingPongNumber<T>& other);
PingPongNumber<T>& operator=(const T& value);
PingPongNumber<T>& operator++();
PingPongNumber<T> operator++(int);
PingPongNumber<T>& operator--();
PingPongNumber<T> operator--(int);
virtual void dec(float elapsedTime = 1);
virtual void inc(float elapsedTime = 1);
virtual T getValidValue(const T& value) const;
/** Used for debugging and testing only.*/
T getCyclicValue() const;
void setIncrement(const T& increment);
};
template <class T>
PingPongNumber<T>::PingPongNumber(T value, T min, T max, T increment):
RangedNumber(reflect(value, min, max - increment), min, max, increment),
mCyclicNumber(value, min, max + max - min - increment - increment, increment)
{
}
template <class T>
PingPongNumber<T>::PingPongNumber(const PingPongNumber &other):
RangedNumber(other),
mCyclicNumber(other.mCyclicNumber)
{
}
template <class T>
PingPongNumber<T>& PingPongNumber<T>::operator=(const PingPongNumber<T>& other)
{
modify(other.mMin, other.mMax, other.mIncrement);
mCyclicNumber = other.mCyclicNumber;
mValue = pingPongValue();
return *this;
}
template <class T>
PingPongNumber<T>& PingPongNumber<T>::operator=(const T& value)
{
mCyclicNumber = value;
mValue = pingPongValue();
return *this;
}
template <class T>
PingPongNumber<T>& PingPongNumber<T>::operator++()
{
inc();
return *this;
}
template <class T>
PingPongNumber<T> PingPongNumber<T>::operator++(int)
{
PingPongNumber<T> tmp = *this;
++*this;
return tmp;
}
template <class T>
PingPongNumber<T>& PingPongNumber<T>::operator--()
{
dec();
return *this;
}
template <class T>
PingPongNumber<T> PingPongNumber<T>::operator--(int)
{
PingPongNumber<T> tmp = *this;
--*this;
return tmp;
}
template <class T>
T PingPongNumber<T>::getValidValue(const T& value) const
{
return pingPongValue(mCyclicNumber.getValidValue(value));
}
template <class T>
void PingPongNumber<T>::inc(float ellapsedTime)
{
mCyclicNumber.inc(ellapsedTime);
mValue = pingPongValue((T) mCyclicNumber);
}
template <class T>
void PingPongNumber<T>::dec(float ellapsedTime)
{
mCyclicNumber.dec(ellapsedTime);
mValue = pingPongValue((T) mCyclicNumber);
}
template <class T>
void PingPongNumber<T>::setIncrement(const T& increment)
{
mCyclicNumber.modify(mMin, 2 * mMax - mMin - 2 * increment, increment);
RangedNumber::setIncrement(increment);
}
template <class T>
T PingPongNumber<T>::getCyclicValue() const
{
return mCyclicNumber.getValue();
}
};};//namespace
#endif //_PING_PONG_NUMBER_H | [
"herman.tulleken@efac63d9-b148-0410-ace2-6f69ea89f809"
] | [
[
[
1,
196
]
]
] |
4dadaa270aca36cea5a386bad9a199f707e2713e | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/ntrigger/src/ntrigger/ngameevent.cc | becacb9e8761ff7251630fb219200199d3cd7295 | [] | 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 | 5,679 | cc | //-----------------------------------------------------------------------------
// ngameevent.cc
// (C) 2005 Conjurer Services, S.A.
//-----------------------------------------------------------------------------
#include "precompiled/pchntrigger.h"
#include "ntrigger/ngameevent.h"
#include "ntrigger/ntriggerserver.h"
//-----------------------------------------------------------------------------
#define GameEvent nGameEvent::Info
// Type info about all the events
static nGameEvent::Info eventTypeInfo[ nGameEvent::EVENTS_NUMBER ] =
{
// The event persistent name must only have letters, numbers and underscore
// The event persistent name mustn't change if backwards compatibility is desired
// This table must be in the same order as nGameEvent::Type
{ "invalid_event", "<invalid>", GameEvent::NO_SCOPE, GameEvent::NO_SENSATION },
{ "done", "Done", GameEvent::FSM_IN, GameEvent::NO_SENSATION },
{ "fail", "Fail", GameEvent::FSM_IN, GameEvent::NO_SENSATION },
{ "player", "Player", GameEvent::FSM_AND_AREA_TRIGGER_IN, GameEvent::VIEW_AND_TOUCH },
{ "squad_member", "Squad member", GameEvent::FSM_AND_AREA_TRIGGER_IN, GameEvent::VIEW_AND_TOUCH },
{ "enter_area", "Enter in area", GameEvent::AREA_TRIGGER_OUT, GameEvent::NO_SENSATION },
{ "exit_area", "Exit from area", GameEvent::AREA_TRIGGER_OUT, GameEvent::NO_SENSATION },
{ "action issued", "Action issued", GameEvent::ACTION_TRIGGER_OUT, GameEvent::NO_SENSATION },
{ "trigger_activation", "Activation", GameEvent::GENERIC_TRIGGER_OUT, GameEvent::NO_SENSATION },
{ "human_sound", "Human sound", GameEvent::ALL_IN, GameEvent::AUDIBLE },
{ "target_lost", "Target lost", GameEvent::FSM_IN, GameEvent::NO_SENSATION },
{ "dead_human", "Dead human", GameEvent::ALL_IN, GameEvent::VIEW_AND_TOUCH_AND_HEAR },
{ "shoot_sound", "Shoot sound", GameEvent::ALL_IN, GameEvent::AUDIBLE },
{ "explosion_sound","Explosion sound", GameEvent::ALL_IN, GameEvent::AUDIBLE },
{ "impact_sound", "Impact sound", GameEvent::ALL_IN, GameEvent::AUDIBLE },
{ "hit", "Hit", GameEvent::ALL_IN, GameEvent::NO_SENSATION },
{ "vehicle", "Vehicle", GameEvent::ALL_IN, GameEvent::VIEW_AND_TOUCH },
{ "vehicle_sound", "Vehicle sound", GameEvent::ALL_IN, GameEvent::AUDIBLE }
};
#undef GameEvent
//------------------------------------------------------------------------------
/**
Start emitting the event
*/
void
nGameEvent::StartEvent( Time startTime )
{
this->startTime = startTime;
this->expirationTime = startTime + this->duration;
}
//-----------------------------------------------------------------------------
/**
Return the mutable id of an event by its unmutable id
*/
nGameEvent::Type
nGameEvent::GetEventTransientId( const char* idName )
{
nString strName( idName );
for ( int i(0); i < EVENTS_NUMBER; ++i )
{
if ( strName == eventTypeInfo[i].id )
{
return Type(i);
}
}
NLOG( trigger, (nTriggerServer::ErrorsLog | 0,
"Found a reference to the unknown event '%s'", idName) );
return INVALID_TYPE;
}
//-----------------------------------------------------------------------------
/**
Return the unmutable id of an event
*/
const char*
nGameEvent::GetEventPersistentId( Type eventType )
{
n_assert( eventType >= 0 && eventType < nGameEvent::EVENTS_NUMBER );
return eventTypeInfo[ eventType ].id;
}
//-----------------------------------------------------------------------------
/**
Return the label of an event
*/
const char*
nGameEvent::GetEventLabel( Type eventType )
{
n_assert( eventType >= 0 && eventType < nGameEvent::EVENTS_NUMBER );
return eventTypeInfo[ eventType ].label;
}
//-----------------------------------------------------------------------------
/**
Return the scope of an event
*/
nGameEvent::Info::Scope
nGameEvent::GetEventScope( Type eventType )
{
n_assert( eventType >= 0 && eventType < nGameEvent::EVENTS_NUMBER );
return eventTypeInfo[ eventType ].scope;
}
//-----------------------------------------------------------------------------
/**
Return the sensation type of an event
*/
nGameEvent::Info::Sensation
nGameEvent::GetEventSensation( Type eventType )
{
n_assert( eventType >= 0 && eventType < nGameEvent::EVENTS_NUMBER );
return eventTypeInfo[ eventType ].sensation;
}
#ifndef NGAME
//-----------------------------------------------------------------------------
/**
Get a string description of the event
*/
void
nGameEvent::ToString( nString& str ) const
{
str = "id=" + nString( int(this->eventId) ) \
+ ", type=" + nString( nGameEvent::GetEventPersistentId(this->eventType) ) \
+ ", source=" + nString( int(this->sourceId) ) \
+ ", emitter=" + nString( int(this->emitterId) ) \
+ ", begin=" + nString( int(this->startTime) ) \
+ ", end=" + nString( int(this->expirationTime) ) \
+ ", priority=" + nString( this->priority ) \
+ ", properties=" + nString(properties);
}
#endif
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
132
]
]
] |
eaf502cc8b36d3ca15408d84b46d68b5a9518d23 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataPreProcess.cpp | 79a77dba063b2f722df4e8c404b7494fd2ebc43e | [] | no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | cpp | #include <QtGui>
#include "proRataPreProcess.h"
#include <iostream>
using namespace std;
ProRataPreProcessWizard::ProRataPreProcessWizard(QWidget *qwParent)
: ProRataPreProcessAbstract(qwParent)
{
setNumPages(4);
}
QWidget *ProRataPreProcessWizard::createPage(int iIndex)
{
switch (iIndex) {
case 0:
prwdbFirstPage = new ProRataWorkingDirBrowser(this);
return prwdbFirstPage;
case 1:
prdtasSecondPage = new ProRataDTASelect(this);
return prdtasSecondPage;
case 2:
prcbThirdPage = new ProRataConfigBrowser(this);
return prcbThirdPage;
case 3:
prr2mFourthPage = new ProRataRaw2MzXMLBrowser(this);
return prr2mFourthPage;
}
return 0;
}
void ProRataPreProcessWizard::accept()
{
cout << "Working Directory = " << prwdbFirstPage->getWorkingDirectory().toAscii().data() << endl;
cout << "DTA results file = " << prdtasSecondPage->getResultFile().toAscii().data() << endl;
cout << "Configuration file = " << prcbThirdPage->getConfigurationFile().toAscii().data() << endl;
cout << "Raw data Directory = " << prr2mFourthPage->getRawDataDirectory().toAscii().data() << endl;
cout << "Conversion Program name = " << prr2mFourthPage->getConversionProgram().toAscii().data() << endl;
// Do further processing.
//
ProRataPreProcessAbstract::accept();
}
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
] | [
[
[
1,
44
]
]
] |
0583fce75872cf946fbe8515affc8f7cd5382d22 | cd0987589d3815de1dea8529a7705caac479e7e9 | /includes/webkitsupport/platform/BlackBerryPlatformTimer.h | 69e60c5c7ef5f2e90c4db22949447d981099311c | [] | no_license | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,439 | h | /*
* Copyright (C) Research In Motion Limited 2009-2011. All rights reserved.
*/
#ifndef BlackBerryPlatformTimer_h
#define BlackBerryPlatformTimer_h
namespace blackberry {
namespace bridge {
class Timer;
}
}
namespace BlackBerry {
namespace Platform {
class TimerClient {
public:
virtual bool willFireTimer() = 0;
};
typedef void (*TimerFunction)();
typedef void (*ContextTimerFunction)(void*);
void timerStart(double interval, TimerFunction function);
void timerStop();
void setTimerClient(TimerClient*);
class TimerBase
{
public:
TimerBase();
virtual ~TimerBase();
void start(double interval, ContextTimerFunction function, void* context);
void start(double interval, TimerFunction function);
void stop();
void setPeriodic(bool periodic);
void setClient(TimerClient* client);
TimerClient* client() const;
virtual void fired() = 0;
bool started() const;
protected:
static void timerFired(blackberry::bridge::Timer*, void* context);
TimerClient* m_timerClient;
TimerFunction m_timerFunction;
ContextTimerFunction m_contextTimerFunction;
void* m_context;
bool m_timerStarted;
bool m_periodic;
double m_interval;
blackberry::bridge::Timer* m_timer;
};
// A templated timer class that will invoke a method when the timer fires
template<typename T> class Timer : public TimerBase {
public:
Timer(T* object, void(T::*method)()) : m_object(object), m_method(method) { }
void start(double interval);
virtual void fired();
private:
T* m_object;
void(T::*m_method)();
};
template<typename T>
void Timer<T>::start(double interval)
{
TimerBase::start(interval, 0);
}
template<typename T>
void Timer<T>::fired()
{
if (!started())
return;
if (m_periodic)
start(m_interval);
else
m_timerStarted = false;
if (m_timerClient && !m_timerClient->willFireTimer())
TimerBase::start(0.0, m_timerFunction);
else
(m_object->*m_method)();
}
} // namespace Platform
} // namespace BlackBerry
#endif // BlackBerryPlatformTimer_h
| [
"[email protected]"
] | [
[
[
1,
98
]
]
] |
5f99fcf71b3c288cab00dd5dda05d71976a9ad3f | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/disassembler/DIVU.h | 7bea676fbe42cff1b2d071ced609516539d80454 | [] | no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 335 | h | /* DIVU */
void AllegrexInstructionTemplate< 0x0000001b, 0xfc00ffff >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment)
{
using namespace Allegrex;
::strcpy(opcode_name, "divu");
::sprintf(operands, "%s, %s", gpr_name[rs(opcode)], gpr_name[rt(opcode)]);
::strcpy(comment, "");
}
| [
"[email protected]"
] | [
[
[
1,
9
]
]
] |
17734ab51a7793a8fcac10faf8dbb46db548770c | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /GServerEngine/Public/TimerList.cpp | f9b75d4b8a32d304da7e86ec872a97d7b77be2ed | [] | 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 | 3,036 | cpp | #include "StdAfx.h"
#include "TimerList.h"
template<class type_name>
CTimerList<type_name>::CTimerList(void)
{
// m_pTimerArray = (tagTimerVar*)VirtualAlloc( NULL , sizeof(tagTimerVar) * MAX_TIMER_NUM , MEM_COMMIT ,PAGE_READWRITE );
//
// for ( int count = 0 ; count < MAX_TIMER_NUM ; count ++ )
// {
// m_pTimerArray[i].TimerId = count + 1;
// m_pTimerArray[i].Type = NULL;
// m_pTimerArray[i].StartTime=0;
//
// m_UnUsingList.AddNode( &m_pTimerArray[i] );
// }
m_Count = 0;
}
template<class type_name>
CTimerList<type_name>::~CTimerList(void)
{
// m_UnUsingList.ReleaseList();
// m_UsingList.ReleaseList();
//
// VirtualFree(m_pTimerArray,0,MEM_RELEASE);
m_Timerlist.clear();
}
template<class type_name>
long CTimerList<type_name>::AddTimer(const type_name * arg,
unsigned long stime,
unsigned long interval)
{
sync::scope_guard sg ( m_section );
tagTimerVar * timeNode = new tagTimerVar ;
if ( timeNode != NULL )
{
//m_UnUsingList.RemoveNode( timeNode );
timeNode->pObj = arg;
timeNode->StartTime = stime;
timeNode->Interval = interval;
m_Timerlist.push( timeNode );
m_Count ++ ;
return m_Count;
}
return 0;
}
/*
* 执行定时器的元素
* 注:这样效率低下,查找需要O(n)
*/
template< class type_name >
long CTimerList<type_name>::Expired(long CurrentTime)
{
// sync::scope_guard sg ( m_section );
//
// tagTimerVar * pRoot = m_UsingList.GetHead();
//
// while ( pRoot )
// {
// if ( (CurrentTime - pRoot->StartTime) >= pRoot->Interval )
// {
// pRoot->pObj->Execute( pRoot );
//
// if ( pRoot->Interval != 0 )
// {
// AddTimer( pRoot->pObj, timeGetTime()+pRoot->Interval , Interval );
// }
// RemoveTimer( pRoot );
// return pRoot->TimerId;
// }
// pRoot = pRoot->next;
// }
while ( !m_Timerlist.empty() )
{
tagTimerVar * pt = test.top();
if ( pt->StartTime > CurrentTime )
break;
test.pop();
// 执行定时器
pt->pObj->Execute( pt );
// 循环周期
if ( pt->Interval> 0 )
{
pt->StartTime = time(NULL) + pt->Interval;
m_Timerlist.push( pt );
}
else
{
delete pt;
}
}
return 0;
}
template < class type_name >
long CTimerList<type_name>::OnTimeOut(const type_name * arg)
{
return 0;
}
template < class type_name >
bool CTimerList<type_name>::RelaseGameEndTimer(long id)
{
sync::scope_guard sg ( m_section );
// tagTimerVar * pRoot = m_UsingList.GetHead();
//
// while ( pRoot )
// {
// if ( id == pRoot->TimerId )
// {
// m_UsingList.RemoveNode ( pRoot );
// m_UnUsingList.AddNode( pRoot );
// return true ;
// }
// pRoot = pRoot->next;
// }
return false;
}
template < class type_name >
bool CTimerList<type_name>::RemoveTimer(tagTimerVar *node)
{
sync::scope_guard sg ( m_section );
// m_UsingList.RemoveNode ( node );
// m_UnUsingList.AddNode( node );
return true;
}
| [
"[email protected]"
] | [
[
[
1,
142
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.